Skip to content

Comments

ClientContext.h: Prevent double free for freeRTOS#3370

Open
functionpointer wants to merge 1 commit intoearlephilhower:masterfrom
functionpointer:clientcontext_double_free
Open

ClientContext.h: Prevent double free for freeRTOS#3370
functionpointer wants to merge 1 commit intoearlephilhower:masterfrom
functionpointer:clientcontext_double_free

Conversation

@functionpointer
Copy link

As discussed in #3368 and #3265 there are several race conditions in ClientContext.h.

LWIP can close tcp connections whenever it feels like it, and it will free the associated struct pcb (Protocol Control Block) without warning. It does inform sketch code with a callback.

However, ClientContext.h does not handle this correctly. abort() and close() are especially problematic, as they remove the callback and then call tcp_abort() or tcp_close(). This frees the connection. In case LWIP frees the connection between removal of the callback and tcp_abort() we have a double free that locks up the system when the next tcp connection is allocated.

Additionally, many other functions in ClientContext.h contain race conditions where _pcb is checked and then used. Since no mutex is held, LWIP can free _pcb between check and usage. The check is effectively useless.

This PR fixes the issue by holding the mutex between check and usage. Naively, a simple LWIPMutex m; as in #3368 would suffice. However, that won't work for freeRTOS. This PR works for both baremetal and freeRTOS. In addition to the LWIPMutex m; it also wraps all critical sections with lwip_callback(), which ends up executing it in LWIP task.

The existing lwip_callback() is quite cumbersome to use for this, as wrapped code needs local variables of ClientContext.h and generates return values. I have attempted to work around this by using lambda functions, which can capture local variables. To make this possible, a new lwip_callback() is required that accepts function objects.

Previous LWIPMutex solution only worked for core
functionpointer added a commit to functionpointer/arduino-pico that referenced this pull request Feb 13, 2026
This work in progress commit adds NULL checks in lwip_wrap.cpp to prevent double frees in ClientContext.h

See earlephilhower#3265 and earlephilhower#3368

It is alternative to earlephilhower#3370
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant