Menu

Thread safety in memory management in GCC's newLib?

2017-12-19
2017-12-19
  • Craig Broadbooks

    I've been using the Quantum Framework (QPCPP with the Quantum Kernel) for some time with IAR, but recently we migrated our project to GCC. This has mostly gone smoothly, but we started getting a sporatic hard fault from time to time. It was pretty rare and seemed random. Finally I caught it in the debugger and found that it was coming from one of two places, either in _Balloc or _Bfree which were being called from one of the printf variants (vsprintf, etc.). Those need a little dynamic memory for formatting various values. I have a small heap, but it is big enough to accomodate. It occurred to me that GCC's newLib memory functions may not be thread safe. After searching a bit I came accross this document: https://www.cs.ccu.edu.tw/~pahsiung/courses/esd/resources/newlib.pdf with the following paragraph on page 6: "To permit multiple processing contexts in newlib’s malloc() implementation, you must also provide the functions __malloc_lock() and __malloc_unlock() to protect your memory pool from corruption during simultaneous allocations. If you are using an RTOS’s reentrant memory pool implementation for dynamic memory allocation, however, this heap protection is unnecessary--- the RTOS protects the heap itself."

    For my purposes, it seems that using a singleton that contains a QP::QMutex where I lock on a call to __malloc_lock() and unlock on the subsequent call to __malloc_unlock() is the right thing to do.

    Is this the recommended approach? Any other approaches or considerations?

    Thanks,
    Craig

     
  • Quantum Leaps

    Quantum Leaps - 2017-12-19

    The newer versions of the QK kernel have replaced the non-blocking mutex with QK scheduler locking (QK::schedLock() / QK::schedUnlock()).

    But I would also recommend that you take a look at QP/Spy as a replacement for printf()/sprintf()/vsprintf(). Specifically, you can easily geneate custom application-specific trace records.

    QP/Spy is much less intrusive than printf(), because it avoids performing formatting in the time-critical path through the code. QP/Spy is also thread-safe and can be used even in ISRs. It takes only a fraction of the code required by the printf() formatter. (Full-blown printf()/sprintf() formatter is actually bigger than the whole QP/QK combined!). All examples provided in the QP/C++ demonstrate the QP/Spy interface in the "Spy" build configuration. Finally, once you have QP/Spy going, you can use it for unit-testing your application on target and on the host (see QUTest).

    --MMS

     

Log in to post a comment.