OSDN Git Service

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