-
Notifications
You must be signed in to change notification settings - Fork 6.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix newlib malloc thread safety issue #35227
Conversation
This commit adds a lock implementation for the newlib heap memory management functions (`malloc` and `free`). The `__malloc_lock` and `__malloc_unlock` functions are called by the newlib `malloc` and `free` functions to synchronise access to the heap region. Without this lock, making use of the `malloc` and `free` functions from multiple threads will result in the corruption of the heap region. Signed-off-by: Stephanos Ioannidis <[email protected]>
This commit removes the lock inside the newlib internal `_sbrk` function, which is called by `malloc` when additional heap memory is needed. This lock is no longer required because any calls to the `malloc` function are synchronised by the `__malloc_lock` and `__malloc_unlock` functions. Signed-off-by: Stephanos Ioannidis <[email protected]>
ae04595
to
973f918
Compare
Please ignore checkpatch warning. It's wrong. |
This commit adds a new test to verify the thread safety of the C standard functions provided by newlib. Only the memory management functions (malloc and free) are tested at this time; this test will be further extended in the future, to verify the thread safety and re-entrancy of all supported newlib functions. Signed-off-by: Stephanos Ioannidis <[email protected]>
973f918
to
36f64da
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks very reasonable
@@ -291,6 +292,18 @@ void *_sbrk(intptr_t count) | |||
} | |||
__weak FUNC_ALIAS(_sbrk, sbrk, void *); | |||
|
|||
static LIBC_DATA SYS_MUTEX_DEFINE(heap_mutex); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When CONFIG_USERSPACE=n, making this a spinlock would be much smaller/faster. But they I guess someday we'll get around to implementing a futex backend for sys_mutex which would have the same property.
This series includes a set of patches to fix the thread safety-related issue when calling the
malloc
andfree
functions from multiple threads, as well as a new test to validate the thread safety issue.Before
After
A more comprehensive series addressing the thread safety and re-entrancy issues for all newlib functions will be submitted in the future -- this series is meant to address only the most critical aspect (i.e. memory management) of the underlying problems in a timely manner.
Related to #21519 and #21518