Mark ChangeLog
[official-gcc.git] / gcc / collect2.c
blob120369a26629dd428d1101c636d4c00484d8a285
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).
10 This file is part of GCC.
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.
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.
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/>. */
27 /* Build tables of static constructors and destructors and run ld. */
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
38 #ifndef LIBRARY_PATH_ENV
39 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
40 #endif
42 #define COLLECT
44 #include "collect2.h"
45 #include "collect2-aix.h"
46 #include "demangle.h"
47 #include "obstack.h"
48 #include "intl.h"
49 #include "version.h"
51 /* On certain systems, we have code that works by scanning the object file
52 directly. But this code uses system-specific header files and library
53 functions, so turn it off in a cross-compiler. Likewise, the names of
54 the utilities are not correct for a cross-compiler; we have to hope that
55 cross-versions are in the proper directories. */
57 #ifdef CROSS_DIRECTORY_STRUCTURE
58 #ifndef CROSS_AIX_SUPPORT
59 #undef OBJECT_FORMAT_COFF
60 #endif
61 #undef MD_EXEC_PREFIX
62 #undef REAL_LD_FILE_NAME
63 #undef REAL_NM_FILE_NAME
64 #undef REAL_STRIP_FILE_NAME
65 #endif
67 /* If we cannot use a special method, use the ordinary one:
68 run nm to find what symbols are present.
69 In a cross-compiler, this means you need a cross nm,
70 but that is not quite as unpleasant as special headers. */
72 #if !defined (OBJECT_FORMAT_COFF)
73 #define OBJECT_FORMAT_NONE
74 #endif
76 #ifdef OBJECT_FORMAT_COFF
78 #ifndef CROSS_DIRECTORY_STRUCTURE
79 #include <a.out.h>
80 #include <ar.h>
82 #ifdef UMAX
83 #include <sgs.h>
84 #endif
86 /* Many versions of ldfcn.h define these. */
87 #ifdef FREAD
88 #undef FREAD
89 #undef FWRITE
90 #endif
92 #include <ldfcn.h>
93 #endif
95 /* Some systems have an ISCOFF macro, but others do not. In some cases
96 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
97 that either do not have an ISCOFF macro in /usr/include or for those
98 where it is wrong. */
100 #ifndef MY_ISCOFF
101 #define MY_ISCOFF(X) ISCOFF (X)
102 #endif
104 #endif /* OBJECT_FORMAT_COFF */
106 #ifdef OBJECT_FORMAT_NONE
108 /* Default flags to pass to nm. */
109 #ifndef NM_FLAGS
110 #define NM_FLAGS "-n"
111 #endif
113 #endif /* OBJECT_FORMAT_NONE */
115 /* Some systems use __main in a way incompatible with its use in gcc, in these
116 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
117 give the same symbol without quotes for an alternative entry point. */
118 #ifndef NAME__MAIN
119 #define NAME__MAIN "__main"
120 #endif
122 /* This must match tree.h. */
123 #define DEFAULT_INIT_PRIORITY 65535
125 #ifndef COLLECT_SHARED_INIT_FUNC
126 #define COLLECT_SHARED_INIT_FUNC(STREAM, FUNC) \
127 fprintf ((STREAM), "void _GLOBAL__DI() {\n\t%s();\n}\n", (FUNC))
128 #endif
129 #ifndef COLLECT_SHARED_FINI_FUNC
130 #define COLLECT_SHARED_FINI_FUNC(STREAM, FUNC) \
131 fprintf ((STREAM), "void _GLOBAL__DD() {\n\t%s();\n}\n", (FUNC))
132 #endif
134 #ifdef LDD_SUFFIX
135 #define SCAN_LIBRARIES
136 #endif
138 #ifndef SHLIB_SUFFIX
139 #define SHLIB_SUFFIX ".so"
140 #endif
142 #ifdef USE_COLLECT2
143 int do_collecting = 1;
144 #else
145 int do_collecting = 0;
146 #endif
148 /* Cook up an always defined indication of whether we proceed the
149 "EXPORT_LIST" way. */
151 #ifdef COLLECT_EXPORT_LIST
152 #define DO_COLLECT_EXPORT_LIST 1
153 #else
154 #define DO_COLLECT_EXPORT_LIST 0
155 #endif
157 /* Nonzero if we should suppress the automatic demangling of identifiers
158 in linker error messages. Set from COLLECT_NO_DEMANGLE. */
159 int no_demangle;
161 /* Linked lists of constructor and destructor names. */
163 struct id
165 struct id *next;
166 int sequence;
167 char name[1];
170 struct head
172 struct id *first;
173 struct id *last;
174 int number;
177 int vflag; /* true if -v */
178 static int rflag; /* true if -r */
179 static int strip_flag; /* true if -s */
180 static const char *demangle_flag;
181 #ifdef COLLECT_EXPORT_LIST
182 static int export_flag; /* true if -bE */
183 static int aix64_flag; /* true if -b64 */
184 static int aixrtl_flag; /* true if -brtl */
185 #endif
187 enum lto_mode_d {
188 LTO_MODE_NONE, /* Not doing LTO. */
189 LTO_MODE_LTO, /* Normal LTO. */
190 LTO_MODE_WHOPR /* WHOPR. */
193 /* Current LTO mode. */
194 static enum lto_mode_d lto_mode = LTO_MODE_NONE;
196 int debug; /* true if -debug */
198 static int shared_obj; /* true if -shared */
200 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
201 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
202 #ifdef COLLECT_EXPORT_LIST
203 static const char *export_file; /* <xxx>.x for AIX export list. */
204 #endif
205 static char **lto_o_files; /* Output files for LTO. */
206 const char *ldout; /* File for ld stdout. */
207 const char *lderrout; /* File for ld stderr. */
208 static const char *output_file; /* Output file for ld. */
209 static const char *nm_file_name; /* pathname of nm */
210 #ifdef LDD_SUFFIX
211 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
212 #endif
213 static const char *strip_file_name; /* pathname of strip */
214 const char *c_file_name; /* pathname of gcc */
215 static char *initname, *fininame; /* names of init and fini funcs */
217 static struct head constructors; /* list of constructors found */
218 static struct head destructors; /* list of destructors found */
219 #ifdef COLLECT_EXPORT_LIST
220 static struct head exports; /* list of exported symbols */
221 #endif
222 static struct head frame_tables; /* list of frame unwind info tables */
224 static bool at_file_supplied; /* Whether to use @file arguments */
225 static char *response_file; /* Name of any current response file */
227 struct obstack temporary_obstack;
228 char * temporary_firstobj;
230 /* A string that must be prepended to a target OS path in order to find
231 it on the host system. */
232 #ifdef TARGET_SYSTEM_ROOT
233 static const char *target_system_root = TARGET_SYSTEM_ROOT;
234 #else
235 static const char *target_system_root = "";
236 #endif
238 /* Structure to hold all the directories in which to search for files to
239 execute. */
241 struct prefix_list
243 const char *prefix; /* String to prepend to the path. */
244 struct prefix_list *next; /* Next in linked list. */
247 struct path_prefix
249 struct prefix_list *plist; /* List of prefixes to try */
250 int max_len; /* Max length of a prefix in PLIST */
251 const char *name; /* Name of this list (used in config stuff) */
254 #ifdef COLLECT_EXPORT_LIST
255 /* Lists to keep libraries to be scanned for global constructors/destructors. */
256 static struct head libs; /* list of libraries */
257 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
258 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
259 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
260 &libpath_lib_dirs, NULL};
261 #endif
263 /* List of names of object files containing LTO information.
264 These are a subset of the object file names appearing on the
265 command line, and must be identical, in the sense of pointer
266 equality, with the names passed to maybe_run_lto_and_relink(). */
268 struct lto_object
270 const char *name; /* Name of object file. */
271 struct lto_object *next; /* Next in linked list. */
274 struct lto_object_list
276 struct lto_object *first; /* First list element. */
277 struct lto_object *last; /* Last list element. */
280 static struct lto_object_list lto_objects;
282 /* Special kinds of symbols that a name may denote. */
284 typedef enum {
285 SYM_REGULAR = 0, /* nothing special */
287 SYM_CTOR = 1, /* constructor */
288 SYM_DTOR = 2, /* destructor */
289 SYM_INIT = 3, /* shared object routine that calls all the ctors */
290 SYM_FINI = 4, /* shared object routine that calls all the dtors */
291 SYM_DWEH = 5 /* DWARF exception handling table */
292 } symkind;
294 static symkind is_ctor_dtor (const char *);
296 static void handler (int);
297 static char *find_a_file (struct path_prefix *, const char *);
298 static void add_prefix (struct path_prefix *, const char *);
299 static void prefix_from_env (const char *, struct path_prefix *);
300 static void prefix_from_string (const char *, struct path_prefix *);
301 static void do_wait (const char *, struct pex_obj *);
302 static void fork_execute (const char *, char **);
303 static void maybe_unlink (const char *);
304 static void maybe_unlink_list (char **);
305 static void add_to_list (struct head *, const char *);
306 static int extract_init_priority (const char *);
307 static void sort_ids (struct head *);
308 static void write_list (FILE *, const char *, struct id *);
309 #ifdef COLLECT_EXPORT_LIST
310 static void dump_list (FILE *, const char *, struct id *);
311 #endif
312 #if 0
313 static void dump_prefix_list (FILE *, const char *, struct prefix_list *);
314 #endif
315 static void write_list_with_asm (FILE *, const char *, struct id *);
316 static void write_c_file (FILE *, const char *);
317 static void write_c_file_stat (FILE *, const char *);
318 #ifndef LD_INIT_SWITCH
319 static void write_c_file_glob (FILE *, const char *);
320 #endif
321 #ifdef SCAN_LIBRARIES
322 static void scan_libraries (const char *);
323 #endif
324 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
325 static int is_in_args (const char *, const char **, const char **);
326 #endif
327 #ifdef COLLECT_EXPORT_LIST
328 #if 0
329 static int is_in_list (const char *, struct id *);
330 #endif
331 static void write_aix_file (FILE *, struct id *);
332 static char *resolve_lib_name (const char *);
333 #endif
334 static char *extract_string (const char **);
336 /* Enumerations describing which pass this is for scanning the
337 program file ... */
339 typedef enum {
340 PASS_FIRST, /* without constructors */
341 PASS_OBJ, /* individual objects */
342 PASS_LIB, /* looking for shared libraries */
343 PASS_SECOND, /* with constructors linked in */
344 PASS_LTOINFO /* looking for objects with LTO info */
345 } scanpass;
347 /* ... and which kinds of symbols are to be considered. */
349 enum scanfilter_masks {
350 SCAN_NOTHING = 0,
352 SCAN_CTOR = 1 << SYM_CTOR,
353 SCAN_DTOR = 1 << SYM_DTOR,
354 SCAN_INIT = 1 << SYM_INIT,
355 SCAN_FINI = 1 << SYM_FINI,
356 SCAN_DWEH = 1 << SYM_DWEH,
357 SCAN_ALL = ~0
360 /* This type is used for parameters and variables which hold
361 combinations of the flags in enum scanfilter_masks. */
362 typedef int scanfilter;
364 /* Scan the name list of the loaded program for the symbols g++ uses for
365 static constructors and destructors.
367 The SCANPASS argument tells which collect processing pass this is for and
368 the SCANFILTER argument tells which kinds of symbols to consider in this
369 pass. Symbols of a special kind not in the filter mask are considered as
370 regular ones.
372 The constructor table begins at __CTOR_LIST__ and contains a count of the
373 number of pointers (or -1 if the constructors are built in a separate
374 section by the linker), followed by the pointers to the constructor
375 functions, terminated with a null pointer. The destructor table has the
376 same format, and begins at __DTOR_LIST__. */
378 static void scan_prog_file (const char *, scanpass, scanfilter);
381 /* Delete tempfiles and exit function. */
383 void
384 collect_exit (int status)
386 if (c_file != 0 && c_file[0])
387 maybe_unlink (c_file);
389 if (o_file != 0 && o_file[0])
390 maybe_unlink (o_file);
392 #ifdef COLLECT_EXPORT_LIST
393 if (export_file != 0 && export_file[0])
394 maybe_unlink (export_file);
395 #endif
397 if (lto_o_files)
398 maybe_unlink_list (lto_o_files);
400 if (ldout != 0 && ldout[0])
402 dump_file (ldout, stdout);
403 maybe_unlink (ldout);
406 if (lderrout != 0 && lderrout[0])
408 dump_file (lderrout, stderr);
409 maybe_unlink (lderrout);
412 if (status != 0 && output_file != 0 && output_file[0])
413 maybe_unlink (output_file);
415 if (response_file)
416 maybe_unlink (response_file);
418 exit (status);
422 /* Notify user of a non-error. */
423 void
424 notice (const char *cmsgid, ...)
426 va_list ap;
428 va_start (ap, cmsgid);
429 vfprintf (stderr, _(cmsgid), ap);
430 va_end (ap);
433 /* Notify user of a non-error, without translating the format string. */
434 void
435 notice_translated (const char *cmsgid, ...)
437 va_list ap;
439 va_start (ap, cmsgid);
440 vfprintf (stderr, cmsgid, ap);
441 va_end (ap);
444 /* Die when sys call fails. */
446 void
447 fatal_perror (const char * cmsgid, ...)
449 int e = errno;
450 va_list ap;
452 va_start (ap, cmsgid);
453 fprintf (stderr, "collect2: ");
454 vfprintf (stderr, _(cmsgid), ap);
455 fprintf (stderr, ": %s\n", xstrerror (e));
456 va_end (ap);
458 collect_exit (FATAL_EXIT_CODE);
461 /* Just die. */
463 void
464 fatal (const char * cmsgid, ...)
466 va_list ap;
468 va_start (ap, cmsgid);
469 fprintf (stderr, "collect2: ");
470 vfprintf (stderr, _(cmsgid), ap);
471 fprintf (stderr, "\n");
472 va_end (ap);
474 collect_exit (FATAL_EXIT_CODE);
477 /* Write error message. */
479 void
480 error (const char * gmsgid, ...)
482 va_list ap;
484 va_start (ap, gmsgid);
485 fprintf (stderr, "collect2: ");
486 vfprintf (stderr, _(gmsgid), ap);
487 fprintf (stderr, "\n");
488 va_end(ap);
491 /* In case obstack is linked in, and abort is defined to fancy_abort,
492 provide a default entry. */
494 void
495 fancy_abort (const char *file, int line, const char *func)
497 fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
500 static void
501 handler (int signo)
503 if (c_file != 0 && c_file[0])
504 maybe_unlink (c_file);
506 if (o_file != 0 && o_file[0])
507 maybe_unlink (o_file);
509 if (ldout != 0 && ldout[0])
510 maybe_unlink (ldout);
512 if (lderrout != 0 && lderrout[0])
513 maybe_unlink (lderrout);
515 #ifdef COLLECT_EXPORT_LIST
516 if (export_file != 0 && export_file[0])
517 maybe_unlink (export_file);
518 #endif
520 if (lto_o_files)
521 maybe_unlink_list (lto_o_files);
523 if (response_file)
524 maybe_unlink (response_file);
526 signal (signo, SIG_DFL);
527 raise (signo);
532 file_exists (const char *name)
534 return access (name, R_OK) == 0;
537 /* Parse a reasonable subset of shell quoting syntax. */
539 static char *
540 extract_string (const char **pp)
542 const char *p = *pp;
543 int backquote = 0;
544 int inside = 0;
546 for (;;)
548 char c = *p;
549 if (c == '\0')
550 break;
551 ++p;
552 if (backquote)
553 obstack_1grow (&temporary_obstack, c);
554 else if (! inside && c == ' ')
555 break;
556 else if (! inside && c == '\\')
557 backquote = 1;
558 else if (c == '\'')
559 inside = !inside;
560 else
561 obstack_1grow (&temporary_obstack, c);
564 obstack_1grow (&temporary_obstack, '\0');
565 *pp = p;
566 return XOBFINISH (&temporary_obstack, char *);
569 void
570 dump_file (const char *name, FILE *to)
572 FILE *stream = fopen (name, "r");
574 if (stream == 0)
575 return;
576 while (1)
578 int c;
579 while (c = getc (stream),
580 c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
581 obstack_1grow (&temporary_obstack, c);
582 if (obstack_object_size (&temporary_obstack) > 0)
584 const char *word, *p;
585 char *result;
586 obstack_1grow (&temporary_obstack, '\0');
587 word = XOBFINISH (&temporary_obstack, const char *);
589 if (*word == '.')
590 ++word, putc ('.', to);
591 p = word;
592 if (!strncmp (p, USER_LABEL_PREFIX, strlen (USER_LABEL_PREFIX)))
593 p += strlen (USER_LABEL_PREFIX);
595 #ifdef HAVE_LD_DEMANGLE
596 result = 0;
597 #else
598 if (no_demangle)
599 result = 0;
600 else
601 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
602 #endif
604 if (result)
606 int diff;
607 fputs (result, to);
609 diff = strlen (word) - strlen (result);
610 while (diff > 0 && c == ' ')
611 --diff, putc (' ', to);
612 if (diff < 0 && c == ' ')
614 while (diff < 0 && c == ' ')
615 ++diff, c = getc (stream);
616 if (!ISSPACE (c))
618 /* Make sure we output at least one space, or
619 the demangled symbol name will run into
620 whatever text follows. */
621 putc (' ', to);
625 free (result);
627 else
628 fputs (word, to);
630 fflush (to);
631 obstack_free (&temporary_obstack, temporary_firstobj);
633 if (c == EOF)
634 break;
635 putc (c, to);
637 fclose (stream);
640 /* Return the kind of symbol denoted by name S. */
642 static symkind
643 is_ctor_dtor (const char *s)
645 struct names { const char *const name; const int len; symkind ret;
646 const int two_underscores; };
648 const struct names *p;
649 int ch;
650 const char *orig_s = s;
652 static const struct names special[] = {
653 #ifndef NO_DOLLAR_IN_LABEL
654 { "GLOBAL__I$", sizeof ("GLOBAL__I$")-1, SYM_CTOR, 0 },
655 { "GLOBAL__D$", sizeof ("GLOBAL__D$")-1, SYM_DTOR, 0 },
656 #else
657 #ifndef NO_DOT_IN_LABEL
658 { "GLOBAL__I.", sizeof ("GLOBAL__I.")-1, SYM_CTOR, 0 },
659 { "GLOBAL__D.", sizeof ("GLOBAL__D.")-1, SYM_DTOR, 0 },
660 #endif /* NO_DOT_IN_LABEL */
661 #endif /* NO_DOLLAR_IN_LABEL */
662 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, SYM_CTOR, 0 },
663 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, SYM_DTOR, 0 },
664 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, SYM_DWEH, 0 },
665 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, SYM_INIT, 0 },
666 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, SYM_FINI, 0 },
667 { NULL, 0, SYM_REGULAR, 0 }
670 while ((ch = *s) == '_')
671 ++s;
673 if (s == orig_s)
674 return SYM_REGULAR;
676 for (p = &special[0]; p->len > 0; p++)
678 if (ch == p->name[0]
679 && (!p->two_underscores || ((s - orig_s) >= 2))
680 && strncmp(s, p->name, p->len) == 0)
682 return p->ret;
685 return SYM_REGULAR;
688 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
689 and one from the PATH variable. */
691 static struct path_prefix cpath, path;
693 #ifdef CROSS_DIRECTORY_STRUCTURE
694 /* This is the name of the target machine. We use it to form the name
695 of the files to execute. */
697 static const char *const target_machine = TARGET_MACHINE;
698 #endif
700 /* Search for NAME using prefix list PPREFIX. We only look for executable
701 files.
703 Return 0 if not found, otherwise return its name, allocated with malloc. */
705 static char *
706 find_a_file (struct path_prefix *pprefix, const char *name)
708 char *temp;
709 struct prefix_list *pl;
710 int len = pprefix->max_len + strlen (name) + 1;
712 if (debug)
713 fprintf (stderr, "Looking for '%s'\n", name);
715 #ifdef HOST_EXECUTABLE_SUFFIX
716 len += strlen (HOST_EXECUTABLE_SUFFIX);
717 #endif
719 temp = XNEWVEC (char, len);
721 /* Determine the filename to execute (special case for absolute paths). */
723 if (IS_ABSOLUTE_PATH (name))
725 if (access (name, X_OK) == 0)
727 strcpy (temp, name);
729 if (debug)
730 fprintf (stderr, " - found: absolute path\n");
732 return temp;
735 #ifdef HOST_EXECUTABLE_SUFFIX
736 /* Some systems have a suffix for executable files.
737 So try appending that. */
738 strcpy (temp, name);
739 strcat (temp, HOST_EXECUTABLE_SUFFIX);
741 if (access (temp, X_OK) == 0)
742 return temp;
743 #endif
745 if (debug)
746 fprintf (stderr, " - failed to locate using absolute path\n");
748 else
749 for (pl = pprefix->plist; pl; pl = pl->next)
751 struct stat st;
753 strcpy (temp, pl->prefix);
754 strcat (temp, name);
756 if (stat (temp, &st) >= 0
757 && ! S_ISDIR (st.st_mode)
758 && access (temp, X_OK) == 0)
759 return temp;
761 #ifdef HOST_EXECUTABLE_SUFFIX
762 /* Some systems have a suffix for executable files.
763 So try appending that. */
764 strcat (temp, HOST_EXECUTABLE_SUFFIX);
766 if (stat (temp, &st) >= 0
767 && ! S_ISDIR (st.st_mode)
768 && access (temp, X_OK) == 0)
769 return temp;
770 #endif
773 if (debug && pprefix->plist == NULL)
774 fprintf (stderr, " - failed: no entries in prefix list\n");
776 free (temp);
777 return 0;
780 /* Add an entry for PREFIX to prefix list PPREFIX. */
782 static void
783 add_prefix (struct path_prefix *pprefix, const char *prefix)
785 struct prefix_list *pl, **prev;
786 int len;
788 if (pprefix->plist)
790 for (pl = pprefix->plist; pl->next; pl = pl->next)
792 prev = &pl->next;
794 else
795 prev = &pprefix->plist;
797 /* Keep track of the longest prefix. */
799 len = strlen (prefix);
800 if (len > pprefix->max_len)
801 pprefix->max_len = len;
803 pl = XNEW (struct prefix_list);
804 pl->prefix = xstrdup (prefix);
806 if (*prev)
807 pl->next = *prev;
808 else
809 pl->next = (struct prefix_list *) 0;
810 *prev = pl;
813 /* Take the value of the environment variable ENV, break it into a path, and
814 add of the entries to PPREFIX. */
816 static void
817 prefix_from_env (const char *env, struct path_prefix *pprefix)
819 const char *p;
820 GET_ENVIRONMENT (p, env);
822 if (p)
823 prefix_from_string (p, pprefix);
826 static void
827 prefix_from_string (const char *p, struct path_prefix *pprefix)
829 const char *startp, *endp;
830 char *nstore = XNEWVEC (char, strlen (p) + 3);
832 if (debug)
833 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
835 startp = endp = p;
836 while (1)
838 if (*endp == PATH_SEPARATOR || *endp == 0)
840 strncpy (nstore, startp, endp-startp);
841 if (endp == startp)
843 strcpy (nstore, "./");
845 else if (! IS_DIR_SEPARATOR (endp[-1]))
847 nstore[endp-startp] = DIR_SEPARATOR;
848 nstore[endp-startp+1] = 0;
850 else
851 nstore[endp-startp] = 0;
853 if (debug)
854 fprintf (stderr, " - add prefix: %s\n", nstore);
856 add_prefix (pprefix, nstore);
857 if (*endp == 0)
858 break;
859 endp = startp = endp + 1;
861 else
862 endp++;
864 free (nstore);
867 #ifdef OBJECT_FORMAT_NONE
869 /* Add an entry for the object file NAME to object file list LIST.
870 New entries are added at the end of the list. The original pointer
871 value of NAME is preserved, i.e., no string copy is performed. */
873 static void
874 add_lto_object (struct lto_object_list *list, const char *name)
876 struct lto_object *n = XNEW (struct lto_object);
877 n->name = name;
878 n->next = NULL;
880 if (list->last)
881 list->last->next = n;
882 else
883 list->first = n;
885 list->last = n;
887 #endif /* OBJECT_FORMAT_NONE */
890 /* Perform a link-time recompilation and relink if any of the object
891 files contain LTO info. The linker command line LTO_LD_ARGV
892 represents the linker command that would produce a final executable
893 without the use of LTO. OBJECT_LST is a vector of object file names
894 appearing in LTO_LD_ARGV that are to be considerd for link-time
895 recompilation, where OBJECT is a pointer to the last valid element.
896 (This awkward convention avoids an impedance mismatch with the
897 usage of similarly-named variables in main().) The elements of
898 OBJECT_LST must be identical, i.e., pointer equal, to the
899 corresponding arguments in LTO_LD_ARGV.
901 Upon entry, at least one linker run has been performed without the
902 use of any LTO info that might be present. Any recompilations
903 necessary for template instantiations have been performed, and
904 initializer/finalizer tables have been created if needed and
905 included in the linker command line LTO_LD_ARGV. If any of the
906 object files contain LTO info, we run the LTO back end on all such
907 files, and perform the final link with the LTO back end output
908 substituted for the LTO-optimized files. In some cases, a final
909 link with all link-time generated code has already been performed,
910 so there is no need to relink if no LTO info is found. In other
911 cases, our caller has not produced the final executable, and is
912 relying on us to perform the required link whether LTO info is
913 present or not. In that case, the FORCE argument should be true.
914 Note that the linker command line argument LTO_LD_ARGV passed into
915 this function may be modified in place. */
917 static void
918 maybe_run_lto_and_relink (char **lto_ld_argv, char **object_lst,
919 const char **object, bool force)
921 const char **object_file = CONST_CAST2 (const char **, char **, object_lst);
923 int num_lto_c_args = 1; /* Allow space for the terminating NULL. */
925 while (object_file < object)
927 /* If file contains LTO info, add it to the list of LTO objects. */
928 scan_prog_file (*object_file++, PASS_LTOINFO, SCAN_ALL);
930 /* Increment the argument count by the number of object file arguments
931 we will add. An upper bound suffices, so just count all of the
932 object files regardless of whether they contain LTO info. */
933 num_lto_c_args++;
936 if (lto_objects.first)
938 const char *opts;
939 char **lto_c_argv;
940 const char **lto_c_ptr;
941 const char *cp;
942 const char **p, **q, **r;
943 const char **lto_o_ptr;
944 struct lto_object *list;
945 char *lto_wrapper = getenv ("COLLECT_LTO_WRAPPER");
946 struct pex_obj *pex;
947 const char *prog = "lto-wrapper";
949 if (!lto_wrapper)
950 fatal ("COLLECT_LTO_WRAPPER must be set.");
952 /* There is at least one object file containing LTO info,
953 so we need to run the LTO back end and relink. */
955 /* Get compiler options passed down from the parent `gcc' command.
956 These must be passed to the LTO back end. */
957 opts = getenv ("COLLECT_GCC_OPTIONS");
959 /* Increment the argument count by the number of inherited options.
960 Some arguments may be filtered out later. Again, an upper bound
961 suffices. */
963 cp = opts;
965 while (cp && *cp)
967 extract_string (&cp);
968 num_lto_c_args++;
970 obstack_free (&temporary_obstack, temporary_firstobj);
972 if (debug)
973 num_lto_c_args++;
975 /* Increment the argument count by the number of initial
976 arguments added below. */
977 num_lto_c_args += 9;
979 lto_c_argv = (char **) xcalloc (sizeof (char *), num_lto_c_args);
980 lto_c_ptr = CONST_CAST2 (const char **, char **, lto_c_argv);
982 *lto_c_ptr++ = lto_wrapper;
983 *lto_c_ptr++ = c_file_name;
985 cp = opts;
987 while (cp && *cp)
989 const char *s = extract_string (&cp);
991 /* Pass the option or argument to the wrapper. */
992 *lto_c_ptr++ = xstrdup (s);
994 obstack_free (&temporary_obstack, temporary_firstobj);
996 if (debug)
997 *lto_c_ptr++ = xstrdup ("-debug");
999 /* Add LTO objects to the wrapper command line. */
1000 for (list = lto_objects.first; list; list = list->next)
1001 *lto_c_ptr++ = list->name;
1003 *lto_c_ptr = NULL;
1005 /* Save intermediate WPA files in lto1 if debug. */
1006 if (debug)
1007 putenv (xstrdup ("WPA_SAVE_LTRANS=1"));
1009 /* Run the LTO back end. */
1010 pex = collect_execute (prog, lto_c_argv, NULL, NULL, PEX_SEARCH);
1012 int c;
1013 FILE *stream;
1014 size_t i, num_files;
1015 char *start, *end;
1017 stream = pex_read_output (pex, 0);
1018 gcc_assert (stream);
1020 num_files = 0;
1021 while ((c = getc (stream)) != EOF)
1023 obstack_1grow (&temporary_obstack, c);
1024 if (c == '\n')
1025 ++num_files;
1028 lto_o_files = XNEWVEC (char *, num_files + 1);
1029 lto_o_files[num_files] = NULL;
1030 start = XOBFINISH (&temporary_obstack, char *);
1031 for (i = 0; i < num_files; ++i)
1033 end = start;
1034 while (*end != '\n')
1035 ++end;
1036 *end = '\0';
1038 lto_o_files[i] = xstrdup (start);
1040 start = end + 1;
1043 obstack_free (&temporary_obstack, temporary_firstobj);
1045 do_wait (prog, pex);
1046 pex = NULL;
1048 /* After running the LTO back end, we will relink, substituting
1049 the LTO output for the object files that we submitted to the
1050 LTO. Here, we modify the linker command line for the relink. */
1051 p = CONST_CAST2 (const char **, char **, lto_ld_argv);
1052 lto_o_ptr = CONST_CAST2 (const char **, char **, lto_o_files);
1054 while (*p != NULL)
1056 for (list = lto_objects.first; list; list = list->next)
1058 if (*p == list->name) /* Note test for pointer equality! */
1060 /* Excise argument from linker command line. */
1061 if (*lto_o_ptr)
1063 /* Replace first argument with LTO output file. */
1064 *p++ = *lto_o_ptr++;
1066 else
1068 /* Move following arguments one position earlier,
1069 overwriting the current argument. */
1070 q = p;
1071 r = p + 1;
1072 while (*r != NULL)
1073 *q++ = *r++;
1074 *q = NULL;
1077 /* No need to continue searching the LTO object list. */
1078 break;
1082 /* If we didn't find a match, move on to the next argument.
1083 Otherwise, P has been set to the correct argument position
1084 at which to continue. */
1085 if (!list) ++p;
1088 /* The code above assumes we will never have more lto output files than
1089 input files. Otherwise, we need to resize lto_ld_argv. Check this
1090 assumption. */
1091 if (*lto_o_ptr)
1092 fatal ("too many lto output files");
1094 /* Run the linker again, this time replacing the object files
1095 optimized by the LTO with the temporary file generated by the LTO. */
1096 fork_execute ("ld", lto_ld_argv);
1098 maybe_unlink_list (lto_o_files);
1100 else if (force)
1102 /* Our caller is relying on us to do the link
1103 even though there is no LTO back end work to be done. */
1104 fork_execute ("ld", lto_ld_argv);
1108 /* Main program. */
1111 main (int argc, char **argv)
1113 static const char *const ld_suffix = "ld";
1114 static const char *const plugin_ld_suffix = PLUGIN_LD;
1115 static const char *const real_ld_suffix = "real-ld";
1116 static const char *const collect_ld_suffix = "collect-ld";
1117 static const char *const nm_suffix = "nm";
1118 static const char *const gnm_suffix = "gnm";
1119 #ifdef LDD_SUFFIX
1120 static const char *const ldd_suffix = LDD_SUFFIX;
1121 #endif
1122 static const char *const strip_suffix = "strip";
1123 static const char *const gstrip_suffix = "gstrip";
1125 #ifdef CROSS_DIRECTORY_STRUCTURE
1126 /* If we look for a program in the compiler directories, we just use
1127 the short name, since these directories are already system-specific.
1128 But it we look for a program in the system directories, we need to
1129 qualify the program name with the target machine. */
1131 const char *const full_ld_suffix =
1132 concat(target_machine, "-", ld_suffix, NULL);
1133 const char *const full_plugin_ld_suffix =
1134 concat(target_machine, "-", plugin_ld_suffix, NULL);
1135 const char *const full_nm_suffix =
1136 concat (target_machine, "-", nm_suffix, NULL);
1137 const char *const full_gnm_suffix =
1138 concat (target_machine, "-", gnm_suffix, NULL);
1139 #ifdef LDD_SUFFIX
1140 const char *const full_ldd_suffix =
1141 concat (target_machine, "-", ldd_suffix, NULL);
1142 #endif
1143 const char *const full_strip_suffix =
1144 concat (target_machine, "-", strip_suffix, NULL);
1145 const char *const full_gstrip_suffix =
1146 concat (target_machine, "-", gstrip_suffix, NULL);
1147 #else
1148 const char *const full_ld_suffix = ld_suffix;
1149 const char *const full_plugin_ld_suffix = plugin_ld_suffix;
1150 const char *const full_nm_suffix = nm_suffix;
1151 const char *const full_gnm_suffix = gnm_suffix;
1152 #ifdef LDD_SUFFIX
1153 const char *const full_ldd_suffix = ldd_suffix;
1154 #endif
1155 const char *const full_strip_suffix = strip_suffix;
1156 const char *const full_gstrip_suffix = gstrip_suffix;
1157 #endif /* CROSS_DIRECTORY_STRUCTURE */
1159 const char *arg;
1160 FILE *outf;
1161 #ifdef COLLECT_EXPORT_LIST
1162 FILE *exportf;
1163 #endif
1164 const char *ld_file_name;
1165 const char *p;
1166 char **c_argv;
1167 const char **c_ptr;
1168 char **ld1_argv;
1169 const char **ld1;
1170 bool use_plugin = false;
1172 /* The kinds of symbols we will have to consider when scanning the
1173 outcome of a first pass link. This is ALL to start with, then might
1174 be adjusted before getting to the first pass link per se, typically on
1175 AIX where we perform an early scan of objects and libraries to fetch
1176 the list of global ctors/dtors and make sure they are not garbage
1177 collected. */
1178 scanfilter ld1_filter = SCAN_ALL;
1180 char **ld2_argv;
1181 const char **ld2;
1182 char **object_lst;
1183 const char **object;
1184 int first_file;
1185 int num_c_args;
1186 char **old_argv;
1188 bool use_verbose = false;
1190 old_argv = argv;
1191 expandargv (&argc, &argv);
1192 if (argv != old_argv)
1193 at_file_supplied = 1;
1195 num_c_args = argc + 9;
1197 no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
1199 /* Suppress demangling by the real linker, which may be broken. */
1200 putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
1202 #if defined (COLLECT2_HOST_INITIALIZATION)
1203 /* Perform system dependent initialization, if necessary. */
1204 COLLECT2_HOST_INITIALIZATION;
1205 #endif
1207 #ifdef SIGCHLD
1208 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1209 receive the signal. A different setting is inheritable */
1210 signal (SIGCHLD, SIG_DFL);
1211 #endif
1213 /* Unlock the stdio streams. */
1214 unlock_std_streams ();
1216 gcc_init_libintl ();
1218 /* Do not invoke xcalloc before this point, since locale needs to be
1219 set first, in case a diagnostic is issued. */
1221 ld1_argv = XCNEWVEC (char *, argc + 4);
1222 ld1 = CONST_CAST2 (const char **, char **, ld1_argv);
1223 ld2_argv = XCNEWVEC (char *, argc + 11);
1224 ld2 = CONST_CAST2 (const char **, char **, ld2_argv);
1225 object_lst = XCNEWVEC (char *, argc);
1226 object = CONST_CAST2 (const char **, char **, object_lst);
1228 #ifdef DEBUG
1229 debug = 1;
1230 #endif
1232 /* Parse command line early for instances of -debug. This allows
1233 the debug flag to be set before functions like find_a_file()
1234 are called. We also look for the -flto or -fwhopr flag to know
1235 what LTO mode we are in. */
1237 int i;
1239 for (i = 1; argv[i] != NULL; i ++)
1241 if (! strcmp (argv[i], "-debug"))
1242 debug = 1;
1243 else if (! strcmp (argv[i], "-flto") && ! use_plugin)
1245 use_verbose = true;
1246 lto_mode = LTO_MODE_LTO;
1248 else if (! strcmp (argv[i], "-fwhopr") && ! use_plugin)
1250 use_verbose = true;
1251 lto_mode = LTO_MODE_WHOPR;
1253 else if (! strcmp (argv[i], "-plugin"))
1255 use_plugin = true;
1256 use_verbose = true;
1257 lto_mode = LTO_MODE_NONE;
1259 #ifdef COLLECT_EXPORT_LIST
1260 /* since -brtl, -bexport, -b64 are not position dependent
1261 also check for them here */
1262 if ((argv[i][0] == '-') && (argv[i][1] == 'b'))
1264 arg = argv[i];
1265 /* We want to disable automatic exports on AIX when user
1266 explicitly puts an export list in command line */
1267 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1268 export_flag = 1;
1269 else if (arg[2] == '6' && arg[3] == '4')
1270 aix64_flag = 1;
1271 else if (arg[2] == 'r' && arg[3] == 't' && arg[4] == 'l')
1272 aixrtl_flag = 1;
1274 #endif
1276 vflag = debug;
1279 #ifndef DEFAULT_A_OUT_NAME
1280 output_file = "a.out";
1281 #else
1282 output_file = DEFAULT_A_OUT_NAME;
1283 #endif
1285 obstack_begin (&temporary_obstack, 0);
1286 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
1288 #ifndef HAVE_LD_DEMANGLE
1289 current_demangling_style = auto_demangling;
1290 #endif
1291 p = getenv ("COLLECT_GCC_OPTIONS");
1292 while (p && *p)
1294 const char *q = extract_string (&p);
1295 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1296 num_c_args++;
1298 obstack_free (&temporary_obstack, temporary_firstobj);
1300 /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
1301 -fno-exceptions -w -fno-whole-program */
1302 num_c_args += 6;
1304 c_argv = XCNEWVEC (char *, num_c_args);
1305 c_ptr = CONST_CAST2 (const char **, char **, c_argv);
1307 if (argc < 2)
1308 fatal ("no arguments");
1310 #ifdef SIGQUIT
1311 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1312 signal (SIGQUIT, handler);
1313 #endif
1314 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1315 signal (SIGINT, handler);
1316 #ifdef SIGALRM
1317 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1318 signal (SIGALRM, handler);
1319 #endif
1320 #ifdef SIGHUP
1321 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1322 signal (SIGHUP, handler);
1323 #endif
1324 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1325 signal (SIGSEGV, handler);
1326 #ifdef SIGBUS
1327 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1328 signal (SIGBUS, handler);
1329 #endif
1331 /* Extract COMPILER_PATH and PATH into our prefix list. */
1332 prefix_from_env ("COMPILER_PATH", &cpath);
1333 prefix_from_env ("PATH", &path);
1335 /* Try to discover a valid linker/nm/strip to use. */
1337 /* Maybe we know the right file to use (if not cross). */
1338 ld_file_name = 0;
1339 #ifdef DEFAULT_LINKER
1340 if (access (DEFAULT_LINKER, X_OK) == 0)
1341 ld_file_name = DEFAULT_LINKER;
1342 if (ld_file_name == 0)
1343 #endif
1344 #ifdef REAL_LD_FILE_NAME
1345 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1346 if (ld_file_name == 0)
1347 #endif
1348 /* Search the (target-specific) compiler dirs for ld'. */
1349 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1350 /* Likewise for `collect-ld'. */
1351 if (ld_file_name == 0)
1352 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1353 /* Search the compiler directories for `ld'. We have protection against
1354 recursive calls in find_a_file. */
1355 if (ld_file_name == 0)
1356 ld_file_name = find_a_file (&cpath,
1357 use_plugin
1358 ? plugin_ld_suffix
1359 : ld_suffix);
1360 /* Search the ordinary system bin directories
1361 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1362 if (ld_file_name == 0)
1363 ld_file_name = find_a_file (&path,
1364 use_plugin
1365 ? full_plugin_ld_suffix
1366 : full_ld_suffix);
1368 #ifdef REAL_NM_FILE_NAME
1369 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1370 if (nm_file_name == 0)
1371 #endif
1372 nm_file_name = find_a_file (&cpath, gnm_suffix);
1373 if (nm_file_name == 0)
1374 nm_file_name = find_a_file (&path, full_gnm_suffix);
1375 if (nm_file_name == 0)
1376 nm_file_name = find_a_file (&cpath, nm_suffix);
1377 if (nm_file_name == 0)
1378 nm_file_name = find_a_file (&path, full_nm_suffix);
1380 #ifdef LDD_SUFFIX
1381 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1382 if (ldd_file_name == 0)
1383 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1384 #endif
1386 #ifdef REAL_STRIP_FILE_NAME
1387 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1388 if (strip_file_name == 0)
1389 #endif
1390 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1391 if (strip_file_name == 0)
1392 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1393 if (strip_file_name == 0)
1394 strip_file_name = find_a_file (&cpath, strip_suffix);
1395 if (strip_file_name == 0)
1396 strip_file_name = find_a_file (&path, full_strip_suffix);
1398 /* Determine the full path name of the C compiler to use. */
1399 c_file_name = getenv ("COLLECT_GCC");
1400 if (c_file_name == 0)
1402 #ifdef CROSS_DIRECTORY_STRUCTURE
1403 c_file_name = concat (target_machine, "-gcc", NULL);
1404 #else
1405 c_file_name = "gcc";
1406 #endif
1409 p = find_a_file (&cpath, c_file_name);
1411 /* Here it should be safe to use the system search path since we should have
1412 already qualified the name of the compiler when it is needed. */
1413 if (p == 0)
1414 p = find_a_file (&path, c_file_name);
1416 if (p)
1417 c_file_name = p;
1419 *ld1++ = *ld2++ = ld_file_name;
1421 /* Make temp file names. */
1422 c_file = make_temp_file (".c");
1423 o_file = make_temp_file (".o");
1424 #ifdef COLLECT_EXPORT_LIST
1425 export_file = make_temp_file (".x");
1426 #endif
1427 ldout = make_temp_file (".ld");
1428 lderrout = make_temp_file (".le");
1429 *c_ptr++ = c_file_name;
1430 *c_ptr++ = "-x";
1431 *c_ptr++ = "c";
1432 *c_ptr++ = "-c";
1433 *c_ptr++ = "-o";
1434 *c_ptr++ = o_file;
1436 #ifdef COLLECT_EXPORT_LIST
1437 /* Generate a list of directories from LIBPATH. */
1438 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1439 /* Add to this list also two standard directories where
1440 AIX loader always searches for libraries. */
1441 add_prefix (&libpath_lib_dirs, "/lib");
1442 add_prefix (&libpath_lib_dirs, "/usr/lib");
1443 #endif
1445 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1447 AIX support needs to know if -shared has been specified before
1448 parsing commandline arguments. */
1450 p = getenv ("COLLECT_GCC_OPTIONS");
1451 while (p && *p)
1453 const char *q = extract_string (&p);
1454 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1455 *c_ptr++ = xstrdup (q);
1456 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1457 *c_ptr++ = xstrdup (q);
1458 if (strcmp (q, "-shared") == 0)
1459 shared_obj = 1;
1460 if (*q == '-' && q[1] == 'B')
1462 *c_ptr++ = xstrdup (q);
1463 if (q[2] == 0)
1465 q = extract_string (&p);
1466 *c_ptr++ = xstrdup (q);
1469 if (use_verbose && *q == '-' && q[1] == 'v' && q[2] == 0)
1471 /* Turn on trace in collect2 if needed. */
1472 vflag = 1;
1475 obstack_free (&temporary_obstack, temporary_firstobj);
1476 *c_ptr++ = "-fno-profile-arcs";
1477 *c_ptr++ = "-fno-test-coverage";
1478 *c_ptr++ = "-fno-branch-probabilities";
1479 *c_ptr++ = "-fno-exceptions";
1480 *c_ptr++ = "-w";
1481 *c_ptr++ = "-fno-whole-program";
1483 /* !!! When GCC calls collect2,
1484 it does not know whether it is calling collect2 or ld.
1485 So collect2 cannot meaningfully understand any options
1486 except those ld understands.
1487 If you propose to make GCC pass some other option,
1488 just imagine what will happen if ld is really ld!!! */
1490 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1491 /* After the first file, put in the c++ rt0. */
1493 first_file = 1;
1494 #ifdef HAVE_LD_DEMANGLE
1495 if (!demangle_flag && !no_demangle)
1496 demangle_flag = "--demangle";
1497 if (demangle_flag)
1498 *ld1++ = *ld2++ = demangle_flag;
1499 #endif
1500 while ((arg = *++argv) != (char *) 0)
1502 *ld1++ = *ld2++ = arg;
1504 if (arg[0] == '-')
1506 switch (arg[1])
1508 case 'd':
1509 if (!strcmp (arg, "-debug"))
1511 /* Already parsed. */
1512 ld1--;
1513 ld2--;
1515 if (!strcmp (arg, "-dynamic-linker") && argv[1])
1517 ++argv;
1518 *ld1++ = *ld2++ = *argv;
1520 break;
1522 case 'f':
1523 if (strcmp (arg, "-flto") == 0 || strcmp (arg, "-fwhopr") == 0)
1525 #ifdef ENABLE_LTO
1526 /* Do not pass LTO flag to the linker. */
1527 ld1--;
1528 ld2--;
1529 #else
1530 error ("LTO support has not been enabled in this "
1531 "configuration");
1532 #endif
1534 break;
1536 case 'l':
1537 if (first_file)
1539 /* place o_file BEFORE this argument! */
1540 first_file = 0;
1541 ld2--;
1542 *ld2++ = o_file;
1543 *ld2++ = arg;
1545 #ifdef COLLECT_EXPORT_LIST
1547 /* Resolving full library name. */
1548 const char *s = resolve_lib_name (arg+2);
1550 /* Saving a full library name. */
1551 add_to_list (&libs, s);
1553 #endif
1554 break;
1556 #ifdef COLLECT_EXPORT_LIST
1557 /* Saving directories where to search for libraries. */
1558 case 'L':
1559 add_prefix (&cmdline_lib_dirs, arg+2);
1560 break;
1561 #else
1562 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1563 case 'L':
1564 if (is_in_args (arg,
1565 CONST_CAST2 (const char **, char **, ld1_argv),
1566 ld1 - 1))
1567 --ld1;
1568 break;
1569 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1570 #endif
1572 case 'o':
1573 if (arg[2] == '\0')
1574 output_file = *ld1++ = *ld2++ = *++argv;
1575 else if (1
1576 #ifdef SWITCHES_NEED_SPACES
1577 && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1578 #endif
1581 output_file = &arg[2];
1582 break;
1584 case 'r':
1585 if (arg[2] == '\0')
1586 rflag = 1;
1587 break;
1589 case 's':
1590 if (arg[2] == '\0' && do_collecting)
1592 /* We must strip after the nm run, otherwise C++ linking
1593 will not work. Thus we strip in the second ld run, or
1594 else with strip if there is no second ld run. */
1595 strip_flag = 1;
1596 ld1--;
1598 break;
1600 case 'v':
1601 if (arg[2] == '\0')
1602 vflag = 1;
1603 break;
1605 case '-':
1606 if (strcmp (arg, "--no-demangle") == 0)
1608 demangle_flag = arg;
1609 no_demangle = 1;
1610 ld1--;
1611 ld2--;
1613 else if (strncmp (arg, "--demangle", 10) == 0)
1615 demangle_flag = arg;
1616 no_demangle = 0;
1617 #ifndef HAVE_LD_DEMANGLE
1618 if (arg[10] == '=')
1620 enum demangling_styles style
1621 = cplus_demangle_name_to_style (arg+11);
1622 if (style == unknown_demangling)
1623 error ("unknown demangling style '%s'", arg+11);
1624 else
1625 current_demangling_style = style;
1627 #endif
1628 ld1--;
1629 ld2--;
1631 else if (strncmp (arg, "--sysroot=", 10) == 0)
1632 target_system_root = arg + 10;
1633 break;
1636 else if ((p = strrchr (arg, '.')) != (char *) 0
1637 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1638 || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1639 || strcmp (p, ".obj") == 0))
1641 if (first_file)
1643 first_file = 0;
1644 if (p[1] == 'o')
1645 *ld2++ = o_file;
1646 else
1648 /* place o_file BEFORE this argument! */
1649 ld2--;
1650 *ld2++ = o_file;
1651 *ld2++ = arg;
1654 if (p[1] == 'o' || p[1] == 'l')
1655 *object++ = arg;
1656 #ifdef COLLECT_EXPORT_LIST
1657 /* libraries can be specified directly, i.e. without -l flag. */
1658 else
1660 /* Saving a full library name. */
1661 add_to_list (&libs, arg);
1663 #endif
1667 #ifdef COLLECT_EXPORT_LIST
1668 /* This is added only for debugging purposes. */
1669 if (debug)
1671 fprintf (stderr, "List of libraries:\n");
1672 dump_list (stderr, "\t", libs.first);
1675 /* The AIX linker will discard static constructors in object files if
1676 nothing else in the file is referenced, so look at them first. Unless
1677 we are building a shared object, ignore the eh frame tables, as we
1678 would otherwise reference them all, hence drag all the corresponding
1679 objects even if nothing else is referenced. */
1681 const char **export_object_lst
1682 = CONST_CAST2 (const char **, char **, object_lst);
1684 struct id *list = libs.first;
1686 /* Compute the filter to use from the current one, do scan, then adjust
1687 the "current" filter to remove what we just included here. This will
1688 control whether we need a first pass link later on or not, and what
1689 will remain to be scanned there. */
1691 scanfilter this_filter = ld1_filter;
1692 #if HAVE_AS_REF
1693 if (!shared_obj)
1694 this_filter &= ~SCAN_DWEH;
1695 #endif
1697 while (export_object_lst < object)
1698 scan_prog_file (*export_object_lst++, PASS_OBJ, this_filter);
1700 for (; list; list = list->next)
1701 scan_prog_file (list->name, PASS_FIRST, this_filter);
1703 ld1_filter = ld1_filter & ~this_filter;
1706 if (exports.first)
1708 char *buf = concat ("-bE:", export_file, NULL);
1710 *ld1++ = buf;
1711 *ld2++ = buf;
1713 exportf = fopen (export_file, "w");
1714 if (exportf == (FILE *) 0)
1715 fatal_perror ("fopen %s", export_file);
1716 write_aix_file (exportf, exports.first);
1717 if (fclose (exportf))
1718 fatal_perror ("fclose %s", export_file);
1720 #endif
1722 *c_ptr++ = c_file;
1723 *c_ptr = *ld1 = *object = (char *) 0;
1725 if (vflag)
1727 notice ("collect2 version %s", version_string);
1728 #ifdef TARGET_VERSION
1729 TARGET_VERSION;
1730 #endif
1731 fprintf (stderr, "\n");
1734 if (debug)
1736 const char *ptr;
1737 fprintf (stderr, "ld_file_name = %s\n",
1738 (ld_file_name ? ld_file_name : "not found"));
1739 fprintf (stderr, "c_file_name = %s\n",
1740 (c_file_name ? c_file_name : "not found"));
1741 fprintf (stderr, "nm_file_name = %s\n",
1742 (nm_file_name ? nm_file_name : "not found"));
1743 #ifdef LDD_SUFFIX
1744 fprintf (stderr, "ldd_file_name = %s\n",
1745 (ldd_file_name ? ldd_file_name : "not found"));
1746 #endif
1747 fprintf (stderr, "strip_file_name = %s\n",
1748 (strip_file_name ? strip_file_name : "not found"));
1749 fprintf (stderr, "c_file = %s\n",
1750 (c_file ? c_file : "not found"));
1751 fprintf (stderr, "o_file = %s\n",
1752 (o_file ? o_file : "not found"));
1754 ptr = getenv ("COLLECT_GCC_OPTIONS");
1755 if (ptr)
1756 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1758 ptr = getenv ("COLLECT_GCC");
1759 if (ptr)
1760 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1762 ptr = getenv ("COMPILER_PATH");
1763 if (ptr)
1764 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1766 ptr = getenv (LIBRARY_PATH_ENV);
1767 if (ptr)
1768 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1770 fprintf (stderr, "\n");
1773 /* Load the program, searching all libraries and attempting to provide
1774 undefined symbols from repository information.
1776 If -r or they will be run via some other method, do not build the
1777 constructor or destructor list, just return now. */
1779 bool early_exit
1780 = rflag || (! DO_COLLECT_EXPORT_LIST && ! do_collecting);
1782 /* Perform the first pass link now, if we're about to exit or if we need
1783 to scan for things we haven't collected yet before pursuing further.
1785 On AIX, the latter typically includes nothing for shared objects or
1786 frame tables for an executable, out of what the required early scan on
1787 objects and libraries has performed above. In the !shared_obj case, we
1788 expect the relevant tables to be dragged together with their associated
1789 functions from precise cross reference insertions by the compiler. */
1791 if (early_exit || ld1_filter != SCAN_NOTHING)
1792 do_tlink (ld1_argv, object_lst);
1794 if (early_exit)
1796 #ifdef COLLECT_EXPORT_LIST
1797 /* Make sure we delete the export file we may have created. */
1798 if (export_file != 0 && export_file[0])
1799 maybe_unlink (export_file);
1800 #endif
1801 if (lto_mode)
1802 maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1804 maybe_unlink (c_file);
1805 maybe_unlink (o_file);
1806 return 0;
1810 /* Unless we have done it all already, examine the namelist and search for
1811 static constructors and destructors to call. Write the constructor and
1812 destructor tables to a .s file and reload. */
1814 if (ld1_filter != SCAN_NOTHING)
1815 scan_prog_file (output_file, PASS_FIRST, ld1_filter);
1817 #ifdef SCAN_LIBRARIES
1818 scan_libraries (output_file);
1819 #endif
1821 if (debug)
1823 notice_translated (ngettext ("%d constructor found\n",
1824 "%d constructors found\n",
1825 constructors.number),
1826 constructors.number);
1827 notice_translated (ngettext ("%d destructor found\n",
1828 "%d destructors found\n",
1829 destructors.number),
1830 destructors.number);
1831 notice_translated (ngettext("%d frame table found\n",
1832 "%d frame tables found\n",
1833 frame_tables.number),
1834 frame_tables.number);
1837 /* If the scan exposed nothing of special interest, there's no need to
1838 generate the glue code and relink so return now. */
1840 if (constructors.number == 0 && destructors.number == 0
1841 && frame_tables.number == 0
1842 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1843 /* If we will be running these functions ourselves, we want to emit
1844 stubs into the shared library so that we do not have to relink
1845 dependent programs when we add static objects. */
1846 && ! shared_obj
1847 #endif
1850 /* Do tlink without additional code generation now if we didn't
1851 do it earlier for scanning purposes. */
1852 if (ld1_filter == SCAN_NOTHING)
1853 do_tlink (ld1_argv, object_lst);
1855 if (lto_mode)
1856 maybe_run_lto_and_relink (ld1_argv, object_lst, object, false);
1858 /* Strip now if it was requested on the command line. */
1859 if (strip_flag)
1861 char **real_strip_argv = XCNEWVEC (char *, 3);
1862 const char ** strip_argv = CONST_CAST2 (const char **, char **,
1863 real_strip_argv);
1865 strip_argv[0] = strip_file_name;
1866 strip_argv[1] = output_file;
1867 strip_argv[2] = (char *) 0;
1868 fork_execute ("strip", real_strip_argv);
1871 #ifdef COLLECT_EXPORT_LIST
1872 maybe_unlink (export_file);
1873 #endif
1874 maybe_unlink (c_file);
1875 maybe_unlink (o_file);
1876 return 0;
1879 /* Sort ctor and dtor lists by priority. */
1880 sort_ids (&constructors);
1881 sort_ids (&destructors);
1883 maybe_unlink(output_file);
1884 outf = fopen (c_file, "w");
1885 if (outf == (FILE *) 0)
1886 fatal_perror ("fopen %s", c_file);
1888 write_c_file (outf, c_file);
1890 if (fclose (outf))
1891 fatal_perror ("fclose %s", c_file);
1893 /* Tell the linker that we have initializer and finalizer functions. */
1894 #ifdef LD_INIT_SWITCH
1895 #ifdef COLLECT_EXPORT_LIST
1896 *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1897 #else
1898 *ld2++ = LD_INIT_SWITCH;
1899 *ld2++ = initname;
1900 *ld2++ = LD_FINI_SWITCH;
1901 *ld2++ = fininame;
1902 #endif
1903 #endif
1905 #ifdef COLLECT_EXPORT_LIST
1906 if (shared_obj)
1908 /* If we did not add export flag to link arguments before, add it to
1909 second link phase now. No new exports should have been added. */
1910 if (! exports.first)
1911 *ld2++ = concat ("-bE:", export_file, NULL);
1913 #ifndef LD_INIT_SWITCH
1914 add_to_list (&exports, initname);
1915 add_to_list (&exports, fininame);
1916 add_to_list (&exports, "_GLOBAL__DI");
1917 add_to_list (&exports, "_GLOBAL__DD");
1918 #endif
1919 exportf = fopen (export_file, "w");
1920 if (exportf == (FILE *) 0)
1921 fatal_perror ("fopen %s", export_file);
1922 write_aix_file (exportf, exports.first);
1923 if (fclose (exportf))
1924 fatal_perror ("fclose %s", export_file);
1926 #endif
1928 /* End of arguments to second link phase. */
1929 *ld2 = (char*) 0;
1931 if (debug)
1933 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1934 output_file, c_file);
1935 write_c_file (stderr, "stderr");
1936 fprintf (stderr, "========== end of c_file\n\n");
1937 #ifdef COLLECT_EXPORT_LIST
1938 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1939 write_aix_file (stderr, exports.first);
1940 fprintf (stderr, "========== end of export_file\n\n");
1941 #endif
1944 /* Assemble the constructor and destructor tables.
1945 Link the tables in with the rest of the program. */
1947 fork_execute ("gcc", c_argv);
1948 #ifdef COLLECT_EXPORT_LIST
1949 /* On AIX we must call tlink because of possible templates resolution. */
1950 do_tlink (ld2_argv, object_lst);
1952 if (lto_mode)
1953 maybe_run_lto_and_relink (ld2_argv, object_lst, object, false);
1954 #else
1955 /* Otherwise, simply call ld because tlink is already done. */
1956 if (lto_mode)
1957 maybe_run_lto_and_relink (ld2_argv, object_lst, object, true);
1958 else
1959 fork_execute ("ld", ld2_argv);
1961 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1962 constructors/destructors in shared libraries. */
1963 scan_prog_file (output_file, PASS_SECOND, SCAN_ALL);
1964 #endif
1966 maybe_unlink (c_file);
1967 maybe_unlink (o_file);
1969 #ifdef COLLECT_EXPORT_LIST
1970 maybe_unlink (export_file);
1971 #endif
1973 return 0;
1977 /* Wait for a process to finish, and exit if a nonzero status is found. */
1980 collect_wait (const char *prog, struct pex_obj *pex)
1982 int status;
1984 if (!pex_get_status (pex, 1, &status))
1985 fatal_perror ("can't get program status");
1986 pex_free (pex);
1988 if (status)
1990 if (WIFSIGNALED (status))
1992 int sig = WTERMSIG (status);
1993 error ("%s terminated with signal %d [%s]%s",
1994 prog, sig, strsignal(sig),
1995 WCOREDUMP(status) ? ", core dumped" : "");
1996 collect_exit (FATAL_EXIT_CODE);
1999 if (WIFEXITED (status))
2000 return WEXITSTATUS (status);
2002 return 0;
2005 static void
2006 do_wait (const char *prog, struct pex_obj *pex)
2008 int ret = collect_wait (prog, pex);
2009 if (ret != 0)
2011 error ("%s returned %d exit status", prog, ret);
2012 collect_exit (ret);
2015 if (response_file)
2017 unlink (response_file);
2018 response_file = NULL;
2023 /* Execute a program, and wait for the reply. */
2025 struct pex_obj *
2026 collect_execute (const char *prog, char **argv, const char *outname,
2027 const char *errname, int flags)
2029 struct pex_obj *pex;
2030 const char *errmsg;
2031 int err;
2032 char *response_arg = NULL;
2033 char *response_argv[3] ATTRIBUTE_UNUSED;
2035 if (HAVE_GNU_LD && at_file_supplied && argv[0] != NULL)
2037 /* If using @file arguments, create a temporary file and put the
2038 contents of argv into it. Then change argv to an array corresponding
2039 to a single argument @FILE, where FILE is the temporary filename. */
2041 char **current_argv = argv + 1;
2042 char *argv0 = argv[0];
2043 int status;
2044 FILE *f;
2046 /* Note: we assume argv contains at least one element; this is
2047 checked above. */
2049 response_file = make_temp_file ("");
2051 f = fopen (response_file, "w");
2053 if (f == NULL)
2054 fatal ("could not open response file %s", response_file);
2056 status = writeargv (current_argv, f);
2058 if (status)
2059 fatal ("could not write to response file %s", response_file);
2061 status = fclose (f);
2063 if (EOF == status)
2064 fatal ("could not close response file %s", response_file);
2066 response_arg = concat ("@", response_file, NULL);
2067 response_argv[0] = argv0;
2068 response_argv[1] = response_arg;
2069 response_argv[2] = NULL;
2071 argv = response_argv;
2074 if (vflag || debug)
2076 char **p_argv;
2077 const char *str;
2079 if (argv[0])
2080 fprintf (stderr, "%s", argv[0]);
2081 else
2082 notice ("[cannot find %s]", prog);
2084 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
2085 fprintf (stderr, " %s", str);
2087 fprintf (stderr, "\n");
2090 fflush (stdout);
2091 fflush (stderr);
2093 /* If we cannot find a program we need, complain error. Do this here
2094 since we might not end up needing something that we could not find. */
2096 if (argv[0] == 0)
2097 fatal ("cannot find '%s'", prog);
2099 pex = pex_init (0, "collect2", NULL);
2100 if (pex == NULL)
2101 fatal_perror ("pex_init failed");
2103 errmsg = pex_run (pex, flags, argv[0], argv, outname,
2104 errname, &err);
2105 if (errmsg != NULL)
2107 if (err != 0)
2109 errno = err;
2110 fatal_perror (errmsg);
2112 else
2113 fatal (errmsg);
2116 if (response_arg)
2117 free (response_arg);
2119 return pex;
2122 static void
2123 fork_execute (const char *prog, char **argv)
2125 struct pex_obj *pex;
2127 pex = collect_execute (prog, argv, NULL, NULL, PEX_LAST | PEX_SEARCH);
2128 do_wait (prog, pex);
2131 /* Unlink a file unless we are debugging. */
2133 static void
2134 maybe_unlink (const char *file)
2136 if (!debug)
2137 unlink_if_ordinary (file);
2138 else
2139 notice ("[Leaving %s]\n", file);
2142 /* Call maybe_unlink on the NULL-terminated list, FILE_LIST. */
2144 static void
2145 maybe_unlink_list (char **file_list)
2147 char **tmp = file_list;
2149 while (*tmp)
2150 maybe_unlink (*(tmp++));
2154 static long sequence_number = 0;
2156 /* Add a name to a linked list. */
2158 static void
2159 add_to_list (struct head *head_ptr, const char *name)
2161 struct id *newid
2162 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
2163 struct id *p;
2164 strcpy (newid->name, name);
2166 if (head_ptr->first)
2167 head_ptr->last->next = newid;
2168 else
2169 head_ptr->first = newid;
2171 /* Check for duplicate symbols. */
2172 for (p = head_ptr->first;
2173 strcmp (name, p->name) != 0;
2174 p = p->next)
2176 if (p != newid)
2178 head_ptr->last->next = 0;
2179 free (newid);
2180 return;
2183 newid->sequence = ++sequence_number;
2184 head_ptr->last = newid;
2185 head_ptr->number++;
2188 /* Grab the init priority number from an init function name that
2189 looks like "_GLOBAL_.I.12345.foo". */
2191 static int
2192 extract_init_priority (const char *name)
2194 int pos = 0, pri;
2196 while (name[pos] == '_')
2197 ++pos;
2198 pos += 10; /* strlen ("GLOBAL__X_") */
2200 /* Extract init_p number from ctor/dtor name. */
2201 pri = atoi (name + pos);
2202 return pri ? pri : DEFAULT_INIT_PRIORITY;
2205 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
2206 ctors will be run from right to left, dtors from left to right. */
2208 static void
2209 sort_ids (struct head *head_ptr)
2211 /* id holds the current element to insert. id_next holds the next
2212 element to insert. id_ptr iterates through the already sorted elements
2213 looking for the place to insert id. */
2214 struct id *id, *id_next, **id_ptr;
2216 id = head_ptr->first;
2218 /* We don't have any sorted elements yet. */
2219 head_ptr->first = NULL;
2221 for (; id; id = id_next)
2223 id_next = id->next;
2224 id->sequence = extract_init_priority (id->name);
2226 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
2227 if (*id_ptr == NULL
2228 /* If the sequence numbers are the same, we put the id from the
2229 file later on the command line later in the list. */
2230 || id->sequence > (*id_ptr)->sequence
2231 /* Hack: do lexical compare, too.
2232 || (id->sequence == (*id_ptr)->sequence
2233 && strcmp (id->name, (*id_ptr)->name) > 0) */
2236 id->next = *id_ptr;
2237 *id_ptr = id;
2238 break;
2242 /* Now set the sequence numbers properly so write_c_file works. */
2243 for (id = head_ptr->first; id; id = id->next)
2244 id->sequence = ++sequence_number;
2247 /* Write: `prefix', the names on list LIST, `suffix'. */
2249 static void
2250 write_list (FILE *stream, const char *prefix, struct id *list)
2252 while (list)
2254 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
2255 list = list->next;
2259 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
2260 /* Given a STRING, return nonzero if it occurs in the list in range
2261 [ARGS_BEGIN,ARGS_END). */
2263 static int
2264 is_in_args (const char *string, const char **args_begin,
2265 const char **args_end)
2267 const char **args_pointer;
2268 for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
2269 if (strcmp (string, *args_pointer) == 0)
2270 return 1;
2271 return 0;
2273 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
2275 #ifdef COLLECT_EXPORT_LIST
2276 /* This function is really used only on AIX, but may be useful. */
2277 #if 0
2278 static int
2279 is_in_list (const char *prefix, struct id *list)
2281 while (list)
2283 if (!strcmp (prefix, list->name)) return 1;
2284 list = list->next;
2286 return 0;
2288 #endif
2289 #endif /* COLLECT_EXPORT_LIST */
2291 /* Added for debugging purpose. */
2292 #ifdef COLLECT_EXPORT_LIST
2293 static void
2294 dump_list (FILE *stream, const char *prefix, struct id *list)
2296 while (list)
2298 fprintf (stream, "%s%s,\n", prefix, list->name);
2299 list = list->next;
2302 #endif
2304 #if 0
2305 static void
2306 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
2308 while (list)
2310 fprintf (stream, "%s%s,\n", prefix, list->prefix);
2311 list = list->next;
2314 #endif
2316 static void
2317 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
2319 while (list)
2321 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
2322 prefix, list->sequence, list->name);
2323 list = list->next;
2327 /* Write out the constructor and destructor tables statically (for a shared
2328 object), along with the functions to execute them. */
2330 static void
2331 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2333 const char *p, *q;
2334 char *prefix, *r;
2335 int frames = (frame_tables.number > 0);
2337 /* Figure out name of output_file, stripping off .so version. */
2338 p = strrchr (output_file, '/');
2339 if (p == 0)
2340 p = output_file;
2341 else
2342 p++;
2343 q = p;
2344 while (q)
2346 q = strchr (q,'.');
2347 if (q == 0)
2349 q = p + strlen (p);
2350 break;
2352 else
2354 if (strncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
2356 q += strlen (SHLIB_SUFFIX);
2357 break;
2359 else
2360 q++;
2363 /* q points to null at end of the string (or . of the .so version) */
2364 prefix = XNEWVEC (char, q - p + 1);
2365 strncpy (prefix, p, q - p);
2366 prefix[q - p] = 0;
2367 for (r = prefix; *r; r++)
2368 if (!ISALNUM ((unsigned char)*r))
2369 *r = '_';
2370 if (debug)
2371 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
2372 output_file, prefix);
2374 initname = concat ("_GLOBAL__FI_", prefix, NULL);
2375 fininame = concat ("_GLOBAL__FD_", prefix, NULL);
2377 free (prefix);
2379 /* Write the tables as C code. */
2381 fprintf (stream, "static int count;\n");
2382 fprintf (stream, "typedef void entry_pt();\n");
2383 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2385 if (frames)
2387 write_list_with_asm (stream, "extern void *", frame_tables.first);
2389 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2390 write_list (stream, "\t\t&", frame_tables.first);
2391 fprintf (stream, "\t0\n};\n");
2393 /* This must match what's in frame.h. */
2394 fprintf (stream, "struct object {\n");
2395 fprintf (stream, " void *pc_begin;\n");
2396 fprintf (stream, " void *pc_end;\n");
2397 fprintf (stream, " void *fde_begin;\n");
2398 fprintf (stream, " void *fde_array;\n");
2399 fprintf (stream, " __SIZE_TYPE__ count;\n");
2400 fprintf (stream, " struct object *next;\n");
2401 fprintf (stream, "};\n");
2403 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2404 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2406 fprintf (stream, "static void reg_frame () {\n");
2407 fprintf (stream, "\tstatic struct object ob;\n");
2408 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2409 fprintf (stream, "\t}\n");
2411 fprintf (stream, "static void dereg_frame () {\n");
2412 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2413 fprintf (stream, "\t}\n");
2416 fprintf (stream, "void %s() {\n", initname);
2417 if (constructors.number > 0 || frames)
2419 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2420 write_list (stream, "\t\t", constructors.first);
2421 if (frames)
2422 fprintf (stream, "\treg_frame,\n");
2423 fprintf (stream, "\t};\n");
2424 fprintf (stream, "\tentry_pt **p;\n");
2425 fprintf (stream, "\tif (count++ != 0) return;\n");
2426 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2427 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2429 else
2430 fprintf (stream, "\t++count;\n");
2431 fprintf (stream, "}\n");
2432 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2433 fprintf (stream, "void %s() {\n", fininame);
2434 if (destructors.number > 0 || frames)
2436 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2437 write_list (stream, "\t\t", destructors.first);
2438 if (frames)
2439 fprintf (stream, "\tdereg_frame,\n");
2440 fprintf (stream, "\t};\n");
2441 fprintf (stream, "\tentry_pt **p;\n");
2442 fprintf (stream, "\tif (--count != 0) return;\n");
2443 fprintf (stream, "\tp = dtors;\n");
2444 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2445 destructors.number + frames);
2447 fprintf (stream, "}\n");
2449 if (shared_obj)
2451 COLLECT_SHARED_INIT_FUNC(stream, initname);
2452 COLLECT_SHARED_FINI_FUNC(stream, fininame);
2456 /* Write the constructor/destructor tables. */
2458 #ifndef LD_INIT_SWITCH
2459 static void
2460 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2462 /* Write the tables as C code. */
2464 int frames = (frame_tables.number > 0);
2466 fprintf (stream, "typedef void entry_pt();\n\n");
2468 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2470 if (frames)
2472 write_list_with_asm (stream, "extern void *", frame_tables.first);
2474 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2475 write_list (stream, "\t\t&", frame_tables.first);
2476 fprintf (stream, "\t0\n};\n");
2478 /* This must match what's in frame.h. */
2479 fprintf (stream, "struct object {\n");
2480 fprintf (stream, " void *pc_begin;\n");
2481 fprintf (stream, " void *pc_end;\n");
2482 fprintf (stream, " void *fde_begin;\n");
2483 fprintf (stream, " void *fde_array;\n");
2484 fprintf (stream, " __SIZE_TYPE__ count;\n");
2485 fprintf (stream, " struct object *next;\n");
2486 fprintf (stream, "};\n");
2488 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2489 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2491 fprintf (stream, "static void reg_frame () {\n");
2492 fprintf (stream, "\tstatic struct object ob;\n");
2493 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2494 fprintf (stream, "\t}\n");
2496 fprintf (stream, "static void dereg_frame () {\n");
2497 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2498 fprintf (stream, "\t}\n");
2501 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2502 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2503 write_list (stream, "\t", constructors.first);
2504 if (frames)
2505 fprintf (stream, "\treg_frame,\n");
2506 fprintf (stream, "\t0\n};\n\n");
2508 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2510 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2511 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2512 write_list (stream, "\t", destructors.first);
2513 if (frames)
2514 fprintf (stream, "\tdereg_frame,\n");
2515 fprintf (stream, "\t0\n};\n\n");
2517 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2518 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2520 #endif /* ! LD_INIT_SWITCH */
2522 static void
2523 write_c_file (FILE *stream, const char *name)
2525 #ifndef LD_INIT_SWITCH
2526 if (! shared_obj)
2527 write_c_file_glob (stream, name);
2528 else
2529 #endif
2530 write_c_file_stat (stream, name);
2533 #ifdef COLLECT_EXPORT_LIST
2534 static void
2535 write_aix_file (FILE *stream, struct id *list)
2537 for (; list; list = list->next)
2539 fputs (list->name, stream);
2540 putc ('\n', stream);
2543 #endif
2545 #ifdef OBJECT_FORMAT_NONE
2547 /* Check to make sure the file is an ELF file. LTO objects must
2548 be in ELF format. */
2550 static bool
2551 is_elf (const char *prog_name)
2553 FILE *f;
2554 char buf[4];
2555 static char magic[4] = { 0x7f, 'E', 'L', 'F' };
2557 f = fopen (prog_name, "r");
2558 if (f == NULL)
2559 return false;
2560 if (fread (buf, sizeof (buf), 1, f) != 1)
2561 buf[0] = 0;
2562 fclose (f);
2563 return memcmp (buf, magic, sizeof (magic)) == 0;
2566 /* Generic version to scan the name list of the loaded program for
2567 the symbols g++ uses for static constructors and destructors. */
2569 static void
2570 scan_prog_file (const char *prog_name, scanpass which_pass,
2571 scanfilter filter)
2573 void (*int_handler) (int);
2574 #ifdef SIGQUIT
2575 void (*quit_handler) (int);
2576 #endif
2577 char *real_nm_argv[4];
2578 const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2579 int argc = 0;
2580 struct pex_obj *pex;
2581 const char *errmsg;
2582 int err;
2583 char *p, buf[1024];
2584 FILE *inf;
2585 int found_lto = 0;
2587 if (which_pass == PASS_SECOND)
2588 return;
2590 /* LTO objects must be in ELF format. This check prevents
2591 us from accepting an archive containing LTO objects, which
2592 gcc cannnot currently handle. */
2593 if (which_pass == PASS_LTOINFO && !is_elf (prog_name))
2594 return;
2596 /* If we do not have an `nm', complain. */
2597 if (nm_file_name == 0)
2598 fatal ("cannot find 'nm'");
2600 nm_argv[argc++] = nm_file_name;
2601 if (NM_FLAGS[0] != '\0')
2602 nm_argv[argc++] = NM_FLAGS;
2604 nm_argv[argc++] = prog_name;
2605 nm_argv[argc++] = (char *) 0;
2607 /* Trace if needed. */
2608 if (vflag)
2610 const char **p_argv;
2611 const char *str;
2613 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2614 fprintf (stderr, " %s", str);
2616 fprintf (stderr, "\n");
2619 fflush (stdout);
2620 fflush (stderr);
2622 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2623 if (pex == NULL)
2624 fatal_perror ("pex_init failed");
2626 errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, HOST_BIT_BUCKET,
2627 &err);
2628 if (errmsg != NULL)
2630 if (err != 0)
2632 errno = err;
2633 fatal_perror (errmsg);
2635 else
2636 fatal (errmsg);
2639 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2640 #ifdef SIGQUIT
2641 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2642 #endif
2644 inf = pex_read_output (pex, 0);
2645 if (inf == NULL)
2646 fatal_perror ("can't open nm output");
2648 if (debug)
2650 if (which_pass == PASS_LTOINFO)
2651 fprintf (stderr, "\nnm output with LTO info marker symbol.\n");
2652 else
2653 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2656 /* Read each line of nm output. */
2657 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2659 int ch, ch2;
2660 char *name, *end;
2662 if (debug)
2663 fprintf (stderr, "\t%s\n", buf);
2665 if (which_pass == PASS_LTOINFO)
2667 if (found_lto)
2668 continue;
2670 /* Look for the LTO info marker symbol, and add filename to
2671 the LTO objects list if found. */
2672 for (p = buf; (ch = *p) != '\0' && ch != '\n'; p++)
2673 if (ch == ' '
2674 && (strncmp (p + 1, "__gnu_lto_v1", 12) == 0)
2675 && ISSPACE (p[13]))
2677 add_lto_object (&lto_objects, prog_name);
2679 /* We need to read all the input, so we can't just
2680 return here. But we can avoid useless work. */
2681 found_lto = 1;
2683 break;
2686 continue;
2689 /* If it contains a constructor or destructor name, add the name
2690 to the appropriate list unless this is a kind of symbol we're
2691 not supposed to even consider. */
2693 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2694 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2695 break;
2697 if (ch != '_')
2698 continue;
2700 name = p;
2701 /* Find the end of the symbol name.
2702 Do not include `|', because Encore nm can tack that on the end. */
2703 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2704 end++)
2705 continue;
2708 *end = '\0';
2709 switch (is_ctor_dtor (name))
2711 case SYM_CTOR:
2712 if (! (filter & SCAN_CTOR))
2713 break;
2714 if (which_pass != PASS_LIB)
2715 add_to_list (&constructors, name);
2716 break;
2718 case SYM_DTOR:
2719 if (! (filter & SCAN_DTOR))
2720 break;
2721 if (which_pass != PASS_LIB)
2722 add_to_list (&destructors, name);
2723 break;
2725 case SYM_INIT:
2726 if (! (filter & SCAN_INIT))
2727 break;
2728 if (which_pass != PASS_LIB)
2729 fatal ("init function found in object %s", prog_name);
2730 #ifndef LD_INIT_SWITCH
2731 add_to_list (&constructors, name);
2732 #endif
2733 break;
2735 case SYM_FINI:
2736 if (! (filter & SCAN_FINI))
2737 break;
2738 if (which_pass != PASS_LIB)
2739 fatal ("fini function found in object %s", prog_name);
2740 #ifndef LD_FINI_SWITCH
2741 add_to_list (&destructors, name);
2742 #endif
2743 break;
2745 case SYM_DWEH:
2746 if (! (filter & SCAN_DWEH))
2747 break;
2748 if (which_pass != PASS_LIB)
2749 add_to_list (&frame_tables, name);
2750 break;
2752 default: /* not a constructor or destructor */
2753 continue;
2757 if (debug)
2758 fprintf (stderr, "\n");
2760 do_wait (nm_file_name, pex);
2762 signal (SIGINT, int_handler);
2763 #ifdef SIGQUIT
2764 signal (SIGQUIT, quit_handler);
2765 #endif
2768 #ifdef LDD_SUFFIX
2770 /* Use the List Dynamic Dependencies program to find shared libraries that
2771 the output file depends upon and their initialization/finalization
2772 routines, if any. */
2774 static void
2775 scan_libraries (const char *prog_name)
2777 static struct head libraries; /* list of shared libraries found */
2778 struct id *list;
2779 void (*int_handler) (int);
2780 #ifdef SIGQUIT
2781 void (*quit_handler) (int);
2782 #endif
2783 char *real_ldd_argv[4];
2784 const char **ldd_argv = CONST_CAST2 (const char **, char **, real_ldd_argv);
2785 int argc = 0;
2786 struct pex_obj *pex;
2787 const char *errmsg;
2788 int err;
2789 char buf[1024];
2790 FILE *inf;
2792 /* If we do not have an `ldd', complain. */
2793 if (ldd_file_name == 0)
2795 error ("cannot find 'ldd'");
2796 return;
2799 ldd_argv[argc++] = ldd_file_name;
2800 ldd_argv[argc++] = prog_name;
2801 ldd_argv[argc++] = (char *) 0;
2803 /* Trace if needed. */
2804 if (vflag)
2806 const char **p_argv;
2807 const char *str;
2809 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2810 fprintf (stderr, " %s", str);
2812 fprintf (stderr, "\n");
2815 fflush (stdout);
2816 fflush (stderr);
2818 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2819 if (pex == NULL)
2820 fatal_perror ("pex_init failed");
2822 errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2823 if (errmsg != NULL)
2825 if (err != 0)
2827 errno = err;
2828 fatal_perror (errmsg);
2830 else
2831 fatal (errmsg);
2834 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2835 #ifdef SIGQUIT
2836 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2837 #endif
2839 inf = pex_read_output (pex, 0);
2840 if (inf == NULL)
2841 fatal_perror ("can't open ldd output");
2843 if (debug)
2844 notice ("\nldd output with constructors/destructors.\n");
2846 /* Read each line of ldd output. */
2847 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2849 int ch2;
2850 char *name, *end, *p = buf;
2852 /* Extract names of libraries and add to list. */
2853 PARSE_LDD_OUTPUT (p);
2854 if (p == 0)
2855 continue;
2857 name = p;
2858 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2859 fatal ("dynamic dependency %s not found", buf);
2861 /* Find the end of the symbol name. */
2862 for (end = p;
2863 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2864 end++)
2865 continue;
2866 *end = '\0';
2868 if (access (name, R_OK) == 0)
2869 add_to_list (&libraries, name);
2870 else
2871 fatal ("unable to open dynamic dependency '%s'", buf);
2873 if (debug)
2874 fprintf (stderr, "\t%s\n", buf);
2876 if (debug)
2877 fprintf (stderr, "\n");
2879 do_wait (ldd_file_name, pex);
2881 signal (SIGINT, int_handler);
2882 #ifdef SIGQUIT
2883 signal (SIGQUIT, quit_handler);
2884 #endif
2886 /* Now iterate through the library list adding their symbols to
2887 the list. */
2888 for (list = libraries.first; list; list = list->next)
2889 scan_prog_file (list->name, PASS_LIB, SCAN_ALL);
2892 #endif /* LDD_SUFFIX */
2894 #endif /* OBJECT_FORMAT_NONE */
2898 * COFF specific stuff.
2901 #ifdef OBJECT_FORMAT_COFF
2903 #if defined (EXTENDED_COFF)
2905 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2906 # define GCC_SYMENT SYMR
2907 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2908 # define GCC_SYMINC(X) (1)
2909 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2910 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2912 #else
2914 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2915 # define GCC_SYMENT SYMENT
2916 # if defined (C_WEAKEXT)
2917 # define GCC_OK_SYMBOL(X) \
2918 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2919 ((X).n_scnum > N_UNDEF) && \
2920 (aix64_flag \
2921 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2922 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2923 # define GCC_UNDEF_SYMBOL(X) \
2924 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2925 ((X).n_scnum == N_UNDEF))
2926 # else
2927 # define GCC_OK_SYMBOL(X) \
2928 (((X).n_sclass == C_EXT) && \
2929 ((X).n_scnum > N_UNDEF) && \
2930 (aix64_flag \
2931 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2932 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2933 # define GCC_UNDEF_SYMBOL(X) \
2934 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2935 # endif
2936 # define GCC_SYMINC(X) ((X).n_numaux+1)
2937 # define GCC_SYMZERO(X) 0
2939 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2940 #if TARGET_AIX_VERSION >= 51
2941 # define GCC_CHECK_HDR(X) \
2942 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2943 || (HEADER (X).f_magic == 0767 && aix64_flag))
2944 #else
2945 # define GCC_CHECK_HDR(X) \
2946 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2947 || (HEADER (X).f_magic == 0757 && aix64_flag))
2948 #endif
2950 #endif
2952 #ifdef COLLECT_EXPORT_LIST
2953 /* Array of standard AIX libraries which should not
2954 be scanned for ctors/dtors. */
2955 static const char *const aix_std_libs[] = {
2956 "/unix",
2957 "/lib/libc.a",
2958 "/lib/libm.a",
2959 "/lib/libc_r.a",
2960 "/lib/libm_r.a",
2961 "/usr/lib/libc.a",
2962 "/usr/lib/libm.a",
2963 "/usr/lib/libc_r.a",
2964 "/usr/lib/libm_r.a",
2965 "/usr/lib/threads/libc.a",
2966 "/usr/ccs/lib/libc.a",
2967 "/usr/ccs/lib/libm.a",
2968 "/usr/ccs/lib/libc_r.a",
2969 "/usr/ccs/lib/libm_r.a",
2970 NULL
2973 /* This function checks the filename and returns 1
2974 if this name matches the location of a standard AIX library. */
2975 static int ignore_library (const char *);
2976 static int
2977 ignore_library (const char *name)
2979 const char *const *p;
2980 size_t length;
2982 if (target_system_root[0] != '\0')
2984 length = strlen (target_system_root);
2985 if (strncmp (name, target_system_root, length) != 0)
2986 return 0;
2987 name += length;
2989 for (p = &aix_std_libs[0]; *p != NULL; ++p)
2990 if (strcmp (name, *p) == 0)
2991 return 1;
2992 return 0;
2994 #endif /* COLLECT_EXPORT_LIST */
2996 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2997 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2998 #endif
3000 /* COFF version to scan the name list of the loaded program for
3001 the symbols g++ uses for static constructors and destructors. */
3003 static void
3004 scan_prog_file (const char *prog_name, scanpass which_pass,
3005 scanfilter filter)
3007 LDFILE *ldptr = NULL;
3008 int sym_index, sym_count;
3009 int is_shared = 0;
3011 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
3012 return;
3014 #ifdef COLLECT_EXPORT_LIST
3015 /* We do not need scanning for some standard C libraries. */
3016 if (which_pass == PASS_FIRST && ignore_library (prog_name))
3017 return;
3019 /* On AIX we have a loop, because there is not much difference
3020 between an object and an archive. This trick allows us to
3021 eliminate scan_libraries() function. */
3024 #endif
3025 /* Some platforms (e.g. OSF4) declare ldopen as taking a
3026 non-const char * filename parameter, even though it will not
3027 modify that string. So we must cast away const-ness here,
3028 using CONST_CAST to prevent complaints from -Wcast-qual. */
3029 if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
3031 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
3032 fatal ("%s: not a COFF file", prog_name);
3034 if (GCC_CHECK_HDR (ldptr))
3036 sym_count = GCC_SYMBOLS (ldptr);
3037 sym_index = GCC_SYMZERO (ldptr);
3039 #ifdef COLLECT_EXPORT_LIST
3040 /* Is current archive member a shared object? */
3041 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
3042 #endif
3044 while (sym_index < sym_count)
3046 GCC_SYMENT symbol;
3048 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
3049 break;
3050 sym_index += GCC_SYMINC (symbol);
3052 if (GCC_OK_SYMBOL (symbol))
3054 char *name;
3056 if ((name = ldgetname (ldptr, &symbol)) == NULL)
3057 continue; /* Should never happen. */
3059 #ifdef XCOFF_DEBUGGING_INFO
3060 /* All AIX function names have a duplicate entry
3061 beginning with a dot. */
3062 if (*name == '.')
3063 ++name;
3064 #endif
3066 switch (is_ctor_dtor (name))
3068 case SYM_CTOR:
3069 if (! (filter & SCAN_CTOR))
3070 break;
3071 if (! is_shared)
3072 add_to_list (&constructors, name);
3073 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3074 if (which_pass == PASS_OBJ)
3075 add_to_list (&exports, name);
3076 #endif
3077 break;
3079 case SYM_DTOR:
3080 if (! (filter & SCAN_DTOR))
3081 break;
3082 if (! is_shared)
3083 add_to_list (&destructors, name);
3084 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3085 if (which_pass == PASS_OBJ)
3086 add_to_list (&exports, name);
3087 #endif
3088 break;
3090 #ifdef COLLECT_EXPORT_LIST
3091 case SYM_INIT:
3092 if (! (filter & SCAN_INIT))
3093 break;
3094 #ifndef LD_INIT_SWITCH
3095 if (is_shared)
3096 add_to_list (&constructors, name);
3097 #endif
3098 break;
3100 case SYM_FINI:
3101 if (! (filter & SCAN_FINI))
3102 break;
3103 #ifndef LD_INIT_SWITCH
3104 if (is_shared)
3105 add_to_list (&destructors, name);
3106 #endif
3107 break;
3108 #endif
3110 case SYM_DWEH:
3111 if (! (filter & SCAN_DWEH))
3112 break;
3113 if (! is_shared)
3114 add_to_list (&frame_tables, name);
3115 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
3116 if (which_pass == PASS_OBJ)
3117 add_to_list (&exports, name);
3118 #endif
3119 break;
3121 default: /* not a constructor or destructor */
3122 #ifdef COLLECT_EXPORT_LIST
3123 /* Explicitly export all global symbols when
3124 building a shared object on AIX, but do not
3125 re-export symbols from another shared object
3126 and do not export symbols if the user
3127 provides an explicit export list. */
3128 if (shared_obj && !is_shared
3129 && which_pass == PASS_OBJ && !export_flag)
3130 add_to_list (&exports, name);
3131 #endif
3132 continue;
3135 if (debug)
3136 #if !defined(EXTENDED_COFF)
3137 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
3138 symbol.n_scnum, symbol.n_sclass,
3139 (symbol.n_type ? "0" : ""), symbol.n_type,
3140 name);
3141 #else
3142 fprintf (stderr,
3143 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
3144 symbol.iss, (long) symbol.value, symbol.index, name);
3145 #endif
3149 #ifdef COLLECT_EXPORT_LIST
3150 else
3152 /* If archive contains both 32-bit and 64-bit objects,
3153 we want to skip objects in other mode so mismatch normal. */
3154 if (debug)
3155 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
3156 prog_name, HEADER (ldptr).f_magic, aix64_flag);
3158 #endif
3160 else
3162 fatal ("%s: cannot open as COFF file", prog_name);
3164 #ifdef COLLECT_EXPORT_LIST
3165 /* On AIX loop continues while there are more members in archive. */
3167 while (ldclose (ldptr) == FAILURE);
3168 #else
3169 /* Otherwise we simply close ldptr. */
3170 (void) ldclose(ldptr);
3171 #endif
3173 #endif /* OBJECT_FORMAT_COFF */
3175 #ifdef COLLECT_EXPORT_LIST
3176 /* Given a library name without "lib" prefix, this function
3177 returns a full library name including a path. */
3178 static char *
3179 resolve_lib_name (const char *name)
3181 char *lib_buf;
3182 int i, j, l = 0;
3183 /* Library extensions for AIX dynamic linking. */
3184 const char * const libexts[2] = {"a", "so"};
3186 for (i = 0; libpaths[i]; i++)
3187 if (libpaths[i]->max_len > l)
3188 l = libpaths[i]->max_len;
3190 lib_buf = XNEWVEC (char, l + strlen(name) + 10);
3192 for (i = 0; libpaths[i]; i++)
3194 struct prefix_list *list = libpaths[i]->plist;
3195 for (; list; list = list->next)
3197 /* The following lines are needed because path_prefix list
3198 may contain directories both with trailing '/' and
3199 without it. */
3200 const char *p = "";
3201 if (list->prefix[strlen(list->prefix)-1] != '/')
3202 p = "/";
3203 for (j = 0; j < 2; j++)
3205 sprintf (lib_buf, "%s%slib%s.%s",
3206 list->prefix, p, name,
3207 libexts[(j + aixrtl_flag) % 2]);
3208 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
3209 if (file_exists (lib_buf))
3211 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
3212 return (lib_buf);
3217 if (debug)
3218 fprintf (stderr, "not found\n");
3219 else
3220 fatal ("library lib%s not found", name);
3221 return (NULL);
3223 #endif /* COLLECT_EXPORT_LIST */