_sbrk() check for overflow past MSP.
authorAdam Green <adamgr@foo.bar>
Thu, 7 Feb 2013 03:01:50 +0000 (19:01 -0800)
committerAdam Green <adamgr@foo.bar>
Thu, 7 Feb 2013 03:01:50 +0000 (19:01 -0800)
Make sure that a dynamic memory allocation won't exceed the current top
of stack.  It is still possible for stack to grow down into heap.

gcc4mbed/src/gcc4mbed.c

index 81d9484..c6a70e2 100644 (file)
@@ -15,6 +15,8 @@
 */\r
 /* Provide routines which hook the MRI debug monitor into GCC4MBED projects. */\r
 #include <string.h>\r
+#include <sys/types.h>\r
+#include <errno.h>\r
 #include <mri.h>\r
 #include <cmsis.h>\r
 \r
@@ -123,3 +125,27 @@ extern "C" void __malloc_lock(void)
 extern "C" void __malloc_unlock(void)\r
 {\r
 }\r
+\r
+\r
+/* Linker defined symbol to be used by sbrk for where dynamically heap should start. */\r
+extern "C" int __HeapLimit;\r
+\r
+/* Turn off the errno macro and use actual external global variable instead. */\r
+#undef errno\r
+extern int errno;\r
+\r
+/* Dynamic memory allocation related syscalls. */\r
+extern "C" caddr_t _sbrk(int incr) \r
+{\r
+    static unsigned char* heap = (unsigned char*)&__HeapLimit;\r
+    unsigned char*        prev_heap = heap;\r
+    unsigned char*        new_heap = heap + incr;\r
+\r
+    if (new_heap >= (unsigned char*)__get_MSP()) {\r
+        errno = ENOMEM;\r
+        return (caddr_t)-1;\r
+    }\r
+    \r
+    heap = new_heap;\r
+    return (caddr_t) prev_heap;\r
+}\r