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;
18
19#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
20static volatile int lock[1];
21volatile int *const __atexit_lockptr = lock;
22#endif
23
24void __funcs_on_exit()
25{
26 void (*func)(void *), *arg;
27 LOCK(lock);
28 for (; head; head=head->next, slot=COUNT) while(slot-->0) {
29 func = head->f[slot];
30 arg = head->a[slot];
31 UNLOCK(lock);
32 func(arg);
33 LOCK(lock);
34 }
35}
36
37void __cxa_finalize(void *dso)
38{
39}
40
41int __cxa_atexit(void (*func)(void *), void *arg, void *dso)
42{
43 LOCK(lock);
44
45 /* Defer initialization of head so it can be in BSS */
46 if (!head) head = &builtin;
47
48 /* If the current function list is full, add a new one */
49 if (slot==COUNT) {
50 struct fl *new_fl = calloc(sizeof(struct fl), 1);
51 if (!new_fl) {
52 UNLOCK(lock);
53 return -1;
54 }
55 new_fl->next = head;
56 head = new_fl;
57 slot = 0;
58 }
59
60 /* Append function to the list. */
61 head->f[slot] = func;
62 head->a[slot] = arg;
63 slot++;
64
65 UNLOCK(lock);
66 return 0;
67}
68
69static void call(void *p)
70{
71 ((void (*)(void))(uintptr_t)p)();
72}
73
74int atexit(void (*func)(void))
75{
76 return __cxa_atexit(call, (void *)(uintptr_t)func, 0);
77}