2001-03-22 Philip Blundell <philb@gnu.org>
[binutils.git] / libiberty / xatexit.c
blob31476c29ddca36d2b037c26541147bd43c1a6805
1 /*
2 * Copyright (c) 1990 Regents of the University of California.
3 * All rights reserved.
5 * %sccs.include.redist.c%
6 */
8 /* Adapted from newlib/libc/stdlib/{,at}exit.[ch].
9 If you use xatexit, you must call xexit instead of exit. */
11 #include "ansidecl.h"
12 #include "libiberty.h"
14 #include <stdio.h>
16 #ifdef __STDC__
17 #include <stddef.h>
18 #else
19 #define size_t unsigned long
20 #endif
22 /* For systems with larger pointers than ints, this must be declared. */
23 PTR malloc PARAMS ((size_t));
25 static void xatexit_cleanup PARAMS ((void));
27 /* Pointer to function run by xexit. */
28 extern void (*_xexit_cleanup) PARAMS ((void));
30 #define XATEXIT_SIZE 32
32 struct xatexit {
33 struct xatexit *next; /* next in list */
34 int ind; /* next index in this table */
35 void (*fns[XATEXIT_SIZE]) PARAMS ((void)); /* the table itself */
38 /* Allocate one struct statically to guarantee that we can register
39 at least a few handlers. */
40 static struct xatexit xatexit_first;
42 /* Points to head of LIFO stack. */
43 static struct xatexit *xatexit_head = &xatexit_first;
45 /* Register function FN to be run by xexit.
46 Return 0 if successful, -1 if not. */
48 int
49 xatexit (fn)
50 void (*fn) PARAMS ((void));
52 register struct xatexit *p;
54 /* Tell xexit to call xatexit_cleanup. */
55 if (!_xexit_cleanup)
56 _xexit_cleanup = xatexit_cleanup;
58 p = xatexit_head;
59 if (p->ind >= XATEXIT_SIZE)
61 if ((p = (struct xatexit *) malloc (sizeof *p)) == NULL)
62 return -1;
63 p->ind = 0;
64 p->next = xatexit_head;
65 xatexit_head = p;
67 p->fns[p->ind++] = fn;
68 return 0;
71 /* Call any cleanup functions. */
73 static void
74 xatexit_cleanup ()
76 register struct xatexit *p;
77 register int n;
79 for (p = xatexit_head; p; p = p->next)
80 for (n = p->ind; --n >= 0;)
81 (*p->fns[n]) ();