summaryrefslogtreecommitdiff
path: root/heap.c
diff options
context:
space:
mode:
Diffstat (limited to 'heap.c')
-rw-r--r--heap.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/heap.c b/heap.c
new file mode 100644
index 0000000..0789abc
--- /dev/null
+++ b/heap.c
@@ -0,0 +1,63 @@
+#include<u.h>
+#include<libc.h>
+#include<mheap.h>
+
+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;
+}