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