:: commit f4522ba51617567fb0a7ff9fe7976f1bd288f749

mintsuki <mintsuki@protonmail.com> — 2020-04-13 06:21

parents: 3a4ec45eec

Add panics on failed allocations

diff --git a/src/lib/blib.c b/src/lib/blib.c
index 26191d0b..6d78a87f 100644
--- a/src/lib/blib.c
+++ b/src/lib/blib.c
@@ -8,22 +8,37 @@
 #include <lib/libc.h>
 #include <lib/cio.h>
 
+void panic(const char *str) {
+    print("PANIC: %s", str);
+    for (;;) {
+        asm volatile ("cli; hlt");
+    }
+}
+
 static size_t bump_allocator_base = 0x20000;
+#define BUMP_ALLOCATOR_LIMIT ((size_t)0x80000)
 
 void *balloc(size_t count) {
     void *ret = (void *)bump_allocator_base;
-    bump_allocator_base += count;
+    size_t new_base = bump_allocator_base + count;
+    if (new_base >= BUMP_ALLOCATOR_LIMIT)
+        panic("Memory allocation failed");
+    bump_allocator_base = new_base;
     return ret;
 }
 
 // Only power of 2 alignments
 void *balloc_aligned(size_t count, size_t alignment) {
-    if (bump_allocator_base & (alignment - 1)) {
-        bump_allocator_base &= ~(alignment - 1);
-        bump_allocator_base += alignment;
+    size_t new_base = bump_allocator_base;
+    if (new_base & (alignment - 1)) {
+        new_base &= ~(alignment - 1);
+        new_base += alignment;
     }
-    void *ret = (void *)bump_allocator_base;
-    bump_allocator_base += count;
+    void *ret = (void *)new_base;
+    new_base += count;
+    if (new_base >= BUMP_ALLOCATOR_LIMIT)
+        panic("Memory allocation failed");
+    bump_allocator_base = new_base;
     return ret;
 }
 
diff --git a/src/lib/blib.h b/src/lib/blib.h
index 20083b73..f3d99f35 100644
--- a/src/lib/blib.h
+++ b/src/lib/blib.h
@@ -4,6 +4,8 @@
 #include <stddef.h>
 #include <stdint.h>
 
+void panic(const char *str);
+
 void pit_sleep(uint64_t pit_ticks);
 int pit_sleep_and_quit_on_keypress(uint64_t pit_ticks);
 
tab: 248 wrap: offon