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