Enable dumping of alias graphs.
[official-gcc/Ramakrishna.git] / gcc / collect2.c
blobb235f2bda8435cd9d6facd0ec2b7c49ef1080546
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
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 int debug; /* true if -debug */
189 static int shared_obj; /* true if -shared */
191 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
192 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
193 #ifdef COLLECT_EXPORT_LIST
194 static const char *export_file; /* <xxx>.x for AIX export list. */
195 #endif
196 const char *ldout; /* File for ld stdout. */
197 const char *lderrout; /* File for ld stderr. */
198 static const char *output_file; /* Output file for ld. */
199 static const char *nm_file_name; /* pathname of nm */
200 #ifdef LDD_SUFFIX
201 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
202 #endif
203 static const char *strip_file_name; /* pathname of strip */
204 const char *c_file_name; /* pathname of gcc */
205 static char *initname, *fininame; /* names of init and fini funcs */
207 static struct head constructors; /* list of constructors found */
208 static struct head destructors; /* list of destructors found */
209 #ifdef COLLECT_EXPORT_LIST
210 static struct head exports; /* list of exported symbols */
211 #endif
212 static struct head frame_tables; /* list of frame unwind info tables */
214 static bool at_file_supplied; /* Whether to use @file arguments */
215 static char *response_file; /* Name of any current response file */
217 struct obstack temporary_obstack;
218 char * temporary_firstobj;
220 /* A string that must be prepended to a target OS path in order to find
221 it on the host system. */
222 #ifdef TARGET_SYSTEM_ROOT
223 static const char *target_system_root = TARGET_SYSTEM_ROOT;
224 #else
225 static const char *target_system_root = "";
226 #endif
228 /* Structure to hold all the directories in which to search for files to
229 execute. */
231 struct prefix_list
233 const char *prefix; /* String to prepend to the path. */
234 struct prefix_list *next; /* Next in linked list. */
237 struct path_prefix
239 struct prefix_list *plist; /* List of prefixes to try */
240 int max_len; /* Max length of a prefix in PLIST */
241 const char *name; /* Name of this list (used in config stuff) */
244 #ifdef COLLECT_EXPORT_LIST
245 /* Lists to keep libraries to be scanned for global constructors/destructors. */
246 static struct head libs; /* list of libraries */
247 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
248 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
249 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
250 &libpath_lib_dirs, NULL};
251 #endif
253 /* Special kinds of symbols that a name may denote. */
255 typedef enum {
256 SYM_REGULAR = 0, /* nothing special */
258 SYM_CTOR = 1, /* constructor */
259 SYM_DTOR = 2, /* destructor */
260 SYM_INIT = 3, /* shared object routine that calls all the ctors */
261 SYM_FINI = 4, /* shared object routine that calls all the dtors */
262 SYM_DWEH = 5 /* DWARF exception handling table */
263 } symkind;
265 static symkind is_ctor_dtor (const char *);
267 static void handler (int);
268 static char *find_a_file (struct path_prefix *, const char *);
269 static void add_prefix (struct path_prefix *, const char *);
270 static void prefix_from_env (const char *, struct path_prefix *);
271 static void prefix_from_string (const char *, struct path_prefix *);
272 static void do_wait (const char *, struct pex_obj *);
273 static void fork_execute (const char *, char **);
274 static void maybe_unlink (const char *);
275 static void add_to_list (struct head *, const char *);
276 static int extract_init_priority (const char *);
277 static void sort_ids (struct head *);
278 static void write_list (FILE *, const char *, struct id *);
279 #ifdef COLLECT_EXPORT_LIST
280 static void dump_list (FILE *, const char *, struct id *);
281 #endif
282 #if 0
283 static void dump_prefix_list (FILE *, const char *, struct prefix_list *);
284 #endif
285 static void write_list_with_asm (FILE *, const char *, struct id *);
286 static void write_c_file (FILE *, const char *);
287 static void write_c_file_stat (FILE *, const char *);
288 #ifndef LD_INIT_SWITCH
289 static void write_c_file_glob (FILE *, const char *);
290 #endif
291 #ifdef SCAN_LIBRARIES
292 static void scan_libraries (const char *);
293 #endif
294 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
295 static int is_in_args (const char *, const char **, const char **);
296 #endif
297 #ifdef COLLECT_EXPORT_LIST
298 #if 0
299 static int is_in_list (const char *, struct id *);
300 #endif
301 static void write_aix_file (FILE *, struct id *);
302 static char *resolve_lib_name (const char *);
303 #endif
304 static char *extract_string (const char **);
306 /* Enumerations describing which pass this is for scanning the
307 program file ... */
309 typedef enum {
310 PASS_FIRST, /* without constructors */
311 PASS_OBJ, /* individual objects */
312 PASS_LIB, /* looking for shared libraries */
313 PASS_SECOND /* with constructors linked in */
314 } scanpass;
316 /* ... and which kinds of symbols are to be considered. */
318 enum scanfilter_masks {
319 SCAN_NOTHING = 0,
321 SCAN_CTOR = 1 << SYM_CTOR,
322 SCAN_DTOR = 1 << SYM_DTOR,
323 SCAN_INIT = 1 << SYM_INIT,
324 SCAN_FINI = 1 << SYM_FINI,
325 SCAN_DWEH = 1 << SYM_DWEH,
326 SCAN_ALL = ~0
329 /* This type is used for parameters and variables which hold
330 combinations of the flags in enum scanfilter_masks. */
331 typedef int scanfilter;
333 /* Scan the name list of the loaded program for the symbols g++ uses for
334 static constructors and destructors.
336 The SCANPASS argument tells which collect processing pass this is for and
337 the SCANFILTER argument tells which kinds of symbols to consider in this
338 pass. Symbols of a special kind not in the filter mask are considered as
339 regular ones.
341 The constructor table begins at __CTOR_LIST__ and contains a count of the
342 number of pointers (or -1 if the constructors are built in a separate
343 section by the linker), followed by the pointers to the constructor
344 functions, terminated with a null pointer. The destructor table has the
345 same format, and begins at __DTOR_LIST__. */
347 static void scan_prog_file (const char *, scanpass, scanfilter);
350 /* Delete tempfiles and exit function. */
352 void
353 collect_exit (int status)
355 if (c_file != 0 && c_file[0])
356 maybe_unlink (c_file);
358 if (o_file != 0 && o_file[0])
359 maybe_unlink (o_file);
361 #ifdef COLLECT_EXPORT_LIST
362 if (export_file != 0 && export_file[0])
363 maybe_unlink (export_file);
364 #endif
366 if (ldout != 0 && ldout[0])
368 dump_file (ldout, stdout);
369 maybe_unlink (ldout);
372 if (lderrout != 0 && lderrout[0])
374 dump_file (lderrout, stderr);
375 maybe_unlink (lderrout);
378 if (status != 0 && output_file != 0 && output_file[0])
379 maybe_unlink (output_file);
381 if (response_file)
382 maybe_unlink (response_file);
384 exit (status);
388 /* Notify user of a non-error. */
389 void
390 notice (const char *cmsgid, ...)
392 va_list ap;
394 va_start (ap, cmsgid);
395 vfprintf (stderr, _(cmsgid), ap);
396 va_end (ap);
399 /* Die when sys call fails. */
401 void
402 fatal_perror (const char * cmsgid, ...)
404 int e = errno;
405 va_list ap;
407 va_start (ap, cmsgid);
408 fprintf (stderr, "collect2: ");
409 vfprintf (stderr, _(cmsgid), ap);
410 fprintf (stderr, ": %s\n", xstrerror (e));
411 va_end (ap);
413 collect_exit (FATAL_EXIT_CODE);
416 /* Just die. */
418 void
419 fatal (const char * cmsgid, ...)
421 va_list ap;
423 va_start (ap, cmsgid);
424 fprintf (stderr, "collect2: ");
425 vfprintf (stderr, _(cmsgid), ap);
426 fprintf (stderr, "\n");
427 va_end (ap);
429 collect_exit (FATAL_EXIT_CODE);
432 /* Write error message. */
434 void
435 error (const char * gmsgid, ...)
437 va_list ap;
439 va_start (ap, gmsgid);
440 fprintf (stderr, "collect2: ");
441 vfprintf (stderr, _(gmsgid), ap);
442 fprintf (stderr, "\n");
443 va_end(ap);
446 /* In case obstack is linked in, and abort is defined to fancy_abort,
447 provide a default entry. */
449 void
450 fancy_abort (const char *file, int line, const char *func)
452 fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
455 static void
456 handler (int signo)
458 if (c_file != 0 && c_file[0])
459 maybe_unlink (c_file);
461 if (o_file != 0 && o_file[0])
462 maybe_unlink (o_file);
464 if (ldout != 0 && ldout[0])
465 maybe_unlink (ldout);
467 if (lderrout != 0 && lderrout[0])
468 maybe_unlink (lderrout);
470 #ifdef COLLECT_EXPORT_LIST
471 if (export_file != 0 && export_file[0])
472 maybe_unlink (export_file);
473 #endif
475 if (response_file)
476 maybe_unlink (response_file);
478 signal (signo, SIG_DFL);
479 raise (signo);
484 file_exists (const char *name)
486 return access (name, R_OK) == 0;
489 /* Parse a reasonable subset of shell quoting syntax. */
491 static char *
492 extract_string (const char **pp)
494 const char *p = *pp;
495 int backquote = 0;
496 int inside = 0;
498 for (;;)
500 char c = *p;
501 if (c == '\0')
502 break;
503 ++p;
504 if (backquote)
505 obstack_1grow (&temporary_obstack, c);
506 else if (! inside && c == ' ')
507 break;
508 else if (! inside && c == '\\')
509 backquote = 1;
510 else if (c == '\'')
511 inside = !inside;
512 else
513 obstack_1grow (&temporary_obstack, c);
516 obstack_1grow (&temporary_obstack, '\0');
517 *pp = p;
518 return XOBFINISH (&temporary_obstack, char *);
521 void
522 dump_file (const char *name, FILE *to)
524 FILE *stream = fopen (name, "r");
526 if (stream == 0)
527 return;
528 while (1)
530 int c;
531 while (c = getc (stream),
532 c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
533 obstack_1grow (&temporary_obstack, c);
534 if (obstack_object_size (&temporary_obstack) > 0)
536 const char *word, *p;
537 char *result;
538 obstack_1grow (&temporary_obstack, '\0');
539 word = XOBFINISH (&temporary_obstack, const char *);
541 if (*word == '.')
542 ++word, putc ('.', to);
543 p = word;
544 if (!strncmp (p, USER_LABEL_PREFIX, strlen (USER_LABEL_PREFIX)))
545 p += strlen (USER_LABEL_PREFIX);
547 #ifdef HAVE_LD_DEMANGLE
548 result = 0;
549 #else
550 if (no_demangle)
551 result = 0;
552 else
553 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
554 #endif
556 if (result)
558 int diff;
559 fputs (result, to);
561 diff = strlen (word) - strlen (result);
562 while (diff > 0 && c == ' ')
563 --diff, putc (' ', to);
564 if (diff < 0 && c == ' ')
566 while (diff < 0 && c == ' ')
567 ++diff, c = getc (stream);
568 if (!ISSPACE (c))
570 /* Make sure we output at least one space, or
571 the demangled symbol name will run into
572 whatever text follows. */
573 putc (' ', to);
577 free (result);
579 else
580 fputs (word, to);
582 fflush (to);
583 obstack_free (&temporary_obstack, temporary_firstobj);
585 if (c == EOF)
586 break;
587 putc (c, to);
589 fclose (stream);
592 /* Return the kind of symbol denoted by name S. */
594 static symkind
595 is_ctor_dtor (const char *s)
597 struct names { const char *const name; const int len; symkind ret;
598 const int two_underscores; };
600 const struct names *p;
601 int ch;
602 const char *orig_s = s;
604 static const struct names special[] = {
605 #ifndef NO_DOLLAR_IN_LABEL
606 { "GLOBAL__I$", sizeof ("GLOBAL__I$")-1, SYM_CTOR, 0 },
607 { "GLOBAL__D$", sizeof ("GLOBAL__D$")-1, SYM_DTOR, 0 },
608 #else
609 #ifndef NO_DOT_IN_LABEL
610 { "GLOBAL__I.", sizeof ("GLOBAL__I.")-1, SYM_CTOR, 0 },
611 { "GLOBAL__D.", sizeof ("GLOBAL__D.")-1, SYM_DTOR, 0 },
612 #endif /* NO_DOT_IN_LABEL */
613 #endif /* NO_DOLLAR_IN_LABEL */
614 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, SYM_CTOR, 0 },
615 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, SYM_DTOR, 0 },
616 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, SYM_DWEH, 0 },
617 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, SYM_INIT, 0 },
618 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, SYM_FINI, 0 },
619 { NULL, 0, SYM_REGULAR, 0 }
622 while ((ch = *s) == '_')
623 ++s;
625 if (s == orig_s)
626 return SYM_REGULAR;
628 for (p = &special[0]; p->len > 0; p++)
630 if (ch == p->name[0]
631 && (!p->two_underscores || ((s - orig_s) >= 2))
632 && strncmp(s, p->name, p->len) == 0)
634 return p->ret;
637 return SYM_REGULAR;
640 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
641 and one from the PATH variable. */
643 static struct path_prefix cpath, path;
645 #ifdef CROSS_DIRECTORY_STRUCTURE
646 /* This is the name of the target machine. We use it to form the name
647 of the files to execute. */
649 static const char *const target_machine = TARGET_MACHINE;
650 #endif
652 /* Search for NAME using prefix list PPREFIX. We only look for executable
653 files.
655 Return 0 if not found, otherwise return its name, allocated with malloc. */
657 static char *
658 find_a_file (struct path_prefix *pprefix, const char *name)
660 char *temp;
661 struct prefix_list *pl;
662 int len = pprefix->max_len + strlen (name) + 1;
664 if (debug)
665 fprintf (stderr, "Looking for '%s'\n", name);
667 #ifdef HOST_EXECUTABLE_SUFFIX
668 len += strlen (HOST_EXECUTABLE_SUFFIX);
669 #endif
671 temp = XNEWVEC (char, len);
673 /* Determine the filename to execute (special case for absolute paths). */
675 if (IS_ABSOLUTE_PATH (name))
677 if (access (name, X_OK) == 0)
679 strcpy (temp, name);
681 if (debug)
682 fprintf (stderr, " - found: absolute path\n");
684 return temp;
687 #ifdef HOST_EXECUTABLE_SUFFIX
688 /* Some systems have a suffix for executable files.
689 So try appending that. */
690 strcpy (temp, name);
691 strcat (temp, HOST_EXECUTABLE_SUFFIX);
693 if (access (temp, X_OK) == 0)
694 return temp;
695 #endif
697 if (debug)
698 fprintf (stderr, " - failed to locate using absolute path\n");
700 else
701 for (pl = pprefix->plist; pl; pl = pl->next)
703 struct stat st;
705 strcpy (temp, pl->prefix);
706 strcat (temp, name);
708 if (stat (temp, &st) >= 0
709 && ! S_ISDIR (st.st_mode)
710 && access (temp, X_OK) == 0)
711 return temp;
713 #ifdef HOST_EXECUTABLE_SUFFIX
714 /* Some systems have a suffix for executable files.
715 So try appending that. */
716 strcat (temp, HOST_EXECUTABLE_SUFFIX);
718 if (stat (temp, &st) >= 0
719 && ! S_ISDIR (st.st_mode)
720 && access (temp, X_OK) == 0)
721 return temp;
722 #endif
725 if (debug && pprefix->plist == NULL)
726 fprintf (stderr, " - failed: no entries in prefix list\n");
728 free (temp);
729 return 0;
732 /* Add an entry for PREFIX to prefix list PPREFIX. */
734 static void
735 add_prefix (struct path_prefix *pprefix, const char *prefix)
737 struct prefix_list *pl, **prev;
738 int len;
740 if (pprefix->plist)
742 for (pl = pprefix->plist; pl->next; pl = pl->next)
744 prev = &pl->next;
746 else
747 prev = &pprefix->plist;
749 /* Keep track of the longest prefix. */
751 len = strlen (prefix);
752 if (len > pprefix->max_len)
753 pprefix->max_len = len;
755 pl = XNEW (struct prefix_list);
756 pl->prefix = xstrdup (prefix);
758 if (*prev)
759 pl->next = *prev;
760 else
761 pl->next = (struct prefix_list *) 0;
762 *prev = pl;
765 /* Take the value of the environment variable ENV, break it into a path, and
766 add of the entries to PPREFIX. */
768 static void
769 prefix_from_env (const char *env, struct path_prefix *pprefix)
771 const char *p;
772 GET_ENVIRONMENT (p, env);
774 if (p)
775 prefix_from_string (p, pprefix);
778 static void
779 prefix_from_string (const char *p, struct path_prefix *pprefix)
781 const char *startp, *endp;
782 char *nstore = XNEWVEC (char, strlen (p) + 3);
784 if (debug)
785 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
787 startp = endp = p;
788 while (1)
790 if (*endp == PATH_SEPARATOR || *endp == 0)
792 strncpy (nstore, startp, endp-startp);
793 if (endp == startp)
795 strcpy (nstore, "./");
797 else if (! IS_DIR_SEPARATOR (endp[-1]))
799 nstore[endp-startp] = DIR_SEPARATOR;
800 nstore[endp-startp+1] = 0;
802 else
803 nstore[endp-startp] = 0;
805 if (debug)
806 fprintf (stderr, " - add prefix: %s\n", nstore);
808 add_prefix (pprefix, nstore);
809 if (*endp == 0)
810 break;
811 endp = startp = endp + 1;
813 else
814 endp++;
816 free (nstore);
819 /* Main program. */
822 main (int argc, char **argv)
824 static const char *const ld_suffix = "ld";
825 static const char *const real_ld_suffix = "real-ld";
826 static const char *const collect_ld_suffix = "collect-ld";
827 static const char *const nm_suffix = "nm";
828 static const char *const gnm_suffix = "gnm";
829 #ifdef LDD_SUFFIX
830 static const char *const ldd_suffix = LDD_SUFFIX;
831 #endif
832 static const char *const strip_suffix = "strip";
833 static const char *const gstrip_suffix = "gstrip";
835 #ifdef CROSS_DIRECTORY_STRUCTURE
836 /* If we look for a program in the compiler directories, we just use
837 the short name, since these directories are already system-specific.
838 But it we look for a program in the system directories, we need to
839 qualify the program name with the target machine. */
841 const char *const full_ld_suffix =
842 concat(target_machine, "-", ld_suffix, NULL);
843 const char *const full_nm_suffix =
844 concat (target_machine, "-", nm_suffix, NULL);
845 const char *const full_gnm_suffix =
846 concat (target_machine, "-", gnm_suffix, NULL);
847 #ifdef LDD_SUFFIX
848 const char *const full_ldd_suffix =
849 concat (target_machine, "-", ldd_suffix, NULL);
850 #endif
851 const char *const full_strip_suffix =
852 concat (target_machine, "-", strip_suffix, NULL);
853 const char *const full_gstrip_suffix =
854 concat (target_machine, "-", gstrip_suffix, NULL);
855 #else
856 const char *const full_ld_suffix = ld_suffix;
857 const char *const full_nm_suffix = nm_suffix;
858 const char *const full_gnm_suffix = gnm_suffix;
859 #ifdef LDD_SUFFIX
860 const char *const full_ldd_suffix = ldd_suffix;
861 #endif
862 const char *const full_strip_suffix = strip_suffix;
863 const char *const full_gstrip_suffix = gstrip_suffix;
864 #endif /* CROSS_DIRECTORY_STRUCTURE */
866 const char *arg;
867 FILE *outf;
868 #ifdef COLLECT_EXPORT_LIST
869 FILE *exportf;
870 #endif
871 const char *ld_file_name;
872 const char *p;
873 char **c_argv;
874 const char **c_ptr;
875 char **ld1_argv;
876 const char **ld1;
878 /* The kinds of symbols we will have to consider when scanning the
879 outcome of a first pass link. This is ALL to start with, then might
880 be adjusted before getting to the first pass link per se, typically on
881 AIX where we perform an early scan of objects and libraries to fetch
882 the list of global ctors/dtors and make sure they are not garbage
883 collected. */
884 scanfilter ld1_filter = SCAN_ALL;
886 char **ld2_argv;
887 const char **ld2;
888 char **object_lst;
889 const char **object;
890 int first_file;
891 int num_c_args;
892 char **old_argv;
894 old_argv = argv;
895 expandargv (&argc, &argv);
896 if (argv != old_argv)
897 at_file_supplied = 1;
899 num_c_args = argc + 9;
901 no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
903 /* Suppress demangling by the real linker, which may be broken. */
904 putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
906 #if defined (COLLECT2_HOST_INITIALIZATION)
907 /* Perform system dependent initialization, if necessary. */
908 COLLECT2_HOST_INITIALIZATION;
909 #endif
911 #ifdef SIGCHLD
912 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
913 receive the signal. A different setting is inheritable */
914 signal (SIGCHLD, SIG_DFL);
915 #endif
917 /* Unlock the stdio streams. */
918 unlock_std_streams ();
920 gcc_init_libintl ();
922 /* Do not invoke xcalloc before this point, since locale needs to be
923 set first, in case a diagnostic is issued. */
925 ld1_argv = XCNEWVEC (char *, argc + 4);
926 ld1 = CONST_CAST2 (const char **, char **, ld1_argv);
927 ld2_argv = XCNEWVEC (char *, argc + 11);
928 ld2 = CONST_CAST2 (const char **, char **, ld2_argv);
929 object_lst = XCNEWVEC (char *, argc);
930 object = CONST_CAST2 (const char **, char **, object_lst);
932 #ifdef DEBUG
933 debug = 1;
934 #endif
936 /* Parse command line early for instances of -debug. This allows
937 the debug flag to be set before functions like find_a_file()
938 are called. */
940 int i;
942 for (i = 1; argv[i] != NULL; i ++)
944 if (! strcmp (argv[i], "-debug"))
945 debug = 1;
947 vflag = debug;
950 #ifndef DEFAULT_A_OUT_NAME
951 output_file = "a.out";
952 #else
953 output_file = DEFAULT_A_OUT_NAME;
954 #endif
956 obstack_begin (&temporary_obstack, 0);
957 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
959 #ifndef HAVE_LD_DEMANGLE
960 current_demangling_style = auto_demangling;
961 #endif
962 p = getenv ("COLLECT_GCC_OPTIONS");
963 while (p && *p)
965 const char *q = extract_string (&p);
966 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
967 num_c_args++;
969 obstack_free (&temporary_obstack, temporary_firstobj);
971 /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
972 -fno-exceptions -w */
973 num_c_args += 5;
975 c_argv = XCNEWVEC (char *, num_c_args);
976 c_ptr = CONST_CAST2 (const char **, char **, c_argv);
978 if (argc < 2)
979 fatal ("no arguments");
981 #ifdef SIGQUIT
982 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
983 signal (SIGQUIT, handler);
984 #endif
985 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
986 signal (SIGINT, handler);
987 #ifdef SIGALRM
988 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
989 signal (SIGALRM, handler);
990 #endif
991 #ifdef SIGHUP
992 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
993 signal (SIGHUP, handler);
994 #endif
995 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
996 signal (SIGSEGV, handler);
997 #ifdef SIGBUS
998 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
999 signal (SIGBUS, handler);
1000 #endif
1002 /* Extract COMPILER_PATH and PATH into our prefix list. */
1003 prefix_from_env ("COMPILER_PATH", &cpath);
1004 prefix_from_env ("PATH", &path);
1006 /* Try to discover a valid linker/nm/strip to use. */
1008 /* Maybe we know the right file to use (if not cross). */
1009 ld_file_name = 0;
1010 #ifdef DEFAULT_LINKER
1011 if (access (DEFAULT_LINKER, X_OK) == 0)
1012 ld_file_name = DEFAULT_LINKER;
1013 if (ld_file_name == 0)
1014 #endif
1015 #ifdef REAL_LD_FILE_NAME
1016 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1017 if (ld_file_name == 0)
1018 #endif
1019 /* Search the (target-specific) compiler dirs for ld'. */
1020 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1021 /* Likewise for `collect-ld'. */
1022 if (ld_file_name == 0)
1023 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1024 /* Search the compiler directories for `ld'. We have protection against
1025 recursive calls in find_a_file. */
1026 if (ld_file_name == 0)
1027 ld_file_name = find_a_file (&cpath, ld_suffix);
1028 /* Search the ordinary system bin directories
1029 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1030 if (ld_file_name == 0)
1031 ld_file_name = find_a_file (&path, full_ld_suffix);
1033 #ifdef REAL_NM_FILE_NAME
1034 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1035 if (nm_file_name == 0)
1036 #endif
1037 nm_file_name = find_a_file (&cpath, gnm_suffix);
1038 if (nm_file_name == 0)
1039 nm_file_name = find_a_file (&path, full_gnm_suffix);
1040 if (nm_file_name == 0)
1041 nm_file_name = find_a_file (&cpath, nm_suffix);
1042 if (nm_file_name == 0)
1043 nm_file_name = find_a_file (&path, full_nm_suffix);
1045 #ifdef LDD_SUFFIX
1046 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1047 if (ldd_file_name == 0)
1048 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1049 #endif
1051 #ifdef REAL_STRIP_FILE_NAME
1052 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1053 if (strip_file_name == 0)
1054 #endif
1055 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1056 if (strip_file_name == 0)
1057 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1058 if (strip_file_name == 0)
1059 strip_file_name = find_a_file (&cpath, strip_suffix);
1060 if (strip_file_name == 0)
1061 strip_file_name = find_a_file (&path, full_strip_suffix);
1063 /* Determine the full path name of the C compiler to use. */
1064 c_file_name = getenv ("COLLECT_GCC");
1065 if (c_file_name == 0)
1067 #ifdef CROSS_DIRECTORY_STRUCTURE
1068 c_file_name = concat (target_machine, "-gcc", NULL);
1069 #else
1070 c_file_name = "gcc";
1071 #endif
1074 p = find_a_file (&cpath, c_file_name);
1076 /* Here it should be safe to use the system search path since we should have
1077 already qualified the name of the compiler when it is needed. */
1078 if (p == 0)
1079 p = find_a_file (&path, c_file_name);
1081 if (p)
1082 c_file_name = p;
1084 *ld1++ = *ld2++ = ld_file_name;
1086 /* Make temp file names. */
1087 c_file = make_temp_file (".c");
1088 o_file = make_temp_file (".o");
1089 #ifdef COLLECT_EXPORT_LIST
1090 export_file = make_temp_file (".x");
1091 #endif
1092 ldout = make_temp_file (".ld");
1093 lderrout = make_temp_file (".le");
1094 *c_ptr++ = c_file_name;
1095 *c_ptr++ = "-x";
1096 *c_ptr++ = "c";
1097 *c_ptr++ = "-c";
1098 *c_ptr++ = "-o";
1099 *c_ptr++ = o_file;
1101 #ifdef COLLECT_EXPORT_LIST
1102 /* Generate a list of directories from LIBPATH. */
1103 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1104 /* Add to this list also two standard directories where
1105 AIX loader always searches for libraries. */
1106 add_prefix (&libpath_lib_dirs, "/lib");
1107 add_prefix (&libpath_lib_dirs, "/usr/lib");
1108 #endif
1110 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1112 AIX support needs to know if -shared has been specified before
1113 parsing commandline arguments. */
1115 p = getenv ("COLLECT_GCC_OPTIONS");
1116 while (p && *p)
1118 const char *q = extract_string (&p);
1119 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1120 *c_ptr++ = xstrdup (q);
1121 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1122 *c_ptr++ = xstrdup (q);
1123 if (strcmp (q, "-shared") == 0)
1124 shared_obj = 1;
1125 if (*q == '-' && q[1] == 'B')
1127 *c_ptr++ = xstrdup (q);
1128 if (q[2] == 0)
1130 q = extract_string (&p);
1131 *c_ptr++ = xstrdup (q);
1135 obstack_free (&temporary_obstack, temporary_firstobj);
1136 *c_ptr++ = "-fno-profile-arcs";
1137 *c_ptr++ = "-fno-test-coverage";
1138 *c_ptr++ = "-fno-branch-probabilities";
1139 *c_ptr++ = "-fno-exceptions";
1140 *c_ptr++ = "-w";
1142 /* !!! When GCC calls collect2,
1143 it does not know whether it is calling collect2 or ld.
1144 So collect2 cannot meaningfully understand any options
1145 except those ld understands.
1146 If you propose to make GCC pass some other option,
1147 just imagine what will happen if ld is really ld!!! */
1149 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1150 /* After the first file, put in the c++ rt0. */
1152 first_file = 1;
1153 #ifdef HAVE_LD_DEMANGLE
1154 if (!demangle_flag && !no_demangle)
1155 demangle_flag = "--demangle";
1156 if (demangle_flag)
1157 *ld1++ = *ld2++ = demangle_flag;
1158 #endif
1159 while ((arg = *++argv) != (char *) 0)
1161 *ld1++ = *ld2++ = arg;
1163 if (arg[0] == '-')
1165 switch (arg[1])
1167 #ifdef COLLECT_EXPORT_LIST
1168 /* We want to disable automatic exports on AIX when user
1169 explicitly puts an export list in command line */
1170 case 'b':
1171 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1172 export_flag = 1;
1173 else if (arg[2] == '6' && arg[3] == '4')
1174 aix64_flag = 1;
1175 else if (arg[2] == 'r' && arg[3] == 't' && arg[4] == 'l')
1176 aixrtl_flag = 1;
1177 break;
1178 #endif
1180 case 'd':
1181 if (!strcmp (arg, "-debug"))
1183 /* Already parsed. */
1184 ld1--;
1185 ld2--;
1187 if (!strcmp (arg, "-dynamic-linker") && argv[1])
1189 ++argv;
1190 *ld1++ = *ld2++ = *argv;
1192 break;
1194 case 'l':
1195 if (first_file)
1197 /* place o_file BEFORE this argument! */
1198 first_file = 0;
1199 ld2--;
1200 *ld2++ = o_file;
1201 *ld2++ = arg;
1203 #ifdef COLLECT_EXPORT_LIST
1205 /* Resolving full library name. */
1206 const char *s = resolve_lib_name (arg+2);
1208 /* Saving a full library name. */
1209 add_to_list (&libs, s);
1211 #endif
1212 break;
1214 #ifdef COLLECT_EXPORT_LIST
1215 /* Saving directories where to search for libraries. */
1216 case 'L':
1217 add_prefix (&cmdline_lib_dirs, arg+2);
1218 break;
1219 #else
1220 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1221 case 'L':
1222 if (is_in_args (arg,
1223 CONST_CAST2 (const char **, char **, ld1_argv),
1224 ld1 - 1))
1225 --ld1;
1226 break;
1227 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1228 #endif
1230 case 'o':
1231 if (arg[2] == '\0')
1232 output_file = *ld1++ = *ld2++ = *++argv;
1233 else if (1
1234 #ifdef SWITCHES_NEED_SPACES
1235 && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1236 #endif
1239 output_file = &arg[2];
1240 break;
1242 case 'r':
1243 if (arg[2] == '\0')
1244 rflag = 1;
1245 break;
1247 case 's':
1248 if (arg[2] == '\0' && do_collecting)
1250 /* We must strip after the nm run, otherwise C++ linking
1251 will not work. Thus we strip in the second ld run, or
1252 else with strip if there is no second ld run. */
1253 strip_flag = 1;
1254 ld1--;
1256 break;
1258 case 'v':
1259 if (arg[2] == '\0')
1260 vflag = 1;
1261 break;
1263 case '-':
1264 if (strcmp (arg, "--no-demangle") == 0)
1266 demangle_flag = arg;
1267 no_demangle = 1;
1268 ld1--;
1269 ld2--;
1271 else if (strncmp (arg, "--demangle", 10) == 0)
1273 demangle_flag = arg;
1274 no_demangle = 0;
1275 #ifndef HAVE_LD_DEMANGLE
1276 if (arg[10] == '=')
1278 enum demangling_styles style
1279 = cplus_demangle_name_to_style (arg+11);
1280 if (style == unknown_demangling)
1281 error ("unknown demangling style '%s'", arg+11);
1282 else
1283 current_demangling_style = style;
1285 #endif
1286 ld1--;
1287 ld2--;
1289 else if (strncmp (arg, "--sysroot=", 10) == 0)
1290 target_system_root = arg + 10;
1291 break;
1294 else if ((p = strrchr (arg, '.')) != (char *) 0
1295 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1296 || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1297 || strcmp (p, ".obj") == 0))
1299 if (first_file)
1301 first_file = 0;
1302 if (p[1] == 'o')
1303 *ld2++ = o_file;
1304 else
1306 /* place o_file BEFORE this argument! */
1307 ld2--;
1308 *ld2++ = o_file;
1309 *ld2++ = arg;
1312 if (p[1] == 'o' || p[1] == 'l')
1313 *object++ = arg;
1314 #ifdef COLLECT_EXPORT_LIST
1315 /* libraries can be specified directly, i.e. without -l flag. */
1316 else
1318 /* Saving a full library name. */
1319 add_to_list (&libs, arg);
1321 #endif
1325 #ifdef COLLECT_EXPORT_LIST
1326 /* This is added only for debugging purposes. */
1327 if (debug)
1329 fprintf (stderr, "List of libraries:\n");
1330 dump_list (stderr, "\t", libs.first);
1333 /* The AIX linker will discard static constructors in object files if
1334 nothing else in the file is referenced, so look at them first. Unless
1335 we are building a shared object, ignore the eh frame tables, as we
1336 would otherwise reference them all, hence drag all the corresponding
1337 objects even if nothing else is referenced. */
1339 const char **export_object_lst
1340 = CONST_CAST2 (const char **, char **, object_lst);
1342 struct id *list = libs.first;
1344 /* Compute the filter to use from the current one, do scan, then adjust
1345 the "current" filter to remove what we just included here. This will
1346 control whether we need a first pass link later on or not, and what
1347 will remain to be scanned there. */
1349 scanfilter this_filter
1350 = shared_obj ? ld1_filter : (ld1_filter & ~SCAN_DWEH);
1352 while (export_object_lst < object)
1353 scan_prog_file (*export_object_lst++, PASS_OBJ, this_filter);
1355 for (; list; list = list->next)
1356 scan_prog_file (list->name, PASS_FIRST, this_filter);
1358 ld1_filter = ld1_filter & ~this_filter;
1361 if (exports.first)
1363 char *buf = concat ("-bE:", export_file, NULL);
1365 *ld1++ = buf;
1366 *ld2++ = buf;
1368 exportf = fopen (export_file, "w");
1369 if (exportf == (FILE *) 0)
1370 fatal_perror ("fopen %s", export_file);
1371 write_aix_file (exportf, exports.first);
1372 if (fclose (exportf))
1373 fatal_perror ("fclose %s", export_file);
1375 #endif
1377 *c_ptr++ = c_file;
1378 *c_ptr = *ld1 = *object = (char *) 0;
1380 if (vflag)
1382 notice ("collect2 version %s", version_string);
1383 #ifdef TARGET_VERSION
1384 TARGET_VERSION;
1385 #endif
1386 fprintf (stderr, "\n");
1389 if (debug)
1391 const char *ptr;
1392 fprintf (stderr, "ld_file_name = %s\n",
1393 (ld_file_name ? ld_file_name : "not found"));
1394 fprintf (stderr, "c_file_name = %s\n",
1395 (c_file_name ? c_file_name : "not found"));
1396 fprintf (stderr, "nm_file_name = %s\n",
1397 (nm_file_name ? nm_file_name : "not found"));
1398 #ifdef LDD_SUFFIX
1399 fprintf (stderr, "ldd_file_name = %s\n",
1400 (ldd_file_name ? ldd_file_name : "not found"));
1401 #endif
1402 fprintf (stderr, "strip_file_name = %s\n",
1403 (strip_file_name ? strip_file_name : "not found"));
1404 fprintf (stderr, "c_file = %s\n",
1405 (c_file ? c_file : "not found"));
1406 fprintf (stderr, "o_file = %s\n",
1407 (o_file ? o_file : "not found"));
1409 ptr = getenv ("COLLECT_GCC_OPTIONS");
1410 if (ptr)
1411 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1413 ptr = getenv ("COLLECT_GCC");
1414 if (ptr)
1415 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1417 ptr = getenv ("COMPILER_PATH");
1418 if (ptr)
1419 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1421 ptr = getenv (LIBRARY_PATH_ENV);
1422 if (ptr)
1423 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1425 fprintf (stderr, "\n");
1428 /* Load the program, searching all libraries and attempting to provide
1429 undefined symbols from repository information.
1431 If -r or they will be run via some other method, do not build the
1432 constructor or destructor list, just return now. */
1434 bool early_exit
1435 = rflag || (! DO_COLLECT_EXPORT_LIST && ! do_collecting);
1437 /* Perform the first pass link now, if we're about to exit or if we need
1438 to scan for things we haven't collected yet before pursuing further.
1440 On AIX, the latter typically includes nothing for shared objects or
1441 frame tables for an executable, out of what the required early scan on
1442 objects and libraries has performed above. In the !shared_obj case, we
1443 expect the relevant tables to be dragged together with their associated
1444 functions from precise cross reference insertions by the compiler. */
1446 if (early_exit || ld1_filter != SCAN_NOTHING)
1447 do_tlink (ld1_argv, object_lst);
1449 if (early_exit)
1451 #ifdef COLLECT_EXPORT_LIST
1452 /* Make sure we delete the export file we may have created. */
1453 if (export_file != 0 && export_file[0])
1454 maybe_unlink (export_file);
1455 #endif
1456 maybe_unlink (c_file);
1457 maybe_unlink (o_file);
1458 return 0;
1462 /* Unless we have done it all already, examine the namelist and search for
1463 static constructors and destructors to call. Write the constructor and
1464 destructor tables to a .s file and reload. */
1466 if (ld1_filter != SCAN_NOTHING)
1467 scan_prog_file (output_file, PASS_FIRST, ld1_filter);
1469 #ifdef SCAN_LIBRARIES
1470 scan_libraries (output_file);
1471 #endif
1473 if (debug)
1475 notice ("%d constructor(s) found\n", constructors.number);
1476 notice ("%d destructor(s) found\n", destructors.number);
1477 notice ("%d frame table(s) found\n", frame_tables.number);
1480 /* If the scan exposed nothing of special interest, there's no need to
1481 generate the glue code and relink so return now. */
1483 if (constructors.number == 0 && destructors.number == 0
1484 && frame_tables.number == 0
1485 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1486 /* If we will be running these functions ourselves, we want to emit
1487 stubs into the shared library so that we do not have to relink
1488 dependent programs when we add static objects. */
1489 && ! shared_obj
1490 #endif
1493 /* Do tlink without additional code generation now if we didn't
1494 do it earlier for scanning purposes. */
1495 if (ld1_filter == SCAN_NOTHING)
1496 do_tlink (ld1_argv, object_lst);
1498 /* Strip now if it was requested on the command line. */
1499 if (strip_flag)
1501 char **real_strip_argv = XCNEWVEC (char *, 3);
1502 const char ** strip_argv = CONST_CAST2 (const char **, char **,
1503 real_strip_argv);
1505 strip_argv[0] = strip_file_name;
1506 strip_argv[1] = output_file;
1507 strip_argv[2] = (char *) 0;
1508 fork_execute ("strip", real_strip_argv);
1511 #ifdef COLLECT_EXPORT_LIST
1512 maybe_unlink (export_file);
1513 #endif
1514 maybe_unlink (c_file);
1515 maybe_unlink (o_file);
1516 return 0;
1519 /* Sort ctor and dtor lists by priority. */
1520 sort_ids (&constructors);
1521 sort_ids (&destructors);
1523 maybe_unlink(output_file);
1524 outf = fopen (c_file, "w");
1525 if (outf == (FILE *) 0)
1526 fatal_perror ("fopen %s", c_file);
1528 write_c_file (outf, c_file);
1530 if (fclose (outf))
1531 fatal_perror ("fclose %s", c_file);
1533 /* Tell the linker that we have initializer and finalizer functions. */
1534 #ifdef LD_INIT_SWITCH
1535 #ifdef COLLECT_EXPORT_LIST
1536 *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1537 #else
1538 *ld2++ = LD_INIT_SWITCH;
1539 *ld2++ = initname;
1540 *ld2++ = LD_FINI_SWITCH;
1541 *ld2++ = fininame;
1542 #endif
1543 #endif
1545 #ifdef COLLECT_EXPORT_LIST
1546 if (shared_obj)
1548 /* If we did not add export flag to link arguments before, add it to
1549 second link phase now. No new exports should have been added. */
1550 if (! exports.first)
1551 *ld2++ = concat ("-bE:", export_file, NULL);
1553 #ifndef LD_INIT_SWITCH
1554 add_to_list (&exports, initname);
1555 add_to_list (&exports, fininame);
1556 add_to_list (&exports, "_GLOBAL__DI");
1557 add_to_list (&exports, "_GLOBAL__DD");
1558 #endif
1559 exportf = fopen (export_file, "w");
1560 if (exportf == (FILE *) 0)
1561 fatal_perror ("fopen %s", export_file);
1562 write_aix_file (exportf, exports.first);
1563 if (fclose (exportf))
1564 fatal_perror ("fclose %s", export_file);
1566 #endif
1568 /* End of arguments to second link phase. */
1569 *ld2 = (char*) 0;
1571 if (debug)
1573 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1574 output_file, c_file);
1575 write_c_file (stderr, "stderr");
1576 fprintf (stderr, "========== end of c_file\n\n");
1577 #ifdef COLLECT_EXPORT_LIST
1578 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1579 write_aix_file (stderr, exports.first);
1580 fprintf (stderr, "========== end of export_file\n\n");
1581 #endif
1584 /* Assemble the constructor and destructor tables.
1585 Link the tables in with the rest of the program. */
1587 fork_execute ("gcc", c_argv);
1588 #ifdef COLLECT_EXPORT_LIST
1589 /* On AIX we must call tlink because of possible templates resolution. */
1590 do_tlink (ld2_argv, object_lst);
1591 #else
1592 /* Otherwise, simply call ld because tlink is already done. */
1593 fork_execute ("ld", ld2_argv);
1595 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1596 constructors/destructors in shared libraries. */
1597 scan_prog_file (output_file, PASS_SECOND, SCAN_ALL);
1598 #endif
1600 maybe_unlink (c_file);
1601 maybe_unlink (o_file);
1603 #ifdef COLLECT_EXPORT_LIST
1604 maybe_unlink (export_file);
1605 #endif
1607 return 0;
1611 /* Wait for a process to finish, and exit if a nonzero status is found. */
1614 collect_wait (const char *prog, struct pex_obj *pex)
1616 int status;
1618 if (!pex_get_status (pex, 1, &status))
1619 fatal_perror ("can't get program status");
1620 pex_free (pex);
1622 if (status)
1624 if (WIFSIGNALED (status))
1626 int sig = WTERMSIG (status);
1627 error ("%s terminated with signal %d [%s]%s",
1628 prog, sig, strsignal(sig),
1629 WCOREDUMP(status) ? ", core dumped" : "");
1630 collect_exit (FATAL_EXIT_CODE);
1633 if (WIFEXITED (status))
1634 return WEXITSTATUS (status);
1636 return 0;
1639 static void
1640 do_wait (const char *prog, struct pex_obj *pex)
1642 int ret = collect_wait (prog, pex);
1643 if (ret != 0)
1645 error ("%s returned %d exit status", prog, ret);
1646 collect_exit (ret);
1649 if (response_file)
1651 unlink (response_file);
1652 response_file = NULL;
1657 /* Execute a program, and wait for the reply. */
1659 struct pex_obj *
1660 collect_execute (const char *prog, char **argv, const char *outname,
1661 const char *errname)
1663 struct pex_obj *pex;
1664 const char *errmsg;
1665 int err;
1666 char *response_arg = NULL;
1667 char *response_argv[3] ATTRIBUTE_UNUSED;
1669 if (HAVE_GNU_LD && at_file_supplied && argv[0] != NULL)
1671 /* If using @file arguments, create a temporary file and put the
1672 contents of argv into it. Then change argv to an array corresponding
1673 to a single argument @FILE, where FILE is the temporary filename. */
1675 char **current_argv = argv + 1;
1676 char *argv0 = argv[0];
1677 int status;
1678 FILE *f;
1680 /* Note: we assume argv contains at least one element; this is
1681 checked above. */
1683 response_file = make_temp_file ("");
1685 f = fopen (response_file, "w");
1687 if (f == NULL)
1688 fatal ("could not open response file %s", response_file);
1690 status = writeargv (current_argv, f);
1692 if (status)
1693 fatal ("could not write to response file %s", response_file);
1695 status = fclose (f);
1697 if (EOF == status)
1698 fatal ("could not close response file %s", response_file);
1700 response_arg = concat ("@", response_file, NULL);
1701 response_argv[0] = argv0;
1702 response_argv[1] = response_arg;
1703 response_argv[2] = NULL;
1705 argv = response_argv;
1708 if (vflag || debug)
1710 char **p_argv;
1711 const char *str;
1713 if (argv[0])
1714 fprintf (stderr, "%s", argv[0]);
1715 else
1716 notice ("[cannot find %s]", prog);
1718 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1719 fprintf (stderr, " %s", str);
1721 fprintf (stderr, "\n");
1724 fflush (stdout);
1725 fflush (stderr);
1727 /* If we cannot find a program we need, complain error. Do this here
1728 since we might not end up needing something that we could not find. */
1730 if (argv[0] == 0)
1731 fatal ("cannot find '%s'", prog);
1733 pex = pex_init (0, "collect2", NULL);
1734 if (pex == NULL)
1735 fatal_perror ("pex_init failed");
1737 errmsg = pex_run (pex, PEX_LAST | PEX_SEARCH, argv[0], argv, outname,
1738 errname, &err);
1739 if (errmsg != NULL)
1741 if (err != 0)
1743 errno = err;
1744 fatal_perror (errmsg);
1746 else
1747 fatal (errmsg);
1750 if (response_arg)
1751 free (response_arg);
1753 return pex;
1756 static void
1757 fork_execute (const char *prog, char **argv)
1759 struct pex_obj *pex;
1761 pex = collect_execute (prog, argv, NULL, NULL);
1762 do_wait (prog, pex);
1765 /* Unlink a file unless we are debugging. */
1767 static void
1768 maybe_unlink (const char *file)
1770 if (!debug)
1771 unlink_if_ordinary (file);
1772 else
1773 notice ("[Leaving %s]\n", file);
1777 static long sequence_number = 0;
1779 /* Add a name to a linked list. */
1781 static void
1782 add_to_list (struct head *head_ptr, const char *name)
1784 struct id *newid
1785 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1786 struct id *p;
1787 strcpy (newid->name, name);
1789 if (head_ptr->first)
1790 head_ptr->last->next = newid;
1791 else
1792 head_ptr->first = newid;
1794 /* Check for duplicate symbols. */
1795 for (p = head_ptr->first;
1796 strcmp (name, p->name) != 0;
1797 p = p->next)
1799 if (p != newid)
1801 head_ptr->last->next = 0;
1802 free (newid);
1803 return;
1806 newid->sequence = ++sequence_number;
1807 head_ptr->last = newid;
1808 head_ptr->number++;
1811 /* Grab the init priority number from an init function name that
1812 looks like "_GLOBAL_.I.12345.foo". */
1814 static int
1815 extract_init_priority (const char *name)
1817 int pos = 0, pri;
1819 while (name[pos] == '_')
1820 ++pos;
1821 pos += 10; /* strlen ("GLOBAL__X_") */
1823 /* Extract init_p number from ctor/dtor name. */
1824 pri = atoi (name + pos);
1825 return pri ? pri : DEFAULT_INIT_PRIORITY;
1828 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1829 ctors will be run from right to left, dtors from left to right. */
1831 static void
1832 sort_ids (struct head *head_ptr)
1834 /* id holds the current element to insert. id_next holds the next
1835 element to insert. id_ptr iterates through the already sorted elements
1836 looking for the place to insert id. */
1837 struct id *id, *id_next, **id_ptr;
1839 id = head_ptr->first;
1841 /* We don't have any sorted elements yet. */
1842 head_ptr->first = NULL;
1844 for (; id; id = id_next)
1846 id_next = id->next;
1847 id->sequence = extract_init_priority (id->name);
1849 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1850 if (*id_ptr == NULL
1851 /* If the sequence numbers are the same, we put the id from the
1852 file later on the command line later in the list. */
1853 || id->sequence > (*id_ptr)->sequence
1854 /* Hack: do lexical compare, too.
1855 || (id->sequence == (*id_ptr)->sequence
1856 && strcmp (id->name, (*id_ptr)->name) > 0) */
1859 id->next = *id_ptr;
1860 *id_ptr = id;
1861 break;
1865 /* Now set the sequence numbers properly so write_c_file works. */
1866 for (id = head_ptr->first; id; id = id->next)
1867 id->sequence = ++sequence_number;
1870 /* Write: `prefix', the names on list LIST, `suffix'. */
1872 static void
1873 write_list (FILE *stream, const char *prefix, struct id *list)
1875 while (list)
1877 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1878 list = list->next;
1882 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1883 /* Given a STRING, return nonzero if it occurs in the list in range
1884 [ARGS_BEGIN,ARGS_END). */
1886 static int
1887 is_in_args (const char *string, const char **args_begin,
1888 const char **args_end)
1890 const char **args_pointer;
1891 for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1892 if (strcmp (string, *args_pointer) == 0)
1893 return 1;
1894 return 0;
1896 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1898 #ifdef COLLECT_EXPORT_LIST
1899 /* This function is really used only on AIX, but may be useful. */
1900 #if 0
1901 static int
1902 is_in_list (const char *prefix, struct id *list)
1904 while (list)
1906 if (!strcmp (prefix, list->name)) return 1;
1907 list = list->next;
1909 return 0;
1911 #endif
1912 #endif /* COLLECT_EXPORT_LIST */
1914 /* Added for debugging purpose. */
1915 #ifdef COLLECT_EXPORT_LIST
1916 static void
1917 dump_list (FILE *stream, const char *prefix, struct id *list)
1919 while (list)
1921 fprintf (stream, "%s%s,\n", prefix, list->name);
1922 list = list->next;
1925 #endif
1927 #if 0
1928 static void
1929 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
1931 while (list)
1933 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1934 list = list->next;
1937 #endif
1939 static void
1940 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
1942 while (list)
1944 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1945 prefix, list->sequence, list->name);
1946 list = list->next;
1950 /* Write out the constructor and destructor tables statically (for a shared
1951 object), along with the functions to execute them. */
1953 static void
1954 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
1956 const char *p, *q;
1957 char *prefix, *r;
1958 int frames = (frame_tables.number > 0);
1960 /* Figure out name of output_file, stripping off .so version. */
1961 p = strrchr (output_file, '/');
1962 if (p == 0)
1963 p = output_file;
1964 else
1965 p++;
1966 q = p;
1967 while (q)
1969 q = strchr (q,'.');
1970 if (q == 0)
1972 q = p + strlen (p);
1973 break;
1975 else
1977 if (strncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
1979 q += strlen (SHLIB_SUFFIX);
1980 break;
1982 else
1983 q++;
1986 /* q points to null at end of the string (or . of the .so version) */
1987 prefix = XNEWVEC (char, q - p + 1);
1988 strncpy (prefix, p, q - p);
1989 prefix[q - p] = 0;
1990 for (r = prefix; *r; r++)
1991 if (!ISALNUM ((unsigned char)*r))
1992 *r = '_';
1993 if (debug)
1994 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1995 output_file, prefix);
1997 initname = concat ("_GLOBAL__FI_", prefix, NULL);
1998 fininame = concat ("_GLOBAL__FD_", prefix, NULL);
2000 free (prefix);
2002 /* Write the tables as C code. */
2004 fprintf (stream, "static int count;\n");
2005 fprintf (stream, "typedef void entry_pt();\n");
2006 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2008 if (frames)
2010 write_list_with_asm (stream, "extern void *", frame_tables.first);
2012 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2013 write_list (stream, "\t\t&", frame_tables.first);
2014 fprintf (stream, "\t0\n};\n");
2016 /* This must match what's in frame.h. */
2017 fprintf (stream, "struct object {\n");
2018 fprintf (stream, " void *pc_begin;\n");
2019 fprintf (stream, " void *pc_end;\n");
2020 fprintf (stream, " void *fde_begin;\n");
2021 fprintf (stream, " void *fde_array;\n");
2022 fprintf (stream, " __SIZE_TYPE__ count;\n");
2023 fprintf (stream, " struct object *next;\n");
2024 fprintf (stream, "};\n");
2026 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2027 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2029 fprintf (stream, "static void reg_frame () {\n");
2030 fprintf (stream, "\tstatic struct object ob;\n");
2031 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2032 fprintf (stream, "\t}\n");
2034 fprintf (stream, "static void dereg_frame () {\n");
2035 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2036 fprintf (stream, "\t}\n");
2039 fprintf (stream, "void %s() {\n", initname);
2040 if (constructors.number > 0 || frames)
2042 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2043 write_list (stream, "\t\t", constructors.first);
2044 if (frames)
2045 fprintf (stream, "\treg_frame,\n");
2046 fprintf (stream, "\t};\n");
2047 fprintf (stream, "\tentry_pt **p;\n");
2048 fprintf (stream, "\tif (count++ != 0) return;\n");
2049 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2050 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2052 else
2053 fprintf (stream, "\t++count;\n");
2054 fprintf (stream, "}\n");
2055 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2056 fprintf (stream, "void %s() {\n", fininame);
2057 if (destructors.number > 0 || frames)
2059 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2060 write_list (stream, "\t\t", destructors.first);
2061 if (frames)
2062 fprintf (stream, "\tdereg_frame,\n");
2063 fprintf (stream, "\t};\n");
2064 fprintf (stream, "\tentry_pt **p;\n");
2065 fprintf (stream, "\tif (--count != 0) return;\n");
2066 fprintf (stream, "\tp = dtors;\n");
2067 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2068 destructors.number + frames);
2070 fprintf (stream, "}\n");
2072 if (shared_obj)
2074 COLLECT_SHARED_INIT_FUNC(stream, initname);
2075 COLLECT_SHARED_FINI_FUNC(stream, fininame);
2079 /* Write the constructor/destructor tables. */
2081 #ifndef LD_INIT_SWITCH
2082 static void
2083 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2085 /* Write the tables as C code. */
2087 int frames = (frame_tables.number > 0);
2089 fprintf (stream, "typedef void entry_pt();\n\n");
2091 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2093 if (frames)
2095 write_list_with_asm (stream, "extern void *", frame_tables.first);
2097 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2098 write_list (stream, "\t\t&", frame_tables.first);
2099 fprintf (stream, "\t0\n};\n");
2101 /* This must match what's in frame.h. */
2102 fprintf (stream, "struct object {\n");
2103 fprintf (stream, " void *pc_begin;\n");
2104 fprintf (stream, " void *pc_end;\n");
2105 fprintf (stream, " void *fde_begin;\n");
2106 fprintf (stream, " void *fde_array;\n");
2107 fprintf (stream, " __SIZE_TYPE__ count;\n");
2108 fprintf (stream, " struct object *next;\n");
2109 fprintf (stream, "};\n");
2111 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2112 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2114 fprintf (stream, "static void reg_frame () {\n");
2115 fprintf (stream, "\tstatic struct object ob;\n");
2116 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2117 fprintf (stream, "\t}\n");
2119 fprintf (stream, "static void dereg_frame () {\n");
2120 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2121 fprintf (stream, "\t}\n");
2124 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2125 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2126 write_list (stream, "\t", constructors.first);
2127 if (frames)
2128 fprintf (stream, "\treg_frame,\n");
2129 fprintf (stream, "\t0\n};\n\n");
2131 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2133 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2134 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2135 write_list (stream, "\t", destructors.first);
2136 if (frames)
2137 fprintf (stream, "\tdereg_frame,\n");
2138 fprintf (stream, "\t0\n};\n\n");
2140 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2141 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2143 #endif /* ! LD_INIT_SWITCH */
2145 static void
2146 write_c_file (FILE *stream, const char *name)
2148 #ifndef LD_INIT_SWITCH
2149 if (! shared_obj)
2150 write_c_file_glob (stream, name);
2151 else
2152 #endif
2153 write_c_file_stat (stream, name);
2156 #ifdef COLLECT_EXPORT_LIST
2157 static void
2158 write_aix_file (FILE *stream, struct id *list)
2160 for (; list; list = list->next)
2162 fputs (list->name, stream);
2163 putc ('\n', stream);
2166 #endif
2168 #ifdef OBJECT_FORMAT_NONE
2170 /* Generic version to scan the name list of the loaded program for
2171 the symbols g++ uses for static constructors and destructors. */
2173 static void
2174 scan_prog_file (const char *prog_name, scanpass which_pass,
2175 scanfilter filter)
2177 void (*int_handler) (int);
2178 #ifdef SIGQUIT
2179 void (*quit_handler) (int);
2180 #endif
2181 char *real_nm_argv[4];
2182 const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2183 int argc = 0;
2184 struct pex_obj *pex;
2185 const char *errmsg;
2186 int err;
2187 char *p, buf[1024];
2188 FILE *inf;
2190 if (which_pass == PASS_SECOND)
2191 return;
2193 /* If we do not have an `nm', complain. */
2194 if (nm_file_name == 0)
2195 fatal ("cannot find 'nm'");
2197 nm_argv[argc++] = nm_file_name;
2198 if (NM_FLAGS[0] != '\0')
2199 nm_argv[argc++] = NM_FLAGS;
2201 nm_argv[argc++] = prog_name;
2202 nm_argv[argc++] = (char *) 0;
2204 /* Trace if needed. */
2205 if (vflag)
2207 const char **p_argv;
2208 const char *str;
2210 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2211 fprintf (stderr, " %s", str);
2213 fprintf (stderr, "\n");
2216 fflush (stdout);
2217 fflush (stderr);
2219 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2220 if (pex == NULL)
2221 fatal_perror ("pex_init failed");
2223 errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, NULL, &err);
2224 if (errmsg != NULL)
2226 if (err != 0)
2228 errno = err;
2229 fatal_perror (errmsg);
2231 else
2232 fatal (errmsg);
2235 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2236 #ifdef SIGQUIT
2237 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2238 #endif
2240 inf = pex_read_output (pex, 0);
2241 if (inf == NULL)
2242 fatal_perror ("can't open nm output");
2244 if (debug)
2245 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2247 /* Read each line of nm output. */
2248 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2250 int ch, ch2;
2251 char *name, *end;
2253 /* If it contains a constructor or destructor name, add the name
2254 to the appropriate list unless this is a kind of symbol we're
2255 not supposed to even consider. */
2257 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2258 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2259 break;
2261 if (ch != '_')
2262 continue;
2264 name = p;
2265 /* Find the end of the symbol name.
2266 Do not include `|', because Encore nm can tack that on the end. */
2267 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2268 end++)
2269 continue;
2272 *end = '\0';
2273 switch (is_ctor_dtor (name))
2275 case SYM_CTOR:
2276 if (! (filter & SCAN_CTOR))
2277 break;
2278 if (which_pass != PASS_LIB)
2279 add_to_list (&constructors, name);
2280 break;
2282 case SYM_DTOR:
2283 if (! (filter & SCAN_DTOR))
2284 break;
2285 if (which_pass != PASS_LIB)
2286 add_to_list (&destructors, name);
2287 break;
2289 case SYM_INIT:
2290 if (! (filter & SCAN_INIT))
2291 break;
2292 if (which_pass != PASS_LIB)
2293 fatal ("init function found in object %s", prog_name);
2294 #ifndef LD_INIT_SWITCH
2295 add_to_list (&constructors, name);
2296 #endif
2297 break;
2299 case SYM_FINI:
2300 if (! (filter & SCAN_FINI))
2301 break;
2302 if (which_pass != PASS_LIB)
2303 fatal ("fini function found in object %s", prog_name);
2304 #ifndef LD_FINI_SWITCH
2305 add_to_list (&destructors, name);
2306 #endif
2307 break;
2309 case SYM_DWEH:
2310 if (! (filter & SCAN_DWEH))
2311 break;
2312 if (which_pass != PASS_LIB)
2313 add_to_list (&frame_tables, name);
2314 break;
2316 default: /* not a constructor or destructor */
2317 continue;
2320 if (debug)
2321 fprintf (stderr, "\t%s\n", buf);
2324 if (debug)
2325 fprintf (stderr, "\n");
2327 do_wait (nm_file_name, pex);
2329 signal (SIGINT, int_handler);
2330 #ifdef SIGQUIT
2331 signal (SIGQUIT, quit_handler);
2332 #endif
2335 #ifdef LDD_SUFFIX
2337 /* Use the List Dynamic Dependencies program to find shared libraries that
2338 the output file depends upon and their initialization/finalization
2339 routines, if any. */
2341 static void
2342 scan_libraries (const char *prog_name)
2344 static struct head libraries; /* list of shared libraries found */
2345 struct id *list;
2346 void (*int_handler) (int);
2347 #ifdef SIGQUIT
2348 void (*quit_handler) (int);
2349 #endif
2350 char *real_ldd_argv[4];
2351 const char **ldd_argv = CONST_CAST2 (const char **, char **, real_ldd_argv);
2352 int argc = 0;
2353 struct pex_obj *pex;
2354 const char *errmsg;
2355 int err;
2356 char buf[1024];
2357 FILE *inf;
2359 /* If we do not have an `ldd', complain. */
2360 if (ldd_file_name == 0)
2362 error ("cannot find 'ldd'");
2363 return;
2366 ldd_argv[argc++] = ldd_file_name;
2367 ldd_argv[argc++] = prog_name;
2368 ldd_argv[argc++] = (char *) 0;
2370 /* Trace if needed. */
2371 if (vflag)
2373 const char **p_argv;
2374 const char *str;
2376 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2377 fprintf (stderr, " %s", str);
2379 fprintf (stderr, "\n");
2382 fflush (stdout);
2383 fflush (stderr);
2385 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2386 if (pex == NULL)
2387 fatal_perror ("pex_init failed");
2389 errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2390 if (errmsg != NULL)
2392 if (err != 0)
2394 errno = err;
2395 fatal_perror (errmsg);
2397 else
2398 fatal (errmsg);
2401 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2402 #ifdef SIGQUIT
2403 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2404 #endif
2406 inf = pex_read_output (pex, 0);
2407 if (inf == NULL)
2408 fatal_perror ("can't open ldd output");
2410 if (debug)
2411 notice ("\nldd output with constructors/destructors.\n");
2413 /* Read each line of ldd output. */
2414 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2416 int ch2;
2417 char *name, *end, *p = buf;
2419 /* Extract names of libraries and add to list. */
2420 PARSE_LDD_OUTPUT (p);
2421 if (p == 0)
2422 continue;
2424 name = p;
2425 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2426 fatal ("dynamic dependency %s not found", buf);
2428 /* Find the end of the symbol name. */
2429 for (end = p;
2430 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2431 end++)
2432 continue;
2433 *end = '\0';
2435 if (access (name, R_OK) == 0)
2436 add_to_list (&libraries, name);
2437 else
2438 fatal ("unable to open dynamic dependency '%s'", buf);
2440 if (debug)
2441 fprintf (stderr, "\t%s\n", buf);
2443 if (debug)
2444 fprintf (stderr, "\n");
2446 do_wait (ldd_file_name, pex);
2448 signal (SIGINT, int_handler);
2449 #ifdef SIGQUIT
2450 signal (SIGQUIT, quit_handler);
2451 #endif
2453 /* Now iterate through the library list adding their symbols to
2454 the list. */
2455 for (list = libraries.first; list; list = list->next)
2456 scan_prog_file (list->name, PASS_LIB);
2459 #endif /* LDD_SUFFIX */
2461 #endif /* OBJECT_FORMAT_NONE */
2465 * COFF specific stuff.
2468 #ifdef OBJECT_FORMAT_COFF
2470 #if defined (EXTENDED_COFF)
2472 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2473 # define GCC_SYMENT SYMR
2474 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2475 # define GCC_SYMINC(X) (1)
2476 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2477 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2479 #else
2481 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2482 # define GCC_SYMENT SYMENT
2483 # if defined (C_WEAKEXT)
2484 # define GCC_OK_SYMBOL(X) \
2485 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2486 ((X).n_scnum > N_UNDEF) && \
2487 (aix64_flag \
2488 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2489 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2490 # define GCC_UNDEF_SYMBOL(X) \
2491 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2492 ((X).n_scnum == N_UNDEF))
2493 # else
2494 # define GCC_OK_SYMBOL(X) \
2495 (((X).n_sclass == C_EXT) && \
2496 ((X).n_scnum > N_UNDEF) && \
2497 (aix64_flag \
2498 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2499 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2500 # define GCC_UNDEF_SYMBOL(X) \
2501 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2502 # endif
2503 # define GCC_SYMINC(X) ((X).n_numaux+1)
2504 # define GCC_SYMZERO(X) 0
2506 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2507 #if TARGET_AIX_VERSION >= 51
2508 # define GCC_CHECK_HDR(X) \
2509 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2510 || (HEADER (X).f_magic == 0767 && aix64_flag))
2511 #else
2512 # define GCC_CHECK_HDR(X) \
2513 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2514 || (HEADER (X).f_magic == 0757 && aix64_flag))
2515 #endif
2517 #endif
2519 #ifdef COLLECT_EXPORT_LIST
2520 /* Array of standard AIX libraries which should not
2521 be scanned for ctors/dtors. */
2522 static const char *const aix_std_libs[] = {
2523 "/unix",
2524 "/lib/libc.a",
2525 "/lib/libm.a",
2526 "/lib/libc_r.a",
2527 "/lib/libm_r.a",
2528 "/usr/lib/libc.a",
2529 "/usr/lib/libm.a",
2530 "/usr/lib/libc_r.a",
2531 "/usr/lib/libm_r.a",
2532 "/usr/lib/threads/libc.a",
2533 "/usr/ccs/lib/libc.a",
2534 "/usr/ccs/lib/libm.a",
2535 "/usr/ccs/lib/libc_r.a",
2536 "/usr/ccs/lib/libm_r.a",
2537 NULL
2540 /* This function checks the filename and returns 1
2541 if this name matches the location of a standard AIX library. */
2542 static int ignore_library (const char *);
2543 static int
2544 ignore_library (const char *name)
2546 const char *const *p;
2547 size_t length;
2549 if (target_system_root[0] != '\0')
2551 length = strlen (target_system_root);
2552 if (strncmp (name, target_system_root, length) != 0)
2553 return 0;
2554 name += length;
2556 for (p = &aix_std_libs[0]; *p != NULL; ++p)
2557 if (strcmp (name, *p) == 0)
2558 return 1;
2559 return 0;
2561 #endif /* COLLECT_EXPORT_LIST */
2563 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2564 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2565 #endif
2567 /* COFF version to scan the name list of the loaded program for
2568 the symbols g++ uses for static constructors and destructors. */
2570 static void
2571 scan_prog_file (const char *prog_name, scanpass which_pass,
2572 scanfilter filter)
2574 LDFILE *ldptr = NULL;
2575 int sym_index, sym_count;
2576 int is_shared = 0;
2578 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2579 return;
2581 #ifdef COLLECT_EXPORT_LIST
2582 /* We do not need scanning for some standard C libraries. */
2583 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2584 return;
2586 /* On AIX we have a loop, because there is not much difference
2587 between an object and an archive. This trick allows us to
2588 eliminate scan_libraries() function. */
2591 #endif
2592 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2593 non-const char * filename parameter, even though it will not
2594 modify that string. So we must cast away const-ness here,
2595 using CONST_CAST to prevent complaints from -Wcast-qual. */
2596 if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
2598 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2599 fatal ("%s: not a COFF file", prog_name);
2601 if (GCC_CHECK_HDR (ldptr))
2603 sym_count = GCC_SYMBOLS (ldptr);
2604 sym_index = GCC_SYMZERO (ldptr);
2606 #ifdef COLLECT_EXPORT_LIST
2607 /* Is current archive member a shared object? */
2608 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2609 #endif
2611 while (sym_index < sym_count)
2613 GCC_SYMENT symbol;
2615 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2616 break;
2617 sym_index += GCC_SYMINC (symbol);
2619 if (GCC_OK_SYMBOL (symbol))
2621 char *name;
2623 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2624 continue; /* Should never happen. */
2626 #ifdef XCOFF_DEBUGGING_INFO
2627 /* All AIX function names have a duplicate entry
2628 beginning with a dot. */
2629 if (*name == '.')
2630 ++name;
2631 #endif
2633 switch (is_ctor_dtor (name))
2635 case SYM_CTOR:
2636 if (! (filter & SCAN_CTOR))
2637 break;
2638 if (! is_shared)
2639 add_to_list (&constructors, name);
2640 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2641 if (which_pass == PASS_OBJ)
2642 add_to_list (&exports, name);
2643 #endif
2644 break;
2646 case SYM_DTOR:
2647 if (! (filter & SCAN_DTOR))
2648 break;
2649 if (! is_shared)
2650 add_to_list (&destructors, name);
2651 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2652 if (which_pass == PASS_OBJ)
2653 add_to_list (&exports, name);
2654 #endif
2655 break;
2657 #ifdef COLLECT_EXPORT_LIST
2658 case SYM_INIT:
2659 if (! (filter & SCAN_INIT))
2660 break;
2661 #ifndef LD_INIT_SWITCH
2662 if (is_shared)
2663 add_to_list (&constructors, name);
2664 #endif
2665 break;
2667 case SYM_FINI:
2668 if (! (filter & SCAN_FINI))
2669 break;
2670 #ifndef LD_INIT_SWITCH
2671 if (is_shared)
2672 add_to_list (&destructors, name);
2673 #endif
2674 break;
2675 #endif
2677 case SYM_DWEH:
2678 if (! (filter & SCAN_DWEH))
2679 break;
2680 if (! is_shared)
2681 add_to_list (&frame_tables, name);
2682 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2683 if (which_pass == PASS_OBJ)
2684 add_to_list (&exports, name);
2685 #endif
2686 break;
2688 default: /* not a constructor or destructor */
2689 #ifdef COLLECT_EXPORT_LIST
2690 /* Explicitly export all global symbols when
2691 building a shared object on AIX, but do not
2692 re-export symbols from another shared object
2693 and do not export symbols if the user
2694 provides an explicit export list. */
2695 if (shared_obj && !is_shared
2696 && which_pass == PASS_OBJ && !export_flag)
2697 add_to_list (&exports, name);
2698 #endif
2699 continue;
2702 if (debug)
2703 #if !defined(EXTENDED_COFF)
2704 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2705 symbol.n_scnum, symbol.n_sclass,
2706 (symbol.n_type ? "0" : ""), symbol.n_type,
2707 name);
2708 #else
2709 fprintf (stderr,
2710 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2711 symbol.iss, (long) symbol.value, symbol.index, name);
2712 #endif
2716 #ifdef COLLECT_EXPORT_LIST
2717 else
2719 /* If archive contains both 32-bit and 64-bit objects,
2720 we want to skip objects in other mode so mismatch normal. */
2721 if (debug)
2722 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2723 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2725 #endif
2727 else
2729 fatal ("%s: cannot open as COFF file", prog_name);
2731 #ifdef COLLECT_EXPORT_LIST
2732 /* On AIX loop continues while there are more members in archive. */
2734 while (ldclose (ldptr) == FAILURE);
2735 #else
2736 /* Otherwise we simply close ldptr. */
2737 (void) ldclose(ldptr);
2738 #endif
2740 #endif /* OBJECT_FORMAT_COFF */
2742 #ifdef COLLECT_EXPORT_LIST
2743 /* Given a library name without "lib" prefix, this function
2744 returns a full library name including a path. */
2745 static char *
2746 resolve_lib_name (const char *name)
2748 char *lib_buf;
2749 int i, j, l = 0;
2750 /* Library extensions for AIX dynamic linking. */
2751 const char * const libexts[2] = {"a", "so"};
2753 for (i = 0; libpaths[i]; i++)
2754 if (libpaths[i]->max_len > l)
2755 l = libpaths[i]->max_len;
2757 lib_buf = XNEWVEC (char, l + strlen(name) + 10);
2759 for (i = 0; libpaths[i]; i++)
2761 struct prefix_list *list = libpaths[i]->plist;
2762 for (; list; list = list->next)
2764 /* The following lines are needed because path_prefix list
2765 may contain directories both with trailing '/' and
2766 without it. */
2767 const char *p = "";
2768 if (list->prefix[strlen(list->prefix)-1] != '/')
2769 p = "/";
2770 for (j = 0; j < 2; j++)
2772 sprintf (lib_buf, "%s%slib%s.%s",
2773 list->prefix, p, name,
2774 libexts[(j + aixrtl_flag) % 2]);
2775 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2776 if (file_exists (lib_buf))
2778 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2779 return (lib_buf);
2784 if (debug)
2785 fprintf (stderr, "not found\n");
2786 else
2787 fatal ("library lib%s not found", name);
2788 return (NULL);
2790 #endif /* COLLECT_EXPORT_LIST */