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