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