Re: Refactor copying decl section names
[official-gcc.git] / gcc / collect2.c
blob3a43a5a61aaaed91b63decc3b803a5413abd6c65
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992-2020 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).
8 This file is part of GCC.
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.
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.
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/>. */
25 /* Build tables of static constructors and destructors and run ld. */
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"
36 /* TARGET_64BIT may be defined to use driver specific functionality. */
37 #undef TARGET_64BIT
38 #define TARGET_64BIT TARGET_64BIT_DEFAULT
40 #ifndef LIBRARY_PATH_ENV
41 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
42 #endif
44 #define COLLECT
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"
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. */
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
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. */
76 #if !defined (OBJECT_FORMAT_COFF)
77 #define OBJECT_FORMAT_NONE
78 #endif
80 #ifdef OBJECT_FORMAT_COFF
82 #ifndef CROSS_DIRECTORY_STRUCTURE
83 #include <a.out.h>
84 #include <ar.h>
86 #ifdef UMAX
87 #include <sgs.h>
88 #endif
90 /* Many versions of ldfcn.h define these. */
91 #ifdef FREAD
92 #undef FREAD
93 #undef FWRITE
94 #endif
96 #include <ldfcn.h>
97 #endif
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. */
104 #ifndef MY_ISCOFF
105 #define MY_ISCOFF(X) ISCOFF (X)
106 #endif
108 #endif /* OBJECT_FORMAT_COFF */
110 #ifdef OBJECT_FORMAT_NONE
112 /* Default flags to pass to nm. */
113 #ifndef NM_FLAGS
114 #define NM_FLAGS "-n"
115 #endif
117 #endif /* OBJECT_FORMAT_NONE */
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
126 /* This must match tree.h. */
127 #define DEFAULT_INIT_PRIORITY 65535
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
138 #ifdef LDD_SUFFIX
139 #define SCAN_LIBRARIES
140 #endif
142 #ifndef SHLIB_SUFFIX
143 #define SHLIB_SUFFIX ".so"
144 #endif
146 #ifdef USE_COLLECT2
147 int do_collecting = 1;
148 #else
149 int do_collecting = 0;
150 #endif
152 /* Cook up an always defined indication of whether we proceed the
153 "EXPORT_LIST" way. */
155 #ifdef COLLECT_EXPORT_LIST
156 #define DO_COLLECT_EXPORT_LIST 1
157 #else
158 #define DO_COLLECT_EXPORT_LIST 0
159 #endif
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;
165 /* Linked lists of constructor and destructor names. */
167 struct id
169 struct id *next;
170 int sequence;
171 char name[1];
174 struct head
176 struct id *first;
177 struct id *last;
178 int number;
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
191 enum lto_mode_d {
192 LTO_MODE_NONE, /* Not doing LTO. */
193 LTO_MODE_LTO, /* Normal LTO. */
194 LTO_MODE_WHOPR /* WHOPR. */
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
204 bool helpflag; /* true if --help */
206 static int shared_obj; /* true if -shared */
207 static int static_obj; /* true if -static */
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 */
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
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 */
238 bool at_file_supplied; /* Whether to use @file arguments */
240 struct obstack temporary_obstack;
241 char * temporary_firstobj;
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
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;
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
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(). */
272 struct lto_object
274 const char *name; /* Name of object file. */
275 struct lto_object *next; /* Next in linked list. */
278 struct lto_object_list
280 struct lto_object *first; /* First list element. */
281 struct lto_object *last; /* Last list element. */
284 static struct lto_object_list lto_objects;
286 /* Special kinds of symbols that a name may denote. */
288 enum symkind {
289 SYM_REGULAR = 0, /* nothing special */
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
300 const char tool_name[] = "collect2";
302 static symkind is_ctor_dtor (const char *);
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);
334 /* Enumerations describing which pass this is for scanning the
335 program file ... */
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 */
345 /* ... and which kinds of symbols are to be considered. */
347 enum scanfilter_masks {
348 SCAN_NOTHING = 0,
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
360 /* This type is used for parameters and variables which hold
361 combinations of the flags in enum scanfilter_masks. */
362 typedef int scanfilter;
364 /* Scan the name list of the loaded program for the symbols g++ uses for
365 static constructors and destructors.
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.
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__. */
378 static void scan_prog_file (const char *, scanpass, scanfilter);
381 /* Delete tempfiles and exit function. */
383 void
384 tool_cleanup (bool from_signal)
386 /* maybe_unlink may call notice, which is not signal safe. */
387 if (from_signal)
388 verbose = false;
390 if (c_file != 0 && c_file[0])
391 maybe_unlink (c_file);
393 if (o_file != 0 && o_file[0])
394 maybe_unlink (o_file);
396 #ifdef COLLECT_EXPORT_LIST
397 if (export_file != 0 && export_file[0])
398 maybe_unlink (export_file);
399 #endif
401 if (lto_o_files)
402 maybe_unlink_list (lto_o_files);
405 static void
406 collect_atexit (void)
408 tool_cleanup (false);
411 static void
412 handler (int signo)
414 tool_cleanup (true);
416 signal (signo, SIG_DFL);
417 raise (signo);
419 /* Notify user of a non-error, without translating the format string. */
420 void
421 notice_translated (const char *cmsgid, ...)
423 va_list ap;
425 va_start (ap, cmsgid);
426 vfprintf (stderr, cmsgid, ap);
427 va_end (ap);
431 file_exists (const char *name)
433 return access (name, R_OK) == 0;
436 /* Parse a reasonable subset of shell quoting syntax. */
438 static char *
439 extract_string (const char **pp)
441 const char *p = *pp;
442 int backquote = 0;
443 int inside = 0;
445 for (;;)
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);
463 obstack_1grow (&temporary_obstack, '\0');
464 *pp = p;
465 return XOBFINISH (&temporary_obstack, char *);
468 /* Return the kind of symbol denoted by name S. */
470 static symkind
471 is_ctor_dtor (const char *s)
473 struct names { const char *const name; const int len; symkind ret;
474 const int two_underscores; };
476 const struct names *p;
477 int ch;
478 const char *orig_s = s;
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 }
502 while ((ch = *s) == '_')
503 ++s;
505 if (s == orig_s)
506 return SYM_REGULAR;
508 for (p = &special[0]; p->len > 0; p++)
510 if (ch == p->name[0]
511 && (!p->two_underscores || ((s - orig_s) >= 2))
512 && strncmp (s, p->name, p->len) == 0)
514 return p->ret;
517 return SYM_REGULAR;
520 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
521 and one from the PATH variable. */
523 static struct path_prefix cpath, path;
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. */
529 static const char *const target_machine = TARGET_MACHINE;
530 #endif
532 /* Search for NAME using prefix list PPREFIX. We only look for executable
533 files.
535 Return 0 if not found, otherwise return its name, allocated with malloc. */
537 #ifdef OBJECT_FORMAT_NONE
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. */
543 static void
544 add_lto_object (struct lto_object_list *list, const char *name)
546 struct lto_object *n = XNEW (struct lto_object);
547 n->name = name;
548 n->next = NULL;
550 if (list->last)
551 list->last->next = n;
552 else
553 list->first = n;
555 list->last = n;
557 #endif /* OBJECT_FORMAT_NONE */
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.
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. */
587 static void
588 maybe_run_lto_and_relink (char **lto_ld_argv, char **object_lst,
589 const char **object, bool force)
591 const char **object_file = CONST_CAST2 (const char **, char **, object_lst);
593 int num_lto_c_args = 1; /* Allow space for the terminating NULL. */
595 while (object_file < object)
597 /* If file contains LTO info, add it to the list of LTO objects. */
598 scan_prog_file (*object_file++, PASS_LTOINFO, SCAN_ALL);
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++;
606 if (lto_objects.first)
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;
621 if (!lto_wrapper)
622 fatal_error (input_location, "environment variable "
623 "%<COLLECT_LTO_WRAPPER%> must be set");
625 num_lto_c_args++;
627 /* There is at least one object file containing LTO info,
628 so we need to run the LTO back end and relink.
630 To do so we build updated ld arguments with first
631 LTO object replaced by all partitions and other LTO
632 objects removed. */
634 lto_c_argv = (char **) xcalloc (sizeof (char *), num_lto_c_args);
635 lto_c_ptr = CONST_CAST2 (const char **, char **, lto_c_argv);
637 *lto_c_ptr++ = lto_wrapper;
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;
643 *lto_c_ptr = NULL;
645 /* Run the LTO back end. */
646 pex = collect_execute (prog, lto_c_argv, NULL, NULL, PEX_SEARCH,
647 at_file_supplied, NULL);
649 int c;
650 FILE *stream;
651 size_t i;
652 char *start, *end;
654 stream = pex_read_output (pex, 0);
655 gcc_assert (stream);
657 num_files = 0;
658 while ((c = getc (stream)) != EOF)
660 obstack_1grow (&temporary_obstack, c);
661 if (c == '\n')
662 ++num_files;
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)
673 end = start;
674 while (*end != '\n')
675 ++end;
676 *end = '\0';
678 lto_o_files[i] = xstrdup (start);
680 start = end + 1;
683 obstack_free (&temporary_obstack, temporary_firstobj);
685 do_wait (prog, pex);
686 pex = NULL;
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++)
692 out_lto_ld_argv = XCNEWVEC (char *, num_files + lto_ld_argv_size + 1);
693 out_lto_ld_argv_size = 0;
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. */
699 /* Copy all arguments until we find first LTO file. */
700 p = lto_ld_argv;
701 while (*p != NULL)
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++;
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++;
716 /* ... and copy the rest. */
717 while (*p != NULL)
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++;
726 out_lto_ld_argv[out_lto_ld_argv_size++] = 0;
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 NULL);
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);
737 maybe_unlink_list (lto_o_files);
739 else if (force)
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, NULL);
744 /* No LTO objects were found, so no new temp file. */
745 post_ld_pass (/*temp_file*/false);
747 else
748 post_ld_pass (false); /* No LTO objects were found, no temp file. */
750 /* Entry point for linker invoation. Called from main in collect2.c.
751 LD_ARGV is an array of arguments for the linker. */
753 static void
754 do_link (char **ld_argv)
756 struct pex_obj *pex;
757 const char *prog = "ld";
758 pex = collect_execute (prog, ld_argv, NULL, NULL,
759 PEX_LAST | PEX_SEARCH,
760 HAVE_GNU_LD && at_file_supplied, NULL);
761 int ret = collect_wait (prog, pex);
762 if (ret)
764 error ("ld returned %d exit status", ret);
765 exit (ret);
767 else
769 /* We have just successfully produced an output file, so assume that we
770 may unlink it if need be for now on. */
771 may_unlink_output_file = true;
775 /* Main program. */
778 main (int argc, char **argv)
780 enum linker_select
782 USE_DEFAULT_LD,
783 USE_PLUGIN_LD,
784 USE_GOLD_LD,
785 USE_BFD_LD,
786 USE_LLD_LD,
787 USE_LD_MAX
788 } selected_linker = USE_DEFAULT_LD;
789 static const char *const ld_suffixes[USE_LD_MAX] =
791 "ld",
792 PLUGIN_LD_SUFFIX,
793 "ld.gold",
794 "ld.bfd",
795 "ld.lld"
797 static const char *const real_ld_suffix = "real-ld";
798 static const char *const collect_ld_suffix = "collect-ld";
799 static const char *const nm_suffix = "nm";
800 static const char *const gnm_suffix = "gnm";
801 #ifdef LDD_SUFFIX
802 static const char *const ldd_suffix = LDD_SUFFIX;
803 #endif
804 static const char *const strip_suffix = "strip";
805 static const char *const gstrip_suffix = "gstrip";
807 const char *full_ld_suffixes[USE_LD_MAX];
808 #ifdef CROSS_DIRECTORY_STRUCTURE
809 /* If we look for a program in the compiler directories, we just use
810 the short name, since these directories are already system-specific.
811 But it we look for a program in the system directories, we need to
812 qualify the program name with the target machine. */
814 const char *const full_nm_suffix =
815 concat (target_machine, "-", nm_suffix, NULL);
816 const char *const full_gnm_suffix =
817 concat (target_machine, "-", gnm_suffix, NULL);
818 #ifdef LDD_SUFFIX
819 const char *const full_ldd_suffix =
820 concat (target_machine, "-", ldd_suffix, NULL);
821 #endif
822 const char *const full_strip_suffix =
823 concat (target_machine, "-", strip_suffix, NULL);
824 const char *const full_gstrip_suffix =
825 concat (target_machine, "-", gstrip_suffix, NULL);
826 #else
827 #ifdef LDD_SUFFIX
828 const char *const full_ldd_suffix = ldd_suffix;
829 #endif
830 const char *const full_nm_suffix = nm_suffix;
831 const char *const full_gnm_suffix = gnm_suffix;
832 const char *const full_strip_suffix = strip_suffix;
833 const char *const full_gstrip_suffix = gstrip_suffix;
834 #endif /* CROSS_DIRECTORY_STRUCTURE */
836 const char *arg;
837 FILE *outf;
838 #ifdef COLLECT_EXPORT_LIST
839 FILE *exportf;
840 #endif
841 const char *ld_file_name;
842 const char *p;
843 char **c_argv;
844 const char **c_ptr;
845 char **ld1_argv;
846 const char **ld1;
847 bool use_plugin = false;
848 bool use_collect_ld = false;
850 /* The kinds of symbols we will have to consider when scanning the
851 outcome of a first pass link. This is ALL to start with, then might
852 be adjusted before getting to the first pass link per se, typically on
853 AIX where we perform an early scan of objects and libraries to fetch
854 the list of global ctors/dtors and make sure they are not garbage
855 collected. */
856 scanfilter ld1_filter = SCAN_ALL;
858 char **ld2_argv;
859 const char **ld2;
860 char **object_lst;
861 const char **object;
862 #ifdef TARGET_AIX_VERSION
863 int object_nbr = argc;
864 #endif
865 int first_file;
866 int num_c_args;
867 char **old_argv;
868 #ifdef COLLECT_EXPORT_LIST
869 bool is_static = false;
870 #endif
871 int i;
873 for (i = 0; i < USE_LD_MAX; i++)
874 full_ld_suffixes[i]
875 #ifdef CROSS_DIRECTORY_STRUCTURE
876 = concat (target_machine, "-", ld_suffixes[i], NULL);
877 #else
878 = ld_suffixes[i];
879 #endif
881 p = argv[0] + strlen (argv[0]);
882 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
883 --p;
884 progname = p;
886 xmalloc_set_program_name (progname);
888 old_argv = argv;
889 expandargv (&argc, &argv);
890 if (argv != old_argv)
891 at_file_supplied = 1;
893 process_args (&argc, argv);
895 num_c_args = argc + 9;
897 #ifndef HAVE_LD_DEMANGLE
898 no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
900 /* Suppress demangling by the real linker, which may be broken. */
901 putenv (xstrdup ("COLLECT_NO_DEMANGLE=1"));
902 #endif
904 #if defined (COLLECT2_HOST_INITIALIZATION)
905 /* Perform system dependent initialization, if necessary. */
906 COLLECT2_HOST_INITIALIZATION;
907 #endif
909 #ifdef SIGCHLD
910 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
911 receive the signal. A different setting is inheritable */
912 signal (SIGCHLD, SIG_DFL);
913 #endif
915 /* Unlock the stdio streams. */
916 unlock_std_streams ();
918 gcc_init_libintl ();
920 diagnostic_initialize (global_dc, 0);
922 if (atexit (collect_atexit) != 0)
923 fatal_error (input_location, "atexit failed");
925 /* Do not invoke xcalloc before this point, since locale needs to be
926 set first, in case a diagnostic is issued. */
928 ld1_argv = XCNEWVEC (char *, argc + 4);
929 ld1 = CONST_CAST2 (const char **, char **, ld1_argv);
930 ld2_argv = XCNEWVEC (char *, argc + 11);
931 ld2 = CONST_CAST2 (const char **, char **, ld2_argv);
932 object_lst = XCNEWVEC (char *, argc);
933 object = CONST_CAST2 (const char **, char **, object_lst);
935 #ifdef DEBUG
936 debug = true;
937 #endif
939 save_temps = false;
940 verbose = false;
942 #ifndef DEFAULT_A_OUT_NAME
943 output_file = "a.out";
944 #else
945 output_file = DEFAULT_A_OUT_NAME;
946 #endif
948 /* Parse command line / environment for flags we want early.
949 This allows the debug flag to be set before functions like find_a_file()
950 are called. */
952 bool no_partition = false;
954 for (i = 1; argv[i] != NULL; i ++)
956 if (! strcmp (argv[i], "-debug"))
957 debug = true;
958 else if (!strncmp (argv[i], "-fno-lto", 8))
959 lto_mode = LTO_MODE_NONE;
960 else if (! strcmp (argv[i], "-plugin"))
962 use_plugin = true;
963 if (selected_linker == USE_DEFAULT_LD)
964 selected_linker = USE_PLUGIN_LD;
966 else if (strcmp (argv[i], "-fuse-ld=bfd") == 0)
967 selected_linker = USE_BFD_LD;
968 else if (strcmp (argv[i], "-fuse-ld=gold") == 0)
969 selected_linker = USE_GOLD_LD;
970 else if (strcmp (argv[i], "-fuse-ld=lld") == 0)
971 selected_linker = USE_LLD_LD;
972 else if (strncmp (argv[i], "-o", 2) == 0)
974 /* Parse the output filename if it's given so that we can make
975 meaningful temp filenames. */
976 if (argv[i][2] == '\0')
977 output_file = argv[i+1];
978 else
979 output_file = &argv[i][2];
982 #ifdef COLLECT_EXPORT_LIST
983 /* These flags are position independent, although their order
984 is important - subsequent flags override earlier ones. */
985 else if (strcmp (argv[i], "-b64") == 0)
986 aix64_flag = 1;
987 /* -bexport:filename always needs the :filename */
988 else if (strncmp (argv[i], "-bE:", 4) == 0
989 || strncmp (argv[i], "-bexport:", 9) == 0)
990 export_flag = 1;
991 else if (strcmp (argv[i], "-brtl") == 0
992 || strcmp (argv[i], "-bsvr4") == 0
993 || strcmp (argv[i], "-G") == 0)
994 aixrtl_flag = 1;
995 else if (strcmp (argv[i], "-bnortl") == 0)
996 aixrtl_flag = 0;
997 else if (strcmp (argv[i], "-blazy") == 0)
998 aixlazy_flag = 1;
999 #endif
1002 obstack_begin (&temporary_obstack, 0);
1003 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
1005 #ifndef HAVE_LD_DEMANGLE
1006 current_demangling_style = auto_demangling;
1007 #endif
1009 /* Now pick up any flags we want early from COLLECT_GCC_OPTIONS
1010 The LTO options are passed here as are other options that might
1011 be unsuitable for ld (e.g. -save-temps). */
1012 p = getenv ("COLLECT_GCC_OPTIONS");
1013 while (p && *p)
1015 const char *q = extract_string (&p);
1016 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1017 num_c_args++;
1018 if (strncmp (q, "-flto-partition=none", 20) == 0)
1019 no_partition = true;
1020 else if (strncmp (q, "-fno-lto", 8) == 0)
1021 lto_mode = LTO_MODE_NONE;
1022 else if (strncmp (q, "-save-temps", 11) == 0)
1023 /* FIXME: Honour =obj. */
1024 save_temps = true;
1026 obstack_free (&temporary_obstack, temporary_firstobj);
1028 verbose = verbose || debug;
1029 save_temps = save_temps || debug;
1030 find_file_set_debug (debug);
1031 if (use_plugin)
1032 lto_mode = LTO_MODE_NONE;
1033 if (no_partition && lto_mode == LTO_MODE_WHOPR)
1034 lto_mode = LTO_MODE_LTO;
1037 /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
1038 -fno-exceptions -w -fno-whole-program */
1039 num_c_args += 6;
1041 c_argv = XCNEWVEC (char *, num_c_args);
1042 c_ptr = CONST_CAST2 (const char **, char **, c_argv);
1044 if (argc < 2)
1045 fatal_error (input_location, "no arguments");
1047 #ifdef SIGQUIT
1048 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1049 signal (SIGQUIT, handler);
1050 #endif
1051 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1052 signal (SIGINT, handler);
1053 #ifdef SIGALRM
1054 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1055 signal (SIGALRM, handler);
1056 #endif
1057 #ifdef SIGHUP
1058 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1059 signal (SIGHUP, handler);
1060 #endif
1061 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1062 signal (SIGSEGV, handler);
1063 #ifdef SIGBUS
1064 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1065 signal (SIGBUS, handler);
1066 #endif
1068 /* Extract COMPILER_PATH and PATH into our prefix list. */
1069 prefix_from_env ("COMPILER_PATH", &cpath);
1070 prefix_from_env ("PATH", &path);
1072 /* Try to discover a valid linker/nm/strip to use. */
1074 /* Maybe we know the right file to use (if not cross). */
1075 ld_file_name = 0;
1076 #ifdef DEFAULT_LINKER
1077 if (selected_linker == USE_BFD_LD || selected_linker == USE_GOLD_LD ||
1078 selected_linker == USE_LLD_LD)
1080 char *linker_name;
1081 # ifdef HOST_EXECUTABLE_SUFFIX
1082 int len = (sizeof (DEFAULT_LINKER)
1083 - sizeof (HOST_EXECUTABLE_SUFFIX));
1084 linker_name = NULL;
1085 if (len > 0)
1087 char *default_linker = xstrdup (DEFAULT_LINKER);
1088 /* Strip HOST_EXECUTABLE_SUFFIX if DEFAULT_LINKER contains
1089 HOST_EXECUTABLE_SUFFIX. */
1090 if (! strcmp (&default_linker[len], HOST_EXECUTABLE_SUFFIX))
1092 default_linker[len] = '\0';
1093 linker_name = concat (default_linker,
1094 &ld_suffixes[selected_linker][2],
1095 HOST_EXECUTABLE_SUFFIX, NULL);
1098 if (linker_name == NULL)
1099 # endif
1100 linker_name = concat (DEFAULT_LINKER,
1101 &ld_suffixes[selected_linker][2],
1102 NULL);
1103 if (access (linker_name, X_OK) == 0)
1104 ld_file_name = linker_name;
1106 if (ld_file_name == 0 && access (DEFAULT_LINKER, X_OK) == 0)
1107 ld_file_name = DEFAULT_LINKER;
1108 if (ld_file_name == 0)
1109 #endif
1110 #ifdef REAL_LD_FILE_NAME
1111 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME, X_OK);
1112 if (ld_file_name == 0)
1113 #endif
1114 /* Search the (target-specific) compiler dirs for ld'. */
1115 ld_file_name = find_a_file (&cpath, real_ld_suffix, X_OK);
1116 /* Likewise for `collect-ld'. */
1117 if (ld_file_name == 0)
1119 ld_file_name = find_a_file (&cpath, collect_ld_suffix, X_OK);
1120 use_collect_ld = ld_file_name != 0;
1122 /* Search the compiler directories for `ld'. We have protection against
1123 recursive calls in find_a_file. */
1124 if (ld_file_name == 0)
1125 ld_file_name = find_a_file (&cpath, ld_suffixes[selected_linker], X_OK);
1126 /* Search the ordinary system bin directories
1127 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1128 if (ld_file_name == 0)
1129 ld_file_name = find_a_file (&path, full_ld_suffixes[selected_linker], X_OK);
1131 #ifdef REAL_NM_FILE_NAME
1132 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME, X_OK);
1133 if (nm_file_name == 0)
1134 #endif
1135 nm_file_name = find_a_file (&cpath, gnm_suffix, X_OK);
1136 if (nm_file_name == 0)
1137 nm_file_name = find_a_file (&path, full_gnm_suffix, X_OK);
1138 if (nm_file_name == 0)
1139 nm_file_name = find_a_file (&cpath, nm_suffix, X_OK);
1140 if (nm_file_name == 0)
1141 nm_file_name = find_a_file (&path, full_nm_suffix, X_OK);
1143 #ifdef LDD_SUFFIX
1144 ldd_file_name = find_a_file (&cpath, ldd_suffix, X_OK);
1145 if (ldd_file_name == 0)
1146 ldd_file_name = find_a_file (&path, full_ldd_suffix, X_OK);
1147 #endif
1149 #ifdef REAL_STRIP_FILE_NAME
1150 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME, X_OK);
1151 if (strip_file_name == 0)
1152 #endif
1153 strip_file_name = find_a_file (&cpath, gstrip_suffix, X_OK);
1154 if (strip_file_name == 0)
1155 strip_file_name = find_a_file (&path, full_gstrip_suffix, X_OK);
1156 if (strip_file_name == 0)
1157 strip_file_name = find_a_file (&cpath, strip_suffix, X_OK);
1158 if (strip_file_name == 0)
1159 strip_file_name = find_a_file (&path, full_strip_suffix, X_OK);
1161 /* Determine the full path name of the C compiler to use. */
1162 c_file_name = getenv ("COLLECT_GCC");
1163 if (c_file_name == 0)
1165 #ifdef CROSS_DIRECTORY_STRUCTURE
1166 c_file_name = concat (target_machine, "-gcc", NULL);
1167 #else
1168 c_file_name = "gcc";
1169 #endif
1172 p = find_a_file (&cpath, c_file_name, X_OK);
1174 /* Here it should be safe to use the system search path since we should have
1175 already qualified the name of the compiler when it is needed. */
1176 if (p == 0)
1177 p = find_a_file (&path, c_file_name, X_OK);
1179 if (p)
1180 c_file_name = p;
1182 *ld1++ = *ld2++ = ld_file_name;
1184 /* Make temp file names. */
1185 if (save_temps)
1187 c_file = concat (output_file, ".cdtor.c", NULL);
1188 o_file = concat (output_file, ".cdtor.o", NULL);
1189 #ifdef COLLECT_EXPORT_LIST
1190 export_file = concat (output_file, ".x", NULL);
1191 #endif
1193 else
1195 c_file = make_temp_file (".cdtor.c");
1196 o_file = make_temp_file (".cdtor.o");
1197 #ifdef COLLECT_EXPORT_LIST
1198 export_file = make_temp_file (".x");
1199 #endif
1201 /* Build the command line to compile the ctor/dtor list. */
1202 *c_ptr++ = c_file_name;
1203 *c_ptr++ = "-x";
1204 *c_ptr++ = "c";
1205 *c_ptr++ = "-c";
1206 *c_ptr++ = "-o";
1207 *c_ptr++ = o_file;
1209 #ifdef COLLECT_EXPORT_LIST
1210 /* Generate a list of directories from LIBPATH. */
1211 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1212 /* Add to this list also two standard directories where
1213 AIX loader always searches for libraries. */
1214 add_prefix (&libpath_lib_dirs, "/lib");
1215 add_prefix (&libpath_lib_dirs, "/usr/lib");
1216 #endif
1218 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1220 AIX support needs to know if -shared has been specified before
1221 parsing commandline arguments. */
1223 p = getenv ("COLLECT_GCC_OPTIONS");
1224 while (p && *p)
1226 const char *q = extract_string (&p);
1227 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1228 *c_ptr++ = xstrdup (q);
1229 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1230 *c_ptr++ = xstrdup (q);
1231 if (strcmp (q, "-shared") == 0)
1232 shared_obj = 1;
1233 if (strcmp (q, "-static") == 0)
1234 static_obj = 1;
1235 if (*q == '-' && q[1] == 'B')
1237 *c_ptr++ = xstrdup (q);
1238 if (q[2] == 0)
1240 q = extract_string (&p);
1241 *c_ptr++ = xstrdup (q);
1244 #ifdef COLLECT_EXPORT_LIST
1245 /* Detect any invocation with -fvisibility. */
1246 if (strncmp (q, "-fvisibility", 12) == 0)
1247 visibility_flag = 1;
1248 #endif
1250 obstack_free (&temporary_obstack, temporary_firstobj);
1251 *c_ptr++ = "-fno-profile-arcs";
1252 *c_ptr++ = "-fno-test-coverage";
1253 *c_ptr++ = "-fno-branch-probabilities";
1254 *c_ptr++ = "-fno-exceptions";
1255 *c_ptr++ = "-w";
1256 *c_ptr++ = "-fno-whole-program";
1258 /* !!! When GCC calls collect2,
1259 it does not know whether it is calling collect2 or ld.
1260 So collect2 cannot meaningfully understand any options
1261 except those ld understands.
1262 If you propose to make GCC pass some other option,
1263 just imagine what will happen if ld is really ld!!! */
1265 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1266 /* After the first file, put in the c++ rt0. */
1268 #ifdef COLLECT_EXPORT_LIST
1269 is_static = static_obj;
1270 #endif
1271 first_file = 1;
1272 while ((arg = *++argv) != (char *) 0)
1274 *ld1++ = *ld2++ = arg;
1276 if (arg[0] == '-')
1278 switch (arg[1])
1280 case 'd':
1281 if (!strcmp (arg, "-debug"))
1283 /* Already parsed. */
1284 ld1--;
1285 ld2--;
1287 if (!strcmp (arg, "-dynamic-linker") && argv[1])
1289 ++argv;
1290 *ld1++ = *ld2++ = *argv;
1292 break;
1294 case 'f':
1295 if (strncmp (arg, "-flto", 5) == 0)
1297 #ifdef ENABLE_LTO
1298 /* Do not pass LTO flag to the linker. */
1299 ld1--;
1300 ld2--;
1301 #else
1302 error ("LTO support has not been enabled in this "
1303 "configuration");
1304 #endif
1306 else if (!use_collect_ld
1307 && strncmp (arg, "-fuse-ld=", 9) == 0)
1309 /* Do not pass -fuse-ld={bfd|gold|lld} to the linker. */
1310 ld1--;
1311 ld2--;
1313 else if (strncmp (arg, "-fno-lto", 8) == 0)
1315 /* Do not pass -fno-lto to the linker. */
1316 ld1--;
1317 ld2--;
1319 #ifdef TARGET_AIX_VERSION
1320 else
1322 /* File containing a list of input files to process. */
1324 FILE *stream;
1325 char buf[MAXPATHLEN + 2];
1326 /* Number of additionnal object files. */
1327 int add_nbr = 0;
1328 /* Maximum of additionnal object files before vector
1329 expansion. */
1330 int add_max = 0;
1331 const char *list_filename = arg + 2;
1333 /* Accept -fFILENAME and -f FILENAME. */
1334 if (*list_filename == '\0' && argv[1])
1336 ++argv;
1337 list_filename = *argv;
1338 *ld1++ = *ld2++ = *argv;
1341 stream = fopen (list_filename, "r");
1342 if (stream == NULL)
1343 fatal_error (input_location, "cannot open %s: %m",
1344 list_filename);
1346 while (fgets (buf, sizeof buf, stream) != NULL)
1348 /* Remove end of line. */
1349 int len = strlen (buf);
1350 if (len >= 1 && buf[len - 1] =='\n')
1351 buf[len - 1] = '\0';
1353 /* Put on object vector.
1354 Note: we only expanse vector here, so we must keep
1355 extra space for remaining arguments. */
1356 if (add_nbr >= add_max)
1358 int pos =
1359 object - CONST_CAST2 (const char **, char **,
1360 object_lst);
1361 add_max = (add_max == 0) ? 16 : add_max * 2;
1362 object_lst = XRESIZEVEC (char *, object_lst,
1363 object_nbr + add_max);
1364 object = CONST_CAST2 (const char **, char **,
1365 object_lst) + pos;
1366 object_nbr += add_max;
1368 *object++ = xstrdup (buf);
1369 add_nbr++;
1371 fclose (stream);
1373 #endif
1374 break;
1376 #ifdef COLLECT_EXPORT_LIST
1377 case 'b':
1378 if (!strcmp (arg, "-bstatic"))
1380 is_static = true;
1382 else if (!strcmp (arg, "-bdynamic") || !strcmp (arg, "-bshared"))
1384 is_static = false;
1386 break;
1387 #endif
1388 case 'l':
1389 if (first_file)
1391 /* place o_file BEFORE this argument! */
1392 first_file = 0;
1393 ld2--;
1394 *ld2++ = o_file;
1395 *ld2++ = arg;
1397 #ifdef COLLECT_EXPORT_LIST
1399 /* Resolving full library name. */
1400 const char *s = resolve_lib_name (arg+2);
1402 /* Saving a full library name. */
1403 add_to_list (&libs, s);
1404 if (is_static)
1405 add_to_list (&static_libs, s);
1407 #endif
1408 break;
1410 #ifdef COLLECT_EXPORT_LIST
1411 /* Saving directories where to search for libraries. */
1412 case 'L':
1413 add_prefix (&cmdline_lib_dirs, arg+2);
1414 break;
1415 #endif
1417 case 'o':
1418 if (arg[2] == '\0')
1419 output_file = *ld1++ = *ld2++ = *++argv;
1420 else
1421 output_file = &arg[2];
1422 break;
1424 case 'r':
1425 if (arg[2] == '\0')
1426 rflag = 1;
1427 break;
1429 case 's':
1430 if (arg[2] == '\0' && do_collecting)
1432 /* We must strip after the nm run, otherwise C++ linking
1433 will not work. Thus we strip in the second ld run, or
1434 else with strip if there is no second ld run. */
1435 strip_flag = 1;
1436 ld1--;
1438 break;
1440 case 'v':
1441 if (arg[2] == '\0')
1442 verbose = true;
1443 break;
1445 case '-':
1446 if (strcmp (arg, "--no-demangle") == 0)
1448 #ifndef HAVE_LD_DEMANGLE
1449 no_demangle = 1;
1450 ld1--;
1451 ld2--;
1452 #endif
1454 else if (strncmp (arg, "--demangle", 10) == 0)
1456 #ifndef HAVE_LD_DEMANGLE
1457 no_demangle = 0;
1458 if (arg[10] == '=')
1460 enum demangling_styles style
1461 = cplus_demangle_name_to_style (arg+11);
1462 if (style == unknown_demangling)
1463 error ("unknown demangling style %qs", arg+11);
1464 else
1465 current_demangling_style = style;
1467 ld1--;
1468 ld2--;
1469 #endif
1471 else if (strncmp (arg, "--sysroot=", 10) == 0)
1472 target_system_root = arg + 10;
1473 else if (strcmp (arg, "--version") == 0)
1474 verbose = true;
1475 else if (strcmp (arg, "--help") == 0)
1476 helpflag = true;
1477 break;
1480 else if ((p = strrchr (arg, '.')) != (char *) 0
1481 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1482 || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1483 || strcmp (p, ".obj") == 0))
1485 if (first_file)
1487 first_file = 0;
1488 if (p[1] == 'o')
1489 *ld2++ = o_file;
1490 else
1492 /* place o_file BEFORE this argument! */
1493 ld2--;
1494 *ld2++ = o_file;
1495 *ld2++ = arg;
1498 if (p[1] == 'o' || p[1] == 'l')
1499 *object++ = arg;
1500 #ifdef COLLECT_EXPORT_LIST
1501 /* libraries can be specified directly, i.e. without -l flag. */
1502 else
1504 /* Saving a full library name. */
1505 add_to_list (&libs, arg);
1506 if (is_static)
1507 add_to_list (&static_libs, arg);
1509 #endif
1513 #ifdef COLLECT_EXPORT_LIST
1514 /* This is added only for debugging purposes. */
1515 if (debug)
1517 fprintf (stderr, "List of libraries:\n");
1518 dump_list (stderr, "\t", libs.first);
1519 fprintf (stderr, "List of statically linked libraries:\n");
1520 dump_list (stderr, "\t", static_libs.first);
1523 /* The AIX linker will discard static constructors in object files if
1524 nothing else in the file is referenced, so look at them first. Unless
1525 we are building a shared object, ignore the eh frame tables, as we
1526 would otherwise reference them all, hence drag all the corresponding
1527 objects even if nothing else is referenced. */
1529 const char **export_object_lst
1530 = CONST_CAST2 (const char **, char **, object_lst);
1532 struct id *list = libs.first;
1534 /* Compute the filter to use from the current one, do scan, then adjust
1535 the "current" filter to remove what we just included here. This will
1536 control whether we need a first pass link later on or not, and what
1537 will remain to be scanned there. */
1539 scanfilter this_filter = ld1_filter;
1540 #if HAVE_AS_REF
1541 if (!shared_obj)
1542 this_filter &= ~SCAN_DWEH;
1543 #endif
1545 /* Scan object files. */
1546 while (export_object_lst < object)
1547 scan_prog_file (*export_object_lst++, PASS_OBJ, this_filter);
1549 /* Scan libraries. */
1550 for (; list; list = list->next)
1551 scan_prog_file (list->name, PASS_FIRST, this_filter);
1553 ld1_filter = ld1_filter & ~this_filter;
1556 if (exports.first)
1558 char *buf = concat ("-bE:", export_file, NULL);
1560 *ld1++ = buf;
1561 *ld2++ = buf;
1563 exportf = fopen (export_file, "w");
1564 if (exportf == (FILE *) 0)
1565 fatal_error (input_location, "fopen %s: %m", export_file);
1566 write_aix_file (exportf, exports.first);
1567 if (fclose (exportf))
1568 fatal_error (input_location, "fclose %s: %m", export_file);
1570 #endif
1572 *c_ptr++ = c_file;
1573 *c_ptr = *ld1 = *object = (char *) 0;
1575 if (verbose)
1576 notice ("collect2 version %s\n", version_string);
1578 if (helpflag)
1580 printf ("Usage: collect2 [options]\n");
1581 printf (" Wrap linker and generate constructor code if needed.\n");
1582 printf (" Options:\n");
1583 printf (" -debug Enable debug output\n");
1584 printf (" --help Display this information\n");
1585 printf (" -v, --version Display this program's version number\n");
1586 printf ("\n");
1587 printf ("Overview: https://gcc.gnu.org/onlinedocs/gccint/Collect2.html\n");
1588 printf ("Report bugs: %s\n", bug_report_url);
1589 printf ("\n");
1592 if (debug)
1594 const char *ptr;
1595 fprintf (stderr, "ld_file_name = %s\n",
1596 (ld_file_name ? ld_file_name : "not found"));
1597 fprintf (stderr, "c_file_name = %s\n",
1598 (c_file_name ? c_file_name : "not found"));
1599 fprintf (stderr, "nm_file_name = %s\n",
1600 (nm_file_name ? nm_file_name : "not found"));
1601 #ifdef LDD_SUFFIX
1602 fprintf (stderr, "ldd_file_name = %s\n",
1603 (ldd_file_name ? ldd_file_name : "not found"));
1604 #endif
1605 fprintf (stderr, "strip_file_name = %s\n",
1606 (strip_file_name ? strip_file_name : "not found"));
1607 fprintf (stderr, "c_file = %s\n",
1608 (c_file ? c_file : "not found"));
1609 fprintf (stderr, "o_file = %s\n",
1610 (o_file ? o_file : "not found"));
1612 ptr = getenv ("COLLECT_GCC_OPTIONS");
1613 if (ptr)
1614 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1616 ptr = getenv ("COLLECT_GCC");
1617 if (ptr)
1618 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1620 ptr = getenv ("COMPILER_PATH");
1621 if (ptr)
1622 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1624 ptr = getenv (LIBRARY_PATH_ENV);
1625 if (ptr)
1626 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1628 fprintf (stderr, "\n");
1631 /* Load the program, searching all libraries and attempting to provide
1632 undefined symbols from repository information.
1634 If -r or they will be run via some other method, do not build the
1635 constructor or destructor list, just return now. */
1637 bool early_exit
1638 = rflag || (! DO_COLLECT_EXPORT_LIST && ! do_collecting);
1640 /* Perform the first pass link now, if we're about to exit or if we need
1641 to scan for things we haven't collected yet before pursuing further.
1643 On AIX, the latter typically includes nothing for shared objects or
1644 frame tables for an executable, out of what the required early scan on
1645 objects and libraries has performed above. In the !shared_obj case, we
1646 expect the relevant tables to be dragged together with their associated
1647 functions from precise cross reference insertions by the compiler. */
1649 if (early_exit || ld1_filter != SCAN_NOTHING)
1650 do_link (ld1_argv);
1652 if (early_exit)
1654 #ifdef COLLECT_EXPORT_LIST
1655 /* Make sure we delete the export file we may have created. */
1656 if (export_file != 0 && export_file[0])
1657 maybe_unlink (export_file);
1658 #endif
1659 if (lto_mode != LTO_MODE_NONE)
1660 maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1661 else
1662 post_ld_pass (/*temp_file*/false);
1664 return 0;
1668 /* Unless we have done it all already, examine the namelist and search for
1669 static constructors and destructors to call. Write the constructor and
1670 destructor tables to a .s file and reload. */
1672 if (ld1_filter != SCAN_NOTHING)
1673 scan_prog_file (output_file, PASS_FIRST, ld1_filter);
1675 #ifdef SCAN_LIBRARIES
1676 scan_libraries (output_file);
1677 #endif
1679 if (debug)
1681 notice_translated (ngettext ("%d constructor found\n",
1682 "%d constructors found\n",
1683 constructors.number),
1684 constructors.number);
1685 notice_translated (ngettext ("%d destructor found\n",
1686 "%d destructors found\n",
1687 destructors.number),
1688 destructors.number);
1689 notice_translated (ngettext ("%d frame table found\n",
1690 "%d frame tables found\n",
1691 frame_tables.number),
1692 frame_tables.number);
1695 /* If the scan exposed nothing of special interest, there's no need to
1696 generate the glue code and relink so return now. */
1698 if (constructors.number == 0 && destructors.number == 0
1699 && frame_tables.number == 0
1700 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1701 /* If we will be running these functions ourselves, we want to emit
1702 stubs into the shared library so that we do not have to relink
1703 dependent programs when we add static objects. */
1704 && ! shared_obj
1705 #endif
1708 /* Do link without additional code generation now if we didn't
1709 do it earlier for scanning purposes. */
1710 if (ld1_filter == SCAN_NOTHING)
1711 do_link (ld1_argv);
1713 if (lto_mode)
1714 maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1716 /* Strip now if it was requested on the command line. */
1717 if (strip_flag)
1719 char **real_strip_argv = XCNEWVEC (char *, 3);
1720 const char ** strip_argv = CONST_CAST2 (const char **, char **,
1721 real_strip_argv);
1723 strip_argv[0] = strip_file_name;
1724 strip_argv[1] = output_file;
1725 strip_argv[2] = (char *) 0;
1726 fork_execute ("strip", real_strip_argv, false, NULL);
1729 #ifdef COLLECT_EXPORT_LIST
1730 maybe_unlink (export_file);
1731 #endif
1732 post_ld_pass (/*temp_file*/false);
1733 return 0;
1736 /* Sort ctor and dtor lists by priority. */
1737 sort_ids (&constructors);
1738 sort_ids (&destructors);
1740 maybe_unlink (output_file);
1741 outf = fopen (c_file, "w");
1742 if (outf == (FILE *) 0)
1743 fatal_error (input_location, "fopen %s: %m", c_file);
1745 write_c_file (outf, c_file);
1747 if (fclose (outf))
1748 fatal_error (input_location, "fclose %s: %m", c_file);
1750 /* Tell the linker that we have initializer and finalizer functions. */
1751 #ifdef LD_INIT_SWITCH
1752 #ifdef COLLECT_EXPORT_LIST
1753 *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1754 #else
1755 *ld2++ = LD_INIT_SWITCH;
1756 *ld2++ = initname;
1757 *ld2++ = LD_FINI_SWITCH;
1758 *ld2++ = fininame;
1759 #endif
1760 #endif
1762 #ifdef COLLECT_EXPORT_LIST
1763 if (shared_obj)
1765 /* If we did not add export flag to link arguments before, add it to
1766 second link phase now. No new exports should have been added. */
1767 if (! exports.first)
1768 *ld2++ = concat ("-bE:", export_file, NULL);
1770 #ifdef TARGET_AIX_VERSION
1771 add_to_list (&exports, aix_shared_initname);
1772 add_to_list (&exports, aix_shared_fininame);
1773 #endif
1775 #ifndef LD_INIT_SWITCH
1776 add_to_list (&exports, initname);
1777 add_to_list (&exports, fininame);
1778 add_to_list (&exports, "_GLOBAL__DI");
1779 add_to_list (&exports, "_GLOBAL__DD");
1780 #endif
1781 exportf = fopen (export_file, "w");
1782 if (exportf == (FILE *) 0)
1783 fatal_error (input_location, "fopen %s: %m", export_file);
1784 write_aix_file (exportf, exports.first);
1785 if (fclose (exportf))
1786 fatal_error (input_location, "fclose %s: %m", export_file);
1788 #endif
1790 /* End of arguments to second link phase. */
1791 *ld2 = (char*) 0;
1793 if (debug)
1795 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1796 output_file, c_file);
1797 write_c_file (stderr, "stderr");
1798 fprintf (stderr, "========== end of c_file\n\n");
1799 #ifdef COLLECT_EXPORT_LIST
1800 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1801 write_aix_file (stderr, exports.first);
1802 fprintf (stderr, "========== end of export_file\n\n");
1803 #endif
1806 /* Assemble the constructor and destructor tables.
1807 Link the tables in with the rest of the program. */
1809 fork_execute ("gcc", c_argv, at_file_supplied, NULL);
1810 #ifdef COLLECT_EXPORT_LIST
1811 /* On AIX we must call link because of possible templates resolution. */
1812 do_link (ld2_argv);
1814 if (lto_mode)
1815 maybe_run_lto_and_relink (ld2_argv, object_lst, object, false);
1816 #else
1817 /* Otherwise, simply call ld because link is already done. */
1818 if (lto_mode)
1819 maybe_run_lto_and_relink (ld2_argv, object_lst, object, true);
1820 else
1822 fork_execute ("ld", ld2_argv, HAVE_GNU_LD && at_file_supplied, NULL);
1823 post_ld_pass (/*temp_file*/false);
1826 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1827 constructors/destructors in shared libraries. */
1828 scan_prog_file (output_file, PASS_SECOND, SCAN_ALL);
1829 #endif
1831 return 0;
1835 /* Unlink FILE unless we are debugging or this is the output_file
1836 and we may not unlink it. */
1838 void
1839 maybe_unlink (const char *file)
1841 if (save_temps && file_exists (file))
1843 if (verbose)
1844 notice ("[Leaving %s]\n", file);
1845 return;
1848 if (file == output_file && !may_unlink_output_file)
1849 return;
1851 unlink_if_ordinary (file);
1854 /* Call maybe_unlink on the NULL-terminated list, FILE_LIST. */
1856 static void
1857 maybe_unlink_list (char **file_list)
1859 char **tmp = file_list;
1861 while (*tmp)
1862 maybe_unlink (*(tmp++));
1866 static long sequence_number = 0;
1868 /* Add a name to a linked list. */
1870 static void
1871 add_to_list (struct head *head_ptr, const char *name)
1873 struct id *newid
1874 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1875 struct id *p;
1876 strcpy (newid->name, name);
1878 if (head_ptr->first)
1879 head_ptr->last->next = newid;
1880 else
1881 head_ptr->first = newid;
1883 /* Check for duplicate symbols. */
1884 for (p = head_ptr->first;
1885 strcmp (name, p->name) != 0;
1886 p = p->next)
1888 if (p != newid)
1890 head_ptr->last->next = 0;
1891 free (newid);
1892 return;
1895 newid->sequence = ++sequence_number;
1896 head_ptr->last = newid;
1897 head_ptr->number++;
1900 /* Grab the init priority number from an init function name that
1901 looks like "_GLOBAL_.I.12345.foo". */
1903 static int
1904 extract_init_priority (const char *name)
1906 int pos = 0, pri;
1908 #ifdef TARGET_AIX_VERSION
1909 /* Run dependent module initializers before any constructors in this
1910 module. */
1911 switch (is_ctor_dtor (name))
1913 case SYM_AIXI:
1914 case SYM_AIXD:
1915 return INT_MIN;
1916 default:
1917 break;
1919 #endif
1921 while (name[pos] == '_')
1922 ++pos;
1923 pos += 10; /* strlen ("GLOBAL__X_") */
1925 /* Extract init_p number from ctor/dtor name. */
1926 pri = atoi (name + pos);
1927 return pri ? pri : DEFAULT_INIT_PRIORITY;
1930 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1931 ctors will be run from right to left, dtors from left to right. */
1933 static void
1934 sort_ids (struct head *head_ptr)
1936 /* id holds the current element to insert. id_next holds the next
1937 element to insert. id_ptr iterates through the already sorted elements
1938 looking for the place to insert id. */
1939 struct id *id, *id_next, **id_ptr;
1941 id = head_ptr->first;
1943 /* We don't have any sorted elements yet. */
1944 head_ptr->first = NULL;
1946 for (; id; id = id_next)
1948 id_next = id->next;
1949 id->sequence = extract_init_priority (id->name);
1951 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1952 if (*id_ptr == NULL
1953 /* If the sequence numbers are the same, we put the id from the
1954 file later on the command line later in the list. */
1955 || id->sequence > (*id_ptr)->sequence
1956 /* Hack: do lexical compare, too.
1957 || (id->sequence == (*id_ptr)->sequence
1958 && strcmp (id->name, (*id_ptr)->name) > 0) */
1961 id->next = *id_ptr;
1962 *id_ptr = id;
1963 break;
1967 /* Now set the sequence numbers properly so write_c_file works. */
1968 for (id = head_ptr->first; id; id = id->next)
1969 id->sequence = ++sequence_number;
1972 /* Write: `prefix', the names on list LIST, `suffix'. */
1974 static void
1975 write_list (FILE *stream, const char *prefix, struct id *list)
1977 while (list)
1979 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1980 list = list->next;
1984 #ifdef COLLECT_EXPORT_LIST
1985 /* This function is really used only on AIX, but may be useful. */
1986 static int
1987 is_in_list (const char *prefix, struct id *list)
1989 while (list)
1991 if (!strcmp (prefix, list->name)) return 1;
1992 list = list->next;
1994 return 0;
1996 #endif /* COLLECT_EXPORT_LIST */
1998 /* Added for debugging purpose. */
1999 #ifdef COLLECT_EXPORT_LIST
2000 static void
2001 dump_list (FILE *stream, const char *prefix, struct id *list)
2003 while (list)
2005 fprintf (stream, "%s%s,\n", prefix, list->name);
2006 list = list->next;
2009 #endif
2011 #if 0
2012 static void
2013 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
2015 while (list)
2017 fprintf (stream, "%s%s,\n", prefix, list->prefix);
2018 list = list->next;
2021 #endif
2023 static void
2024 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
2026 while (list)
2028 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
2029 prefix, list->sequence, list->name);
2030 list = list->next;
2034 /* Write out the constructor and destructor tables statically (for a shared
2035 object), along with the functions to execute them. */
2037 static void
2038 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2040 const char *p, *q;
2041 char *prefix, *r;
2042 int frames = (frame_tables.number > 0);
2044 /* Figure out name of output_file, stripping off .so version. */
2045 q = p = lbasename (output_file);
2047 while (q)
2049 q = strchr (q,'.');
2050 if (q == 0)
2052 q = p + strlen (p);
2053 break;
2055 else
2057 if (filename_ncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
2059 q += strlen (SHLIB_SUFFIX);
2060 break;
2062 else
2063 q++;
2066 /* q points to null at end of the string (or . of the .so version) */
2067 prefix = XNEWVEC (char, q - p + 1);
2068 strncpy (prefix, p, q - p);
2069 prefix[q - p] = 0;
2070 for (r = prefix; *r; r++)
2071 if (!ISALNUM ((unsigned char)*r))
2072 *r = '_';
2073 if (debug)
2074 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
2075 output_file, prefix);
2077 initname = concat ("_GLOBAL__FI_", prefix, NULL);
2078 fininame = concat ("_GLOBAL__FD_", prefix, NULL);
2079 #ifdef TARGET_AIX_VERSION
2080 aix_shared_initname = concat ("_GLOBAL__AIXI_", prefix, NULL);
2081 aix_shared_fininame = concat ("_GLOBAL__AIXD_", prefix, NULL);
2082 #endif
2084 free (prefix);
2086 /* Write the tables as C code. */
2088 /* This count variable is used to prevent multiple calls to the
2089 constructors/destructors.
2090 This guard against multiple calls is important on AIX as the initfini
2091 functions are deliberately invoked multiple times as part of the
2092 mechanisms GCC uses to order constructors across different dependent
2093 shared libraries (see config/rs6000/aix.h).
2095 fprintf (stream, "static int count;\n");
2096 fprintf (stream, "typedef void entry_pt();\n");
2097 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2099 if (frames)
2101 write_list_with_asm (stream, "extern void *", frame_tables.first);
2103 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2104 write_list (stream, "\t\t&", frame_tables.first);
2105 fprintf (stream, "\t0\n};\n");
2107 /* This must match what's in frame.h. */
2108 fprintf (stream, "struct object {\n");
2109 fprintf (stream, " void *pc_begin;\n");
2110 fprintf (stream, " void *pc_end;\n");
2111 fprintf (stream, " void *fde_begin;\n");
2112 fprintf (stream, " void *fde_array;\n");
2113 fprintf (stream, " __SIZE_TYPE__ count;\n");
2114 fprintf (stream, " struct object *next;\n");
2115 fprintf (stream, "};\n");
2117 fprintf (stream, "extern void __register_frame_info_table_bases (void *, struct object *, void *tbase, void *dbase);\n");
2118 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2119 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2120 #ifdef TARGET_AIX_VERSION
2121 fprintf (stream, "extern void *__gcc_unwind_dbase;\n");
2122 #endif
2124 fprintf (stream, "static void reg_frame () {\n");
2125 fprintf (stream, "\tstatic struct object ob;\n");
2126 #ifdef TARGET_AIX_VERSION
2127 /* Use __gcc_unwind_dbase as the base address for data on AIX.
2128 This might not be the start of the segment, signed offsets assumed.
2130 fprintf (stream, "\t__register_frame_info_table_bases (frame_table, &ob, (void *)0, &__gcc_unwind_dbase);\n");
2131 #else
2132 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2133 #endif
2134 fprintf (stream, "\t}\n");
2136 fprintf (stream, "static void dereg_frame () {\n");
2137 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2138 fprintf (stream, "\t}\n");
2141 #ifdef COLLECT_EXPORT_LIST
2142 /* Set visibility of initializers to default. */
2143 if (visibility_flag)
2144 fprintf (stream, "#pragma GCC visibility push(default)\n");
2145 #endif
2146 fprintf (stream, "void %s() {\n", initname);
2147 if (constructors.number > 0 || frames)
2149 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2150 write_list (stream, "\t\t", constructors.first);
2151 if (frames)
2152 fprintf (stream, "\treg_frame,\n");
2153 fprintf (stream, "\t};\n");
2154 fprintf (stream, "\tentry_pt **p;\n");
2155 fprintf (stream, "\tif (count++ != 0) return;\n");
2156 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2157 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2159 else
2160 fprintf (stream, "\t++count;\n");
2161 fprintf (stream, "}\n");
2162 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2163 fprintf (stream, "void %s() {\n", fininame);
2164 if (destructors.number > 0 || frames)
2166 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2167 write_list (stream, "\t\t", destructors.first);
2168 if (frames)
2169 fprintf (stream, "\tdereg_frame,\n");
2170 fprintf (stream, "\t};\n");
2171 fprintf (stream, "\tentry_pt **p;\n");
2172 fprintf (stream, "\tif (--count != 0) return;\n");
2173 fprintf (stream, "\tp = dtors;\n");
2174 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2175 destructors.number + frames);
2177 fprintf (stream, "}\n");
2178 #ifdef COLLECT_EXPORT_LIST
2179 if (visibility_flag)
2180 fprintf (stream, "#pragma GCC visibility pop\n");
2181 #endif
2183 if (shared_obj)
2185 #ifdef COLLECT_EXPORT_LIST
2186 /* Set visibility of initializers to default. */
2187 if (visibility_flag)
2188 fprintf (stream, "#pragma GCC visibility push(default)\n");
2189 #endif
2190 COLLECT_SHARED_INIT_FUNC (stream, initname);
2191 COLLECT_SHARED_FINI_FUNC (stream, fininame);
2192 #ifdef COLLECT_EXPORT_LIST
2193 if (visibility_flag)
2194 fprintf (stream, "#pragma GCC visibility pop\n");
2195 #endif
2199 /* Write the constructor/destructor tables. */
2201 #ifndef LD_INIT_SWITCH
2202 static void
2203 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2205 /* Write the tables as C code. */
2207 int frames = (frame_tables.number > 0);
2209 fprintf (stream, "typedef void entry_pt();\n\n");
2211 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2213 if (frames)
2215 write_list_with_asm (stream, "extern void *", frame_tables.first);
2217 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2218 write_list (stream, "\t\t&", frame_tables.first);
2219 fprintf (stream, "\t0\n};\n");
2221 /* This must match what's in frame.h. */
2222 fprintf (stream, "struct object {\n");
2223 fprintf (stream, " void *pc_begin;\n");
2224 fprintf (stream, " void *pc_end;\n");
2225 fprintf (stream, " void *fde_begin;\n");
2226 fprintf (stream, " void *fde_array;\n");
2227 fprintf (stream, " __SIZE_TYPE__ count;\n");
2228 fprintf (stream, " struct object *next;\n");
2229 fprintf (stream, "};\n");
2231 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2232 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2234 fprintf (stream, "static void reg_frame () {\n");
2235 fprintf (stream, "\tstatic struct object ob;\n");
2236 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2237 fprintf (stream, "\t}\n");
2239 fprintf (stream, "static void dereg_frame () {\n");
2240 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2241 fprintf (stream, "\t}\n");
2244 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2245 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2246 write_list (stream, "\t", constructors.first);
2247 if (frames)
2248 fprintf (stream, "\treg_frame,\n");
2249 fprintf (stream, "\t0\n};\n\n");
2251 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2253 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2254 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2255 write_list (stream, "\t", destructors.first);
2256 if (frames)
2257 fprintf (stream, "\tdereg_frame,\n");
2258 fprintf (stream, "\t0\n};\n\n");
2260 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2261 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2263 #endif /* ! LD_INIT_SWITCH */
2265 static void
2266 write_c_file (FILE *stream, const char *name)
2268 #ifndef LD_INIT_SWITCH
2269 if (! shared_obj)
2270 write_c_file_glob (stream, name);
2271 else
2272 #endif
2273 write_c_file_stat (stream, name);
2276 #ifdef COLLECT_EXPORT_LIST
2277 static void
2278 write_aix_file (FILE *stream, struct id *list)
2280 for (; list; list = list->next)
2282 fputs (list->name, stream);
2283 putc ('\n', stream);
2286 #endif
2288 #ifdef OBJECT_FORMAT_NONE
2290 /* Check to make sure the file is an LTO object file. */
2292 static int
2293 has_lto_section (void *data, const char *name ATTRIBUTE_UNUSED,
2294 off_t offset ATTRIBUTE_UNUSED,
2295 off_t length ATTRIBUTE_UNUSED)
2297 int *found = (int *) data;
2299 if (strncmp (name, LTO_SECTION_NAME_PREFIX,
2300 sizeof (LTO_SECTION_NAME_PREFIX) - 1) != 0)
2302 if (strncmp (name, OFFLOAD_SECTION_NAME_PREFIX,
2303 sizeof (OFFLOAD_SECTION_NAME_PREFIX) - 1) != 0)
2304 return 1;
2307 *found = 1;
2309 /* Stop iteration. */
2310 return 0;
2313 static bool
2314 is_lto_object_file (const char *prog_name)
2316 const char *errmsg;
2317 int err;
2318 int found = 0;
2319 off_t inoff = 0;
2320 int infd = open (prog_name, O_RDONLY | O_BINARY);
2322 if (infd == -1)
2323 return false;
2325 simple_object_read *inobj = simple_object_start_read (infd, inoff,
2326 LTO_SEGMENT_NAME,
2327 &errmsg, &err);
2328 if (!inobj)
2329 return false;
2331 errmsg = simple_object_find_sections (inobj, has_lto_section,
2332 (void *) &found, &err);
2333 if (! errmsg && found)
2334 return true;
2336 if (errmsg)
2337 fatal_error (0, "%s: %s", errmsg, xstrerror (err));
2338 return false;
2341 /* Generic version to scan the name list of the loaded program for
2342 the symbols g++ uses for static constructors and destructors. */
2344 static void
2345 scan_prog_file (const char *prog_name, scanpass which_pass,
2346 scanfilter filter)
2348 void (*int_handler) (int);
2349 #ifdef SIGQUIT
2350 void (*quit_handler) (int);
2351 #endif
2352 char *real_nm_argv[4];
2353 const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2354 int argc = 0;
2355 struct pex_obj *pex;
2356 const char *errmsg;
2357 int err;
2358 char *p, buf[1024];
2359 FILE *inf;
2361 if (which_pass == PASS_SECOND)
2362 return;
2364 /* LTO objects must be in a known format. This check prevents
2365 us from accepting an archive containing LTO objects, which
2366 gcc cannot currently handle. */
2367 if (which_pass == PASS_LTOINFO)
2369 if(is_lto_object_file (prog_name)) {
2370 add_lto_object (&lto_objects, prog_name);
2372 return;
2375 /* If we do not have an `nm', complain. */
2376 if (nm_file_name == 0)
2377 fatal_error (input_location, "cannot find %<nm%>");
2379 nm_argv[argc++] = nm_file_name;
2380 if (NM_FLAGS[0] != '\0')
2381 nm_argv[argc++] = NM_FLAGS;
2383 nm_argv[argc++] = prog_name;
2384 nm_argv[argc++] = (char *) 0;
2386 /* Trace if needed. */
2387 if (verbose)
2389 const char **p_argv;
2390 const char *str;
2392 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2393 fprintf (stderr, " %s", str);
2395 fprintf (stderr, "\n");
2398 fflush (stdout);
2399 fflush (stderr);
2401 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2402 if (pex == NULL)
2403 fatal_error (input_location, "%<pex_init%> failed: %m");
2405 errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, HOST_BIT_BUCKET,
2406 &err);
2407 if (errmsg != NULL)
2409 if (err != 0)
2411 errno = err;
2412 fatal_error (input_location, "%s: %m", _(errmsg));
2414 else
2415 fatal_error (input_location, errmsg);
2418 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2419 #ifdef SIGQUIT
2420 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2421 #endif
2423 inf = pex_read_output (pex, 0);
2424 if (inf == NULL)
2425 fatal_error (input_location, "cannot open nm output: %m");
2427 if (debug)
2428 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2430 /* Read each line of nm output. */
2431 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2433 int ch, ch2;
2434 char *name, *end;
2436 if (debug)
2437 fprintf (stderr, "\t%s\n", buf);
2439 /* If it contains a constructor or destructor name, add the name
2440 to the appropriate list unless this is a kind of symbol we're
2441 not supposed to even consider. */
2443 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2444 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2445 break;
2447 if (ch != '_')
2448 continue;
2450 name = p;
2451 /* Find the end of the symbol name.
2452 Do not include `|', because Encore nm can tack that on the end. */
2453 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2454 end++)
2455 continue;
2458 *end = '\0';
2460 switch (is_ctor_dtor (name))
2462 case SYM_CTOR:
2463 if (! (filter & SCAN_CTOR))
2464 break;
2465 if (which_pass != PASS_LIB)
2466 add_to_list (&constructors, name);
2467 break;
2469 case SYM_DTOR:
2470 if (! (filter & SCAN_DTOR))
2471 break;
2472 if (which_pass != PASS_LIB)
2473 add_to_list (&destructors, name);
2474 break;
2476 case SYM_INIT:
2477 if (! (filter & SCAN_INIT))
2478 break;
2479 if (which_pass != PASS_LIB)
2480 fatal_error (input_location, "init function found in object %s",
2481 prog_name);
2482 #ifndef LD_INIT_SWITCH
2483 add_to_list (&constructors, name);
2484 #endif
2485 break;
2487 case SYM_FINI:
2488 if (! (filter & SCAN_FINI))
2489 break;
2490 if (which_pass != PASS_LIB)
2491 fatal_error (input_location, "fini function found in object %s",
2492 prog_name);
2493 #ifndef LD_FINI_SWITCH
2494 add_to_list (&destructors, name);
2495 #endif
2496 break;
2498 case SYM_DWEH:
2499 if (! (filter & SCAN_DWEH))
2500 break;
2501 if (which_pass != PASS_LIB)
2502 add_to_list (&frame_tables, name);
2503 break;
2505 default: /* not a constructor or destructor */
2506 continue;
2510 if (debug)
2511 fprintf (stderr, "\n");
2513 do_wait (nm_file_name, pex);
2515 signal (SIGINT, int_handler);
2516 #ifdef SIGQUIT
2517 signal (SIGQUIT, quit_handler);
2518 #endif
2521 #ifdef LDD_SUFFIX
2523 /* Use the List Dynamic Dependencies program to find shared libraries that
2524 the output file depends upon and their initialization/finalization
2525 routines, if any. */
2527 static void
2528 scan_libraries (const char *prog_name)
2530 static struct head libraries; /* list of shared libraries found */
2531 struct id *list;
2532 void (*int_handler) (int);
2533 #ifdef SIGQUIT
2534 void (*quit_handler) (int);
2535 #endif
2536 char *real_ldd_argv[4];
2537 const char **ldd_argv = CONST_CAST2 (const char **, char **, real_ldd_argv);
2538 int argc = 0;
2539 struct pex_obj *pex;
2540 const char *errmsg;
2541 int err;
2542 char buf[1024];
2543 FILE *inf;
2545 /* If we do not have an `ldd', complain. */
2546 if (ldd_file_name == 0)
2548 error ("cannot find %<ldd%>");
2549 return;
2552 ldd_argv[argc++] = ldd_file_name;
2553 ldd_argv[argc++] = prog_name;
2554 ldd_argv[argc++] = (char *) 0;
2556 /* Trace if needed. */
2557 if (verbose)
2559 const char **p_argv;
2560 const char *str;
2562 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2563 fprintf (stderr, " %s", str);
2565 fprintf (stderr, "\n");
2568 fflush (stdout);
2569 fflush (stderr);
2571 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2572 if (pex == NULL)
2573 fatal_error (input_location, "pex_init failed: %m");
2575 errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2576 if (errmsg != NULL)
2578 if (err != 0)
2580 errno = err;
2581 fatal_error (input_location, "%s: %m", _(errmsg));
2583 else
2584 fatal_error (input_location, errmsg);
2587 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2588 #ifdef SIGQUIT
2589 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2590 #endif
2592 inf = pex_read_output (pex, 0);
2593 if (inf == NULL)
2594 fatal_error (input_location, "cannot open ldd output: %m");
2596 if (debug)
2597 notice ("\nldd output with constructors/destructors.\n");
2599 /* Read each line of ldd output. */
2600 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2602 int ch2;
2603 char *name, *end, *p = buf;
2605 /* Extract names of libraries and add to list. */
2606 PARSE_LDD_OUTPUT (p);
2607 if (p == 0)
2608 continue;
2610 name = p;
2611 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2612 fatal_error (input_location, "dynamic dependency %s not found", buf);
2614 /* Find the end of the symbol name. */
2615 for (end = p;
2616 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2617 end++)
2618 continue;
2619 *end = '\0';
2621 if (access (name, R_OK) == 0)
2622 add_to_list (&libraries, name);
2623 else
2624 fatal_error (input_location, "unable to open dynamic dependency "
2625 "%qs", buf);
2627 if (debug)
2628 fprintf (stderr, "\t%s\n", buf);
2630 if (debug)
2631 fprintf (stderr, "\n");
2633 do_wait (ldd_file_name, pex);
2635 signal (SIGINT, int_handler);
2636 #ifdef SIGQUIT
2637 signal (SIGQUIT, quit_handler);
2638 #endif
2640 /* Now iterate through the library list adding their symbols to
2641 the list. */
2642 for (list = libraries.first; list; list = list->next)
2643 scan_prog_file (list->name, PASS_LIB, SCAN_ALL);
2646 #endif /* LDD_SUFFIX */
2648 #endif /* OBJECT_FORMAT_NONE */
2652 * COFF specific stuff.
2655 #ifdef OBJECT_FORMAT_COFF
2657 # define GCC_SYMBOLS(X) (HEADER (ldptr).f_nsyms)
2658 # define GCC_SYMENT SYMENT
2659 # if defined (C_WEAKEXT)
2660 # define GCC_OK_SYMBOL(X) \
2661 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2662 ((X).n_scnum > N_UNDEF) && \
2663 (aix64_flag \
2664 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2665 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2666 # define GCC_UNDEF_SYMBOL(X) \
2667 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2668 ((X).n_scnum == N_UNDEF))
2669 # else
2670 # define GCC_OK_SYMBOL(X) \
2671 (((X).n_sclass == C_EXT) && \
2672 ((X).n_scnum > N_UNDEF) && \
2673 (aix64_flag \
2674 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2675 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2676 # define GCC_UNDEF_SYMBOL(X) \
2677 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2678 # endif
2679 # define GCC_SYMINC(X) ((X).n_numaux+1)
2680 # define GCC_SYMZERO(X) 0
2682 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2683 #if TARGET_AIX_VERSION >= 51
2684 # define GCC_CHECK_HDR(X) \
2685 (((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2686 || (HEADER (X).f_magic == 0767 && aix64_flag)) \
2687 && !(HEADER (X).f_flags & F_LOADONLY))
2688 #else
2689 # define GCC_CHECK_HDR(X) \
2690 (((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2691 || (HEADER (X).f_magic == 0757 && aix64_flag)) \
2692 && !(HEADER (X).f_flags & F_LOADONLY))
2693 #endif
2695 #ifdef COLLECT_EXPORT_LIST
2696 /* Array of standard AIX libraries which should not
2697 be scanned for ctors/dtors. */
2698 static const char *const aix_std_libs[] = {
2699 "/unix",
2700 "/lib/libc.a",
2701 "/lib/libm.a",
2702 "/lib/libc_r.a",
2703 "/lib/libm_r.a",
2704 "/usr/lib/libc.a",
2705 "/usr/lib/libm.a",
2706 "/usr/lib/libc_r.a",
2707 "/usr/lib/libm_r.a",
2708 "/usr/lib/threads/libc.a",
2709 "/usr/ccs/lib/libc.a",
2710 "/usr/ccs/lib/libm.a",
2711 "/usr/ccs/lib/libc_r.a",
2712 "/usr/ccs/lib/libm_r.a",
2713 NULL
2716 /* This function checks the filename and returns 1
2717 if this name matches the location of a standard AIX library. */
2718 static int ignore_library (const char *);
2719 static int
2720 ignore_library (const char *name)
2722 const char *const *p;
2723 size_t length;
2725 if (target_system_root[0] != '\0')
2727 length = strlen (target_system_root);
2728 if (strncmp (name, target_system_root, length) != 0)
2729 return 0;
2730 name += length;
2732 for (p = &aix_std_libs[0]; *p != NULL; ++p)
2733 if (strcmp (name, *p) == 0)
2734 return 1;
2735 return 0;
2737 #endif /* COLLECT_EXPORT_LIST */
2739 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2740 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2741 #endif
2743 /* COFF version to scan the name list of the loaded program for
2744 the symbols g++ uses for static constructors and destructors. */
2746 static void
2747 scan_prog_file (const char *prog_name, scanpass which_pass,
2748 scanfilter filter)
2750 LDFILE *ldptr = NULL;
2751 int sym_index, sym_count;
2752 int is_shared = 0;
2754 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2755 return;
2757 #ifdef COLLECT_EXPORT_LIST
2758 /* We do not need scanning for some standard C libraries. */
2759 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2760 return;
2762 /* On AIX we have a loop, because there is not much difference
2763 between an object and an archive. This trick allows us to
2764 eliminate scan_libraries() function. */
2767 #endif
2768 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2769 non-const char * filename parameter, even though it will not
2770 modify that string. So we must cast away const-ness here,
2771 using CONST_CAST to prevent complaints from -Wcast-qual. */
2772 if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
2774 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2775 fatal_error (input_location, "%s: not a COFF file", prog_name);
2777 if (GCC_CHECK_HDR (ldptr))
2779 sym_count = GCC_SYMBOLS (ldptr);
2780 sym_index = GCC_SYMZERO (ldptr);
2782 #ifdef COLLECT_EXPORT_LIST
2783 /* Is current archive member a shared object? */
2784 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2785 #endif
2787 while (sym_index < sym_count)
2789 GCC_SYMENT symbol;
2791 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2792 break;
2793 sym_index += GCC_SYMINC (symbol);
2795 if (GCC_OK_SYMBOL (symbol))
2797 char *name;
2799 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2800 continue; /* Should never happen. */
2802 #ifdef XCOFF_DEBUGGING_INFO
2803 /* All AIX function names have a duplicate entry
2804 beginning with a dot. */
2805 if (*name == '.')
2806 ++name;
2807 #endif
2809 switch (is_ctor_dtor (name))
2811 #if TARGET_AIX_VERSION
2812 /* Add AIX shared library initalisers/finalisers
2813 to the constructors/destructors list of the
2814 current module. */
2815 case SYM_AIXI:
2816 if (! (filter & SCAN_CTOR))
2817 break;
2818 if (is_shared && !aixlazy_flag
2819 #ifdef COLLECT_EXPORT_LIST
2820 && ! static_obj
2821 && ! is_in_list (prog_name, static_libs.first)
2822 #endif
2824 add_to_list (&constructors, name);
2825 break;
2827 case SYM_AIXD:
2828 if (! (filter & SCAN_DTOR))
2829 break;
2830 if (is_shared && !aixlazy_flag)
2831 add_to_list (&destructors, name);
2832 break;
2833 #endif
2835 case SYM_CTOR:
2836 if (! (filter & SCAN_CTOR))
2837 break;
2838 if (! is_shared)
2839 add_to_list (&constructors, name);
2840 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2841 if (which_pass == PASS_OBJ)
2842 add_to_list (&exports, name);
2843 #endif
2844 break;
2846 case SYM_DTOR:
2847 if (! (filter & SCAN_DTOR))
2848 break;
2849 if (! is_shared)
2850 add_to_list (&destructors, 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;
2857 #ifdef COLLECT_EXPORT_LIST
2858 case SYM_INIT:
2859 if (! (filter & SCAN_INIT))
2860 break;
2861 #ifndef LD_INIT_SWITCH
2862 if (is_shared)
2863 add_to_list (&constructors, name);
2864 #endif
2865 break;
2867 case SYM_FINI:
2868 if (! (filter & SCAN_FINI))
2869 break;
2870 #ifndef LD_INIT_SWITCH
2871 if (is_shared)
2872 add_to_list (&destructors, name);
2873 #endif
2874 break;
2875 #endif
2877 case SYM_DWEH:
2878 if (! (filter & SCAN_DWEH))
2879 break;
2880 if (! is_shared)
2881 add_to_list (&frame_tables, name);
2882 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2883 if (which_pass == PASS_OBJ)
2884 add_to_list (&exports, name);
2885 #endif
2886 break;
2888 default: /* not a constructor or destructor */
2889 #ifdef COLLECT_EXPORT_LIST
2890 /* Explicitly export all global symbols when
2891 building a shared object on AIX, but do not
2892 re-export symbols from another shared object
2893 and do not export symbols if the user
2894 provides an explicit export list. */
2895 if (shared_obj && !is_shared
2896 && which_pass == PASS_OBJ && !export_flag)
2898 /* Do not auto-export __dso_handle or
2899 __gcc_unwind_dbase. They are required
2900 to be local to each module. */
2901 if (strcmp(name, "__dso_handle") != 0
2902 && strcmp(name, "__gcc_unwind_dbase") != 0)
2904 add_to_list (&exports, name);
2907 #endif
2908 continue;
2911 if (debug)
2912 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2913 symbol.n_scnum, symbol.n_sclass,
2914 (symbol.n_type ? "0" : ""), symbol.n_type,
2915 name);
2919 #ifdef COLLECT_EXPORT_LIST
2920 else
2922 /* If archive contains both 32-bit and 64-bit objects,
2923 we want to skip objects in other mode so mismatch normal. */
2924 if (debug)
2925 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2926 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2928 #endif
2930 else
2932 fatal_error (input_location, "%s: cannot open as COFF file",
2933 prog_name);
2935 #ifdef COLLECT_EXPORT_LIST
2936 /* On AIX loop continues while there are more members in archive. */
2938 while (ldclose (ldptr) == FAILURE);
2939 #else
2940 /* Otherwise we simply close ldptr. */
2941 (void) ldclose (ldptr);
2942 #endif
2944 #endif /* OBJECT_FORMAT_COFF */
2946 #ifdef COLLECT_EXPORT_LIST
2947 /* Given a library name without "lib" prefix, this function
2948 returns a full library name including a path. */
2949 static char *
2950 resolve_lib_name (const char *name)
2952 char *lib_buf;
2953 int i, j, l = 0;
2954 /* Library extensions for AIX dynamic linking. */
2955 const char * const libexts[2] = {"a", "so"};
2957 for (i = 0; libpaths[i]; i++)
2958 if (libpaths[i]->max_len > l)
2959 l = libpaths[i]->max_len;
2961 lib_buf = XNEWVEC (char, l + strlen (name) + 10);
2963 for (i = 0; libpaths[i]; i++)
2965 struct prefix_list *list = libpaths[i]->plist;
2966 for (; list; list = list->next)
2968 /* The following lines are needed because path_prefix list
2969 may contain directories both with trailing DIR_SEPARATOR and
2970 without it. */
2971 const char *p = "";
2972 if (!IS_DIR_SEPARATOR (list->prefix[strlen (list->prefix)-1]))
2973 p = "/";
2974 for (j = 0; j < 2; j++)
2976 sprintf (lib_buf, "%s%slib%s.%s",
2977 list->prefix, p, name,
2978 libexts[(j + aixrtl_flag) % 2]);
2979 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2980 if (file_exists (lib_buf))
2982 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2983 return (lib_buf);
2988 if (debug)
2989 fprintf (stderr, "not found\n");
2990 else
2991 fatal_error (input_location, "library lib%s not found", name);
2992 return (NULL);
2994 #endif /* COLLECT_EXPORT_LIST */
2996 #ifdef COLLECT_RUN_DSYMUTIL
2997 static int flag_dsym = false;
2998 static int flag_idsym = false;
3000 static void
3001 process_args (int *argcp, char **argv) {
3002 int i, j;
3003 int argc = *argcp;
3004 for (i=0; i<argc; ++i)
3006 if (strcmp (argv[i], "-dsym") == 0)
3008 flag_dsym = true;
3009 /* Remove the flag, as we handle all processing for it. */
3010 j = i;
3012 argv[j] = argv[j+1];
3013 while (++j < argc);
3014 --i;
3015 argc = --(*argcp);
3017 else if (strcmp (argv[i], "-idsym") == 0)
3019 flag_idsym = true;
3020 /* Remove the flag, as we handle all processing for it. */
3021 j = i;
3023 argv[j] = argv[j+1];
3024 while (++j < argc);
3025 --i;
3026 argc = --(*argcp);
3031 static void
3032 do_dsymutil (const char *output_file) {
3033 const char *dsymutil = DSYMUTIL + 1;
3034 struct pex_obj *pex;
3035 char **real_argv = XCNEWVEC (char *, 3);
3036 const char ** argv = CONST_CAST2 (const char **, char **,
3037 real_argv);
3039 argv[0] = dsymutil;
3040 argv[1] = output_file;
3041 argv[2] = (char *) 0;
3043 pex = collect_execute (dsymutil, real_argv, NULL, NULL,
3044 PEX_LAST | PEX_SEARCH, false, NULL);
3045 do_wait (dsymutil, pex);
3048 static void
3049 post_ld_pass (bool temp_file) {
3050 if (!(temp_file && flag_idsym) && !flag_dsym)
3051 return;
3053 do_dsymutil (output_file);
3055 #else
3056 static void
3057 process_args (int *argcp ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) { }
3058 static void post_ld_pass (bool temp_file ATTRIBUTE_UNUSED) { }
3059 #endif