zephyrproject-rtos / zephyr

Primary Git Repository for the Zephyr Project. Zephyr is a new generation, scalable, optimized, secure RTOS for multiple hardware architectures.
https://docs.zephyrproject.org
Apache License 2.0
10.88k stars 6.63k forks source link

Using newlib and common malloc is not thread safe #78124

Open talih0 opened 2 months ago

talih0 commented 2 months ago

Describe the bug

Using COMMON_LIBC_MALLOC and NEWLIB_LIBC is not thread safe. Both implementations share the same heap, but each has their own locking mechanism.

This will cause memory corruptions when malloc() and newlib (i.e. printf()) are used in different threads.

To Reproduce Steps to reproduce the behavior:

Checkout out my branch where I've modified samples/basic/threads to use printf() and malloc(): https://github.com/talih0/zephyr/tree/malloc_newlib_crash

I could reproduce the crash on two boards: xmc47_relax_kit and sam_v71_xult. I did not get the crash when using qemu_86.

  1. west build -b sam_v71_xult samples/basic/threads
  2. west flash
  3. picocom -e b -b 115200 /dev/ttyACM0
%%%ѥUzMեrrjj:2*2RRRj
                    Count 1
Count 1
ASSERTION FAIL [chunk_used(h, c)] @ WEST_TOPDIR/zephyr/lib/heap/heap.c:175
        unexpected heap state (double-free?) for memory at 0x71c92764

Expected behavior No crash.

Environment (please complete the following information):

github-actions[bot] commented 6 days ago

This issue has been marked as stale because it has been open (more than) 60 days with no activity. Remove the stale label or add a comment saying that you would like to have the label removed otherwise this issue will automatically be closed in 14 days. Note, that you can always re-open a closed issue at any time.