atexit.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include "libc.h"
  4. #include "lock.h"
  5. /* Ensure that at least 32 atexit handlers can be registered without malloc */
  6. #define COUNT 32
  7. static struct fl
  8. {
  9. struct fl *next;
  10. void (*f[COUNT])(void *);
  11. void *a[COUNT];
  12. } builtin, *head;
  13. static int slot;
  14. static volatile int lock[1];
  15. void __funcs_on_exit()
  16. {
  17. void (*func)(void *), *arg;
  18. LOCK(lock);
  19. for (; head; head=head->next, slot=COUNT) while(slot-->0) {
  20. func = head->f[slot];
  21. arg = head->a[slot];
  22. UNLOCK(lock);
  23. func(arg);
  24. LOCK(lock);
  25. }
  26. }
  27. void __cxa_finalize(void *dso)
  28. {
  29. }
  30. int __cxa_atexit(void (*func)(void *), void *arg, void *dso)
  31. {
  32. LOCK(lock);
  33. /* Defer initialization of head so it can be in BSS */
  34. if (!head) head = &builtin;
  35. /* If the current function list is full, add a new one */
  36. if (slot==COUNT) {
  37. struct fl *new_fl = calloc(sizeof(struct fl), 1);
  38. if (!new_fl) {
  39. UNLOCK(lock);
  40. return -1;
  41. }
  42. new_fl->next = head;
  43. head = new_fl;
  44. slot = 0;
  45. }
  46. /* Append function to the list. */
  47. head->f[slot] = func;
  48. head->a[slot] = arg;
  49. slot++;
  50. UNLOCK(lock);
  51. return 0;
  52. }
  53. static void call(void *p)
  54. {
  55. ((void (*)(void))(uintptr_t)p)();
  56. }
  57. int atexit(void (*func)(void))
  58. {
  59. return __cxa_atexit(call, (void *)(uintptr_t)func, 0);
  60. }