OSDN Git Service

2005-06-28 Andrew Pinski <pinskia@physics.uc.edu>
[pf3gnuchains/gcc-fork.git] / gcc / collect2.c
1 /* Collect static initialization info into data structures that can be
2    traversed by C++ initialization and finalization routines.
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5    Contributed by Chris Smith (csmith@convex.com).
6    Heavily modified by Michael Meissner (meissner@cygnus.com),
7    Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify it under
12 the terms of the GNU General Public License as published by the Free
13 Software Foundation; either version 2, or (at your option) any later
14 version.
15
16 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17 WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19 for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING.  If not, write to the Free
23 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
24 02110-1301, USA.  */
25
26
27 /* Build tables of static constructors and destructors and run ld.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include <signal.h>
34 #if ! defined( SIGCHLD ) && defined( SIGCLD )
35 #  define SIGCHLD SIGCLD
36 #endif
37
38 #ifndef LIBRARY_PATH_ENV
39 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
40 #endif
41
42 #define COLLECT
43
44 #include "collect2.h"
45 #include "demangle.h"
46 #include "obstack.h"
47 #include "intl.h"
48 #include "version.h"
49 \f
50 /* On certain systems, we have code that works by scanning the object file
51    directly.  But this code uses system-specific header files and library
52    functions, so turn it off in a cross-compiler.  Likewise, the names of
53    the utilities are not correct for a cross-compiler; we have to hope that
54    cross-versions are in the proper directories.  */
55
56 #ifdef CROSS_COMPILE
57 #undef OBJECT_FORMAT_COFF
58 #undef MD_EXEC_PREFIX
59 #undef REAL_LD_FILE_NAME
60 #undef REAL_NM_FILE_NAME
61 #undef REAL_STRIP_FILE_NAME
62 #endif
63
64 /* If we cannot use a special method, use the ordinary one:
65    run nm to find what symbols are present.
66    In a cross-compiler, this means you need a cross nm,
67    but that is not quite as unpleasant as special headers.  */
68
69 #if !defined (OBJECT_FORMAT_COFF)
70 #define OBJECT_FORMAT_NONE
71 #endif
72
73 #ifdef OBJECT_FORMAT_COFF
74
75 #include <a.out.h>
76 #include <ar.h>
77
78 #ifdef UMAX
79 #include <sgs.h>
80 #endif
81
82 /* Many versions of ldfcn.h define these.  */
83 #ifdef FREAD
84 #undef FREAD
85 #undef FWRITE
86 #endif
87
88 #include <ldfcn.h>
89
90 /* Some systems have an ISCOFF macro, but others do not.  In some cases
91    the macro may be wrong.  MY_ISCOFF is defined in tm.h files for machines
92    that either do not have an ISCOFF macro in /usr/include or for those
93    where it is wrong.  */
94
95 #ifndef MY_ISCOFF
96 #define MY_ISCOFF(X) ISCOFF (X)
97 #endif
98
99 #endif /* OBJECT_FORMAT_COFF */
100
101 #ifdef OBJECT_FORMAT_NONE
102
103 /* Default flags to pass to nm.  */
104 #ifndef NM_FLAGS
105 #define NM_FLAGS "-n"
106 #endif
107
108 #endif /* OBJECT_FORMAT_NONE */
109
110 /* Some systems use __main in a way incompatible with its use in gcc, in these
111    cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
112    give the same symbol without quotes for an alternative entry point.  */
113 #ifndef NAME__MAIN
114 #define NAME__MAIN "__main"
115 #endif
116
117 /* This must match tree.h.  */
118 #define DEFAULT_INIT_PRIORITY 65535
119
120 #ifndef COLLECT_SHARED_INIT_FUNC
121 #define COLLECT_SHARED_INIT_FUNC(STREAM, FUNC) \
122   fprintf ((STREAM), "void _GLOBAL__DI() {\n\t%s();\n}\n", (FUNC))
123 #endif
124 #ifndef COLLECT_SHARED_FINI_FUNC
125 #define COLLECT_SHARED_FINI_FUNC(STREAM, FUNC) \
126   fprintf ((STREAM), "void _GLOBAL__DD() {\n\t%s();\n}\n", (FUNC))
127 #endif
128
129 #ifdef LDD_SUFFIX
130 #define SCAN_LIBRARIES
131 #endif
132
133 #ifdef USE_COLLECT2
134 int do_collecting = 1;
135 #else
136 int do_collecting = 0;
137 #endif
138
139 /* Nonzero if we should suppress the automatic demangling of identifiers
140    in linker error messages.  Set from COLLECT_NO_DEMANGLE.  */
141 int no_demangle;
142 \f
143 /* Linked lists of constructor and destructor names.  */
144
145 struct id
146 {
147   struct id *next;
148   int sequence;
149   char name[1];
150 };
151
152 struct head
153 {
154   struct id *first;
155   struct id *last;
156   int number;
157 };
158
159 /* Enumeration giving which pass this is for scanning the program file.  */
160
161 enum pass {
162   PASS_FIRST,                           /* without constructors */
163   PASS_OBJ,                             /* individual objects */
164   PASS_LIB,                             /* looking for shared libraries */
165   PASS_SECOND                           /* with constructors linked in */
166 };
167
168 int vflag;                              /* true if -v */
169 static int rflag;                       /* true if -r */
170 static int strip_flag;                  /* true if -s */
171 static const char *demangle_flag;
172 #ifdef COLLECT_EXPORT_LIST
173 static int export_flag;                 /* true if -bE */
174 static int aix64_flag;                  /* true if -b64 */
175 static int aixrtl_flag;                 /* true if -brtl */
176 #endif
177
178 int debug;                              /* true if -debug */
179
180 static int shared_obj;                  /* true if -shared */
181
182 static const char *c_file;              /* <xxx>.c for constructor/destructor list.  */
183 static const char *o_file;              /* <xxx>.o for constructor/destructor list.  */
184 #ifdef COLLECT_EXPORT_LIST
185 static const char *export_file;         /* <xxx>.x for AIX export list.  */
186 #endif
187 const char *ldout;                      /* File for ld stdout.  */
188 const char *lderrout;                   /* File for ld stderr.  */
189 static const char *output_file;         /* Output file for ld.  */
190 static const char *nm_file_name;        /* pathname of nm */
191 #ifdef LDD_SUFFIX
192 static const char *ldd_file_name;       /* pathname of ldd (or equivalent) */
193 #endif
194 static const char *strip_file_name;             /* pathname of strip */
195 const char *c_file_name;                /* pathname of gcc */
196 static char *initname, *fininame;       /* names of init and fini funcs */
197
198 static struct head constructors;        /* list of constructors found */
199 static struct head destructors;         /* list of destructors found */
200 #ifdef COLLECT_EXPORT_LIST
201 static struct head exports;             /* list of exported symbols */
202 #endif
203 static struct head frame_tables;        /* list of frame unwind info tables */
204
205 struct obstack temporary_obstack;
206 char * temporary_firstobj;
207
208 /* Structure to hold all the directories in which to search for files to
209    execute.  */
210
211 struct prefix_list
212 {
213   const char *prefix;         /* String to prepend to the path.  */
214   struct prefix_list *next;   /* Next in linked list.  */
215 };
216
217 struct path_prefix
218 {
219   struct prefix_list *plist;  /* List of prefixes to try */
220   int max_len;                /* Max length of a prefix in PLIST */
221   const char *name;           /* Name of this list (used in config stuff) */
222 };
223
224 #ifdef COLLECT_EXPORT_LIST
225 /* Lists to keep libraries to be scanned for global constructors/destructors.  */
226 static struct head libs;                    /* list of libraries */
227 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
228 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
229 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
230                                           &libpath_lib_dirs, NULL};
231 #endif
232
233 static void handler (int);
234 static int is_ctor_dtor (const char *);
235 static char *find_a_file (struct path_prefix *, const char *);
236 static void add_prefix (struct path_prefix *, const char *);
237 static void prefix_from_env (const char *, struct path_prefix *);
238 static void prefix_from_string (const char *, struct path_prefix *);
239 static void do_wait (const char *, struct pex_obj *);
240 static void fork_execute (const char *, char **);
241 static void maybe_unlink (const char *);
242 static void add_to_list (struct head *, const char *);
243 static int extract_init_priority (const char *);
244 static void sort_ids (struct head *);
245 static void write_list (FILE *, const char *, struct id *);
246 #ifdef COLLECT_EXPORT_LIST
247 static void dump_list (FILE *, const char *, struct id *);
248 #endif
249 #if 0
250 static void dump_prefix_list (FILE *, const char *, struct prefix_list *);
251 #endif
252 static void write_list_with_asm (FILE *, const char *, struct id *);
253 static void write_c_file (FILE *, const char *);
254 static void write_c_file_stat (FILE *, const char *);
255 #ifndef LD_INIT_SWITCH
256 static void write_c_file_glob (FILE *, const char *);
257 #endif
258 static void scan_prog_file (const char *, enum pass);
259 #ifdef SCAN_LIBRARIES
260 static void scan_libraries (const char *);
261 #endif
262 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
263 static int is_in_args (const char *, const char **, const char **);
264 #endif
265 #ifdef COLLECT_EXPORT_LIST
266 #if 0
267 static int is_in_list (const char *, struct id *);
268 #endif
269 static void write_aix_file (FILE *, struct id *);
270 static char *resolve_lib_name (const char *);
271 #endif
272 static char *extract_string (const char **);
273 \f
274 #ifndef HAVE_DUP2
275 static int
276 dup2 (int oldfd, int newfd)
277 {
278   int fdtmp[256];
279   int fdx = 0;
280   int fd;
281
282   if (oldfd == newfd)
283     return oldfd;
284   close (newfd);
285   while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
286     fdtmp[fdx++] = fd;
287   while (fdx > 0)
288     close (fdtmp[--fdx]);
289
290   return fd;
291 }
292 #endif /* ! HAVE_DUP2 */
293 \f
294 /* Delete tempfiles and exit function.  */
295
296 void
297 collect_exit (int status)
298 {
299   if (c_file != 0 && c_file[0])
300     maybe_unlink (c_file);
301
302   if (o_file != 0 && o_file[0])
303     maybe_unlink (o_file);
304
305 #ifdef COLLECT_EXPORT_LIST
306   if (export_file != 0 && export_file[0])
307     maybe_unlink (export_file);
308 #endif
309
310   if (ldout != 0 && ldout[0])
311     {
312       dump_file (ldout, stdout);
313       maybe_unlink (ldout);
314     }
315
316   if (lderrout != 0 && lderrout[0])
317     {
318       dump_file (lderrout, stderr);
319       maybe_unlink (lderrout);
320     }
321
322   if (status != 0 && output_file != 0 && output_file[0])
323     maybe_unlink (output_file);
324
325   exit (status);
326 }
327
328 \f
329 /* Notify user of a non-error.  */
330 void
331 notice (const char *cmsgid, ...)
332 {
333   va_list ap;
334
335   va_start (ap, cmsgid);
336   vfprintf (stderr, _(cmsgid), ap);
337   va_end (ap);
338 }
339
340 /* Die when sys call fails.  */
341
342 void
343 fatal_perror (const char * cmsgid, ...)
344 {
345   int e = errno;
346   va_list ap;
347
348   va_start (ap, cmsgid);
349   fprintf (stderr, "collect2: ");
350   vfprintf (stderr, _(cmsgid), ap);
351   fprintf (stderr, ": %s\n", xstrerror (e));
352   va_end (ap);
353
354   collect_exit (FATAL_EXIT_CODE);
355 }
356
357 /* Just die.  */
358
359 void
360 fatal (const char * cmsgid, ...)
361 {
362   va_list ap;
363
364   va_start (ap, cmsgid);
365   fprintf (stderr, "collect2: ");
366   vfprintf (stderr, _(cmsgid), ap);
367   fprintf (stderr, "\n");
368   va_end (ap);
369
370   collect_exit (FATAL_EXIT_CODE);
371 }
372
373 /* Write error message.  */
374
375 void
376 error (const char * gmsgid, ...)
377 {
378   va_list ap;
379
380   va_start (ap, gmsgid);
381   fprintf (stderr, "collect2: ");
382   vfprintf (stderr, _(gmsgid), ap);
383   fprintf (stderr, "\n");
384   va_end(ap);
385 }
386
387 /* In case obstack is linked in, and abort is defined to fancy_abort,
388    provide a default entry.  */
389
390 void
391 fancy_abort (const char *file, int line, const char *func)
392 {
393   fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
394 }
395 \f
396 static void
397 handler (int signo)
398 {
399   if (c_file != 0 && c_file[0])
400     maybe_unlink (c_file);
401
402   if (o_file != 0 && o_file[0])
403     maybe_unlink (o_file);
404
405   if (ldout != 0 && ldout[0])
406     maybe_unlink (ldout);
407
408   if (lderrout != 0 && lderrout[0])
409     maybe_unlink (lderrout);
410
411 #ifdef COLLECT_EXPORT_LIST
412   if (export_file != 0 && export_file[0])
413     maybe_unlink (export_file);
414 #endif
415
416   signal (signo, SIG_DFL);
417   raise (signo);
418 }
419
420 \f
421 int
422 file_exists (const char *name)
423 {
424   return access (name, R_OK) == 0;
425 }
426
427 /* Parse a reasonable subset of shell quoting syntax.  */
428
429 static char *
430 extract_string (const char **pp)
431 {
432   const char *p = *pp;
433   int backquote = 0;
434   int inside = 0;
435
436   for (;;)
437     {
438       char c = *p;
439       if (c == '\0')
440         break;
441       ++p;
442       if (backquote)
443         obstack_1grow (&temporary_obstack, c);
444       else if (! inside && c == ' ')
445         break;
446       else if (! inside && c == '\\')
447         backquote = 1;
448       else if (c == '\'')
449         inside = !inside;
450       else
451         obstack_1grow (&temporary_obstack, c);
452     }
453
454   obstack_1grow (&temporary_obstack, '\0');
455   *pp = p;
456   return XOBFINISH (&temporary_obstack, char *);
457 }
458 \f
459 void
460 dump_file (const char *name, FILE *to)
461 {
462   FILE *stream = fopen (name, "r");
463
464   if (stream == 0)
465     return;
466   while (1)
467     {
468       int c;
469       while (c = getc (stream),
470              c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
471         obstack_1grow (&temporary_obstack, c);
472       if (obstack_object_size (&temporary_obstack) > 0)
473         {
474           const char *word, *p;
475           char *result;
476           obstack_1grow (&temporary_obstack, '\0');
477           word = XOBFINISH (&temporary_obstack, const char *);
478
479           if (*word == '.')
480             ++word, putc ('.', to);
481           p = word;
482           if (!strncmp (p, USER_LABEL_PREFIX, strlen (USER_LABEL_PREFIX)))
483             p += strlen (USER_LABEL_PREFIX);
484
485 #ifdef HAVE_LD_DEMANGLE
486           result = 0;
487 #else
488           if (no_demangle)
489             result = 0;
490           else
491             result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
492 #endif
493
494           if (result)
495             {
496               int diff;
497               fputs (result, to);
498
499               diff = strlen (word) - strlen (result);
500               while (diff > 0 && c == ' ')
501                 --diff, putc (' ', to);
502               while (diff < 0 && c == ' ')
503                 ++diff, c = getc (stream);
504
505               free (result);
506             }
507           else
508             fputs (word, to);
509
510           fflush (to);
511           obstack_free (&temporary_obstack, temporary_firstobj);
512         }
513       if (c == EOF)
514         break;
515       putc (c, to);
516     }
517   fclose (stream);
518 }
519 \f
520 /* Decide whether the given symbol is: a constructor (1), a destructor
521    (2), a routine in a shared object that calls all the constructors
522    (3) or destructors (4), a DWARF exception-handling table (5), or
523    nothing special (0).  */
524
525 static int
526 is_ctor_dtor (const char *s)
527 {
528   struct names { const char *const name; const int len; const int ret;
529     const int two_underscores; };
530
531   const struct names *p;
532   int ch;
533   const char *orig_s = s;
534
535   static const struct names special[] = {
536 #ifndef NO_DOLLAR_IN_LABEL
537     { "GLOBAL__I$", sizeof ("GLOBAL__I$")-1, 1, 0 },
538     { "GLOBAL__D$", sizeof ("GLOBAL__D$")-1, 2, 0 },
539 #else
540 #ifndef NO_DOT_IN_LABEL
541     { "GLOBAL__I.", sizeof ("GLOBAL__I.")-1, 1, 0 },
542     { "GLOBAL__D.", sizeof ("GLOBAL__D.")-1, 2, 0 },
543 #endif /* NO_DOT_IN_LABEL */
544 #endif /* NO_DOLLAR_IN_LABEL */
545     { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
546     { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
547     { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
548     { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
549     { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
550     { NULL, 0, 0, 0 }
551   };
552
553   while ((ch = *s) == '_')
554     ++s;
555
556   if (s == orig_s)
557     return 0;
558
559   for (p = &special[0]; p->len > 0; p++)
560     {
561       if (ch == p->name[0]
562           && (!p->two_underscores || ((s - orig_s) >= 2))
563           && strncmp(s, p->name, p->len) == 0)
564         {
565           return p->ret;
566         }
567     }
568   return 0;
569 }
570 \f
571 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
572    and one from the PATH variable.  */
573
574 static struct path_prefix cpath, path;
575
576 #ifdef CROSS_COMPILE
577 /* This is the name of the target machine.  We use it to form the name
578    of the files to execute.  */
579
580 static const char *const target_machine = TARGET_MACHINE;
581 #endif
582
583 /* Search for NAME using prefix list PPREFIX.  We only look for executable
584    files.
585
586    Return 0 if not found, otherwise return its name, allocated with malloc.  */
587
588 static char *
589 find_a_file (struct path_prefix *pprefix, const char *name)
590 {
591   char *temp;
592   struct prefix_list *pl;
593   int len = pprefix->max_len + strlen (name) + 1;
594
595   if (debug)
596     fprintf (stderr, "Looking for '%s'\n", name);
597
598 #ifdef HOST_EXECUTABLE_SUFFIX
599   len += strlen (HOST_EXECUTABLE_SUFFIX);
600 #endif
601
602   temp = xmalloc (len);
603
604   /* Determine the filename to execute (special case for absolute paths).  */
605
606   if (*name == '/'
607 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
608       || (*name && name[1] == ':')
609 #endif
610       )
611     {
612       if (access (name, X_OK) == 0)
613         {
614           strcpy (temp, name);
615
616           if (debug)
617             fprintf (stderr, "  - found: absolute path\n");
618
619           return temp;
620         }
621
622 #ifdef HOST_EXECUTABLE_SUFFIX
623         /* Some systems have a suffix for executable files.
624            So try appending that.  */
625       strcpy (temp, name);
626         strcat (temp, HOST_EXECUTABLE_SUFFIX);
627
628         if (access (temp, X_OK) == 0)
629           return temp;
630 #endif
631
632       if (debug)
633         fprintf (stderr, "  - failed to locate using absolute path\n");
634     }
635   else
636     for (pl = pprefix->plist; pl; pl = pl->next)
637       {
638         struct stat st;
639
640         strcpy (temp, pl->prefix);
641         strcat (temp, name);
642
643         if (stat (temp, &st) >= 0
644             && ! S_ISDIR (st.st_mode)
645             && access (temp, X_OK) == 0)
646           return temp;
647
648 #ifdef HOST_EXECUTABLE_SUFFIX
649         /* Some systems have a suffix for executable files.
650            So try appending that.  */
651         strcat (temp, HOST_EXECUTABLE_SUFFIX);
652
653         if (stat (temp, &st) >= 0
654             && ! S_ISDIR (st.st_mode)
655             && access (temp, X_OK) == 0)
656           return temp;
657 #endif
658       }
659
660   if (debug && pprefix->plist == NULL)
661     fprintf (stderr, "  - failed: no entries in prefix list\n");
662
663   free (temp);
664   return 0;
665 }
666
667 /* Add an entry for PREFIX to prefix list PPREFIX.  */
668
669 static void
670 add_prefix (struct path_prefix *pprefix, const char *prefix)
671 {
672   struct prefix_list *pl, **prev;
673   int len;
674
675   if (pprefix->plist)
676     {
677       for (pl = pprefix->plist; pl->next; pl = pl->next)
678         ;
679       prev = &pl->next;
680     }
681   else
682     prev = &pprefix->plist;
683
684   /* Keep track of the longest prefix.  */
685
686   len = strlen (prefix);
687   if (len > pprefix->max_len)
688     pprefix->max_len = len;
689
690   pl = xmalloc (sizeof (struct prefix_list));
691   pl->prefix = xstrdup (prefix);
692
693   if (*prev)
694     pl->next = *prev;
695   else
696     pl->next = (struct prefix_list *) 0;
697   *prev = pl;
698 }
699 \f
700 /* Take the value of the environment variable ENV, break it into a path, and
701    add of the entries to PPREFIX.  */
702
703 static void
704 prefix_from_env (const char *env, struct path_prefix *pprefix)
705 {
706   const char *p;
707   GET_ENVIRONMENT (p, env);
708
709   if (p)
710     prefix_from_string (p, pprefix);
711 }
712
713 static void
714 prefix_from_string (const char *p, struct path_prefix *pprefix)
715 {
716   const char *startp, *endp;
717   char *nstore = xmalloc (strlen (p) + 3);
718
719   if (debug)
720     fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
721
722   startp = endp = p;
723   while (1)
724     {
725       if (*endp == PATH_SEPARATOR || *endp == 0)
726         {
727           strncpy (nstore, startp, endp-startp);
728           if (endp == startp)
729             {
730               strcpy (nstore, "./");
731             }
732           else if (! IS_DIR_SEPARATOR (endp[-1]))
733             {
734               nstore[endp-startp] = DIR_SEPARATOR;
735               nstore[endp-startp+1] = 0;
736             }
737           else
738             nstore[endp-startp] = 0;
739
740           if (debug)
741             fprintf (stderr, "  - add prefix: %s\n", nstore);
742
743           add_prefix (pprefix, nstore);
744           if (*endp == 0)
745             break;
746           endp = startp = endp + 1;
747         }
748       else
749         endp++;
750     }
751 }
752 \f
753 /* Main program.  */
754
755 int
756 main (int argc, char **argv)
757 {
758   static const char *const ld_suffix    = "ld";
759   static const char *const real_ld_suffix = "real-ld";
760   static const char *const collect_ld_suffix = "collect-ld";
761   static const char *const nm_suffix    = "nm";
762   static const char *const gnm_suffix   = "gnm";
763 #ifdef LDD_SUFFIX
764   static const char *const ldd_suffix   = LDD_SUFFIX;
765 #endif
766   static const char *const strip_suffix = "strip";
767   static const char *const gstrip_suffix = "gstrip";
768
769 #ifdef CROSS_COMPILE
770   /* If we look for a program in the compiler directories, we just use
771      the short name, since these directories are already system-specific.
772      But it we look for a program in the system directories, we need to
773      qualify the program name with the target machine.  */
774
775   const char *const full_ld_suffix =
776     concat(target_machine, "-", ld_suffix, NULL);
777   const char *const full_nm_suffix =
778     concat (target_machine, "-", nm_suffix, NULL);
779   const char *const full_gnm_suffix =
780     concat (target_machine, "-", gnm_suffix, NULL);
781 #ifdef LDD_SUFFIX
782   const char *const full_ldd_suffix =
783     concat (target_machine, "-", ldd_suffix, NULL);
784 #endif
785   const char *const full_strip_suffix =
786     concat (target_machine, "-", strip_suffix, NULL);
787   const char *const full_gstrip_suffix =
788     concat (target_machine, "-", gstrip_suffix, NULL);
789 #else
790   const char *const full_ld_suffix      = ld_suffix;
791   const char *const full_nm_suffix      = nm_suffix;
792   const char *const full_gnm_suffix     = gnm_suffix;
793 #ifdef LDD_SUFFIX
794   const char *const full_ldd_suffix     = ldd_suffix;
795 #endif
796   const char *const full_strip_suffix   = strip_suffix;
797   const char *const full_gstrip_suffix  = gstrip_suffix;
798 #endif /* CROSS_COMPILE */
799
800   const char *arg;
801   FILE *outf;
802 #ifdef COLLECT_EXPORT_LIST
803   FILE *exportf;
804 #endif
805   const char *ld_file_name;
806   const char *p;
807   char **c_argv;
808   const char **c_ptr;
809   char **ld1_argv;
810   const char **ld1;
811   char **ld2_argv;
812   const char **ld2;
813   char **object_lst;
814   const char **object;
815   int first_file;
816   int num_c_args        = argc+9;
817
818   no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
819
820   /* Suppress demangling by the real linker, which may be broken.  */
821   putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
822
823 #if defined (COLLECT2_HOST_INITIALIZATION)
824   /* Perform system dependent initialization, if necessary.  */
825   COLLECT2_HOST_INITIALIZATION;
826 #endif
827
828 #ifdef SIGCHLD
829   /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
830      receive the signal.  A different setting is inheritable */
831   signal (SIGCHLD, SIG_DFL);
832 #endif
833
834   /* Unlock the stdio streams.  */
835   unlock_std_streams ();
836
837   gcc_init_libintl ();
838
839   /* Do not invoke xcalloc before this point, since locale needs to be
840      set first, in case a diagnostic is issued.  */
841
842   ld1 = (const char **)(ld1_argv = xcalloc(sizeof (char *), argc+4));
843   ld2 = (const char **)(ld2_argv = xcalloc(sizeof (char *), argc+11));
844   object = (const char **)(object_lst = xcalloc(sizeof (char *), argc));
845
846 #ifdef DEBUG
847   debug = 1;
848 #endif
849
850   /* Parse command line early for instances of -debug.  This allows
851      the debug flag to be set before functions like find_a_file()
852      are called.  */
853   {
854     int i;
855
856     for (i = 1; argv[i] != NULL; i ++)
857       {
858         if (! strcmp (argv[i], "-debug"))
859           debug = 1;
860       }
861     vflag = debug;
862   }
863
864 #ifndef DEFAULT_A_OUT_NAME
865   output_file = "a.out";
866 #else
867   output_file = DEFAULT_A_OUT_NAME;
868 #endif
869
870   obstack_begin (&temporary_obstack, 0);
871   temporary_firstobj = obstack_alloc (&temporary_obstack, 0);
872
873 #ifndef HAVE_LD_DEMANGLE
874   current_demangling_style = auto_demangling;
875 #endif
876   p = getenv ("COLLECT_GCC_OPTIONS");
877   while (p && *p)
878     {
879       const char *q = extract_string (&p);
880       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
881         num_c_args++;
882     }
883   obstack_free (&temporary_obstack, temporary_firstobj);
884
885   /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
886      -fno-exceptions -w */
887   num_c_args += 5;
888
889   c_ptr = (const char **) (c_argv = xcalloc (sizeof (char *), num_c_args));
890
891   if (argc < 2)
892     fatal ("no arguments");
893
894 #ifdef SIGQUIT
895   if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
896     signal (SIGQUIT, handler);
897 #endif
898   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
899     signal (SIGINT, handler);
900 #ifdef SIGALRM
901   if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
902     signal (SIGALRM, handler);
903 #endif
904 #ifdef SIGHUP
905   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
906     signal (SIGHUP, handler);
907 #endif
908   if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
909     signal (SIGSEGV, handler);
910 #ifdef SIGBUS
911   if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
912     signal (SIGBUS, handler);
913 #endif
914
915   /* Extract COMPILER_PATH and PATH into our prefix list.  */
916   prefix_from_env ("COMPILER_PATH", &cpath);
917   prefix_from_env ("PATH", &path);
918
919   /* Try to discover a valid linker/nm/strip to use.  */
920
921   /* Maybe we know the right file to use (if not cross).  */
922   ld_file_name = 0;
923 #ifdef DEFAULT_LINKER
924   if (access (DEFAULT_LINKER, X_OK) == 0)
925     ld_file_name = DEFAULT_LINKER;
926   if (ld_file_name == 0)
927 #endif
928 #ifdef REAL_LD_FILE_NAME
929   ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
930   if (ld_file_name == 0)
931 #endif
932   /* Search the (target-specific) compiler dirs for ld'.  */
933   ld_file_name = find_a_file (&cpath, real_ld_suffix);
934   /* Likewise for `collect-ld'.  */
935   if (ld_file_name == 0)
936     ld_file_name = find_a_file (&cpath, collect_ld_suffix);
937   /* Search the compiler directories for `ld'.  We have protection against
938      recursive calls in find_a_file.  */
939   if (ld_file_name == 0)
940     ld_file_name = find_a_file (&cpath, ld_suffix);
941   /* Search the ordinary system bin directories
942      for `ld' (if native linking) or `TARGET-ld' (if cross).  */
943   if (ld_file_name == 0)
944     ld_file_name = find_a_file (&path, full_ld_suffix);
945
946 #ifdef REAL_NM_FILE_NAME
947   nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
948   if (nm_file_name == 0)
949 #endif
950   nm_file_name = find_a_file (&cpath, gnm_suffix);
951   if (nm_file_name == 0)
952     nm_file_name = find_a_file (&path, full_gnm_suffix);
953   if (nm_file_name == 0)
954     nm_file_name = find_a_file (&cpath, nm_suffix);
955   if (nm_file_name == 0)
956     nm_file_name = find_a_file (&path, full_nm_suffix);
957
958 #ifdef LDD_SUFFIX
959   ldd_file_name = find_a_file (&cpath, ldd_suffix);
960   if (ldd_file_name == 0)
961     ldd_file_name = find_a_file (&path, full_ldd_suffix);
962 #endif
963
964 #ifdef REAL_STRIP_FILE_NAME
965   strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
966   if (strip_file_name == 0)
967 #endif
968   strip_file_name = find_a_file (&cpath, gstrip_suffix);
969   if (strip_file_name == 0)
970     strip_file_name = find_a_file (&path, full_gstrip_suffix);
971   if (strip_file_name == 0)
972     strip_file_name = find_a_file (&cpath, strip_suffix);
973   if (strip_file_name == 0)
974     strip_file_name = find_a_file (&path, full_strip_suffix);
975
976   /* Determine the full path name of the C compiler to use.  */
977   c_file_name = getenv ("COLLECT_GCC");
978   if (c_file_name == 0)
979     {
980 #ifdef CROSS_COMPILE
981       c_file_name = concat (target_machine, "-gcc", NULL);
982 #else
983       c_file_name = "gcc";
984 #endif
985     }
986
987   p = find_a_file (&cpath, c_file_name);
988
989   /* Here it should be safe to use the system search path since we should have
990      already qualified the name of the compiler when it is needed.  */
991   if (p == 0)
992     p = find_a_file (&path, c_file_name);
993
994   if (p)
995     c_file_name = p;
996
997   *ld1++ = *ld2++ = ld_file_name;
998
999   /* Make temp file names.  */
1000   c_file = make_temp_file (".c");
1001   o_file = make_temp_file (".o");
1002 #ifdef COLLECT_EXPORT_LIST
1003   export_file = make_temp_file (".x");
1004 #endif
1005   ldout = make_temp_file (".ld");
1006   lderrout = make_temp_file (".le");
1007   *c_ptr++ = c_file_name;
1008   *c_ptr++ = "-x";
1009   *c_ptr++ = "c";
1010   *c_ptr++ = "-c";
1011   *c_ptr++ = "-o";
1012   *c_ptr++ = o_file;
1013
1014 #ifdef COLLECT_EXPORT_LIST
1015   /* Generate a list of directories from LIBPATH.  */
1016   prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1017   /* Add to this list also two standard directories where
1018      AIX loader always searches for libraries.  */
1019   add_prefix (&libpath_lib_dirs, "/lib");
1020   add_prefix (&libpath_lib_dirs, "/usr/lib");
1021 #endif
1022
1023   /* Get any options that the upper GCC wants to pass to the sub-GCC.
1024
1025      AIX support needs to know if -shared has been specified before
1026      parsing commandline arguments.  */
1027
1028   p = getenv ("COLLECT_GCC_OPTIONS");
1029   while (p && *p)
1030     {
1031       const char *q = extract_string (&p);
1032       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1033         *c_ptr++ = xstrdup (q);
1034       if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1035         *c_ptr++ = xstrdup (q);
1036       if (strcmp (q, "-shared") == 0)
1037         shared_obj = 1;
1038       if (*q == '-' && q[1] == 'B')
1039         {
1040           *c_ptr++ = xstrdup (q);
1041           if (q[2] == 0)
1042             {
1043               q = extract_string (&p);
1044               *c_ptr++ = xstrdup (q);
1045             }
1046         }
1047     }
1048   obstack_free (&temporary_obstack, temporary_firstobj);
1049   *c_ptr++ = "-fno-profile-arcs";
1050   *c_ptr++ = "-fno-test-coverage";
1051   *c_ptr++ = "-fno-branch-probabilities";
1052   *c_ptr++ = "-fno-exceptions";
1053   *c_ptr++ = "-w";
1054
1055   /* !!! When GCC calls collect2,
1056      it does not know whether it is calling collect2 or ld.
1057      So collect2 cannot meaningfully understand any options
1058      except those ld understands.
1059      If you propose to make GCC pass some other option,
1060      just imagine what will happen if ld is really ld!!!  */
1061
1062   /* Parse arguments.  Remember output file spec, pass the rest to ld.  */
1063   /* After the first file, put in the c++ rt0.  */
1064
1065   first_file = 1;
1066 #ifdef HAVE_LD_DEMANGLE
1067   if (!demangle_flag && !no_demangle)
1068     demangle_flag = "--demangle";
1069   if (demangle_flag)
1070     *ld1++ = *ld2++ = demangle_flag;
1071 #endif
1072   while ((arg = *++argv) != (char *) 0)
1073     {
1074       *ld1++ = *ld2++ = arg;
1075
1076       if (arg[0] == '-')
1077         {
1078           switch (arg[1])
1079             {
1080 #ifdef COLLECT_EXPORT_LIST
1081             /* We want to disable automatic exports on AIX when user
1082                explicitly puts an export list in command line */
1083             case 'b':
1084               if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1085                 export_flag = 1;
1086               else if (arg[2] == '6' && arg[3] == '4')
1087                 aix64_flag = 1;
1088               else if (arg[2] == 'r' && arg[3] == 't' && arg[4] == 'l')
1089                 aixrtl_flag = 1;
1090               break;
1091 #endif
1092
1093             case 'd':
1094               if (!strcmp (arg, "-debug"))
1095                 {
1096                   /* Already parsed.  */
1097                   ld1--;
1098                   ld2--;
1099                 }
1100               if (!strcmp (arg, "-dynamic-linker") && argv[1])
1101                 {
1102                   ++argv;
1103                   *ld1++ = *ld2++ = *argv;
1104                 }
1105               break;
1106
1107             case 'l':
1108               if (first_file)
1109                 {
1110                   /* place o_file BEFORE this argument! */
1111                   first_file = 0;
1112                   ld2--;
1113                   *ld2++ = o_file;
1114                   *ld2++ = arg;
1115                 }
1116 #ifdef COLLECT_EXPORT_LIST
1117               {
1118                 /* Resolving full library name.  */
1119                 const char *s = resolve_lib_name (arg+2);
1120
1121                 /* Saving a full library name.  */
1122                 add_to_list (&libs, s);
1123               }
1124 #endif
1125               break;
1126
1127 #ifdef COLLECT_EXPORT_LIST
1128             /* Saving directories where to search for libraries.  */
1129             case 'L':
1130               add_prefix (&cmdline_lib_dirs, arg+2);
1131               break;
1132 #else
1133 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1134             case 'L':
1135               if (is_in_args (arg, (const char **) ld1_argv, ld1-1))
1136                 --ld1;
1137               break;
1138 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1139 #endif
1140
1141             case 'o':
1142               if (arg[2] == '\0')
1143                 output_file = *ld1++ = *ld2++ = *++argv;
1144               else if (1
1145 #ifdef SWITCHES_NEED_SPACES
1146                        && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1147 #endif
1148                        )
1149
1150                 output_file = &arg[2];
1151               break;
1152
1153             case 'r':
1154               if (arg[2] == '\0')
1155                 rflag = 1;
1156               break;
1157
1158             case 's':
1159               if (arg[2] == '\0' && do_collecting)
1160                 {
1161                   /* We must strip after the nm run, otherwise C++ linking
1162                      will not work.  Thus we strip in the second ld run, or
1163                      else with strip if there is no second ld run.  */
1164                   strip_flag = 1;
1165                   ld1--;
1166                 }
1167               break;
1168
1169             case 'v':
1170               if (arg[2] == '\0')
1171                 vflag = 1;
1172               break;
1173
1174             case '-':
1175               if (strcmp (arg, "--no-demangle") == 0)
1176                 {
1177                   demangle_flag = arg;
1178                   no_demangle = 1;
1179                   ld1--;
1180                   ld2--;
1181                 }
1182               else if (strncmp (arg, "--demangle", 10) == 0)
1183                 {
1184                   demangle_flag = arg;
1185                   no_demangle = 0;
1186 #ifndef HAVE_LD_DEMANGLE
1187                   if (arg[10] == '=')
1188                     {
1189                       enum demangling_styles style
1190                         = cplus_demangle_name_to_style (arg+11);
1191                       if (style == unknown_demangling)
1192                         error ("unknown demangling style '%s'", arg+11);
1193                       else
1194                         current_demangling_style = style;
1195                     }
1196 #endif
1197                   ld1--;
1198                   ld2--;
1199                 }
1200               break;
1201             }
1202         }
1203       else if ((p = strrchr (arg, '.')) != (char *) 0
1204                && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1205                    || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1206                    || strcmp (p, ".obj") == 0))
1207         {
1208           if (first_file)
1209             {
1210               first_file = 0;
1211               if (p[1] == 'o')
1212                 *ld2++ = o_file;
1213               else
1214                 {
1215                   /* place o_file BEFORE this argument! */
1216                   ld2--;
1217                   *ld2++ = o_file;
1218                   *ld2++ = arg;
1219                 }
1220             }
1221           if (p[1] == 'o' || p[1] == 'l')
1222             *object++ = arg;
1223 #ifdef COLLECT_EXPORT_LIST
1224           /* libraries can be specified directly, i.e. without -l flag.  */
1225           else
1226             {
1227               /* Saving a full library name.  */
1228               add_to_list (&libs, arg);
1229             }
1230 #endif
1231         }
1232     }
1233
1234 #ifdef COLLECT_EXPORT_LIST
1235   /* This is added only for debugging purposes.  */
1236   if (debug)
1237     {
1238       fprintf (stderr, "List of libraries:\n");
1239       dump_list (stderr, "\t", libs.first);
1240     }
1241
1242   /* The AIX linker will discard static constructors in object files if
1243      nothing else in the file is referenced, so look at them first.  */
1244   {
1245       const char **export_object_lst = (const char **)object_lst;
1246
1247       while (export_object_lst < object)
1248         scan_prog_file (*export_object_lst++, PASS_OBJ);
1249   }
1250   {
1251     struct id *list = libs.first;
1252
1253     for (; list; list = list->next)
1254       scan_prog_file (list->name, PASS_FIRST);
1255   }
1256
1257   if (exports.first)
1258     {
1259       char *buf = concat ("-bE:", export_file, NULL);
1260
1261       *ld1++ = buf;
1262       *ld2++ = buf;
1263
1264       exportf = fopen (export_file, "w");
1265       if (exportf == (FILE *) 0)
1266         fatal_perror ("fopen %s", export_file);
1267       write_aix_file (exportf, exports.first);
1268       if (fclose (exportf))
1269         fatal_perror ("fclose %s", export_file);
1270     }
1271 #endif
1272
1273   *c_ptr++ = c_file;
1274   *c_ptr = *ld1 = *object = (char *) 0;
1275
1276   if (vflag)
1277     {
1278       notice ("collect2 version %s", version_string);
1279 #ifdef TARGET_VERSION
1280       TARGET_VERSION;
1281 #endif
1282       fprintf (stderr, "\n");
1283     }
1284
1285   if (debug)
1286     {
1287       const char *ptr;
1288       fprintf (stderr, "ld_file_name        = %s\n",
1289                (ld_file_name ? ld_file_name : "not found"));
1290       fprintf (stderr, "c_file_name         = %s\n",
1291                (c_file_name ? c_file_name : "not found"));
1292       fprintf (stderr, "nm_file_name        = %s\n",
1293                (nm_file_name ? nm_file_name : "not found"));
1294 #ifdef LDD_SUFFIX
1295       fprintf (stderr, "ldd_file_name       = %s\n",
1296                (ldd_file_name ? ldd_file_name : "not found"));
1297 #endif
1298       fprintf (stderr, "strip_file_name     = %s\n",
1299                (strip_file_name ? strip_file_name : "not found"));
1300       fprintf (stderr, "c_file              = %s\n",
1301                (c_file ? c_file : "not found"));
1302       fprintf (stderr, "o_file              = %s\n",
1303                (o_file ? o_file : "not found"));
1304
1305       ptr = getenv ("COLLECT_GCC_OPTIONS");
1306       if (ptr)
1307         fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1308
1309       ptr = getenv ("COLLECT_GCC");
1310       if (ptr)
1311         fprintf (stderr, "COLLECT_GCC         = %s\n", ptr);
1312
1313       ptr = getenv ("COMPILER_PATH");
1314       if (ptr)
1315         fprintf (stderr, "COMPILER_PATH       = %s\n", ptr);
1316
1317       ptr = getenv (LIBRARY_PATH_ENV);
1318       if (ptr)
1319         fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1320
1321       fprintf (stderr, "\n");
1322     }
1323
1324   /* Load the program, searching all libraries and attempting to provide
1325      undefined symbols from repository information.  */
1326
1327   /* On AIX we do this later.  */
1328 #ifndef COLLECT_EXPORT_LIST
1329   do_tlink (ld1_argv, object_lst);
1330 #endif
1331
1332   /* If -r or they will be run via some other method, do not build the
1333      constructor or destructor list, just return now.  */
1334   if (rflag
1335 #ifndef COLLECT_EXPORT_LIST
1336       || ! do_collecting
1337 #endif
1338       )
1339     {
1340 #ifdef COLLECT_EXPORT_LIST
1341       /* Do the link we avoided above if we are exiting.  */
1342       do_tlink (ld1_argv, object_lst);
1343
1344       /* But make sure we delete the export file we may have created.  */
1345       if (export_file != 0 && export_file[0])
1346         maybe_unlink (export_file);
1347 #endif
1348       maybe_unlink (c_file);
1349       maybe_unlink (o_file);
1350       return 0;
1351     }
1352
1353   /* Examine the namelist with nm and search it for static constructors
1354      and destructors to call.
1355      Write the constructor and destructor tables to a .s file and reload.  */
1356
1357   /* On AIX we already scanned for global constructors/destructors.  */
1358 #ifndef COLLECT_EXPORT_LIST
1359   scan_prog_file (output_file, PASS_FIRST);
1360 #endif
1361
1362 #ifdef SCAN_LIBRARIES
1363   scan_libraries (output_file);
1364 #endif
1365
1366   if (debug)
1367     {
1368       notice ("%d constructor(s) found\n", constructors.number);
1369       notice ("%d destructor(s)  found\n", destructors.number);
1370       notice ("%d frame table(s) found\n", frame_tables.number);
1371     }
1372
1373   if (constructors.number == 0 && destructors.number == 0
1374       && frame_tables.number == 0
1375 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1376       /* If we will be running these functions ourselves, we want to emit
1377          stubs into the shared library so that we do not have to relink
1378          dependent programs when we add static objects.  */
1379       && ! shared_obj
1380 #endif
1381       )
1382     {
1383 #ifdef COLLECT_EXPORT_LIST
1384       /* Do tlink without additional code generation.  */
1385       do_tlink (ld1_argv, object_lst);
1386 #endif
1387       /* Strip now if it was requested on the command line.  */
1388       if (strip_flag)
1389         {
1390           char **real_strip_argv = xcalloc (sizeof (char *), 3);
1391           const char ** strip_argv = (const char **) real_strip_argv;
1392
1393           strip_argv[0] = strip_file_name;
1394           strip_argv[1] = output_file;
1395           strip_argv[2] = (char *) 0;
1396           fork_execute ("strip", real_strip_argv);
1397         }
1398
1399 #ifdef COLLECT_EXPORT_LIST
1400       maybe_unlink (export_file);
1401 #endif
1402       maybe_unlink (c_file);
1403       maybe_unlink (o_file);
1404       return 0;
1405     }
1406
1407   /* Sort ctor and dtor lists by priority.  */
1408   sort_ids (&constructors);
1409   sort_ids (&destructors);
1410
1411   maybe_unlink(output_file);
1412   outf = fopen (c_file, "w");
1413   if (outf == (FILE *) 0)
1414     fatal_perror ("fopen %s", c_file);
1415
1416   write_c_file (outf, c_file);
1417
1418   if (fclose (outf))
1419     fatal_perror ("fclose %s", c_file);
1420
1421   /* Tell the linker that we have initializer and finalizer functions.  */
1422 #ifdef LD_INIT_SWITCH
1423 #ifdef COLLECT_EXPORT_LIST
1424   *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1425 #else
1426   *ld2++ = LD_INIT_SWITCH;
1427   *ld2++ = initname;
1428   *ld2++ = LD_FINI_SWITCH;
1429   *ld2++ = fininame;
1430 #endif
1431 #endif
1432
1433 #ifdef COLLECT_EXPORT_LIST
1434   if (shared_obj)
1435     {
1436       /* If we did not add export flag to link arguments before, add it to
1437          second link phase now.  No new exports should have been added.  */
1438       if (! exports.first)
1439         *ld2++ = concat ("-bE:", export_file, NULL);
1440
1441 #ifndef LD_INIT_SWITCH
1442       add_to_list (&exports, initname);
1443       add_to_list (&exports, fininame);
1444       add_to_list (&exports, "_GLOBAL__DI");
1445       add_to_list (&exports, "_GLOBAL__DD");
1446 #endif
1447       exportf = fopen (export_file, "w");
1448       if (exportf == (FILE *) 0)
1449         fatal_perror ("fopen %s", export_file);
1450       write_aix_file (exportf, exports.first);
1451       if (fclose (exportf))
1452         fatal_perror ("fclose %s", export_file);
1453     }
1454 #endif
1455
1456   /* End of arguments to second link phase.  */
1457   *ld2 = (char*) 0;
1458
1459   if (debug)
1460     {
1461       fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1462                output_file, c_file);
1463       write_c_file (stderr, "stderr");
1464       fprintf (stderr, "========== end of c_file\n\n");
1465 #ifdef COLLECT_EXPORT_LIST
1466       fprintf (stderr, "\n========== export_file = %s\n", export_file);
1467       write_aix_file (stderr, exports.first);
1468       fprintf (stderr, "========== end of export_file\n\n");
1469 #endif
1470     }
1471
1472   /* Assemble the constructor and destructor tables.
1473      Link the tables in with the rest of the program.  */
1474
1475   fork_execute ("gcc",  c_argv);
1476 #ifdef COLLECT_EXPORT_LIST
1477   /* On AIX we must call tlink because of possible templates resolution.  */
1478   do_tlink (ld2_argv, object_lst);
1479 #else
1480   /* Otherwise, simply call ld because tlink is already done.  */
1481   fork_execute ("ld", ld2_argv);
1482
1483   /* Let scan_prog_file do any final mods (OSF/rose needs this for
1484      constructors/destructors in shared libraries.  */
1485   scan_prog_file (output_file, PASS_SECOND);
1486 #endif
1487
1488   maybe_unlink (c_file);
1489   maybe_unlink (o_file);
1490
1491 #ifdef COLLECT_EXPORT_LIST
1492   maybe_unlink (export_file);
1493 #endif
1494
1495   return 0;
1496 }
1497
1498 \f
1499 /* Wait for a process to finish, and exit if a nonzero status is found.  */
1500
1501 int
1502 collect_wait (const char *prog, struct pex_obj *pex)
1503 {
1504   int status;
1505
1506   if (!pex_get_status (pex, 1, &status))
1507     fatal_perror ("can't get program status");
1508   pex_free (pex);
1509
1510   if (status)
1511     {
1512       if (WIFSIGNALED (status))
1513         {
1514           int sig = WTERMSIG (status);
1515           error ("%s terminated with signal %d [%s]%s",
1516                  prog, sig, strsignal(sig),
1517                  WCOREDUMP(status) ? ", core dumped" : "");
1518           collect_exit (FATAL_EXIT_CODE);
1519         }
1520
1521       if (WIFEXITED (status))
1522         return WEXITSTATUS (status);
1523     }
1524   return 0;
1525 }
1526
1527 static void
1528 do_wait (const char *prog, struct pex_obj *pex)
1529 {
1530   int ret = collect_wait (prog, pex);
1531   if (ret != 0)
1532     {
1533       error ("%s returned %d exit status", prog, ret);
1534       collect_exit (ret);
1535     }
1536 }
1537
1538 \f
1539 /* Execute a program, and wait for the reply.  */
1540
1541 struct pex_obj *
1542 collect_execute (const char *prog, char **argv, const char *outname,
1543                  const char *errname)
1544 {
1545   struct pex_obj *pex;
1546   const char *errmsg;
1547   int err;
1548
1549   if (vflag || debug)
1550     {
1551       char **p_argv;
1552       const char *str;
1553
1554       if (argv[0])
1555         fprintf (stderr, "%s", argv[0]);
1556       else
1557         notice ("[cannot find %s]", prog);
1558
1559       for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1560         fprintf (stderr, " %s", str);
1561
1562       fprintf (stderr, "\n");
1563     }
1564
1565   fflush (stdout);
1566   fflush (stderr);
1567
1568   /* If we cannot find a program we need, complain error.  Do this here
1569      since we might not end up needing something that we could not find.  */
1570
1571   if (argv[0] == 0)
1572     fatal ("cannot find '%s'", prog);
1573
1574   pex = pex_init (0, "collect2", NULL);
1575   if (pex == NULL)
1576     fatal_perror ("pex_init failed");
1577
1578   errmsg = pex_run (pex, PEX_LAST | PEX_SEARCH, argv[0], argv, outname,
1579                     errname, &err);
1580   if (errmsg != NULL)
1581     {
1582       if (err != 0)
1583         {
1584           errno = err;
1585           fatal_perror (errmsg);
1586         }
1587       else
1588         fatal (errmsg);
1589     }
1590
1591   return pex;
1592 }
1593
1594 static void
1595 fork_execute (const char *prog, char **argv)
1596 {
1597   struct pex_obj *pex;
1598
1599   pex = collect_execute (prog, argv, NULL, NULL);
1600   do_wait (prog, pex);
1601 }
1602 \f
1603 /* Unlink a file unless we are debugging.  */
1604
1605 static void
1606 maybe_unlink (const char *file)
1607 {
1608   if (!debug)
1609     unlink_if_ordinary (file);
1610   else
1611     notice ("[Leaving %s]\n", file);
1612 }
1613
1614 \f
1615 static long sequence_number = 0;
1616
1617 /* Add a name to a linked list.  */
1618
1619 static void
1620 add_to_list (struct head *head_ptr, const char *name)
1621 {
1622   struct id *newid = xcalloc (sizeof (struct id) + strlen (name), 1);
1623   struct id *p;
1624   strcpy (newid->name, name);
1625
1626   if (head_ptr->first)
1627     head_ptr->last->next = newid;
1628   else
1629     head_ptr->first = newid;
1630
1631   /* Check for duplicate symbols.  */
1632   for (p = head_ptr->first;
1633        strcmp (name, p->name) != 0;
1634        p = p->next)
1635     ;
1636   if (p != newid)
1637     {
1638       head_ptr->last->next = 0;
1639       free (newid);
1640       return;
1641     }
1642
1643   newid->sequence = ++sequence_number;
1644   head_ptr->last = newid;
1645   head_ptr->number++;
1646 }
1647
1648 /* Grab the init priority number from an init function name that
1649    looks like "_GLOBAL_.I.12345.foo".  */
1650
1651 static int
1652 extract_init_priority (const char *name)
1653 {
1654   int pos = 0, pri;
1655
1656   while (name[pos] == '_')
1657     ++pos;
1658   pos += 10; /* strlen ("GLOBAL__X_") */
1659
1660   /* Extract init_p number from ctor/dtor name.  */
1661   pri = atoi (name + pos);
1662   return pri ? pri : DEFAULT_INIT_PRIORITY;
1663 }
1664
1665 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1666    ctors will be run from right to left, dtors from left to right.  */
1667
1668 static void
1669 sort_ids (struct head *head_ptr)
1670 {
1671   /* id holds the current element to insert.  id_next holds the next
1672      element to insert.  id_ptr iterates through the already sorted elements
1673      looking for the place to insert id.  */
1674   struct id *id, *id_next, **id_ptr;
1675
1676   id = head_ptr->first;
1677
1678   /* We don't have any sorted elements yet.  */
1679   head_ptr->first = NULL;
1680
1681   for (; id; id = id_next)
1682     {
1683       id_next = id->next;
1684       id->sequence = extract_init_priority (id->name);
1685
1686       for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1687         if (*id_ptr == NULL
1688             /* If the sequence numbers are the same, we put the id from the
1689                file later on the command line later in the list.  */
1690             || id->sequence > (*id_ptr)->sequence
1691             /* Hack: do lexical compare, too.
1692             || (id->sequence == (*id_ptr)->sequence
1693                 && strcmp (id->name, (*id_ptr)->name) > 0) */
1694             )
1695           {
1696             id->next = *id_ptr;
1697             *id_ptr = id;
1698             break;
1699           }
1700     }
1701
1702   /* Now set the sequence numbers properly so write_c_file works.  */
1703   for (id = head_ptr->first; id; id = id->next)
1704     id->sequence = ++sequence_number;
1705 }
1706
1707 /* Write: `prefix', the names on list LIST, `suffix'.  */
1708
1709 static void
1710 write_list (FILE *stream, const char *prefix, struct id *list)
1711 {
1712   while (list)
1713     {
1714       fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1715       list = list->next;
1716     }
1717 }
1718
1719 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1720 /* Given a STRING, return nonzero if it occurs in the list in range
1721    [ARGS_BEGIN,ARGS_END).  */
1722
1723 static int
1724 is_in_args (const char *string, const char **args_begin,
1725             const char **args_end)
1726 {
1727   const char **args_pointer;
1728   for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1729     if (strcmp (string, *args_pointer) == 0)
1730       return 1;
1731   return 0;
1732 }
1733 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1734
1735 #ifdef COLLECT_EXPORT_LIST
1736 /* This function is really used only on AIX, but may be useful.  */
1737 #if 0
1738 static int
1739 is_in_list (const char *prefix, struct id *list)
1740 {
1741   while (list)
1742     {
1743       if (!strcmp (prefix, list->name)) return 1;
1744       list = list->next;
1745     }
1746     return 0;
1747 }
1748 #endif
1749 #endif /* COLLECT_EXPORT_LIST */
1750
1751 /* Added for debugging purpose.  */
1752 #ifdef COLLECT_EXPORT_LIST
1753 static void
1754 dump_list (FILE *stream, const char *prefix, struct id *list)
1755 {
1756   while (list)
1757     {
1758       fprintf (stream, "%s%s,\n", prefix, list->name);
1759       list = list->next;
1760     }
1761 }
1762 #endif
1763
1764 #if 0
1765 static void
1766 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
1767 {
1768   while (list)
1769     {
1770       fprintf (stream, "%s%s,\n", prefix, list->prefix);
1771       list = list->next;
1772     }
1773 }
1774 #endif
1775
1776 static void
1777 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
1778 {
1779   while (list)
1780     {
1781       fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1782                prefix, list->sequence, list->name);
1783       list = list->next;
1784     }
1785 }
1786
1787 /* Write out the constructor and destructor tables statically (for a shared
1788    object), along with the functions to execute them.  */
1789
1790 static void
1791 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
1792 {
1793   const char *p, *q;
1794   char *prefix, *r;
1795   int frames = (frame_tables.number > 0);
1796
1797   /* Figure out name of output_file, stripping off .so version.  */
1798   p = strrchr (output_file, '/');
1799   if (p == 0)
1800     p = output_file;
1801   else
1802     p++;
1803   q = p;
1804   while (q)
1805     {
1806       q = strchr (q,'.');
1807       if (q == 0)
1808         {
1809           q = p + strlen (p);
1810           break;
1811         }
1812       else
1813         {
1814           if (strncmp (q, ".so", 3) == 0)
1815             {
1816               q += 3;
1817               break;
1818             }
1819           else
1820             q++;
1821         }
1822     }
1823   /* q points to null at end of the string (or . of the .so version) */
1824   prefix = xmalloc (q - p + 1);
1825   strncpy (prefix, p, q - p);
1826   prefix[q - p] = 0;
1827   for (r = prefix; *r; r++)
1828     if (!ISALNUM ((unsigned char)*r))
1829       *r = '_';
1830   if (debug)
1831     notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1832             output_file, prefix);
1833
1834   initname = concat ("_GLOBAL__FI_", prefix, NULL);
1835   fininame = concat ("_GLOBAL__FD_", prefix, NULL);
1836
1837   free (prefix);
1838
1839   /* Write the tables as C code.  */
1840
1841   fprintf (stream, "static int count;\n");
1842   fprintf (stream, "typedef void entry_pt();\n");
1843   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1844
1845   if (frames)
1846     {
1847       write_list_with_asm (stream, "extern void *", frame_tables.first);
1848
1849       fprintf (stream, "\tstatic void *frame_table[] = {\n");
1850       write_list (stream, "\t\t&", frame_tables.first);
1851       fprintf (stream, "\t0\n};\n");
1852
1853       /* This must match what's in frame.h.  */
1854       fprintf (stream, "struct object {\n");
1855       fprintf (stream, "  void *pc_begin;\n");
1856       fprintf (stream, "  void *pc_end;\n");
1857       fprintf (stream, "  void *fde_begin;\n");
1858       fprintf (stream, "  void *fde_array;\n");
1859       fprintf (stream, "  __SIZE_TYPE__ count;\n");
1860       fprintf (stream, "  struct object *next;\n");
1861       fprintf (stream, "};\n");
1862
1863       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1864       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1865
1866       fprintf (stream, "static void reg_frame () {\n");
1867       fprintf (stream, "\tstatic struct object ob;\n");
1868       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1869       fprintf (stream, "\t}\n");
1870
1871       fprintf (stream, "static void dereg_frame () {\n");
1872       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1873       fprintf (stream, "\t}\n");
1874     }
1875
1876   fprintf (stream, "void %s() {\n", initname);
1877   if (constructors.number > 0 || frames)
1878     {
1879       fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1880       write_list (stream, "\t\t", constructors.first);
1881       if (frames)
1882         fprintf (stream, "\treg_frame,\n");
1883       fprintf (stream, "\t};\n");
1884       fprintf (stream, "\tentry_pt **p;\n");
1885       fprintf (stream, "\tif (count++ != 0) return;\n");
1886       fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1887       fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1888     }
1889   else
1890     fprintf (stream, "\t++count;\n");
1891   fprintf (stream, "}\n");
1892   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1893   fprintf (stream, "void %s() {\n", fininame);
1894   if (destructors.number > 0 || frames)
1895     {
1896       fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1897       write_list (stream, "\t\t", destructors.first);
1898       if (frames)
1899         fprintf (stream, "\tdereg_frame,\n");
1900       fprintf (stream, "\t};\n");
1901       fprintf (stream, "\tentry_pt **p;\n");
1902       fprintf (stream, "\tif (--count != 0) return;\n");
1903       fprintf (stream, "\tp = dtors;\n");
1904       fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1905                destructors.number + frames);
1906     }
1907   fprintf (stream, "}\n");
1908
1909   if (shared_obj)
1910     {
1911       COLLECT_SHARED_INIT_FUNC(stream, initname);
1912       COLLECT_SHARED_FINI_FUNC(stream, fininame);
1913     }
1914 }
1915
1916 /* Write the constructor/destructor tables.  */
1917
1918 #ifndef LD_INIT_SWITCH
1919 static void
1920 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
1921 {
1922   /* Write the tables as C code.  */
1923
1924   int frames = (frame_tables.number > 0);
1925
1926   fprintf (stream, "typedef void entry_pt();\n\n");
1927
1928   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1929
1930   if (frames)
1931     {
1932       write_list_with_asm (stream, "extern void *", frame_tables.first);
1933
1934       fprintf (stream, "\tstatic void *frame_table[] = {\n");
1935       write_list (stream, "\t\t&", frame_tables.first);
1936       fprintf (stream, "\t0\n};\n");
1937
1938       /* This must match what's in frame.h.  */
1939       fprintf (stream, "struct object {\n");
1940       fprintf (stream, "  void *pc_begin;\n");
1941       fprintf (stream, "  void *pc_end;\n");
1942       fprintf (stream, "  void *fde_begin;\n");
1943       fprintf (stream, "  void *fde_array;\n");
1944       fprintf (stream, "  __SIZE_TYPE__ count;\n");
1945       fprintf (stream, "  struct object *next;\n");
1946       fprintf (stream, "};\n");
1947
1948       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1949       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1950
1951       fprintf (stream, "static void reg_frame () {\n");
1952       fprintf (stream, "\tstatic struct object ob;\n");
1953       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1954       fprintf (stream, "\t}\n");
1955
1956       fprintf (stream, "static void dereg_frame () {\n");
1957       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1958       fprintf (stream, "\t}\n");
1959     }
1960
1961   fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
1962   fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
1963   write_list (stream, "\t", constructors.first);
1964   if (frames)
1965     fprintf (stream, "\treg_frame,\n");
1966   fprintf (stream, "\t0\n};\n\n");
1967
1968   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1969
1970   fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
1971   fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
1972   write_list (stream, "\t", destructors.first);
1973   if (frames)
1974     fprintf (stream, "\tdereg_frame,\n");
1975   fprintf (stream, "\t0\n};\n\n");
1976
1977   fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
1978   fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
1979 }
1980 #endif /* ! LD_INIT_SWITCH */
1981
1982 static void
1983 write_c_file (FILE *stream, const char *name)
1984 {
1985   fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
1986 #ifndef LD_INIT_SWITCH
1987   if (! shared_obj)
1988     write_c_file_glob (stream, name);
1989   else
1990 #endif
1991     write_c_file_stat (stream, name);
1992   fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
1993 }
1994
1995 #ifdef COLLECT_EXPORT_LIST
1996 static void
1997 write_aix_file (FILE *stream, struct id *list)
1998 {
1999   for (; list; list = list->next)
2000     {
2001       fputs (list->name, stream);
2002       putc ('\n', stream);
2003     }
2004 }
2005 #endif
2006 \f
2007 #ifdef OBJECT_FORMAT_NONE
2008
2009 /* Generic version to scan the name list of the loaded program for
2010    the symbols g++ uses for static constructors and destructors.
2011
2012    The constructor table begins at __CTOR_LIST__ and contains a count
2013    of the number of pointers (or -1 if the constructors are built in a
2014    separate section by the linker), followed by the pointers to the
2015    constructor functions, terminated with a null pointer.  The
2016    destructor table has the same format, and begins at __DTOR_LIST__.  */
2017
2018 static void
2019 scan_prog_file (const char *prog_name, enum pass which_pass)
2020 {
2021   void (*int_handler) (int);
2022 #ifdef SIGQUIT
2023   void (*quit_handler) (int);
2024 #endif
2025   char *real_nm_argv[4];
2026   const char **nm_argv = (const char **) real_nm_argv;
2027   int argc = 0;
2028   struct pex_obj *pex;
2029   const char *errmsg;
2030   int err;
2031   char *p, buf[1024];
2032   FILE *inf;
2033
2034   if (which_pass == PASS_SECOND)
2035     return;
2036
2037   /* If we do not have an `nm', complain.  */
2038   if (nm_file_name == 0)
2039     fatal ("cannot find 'nm'");
2040
2041   nm_argv[argc++] = nm_file_name;
2042   if (NM_FLAGS[0] != '\0')
2043     nm_argv[argc++] = NM_FLAGS;
2044
2045   nm_argv[argc++] = prog_name;
2046   nm_argv[argc++] = (char *) 0;
2047
2048   /* Trace if needed.  */
2049   if (vflag)
2050     {
2051       const char **p_argv;
2052       const char *str;
2053
2054       for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2055         fprintf (stderr, " %s", str);
2056
2057       fprintf (stderr, "\n");
2058     }
2059
2060   fflush (stdout);
2061   fflush (stderr);
2062
2063   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2064   if (pex == NULL)
2065     fatal_perror ("pex_init failed");
2066
2067   errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, NULL, &err);
2068   if (errmsg != NULL)
2069     {
2070       if (err != 0)
2071         {
2072           errno = err;
2073           fatal_perror (errmsg);
2074         }
2075       else
2076         fatal (errmsg);
2077     }
2078
2079   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2080 #ifdef SIGQUIT
2081   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2082 #endif
2083
2084   inf = pex_read_output (pex, 0);
2085   if (inf == NULL)
2086     fatal_perror ("can't open nm output");
2087
2088   if (debug)
2089     fprintf (stderr, "\nnm output with constructors/destructors.\n");
2090
2091   /* Read each line of nm output.  */
2092   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2093     {
2094       int ch, ch2;
2095       char *name, *end;
2096
2097       /* If it contains a constructor or destructor name, add the name
2098          to the appropriate list.  */
2099
2100       for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2101         if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2102           break;
2103
2104       if (ch != '_')
2105         continue;
2106
2107       name = p;
2108       /* Find the end of the symbol name.
2109          Do not include `|', because Encore nm can tack that on the end.  */
2110       for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2111            end++)
2112         continue;
2113
2114
2115       *end = '\0';
2116       switch (is_ctor_dtor (name))
2117         {
2118         case 1:
2119           if (which_pass != PASS_LIB)
2120             add_to_list (&constructors, name);
2121           break;
2122
2123         case 2:
2124           if (which_pass != PASS_LIB)
2125             add_to_list (&destructors, name);
2126           break;
2127
2128         case 3:
2129           if (which_pass != PASS_LIB)
2130             fatal ("init function found in object %s", prog_name);
2131 #ifndef LD_INIT_SWITCH
2132           add_to_list (&constructors, name);
2133 #endif
2134           break;
2135
2136         case 4:
2137           if (which_pass != PASS_LIB)
2138             fatal ("fini function found in object %s", prog_name);
2139 #ifndef LD_FINI_SWITCH
2140           add_to_list (&destructors, name);
2141 #endif
2142           break;
2143
2144         case 5:
2145           if (which_pass != PASS_LIB)
2146             add_to_list (&frame_tables, name);
2147           break;
2148
2149         default:                /* not a constructor or destructor */
2150           continue;
2151         }
2152
2153       if (debug)
2154         fprintf (stderr, "\t%s\n", buf);
2155     }
2156
2157   if (debug)
2158     fprintf (stderr, "\n");
2159
2160   do_wait (nm_file_name, pex);
2161
2162   signal (SIGINT,  int_handler);
2163 #ifdef SIGQUIT
2164   signal (SIGQUIT, quit_handler);
2165 #endif
2166 }
2167
2168 #ifdef LDD_SUFFIX
2169
2170 /* Use the List Dynamic Dependencies program to find shared libraries that
2171    the output file depends upon and their initialization/finalization
2172    routines, if any.  */
2173
2174 static void
2175 scan_libraries (const char *prog_name)
2176 {
2177   static struct head libraries;         /* list of shared libraries found */
2178   struct id *list;
2179   void (*int_handler) (int);
2180 #ifdef SIGQUIT
2181   void (*quit_handler) (int);
2182 #endif
2183   char *real_ldd_argv[4];
2184   const char **ldd_argv = (const char **) real_ldd_argv;
2185   int argc = 0;
2186   struct pex_obj *pex;
2187   const char *errmsg;
2188   int err;
2189   char buf[1024];
2190   FILE *inf;
2191
2192   /* If we do not have an `ldd', complain.  */
2193   if (ldd_file_name == 0)
2194     {
2195       error ("cannot find 'ldd'");
2196       return;
2197     }
2198
2199   ldd_argv[argc++] = ldd_file_name;
2200   ldd_argv[argc++] = prog_name;
2201   ldd_argv[argc++] = (char *) 0;
2202
2203   /* Trace if needed.  */
2204   if (vflag)
2205     {
2206       const char **p_argv;
2207       const char *str;
2208
2209       for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2210         fprintf (stderr, " %s", str);
2211
2212       fprintf (stderr, "\n");
2213     }
2214
2215   fflush (stdout);
2216   fflush (stderr);
2217
2218   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2219   if (pex == NULL)
2220     fatal_perror ("pex_init failed");
2221
2222   errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2223   if (errmsg != NULL)
2224     {
2225       if (err != 0)
2226         {
2227           errno = err;
2228           fatal_perror (errmsg);
2229         }
2230       else
2231         fatal (errmsg);
2232     }
2233
2234   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2235 #ifdef SIGQUIT
2236   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2237 #endif
2238
2239   inf = pex_read_output (pex, 0);
2240   if (inf == NULL)
2241     fatal_perror ("can't open ldd output");
2242
2243   if (debug)
2244     notice ("\nldd output with constructors/destructors.\n");
2245
2246   /* Read each line of ldd output.  */
2247   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2248     {
2249       int ch2;
2250       char *name, *end, *p = buf;
2251
2252       /* Extract names of libraries and add to list.  */
2253       PARSE_LDD_OUTPUT (p);
2254       if (p == 0)
2255         continue;
2256
2257       name = p;
2258       if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2259         fatal ("dynamic dependency %s not found", buf);
2260
2261       /* Find the end of the symbol name.  */
2262       for (end = p;
2263            (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2264            end++)
2265         continue;
2266       *end = '\0';
2267
2268       if (access (name, R_OK) == 0)
2269         add_to_list (&libraries, name);
2270       else
2271         fatal ("unable to open dynamic dependency '%s'", buf);
2272
2273       if (debug)
2274         fprintf (stderr, "\t%s\n", buf);
2275     }
2276   if (debug)
2277     fprintf (stderr, "\n");
2278
2279   do_wait (ldd_file_name, pex);
2280
2281   signal (SIGINT,  int_handler);
2282 #ifdef SIGQUIT
2283   signal (SIGQUIT, quit_handler);
2284 #endif
2285
2286   /* Now iterate through the library list adding their symbols to
2287      the list.  */
2288   for (list = libraries.first; list; list = list->next)
2289     scan_prog_file (list->name, PASS_LIB);
2290 }
2291
2292 #endif /* LDD_SUFFIX */
2293
2294 #endif /* OBJECT_FORMAT_NONE */
2295
2296 \f
2297 /*
2298  * COFF specific stuff.
2299  */
2300
2301 #ifdef OBJECT_FORMAT_COFF
2302
2303 #if defined (EXTENDED_COFF)
2304
2305 #   define GCC_SYMBOLS(X)       (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2306 #   define GCC_SYMENT           SYMR
2307 #   define GCC_OK_SYMBOL(X)     ((X).st == stProc || (X).st == stGlobal)
2308 #   define GCC_SYMINC(X)        (1)
2309 #   define GCC_SYMZERO(X)       (SYMHEADER(X).isymMax)
2310 #   define GCC_CHECK_HDR(X)     (PSYMTAB(X) != 0)
2311
2312 #else
2313
2314 #   define GCC_SYMBOLS(X)       (HEADER(ldptr).f_nsyms)
2315 #   define GCC_SYMENT           SYMENT
2316 #   if defined (C_WEAKEXT)
2317 #     define GCC_OK_SYMBOL(X) \
2318        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2319         ((X).n_scnum > N_UNDEF) && \
2320         (aix64_flag \
2321          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2322              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2323 #     define GCC_UNDEF_SYMBOL(X) \
2324        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2325         ((X).n_scnum == N_UNDEF))
2326 #   else
2327 #     define GCC_OK_SYMBOL(X) \
2328        (((X).n_sclass == C_EXT) && \
2329         ((X).n_scnum > N_UNDEF) && \
2330         (aix64_flag \
2331          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2332              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2333 #     define GCC_UNDEF_SYMBOL(X) \
2334        (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2335 #   endif
2336 #   define GCC_SYMINC(X)        ((X).n_numaux+1)
2337 #   define GCC_SYMZERO(X)       0
2338
2339 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2340 #ifdef _AIX51
2341 #   define GCC_CHECK_HDR(X) \
2342      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2343       || (HEADER (X).f_magic == 0767 && aix64_flag))
2344 #else
2345 #   define GCC_CHECK_HDR(X) \
2346      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2347       || (HEADER (X).f_magic == 0757 && aix64_flag))
2348 #endif
2349
2350 #endif
2351
2352 #ifdef COLLECT_EXPORT_LIST
2353 /* Array of standard AIX libraries which should not
2354    be scanned for ctors/dtors.  */
2355 static const char *const aix_std_libs[] = {
2356   "/unix",
2357   "/lib/libc.a",
2358   "/lib/libm.a",
2359   "/lib/libc_r.a",
2360   "/lib/libm_r.a",
2361   "/usr/lib/libc.a",
2362   "/usr/lib/libm.a",
2363   "/usr/lib/libc_r.a",
2364   "/usr/lib/libm_r.a",
2365   "/usr/lib/threads/libc.a",
2366   "/usr/ccs/lib/libc.a",
2367   "/usr/ccs/lib/libm.a",
2368   "/usr/ccs/lib/libc_r.a",
2369   "/usr/ccs/lib/libm_r.a",
2370   NULL
2371 };
2372
2373 /* This function checks the filename and returns 1
2374    if this name matches the location of a standard AIX library.  */
2375 static int ignore_library (const char *);
2376 static int
2377 ignore_library (const char *name)
2378 {
2379   const char *const *p = &aix_std_libs[0];
2380   while (*p++ != NULL)
2381     if (! strcmp (name, *p)) return 1;
2382   return 0;
2383 }
2384 #endif /* COLLECT_EXPORT_LIST */
2385
2386 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2387 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2388 #endif
2389
2390 /* COFF version to scan the name list of the loaded program for
2391    the symbols g++ uses for static constructors and destructors.
2392
2393    The constructor table begins at __CTOR_LIST__ and contains a count
2394    of the number of pointers (or -1 if the constructors are built in a
2395    separate section by the linker), followed by the pointers to the
2396    constructor functions, terminated with a null pointer.  The
2397    destructor table has the same format, and begins at __DTOR_LIST__.  */
2398
2399 static void
2400 scan_prog_file (const char *prog_name, enum pass which_pass)
2401 {
2402   LDFILE *ldptr = NULL;
2403   int sym_index, sym_count;
2404   int is_shared = 0;
2405
2406   if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2407     return;
2408
2409 #ifdef COLLECT_EXPORT_LIST
2410   /* We do not need scanning for some standard C libraries.  */
2411   if (which_pass == PASS_FIRST && ignore_library (prog_name))
2412     return;
2413
2414   /* On AIX we have a loop, because there is not much difference
2415      between an object and an archive. This trick allows us to
2416      eliminate scan_libraries() function.  */
2417   do
2418     {
2419 #endif
2420       /* Some platforms (e.g. OSF4) declare ldopen as taking a
2421          non-const char * filename parameter, even though it will not
2422          modify that string.  So we must cast away const-ness here,
2423          which will cause -Wcast-qual to burp.  */
2424       if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2425         {
2426           if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2427             fatal ("%s: not a COFF file", prog_name);
2428
2429           if (GCC_CHECK_HDR (ldptr))
2430             {
2431               sym_count = GCC_SYMBOLS (ldptr);
2432               sym_index = GCC_SYMZERO (ldptr);
2433
2434 #ifdef COLLECT_EXPORT_LIST
2435               /* Is current archive member a shared object?  */
2436               is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2437 #endif
2438
2439               while (sym_index < sym_count)
2440                 {
2441                   GCC_SYMENT symbol;
2442
2443                   if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2444                     break;
2445                   sym_index += GCC_SYMINC (symbol);
2446
2447                   if (GCC_OK_SYMBOL (symbol))
2448                     {
2449                       char *name;
2450
2451                       if ((name = ldgetname (ldptr, &symbol)) == NULL)
2452                         continue;               /* Should never happen.  */
2453
2454 #ifdef XCOFF_DEBUGGING_INFO
2455                       /* All AIX function names have a duplicate entry
2456                          beginning with a dot.  */
2457                       if (*name == '.')
2458                         ++name;
2459 #endif
2460
2461                       switch (is_ctor_dtor (name))
2462                         {
2463                         case 1:
2464                           if (! is_shared)
2465                             add_to_list (&constructors, name);
2466 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2467                           if (which_pass == PASS_OBJ)
2468                             add_to_list (&exports, name);
2469 #endif
2470                           break;
2471
2472                         case 2:
2473                           if (! is_shared)
2474                             add_to_list (&destructors, name);
2475 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2476                           if (which_pass == PASS_OBJ)
2477                             add_to_list (&exports, name);
2478 #endif
2479                           break;
2480
2481 #ifdef COLLECT_EXPORT_LIST
2482                         case 3:
2483 #ifndef LD_INIT_SWITCH
2484                           if (is_shared)
2485                             add_to_list (&constructors, name);
2486 #endif
2487                           break;
2488
2489                         case 4:
2490 #ifndef LD_INIT_SWITCH
2491                           if (is_shared)
2492                             add_to_list (&destructors, name);
2493 #endif
2494                           break;
2495 #endif
2496
2497                         case 5:
2498                           if (! is_shared)
2499                             add_to_list (&frame_tables, name);
2500 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2501                           if (which_pass == PASS_OBJ)
2502                             add_to_list (&exports, name);
2503 #endif
2504                           break;
2505
2506                         default:        /* not a constructor or destructor */
2507 #ifdef COLLECT_EXPORT_LIST
2508                           /* Explicitly export all global symbols when
2509                              building a shared object on AIX, but do not
2510                              re-export symbols from another shared object
2511                              and do not export symbols if the user
2512                              provides an explicit export list.  */
2513                           if (shared_obj && !is_shared
2514                               && which_pass == PASS_OBJ && !export_flag)
2515                             add_to_list (&exports, name);
2516 #endif
2517                           continue;
2518                         }
2519
2520                       if (debug)
2521 #if !defined(EXTENDED_COFF)
2522                         fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2523                                  symbol.n_scnum, symbol.n_sclass,
2524                                  (symbol.n_type ? "0" : ""), symbol.n_type,
2525                                  name);
2526 #else
2527                         fprintf (stderr,
2528                                  "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2529                                  symbol.iss, (long) symbol.value, symbol.index, name);
2530 #endif
2531                     }
2532                 }
2533             }
2534 #ifdef COLLECT_EXPORT_LIST
2535           else
2536             {
2537               /* If archive contains both 32-bit and 64-bit objects,
2538                  we want to skip objects in other mode so mismatch normal.  */
2539               if (debug)
2540                 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2541                          prog_name, HEADER (ldptr).f_magic, aix64_flag);
2542             }
2543 #endif
2544         }
2545       else
2546         {
2547           fatal ("%s: cannot open as COFF file", prog_name);
2548         }
2549 #ifdef COLLECT_EXPORT_LIST
2550       /* On AIX loop continues while there are more members in archive.  */
2551     }
2552   while (ldclose (ldptr) == FAILURE);
2553 #else
2554   /* Otherwise we simply close ldptr.  */
2555   (void) ldclose(ldptr);
2556 #endif
2557 }
2558 #endif /* OBJECT_FORMAT_COFF */
2559
2560 #ifdef COLLECT_EXPORT_LIST
2561 /* Given a library name without "lib" prefix, this function
2562    returns a full library name including a path.  */
2563 static char *
2564 resolve_lib_name (const char *name)
2565 {
2566   char *lib_buf;
2567   int i, j, l = 0;
2568   /* Library extensions for AIX dynamic linking.  */
2569   const char * const libexts[2] = {"a", "so"};
2570
2571   for (i = 0; libpaths[i]; i++)
2572     if (libpaths[i]->max_len > l)
2573       l = libpaths[i]->max_len;
2574
2575   lib_buf = xmalloc (l + strlen(name) + 10);
2576
2577   for (i = 0; libpaths[i]; i++)
2578     {
2579       struct prefix_list *list = libpaths[i]->plist;
2580       for (; list; list = list->next)
2581         {
2582           /* The following lines are needed because path_prefix list
2583              may contain directories both with trailing '/' and
2584              without it.  */
2585           const char *p = "";
2586           if (list->prefix[strlen(list->prefix)-1] != '/')
2587             p = "/";
2588           for (j = 0; j < 2; j++)
2589             {
2590               sprintf (lib_buf, "%s%slib%s.%s",
2591                        list->prefix, p, name,
2592                        libexts[(j + aixrtl_flag) % 2]);
2593               if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2594               if (file_exists (lib_buf))
2595                 {
2596                   if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2597                   return (lib_buf);
2598                 }
2599             }
2600         }
2601     }
2602   if (debug)
2603     fprintf (stderr, "not found\n");
2604   else
2605     fatal ("library lib%s not found", name);
2606   return (NULL);
2607 }
2608 #endif /* COLLECT_EXPORT_LIST */