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