#include #include #include static void *pool = nil; static void *ptop; static ulong psz = 0; static ulong csz = 0; static void *stack[128]; // Stack depth is 128 maximum static void **stop = stack; int hdebug = 0; void hinit(ulong sz) { if(pool) free(pool); pool = malloc(sz); if(pool == nil) sysfatal("hinit: %r"); psz = sz; csz = 0; ptop = pool; } void * halloc(ulong sz) { void *ptr; /* Check bounds */ if(sz + csz > psz) sysfatal("halloc: heap exhausted"); ptr = ptop; ptop = sz + (uchar*)ptop; csz += sz; if(hdebug) fprint(2, "halloc: %uld\n", csz); return ptr; } /* Stack management */ ulong hpush(void) { *stop = ptop; return (ulong)*stop++; } ulong hpop(void) { ptop = *--stop; csz = ((uchar *)ptop - (uchar*)pool); return (ulong)ptop; }