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