#include <cstdint>

extern "C" uint32_t         __end__;                                                                                                                                                                                extern "C" uint32_t         __HeapLimit;

// Turn off the errno macro and use actual global variable instead.
#undef errno
extern "C" int errno;

// Weak attribute allows user to override, e.g. to use external RAM for dynamic memory.
extern "C" __attribute__ ((weak)) void * _sbrk(int incr)
{
    static uint32_t heap = (uint32_t) &__end__;
    uint32_t prev_heap = heap;
    uint32_t new_heap = heap + incr;

    /* __HeapLimit is end of heap section */
    if (new_heap > (uint32_t) &__HeapLimit) {
        errno = -42;
        return (void *) - 1;
    }

    heap = new_heap;
    return (void *) prev_heap;
}

extern "C" __attribute__ ((weak)) int _getpid() { return -1; }
extern "C" __attribute__ ((weak)) int _close() { return -1; }
extern "C" __attribute__ ((weak)) int _kill() { return -1; }
