OSDN Git Service

2006-05-15 Mircea Namolaru <namolaru@il.ibm.com>
[pf3gnuchains/gcc-fork.git] / gcc / config / darwin-crt3.c
1 /* __cxa_atexit backwards-compatibility support for Darwin.
2    Copyright (C) 2006 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 In addition to the permissions in the GNU General Public License, the
12 Free Software Foundation gives you unlimited permission to link the
13 compiled version of this file into combinations with other programs,
14 and to distribute those combinations without any restriction coming
15 from the use of this file.  (The General Public License restrictions
16 do apply in other respects; for example, they cover modification of
17 the file, and distribution when not linked into a combine
18 executable.)
19
20 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
21 WARRANTY; without even the implied warranty of MERCHANTABILITY or
22 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
23 for more details.
24
25 You should have received a copy of the GNU General Public License
26 along with GCC; see the file COPYING.  If not, write to the Free
27 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
28 02110-1301, USA.  */
29
30 /* It is incorrect to include config.h here, because this file is being
31    compiled for the target, and hence definitions concerning only the host
32    do not apply.  */
33
34 #include "tconfig.h"
35 #include "tsystem.h"
36
37 #include <dlfcn.h>
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <string.h>
41
42 /* This file works around two different problems.
43
44    The first problem is that there is no __cxa_atexit on Mac OS versions
45    before 10.4.  It fixes this by providing a complete atexit and
46    __cxa_atexit emulation called from the regular atexit.
47
48    The second problem is that on all shipping versions of Mac OS,
49    __cxa_finalize and exit() don't work right: they don't run routines
50    that were registered while other atexit routines are running.  This
51    is worked around by wrapping each atexit/__cxa_atexit routine with
52    our own routine which ensures that any __cxa_atexit calls while it
53    is running are honoured.
54
55    There are still problems which this does not solve.  Before 10.4,
56    shared objects linked with previous compilers won't have their
57    atexit calls properly interleaved with code compiled with newer
58    compilers.  Also, atexit routines registered from shared objects
59    linked with previous compilers won't get the bug fix.  */
60
61 typedef int (*cxa_atexit_p)(void (*func) (void*), void* arg, const void* dso);
62 typedef void (*cxa_finalize_p)(const void *dso);
63 typedef int (*atexit_p)(void (*func)(void));
64
65 /* These are from "keymgr.h".  */
66 extern void *_keymgr_get_and_lock_processwide_ptr (unsigned key);
67 extern int _keymgr_get_and_lock_processwide_ptr_2 (unsigned, void **);
68 extern int _keymgr_set_and_unlock_processwide_ptr (unsigned key, void *ptr);
69
70 extern void *__keymgr_global[];
71 typedef struct _Sinfo_Node {
72         unsigned int size ;             /*size of this node*/
73         unsigned short major_version ;  /*API major version.*/
74         unsigned short minor_version ;  /*API minor version.*/
75         } _Tinfo_Node ;
76
77 #ifdef __ppc__
78 #define CHECK_KEYMGR_ERROR(e) \
79   (((_Tinfo_Node *)__keymgr_global[2])->major_version >= 4 ? (e) : 0)
80 #else
81 #define CHECK_KEYMGR_ERROR(e) (e)
82 #endif
83
84 /* Our globals are stored under this keymgr index.  */
85 #define KEYMGR_ATEXIT_LIST      14
86
87 /* The different kinds of callback routines.  */
88 typedef void (*atexit_callback)(void);
89 typedef void (*cxa_atexit_callback)(void *);
90
91 /* This structure holds a routine to call.  There may be extra fields
92    at the end of the structure that this code doesn't know about.  */
93 struct one_atexit_routine 
94 {
95   union {
96     atexit_callback ac;
97     cxa_atexit_callback cac;
98   } callback;
99   /* has_arg is 0/2/4 if 'ac' is live, 1/3/5 if 'cac' is live.  
100      Higher numbers indicate a later version of the structure that this
101      code doesn't understand and will ignore.  */
102   int has_arg;
103   void * arg;
104 };
105
106 struct atexit_routine_list
107 {
108   struct atexit_routine_list * next;
109   struct one_atexit_routine r;
110 };
111
112 /* The various possibilities for status of atexit().  */
113 enum atexit_status {
114   atexit_status_unknown = 0,
115   atexit_status_missing = 1,
116   atexit_status_broken = 2,
117   atexit_status_working = 16
118 };
119
120 struct keymgr_atexit_list
121 {
122   /* Version of this list.  This code knows only about version 0.
123      If the version is higher than 0, this code may add new atexit routines
124      but should not attempt to run the list.  */
125   short version;
126   /* 1 if an atexit routine is currently being run by this code, 0
127      otherwise.  */
128   char running_routines;
129   /* Holds a value from 'enum atexit_status'.  */
130   unsigned char atexit_status;
131   /* The list of atexit and cxa_atexit routines registered.  If
132    atexit_status_missing it contains all routines registered while
133    linked with this code.  If atexit_status_broken it contains all
134    routines registered during cxa_finalize while linked with this
135    code.  */
136   struct atexit_routine_list *l;
137   /* &__cxa_atexit; set if atexit_status >= atexit_status_broken.  */
138   cxa_atexit_p cxa_atexit_f;
139   /* &__cxa_finalize; set if atexit_status >= atexit_status_broken.  */
140   cxa_finalize_p cxa_finalize_f;
141   /* &atexit; set if atexit_status >= atexit_status_working
142      or atexit_status == atexit_status_missing.  */
143   atexit_p atexit_f;
144 };
145
146 /* Return 0 if __cxa_atexit has the bug it has in Mac OS 10.4: it
147    fails to call routines registered while an atexit routine is
148    running.  Return 1 if it works properly, and -1 if an error occurred.  */
149
150 struct atexit_data 
151 {
152   int result;
153   cxa_atexit_p cxa_atexit;
154 };
155
156 static void cxa_atexit_check_2 (void *arg)
157 {
158   ((struct atexit_data *)arg)->result = 1;
159 }
160
161 static void cxa_atexit_check_1 (void *arg)
162 {
163   struct atexit_data * aed = arg;
164   if (aed->cxa_atexit (cxa_atexit_check_2, arg, arg) != 0)
165     aed->result = -1;
166 }
167
168 static int
169 check_cxa_atexit (cxa_atexit_p cxa_atexit, cxa_finalize_p cxa_finalize)
170 {
171   struct atexit_data aed = { 0, cxa_atexit };
172
173   /* We re-use &aed as the 'dso' parameter, since it's a unique address.  */
174   if (cxa_atexit (cxa_atexit_check_1, &aed, &aed) != 0)
175     return -1;
176   cxa_finalize (&aed);
177   if (aed.result == 0)
178     {
179       /* Call __cxa_finalize again to make sure that cxa_atexit_check_2
180          is removed from the list before AED goes out of scope.  */
181       cxa_finalize (&aed);
182       aed.result = 0;
183     }
184   return aed.result;
185 }
186
187 #ifdef __ppc__
188 /* This comes from Csu.  It works only before 10.4.  The prototype has
189    been altered a bit to avoid casting.  */
190 extern int _dyld_func_lookup(const char *dyld_func_name,
191      void *address) __attribute__((visibility("hidden")));
192
193 static void our_atexit (void);
194
195 /* We're running on 10.3.9.  Find the address of the system atexit()
196    function.  So easy to say, so hard to do.  */
197 static atexit_p
198 find_atexit_10_3 (void)
199 {
200   unsigned int (*dyld_image_count_fn)(void);
201   const char *(*dyld_get_image_name_fn)(unsigned int image_index);
202   const void *(*dyld_get_image_header_fn)(unsigned int image_index);
203   const void *(*NSLookupSymbolInImage_fn)(const void *image, 
204                                           const char *symbolName,
205                                           unsigned int options);
206   void *(*NSAddressOfSymbol_fn)(const void *symbol);
207   unsigned i, count;
208   
209   /* Find some dyld functions.  */
210   _dyld_func_lookup("__dyld_image_count", &dyld_image_count_fn);
211   _dyld_func_lookup("__dyld_get_image_name", &dyld_get_image_name_fn);
212   _dyld_func_lookup("__dyld_get_image_header", &dyld_get_image_header_fn);
213   _dyld_func_lookup("__dyld_NSLookupSymbolInImage", &NSLookupSymbolInImage_fn);
214   _dyld_func_lookup("__dyld_NSAddressOfSymbol", &NSAddressOfSymbol_fn);
215
216   /* If any of these don't exist, that's an error.  */
217   if (! dyld_image_count_fn || ! dyld_get_image_name_fn
218       || ! dyld_get_image_header_fn || ! NSLookupSymbolInImage_fn
219       || ! NSAddressOfSymbol_fn)
220     return NULL;
221   
222   count = dyld_image_count_fn ();
223   for (i = 0; i < count; i++)
224     {
225       const char * path = dyld_get_image_name_fn (i);
226       const void * image;
227       const void * symbol;
228       
229       if (strcmp (path, "/usr/lib/libSystem.B.dylib") != 0)
230         continue;
231       image = dyld_get_image_header_fn (i);
232       if (! image)
233         return NULL;
234       /* '4' is NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR.  */
235       symbol = NSLookupSymbolInImage_fn (image, "_atexit", 4);
236       if (! symbol)
237         return NULL;
238       return NSAddressOfSymbol_fn (symbol);
239     }
240   return NULL;
241 }
242 #endif
243
244 /* Create (if necessary), find, lock, fill in, and return our globals.  
245    Return NULL on error, in which case the globals will not be locked.  
246    The caller should call keymgr_set_and_unlock.  */
247 static struct keymgr_atexit_list *
248 get_globals (void)
249 {
250   struct keymgr_atexit_list * r;
251   
252 #ifdef __ppc__
253   /* 10.3.9 doesn't have _keymgr_get_and_lock_processwide_ptr_2 so the
254      PPC side can't use it.  On 10.4 this just means the error gets
255      reported a little later when
256      _keymgr_set_and_unlock_processwide_ptr finds that the key was
257      never locked.  */
258   r = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
259 #else
260   void * rr;
261   if (_keymgr_get_and_lock_processwide_ptr_2 (KEYMGR_ATEXIT_LIST, &rr))
262     return NULL;
263   r = rr;
264 #endif
265   
266   if (r == NULL)
267     {
268       r = calloc (sizeof (struct keymgr_atexit_list), 1);
269       if (! r)
270         return NULL;
271     }
272
273   if (r->atexit_status == atexit_status_unknown)
274     {
275       void *handle;
276
277       handle = dlopen ("/usr/lib/libSystem.B.dylib", RTLD_NOLOAD);
278       if (!handle)
279         {
280 #ifdef __ppc__
281           r->atexit_status = atexit_status_missing;
282           r->atexit_f = find_atexit_10_3 ();
283           if (! r->atexit_f)
284             goto error;
285           if (r->atexit_f (our_atexit))
286             goto error;
287 #else
288           goto error;
289 #endif
290         }
291       else
292         {
293           int chk_result;
294
295           r->cxa_atexit_f = (cxa_atexit_p)dlsym (handle, "__cxa_atexit");
296           r->cxa_finalize_f = (cxa_finalize_p)dlsym (handle, "__cxa_finalize");
297           if (! r->cxa_atexit_f || ! r->cxa_finalize_f)
298             goto error;
299
300           chk_result = check_cxa_atexit (r->cxa_atexit_f, r->cxa_finalize_f);
301           if (chk_result == -1)
302             goto error;
303           else if (chk_result == 0)
304             r->atexit_status = atexit_status_broken;
305           else
306             {
307               r->atexit_f = (atexit_p)dlsym (handle, "atexit");
308               if (! r->atexit_f)
309                 goto error;
310               r->atexit_status = atexit_status_working;
311             }
312         }
313     }
314
315   return r;
316   
317  error:
318   _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, r);
319   return NULL;
320 }
321
322 /* Add TO_ADD to ATEXIT_LIST.  ATEXIT_LIST may be NULL but is
323    always the result of calling _keymgr_get_and_lock_processwide_ptr and
324    so KEYMGR_ATEXIT_LIST is known to be locked; this routine is responsible
325    for unlocking it.  */
326
327 static int
328 add_routine (struct keymgr_atexit_list * g,
329              const struct one_atexit_routine * to_add)
330 {
331   struct atexit_routine_list * s
332     = malloc (sizeof (struct atexit_routine_list));
333   int result;
334   
335   if (!s)
336     {
337       _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
338       return -1;
339     }
340   s->r = *to_add;
341   s->next = g->l;
342   g->l = s;
343   result = _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
344   return CHECK_KEYMGR_ERROR (result) == 0 ? 0 : -1;
345 }
346
347 /* This runs the routines in G->L up to STOP.  */
348 static struct keymgr_atexit_list *
349 run_routines (struct keymgr_atexit_list *g,
350               struct atexit_routine_list *stop)
351 {
352   for (;;)
353     {
354       struct atexit_routine_list * cur = g->l;
355       if (! cur || cur == stop)
356         break;
357       g->l = cur->next;
358       _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
359
360       switch (cur->r.has_arg) {
361       case 0: case 2: case 4:
362         cur->r.callback.ac ();
363         break;
364       case 1: case 3: case 5:
365         cur->r.callback.cac (cur->r.arg);
366         break;
367       default:
368         /* Don't understand, so don't call it.  */
369         break;
370       }
371       free (cur);
372
373       g = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
374       if (! g)
375         break;
376     }
377   return g;
378 }
379
380 /* Call the routine described by ROUTINE_PARAM and then call any
381    routines added to KEYMGR_ATEXIT_LIST while that routine was
382    running, all with in_cxa_finalize set.  */
383
384 static void
385 cxa_atexit_wrapper (void* routine_param)
386 {
387   struct one_atexit_routine * routine = routine_param;
388   struct keymgr_atexit_list *g;
389   struct atexit_routine_list * base = NULL;
390   char prev_running = 0;
391   
392   g = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
393   if (g)
394     {
395       prev_running = g->running_routines;
396       g->running_routines = 1;
397       base = g->l;
398       _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
399     }
400
401   if (routine->has_arg)
402     routine->callback.cac (routine->arg);
403   else
404     routine->callback.ac ();
405
406   if (g)
407     g = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
408   if (g)
409     g = run_routines (g, base);
410   if (g)
411     {
412       g->running_routines = prev_running;
413       _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
414     }
415 }
416
417 #ifdef __ppc__
418 /* This code is used while running on 10.3.9, when __cxa_atexit doesn't
419    exist in the system library.  10.3.9 only supported regular PowerPC,
420    so this code isn't necessary on x86 or ppc64.  */
421
422 /* This routine is called from the system atexit(); it runs everything
423    registered on the KEYMGR_ATEXIT_LIST.  */
424
425 static void
426 our_atexit (void)
427 {
428   struct keymgr_atexit_list *g;
429   char prev_running;
430
431   g = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
432   if (! g || g->version != 0 || g->atexit_status != atexit_status_missing)
433     return;
434   
435   prev_running = g->running_routines;
436   g->running_routines = 1;
437   g = run_routines (g, NULL);
438   if (! g)
439     return;
440   g->running_routines = prev_running;
441   _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
442 }
443 #endif
444
445 /* This is our wrapper around atexit and __cxa_atexit.  It will return
446    nonzero if an error occurs, and otherwise:
447    - if in_cxa_finalize is set, or running on 10.3.9, add R to
448      KEYMGR_ATEXIT_LIST; or
449    - call the system __cxa_atexit to add cxa_atexit_wrapper with an argument
450      that indicates how cxa_atexit_wrapper should call R.  */
451
452 static int
453 atexit_common (const struct one_atexit_routine *r, const void *dso)
454 {
455   struct keymgr_atexit_list *g = get_globals ();
456
457   if (! g)
458     return -1;
459   
460   if (g->running_routines || g->atexit_status == atexit_status_missing)
461     return add_routine (g, r);
462
463   if (g->atexit_status >= atexit_status_working)
464     {
465       int result;
466       if (r->has_arg)
467         {
468           cxa_atexit_p cxa_atexit = g->cxa_atexit_f;
469           result = _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST,
470                                                            g);
471           if (CHECK_KEYMGR_ERROR (result))
472             return -1;
473           return cxa_atexit (r->callback.cac, r->arg, dso);
474         }
475       else
476         {
477           atexit_p atexit_f = g->atexit_f;
478           result = _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST,
479                                                            g);
480           if (CHECK_KEYMGR_ERROR (result))
481             return -1;
482           return atexit_f (r->callback.ac);
483         }
484     }
485   else
486     {
487       cxa_atexit_p cxa_atexit = g->cxa_atexit_f;
488       struct one_atexit_routine *alloced;
489       int result;
490
491       result = _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, g);
492       if (CHECK_KEYMGR_ERROR (result))
493         return -1;
494
495       alloced = malloc (sizeof (struct one_atexit_routine));
496       if (! alloced)
497         return -1;
498       *alloced = *r;
499       return cxa_atexit (cxa_atexit_wrapper, alloced, dso);
500     }
501 }
502
503 /* These are the actual replacement routines; they just funnel into
504    atexit_common.  */
505
506 int __cxa_atexit (cxa_atexit_callback func, void* arg, 
507                   const void* dso) __attribute__((visibility("hidden")));
508
509 int
510 __cxa_atexit (cxa_atexit_callback func, void* arg, const void* dso)
511 {
512   struct one_atexit_routine r;
513   r.callback.cac = func;
514   r.has_arg = 1;
515   r.arg = arg;
516   return atexit_common (&r, dso);
517 }
518
519 int atexit (atexit_callback func) __attribute__((visibility("hidden")));
520
521 /* Use __dso_handle to allow even bundles that call atexit() to be unloaded
522    on 10.4.  */
523 extern void __dso_handle;
524
525 int
526 atexit (atexit_callback func)
527 {
528   struct one_atexit_routine r;
529   r.callback.ac = func;
530   r.has_arg = 0;
531   return atexit_common (&r, &__dso_handle);
532 }