Skip to content

Commit

Permalink
Make the custom heap thing more portable and slower
Browse files Browse the repository at this point in the history
  • Loading branch information
radare committed Nov 28, 2024
1 parent 0ac0ec9 commit 2d4b255
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 15 deletions.
29 changes: 16 additions & 13 deletions include/sdb/heap.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,47 +12,50 @@ typedef struct sdb_global_heap_t {
void *data;
} SdbGlobalHeap;

extern SdbGlobalHeap Gheap;
extern const SdbGlobalHeap sdb_gh_custom; // custom heap allocator
extern const SdbGlobalHeap sdb_gh_libc; // use libc's heap
SDB_API SdbGlobalHeap *sdb_heap_global(void);

static inline void sdb_gh_use(const SdbGlobalHeap *gh) {
SdbGlobalHeap *gheap = sdb_heap_global ();
if (gh) {
memcpy (&Gheap, gh, sizeof (SdbGlobalHeap));
memcpy (gheap, gh, sizeof (SdbGlobalHeap));
} else {
memset (&Gheap, 0, sizeof (SdbGlobalHeap));
memset (gheap, 0, sizeof (SdbGlobalHeap));
}
}

static inline void sdb_gh_fini(void) {
if (Gheap.fini) {
Gheap.fini (Gheap.data);
SdbGlobalHeap *gheap = sdb_heap_global ();
if (gheap->fini) {
gheap->fini (gheap->data);
}
}

static inline void *sdb_gh_malloc(size_t size) {
if (Gheap.realloc) {
void *ptr = Gheap.realloc (Gheap.data, NULL, size);
SdbGlobalHeap *gheap = sdb_heap_global ();
if (gheap->realloc) {
void *ptr = gheap->realloc (gheap->data, NULL, size);
// eprintf ("malloc %p\n" , ptr);
return ptr;
}
return malloc (size);
}

static inline void *sdb_gh_realloc(void *ptr, size_t size) {
if (Gheap.realloc) {
return Gheap.realloc (Gheap.data, ptr, size);
SdbGlobalHeap *gheap = sdb_heap_global ();
if (gheap->realloc) {
return gheap->realloc (gheap->data, ptr, size);
}
return realloc (ptr, size);
}

static inline void sdb_gh_free(void *ptr) {
SdbGlobalHeap *gheap = sdb_heap_global ();
if (!ptr) {
return;
}
if (Gheap.realloc) {
if (gheap->realloc) {
// eprintf ("free ptr %p\n" , ptr);
Gheap.realloc (Gheap.data, ptr, 0);
gheap->realloc (gheap->data, ptr, 0);
} else {
free (ptr);
}
Expand Down
2 changes: 2 additions & 0 deletions src/entry.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#define SDB_CUSTOM_HEAP sdb_gh_custom
#endif

static const SdbGlobalHeap sdb_gh_libc = { NULL, NULL, NULL };

int main(int argc, const char **argv) {
#if USE_SDB_HEAP
sdb_gh_use (&SDB_CUSTOM_HEAP);
Expand Down
7 changes: 5 additions & 2 deletions src/heap.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
#include "sdb/sdb.h"
#include "sdb/heap.h"

const SdbGlobalHeap sdb_gh_libc = { NULL, NULL, NULL };
SdbGlobalHeap Gheap = {NULL, NULL};
static SdbGlobalHeap Gheap = { NULL, NULL, NULL };

SDB_API SdbGlobalHeap *sdb_heap_global(void) {
return &Gheap;
}

SDB_API char *sdb_strdup(const char *s) {
size_t sl = strlen (s) + 1;
Expand Down

0 comments on commit 2d4b255

Please sign in to comment.