#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

#include <nllibc.h>

#define ATEXIT_FUNCTION_NUM 16
static int atexit_functions_num = 0;
static void (*atexit_functions[ATEXIT_FUNCTION_NUM])(void);

void exit(int status)
{
  while (atexit_functions_num > 0) {
    atexit_functions[--atexit_functions_num]();
  }

  _exit(status);
}

void abort(void)
{
  *(int *)(-1) = 0;
  exit(1);
}

void __stack_chk_fail(void)
{
  abort();
}

int atexit(void (*function)(void))
{
  if (atexit_functions_num == ATEXIT_FUNCTION_NUM) {
    errno = ENOMEM;
    return -1;
  }

  atexit_functions[atexit_functions_num++] = function;

  return 0;
}
