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