// Minimal stubs to support newlib.

// See: https://sourceware.org/newlib/libc.html#Syscalls

#include <errno.h>
#undef errno
extern int errno;


#if 0
// _sbrk is required for malloc, and actually does something.
// Strangely, even if the application doesn't use malloc() (or new, etc.) then 
// defining _sbrk causes the linker to include malloc and free.
// It is therefore disabled.

void* _sbrk(int incr) {
  extern char _end;		/* Defined by the linker */
  static char *heap_end;
  char *prev_heap_end;
 
  if (heap_end == 0) {
    heap_end = &_end;
  }
  prev_heap_end = heap_end;

  // Magic to get the stack pointer:
  register char* stack_ptr asm ("sp");

  if (heap_end + incr > stack_ptr) {
//    write (1, "Heap and stack collision\n", 25);
//    abort ();
    errno = ENOMEM;
    return (void*)-1;
  }

  heap_end += incr;
  return (void*) prev_heap_end;
}
#endif


// Other stubs do nothing useful:

void _exit(int status __attribute__((unused)) )
{
  while (1) {}
}
