[Libwebsockets] Releasing Memory in wsi user_space
andy at warmcat.com
Wed Oct 5 02:39:26 CEST 2016
On Tue, 2016-10-04 at 16:16 +0000, Joerg Pommnitz wrote:
> Hello all,
> I try to keep a pointer to dynamically allocated memory in the per-
> session user memory. I had hoped to free this memory in
> LWS_CALLBACK_WSI_DESTROY. This seems to be OK for WS but not for
The purpose of those callbacks is to make it easy to track "live wsi"
for cases where the user code wants to maintain his own list of extant
> /* outermost destroy notification for wsi (user_space still intact)
> wsi->vhost->protocols.callback(wsi, LWS_CALLBACK_WSI_DESTROY,
> wsi->user_space, NULL, 0);
You can try LWS_CALLBACK_CLOSED_HTTP, user_space should still be
around. But that implies you need to move the creation to later as
well, maybe LWS_CALLBACK_HTTP. It depends on what you intend to do
with the allocations.
Every ws connection went through being an HTTP connection first. So
you can probably leverage that to allocate there.
> vhost->protocols.callback(wsi, LWS_CALLBACK_WSI_DESTROY,
> NULL, NULL, 0);
This has changed in master, there is one unified destroy call in the
wsi close function. The user_space has already gone by then. (As I
say DESTROY's purpose is notification the wsi has gone, not managing
With the plugins and protocol handlers and HTTP/1.1 transaction
pipelining a more sophisticated way of handling the lifetime
allocations was needed.
Basically not only ws sessions can bind to a plugin / protocol but
different pieces of a vhost's URL space can be bound to different
plugins using the lws_mount stuff, and be auto-served. Those plugins
want to allocate completely different private data.
With HTTP/1.1, the same wsi / connection may perform multiple GET or
POST or whatever on various places in the vhost URL space one after the
other. These may map on to different plugin / protocol handlers and
each may want to allocate.
When we bind the wsi to one handler we need a callback to allocate any
special pieces and when we unbind we need another callback to
deallocate them. Those events are no longer related to wsi creation or
destruction but to bind and unbind the wsi to a plugin / protocol,
which may happen many times during one connection lifetime.
For that reason there are two new "lifecycle" related callbacks
these should be used to manage allocations and deallocations, since
they are called when reusing a connection as well as on creation and
destruction. These BIND is always coming after CREATE and DROP before
DESTROY, even in the simple case, and the user_space is always there.
You can see an example in the messageboard demo for generic sessions
> Any reason for the different behaviour? And what is the suggested way
> to handle dynamically allocated per session memory?
> -- Regards Joerg
> Libwebsockets mailing list
> Libwebsockets at ml.libwebsockets.org
More information about the Libwebsockets