// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include static MemPool pool; static size_t liveBlocks; int vcc_heap_init(void *buffer, size_t capacity) { // 16 bytes leaves room for even the smallest block, including WydeAlloc // bookkeeping and the two-byte capacity we keep for realloc. if (liveBlocks || !buffer || capacity < 16 || capacity > UINT_MAX - (unsigned) buffer) return 0; // Normalize the backend byte result to the public int success value. return MemPool_init(&pool, buffer, (char *) buffer + capacity) ? 1 : 0; } void *malloc(size_t size) { if (!pool.start || !size || size > UINT_MAX - sizeof(size_t)) return NULL; // CMOC's 6809 ABI allows a size_t at any byte address. Keep its value in // our own allocation so we never depend on WydeAlloc's private block layout. size_t *block = (size_t *) MemPool_alloc(&pool, size + sizeof(size_t)); if (!block) return NULL; *block = size; ++liveBlocks; return block + 1; } void free(void *ptr) { if (ptr) { MemPool_free(&pool, (size_t *) ptr - 1); --liveBlocks; } } void *calloc(size_t count, size_t size) { if (!count || !size || count > UINT_MAX / size) return NULL; size_t total = count * size; void *ptr = malloc(total); if (ptr) memset(ptr, 0, total); return ptr; } void *realloc(void *ptr, size_t size) { if (!ptr) return malloc(size); if (size == 0) { free(ptr); return NULL; } size_t capacity = *((size_t *) ptr - 1); if (size <= capacity) return ptr; void *larger = malloc(size); if (larger) { memcpy(larger, ptr, capacity); free(ptr); } return larger; }