Created
April 24, 2020 20:05
-
-
Save aap/d78d735b5bb237ebedd1fecdc6bb3863 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MemoryBlock | |
{ | |
size_t sz; | |
uint32 hint; | |
void *origPtr; | |
LLLink inAllocList; | |
}; | |
LinkList allocations; | |
size_t totalMemoryAllocated; | |
// We align managed memory blocks on a 16 byte boundary | |
#define ALIGN16(x) ((x) + 0xF & ~0xF) | |
void* | |
malloc_managed(size_t sz, uint32 hint) | |
{ | |
void *origPtr; | |
uint8 *data; | |
MemoryBlock *mem; | |
if(sz == 0) return nil; | |
origPtr = malloc(sz + sizeof(MemoryBlock) + 15); | |
if(origPtr == nil) | |
return nil; | |
totalMemoryAllocated += sz; | |
data = (uint8*)origPtr; | |
data += sizeof(MemoryBlock); | |
data = (uint8*)ALIGN16((uintptr)data); | |
mem = (MemoryBlock*)(data-sizeof(MemoryBlock)); | |
mem->sz = sz; | |
mem->hint = hint; | |
mem->origPtr = origPtr; | |
allocations.add(&mem->inAllocList); | |
return data; | |
} | |
void* | |
realloc_managed(void *p, size_t sz, uint32 hint) | |
{ | |
void *origPtr; | |
MemoryBlock *mem; | |
uint32 offset; | |
if(p == nil) | |
return malloc_managed(sz, hint); | |
mem = (MemoryBlock*)((uint8*)p-sizeof(MemoryBlock)); | |
offset = (uint8*)p - (uint8*)mem->origPtr; | |
mem->inAllocList.remove(); | |
origPtr = realloc(mem->origPtr, sz + sizeof(MemoryBlock) + 15); | |
if(origPtr == nil){ | |
allocations.add(&mem->inAllocList); | |
return nil; | |
} | |
p = (uint8*)origPtr + offset; | |
mem = (MemoryBlock*)((uint8*)p-sizeof(MemoryBlock)); | |
totalMemoryAllocated -= mem->sz; | |
mem->sz = sz; | |
mem->hint = hint; | |
mem->origPtr = origPtr; | |
allocations.add(&mem->inAllocList); | |
totalMemoryAllocated += mem->sz; | |
return p; | |
} | |
void | |
free_managed(void *p) | |
{ | |
MemoryBlock *mem; | |
if(p == nil) | |
return; | |
mem = (MemoryBlock*)((uint8*)p-sizeof(MemoryBlock)); | |
mem->inAllocList.remove(); | |
totalMemoryAllocated -= mem->sz; | |
free(mem->origPtr); | |
} | |
// TODO: make the debug out configurable | |
void *mustmalloc_h(size_t sz, uint32 hint) | |
{ | |
void *ret; | |
ret = rwMalloc(sz, hint); | |
if(ret || sz == 0) | |
return ret; | |
fprintf(stderr, "Error: out of memory\n"); | |
exit(1); | |
return nil; | |
} | |
void *mustrealloc_h(void *p, size_t sz, uint32 hint) | |
{ | |
void *ret; | |
ret = rwRealloc(p, sz, hint); | |
if(ret || sz == 0) | |
return ret; | |
fprintf(stderr, "Error: out of memory\n"); | |
exit(1); | |
return nil; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment