Home | History | Annotate | Line # | Download | only in stdlib
atexit.c revision 1.20
      1 /*	$NetBSD: atexit.c,v 1.20 2008/02/25 14:06:13 xtraeme Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #if defined(LIBC_SCCS) && !defined(lint)
     41 __RCSID("$NetBSD: atexit.c,v 1.20 2008/02/25 14:06:13 xtraeme Exp $");
     42 #endif /* LIBC_SCCS and not lint */
     43 
     44 #include "reentrant.h"
     45 
     46 #include <assert.h>
     47 #include <stdlib.h>
     48 
     49 #include "atexit.h"
     50 
     51 struct atexit_handler {
     52 	struct atexit_handler *ah_next;
     53 	union {
     54 		void (*fun_atexit)(void);
     55 		void (*fun_cxa_atexit)(void *);
     56 	} ah_fun;
     57 #define	ah_atexit	ah_fun.fun_atexit
     58 #define	ah_cxa_atexit	ah_fun.fun_cxa_atexit
     59 
     60 	void *ah_arg;	/* argument for cxa_atexit handlers */
     61 	void *ah_dso;	/* home DSO for cxa_atexit handlers */
     62 };
     63 
     64 /*
     65  * There must be at least 32 to guarantee ANSI conformance, plus
     66  * 3 additional ones for the benefit of the startup code, which
     67  * may use them to register the dynamic loader's cleanup routine,
     68  * the profiling cleanup routine, and the global destructor routine.
     69  */
     70 #define	NSTATIC_HANDLERS	(32 + 3)
     71 static struct atexit_handler atexit_handler0[NSTATIC_HANDLERS];
     72 
     73 #define	STATIC_HANDLER_P(ah)						\
     74 	(ah >= &atexit_handler0[0] && ah < &atexit_handler0[NSTATIC_HANDLERS])
     75 
     76 /*
     77  * Stack of atexit handlers.  Handlers must be called in the opposite
     78  * order they were registered.
     79  */
     80 static struct atexit_handler *atexit_handler_stack;
     81 
     82 #ifdef _REENTRANT
     83 /* ..and a mutex to protect it all. */
     84 static mutex_t atexit_mutex;
     85 #endif /* _REENTRANT */
     86 
     87 void	__libc_atexit_init(void) __attribute__ ((visibility("hidden")));
     88 
     89 /*
     90  * Allocate an atexit handler descriptor.  If "dso" is NULL, it indicates
     91  * a normal atexit handler, which must be allocated from the static pool,
     92  * if possible. cxa_atexit handlers are never allocated from the static
     93  * pool.
     94  *
     95  * atexit_mutex must be held.
     96  */
     97 static struct atexit_handler *
     98 atexit_handler_alloc(void *dso)
     99 {
    100 	struct atexit_handler *ah;
    101 	int i;
    102 
    103 	if (dso == NULL) {
    104 		for (i = 0; i < NSTATIC_HANDLERS; i++) {
    105 			ah = &atexit_handler0[i];
    106 			if (ah->ah_atexit == NULL && ah->ah_next == NULL) {
    107 				/* Slot is free. */
    108 				return (ah);
    109 			}
    110 		}
    111 	}
    112 
    113 	/*
    114 	 * Either no static slot was free, or this is a cxa_atexit
    115 	 * handler.  Allocate a new one.  We keep the atexit_mutex
    116 	 * held to prevent handlers from being run while we (potentially)
    117 	 * block in malloc().
    118 	 */
    119 	ah = malloc(sizeof(*ah));
    120 	return (ah);
    121 }
    122 
    123 void
    124 __libc_atexit_init(void)
    125 {
    126 	mutexattr_t atexit_mutex_attr;
    127 	mutexattr_init(&atexit_mutex_attr);
    128 	mutexattr_settype(&atexit_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
    129 	mutex_init(&atexit_mutex, &atexit_mutex_attr);
    130 }
    131 
    132 /*
    133  * Register an atexit routine.  This is suitable either for a cxa_atexit
    134  * or normal atexit type handler.  The __cxa_atexit() name and arguments
    135  * are specified by the C++ ABI.  See:
    136  *
    137  *	http://www.codesourcery.com/cxx-abi/abi.html#dso-dtor
    138  */
    139 int
    140 __cxa_atexit(void (*func)(void *), void *arg, void *dso)
    141 {
    142 	struct atexit_handler *ah;
    143 
    144 	_DIAGASSERT(func != NULL);
    145 
    146 	mutex_lock(&atexit_mutex);
    147 
    148 	ah = atexit_handler_alloc(dso);
    149 	if (ah == NULL) {
    150 		mutex_unlock(&atexit_mutex);
    151 		return (-1);
    152 	}
    153 
    154 	ah->ah_cxa_atexit = func;
    155 	ah->ah_arg = arg;
    156 	ah->ah_dso = dso;
    157 
    158 	ah->ah_next = atexit_handler_stack;
    159 	atexit_handler_stack = ah;
    160 
    161 	mutex_unlock(&atexit_mutex);
    162 	return (0);
    163 }
    164 
    165 /*
    166  * Run the list of atexit handlers.  If dso is NULL, run all of them,
    167  * otherwise run only those matching the specified dso.
    168  *
    169  * Note that we can be recursively invoked; rtld cleanup is via an
    170  * atexit handler, and rtld cleanup invokes _fini() for DSOs, which
    171  * in turn invokes __cxa_finalize() for the DSO.
    172  */
    173 void
    174 __cxa_finalize(void *dso)
    175 {
    176 	static thr_t owner;
    177 	static u_int call_depth;
    178 	struct atexit_handler *ah, *dead_handlers = NULL, **prevp;
    179 	void (*cxa_func)(void *);
    180 	void (*atexit_func)(void);
    181 
    182 	/*
    183 	 * We implement our own recursive mutex here because we need
    184 	 * to keep track of the call depth anyway, and it saves us
    185 	 * having to dynamically initialize the mutex.
    186 	 */
    187 	if (mutex_trylock(&atexit_mutex) == 0)
    188 		owner = thr_self();
    189 	else if (owner != thr_self()) {
    190 		mutex_lock(&atexit_mutex);
    191 		owner = thr_self();
    192 	}
    193 
    194 	call_depth++;
    195 
    196 	/*
    197 	 * If we are at call depth 1 (which is usually the "do everything"
    198 	 * call from exit(3)), we go ahead and remove elements from the
    199 	 * list as we call them.  This will prevent any nested calls from
    200 	 * having to traverse elements we've already processed.  If we are
    201 	 * at call depth > 1, we simply mark elements we process as unused.
    202 	 * When the depth 1 caller sees those, it will simply unlink them
    203 	 * for us.
    204 	 */
    205 again:
    206 	for (prevp = &atexit_handler_stack; (ah = (*prevp)) != NULL;) {
    207 		if (dso == NULL || dso == ah->ah_dso || ah->ah_atexit == NULL) {
    208 			if (ah->ah_atexit != NULL) {
    209 				void *p = atexit_handler_stack;
    210 				if (ah->ah_dso != NULL) {
    211 					cxa_func = ah->ah_cxa_atexit;
    212 					ah->ah_cxa_atexit = NULL;
    213 					(*cxa_func)(ah->ah_arg);
    214 				} else {
    215 					atexit_func = ah->ah_atexit;
    216 					ah->ah_atexit = NULL;
    217 					(*atexit_func)();
    218 				}
    219 				/* Restart if new atexit handler was added. */
    220 				if (p != atexit_handler_stack)
    221 					goto again;
    222 			}
    223 
    224 			if (call_depth == 1) {
    225 				*prevp = ah->ah_next;
    226 				if (STATIC_HANDLER_P(ah))
    227 					ah->ah_next = NULL;
    228 				else {
    229 					ah->ah_next = dead_handlers;
    230 					dead_handlers = ah;
    231 				}
    232 			} else
    233 				prevp = &ah->ah_next;
    234 		} else
    235 			prevp = &ah->ah_next;
    236 	}
    237 
    238 	call_depth--;
    239 
    240 	if (call_depth > 0)
    241 		return;
    242 
    243 	mutex_unlock(&atexit_mutex);
    244 
    245 	/*
    246 	 * Now free any dead handlers.  Do this even if we're about to
    247 	 * exit, in case a leak-detecting malloc is being used.
    248 	 */
    249 	while ((ah = dead_handlers) != NULL) {
    250 		dead_handlers = ah->ah_next;
    251 		free(ah);
    252 	}
    253 }
    254 
    255 /*
    256  * Register a function to be performed at exit.
    257  */
    258 int
    259 atexit(void (*func)(void))
    260 {
    261 
    262 	return (__cxa_atexit((void (*)(void *))func, NULL, NULL));
    263 }
    264