ulib dlmalloc, more eco friendly sbrk()

This commit is contained in:
2025-09-15 00:33:46 +02:00
parent 40ccb7d476
commit ce63020b34

View File

@ -54,14 +54,51 @@ static MLOCK_T malloc_global_mutex = { 0 };
#define PAGE_SIZE 0x1000 #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_end = NULL;
static uint8_t *heap_commit = NULL;
static size_t _roundpage(size_t sz) { static size_t _roundpage(size_t sz) {
return (sz + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); return (sz + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
} }
void *sbrk(ptrdiff_t inc) { 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) { if (!heap_end) {
heap_end = heap_start; heap_end = heap_start;
} }
@ -89,4 +126,5 @@ void *sbrk(ptrdiff_t inc) {
heap_end = newh; heap_end = newh;
} }
return oldh; return oldh;
#endif
} }