Default system heap listener

How can a heap listener be used on the system heap?  That is, the system heap that is used for k_malloc() and k_free(), with size set in kconfig as follows.  The kconfig to enable the listener is also added

CONFIG_HEAP_MEM_POOL_SIZE=/* size in bytes */
CONFIG_SYS_HEAP_LISTENER=y

In particular, I'm trying to find out what _heap_id should be used with the macros

HEAP_LISTENER_ALLOC_DEFINE(name, _heap_id, _alloc_cb)
HEAP_LISTENER_FREE_DEFINE(name, _heap_id, _free_cb)


I tried using "HEAP_ID_LIBC" for the _heap_id in the above listener define macros.  It builds, but no calls to the _alloc_cb or _free_cb functions occur, despite many uses of k_malloc() and k_free().  I would assume HEAP_ID_LIBC is for C library calls with malloc() and free(), and not the Zephyr memory pool heap functions k_malloc() and k_free().

What should be used for the heap ID with the heap memory pool?  Is there an example of using the heap listener API?

Thank you,

Walt

  • Hi, 

    Regrettably, poor support is often a hallmark of open source software.

    yes, but fortunately, in most cases, you may find out by reading the source code.

    I have figured out how to get the default system heap. It is a global variable.

    so you can call it simply as follow:

    extern struct k_heap _system_heap;

    void main_heap_listener_alloc_cbh(uintptr_t heap_id, void *mem, size_t bytes);

    void main_heap_listener_free_cbh(uintptr_t heap_id, void *mem, size_t bytes);
    HEAP_LISTENER_ALLOC_DEFINE(AllocListener, HEAP_ID_FROM_POINTER(&_system_heap.heap), main_heap_listener_alloc_cbh);
    HEAP_LISTENER_FREE_DEFINE(FreeListener, HEAP_ID_FROM_POINTER(&_system_heap.heap), main_heap_listener_free_cbh);
  • Jason,

    Awesome!  I was able to get it working using the default heap global variable.  Thank you for posting your solution; that's a big help. 

    Well done,

    Walt

    (PS- for posterity, this was working with nRF Connect v2.2.0)

  • This was so hard to find, thanks for posting this. I have been looking for a way to effectivity monitor the system heap use for a while and had finally found sys_heap_runtime_stats_get() and sys_heap_print_info(), but no way to get a ref to the system heap and your replay has done that. Thanks so much for posting this! 

    I will add for other out there that may have been looking for the same you can use CONFIG_SYS_HEAP_RUNTIME_STATS to enable the heap stats APIs mentioned above. These can then be called in the following manner:

    extern struct k_heap _system_heap;
    static struct sys_memory_stats stats;
    
    sys_heap_print_info(&_system_heap,true);
    //or
    sys_heap_runtime_stats_get(&_system_heap, &stats);
    

    I hope this helps anyone that comes across the same problem. 

Related