Skip to content

Fix use-after-free in BaseObjects destructor - #335

Open
amir-al-mohamad wants to merge 1 commit into
mobizt:mainfrom
amir-al-mohamad:fix/baseobjects-destructor-use-after-free
Open

amir-al-mohamad wants to merge 1 commit into
mobizt:mainfrom
amir-al-mohamad:fix/baseobjects-destructor-use-after-free

Conversation

@amir-al-mohamad

Copy link
Copy Markdown

I was chasing random heap corruption panics on an ESP32-S3 (arduino-esp32 3.x,
IDF 5.5.4) that showed up a few seconds after every Messaging::send(), usually
as tlsf asserts in the wifi or lwip tasks. With comprehensive heap poisoning
the checker reported a single zeroed byte at the start of 3-6 freed blocks
right after my Messages::Message / Notification objects went out of scope, and
a free() journal traced every one of those blocks to BaseO8::~BaseO8 and
BaseO4::~BaseO4.

The cause is in BaseObjects: buffers points at the String buf[N] array of
the derived class, and ~BaseObjects() calls clear() on it. By then the derived
members are already destroyed. GCC at -O2 drops the stores made by the inlined
~String() (dead stores into a dying object), so the Strings still hold the
freed pointer and length, and String::remove(0, len) writes a NUL into freed
memory.

Removing the clear() call from the destructor fixes it, the String members
clean up after themselves anyway. Before the change the heap got corrupted in
5 out of 5 test runs, after it in 0 out of 6.

~BaseObjects() called clear() on the derived class's String buffers after
they had already been destroyed; with GCC -O2 they still hold the freed
pointer, so String::remove() wrote into freed memory.
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