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