OSDN Git Service

2010-07-24 Tobias Burnus <burnus@net-b.de>
[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, 2008, 2009, 2010
5    Free Software Foundation, Inc.
6    Contributed by Chris Smith (csmith@convex.com).
7    Heavily modified by Michael Meissner (meissner@cygnus.com),
8    Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
9
10 This file is part of GCC.
11
12 GCC is free software; you can redistribute it and/or modify it under
13 the terms of the GNU General Public License as published by the Free
14 Software Foundation; either version 3, or (at your option) any later
15 version.
16
17 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
18 WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING3.  If not see
24 <http://www.gnu.org/licenses/>.  */
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 /* TARGET_64BIT may be defined to use driver specific functionality. */
39 #undef TARGET_64BIT
40 #define TARGET_64BIT TARGET_64BIT_DEFAULT
41
42 #ifndef LIBRARY_PATH_ENV
43 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
44 #endif
45
46 #define COLLECT
47
48 #include "collect2.h"
49 #include "collect2-aix.h"
50 #include "demangle.h"
51 #include "obstack.h"
52 #include "intl.h"
53 #include "version.h"
54 \f
55 /* On certain systems, we have code that works by scanning the object file
56    directly.  But this code uses system-specific header files and library
57    functions, so turn it off in a cross-compiler.  Likewise, the names of
58    the utilities are not correct for a cross-compiler; we have to hope that
59    cross-versions are in the proper directories.  */
60
61 #ifdef CROSS_DIRECTORY_STRUCTURE
62 #ifndef CROSS_AIX_SUPPORT
63 #undef OBJECT_FORMAT_COFF
64 #endif
65 #undef MD_EXEC_PREFIX
66 #undef REAL_LD_FILE_NAME
67 #undef REAL_NM_FILE_NAME
68 #undef REAL_STRIP_FILE_NAME
69 #endif
70
71 /* If we cannot use a special method, use the ordinary one:
72    run nm to find what symbols are present.
73    In a cross-compiler, this means you need a cross nm,
74    but that is not quite as unpleasant as special headers.  */
75
76 #if !defined (OBJECT_FORMAT_COFF)
77 #define OBJECT_FORMAT_NONE
78 #endif
79
80 #ifdef OBJECT_FORMAT_COFF
81
82 #ifndef CROSS_DIRECTORY_STRUCTURE
83 #include <a.out.h>
84 #include <ar.h>
85
86 #ifdef UMAX
87 #include <sgs.h>
88 #endif
89
90 /* Many versions of ldfcn.h define these.  */
91 #ifdef FREAD
92 #undef FREAD
93 #undef FWRITE
94 #endif
95
96 #include <ldfcn.h>
97 #endif
98
99 /* Some systems have an ISCOFF macro, but others do not.  In some cases
100    the macro may be wrong.  MY_ISCOFF is defined in tm.h files for machines
101    that either do not have an ISCOFF macro in /usr/include or for those
102    where it is wrong.  */
103
104 #ifndef MY_ISCOFF
105 #define MY_ISCOFF(X) ISCOFF (X)
106 #endif
107
108 #endif /* OBJECT_FORMAT_COFF */
109
110 #ifdef OBJECT_FORMAT_NONE
111
112 /* Default flags to pass to nm.  */
113 #ifndef NM_FLAGS
114 #define NM_FLAGS "-n"
115 #endif
116
117 #endif /* OBJECT_FORMAT_NONE */
118
119 /* Some systems use __main in a way incompatible with its use in gcc, in these
120    cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
121    give the same symbol without quotes for an alternative entry point.  */
122 #ifndef NAME__MAIN
123 #define NAME__MAIN "__main"
124 #endif
125
126 /* This must match tree.h.  */
127 #define DEFAULT_INIT_PRIORITY 65535
128
129 #ifndef COLLECT_SHARED_INIT_FUNC
130 #define COLLECT_SHARED_INIT_FUNC(STREAM, FUNC) \
131   fprintf ((STREAM), "void _GLOBAL__DI() {\n\t%s();\n}\n", (FUNC))
132 #endif
133 #ifndef COLLECT_SHARED_FINI_FUNC
134 #define COLLECT_SHARED_FINI_FUNC(STREAM, FUNC) \
135   fprintf ((STREAM), "void _GLOBAL__DD() {\n\t%s();\n}\n", (FUNC))
136 #endif
137
138 #ifdef LDD_SUFFIX
139 #define SCAN_LIBRARIES
140 #endif
141
142 #ifndef SHLIB_SUFFIX
143 #define SHLIB_SUFFIX ".so"
144 #endif
145
146 #ifdef USE_COLLECT2
147 int do_collecting = 1;
148 #else
149 int do_collecting = 0;
150 #endif
151
152 /* Cook up an always defined indication of whether we proceed the
153    "EXPORT_LIST" way.  */
154
155 #ifdef COLLECT_EXPORT_LIST
156 #define DO_COLLECT_EXPORT_LIST 1
157 #else
158 #define DO_COLLECT_EXPORT_LIST 0
159 #endif
160
161 /* Nonzero if we should suppress the automatic demangling of identifiers
162    in linker error messages.  Set from COLLECT_NO_DEMANGLE.  */
163 int no_demangle;
164 \f
165 /* Linked lists of constructor and destructor names.  */
166
167 struct id
168 {
169   struct id *next;
170   int sequence;
171   char name[1];
172 };
173
174 struct head
175 {
176   struct id *first;
177   struct id *last;
178   int number;
179 };
180
181 bool vflag;                             /* true if -v or --version */ 
182 static int rflag;                       /* true if -r */
183 static int strip_flag;                  /* true if -s */
184 static const char *demangle_flag;
185 #ifdef COLLECT_EXPORT_LIST
186 static int export_flag;                 /* true if -bE */
187 static int aix64_flag;                  /* true if -b64 */
188 static int aixrtl_flag;                 /* true if -brtl */
189 #endif
190
191 enum lto_mode_d {
192   LTO_MODE_NONE,                        /* Not doing LTO.  */
193   LTO_MODE_LTO,                         /* Normal LTO.  */
194   LTO_MODE_WHOPR                        /* WHOPR.  */
195 };
196
197 /* Current LTO mode.  */
198 static enum lto_mode_d lto_mode = LTO_MODE_NONE;
199
200 bool debug;                             /* true if -debug */
201 bool helpflag;                  /* true if --help */
202
203 static int shared_obj;                  /* true if -shared */
204
205 static const char *c_file;              /* <xxx>.c for constructor/destructor list.  */
206 static const char *o_file;              /* <xxx>.o for constructor/destructor list.  */
207 #ifdef COLLECT_EXPORT_LIST
208 static const char *export_file;         /* <xxx>.x for AIX export list.  */
209 #endif
210 static char **lto_o_files;              /* Output files for LTO.  */
211 const char *ldout;                      /* File for ld stdout.  */
212 const char *lderrout;                   /* File for ld stderr.  */
213 static const char *output_file;         /* Output file for ld.  */
214 static const char *nm_file_name;        /* pathname of nm */
215 #ifdef LDD_SUFFIX
216 static const char *ldd_file_name;       /* pathname of ldd (or equivalent) */
217 #endif
218 static const char *strip_file_name;             /* pathname of strip */
219 const char *c_file_name;                /* pathname of gcc */
220 static char *initname, *fininame;       /* names of init and fini funcs */
221
222 static struct head constructors;        /* list of constructors found */
223 static struct head destructors;         /* list of destructors found */
224 #ifdef COLLECT_EXPORT_LIST
225 static struct head exports;             /* list of exported symbols */
226 #endif
227 static struct head frame_tables;        /* list of frame unwind info tables */
228
229 static bool at_file_supplied;           /* Whether to use @file arguments */
230 static char *response_file;             /* Name of any current response file */
231
232 struct obstack temporary_obstack;
233 char * temporary_firstobj;
234
235 /* A string that must be prepended to a target OS path in order to find
236    it on the host system.  */
237 #ifdef TARGET_SYSTEM_ROOT
238 static const char *target_system_root = TARGET_SYSTEM_ROOT;
239 #else
240 static const char *target_system_root = "";
241 #endif
242
243 /* Structure to hold all the directories in which to search for files to
244    execute.  */
245
246 struct prefix_list
247 {
248   const char *prefix;         /* String to prepend to the path.  */
249   struct prefix_list *next;   /* Next in linked list.  */
250 };
251
252 struct path_prefix
253 {
254   struct prefix_list *plist;  /* List of prefixes to try */
255   int max_len;                /* Max length of a prefix in PLIST */
256   const char *name;           /* Name of this list (used in config stuff) */
257 };
258
259 #ifdef COLLECT_EXPORT_LIST
260 /* Lists to keep libraries to be scanned for global constructors/destructors.  */
261 static struct head libs;                    /* list of libraries */
262 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
263 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
264 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
265                                           &libpath_lib_dirs, NULL};
266 #endif
267
268 /* List of names of object files containing LTO information.
269    These are a subset of the object file names appearing on the
270    command line, and must be identical, in the sense of pointer
271    equality, with the names passed to maybe_run_lto_and_relink().  */
272
273 struct lto_object
274 {
275   const char *name;             /* Name of object file.  */
276   struct lto_object *next;      /* Next in linked list.  */
277 };
278
279 struct lto_object_list
280 {
281   struct lto_object *first;     /* First list element.  */
282   struct lto_object *last;      /* Last list element.  */
283 };
284
285 static struct lto_object_list lto_objects;
286
287 /* Special kinds of symbols that a name may denote.  */
288
289 typedef enum {
290   SYM_REGULAR = 0,  /* nothing special  */
291
292   SYM_CTOR = 1,  /* constructor */
293   SYM_DTOR = 2,  /* destructor  */
294   SYM_INIT = 3,  /* shared object routine that calls all the ctors  */
295   SYM_FINI = 4,  /* shared object routine that calls all the dtors  */
296   SYM_DWEH = 5   /* DWARF exception handling table  */
297 } symkind;
298
299 static symkind is_ctor_dtor (const char *);
300
301 static void handler (int);
302 static char *find_a_file (struct path_prefix *, const char *);
303 static void add_prefix (struct path_prefix *, const char *);
304 static void prefix_from_env (const char *, struct path_prefix *);
305 static void prefix_from_string (const char *, struct path_prefix *);
306 static void do_wait (const char *, struct pex_obj *);
307 static void fork_execute (const char *, char **);
308 static void maybe_unlink (const char *);
309 static void maybe_unlink_list (char **);
310 static void add_to_list (struct head *, const char *);
311 static int extract_init_priority (const char *);
312 static void sort_ids (struct head *);
313 static void write_list (FILE *, const char *, struct id *);
314 #ifdef COLLECT_EXPORT_LIST
315 static void dump_list (FILE *, const char *, struct id *);
316 #endif
317 #if 0
318 static void dump_prefix_list (FILE *, const char *, struct prefix_list *);
319 #endif
320 static void write_list_with_asm (FILE *, const char *, struct id *);
321 static void write_c_file (FILE *, const char *);
322 static void write_c_file_stat (FILE *, const char *);
323 #ifndef LD_INIT_SWITCH
324 static void write_c_file_glob (FILE *, const char *);
325 #endif
326 #ifdef SCAN_LIBRARIES
327 static void scan_libraries (const char *);
328 #endif
329 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
330 static int is_in_args (const char *, const char **, const char **);
331 #endif
332 #ifdef COLLECT_EXPORT_LIST
333 #if 0
334 static int is_in_list (const char *, struct id *);
335 #endif
336 static void write_aix_file (FILE *, struct id *);
337 static char *resolve_lib_name (const char *);
338 #endif
339 static char *extract_string (const char **);
340
341 /* Enumerations describing which pass this is for scanning the
342    program file ...  */
343
344 typedef enum {
345   PASS_FIRST,                           /* without constructors */
346   PASS_OBJ,                             /* individual objects */
347   PASS_LIB,                             /* looking for shared libraries */
348   PASS_SECOND,                          /* with constructors linked in */
349   PASS_LTOINFO                          /* looking for objects with LTO info */
350 } scanpass;
351
352 /* ... and which kinds of symbols are to be considered.  */
353
354 enum scanfilter_masks {
355   SCAN_NOTHING = 0,
356
357   SCAN_CTOR = 1 << SYM_CTOR,
358   SCAN_DTOR = 1 << SYM_DTOR,
359   SCAN_INIT = 1 << SYM_INIT,
360   SCAN_FINI = 1 << SYM_FINI,
361   SCAN_DWEH = 1 << SYM_DWEH,
362   SCAN_ALL  = ~0
363 };
364
365 /* This type is used for parameters and variables which hold
366    combinations of the flags in enum scanfilter_masks.  */
367 typedef int scanfilter;
368
369 /* Scan the name list of the loaded program for the symbols g++ uses for
370    static constructors and destructors.
371
372    The SCANPASS argument tells which collect processing pass this is for and
373    the SCANFILTER argument tells which kinds of symbols to consider in this
374    pass.  Symbols of a special kind not in the filter mask are considered as
375    regular ones.
376
377    The constructor table begins at __CTOR_LIST__ and contains a count of the
378    number of pointers (or -1 if the constructors are built in a separate
379    section by the linker), followed by the pointers to the constructor
380    functions, terminated with a null pointer.  The destructor table has the
381    same format, and begins at __DTOR_LIST__.  */
382
383 static void scan_prog_file (const char *, scanpass, scanfilter);
384
385 \f
386 /* Delete tempfiles and exit function.  */
387
388 void
389 collect_exit (int status)
390 {
391   if (c_file != 0 && c_file[0])
392     maybe_unlink (c_file);
393
394   if (o_file != 0 && o_file[0])
395     maybe_unlink (o_file);
396
397 #ifdef COLLECT_EXPORT_LIST
398   if (export_file != 0 && export_file[0])
399     maybe_unlink (export_file);
400 #endif
401
402   if (lto_o_files)
403     maybe_unlink_list (lto_o_files);
404
405   if (ldout != 0 && ldout[0])
406     {
407       dump_file (ldout, stdout);
408       maybe_unlink (ldout);
409     }
410
411   if (lderrout != 0 && lderrout[0])
412     {
413       dump_file (lderrout, stderr);
414       maybe_unlink (lderrout);
415     }
416
417   if (status != 0 && output_file != 0 && output_file[0])
418     maybe_unlink (output_file);
419
420   if (response_file)
421     maybe_unlink (response_file);
422
423   exit (status);
424 }
425
426 \f
427 /* Notify user of a non-error.  */
428 void
429 notice (const char *cmsgid, ...)
430 {
431   va_list ap;
432
433   va_start (ap, cmsgid);
434   vfprintf (stderr, _(cmsgid), ap);
435   va_end (ap);
436 }
437
438 /* Notify user of a non-error, without translating the format string.  */
439 void
440 notice_translated (const char *cmsgid, ...)
441 {
442   va_list ap;
443
444   va_start (ap, cmsgid);
445   vfprintf (stderr, cmsgid, ap);
446   va_end (ap);
447 }
448
449 /* Die when sys call fails.  */
450
451 void
452 fatal_perror (const char * cmsgid, ...)
453 {
454   int e = errno;
455   va_list ap;
456
457   va_start (ap, cmsgid);
458   fprintf (stderr, "collect2: ");
459   vfprintf (stderr, _(cmsgid), ap);
460   fprintf (stderr, ": %s\n", xstrerror (e));
461   va_end (ap);
462
463   collect_exit (FATAL_EXIT_CODE);
464 }
465
466 /* Just die.  */
467
468 void
469 fatal (const char * cmsgid, ...)
470 {
471   va_list ap;
472
473   va_start (ap, cmsgid);
474   fprintf (stderr, "collect2: ");
475   vfprintf (stderr, _(cmsgid), ap);
476   fprintf (stderr, "\n");
477   va_end (ap);
478
479   collect_exit (FATAL_EXIT_CODE);
480 }
481
482 /* Write error message.  */
483
484 void
485 error (const char * gmsgid, ...)
486 {
487   va_list ap;
488
489   va_start (ap, gmsgid);
490   fprintf (stderr, "collect2: ");
491   vfprintf (stderr, _(gmsgid), ap);
492   fprintf (stderr, "\n");
493   va_end(ap);
494 }
495
496 /* In case obstack is linked in, and abort is defined to fancy_abort,
497    provide a default entry.  */
498
499 void
500 fancy_abort (const char *file, int line, const char *func)
501 {
502   fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
503 }
504 \f
505 static void
506 handler (int signo)
507 {
508   if (c_file != 0 && c_file[0])
509     maybe_unlink (c_file);
510
511   if (o_file != 0 && o_file[0])
512     maybe_unlink (o_file);
513
514   if (ldout != 0 && ldout[0])
515     maybe_unlink (ldout);
516
517   if (lderrout != 0 && lderrout[0])
518     maybe_unlink (lderrout);
519
520 #ifdef COLLECT_EXPORT_LIST
521   if (export_file != 0 && export_file[0])
522     maybe_unlink (export_file);
523 #endif
524
525   if (lto_o_files)
526     maybe_unlink_list (lto_o_files);
527
528   if (response_file)
529     maybe_unlink (response_file);
530
531   signal (signo, SIG_DFL);
532   raise (signo);
533 }
534
535 \f
536 int
537 file_exists (const char *name)
538 {
539   return access (name, R_OK) == 0;
540 }
541
542 /* Parse a reasonable subset of shell quoting syntax.  */
543
544 static char *
545 extract_string (const char **pp)
546 {
547   const char *p = *pp;
548   int backquote = 0;
549   int inside = 0;
550
551   for (;;)
552     {
553       char c = *p;
554       if (c == '\0')
555         break;
556       ++p;
557       if (backquote)
558         obstack_1grow (&temporary_obstack, c);
559       else if (! inside && c == ' ')
560         break;
561       else if (! inside && c == '\\')
562         backquote = 1;
563       else if (c == '\'')
564         inside = !inside;
565       else
566         obstack_1grow (&temporary_obstack, c);
567     }
568
569   obstack_1grow (&temporary_obstack, '\0');
570   *pp = p;
571   return XOBFINISH (&temporary_obstack, char *);
572 }
573 \f
574 void
575 dump_file (const char *name, FILE *to)
576 {
577   FILE *stream = fopen (name, "r");
578
579   if (stream == 0)
580     return;
581   while (1)
582     {
583       int c;
584       while (c = getc (stream),
585              c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
586         obstack_1grow (&temporary_obstack, c);
587       if (obstack_object_size (&temporary_obstack) > 0)
588         {
589           const char *word, *p;
590           char *result;
591           obstack_1grow (&temporary_obstack, '\0');
592           word = XOBFINISH (&temporary_obstack, const char *);
593
594           if (*word == '.')
595             ++word, putc ('.', to);
596           p = word;
597           if (!strncmp (p, USER_LABEL_PREFIX, strlen (USER_LABEL_PREFIX)))
598             p += strlen (USER_LABEL_PREFIX);
599
600 #ifdef HAVE_LD_DEMANGLE
601           result = 0;
602 #else
603           if (no_demangle)
604             result = 0;
605           else
606             result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
607 #endif
608
609           if (result)
610             {
611               int diff;
612               fputs (result, to);
613
614               diff = strlen (word) - strlen (result);
615               while (diff > 0 && c == ' ')
616                 --diff, putc (' ', to);
617               if (diff < 0 && c == ' ')
618                 {
619                   while (diff < 0 && c == ' ')
620                     ++diff, c = getc (stream);
621                   if (!ISSPACE (c))
622                     {
623                       /* Make sure we output at least one space, or
624                          the demangled symbol name will run into
625                          whatever text follows.  */
626                       putc (' ', to);
627                     }
628                 }
629
630               free (result);
631             }
632           else
633             fputs (word, to);
634
635           fflush (to);
636           obstack_free (&temporary_obstack, temporary_firstobj);
637         }
638       if (c == EOF)
639         break;
640       putc (c, to);
641     }
642   fclose (stream);
643 }
644 \f
645 /* Return the kind of symbol denoted by name S.  */
646
647 static symkind
648 is_ctor_dtor (const char *s)
649 {
650   struct names { const char *const name; const int len; symkind ret;
651     const int two_underscores; };
652
653   const struct names *p;
654   int ch;
655   const char *orig_s = s;
656
657   static const struct names special[] = {
658 #ifndef NO_DOLLAR_IN_LABEL
659     { "GLOBAL__I$", sizeof ("GLOBAL__I$")-1, SYM_CTOR, 0 },
660     { "GLOBAL__D$", sizeof ("GLOBAL__D$")-1, SYM_DTOR, 0 },
661 #else
662 #ifndef NO_DOT_IN_LABEL
663     { "GLOBAL__I.", sizeof ("GLOBAL__I.")-1, SYM_CTOR, 0 },
664     { "GLOBAL__D.", sizeof ("GLOBAL__D.")-1, SYM_DTOR, 0 },
665 #endif /* NO_DOT_IN_LABEL */
666 #endif /* NO_DOLLAR_IN_LABEL */
667     { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, SYM_CTOR, 0 },
668     { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, SYM_DTOR, 0 },
669     { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, SYM_DWEH, 0 },
670     { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, SYM_INIT, 0 },
671     { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, SYM_FINI, 0 },
672     { NULL, 0, SYM_REGULAR, 0 }
673   };
674
675   while ((ch = *s) == '_')
676     ++s;
677
678   if (s == orig_s)
679     return SYM_REGULAR;
680
681   for (p = &special[0]; p->len > 0; p++)
682     {
683       if (ch == p->name[0]
684           && (!p->two_underscores || ((s - orig_s) >= 2))
685           && strncmp(s, p->name, p->len) == 0)
686         {
687           return p->ret;
688         }
689     }
690   return SYM_REGULAR;
691 }
692 \f
693 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
694    and one from the PATH variable.  */
695
696 static struct path_prefix cpath, path;
697
698 #ifdef CROSS_DIRECTORY_STRUCTURE
699 /* This is the name of the target machine.  We use it to form the name
700    of the files to execute.  */
701
702 static const char *const target_machine = TARGET_MACHINE;
703 #endif
704
705 /* Search for NAME using prefix list PPREFIX.  We only look for executable
706    files.
707
708    Return 0 if not found, otherwise return its name, allocated with malloc.  */
709
710 static char *
711 find_a_file (struct path_prefix *pprefix, const char *name)
712 {
713   char *temp;
714   struct prefix_list *pl;
715   int len = pprefix->max_len + strlen (name) + 1;
716
717   if (debug)
718     fprintf (stderr, "Looking for '%s'\n", name);
719
720 #ifdef HOST_EXECUTABLE_SUFFIX
721   len += strlen (HOST_EXECUTABLE_SUFFIX);
722 #endif
723
724   temp = XNEWVEC (char, len);
725
726   /* Determine the filename to execute (special case for absolute paths).  */
727
728   if (IS_ABSOLUTE_PATH (name))
729     {
730       if (access (name, X_OK) == 0)
731         {
732           strcpy (temp, name);
733
734           if (debug)
735             fprintf (stderr, "  - found: absolute path\n");
736
737           return temp;
738         }
739
740 #ifdef HOST_EXECUTABLE_SUFFIX
741         /* Some systems have a suffix for executable files.
742            So try appending that.  */
743       strcpy (temp, name);
744         strcat (temp, HOST_EXECUTABLE_SUFFIX);
745
746         if (access (temp, X_OK) == 0)
747           return temp;
748 #endif
749
750       if (debug)
751         fprintf (stderr, "  - failed to locate using absolute path\n");
752     }
753   else
754     for (pl = pprefix->plist; pl; pl = pl->next)
755       {
756         struct stat st;
757
758         strcpy (temp, pl->prefix);
759         strcat (temp, name);
760
761         if (stat (temp, &st) >= 0
762             && ! S_ISDIR (st.st_mode)
763             && access (temp, X_OK) == 0)
764           return temp;
765
766 #ifdef HOST_EXECUTABLE_SUFFIX
767         /* Some systems have a suffix for executable files.
768            So try appending that.  */
769         strcat (temp, HOST_EXECUTABLE_SUFFIX);
770
771         if (stat (temp, &st) >= 0
772             && ! S_ISDIR (st.st_mode)
773             && access (temp, X_OK) == 0)
774           return temp;
775 #endif
776       }
777
778   if (debug && pprefix->plist == NULL)
779     fprintf (stderr, "  - failed: no entries in prefix list\n");
780
781   free (temp);
782   return 0;
783 }
784
785 /* Add an entry for PREFIX to prefix list PPREFIX.  */
786
787 static void
788 add_prefix (struct path_prefix *pprefix, const char *prefix)
789 {
790   struct prefix_list *pl, **prev;
791   int len;
792
793   if (pprefix->plist)
794     {
795       for (pl = pprefix->plist; pl->next; pl = pl->next)
796         ;
797       prev = &pl->next;
798     }
799   else
800     prev = &pprefix->plist;
801
802   /* Keep track of the longest prefix.  */
803
804   len = strlen (prefix);
805   if (len > pprefix->max_len)
806     pprefix->max_len = len;
807
808   pl = XNEW (struct prefix_list);
809   pl->prefix = xstrdup (prefix);
810
811   if (*prev)
812     pl->next = *prev;
813   else
814     pl->next = (struct prefix_list *) 0;
815   *prev = pl;
816 }
817 \f
818 /* Take the value of the environment variable ENV, break it into a path, and
819    add of the entries to PPREFIX.  */
820
821 static void
822 prefix_from_env (const char *env, struct path_prefix *pprefix)
823 {
824   const char *p;
825   GET_ENVIRONMENT (p, env);
826
827   if (p)
828     prefix_from_string (p, pprefix);
829 }
830
831 static void
832 prefix_from_string (const char *p, struct path_prefix *pprefix)
833 {
834   const char *startp, *endp;
835   char *nstore = XNEWVEC (char, strlen (p) + 3);
836
837   if (debug)
838     fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
839
840   startp = endp = p;
841   while (1)
842     {
843       if (*endp == PATH_SEPARATOR || *endp == 0)
844         {
845           strncpy (nstore, startp, endp-startp);
846           if (endp == startp)
847             {
848               strcpy (nstore, "./");
849             }
850           else if (! IS_DIR_SEPARATOR (endp[-1]))
851             {
852               nstore[endp-startp] = DIR_SEPARATOR;
853               nstore[endp-startp+1] = 0;
854             }
855           else
856             nstore[endp-startp] = 0;
857
858           if (debug)
859             fprintf (stderr, "  - add prefix: %s\n", nstore);
860
861           add_prefix (pprefix, nstore);
862           if (*endp == 0)
863             break;
864           endp = startp = endp + 1;
865         }
866       else
867         endp++;
868     }
869   free (nstore);
870 }
871
872 #ifdef OBJECT_FORMAT_NONE
873
874 /* Add an entry for the object file NAME to object file list LIST.
875    New entries are added at the end of the list. The original pointer
876    value of NAME is preserved, i.e., no string copy is performed.  */
877
878 static void
879 add_lto_object (struct lto_object_list *list, const char *name)
880 {
881   struct lto_object *n = XNEW (struct lto_object);
882   n->name = name;
883   n->next = NULL;
884
885   if (list->last)
886     list->last->next = n;
887   else
888     list->first = n;
889
890   list->last = n;
891 }
892 #endif /* OBJECT_FORMAT_NONE */
893
894
895 /* Perform a link-time recompilation and relink if any of the object
896    files contain LTO info.  The linker command line LTO_LD_ARGV
897    represents the linker command that would produce a final executable
898    without the use of LTO. OBJECT_LST is a vector of object file names
899    appearing in LTO_LD_ARGV that are to be considerd for link-time
900    recompilation, where OBJECT is a pointer to the last valid element.
901    (This awkward convention avoids an impedance mismatch with the
902    usage of similarly-named variables in main().)  The elements of
903    OBJECT_LST must be identical, i.e., pointer equal, to the
904    corresponding arguments in LTO_LD_ARGV.
905
906    Upon entry, at least one linker run has been performed without the
907    use of any LTO info that might be present.  Any recompilations
908    necessary for template instantiations have been performed, and
909    initializer/finalizer tables have been created if needed and
910    included in the linker command line LTO_LD_ARGV. If any of the
911    object files contain LTO info, we run the LTO back end on all such
912    files, and perform the final link with the LTO back end output
913    substituted for the LTO-optimized files.  In some cases, a final
914    link with all link-time generated code has already been performed,
915    so there is no need to relink if no LTO info is found.  In other
916    cases, our caller has not produced the final executable, and is
917    relying on us to perform the required link whether LTO info is
918    present or not.  In that case, the FORCE argument should be true.
919    Note that the linker command line argument LTO_LD_ARGV passed into
920    this function may be modified in place.  */
921
922 static void
923 maybe_run_lto_and_relink (char **lto_ld_argv, char **object_lst,
924                           const char **object, bool force)
925 {
926   const char **object_file = CONST_CAST2 (const char **, char **, object_lst);
927
928   int num_lto_c_args = 1;    /* Allow space for the terminating NULL.  */
929
930   while (object_file < object)
931   {
932     /* If file contains LTO info, add it to the list of LTO objects.  */
933     scan_prog_file (*object_file++, PASS_LTOINFO, SCAN_ALL);
934
935     /* Increment the argument count by the number of object file arguments
936        we will add.  An upper bound suffices, so just count all of the
937        object files regardless of whether they contain LTO info.  */
938     num_lto_c_args++;
939   }
940
941   if (lto_objects.first)
942     {
943       char **lto_c_argv;
944       const char **lto_c_ptr;
945       const char **p, **q, **r;
946       const char **lto_o_ptr;
947       struct lto_object *list;
948       char *lto_wrapper = getenv ("COLLECT_LTO_WRAPPER");
949       struct pex_obj *pex;
950       const char *prog = "lto-wrapper";
951
952       if (!lto_wrapper)
953         fatal ("COLLECT_LTO_WRAPPER must be set.");
954
955       num_lto_c_args++;
956
957       /* There is at least one object file containing LTO info,
958          so we need to run the LTO back end and relink.  */
959
960       lto_c_argv = (char **) xcalloc (sizeof (char *), num_lto_c_args);
961       lto_c_ptr = CONST_CAST2 (const char **, char **, lto_c_argv);
962
963       *lto_c_ptr++ = lto_wrapper;
964
965       /* Add LTO objects to the wrapper command line.  */
966       for (list = lto_objects.first; list; list = list->next)
967         *lto_c_ptr++ = list->name;
968
969       *lto_c_ptr = NULL;
970
971       /* Run the LTO back end.  */
972       pex = collect_execute (prog, lto_c_argv, NULL, NULL, PEX_SEARCH);
973       {
974         int c;
975         FILE *stream;
976         size_t i, num_files;
977         char *start, *end;
978
979         stream = pex_read_output (pex, 0);
980         gcc_assert (stream);
981
982         num_files = 0;
983         while ((c = getc (stream)) != EOF)
984           {
985             obstack_1grow (&temporary_obstack, c);
986             if (c == '\n')
987               ++num_files;
988           }
989
990         lto_o_files = XNEWVEC (char *, num_files + 1);
991         lto_o_files[num_files] = NULL;
992         start = XOBFINISH (&temporary_obstack, char *);
993         for (i = 0; i < num_files; ++i)
994           {
995             end = start;
996             while (*end != '\n')
997               ++end;
998             *end = '\0';
999
1000             lto_o_files[i] = xstrdup (start);
1001
1002             start = end + 1;
1003           }
1004
1005         obstack_free (&temporary_obstack, temporary_firstobj);
1006       }
1007       do_wait (prog, pex);
1008       pex = NULL;
1009
1010       /* After running the LTO back end, we will relink, substituting
1011          the LTO output for the object files that we submitted to the
1012          LTO. Here, we modify the linker command line for the relink.  */
1013       p = CONST_CAST2 (const char **, char **, lto_ld_argv);
1014       lto_o_ptr = CONST_CAST2 (const char **, char **, lto_o_files);
1015
1016       while (*p != NULL)
1017         {
1018           for (list = lto_objects.first; list; list = list->next)
1019             {
1020               if (*p == list->name) /* Note test for pointer equality!  */
1021                 {
1022                   /* Excise argument from linker command line.  */
1023                   if (*lto_o_ptr)
1024                     {
1025                       /* Replace first argument with LTO output file.  */
1026                       *p++ = *lto_o_ptr++;
1027                     }
1028                   else
1029                     {
1030                       /* Move following arguments one position earlier,
1031                          overwriting the current argument.  */
1032                       q = p;
1033                       r = p + 1;
1034                       while (*r != NULL)
1035                         *q++ = *r++;
1036                       *q = NULL;
1037                     }
1038
1039                   /* No need to continue searching the LTO object list.  */
1040                   break;
1041                 }
1042             }
1043
1044           /* If we didn't find a match, move on to the next argument.
1045              Otherwise, P has been set to the correct argument position
1046              at which to continue.  */
1047           if (!list) ++p;
1048         }
1049
1050       /* The code above assumes we will never have more lto output files than
1051          input files.  Otherwise, we need to resize lto_ld_argv.  Check this
1052          assumption.  */
1053       if (*lto_o_ptr)
1054         fatal ("too many lto output files");
1055
1056       /* Run the linker again, this time replacing the object files
1057          optimized by the LTO with the temporary file generated by the LTO.  */
1058       fork_execute ("ld", lto_ld_argv);
1059
1060       maybe_unlink_list (lto_o_files);
1061     }
1062   else if (force)
1063     {
1064       /* Our caller is relying on us to do the link
1065          even though there is no LTO back end work to be done.  */
1066       fork_execute  ("ld", lto_ld_argv);
1067     }
1068 }
1069 \f
1070 /* Main program.  */
1071
1072 int
1073 main (int argc, char **argv)
1074 {
1075   static const char *const ld_suffix    = "ld";
1076   static const char *const plugin_ld_suffix = PLUGIN_LD;
1077   static const char *const real_ld_suffix = "real-ld";
1078   static const char *const collect_ld_suffix = "collect-ld";
1079   static const char *const nm_suffix    = "nm";
1080   static const char *const gnm_suffix   = "gnm";
1081 #ifdef LDD_SUFFIX
1082   static const char *const ldd_suffix   = LDD_SUFFIX;
1083 #endif
1084   static const char *const strip_suffix = "strip";
1085   static const char *const gstrip_suffix = "gstrip";
1086
1087 #ifdef CROSS_DIRECTORY_STRUCTURE
1088   /* If we look for a program in the compiler directories, we just use
1089      the short name, since these directories are already system-specific.
1090      But it we look for a program in the system directories, we need to
1091      qualify the program name with the target machine.  */
1092
1093   const char *const full_ld_suffix =
1094     concat(target_machine, "-", ld_suffix, NULL);
1095   const char *const full_plugin_ld_suffix =
1096     concat(target_machine, "-", plugin_ld_suffix, NULL);
1097   const char *const full_nm_suffix =
1098     concat (target_machine, "-", nm_suffix, NULL);
1099   const char *const full_gnm_suffix =
1100     concat (target_machine, "-", gnm_suffix, NULL);
1101 #ifdef LDD_SUFFIX
1102   const char *const full_ldd_suffix =
1103     concat (target_machine, "-", ldd_suffix, NULL);
1104 #endif
1105   const char *const full_strip_suffix =
1106     concat (target_machine, "-", strip_suffix, NULL);
1107   const char *const full_gstrip_suffix =
1108     concat (target_machine, "-", gstrip_suffix, NULL);
1109 #else
1110   const char *const full_ld_suffix      = ld_suffix;
1111   const char *const full_plugin_ld_suffix = plugin_ld_suffix;
1112   const char *const full_nm_suffix      = nm_suffix;
1113   const char *const full_gnm_suffix     = gnm_suffix;
1114 #ifdef LDD_SUFFIX
1115   const char *const full_ldd_suffix     = ldd_suffix;
1116 #endif
1117   const char *const full_strip_suffix   = strip_suffix;
1118   const char *const full_gstrip_suffix  = gstrip_suffix;
1119 #endif /* CROSS_DIRECTORY_STRUCTURE */
1120
1121   const char *arg;
1122   FILE *outf;
1123 #ifdef COLLECT_EXPORT_LIST
1124   FILE *exportf;
1125 #endif
1126   const char *ld_file_name;
1127   const char *p;
1128   char **c_argv;
1129   const char **c_ptr;
1130   char **ld1_argv;
1131   const char **ld1;
1132   bool use_plugin = false;
1133
1134   /* The kinds of symbols we will have to consider when scanning the
1135      outcome of a first pass link.  This is ALL to start with, then might
1136      be adjusted before getting to the first pass link per se, typically on
1137      AIX where we perform an early scan of objects and libraries to fetch
1138      the list of global ctors/dtors and make sure they are not garbage
1139      collected.  */
1140   scanfilter ld1_filter = SCAN_ALL;
1141
1142   char **ld2_argv;
1143   const char **ld2;
1144   char **object_lst;
1145   const char **object;
1146   int first_file;
1147   int num_c_args;
1148   char **old_argv;
1149
1150   bool use_verbose = false;
1151
1152   old_argv = argv;
1153   expandargv (&argc, &argv);
1154   if (argv != old_argv)
1155     at_file_supplied = 1;
1156
1157   num_c_args = argc + 9;
1158
1159   no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
1160
1161   /* Suppress demangling by the real linker, which may be broken.  */
1162   putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
1163
1164 #if defined (COLLECT2_HOST_INITIALIZATION)
1165   /* Perform system dependent initialization, if necessary.  */
1166   COLLECT2_HOST_INITIALIZATION;
1167 #endif
1168
1169 #ifdef SIGCHLD
1170   /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1171      receive the signal.  A different setting is inheritable */
1172   signal (SIGCHLD, SIG_DFL);
1173 #endif
1174
1175   /* Unlock the stdio streams.  */
1176   unlock_std_streams ();
1177
1178   gcc_init_libintl ();
1179
1180   /* Do not invoke xcalloc before this point, since locale needs to be
1181      set first, in case a diagnostic is issued.  */
1182
1183   ld1_argv = XCNEWVEC (char *, argc + 4);
1184   ld1 = CONST_CAST2 (const char **, char **, ld1_argv);
1185   ld2_argv = XCNEWVEC (char *, argc + 11);
1186   ld2 = CONST_CAST2 (const char **, char **, ld2_argv);
1187   object_lst = XCNEWVEC (char *, argc);
1188   object = CONST_CAST2 (const char **, char **, object_lst);
1189
1190 #ifdef DEBUG
1191   debug = 1;
1192 #endif
1193
1194   /* Parse command line early for instances of -debug.  This allows
1195      the debug flag to be set before functions like find_a_file()
1196      are called.  We also look for the -flto or -fwhopr flag to know
1197      what LTO mode we are in.  */
1198   {
1199     int i;
1200
1201     for (i = 1; argv[i] != NULL; i ++)
1202       {
1203         if (! strcmp (argv[i], "-debug"))
1204           debug = true;
1205         else if (! strcmp (argv[i], "-flto") && ! use_plugin)
1206           {
1207             use_verbose = true;
1208             lto_mode = LTO_MODE_LTO;
1209           }
1210         else if (! strncmp (argv[i], "-fwhopr", 7) && ! use_plugin)
1211           {
1212             use_verbose = true;
1213             lto_mode = LTO_MODE_WHOPR;
1214           }
1215         else if (! strcmp (argv[i], "-plugin"))
1216           {
1217             use_plugin = true;
1218             use_verbose = true;
1219             lto_mode = LTO_MODE_NONE;
1220           }
1221 #ifdef COLLECT_EXPORT_LIST
1222         /* since -brtl, -bexport, -b64 are not position dependent
1223            also check for them here */
1224         if ((argv[i][0] == '-') && (argv[i][1] == 'b'))
1225           {
1226             arg = argv[i];
1227             /* We want to disable automatic exports on AIX when user
1228                explicitly puts an export list in command line */
1229             if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1230               export_flag = 1;
1231             else if (arg[2] == '6' && arg[3] == '4')
1232               aix64_flag = 1;
1233             else if (arg[2] == 'r' && arg[3] == 't' && arg[4] == 'l')
1234               aixrtl_flag = 1;
1235           }
1236 #endif
1237       }
1238     vflag = debug;
1239   }
1240
1241 #ifndef DEFAULT_A_OUT_NAME
1242   output_file = "a.out";
1243 #else
1244   output_file = DEFAULT_A_OUT_NAME;
1245 #endif
1246
1247   obstack_begin (&temporary_obstack, 0);
1248   temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
1249
1250 #ifndef HAVE_LD_DEMANGLE
1251   current_demangling_style = auto_demangling;
1252 #endif
1253   p = getenv ("COLLECT_GCC_OPTIONS");
1254   while (p && *p)
1255     {
1256       const char *q = extract_string (&p);
1257       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1258         num_c_args++;
1259     }
1260   obstack_free (&temporary_obstack, temporary_firstobj);
1261
1262   /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
1263      -fno-exceptions -w -fno-whole-program */
1264   num_c_args += 6;
1265
1266   c_argv = XCNEWVEC (char *, num_c_args);
1267   c_ptr = CONST_CAST2 (const char **, char **, c_argv);
1268
1269   if (argc < 2)
1270     fatal ("no arguments");
1271
1272 #ifdef SIGQUIT
1273   if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1274     signal (SIGQUIT, handler);
1275 #endif
1276   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1277     signal (SIGINT, handler);
1278 #ifdef SIGALRM
1279   if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1280     signal (SIGALRM, handler);
1281 #endif
1282 #ifdef SIGHUP
1283   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1284     signal (SIGHUP, handler);
1285 #endif
1286   if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1287     signal (SIGSEGV, handler);
1288 #ifdef SIGBUS
1289   if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1290     signal (SIGBUS, handler);
1291 #endif
1292
1293   /* Extract COMPILER_PATH and PATH into our prefix list.  */
1294   prefix_from_env ("COMPILER_PATH", &cpath);
1295   prefix_from_env ("PATH", &path);
1296
1297   /* Try to discover a valid linker/nm/strip to use.  */
1298
1299   /* Maybe we know the right file to use (if not cross).  */
1300   ld_file_name = 0;
1301 #ifdef DEFAULT_LINKER
1302   if (access (DEFAULT_LINKER, X_OK) == 0)
1303     ld_file_name = DEFAULT_LINKER;
1304   if (ld_file_name == 0)
1305 #endif
1306 #ifdef REAL_LD_FILE_NAME
1307   ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1308   if (ld_file_name == 0)
1309 #endif
1310   /* Search the (target-specific) compiler dirs for ld'.  */
1311   ld_file_name = find_a_file (&cpath, real_ld_suffix);
1312   /* Likewise for `collect-ld'.  */
1313   if (ld_file_name == 0)
1314     ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1315   /* Search the compiler directories for `ld'.  We have protection against
1316      recursive calls in find_a_file.  */
1317   if (ld_file_name == 0)
1318     ld_file_name = find_a_file (&cpath,
1319                                 use_plugin
1320                                 ? plugin_ld_suffix
1321                                 : ld_suffix);
1322   /* Search the ordinary system bin directories
1323      for `ld' (if native linking) or `TARGET-ld' (if cross).  */
1324   if (ld_file_name == 0)
1325     ld_file_name = find_a_file (&path,
1326                                 use_plugin
1327                                 ? full_plugin_ld_suffix
1328                                 : full_ld_suffix);
1329
1330 #ifdef REAL_NM_FILE_NAME
1331   nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1332   if (nm_file_name == 0)
1333 #endif
1334   nm_file_name = find_a_file (&cpath, gnm_suffix);
1335   if (nm_file_name == 0)
1336     nm_file_name = find_a_file (&path, full_gnm_suffix);
1337   if (nm_file_name == 0)
1338     nm_file_name = find_a_file (&cpath, nm_suffix);
1339   if (nm_file_name == 0)
1340     nm_file_name = find_a_file (&path, full_nm_suffix);
1341
1342 #ifdef LDD_SUFFIX
1343   ldd_file_name = find_a_file (&cpath, ldd_suffix);
1344   if (ldd_file_name == 0)
1345     ldd_file_name = find_a_file (&path, full_ldd_suffix);
1346 #endif
1347
1348 #ifdef REAL_STRIP_FILE_NAME
1349   strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1350   if (strip_file_name == 0)
1351 #endif
1352   strip_file_name = find_a_file (&cpath, gstrip_suffix);
1353   if (strip_file_name == 0)
1354     strip_file_name = find_a_file (&path, full_gstrip_suffix);
1355   if (strip_file_name == 0)
1356     strip_file_name = find_a_file (&cpath, strip_suffix);
1357   if (strip_file_name == 0)
1358     strip_file_name = find_a_file (&path, full_strip_suffix);
1359
1360   /* Determine the full path name of the C compiler to use.  */
1361   c_file_name = getenv ("COLLECT_GCC");
1362   if (c_file_name == 0)
1363     {
1364 #ifdef CROSS_DIRECTORY_STRUCTURE
1365       c_file_name = concat (target_machine, "-gcc", NULL);
1366 #else
1367       c_file_name = "gcc";
1368 #endif
1369     }
1370
1371   p = find_a_file (&cpath, c_file_name);
1372
1373   /* Here it should be safe to use the system search path since we should have
1374      already qualified the name of the compiler when it is needed.  */
1375   if (p == 0)
1376     p = find_a_file (&path, c_file_name);
1377
1378   if (p)
1379     c_file_name = p;
1380
1381   *ld1++ = *ld2++ = ld_file_name;
1382
1383   /* Make temp file names.  */
1384   c_file = make_temp_file (".c");
1385   o_file = make_temp_file (".o");
1386 #ifdef COLLECT_EXPORT_LIST
1387   export_file = make_temp_file (".x");
1388 #endif
1389   ldout = make_temp_file (".ld");
1390   lderrout = make_temp_file (".le");
1391   *c_ptr++ = c_file_name;
1392   *c_ptr++ = "-x";
1393   *c_ptr++ = "c";
1394   *c_ptr++ = "-c";
1395   *c_ptr++ = "-o";
1396   *c_ptr++ = o_file;
1397
1398 #ifdef COLLECT_EXPORT_LIST
1399   /* Generate a list of directories from LIBPATH.  */
1400   prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1401   /* Add to this list also two standard directories where
1402      AIX loader always searches for libraries.  */
1403   add_prefix (&libpath_lib_dirs, "/lib");
1404   add_prefix (&libpath_lib_dirs, "/usr/lib");
1405 #endif
1406
1407   /* Get any options that the upper GCC wants to pass to the sub-GCC.
1408
1409      AIX support needs to know if -shared has been specified before
1410      parsing commandline arguments.  */
1411
1412   p = getenv ("COLLECT_GCC_OPTIONS");
1413   while (p && *p)
1414     {
1415       const char *q = extract_string (&p);
1416       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1417         *c_ptr++ = xstrdup (q);
1418       if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1419         *c_ptr++ = xstrdup (q);
1420       if (strcmp (q, "-shared") == 0)
1421         shared_obj = 1;
1422       if (*q == '-' && q[1] == 'B')
1423         {
1424           *c_ptr++ = xstrdup (q);
1425           if (q[2] == 0)
1426             {
1427               q = extract_string (&p);
1428               *c_ptr++ = xstrdup (q);
1429             }
1430         }
1431       if (use_verbose && *q == '-' && q[1] == 'v' && q[2] == 0)
1432         {
1433           /* Turn on trace in collect2 if needed.  */
1434           vflag = true;
1435         }
1436     }
1437   obstack_free (&temporary_obstack, temporary_firstobj);
1438   *c_ptr++ = "-fno-profile-arcs";
1439   *c_ptr++ = "-fno-test-coverage";
1440   *c_ptr++ = "-fno-branch-probabilities";
1441   *c_ptr++ = "-fno-exceptions";
1442   *c_ptr++ = "-w";
1443   *c_ptr++ = "-fno-whole-program";
1444
1445   /* !!! When GCC calls collect2,
1446      it does not know whether it is calling collect2 or ld.
1447      So collect2 cannot meaningfully understand any options
1448      except those ld understands.
1449      If you propose to make GCC pass some other option,
1450      just imagine what will happen if ld is really ld!!!  */
1451
1452   /* Parse arguments.  Remember output file spec, pass the rest to ld.  */
1453   /* After the first file, put in the c++ rt0.  */
1454
1455   first_file = 1;
1456 #ifdef HAVE_LD_DEMANGLE
1457   if (!demangle_flag && !no_demangle)
1458     demangle_flag = "--demangle";
1459   if (demangle_flag)
1460     *ld1++ = *ld2++ = demangle_flag;
1461 #endif
1462   while ((arg = *++argv) != (char *) 0)
1463     {
1464       *ld1++ = *ld2++ = arg;
1465
1466       if (arg[0] == '-')
1467         {
1468           switch (arg[1])
1469             {
1470             case 'd':
1471               if (!strcmp (arg, "-debug"))
1472                 {
1473                   /* Already parsed.  */
1474                   ld1--;
1475                   ld2--;
1476                 }
1477               if (!strcmp (arg, "-dynamic-linker") && argv[1])
1478                 {
1479                   ++argv;
1480                   *ld1++ = *ld2++ = *argv;
1481                 }
1482               break;
1483
1484             case 'f':
1485               if (strcmp (arg, "-flto") == 0
1486                   || strncmp (arg, "-fwhopr", 7) == 0)
1487                 {
1488 #ifdef ENABLE_LTO
1489                   /* Do not pass LTO flag to the linker. */
1490                   ld1--;
1491                   ld2--;
1492 #else
1493                   error ("LTO support has not been enabled in this "
1494                          "configuration");
1495 #endif
1496                 }
1497               break;
1498
1499             case 'l':
1500               if (first_file)
1501                 {
1502                   /* place o_file BEFORE this argument! */
1503                   first_file = 0;
1504                   ld2--;
1505                   *ld2++ = o_file;
1506                   *ld2++ = arg;
1507                 }
1508 #ifdef COLLECT_EXPORT_LIST
1509               {
1510                 /* Resolving full library name.  */
1511                 const char *s = resolve_lib_name (arg+2);
1512
1513                 /* Saving a full library name.  */
1514                 add_to_list (&libs, s);
1515               }
1516 #endif
1517               break;
1518
1519 #ifdef COLLECT_EXPORT_LIST
1520             /* Saving directories where to search for libraries.  */
1521             case 'L':
1522               add_prefix (&cmdline_lib_dirs, arg+2);
1523               break;
1524 #else
1525 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1526             case 'L':
1527               if (is_in_args (arg,
1528                               CONST_CAST2 (const char **, char **, ld1_argv),
1529                               ld1 - 1))
1530                 --ld1;
1531               break;
1532 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1533 #endif
1534
1535             case 'o':
1536               if (arg[2] == '\0')
1537                 output_file = *ld1++ = *ld2++ = *++argv;
1538               else
1539                 output_file = &arg[2];
1540               break;
1541
1542             case 'r':
1543               if (arg[2] == '\0')
1544                 rflag = 1;
1545               break;
1546
1547             case 's':
1548               if (arg[2] == '\0' && do_collecting)
1549                 {
1550                   /* We must strip after the nm run, otherwise C++ linking
1551                      will not work.  Thus we strip in the second ld run, or
1552                      else with strip if there is no second ld run.  */
1553                   strip_flag = 1;
1554                   ld1--;
1555                 }
1556               break;
1557
1558             case 'v':
1559               if (arg[2] == '\0')
1560                 vflag = true;
1561               break;
1562
1563             case '-':
1564               if (strcmp (arg, "--no-demangle") == 0)
1565                 {
1566                   demangle_flag = arg;
1567                   no_demangle = 1;
1568                   ld1--;
1569                   ld2--;
1570                 }
1571               else if (strncmp (arg, "--demangle", 10) == 0)
1572                 {
1573                   demangle_flag = arg;
1574                   no_demangle = 0;
1575 #ifndef HAVE_LD_DEMANGLE
1576                   if (arg[10] == '=')
1577                     {
1578                       enum demangling_styles style
1579                         = cplus_demangle_name_to_style (arg+11);
1580                       if (style == unknown_demangling)
1581                         error ("unknown demangling style '%s'", arg+11);
1582                       else
1583                         current_demangling_style = style;
1584                     }
1585 #endif
1586                   ld1--;
1587                   ld2--;
1588                 }
1589               else if (strncmp (arg, "--sysroot=", 10) == 0)
1590                 target_system_root = arg + 10;
1591               else if (strcmp (arg, "--version") == 0)
1592                 vflag = true;
1593               else if (strcmp (arg, "--help") == 0)
1594                 helpflag = true;
1595               break;
1596             }
1597         }
1598       else if ((p = strrchr (arg, '.')) != (char *) 0
1599                && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1600                    || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1601                    || strcmp (p, ".obj") == 0))
1602         {
1603           if (first_file)
1604             {
1605               first_file = 0;
1606               if (p[1] == 'o')
1607                 *ld2++ = o_file;
1608               else
1609                 {
1610                   /* place o_file BEFORE this argument! */
1611                   ld2--;
1612                   *ld2++ = o_file;
1613                   *ld2++ = arg;
1614                 }
1615             }
1616           if (p[1] == 'o' || p[1] == 'l')
1617             *object++ = arg;
1618 #ifdef COLLECT_EXPORT_LIST
1619           /* libraries can be specified directly, i.e. without -l flag.  */
1620           else
1621             {
1622               /* Saving a full library name.  */
1623               add_to_list (&libs, arg);
1624             }
1625 #endif
1626         }
1627     }
1628
1629 #ifdef COLLECT_EXPORT_LIST
1630   /* This is added only for debugging purposes.  */
1631   if (debug)
1632     {
1633       fprintf (stderr, "List of libraries:\n");
1634       dump_list (stderr, "\t", libs.first);
1635     }
1636
1637   /* The AIX linker will discard static constructors in object files if
1638      nothing else in the file is referenced, so look at them first.  Unless
1639      we are building a shared object, ignore the eh frame tables, as we
1640      would otherwise reference them all, hence drag all the corresponding
1641      objects even if nothing else is referenced.  */
1642   {
1643     const char **export_object_lst
1644       = CONST_CAST2 (const char **, char **, object_lst);
1645
1646     struct id *list = libs.first;
1647
1648     /* Compute the filter to use from the current one, do scan, then adjust
1649        the "current" filter to remove what we just included here.  This will
1650        control whether we need a first pass link later on or not, and what
1651        will remain to be scanned there.  */
1652
1653     scanfilter this_filter = ld1_filter;
1654 #if HAVE_AS_REF
1655     if (!shared_obj)
1656       this_filter &= ~SCAN_DWEH;
1657 #endif
1658
1659     while (export_object_lst < object)
1660       scan_prog_file (*export_object_lst++, PASS_OBJ, this_filter);
1661
1662     for (; list; list = list->next)
1663       scan_prog_file (list->name, PASS_FIRST, this_filter);
1664
1665     ld1_filter = ld1_filter & ~this_filter;
1666   }
1667
1668   if (exports.first)
1669     {
1670       char *buf = concat ("-bE:", export_file, NULL);
1671
1672       *ld1++ = buf;
1673       *ld2++ = buf;
1674
1675       exportf = fopen (export_file, "w");
1676       if (exportf == (FILE *) 0)
1677         fatal_perror ("fopen %s", export_file);
1678       write_aix_file (exportf, exports.first);
1679       if (fclose (exportf))
1680         fatal_perror ("fclose %s", export_file);
1681     }
1682 #endif
1683
1684   *c_ptr++ = c_file;
1685   *c_ptr = *ld1 = *object = (char *) 0;
1686
1687   if (vflag)
1688     {
1689       notice ("collect2 version %s", version_string);
1690 #ifdef TARGET_VERSION
1691       TARGET_VERSION;
1692 #endif
1693       fprintf (stderr, "\n");
1694     }
1695
1696   if (helpflag)
1697     {
1698       fprintf (stderr, "Usage: collect2 [options]\n");
1699       fprintf (stderr, " Wrap linker and generate constructor code if needed.\n");
1700       fprintf (stderr, " Options:\n");
1701       fprintf (stderr, "  -debug          Enable debug output\n");
1702       fprintf (stderr, "  --help          Display this information\n");
1703       fprintf (stderr, "  -v, --version   Display this program's version number\n");
1704       fprintf (stderr, "Overview: http://gcc.gnu.org/onlinedocs/gccint/Collect2.html\n");
1705       fprintf (stderr, "Report bugs: %s\n", bug_report_url);
1706
1707       collect_exit (0);
1708     }
1709
1710   if (debug)
1711     {
1712       const char *ptr;
1713       fprintf (stderr, "ld_file_name        = %s\n",
1714                (ld_file_name ? ld_file_name : "not found"));
1715       fprintf (stderr, "c_file_name         = %s\n",
1716                (c_file_name ? c_file_name : "not found"));
1717       fprintf (stderr, "nm_file_name        = %s\n",
1718                (nm_file_name ? nm_file_name : "not found"));
1719 #ifdef LDD_SUFFIX
1720       fprintf (stderr, "ldd_file_name       = %s\n",
1721                (ldd_file_name ? ldd_file_name : "not found"));
1722 #endif
1723       fprintf (stderr, "strip_file_name     = %s\n",
1724                (strip_file_name ? strip_file_name : "not found"));
1725       fprintf (stderr, "c_file              = %s\n",
1726                (c_file ? c_file : "not found"));
1727       fprintf (stderr, "o_file              = %s\n",
1728                (o_file ? o_file : "not found"));
1729
1730       ptr = getenv ("COLLECT_GCC_OPTIONS");
1731       if (ptr)
1732         fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1733
1734       ptr = getenv ("COLLECT_GCC");
1735       if (ptr)
1736         fprintf (stderr, "COLLECT_GCC         = %s\n", ptr);
1737
1738       ptr = getenv ("COMPILER_PATH");
1739       if (ptr)
1740         fprintf (stderr, "COMPILER_PATH       = %s\n", ptr);
1741
1742       ptr = getenv (LIBRARY_PATH_ENV);
1743       if (ptr)
1744         fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1745
1746       fprintf (stderr, "\n");
1747     }
1748
1749   /* Load the program, searching all libraries and attempting to provide
1750      undefined symbols from repository information.
1751
1752      If -r or they will be run via some other method, do not build the
1753      constructor or destructor list, just return now.  */
1754   {
1755     bool early_exit
1756       = rflag || (! DO_COLLECT_EXPORT_LIST && ! do_collecting);
1757
1758     /* Perform the first pass link now, if we're about to exit or if we need
1759        to scan for things we haven't collected yet before pursuing further.
1760
1761        On AIX, the latter typically includes nothing for shared objects or
1762        frame tables for an executable, out of what the required early scan on
1763        objects and libraries has performed above.  In the !shared_obj case, we
1764        expect the relevant tables to be dragged together with their associated
1765        functions from precise cross reference insertions by the compiler.  */
1766
1767     if (early_exit || ld1_filter != SCAN_NOTHING)
1768       do_tlink (ld1_argv, object_lst);
1769
1770     if (early_exit)
1771       {
1772 #ifdef COLLECT_EXPORT_LIST
1773         /* Make sure we delete the export file we may have created.  */
1774         if (export_file != 0 && export_file[0])
1775           maybe_unlink (export_file);
1776 #endif
1777         if (lto_mode != LTO_MODE_NONE)
1778           maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1779
1780         maybe_unlink (c_file);
1781         maybe_unlink (o_file);
1782         return 0;
1783       }
1784   }
1785
1786   /* Unless we have done it all already, examine the namelist and search for
1787      static constructors and destructors to call.  Write the constructor and
1788      destructor tables to a .s file and reload.  */
1789
1790   if (ld1_filter != SCAN_NOTHING)
1791     scan_prog_file (output_file, PASS_FIRST, ld1_filter);
1792
1793 #ifdef SCAN_LIBRARIES
1794   scan_libraries (output_file);
1795 #endif
1796
1797   if (debug)
1798     {
1799       notice_translated (ngettext ("%d constructor found\n",
1800                                    "%d constructors found\n",
1801                                    constructors.number),
1802                          constructors.number);
1803       notice_translated (ngettext ("%d destructor found\n",
1804                                    "%d destructors found\n",
1805                                    destructors.number),
1806                          destructors.number);
1807       notice_translated (ngettext("%d frame table found\n",
1808                                   "%d frame tables found\n",
1809                                   frame_tables.number),
1810                          frame_tables.number);
1811     }
1812
1813   /* If the scan exposed nothing of special interest, there's no need to
1814      generate the glue code and relink so return now.  */
1815
1816   if (constructors.number == 0 && destructors.number == 0
1817       && frame_tables.number == 0
1818 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1819       /* If we will be running these functions ourselves, we want to emit
1820          stubs into the shared library so that we do not have to relink
1821          dependent programs when we add static objects.  */
1822       && ! shared_obj
1823 #endif
1824       )
1825     {
1826       /* Do tlink without additional code generation now if we didn't
1827          do it earlier for scanning purposes.  */
1828       if (ld1_filter == SCAN_NOTHING)
1829         do_tlink (ld1_argv, object_lst);
1830
1831       if (lto_mode)
1832         maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1833
1834       /* Strip now if it was requested on the command line.  */
1835       if (strip_flag)
1836         {
1837           char **real_strip_argv = XCNEWVEC (char *, 3);
1838           const char ** strip_argv = CONST_CAST2 (const char **, char **,
1839                                                   real_strip_argv);
1840
1841           strip_argv[0] = strip_file_name;
1842           strip_argv[1] = output_file;
1843           strip_argv[2] = (char *) 0;
1844           fork_execute ("strip", real_strip_argv);
1845         }
1846
1847 #ifdef COLLECT_EXPORT_LIST
1848       maybe_unlink (export_file);
1849 #endif
1850       maybe_unlink (c_file);
1851       maybe_unlink (o_file);
1852       return 0;
1853     }
1854
1855   /* Sort ctor and dtor lists by priority.  */
1856   sort_ids (&constructors);
1857   sort_ids (&destructors);
1858
1859   maybe_unlink(output_file);
1860   outf = fopen (c_file, "w");
1861   if (outf == (FILE *) 0)
1862     fatal_perror ("fopen %s", c_file);
1863
1864   write_c_file (outf, c_file);
1865
1866   if (fclose (outf))
1867     fatal_perror ("fclose %s", c_file);
1868
1869   /* Tell the linker that we have initializer and finalizer functions.  */
1870 #ifdef LD_INIT_SWITCH
1871 #ifdef COLLECT_EXPORT_LIST
1872   *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1873 #else
1874   *ld2++ = LD_INIT_SWITCH;
1875   *ld2++ = initname;
1876   *ld2++ = LD_FINI_SWITCH;
1877   *ld2++ = fininame;
1878 #endif
1879 #endif
1880
1881 #ifdef COLLECT_EXPORT_LIST
1882   if (shared_obj)
1883     {
1884       /* If we did not add export flag to link arguments before, add it to
1885          second link phase now.  No new exports should have been added.  */
1886       if (! exports.first)
1887         *ld2++ = concat ("-bE:", export_file, NULL);
1888
1889 #ifndef LD_INIT_SWITCH
1890       add_to_list (&exports, initname);
1891       add_to_list (&exports, fininame);
1892       add_to_list (&exports, "_GLOBAL__DI");
1893       add_to_list (&exports, "_GLOBAL__DD");
1894 #endif
1895       exportf = fopen (export_file, "w");
1896       if (exportf == (FILE *) 0)
1897         fatal_perror ("fopen %s", export_file);
1898       write_aix_file (exportf, exports.first);
1899       if (fclose (exportf))
1900         fatal_perror ("fclose %s", export_file);
1901     }
1902 #endif
1903
1904   /* End of arguments to second link phase.  */
1905   *ld2 = (char*) 0;
1906
1907   if (debug)
1908     {
1909       fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1910                output_file, c_file);
1911       write_c_file (stderr, "stderr");
1912       fprintf (stderr, "========== end of c_file\n\n");
1913 #ifdef COLLECT_EXPORT_LIST
1914       fprintf (stderr, "\n========== export_file = %s\n", export_file);
1915       write_aix_file (stderr, exports.first);
1916       fprintf (stderr, "========== end of export_file\n\n");
1917 #endif
1918     }
1919
1920   /* Assemble the constructor and destructor tables.
1921      Link the tables in with the rest of the program.  */
1922
1923   fork_execute ("gcc",  c_argv);
1924 #ifdef COLLECT_EXPORT_LIST
1925   /* On AIX we must call tlink because of possible templates resolution.  */
1926   do_tlink (ld2_argv, object_lst);
1927
1928   if (lto_mode)
1929     maybe_run_lto_and_relink (ld2_argv, object_lst, object, false);
1930 #else
1931   /* Otherwise, simply call ld because tlink is already done.  */
1932   if (lto_mode)
1933     maybe_run_lto_and_relink (ld2_argv, object_lst, object, true);
1934   else
1935     fork_execute ("ld", ld2_argv);
1936
1937   /* Let scan_prog_file do any final mods (OSF/rose needs this for
1938      constructors/destructors in shared libraries.  */
1939   scan_prog_file (output_file, PASS_SECOND, SCAN_ALL);
1940 #endif
1941
1942   maybe_unlink (c_file);
1943   maybe_unlink (o_file);
1944
1945 #ifdef COLLECT_EXPORT_LIST
1946   maybe_unlink (export_file);
1947 #endif
1948
1949   return 0;
1950 }
1951
1952 \f
1953 /* Wait for a process to finish, and exit if a nonzero status is found.  */
1954
1955 int
1956 collect_wait (const char *prog, struct pex_obj *pex)
1957 {
1958   int status;
1959
1960   if (!pex_get_status (pex, 1, &status))
1961     fatal_perror ("can't get program status");
1962   pex_free (pex);
1963
1964   if (status)
1965     {
1966       if (WIFSIGNALED (status))
1967         {
1968           int sig = WTERMSIG (status);
1969           error ("%s terminated with signal %d [%s]%s",
1970                  prog, sig, strsignal(sig),
1971                  WCOREDUMP(status) ? ", core dumped" : "");
1972           collect_exit (FATAL_EXIT_CODE);
1973         }
1974
1975       if (WIFEXITED (status))
1976         return WEXITSTATUS (status);
1977     }
1978   return 0;
1979 }
1980
1981 static void
1982 do_wait (const char *prog, struct pex_obj *pex)
1983 {
1984   int ret = collect_wait (prog, pex);
1985   if (ret != 0)
1986     {
1987       error ("%s returned %d exit status", prog, ret);
1988       collect_exit (ret);
1989     }
1990
1991   if (response_file)
1992     {
1993       unlink (response_file);
1994       response_file = NULL;
1995     }
1996 }
1997
1998 \f
1999 /* Execute a program, and wait for the reply.  */
2000
2001 struct pex_obj *
2002 collect_execute (const char *prog, char **argv, const char *outname,
2003                  const char *errname, int flags)
2004 {
2005   struct pex_obj *pex;
2006   const char *errmsg;
2007   int err;
2008   char *response_arg = NULL;
2009   char *response_argv[3] ATTRIBUTE_UNUSED;
2010
2011   if (HAVE_GNU_LD && at_file_supplied && argv[0] != NULL)
2012     {
2013       /* If using @file arguments, create a temporary file and put the
2014          contents of argv into it.  Then change argv to an array corresponding
2015          to a single argument @FILE, where FILE is the temporary filename.  */
2016
2017       char **current_argv = argv + 1;
2018       char *argv0 = argv[0];
2019       int status;
2020       FILE *f;
2021
2022       /* Note: we assume argv contains at least one element; this is
2023          checked above.  */
2024
2025       response_file = make_temp_file ("");
2026
2027       f = fopen (response_file, "w");
2028
2029       if (f == NULL)
2030         fatal ("could not open response file %s", response_file);
2031
2032       status = writeargv (current_argv, f);
2033
2034       if (status)
2035         fatal ("could not write to response file %s", response_file);
2036
2037       status = fclose (f);
2038
2039       if (EOF == status)
2040         fatal ("could not close response file %s", response_file);
2041
2042       response_arg = concat ("@", response_file, NULL);
2043       response_argv[0] = argv0;
2044       response_argv[1] = response_arg;
2045       response_argv[2] = NULL;
2046
2047       argv = response_argv;
2048     }
2049
2050   if (vflag || debug)
2051     {
2052       char **p_argv;
2053       const char *str;
2054
2055       if (argv[0])
2056         fprintf (stderr, "%s", argv[0]);
2057       else
2058         notice ("[cannot find %s]", prog);
2059
2060       for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
2061         fprintf (stderr, " %s", str);
2062
2063       fprintf (stderr, "\n");
2064     }
2065
2066   fflush (stdout);
2067   fflush (stderr);
2068
2069   /* If we cannot find a program we need, complain error.  Do this here
2070      since we might not end up needing something that we could not find.  */
2071
2072   if (argv[0] == 0)
2073     fatal ("cannot find '%s'", prog);
2074
2075   pex = pex_init (0, "collect2", NULL);
2076   if (pex == NULL)
2077     fatal_perror ("pex_init failed");
2078
2079   errmsg = pex_run (pex, flags, argv[0], argv, outname,
2080                     errname, &err);
2081   if (errmsg != NULL)
2082     {
2083       if (err != 0)
2084         {
2085           errno = err;
2086           fatal_perror (errmsg);
2087         }
2088       else
2089         fatal (errmsg);
2090     }
2091
2092   if (response_arg)
2093     free (response_arg);
2094
2095   return pex;
2096 }
2097
2098 static void
2099 fork_execute (const char *prog, char **argv)
2100 {
2101   struct pex_obj *pex;
2102
2103   pex = collect_execute (prog, argv, NULL, NULL, PEX_LAST | PEX_SEARCH);
2104   do_wait (prog, pex);
2105 }
2106 \f
2107 /* Unlink a file unless we are debugging.  */
2108
2109 static void
2110 maybe_unlink (const char *file)
2111 {
2112   if (!debug)
2113     unlink_if_ordinary (file);
2114   else
2115     notice ("[Leaving %s]\n", file);
2116 }
2117
2118 /* Call maybe_unlink on the NULL-terminated list, FILE_LIST.  */
2119
2120 static void
2121 maybe_unlink_list (char **file_list)
2122 {
2123   char **tmp = file_list;
2124
2125   while (*tmp)
2126     maybe_unlink (*(tmp++));
2127 }
2128
2129 \f
2130 static long sequence_number = 0;
2131
2132 /* Add a name to a linked list.  */
2133
2134 static void
2135 add_to_list (struct head *head_ptr, const char *name)
2136 {
2137   struct id *newid
2138     = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
2139   struct id *p;
2140   strcpy (newid->name, name);
2141
2142   if (head_ptr->first)
2143     head_ptr->last->next = newid;
2144   else
2145     head_ptr->first = newid;
2146
2147   /* Check for duplicate symbols.  */
2148   for (p = head_ptr->first;
2149        strcmp (name, p->name) != 0;
2150        p = p->next)
2151     ;
2152   if (p != newid)
2153     {
2154       head_ptr->last->next = 0;
2155       free (newid);
2156       return;
2157     }
2158
2159   newid->sequence = ++sequence_number;
2160   head_ptr->last = newid;
2161   head_ptr->number++;
2162 }
2163
2164 /* Grab the init priority number from an init function name that
2165    looks like "_GLOBAL_.I.12345.foo".  */
2166
2167 static int
2168 extract_init_priority (const char *name)
2169 {
2170   int pos = 0, pri;
2171
2172   while (name[pos] == '_')
2173     ++pos;
2174   pos += 10; /* strlen ("GLOBAL__X_") */
2175
2176   /* Extract init_p number from ctor/dtor name.  */
2177   pri = atoi (name + pos);
2178   return pri ? pri : DEFAULT_INIT_PRIORITY;
2179 }
2180
2181 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
2182    ctors will be run from right to left, dtors from left to right.  */
2183
2184 static void
2185 sort_ids (struct head *head_ptr)
2186 {
2187   /* id holds the current element to insert.  id_next holds the next
2188      element to insert.  id_ptr iterates through the already sorted elements
2189      looking for the place to insert id.  */
2190   struct id *id, *id_next, **id_ptr;
2191
2192   id = head_ptr->first;
2193
2194   /* We don't have any sorted elements yet.  */
2195   head_ptr->first = NULL;
2196
2197   for (; id; id = id_next)
2198     {
2199       id_next = id->next;
2200       id->sequence = extract_init_priority (id->name);
2201
2202       for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
2203         if (*id_ptr == NULL
2204             /* If the sequence numbers are the same, we put the id from the
2205                file later on the command line later in the list.  */
2206             || id->sequence > (*id_ptr)->sequence
2207             /* Hack: do lexical compare, too.
2208             || (id->sequence == (*id_ptr)->sequence
2209                 && strcmp (id->name, (*id_ptr)->name) > 0) */
2210             )
2211           {
2212             id->next = *id_ptr;
2213             *id_ptr = id;
2214             break;
2215           }
2216     }
2217
2218   /* Now set the sequence numbers properly so write_c_file works.  */
2219   for (id = head_ptr->first; id; id = id->next)
2220     id->sequence = ++sequence_number;
2221 }
2222
2223 /* Write: `prefix', the names on list LIST, `suffix'.  */
2224
2225 static void
2226 write_list (FILE *stream, const char *prefix, struct id *list)
2227 {
2228   while (list)
2229     {
2230       fprintf (stream, "%sx%d,\n", prefix, list->sequence);
2231       list = list->next;
2232     }
2233 }
2234
2235 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
2236 /* Given a STRING, return nonzero if it occurs in the list in range
2237    [ARGS_BEGIN,ARGS_END).  */
2238
2239 static int
2240 is_in_args (const char *string, const char **args_begin,
2241             const char **args_end)
2242 {
2243   const char **args_pointer;
2244   for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
2245     if (strcmp (string, *args_pointer) == 0)
2246       return 1;
2247   return 0;
2248 }
2249 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
2250
2251 #ifdef COLLECT_EXPORT_LIST
2252 /* This function is really used only on AIX, but may be useful.  */
2253 #if 0
2254 static int
2255 is_in_list (const char *prefix, struct id *list)
2256 {
2257   while (list)
2258     {
2259       if (!strcmp (prefix, list->name)) return 1;
2260       list = list->next;
2261     }
2262     return 0;
2263 }
2264 #endif
2265 #endif /* COLLECT_EXPORT_LIST */
2266
2267 /* Added for debugging purpose.  */
2268 #ifdef COLLECT_EXPORT_LIST
2269 static void
2270 dump_list (FILE *stream, const char *prefix, struct id *list)
2271 {
2272   while (list)
2273     {
2274       fprintf (stream, "%s%s,\n", prefix, list->name);
2275       list = list->next;
2276     }
2277 }
2278 #endif
2279
2280 #if 0
2281 static void
2282 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
2283 {
2284   while (list)
2285     {
2286       fprintf (stream, "%s%s,\n", prefix, list->prefix);
2287       list = list->next;
2288     }
2289 }
2290 #endif
2291
2292 static void
2293 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
2294 {
2295   while (list)
2296     {
2297       fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
2298                prefix, list->sequence, list->name);
2299       list = list->next;
2300     }
2301 }
2302
2303 /* Write out the constructor and destructor tables statically (for a shared
2304    object), along with the functions to execute them.  */
2305
2306 static void
2307 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2308 {
2309   const char *p, *q;
2310   char *prefix, *r;
2311   int frames = (frame_tables.number > 0);
2312
2313   /* Figure out name of output_file, stripping off .so version.  */
2314   p = strrchr (output_file, '/');
2315   if (p == 0)
2316     p = output_file;
2317   else
2318     p++;
2319   q = p;
2320   while (q)
2321     {
2322       q = strchr (q,'.');
2323       if (q == 0)
2324         {
2325           q = p + strlen (p);
2326           break;
2327         }
2328       else
2329         {
2330           if (strncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
2331             {
2332               q += strlen (SHLIB_SUFFIX);
2333               break;
2334             }
2335           else
2336             q++;
2337         }
2338     }
2339   /* q points to null at end of the string (or . of the .so version) */
2340   prefix = XNEWVEC (char, q - p + 1);
2341   strncpy (prefix, p, q - p);
2342   prefix[q - p] = 0;
2343   for (r = prefix; *r; r++)
2344     if (!ISALNUM ((unsigned char)*r))
2345       *r = '_';
2346   if (debug)
2347     notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
2348             output_file, prefix);
2349
2350   initname = concat ("_GLOBAL__FI_", prefix, NULL);
2351   fininame = concat ("_GLOBAL__FD_", prefix, NULL);
2352
2353   free (prefix);
2354
2355   /* Write the tables as C code.  */
2356
2357   fprintf (stream, "static int count;\n");
2358   fprintf (stream, "typedef void entry_pt();\n");
2359   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2360
2361   if (frames)
2362     {
2363       write_list_with_asm (stream, "extern void *", frame_tables.first);
2364
2365       fprintf (stream, "\tstatic void *frame_table[] = {\n");
2366       write_list (stream, "\t\t&", frame_tables.first);
2367       fprintf (stream, "\t0\n};\n");
2368
2369       /* This must match what's in frame.h.  */
2370       fprintf (stream, "struct object {\n");
2371       fprintf (stream, "  void *pc_begin;\n");
2372       fprintf (stream, "  void *pc_end;\n");
2373       fprintf (stream, "  void *fde_begin;\n");
2374       fprintf (stream, "  void *fde_array;\n");
2375       fprintf (stream, "  __SIZE_TYPE__ count;\n");
2376       fprintf (stream, "  struct object *next;\n");
2377       fprintf (stream, "};\n");
2378
2379       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2380       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2381
2382       fprintf (stream, "static void reg_frame () {\n");
2383       fprintf (stream, "\tstatic struct object ob;\n");
2384       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2385       fprintf (stream, "\t}\n");
2386
2387       fprintf (stream, "static void dereg_frame () {\n");
2388       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2389       fprintf (stream, "\t}\n");
2390     }
2391
2392   fprintf (stream, "void %s() {\n", initname);
2393   if (constructors.number > 0 || frames)
2394     {
2395       fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2396       write_list (stream, "\t\t", constructors.first);
2397       if (frames)
2398         fprintf (stream, "\treg_frame,\n");
2399       fprintf (stream, "\t};\n");
2400       fprintf (stream, "\tentry_pt **p;\n");
2401       fprintf (stream, "\tif (count++ != 0) return;\n");
2402       fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2403       fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2404     }
2405   else
2406     fprintf (stream, "\t++count;\n");
2407   fprintf (stream, "}\n");
2408   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2409   fprintf (stream, "void %s() {\n", fininame);
2410   if (destructors.number > 0 || frames)
2411     {
2412       fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2413       write_list (stream, "\t\t", destructors.first);
2414       if (frames)
2415         fprintf (stream, "\tdereg_frame,\n");
2416       fprintf (stream, "\t};\n");
2417       fprintf (stream, "\tentry_pt **p;\n");
2418       fprintf (stream, "\tif (--count != 0) return;\n");
2419       fprintf (stream, "\tp = dtors;\n");
2420       fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2421                destructors.number + frames);
2422     }
2423   fprintf (stream, "}\n");
2424
2425   if (shared_obj)
2426     {
2427       COLLECT_SHARED_INIT_FUNC(stream, initname);
2428       COLLECT_SHARED_FINI_FUNC(stream, fininame);
2429     }
2430 }
2431
2432 /* Write the constructor/destructor tables.  */
2433
2434 #ifndef LD_INIT_SWITCH
2435 static void
2436 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2437 {
2438   /* Write the tables as C code.  */
2439
2440   int frames = (frame_tables.number > 0);
2441
2442   fprintf (stream, "typedef void entry_pt();\n\n");
2443
2444   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2445
2446   if (frames)
2447     {
2448       write_list_with_asm (stream, "extern void *", frame_tables.first);
2449
2450       fprintf (stream, "\tstatic void *frame_table[] = {\n");
2451       write_list (stream, "\t\t&", frame_tables.first);
2452       fprintf (stream, "\t0\n};\n");
2453
2454       /* This must match what's in frame.h.  */
2455       fprintf (stream, "struct object {\n");
2456       fprintf (stream, "  void *pc_begin;\n");
2457       fprintf (stream, "  void *pc_end;\n");
2458       fprintf (stream, "  void *fde_begin;\n");
2459       fprintf (stream, "  void *fde_array;\n");
2460       fprintf (stream, "  __SIZE_TYPE__ count;\n");
2461       fprintf (stream, "  struct object *next;\n");
2462       fprintf (stream, "};\n");
2463
2464       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2465       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2466
2467       fprintf (stream, "static void reg_frame () {\n");
2468       fprintf (stream, "\tstatic struct object ob;\n");
2469       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2470       fprintf (stream, "\t}\n");
2471
2472       fprintf (stream, "static void dereg_frame () {\n");
2473       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2474       fprintf (stream, "\t}\n");
2475     }
2476
2477   fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2478   fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2479   write_list (stream, "\t", constructors.first);
2480   if (frames)
2481     fprintf (stream, "\treg_frame,\n");
2482   fprintf (stream, "\t0\n};\n\n");
2483
2484   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2485
2486   fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2487   fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2488   write_list (stream, "\t", destructors.first);
2489   if (frames)
2490     fprintf (stream, "\tdereg_frame,\n");
2491   fprintf (stream, "\t0\n};\n\n");
2492
2493   fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2494   fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2495 }
2496 #endif /* ! LD_INIT_SWITCH */
2497
2498 static void
2499 write_c_file (FILE *stream, const char *name)
2500 {
2501 #ifndef LD_INIT_SWITCH
2502   if (! shared_obj)
2503     write_c_file_glob (stream, name);
2504   else
2505 #endif
2506     write_c_file_stat (stream, name);
2507 }
2508
2509 #ifdef COLLECT_EXPORT_LIST
2510 static void
2511 write_aix_file (FILE *stream, struct id *list)
2512 {
2513   for (; list; list = list->next)
2514     {
2515       fputs (list->name, stream);
2516       putc ('\n', stream);
2517     }
2518 }
2519 #endif
2520 \f
2521 #ifdef OBJECT_FORMAT_NONE
2522
2523 /* Check to make sure the file is an LTO object file.  */
2524
2525 static bool
2526 maybe_lto_object_file (const char *prog_name)
2527 {
2528   FILE *f;
2529   unsigned char buf[4];
2530   int i;
2531
2532   static unsigned char elfmagic[4] = { 0x7f, 'E', 'L', 'F' };
2533   static unsigned char coffmagic[2] = { 0x4c, 0x01 };
2534   static unsigned char coffmagic_x64[2] = { 0x64, 0x86 };
2535   static unsigned char machomagic[4][4] = {
2536     { 0xcf, 0xfa, 0xed, 0xfe },
2537     { 0xce, 0xfa, 0xed, 0xfe },
2538     { 0xfe, 0xed, 0xfa, 0xcf },
2539     { 0xfe, 0xed, 0xfa, 0xce }
2540   };
2541
2542   f = fopen (prog_name, "rb");
2543   if (f == NULL)
2544     return false;
2545   if (fread (buf, sizeof (buf), 1, f) != 1)
2546     buf[0] = 0;
2547   fclose (f);
2548
2549   if (memcmp (buf, elfmagic, sizeof (elfmagic)) == 0
2550       || memcmp (buf, coffmagic, sizeof (coffmagic)) == 0
2551       || memcmp (buf, coffmagic_x64, sizeof (coffmagic_x64)) == 0)
2552     return true;
2553   for (i = 0; i < 4; i++)
2554     if (memcmp (buf, machomagic[i], sizeof (machomagic[i])) == 0)
2555       return true;
2556
2557   return false;
2558 }
2559
2560 /* Generic version to scan the name list of the loaded program for
2561    the symbols g++ uses for static constructors and destructors.  */
2562
2563 static void
2564 scan_prog_file (const char *prog_name, scanpass which_pass,
2565                 scanfilter filter)
2566 {
2567   void (*int_handler) (int);
2568 #ifdef SIGQUIT
2569   void (*quit_handler) (int);
2570 #endif
2571   char *real_nm_argv[4];
2572   const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2573   int argc = 0;
2574   struct pex_obj *pex;
2575   const char *errmsg;
2576   int err;
2577   char *p, buf[1024];
2578   FILE *inf;
2579   int found_lto = 0;
2580
2581   if (which_pass == PASS_SECOND)
2582     return;
2583
2584   /* LTO objects must be in a known format.  This check prevents
2585      us from accepting an archive containing LTO objects, which
2586      gcc cannnot currently handle.  */
2587   if (which_pass == PASS_LTOINFO && !maybe_lto_object_file (prog_name))
2588     return;
2589
2590   /* If we do not have an `nm', complain.  */
2591   if (nm_file_name == 0)
2592     fatal ("cannot find 'nm'");
2593
2594   nm_argv[argc++] = nm_file_name;
2595   if (NM_FLAGS[0] != '\0')
2596     nm_argv[argc++] = NM_FLAGS;
2597
2598   nm_argv[argc++] = prog_name;
2599   nm_argv[argc++] = (char *) 0;
2600
2601   /* Trace if needed.  */
2602   if (vflag)
2603     {
2604       const char **p_argv;
2605       const char *str;
2606
2607       for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2608         fprintf (stderr, " %s", str);
2609
2610       fprintf (stderr, "\n");
2611     }
2612
2613   fflush (stdout);
2614   fflush (stderr);
2615
2616   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2617   if (pex == NULL)
2618     fatal_perror ("pex_init failed");
2619
2620   errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, HOST_BIT_BUCKET,
2621                     &err);
2622   if (errmsg != NULL)
2623     {
2624       if (err != 0)
2625         {
2626           errno = err;
2627           fatal_perror (errmsg);
2628         }
2629       else
2630         fatal (errmsg);
2631     }
2632
2633   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2634 #ifdef SIGQUIT
2635   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2636 #endif
2637
2638   inf = pex_read_output (pex, 0);
2639   if (inf == NULL)
2640     fatal_perror ("can't open nm output");
2641
2642   if (debug)
2643     {
2644       if (which_pass == PASS_LTOINFO)
2645         fprintf (stderr, "\nnm output with LTO info marker symbol.\n");
2646       else
2647         fprintf (stderr, "\nnm output with constructors/destructors.\n");
2648     }
2649
2650   /* Read each line of nm output.  */
2651   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2652     {
2653       int ch, ch2;
2654       char *name, *end;
2655
2656       if (debug)
2657         fprintf (stderr, "\t%s\n", buf);
2658
2659       if (which_pass == PASS_LTOINFO)
2660         {
2661           if (found_lto)
2662             continue;
2663
2664           /* Look for the LTO info marker symbol, and add filename to
2665              the LTO objects list if found.  */
2666           for (p = buf; (ch = *p) != '\0' && ch != '\n'; p++)
2667             if (ch == ' '  && p[1] == '_' && p[2] == '_'
2668                 && (strncmp (p + (p[3] == '_' ? 2 : 1), "__gnu_lto_v1", 12) == 0)
2669                 && ISSPACE (p[p[3] == '_' ? 14 : 13]))
2670               {
2671                 add_lto_object (&lto_objects, prog_name);
2672
2673                 /* We need to read all the input, so we can't just
2674                    return here.  But we can avoid useless work.  */
2675                 found_lto = 1;
2676
2677                 break;
2678               }
2679
2680           continue;
2681         }
2682
2683       /* If it contains a constructor or destructor name, add the name
2684          to the appropriate list unless this is a kind of symbol we're
2685          not supposed to even consider.  */
2686
2687       for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2688         if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2689           break;
2690
2691       if (ch != '_')
2692         continue;
2693
2694       name = p;
2695       /* Find the end of the symbol name.
2696          Do not include `|', because Encore nm can tack that on the end.  */
2697       for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2698            end++)
2699         continue;
2700
2701
2702       *end = '\0';
2703       switch (is_ctor_dtor (name))
2704         {
2705         case SYM_CTOR:
2706           if (! (filter & SCAN_CTOR))
2707             break;
2708           if (which_pass != PASS_LIB)
2709             add_to_list (&constructors, name);
2710           break;
2711
2712         case SYM_DTOR:
2713           if (! (filter & SCAN_DTOR))
2714             break;
2715           if (which_pass != PASS_LIB)
2716             add_to_list (&destructors, name);
2717           break;
2718
2719         case SYM_INIT:
2720           if (! (filter & SCAN_INIT))
2721             break;
2722           if (which_pass != PASS_LIB)
2723             fatal ("init function found in object %s", prog_name);
2724 #ifndef LD_INIT_SWITCH
2725           add_to_list (&constructors, name);
2726 #endif
2727           break;
2728
2729         case SYM_FINI:
2730           if (! (filter & SCAN_FINI))
2731             break;
2732           if (which_pass != PASS_LIB)
2733             fatal ("fini function found in object %s", prog_name);
2734 #ifndef LD_FINI_SWITCH
2735           add_to_list (&destructors, name);
2736 #endif
2737           break;
2738
2739         case SYM_DWEH:
2740           if (! (filter & SCAN_DWEH))
2741             break;
2742           if (which_pass != PASS_LIB)
2743             add_to_list (&frame_tables, name);
2744           break;
2745
2746         default:                /* not a constructor or destructor */
2747           continue;
2748         }
2749     }
2750
2751   if (debug)
2752     fprintf (stderr, "\n");
2753
2754   do_wait (nm_file_name, pex);
2755
2756   signal (SIGINT,  int_handler);
2757 #ifdef SIGQUIT
2758   signal (SIGQUIT, quit_handler);
2759 #endif
2760 }
2761
2762 #ifdef LDD_SUFFIX
2763
2764 /* Use the List Dynamic Dependencies program to find shared libraries that
2765    the output file depends upon and their initialization/finalization
2766    routines, if any.  */
2767
2768 static void
2769 scan_libraries (const char *prog_name)
2770 {
2771   static struct head libraries;         /* list of shared libraries found */
2772   struct id *list;
2773   void (*int_handler) (int);
2774 #ifdef SIGQUIT
2775   void (*quit_handler) (int);
2776 #endif
2777   char *real_ldd_argv[4];
2778   const char **ldd_argv = CONST_CAST2 (const char **, char **, real_ldd_argv);
2779   int argc = 0;
2780   struct pex_obj *pex;
2781   const char *errmsg;
2782   int err;
2783   char buf[1024];
2784   FILE *inf;
2785
2786   /* If we do not have an `ldd', complain.  */
2787   if (ldd_file_name == 0)
2788     {
2789       error ("cannot find 'ldd'");
2790       return;
2791     }
2792
2793   ldd_argv[argc++] = ldd_file_name;
2794   ldd_argv[argc++] = prog_name;
2795   ldd_argv[argc++] = (char *) 0;
2796
2797   /* Trace if needed.  */
2798   if (vflag)
2799     {
2800       const char **p_argv;
2801       const char *str;
2802
2803       for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2804         fprintf (stderr, " %s", str);
2805
2806       fprintf (stderr, "\n");
2807     }
2808
2809   fflush (stdout);
2810   fflush (stderr);
2811
2812   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2813   if (pex == NULL)
2814     fatal_perror ("pex_init failed");
2815
2816   errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2817   if (errmsg != NULL)
2818     {
2819       if (err != 0)
2820         {
2821           errno = err;
2822           fatal_perror (errmsg);
2823         }
2824       else
2825         fatal (errmsg);
2826     }
2827
2828   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2829 #ifdef SIGQUIT
2830   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2831 #endif
2832
2833   inf = pex_read_output (pex, 0);
2834   if (inf == NULL)
2835     fatal_perror ("can't open ldd output");
2836
2837   if (debug)
2838     notice ("\nldd output with constructors/destructors.\n");
2839
2840   /* Read each line of ldd output.  */
2841   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2842     {
2843       int ch2;
2844       char *name, *end, *p = buf;
2845
2846       /* Extract names of libraries and add to list.  */
2847       PARSE_LDD_OUTPUT (p);
2848       if (p == 0)
2849         continue;
2850
2851       name = p;
2852       if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2853         fatal ("dynamic dependency %s not found", buf);
2854
2855       /* Find the end of the symbol name.  */
2856       for (end = p;
2857            (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2858            end++)
2859         continue;
2860       *end = '\0';
2861
2862       if (access (name, R_OK) == 0)
2863         add_to_list (&libraries, name);
2864       else
2865         fatal ("unable to open dynamic dependency '%s'", buf);
2866
2867       if (debug)
2868         fprintf (stderr, "\t%s\n", buf);
2869     }
2870   if (debug)
2871     fprintf (stderr, "\n");
2872
2873   do_wait (ldd_file_name, pex);
2874
2875   signal (SIGINT,  int_handler);
2876 #ifdef SIGQUIT
2877   signal (SIGQUIT, quit_handler);
2878 #endif
2879
2880   /* Now iterate through the library list adding their symbols to
2881      the list.  */
2882   for (list = libraries.first; list; list = list->next)
2883     scan_prog_file (list->name, PASS_LIB, SCAN_ALL);
2884 }
2885
2886 #endif /* LDD_SUFFIX */
2887
2888 #endif /* OBJECT_FORMAT_NONE */
2889
2890 \f
2891 /*
2892  * COFF specific stuff.
2893  */
2894
2895 #ifdef OBJECT_FORMAT_COFF
2896
2897 #if defined (EXTENDED_COFF)
2898
2899 #   define GCC_SYMBOLS(X)       (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2900 #   define GCC_SYMENT           SYMR
2901 #   define GCC_OK_SYMBOL(X)     ((X).st == stProc || (X).st == stGlobal)
2902 #   define GCC_SYMINC(X)        (1)
2903 #   define GCC_SYMZERO(X)       (SYMHEADER(X).isymMax)
2904 #   define GCC_CHECK_HDR(X)     (PSYMTAB(X) != 0)
2905
2906 #else
2907
2908 #   define GCC_SYMBOLS(X)       (HEADER(ldptr).f_nsyms)
2909 #   define GCC_SYMENT           SYMENT
2910 #   if defined (C_WEAKEXT)
2911 #     define GCC_OK_SYMBOL(X) \
2912        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2913         ((X).n_scnum > N_UNDEF) && \
2914         (aix64_flag \
2915          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2916              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2917 #     define GCC_UNDEF_SYMBOL(X) \
2918        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2919         ((X).n_scnum == N_UNDEF))
2920 #   else
2921 #     define GCC_OK_SYMBOL(X) \
2922        (((X).n_sclass == C_EXT) && \
2923         ((X).n_scnum > N_UNDEF) && \
2924         (aix64_flag \
2925          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2926              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2927 #     define GCC_UNDEF_SYMBOL(X) \
2928        (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2929 #   endif
2930 #   define GCC_SYMINC(X)        ((X).n_numaux+1)
2931 #   define GCC_SYMZERO(X)       0
2932
2933 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2934 #if TARGET_AIX_VERSION >= 51
2935 #   define GCC_CHECK_HDR(X) \
2936      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2937       || (HEADER (X).f_magic == 0767 && aix64_flag))
2938 #else
2939 #   define GCC_CHECK_HDR(X) \
2940      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2941       || (HEADER (X).f_magic == 0757 && aix64_flag))
2942 #endif
2943
2944 #endif
2945
2946 #ifdef COLLECT_EXPORT_LIST
2947 /* Array of standard AIX libraries which should not
2948    be scanned for ctors/dtors.  */
2949 static const char *const aix_std_libs[] = {
2950   "/unix",
2951   "/lib/libc.a",
2952   "/lib/libm.a",
2953   "/lib/libc_r.a",
2954   "/lib/libm_r.a",
2955   "/usr/lib/libc.a",
2956   "/usr/lib/libm.a",
2957   "/usr/lib/libc_r.a",
2958   "/usr/lib/libm_r.a",
2959   "/usr/lib/threads/libc.a",
2960   "/usr/ccs/lib/libc.a",
2961   "/usr/ccs/lib/libm.a",
2962   "/usr/ccs/lib/libc_r.a",
2963   "/usr/ccs/lib/libm_r.a",
2964   NULL
2965 };
2966
2967 /* This function checks the filename and returns 1
2968    if this name matches the location of a standard AIX library.  */
2969 static int ignore_library (const char *);
2970 static int
2971 ignore_library (const char *name)
2972 {
2973   const char *const *p;
2974   size_t length;
2975
2976   if (target_system_root[0] != '\0')
2977     {
2978       length = strlen (target_system_root);
2979       if (strncmp (name, target_system_root, length) != 0)
2980         return 0;
2981       name += length;
2982     }
2983   for (p = &aix_std_libs[0]; *p != NULL; ++p)
2984     if (strcmp (name, *p) == 0)
2985       return 1;
2986   return 0;
2987 }
2988 #endif /* COLLECT_EXPORT_LIST */
2989
2990 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2991 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2992 #endif
2993
2994 /* COFF version to scan the name list of the loaded program for
2995    the symbols g++ uses for static constructors and destructors.  */
2996
2997 static void
2998 scan_prog_file (const char *prog_name, scanpass which_pass,
2999                 scanfilter filter)
3000 {
3001   LDFILE *ldptr = NULL;
3002   int sym_index, sym_count;
3003   int is_shared = 0;
3004
3005   if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
3006     return;
3007
3008 #ifdef COLLECT_EXPORT_LIST
3009   /* We do not need scanning for some standard C libraries.  */
3010   if (which_pass == PASS_FIRST && ignore_library (prog_name))
3011     return;
3012
3013   /* On AIX we have a loop, because there is not much difference
3014      between an object and an archive. This trick allows us to
3015      eliminate scan_libraries() function.  */
3016   do
3017     {
3018 #endif
3019       /* Some platforms (e.g. OSF4) declare ldopen as taking a
3020          non-const char * filename parameter, even though it will not
3021          modify that string.  So we must cast away const-ness here,
3022          using CONST_CAST to prevent complaints from -Wcast-qual.  */
3023       if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
3024         {
3025           if (! MY_ISCOFF (HEADER (ldptr).f_magic))
3026             fatal ("%s: not a COFF file", prog_name);
3027
3028           if (GCC_CHECK_HDR (ldptr))
3029             {
3030               sym_count = GCC_SYMBOLS (ldptr);
3031               sym_index = GCC_SYMZERO (ldptr);
3032
3033 #ifdef COLLECT_EXPORT_LIST
3034               /* Is current archive member a shared object?  */
3035               is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
3036 #endif
3037
3038               while (sym_index < sym_count)
3039                 {
3040                   GCC_SYMENT symbol;
3041
3042                   if (ldtbread (ldptr, sym_index, &symbol) <= 0)
3043                     break;
3044                   sym_index += GCC_SYMINC (symbol);
3045
3046                   if (GCC_OK_SYMBOL (symbol))
3047                     {
3048                       char *name;
3049
3050                       if ((name = ldgetname (ldptr, &symbol)) == NULL)
3051                         continue;               /* Should never happen.  */
3052
3053 #ifdef XCOFF_DEBUGGING_INFO
3054                       /* All AIX function names have a duplicate entry
3055                          beginning with a dot.  */
3056                       if (*name == '.')
3057                         ++name;
3058 #endif
3059
3060                       switch (is_ctor_dtor (name))
3061                         {
3062                         case SYM_CTOR:
3063                           if (! (filter & SCAN_CTOR))
3064                             break;
3065                           if (! is_shared)
3066                             add_to_list (&constructors, name);
3067 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3068                           if (which_pass == PASS_OBJ)
3069                             add_to_list (&exports, name);
3070 #endif
3071                           break;
3072
3073                         case SYM_DTOR:
3074                           if (! (filter & SCAN_DTOR))
3075                             break;
3076                           if (! is_shared)
3077                             add_to_list (&destructors, name);
3078 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3079                           if (which_pass == PASS_OBJ)
3080                             add_to_list (&exports, name);
3081 #endif
3082                           break;
3083
3084 #ifdef COLLECT_EXPORT_LIST
3085                         case SYM_INIT:
3086                           if (! (filter & SCAN_INIT))
3087                             break;
3088 #ifndef LD_INIT_SWITCH
3089                           if (is_shared)
3090                             add_to_list (&constructors, name);
3091 #endif
3092                           break;
3093
3094                         case SYM_FINI:
3095                           if (! (filter & SCAN_FINI))
3096                             break;
3097 #ifndef LD_INIT_SWITCH
3098                           if (is_shared)
3099                             add_to_list (&destructors, name);
3100 #endif
3101                           break;
3102 #endif
3103
3104                         case SYM_DWEH:
3105                           if (! (filter & SCAN_DWEH))
3106                             break;
3107                           if (! is_shared)
3108                             add_to_list (&frame_tables, name);
3109 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3110                           if (which_pass == PASS_OBJ)
3111                             add_to_list (&exports, name);
3112 #endif
3113                           break;
3114
3115                         default:        /* not a constructor or destructor */
3116 #ifdef COLLECT_EXPORT_LIST
3117                           /* Explicitly export all global symbols when
3118                              building a shared object on AIX, but do not
3119                              re-export symbols from another shared object
3120                              and do not export symbols if the user
3121                              provides an explicit export list.  */
3122                           if (shared_obj && !is_shared
3123                               && which_pass == PASS_OBJ && !export_flag)
3124                             add_to_list (&exports, name);
3125 #endif
3126                           continue;
3127                         }
3128
3129                       if (debug)
3130 #if !defined(EXTENDED_COFF)
3131                         fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
3132                                  symbol.n_scnum, symbol.n_sclass,
3133                                  (symbol.n_type ? "0" : ""), symbol.n_type,
3134                                  name);
3135 #else
3136                         fprintf (stderr,
3137                                  "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
3138                                  symbol.iss, (long) symbol.value, symbol.index, name);
3139 #endif
3140                     }
3141                 }
3142             }
3143 #ifdef COLLECT_EXPORT_LIST
3144           else
3145             {
3146               /* If archive contains both 32-bit and 64-bit objects,
3147                  we want to skip objects in other mode so mismatch normal.  */
3148               if (debug)
3149                 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
3150                          prog_name, HEADER (ldptr).f_magic, aix64_flag);
3151             }
3152 #endif
3153         }
3154       else
3155         {
3156           fatal ("%s: cannot open as COFF file", prog_name);
3157         }
3158 #ifdef COLLECT_EXPORT_LIST
3159       /* On AIX loop continues while there are more members in archive.  */
3160     }
3161   while (ldclose (ldptr) == FAILURE);
3162 #else
3163   /* Otherwise we simply close ldptr.  */
3164   (void) ldclose(ldptr);
3165 #endif
3166 }
3167 #endif /* OBJECT_FORMAT_COFF */
3168
3169 #ifdef COLLECT_EXPORT_LIST
3170 /* Given a library name without "lib" prefix, this function
3171    returns a full library name including a path.  */
3172 static char *
3173 resolve_lib_name (const char *name)
3174 {
3175   char *lib_buf;
3176   int i, j, l = 0;
3177   /* Library extensions for AIX dynamic linking.  */
3178   const char * const libexts[2] = {"a", "so"};
3179
3180   for (i = 0; libpaths[i]; i++)
3181     if (libpaths[i]->max_len > l)
3182       l = libpaths[i]->max_len;
3183
3184   lib_buf = XNEWVEC (char, l + strlen(name) + 10);
3185
3186   for (i = 0; libpaths[i]; i++)
3187     {
3188       struct prefix_list *list = libpaths[i]->plist;
3189       for (; list; list = list->next)
3190         {
3191           /* The following lines are needed because path_prefix list
3192              may contain directories both with trailing '/' and
3193              without it.  */
3194           const char *p = "";
3195           if (list->prefix[strlen(list->prefix)-1] != '/')
3196             p = "/";
3197           for (j = 0; j < 2; j++)
3198             {
3199               sprintf (lib_buf, "%s%slib%s.%s",
3200                        list->prefix, p, name,
3201                        libexts[(j + aixrtl_flag) % 2]);
3202               if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
3203               if (file_exists (lib_buf))
3204                 {
3205                   if (debug) fprintf (stderr, "found: %s\n", lib_buf);
3206                   return (lib_buf);
3207                 }
3208             }
3209         }
3210     }
3211   if (debug)
3212     fprintf (stderr, "not found\n");
3213   else
3214     fatal ("library lib%s not found", name);
3215   return (NULL);
3216 }
3217 #endif /* COLLECT_EXPORT_LIST */