diff --git a/cores/arduino/main.cpp b/cores/arduino/main.cpp index a6d2cb5f5..8c9bf4659 100644 --- a/cores/arduino/main.cpp +++ b/cores/arduino/main.cpp @@ -56,3 +56,10 @@ int main( void ) return 0; } + +// Ensure our version of sbrk is used by forcing a reference to it here +// (without this, an undefined reference only occurs later when linking +// newlib, and the dummy from libgloss/nosys will be used instead). +// This variable will be optimized away later. +extern "C" void *_sbrk(int); +void * force_reference_to_sbrk = (void*)&_sbrk; diff --git a/cores/arduino/sbrk.c b/cores/arduino/sbrk.c new file mode 100644 index 000000000..e3d4d8a3b --- /dev/null +++ b/cores/arduino/sbrk.c @@ -0,0 +1,23 @@ +#include +#include +#include + +/* How much free space to keep between the stack and the heap by malloc. + * Can be changed by the application at any time. */ +size_t __malloc_margin = 64; + +void *_sbrk(int incr) +{ + extern char end; /* End of global variables, defined by the linker */ + static char *brkval = &end ; + char *prev_brkval = brkval; + + if (brkval + incr + __malloc_margin > (char *)__get_MSP()) { + /* Heap and stack collision */ + errno = ENOMEM; + return (void*) -1; + } + + brkval += incr ; + return (void*) prev_brkval; +} diff --git a/platform.txt b/platform.txt index 3071243ec..e93637426 100644 --- a/platform.txt +++ b/platform.txt @@ -39,13 +39,13 @@ compiler.optimization_flags.debug=-Og -g3 compiler.path={runtime.tools.arm-none-eabi-gcc-7-2017q4.path}/bin/ compiler.c.cmd=arm-none-eabi-gcc -compiler.c.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.optimization_flags} {compiler.warning_flags} -std=gnu11 -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -MMD +compiler.c.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.optimization_flags} {compiler.warning_flags} -std=gnu11 -ffunction-sections -fdata-sections --param max-inline-insns-single=500 -MMD compiler.c.elf.cmd=arm-none-eabi-g++ compiler.c.elf.flags={compiler.optimization_flags} -Wl,--gc-sections -save-temps compiler.S.cmd=arm-none-eabi-gcc compiler.S.flags=-mcpu={build.mcu} -mthumb -c -g -x assembler-with-cpp -MMD compiler.cpp.cmd=arm-none-eabi-g++ -compiler.cpp.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.optimization_flags} {compiler.warning_flags} -std=gnu++11 -ffunction-sections -fdata-sections -fno-threadsafe-statics -nostdlib --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -MMD +compiler.cpp.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.optimization_flags} {compiler.warning_flags} -std=gnu++11 -ffunction-sections -fdata-sections -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -MMD compiler.ar.cmd=arm-none-eabi-ar compiler.ar.flags=rcs compiler.objcopy.cmd=arm-none-eabi-objcopy