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.54k stars 6.46k forks source link

multi_heap: support for realloc #77174

Open mkomet opened 1 month ago

mkomet commented 1 month ago

Introduction

TLDR: Support in the multi_heap component for realloc().

Problem description

Currently there is no way to perform an implicit vector.resize() operation over a multi_heap allocator for example. The user/lib will have to explicitly free, and alloc (even if the chunk itself was large enough for the desired resize()/reserve().

Proposed change

Add support both for sys_multi_heap_realloc and sys_multi_heap_aligned_realloc (similarly to sys_heap):

void *sys_multi_heap_aligned_realloc(struct sys_multi_heap *mheap, void *cfg, void *ptr,
                         size_t align, size_t bytes);

#define sys_multi_heap_realloc(mheap, cfg, ptr, bytes) \
    sys_multi_heap_aligned_realloc(mheap, cfg, ptr, 0, bytes)

Note: Over this can add support as well for shared_multi_heap as a wrapper for the proposed new multi_heap functionality. Note: See man 3 realloc for the special cases.

Detailed RFC

sys_multi_heap_realloc will perform the following (simple flow outlined):

  1. Find relevant heap of allocated ptr
  2. Retrieve usable size of ptr
  3. If requested size is larger than usable size, allocate on multiheap (new alloc can reside on different pool)
  4. memcpy(new_ptr, ptr, size);

Other flows:

  1. If requested size is smaller than usable size, return ptr

  2. If failed to allocate new_ptr return NULL

Note: Important to deal with the "special" realloc cases (!ptr, !size, ...)

Proposed change (Detailed)

Dependencies

Concerns and Unresolved Questions

Do we need to free the original ptr upon failure to allocate new buffer ? This is an implementation detail in realloc, and not a MUST.

Alternatives

N/A

github-actions[bot] commented 1 month ago

Hi @mkomet! We appreciate you submitting your first issue for our open-source project. ๐ŸŒŸ

Even though I'm a bot, I can assure you that the whole community is genuinely grateful for your time and effort. ๐Ÿค–๐Ÿ’™