hammer/src/system_allocator.c

84 lines
2 KiB
C
Raw Normal View History

2013-04-26 20:36:54 -07:00
#include <string.h>
#include <stdlib.h>
2012-10-10 15:58:03 +02:00
#include "internal.h"
// NOTE(uucidl): undefine to automatically fill up newly allocated block
// with this byte:
// #define DEBUG__MEMFILL 0xFF
/**
* Blocks allocated by the system_allocator start with this header.
* I.e. the user part of the allocation directly follows.
*/
typedef struct HDebugBlockHeader_
{
size_t size; /** size of the user allocation */
} HDebugBlockHeader;
#define BLOCK_HEADER_SIZE (sizeof(HDebugBlockHeader))
/**
* Compute the total size needed for a given allocation size.
*/
static inline size_t block_size(size_t alloc_size) {
return BLOCK_HEADER_SIZE + alloc_size;
}
/**
* Obtain the block containing the user pointer `uptr`
*/
static inline void* block_for_user_ptr(void *uptr) {
return ((char*)uptr) - BLOCK_HEADER_SIZE;
}
/**
* Obtain the user area of the allocation from a given block
*/
static inline void* user_ptr(void *block) {
return ((char*)block) + BLOCK_HEADER_SIZE;
}
2012-10-10 15:58:03 +02:00
static void* system_alloc(HAllocator *allocator, size_t size) {
void *block = malloc(block_size(size));
if (!block) {
return NULL;
}
void *uptr = user_ptr(block);
#ifdef DEBUG__MEMFILL
memset(uptr, DEBUG__MEMFILL, size);
#endif
((HDebugBlockHeader*)block)->size = size;
return uptr;
2012-10-10 15:58:03 +02:00
}
static void* system_realloc(HAllocator *allocator, void* uptr, size_t size) {
if (!uptr) {
2013-04-26 20:36:54 -07:00
return system_alloc(allocator, size);
}
void* block = realloc(block_for_user_ptr(uptr), block_size(size));
if (!block) {
return NULL;
}
uptr = user_ptr(block);
#ifdef DEBUG__MEMFILL
size_t old_size = ((HDebugBlockHeader*)block)->size;
2013-04-26 20:36:54 -07:00
if (size > old_size)
memset((char*)uptr+old_size, DEBUG__MEMFILL, size - old_size);
#endif
((HDebugBlockHeader*)block)->size = size;
return uptr;
2012-10-10 15:58:03 +02:00
}
static void system_free(HAllocator *allocator, void* uptr) {
if (uptr) {
free(block_for_user_ptr(uptr));
}
2012-10-10 15:58:03 +02:00
}
HAllocator system_allocator = {
.alloc = system_alloc,
.realloc = system_realloc,
.free = system_free,
};