1 /**
2  * Copyright (c) 2012 David Chisnall.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to
6  * deal in the Software without restriction, including without limitation the
7  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8  * sell copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20  * IN THE SOFTWARE.
21  *
22  */
23 
24 /* Special thanks to TBricks for partially funding this work */
25 
26 #ifdef __sun__
27 #include <pthread.h>
28 #include <stdlib.h>
29 
30 static struct atexit_handler {
31   void (*f)(void *);
32   void *p;
33   void *d;
34   struct atexit_handler *next;
35 } *head;
36 
37 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
38 
39 int __cxa_atexit( void (*f)(void *), void *p, void *d) {
40   pthread_mutex_lock(&lock);
41   struct atexit_handler *h = malloc(sizeof(*h));
42   if (!h) {
43     pthread_mutex_unlock(&lock);
44     return 1;
45   }
46   h->f = f;
47   h->p = p;
48   h->d = d;
49   h->next = head;
50   head = h;
51   pthread_mutex_unlock(&lock);
52   return 0;
53 }
54 
55 void __cxa_finalize(void *d ) {
56   pthread_mutex_lock(&lock);
57   struct atexit_handler **last = &head;
58   for (struct atexit_handler *h = head ; h ; h = h->next) {
59     if ((h->d == d) || (d == 0)) {
60       *last = h->next;
61       h->f(h->p);
62       free(h);
63     } else {
64       last = &h->next;
65     }
66   }
67   pthread_mutex_unlock(&lock);
68 }
69 #endif
70