1 2 #include <stdint.h> 3 #include <stdlib.h> 4 5 #include <syscall.h> 6 7 struct atexit_cb { 8 struct atexit_cb *next; 9 void (*cb)(void); 10 }; 11 12 static uint64_t _atexit_count = 0; 13 static struct atexit_cb _atexits[32]; // POSIX requires at least 32 atexit functions 14 static struct atexit_cb *_atexit_last = NULL; 15 16 int atexit(void (* function)(void))17atexit(void (*function)(void)) 18 { 19 if (_atexit_count < 32) { 20 struct atexit_cb *prev = _atexit_last; 21 22 _atexits[_atexit_count].cb = function; 23 _atexits[_atexit_count].next = prev; 24 25 _atexit_last = &_atexits[_atexit_count]; 26 _atexit_count++; 27 } else { 28 // XXX: Support malloc 29 return -1; 30 } 31 32 return 0; 33 } 34 35 void exit(int status)36exit(int status) 37 { 38 while (_atexit_last != NULL) { 39 (_atexit_last->cb)(); 40 _atexit_last = _atexit_last->next; 41 } 42 43 OSExit(status & 0x00ff); 44 45 __builtin_unreachable(); 46 } 47 48