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