diff --git a/ulib/dlmalloc/dlmalloc_port.inc b/ulib/dlmalloc/dlmalloc_port.inc index 9795d71..8ada055 100644 --- a/ulib/dlmalloc/dlmalloc_port.inc +++ b/ulib/dlmalloc/dlmalloc_port.inc @@ -54,14 +54,51 @@ static MLOCK_T malloc_global_mutex = { 0 }; #define PAGE_SIZE 0x1000 -static uint8_t *heap_start = (uint8_t *)NULL; +static uint8_t *heap_start = NULL; static uint8_t *heap_end = NULL; +static uint8_t *heap_commit = NULL; static size_t _roundpage(size_t sz) { return (sz + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); } void *sbrk(ptrdiff_t inc) { + if (!heap_end) { + size_t allocsz = PAGE_SIZE; + uint8_t *maddr = NULL; + int32_t ret = mman_map(NULL, allocsz, MMAN_MAP_PF_RW, 0, &maddr); + if (ret != E_OK || maddr == NULL) { + return (void *)-1; + } + heap_start = maddr; + heap_end = maddr; + heap_commit = maddr + allocsz; + } + + if (inc == 0) { + return heap_end; + } + + uint8_t *oldh = heap_end; + uint8_t *newh = heap_end + inc; + + if (inc > 0) { + if (newh > heap_commit) { + size_t extra = _roundpage((size_t)(newh - heap_commit)); + uint8_t *maddr = NULL; + int32_t ret = mman_map(NULL, extra, MMAN_MAP_PF_RW, 0, &maddr); + if (ret != E_OK || maddr == NULL) { + return (void *)-1; + } + heap_commit += extra; + } + heap_end = newh; + } else { + heap_end = newh; + } + return oldh; + + #if 0 if (!heap_end) { heap_end = heap_start; } @@ -89,4 +126,5 @@ void *sbrk(ptrdiff_t inc) { heap_end = newh; } return oldh; + #endif }