2009-06-08 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / collect2.c
blob9848b903580b1ec94d361c28c3aeb4a0546894ed
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 /* Nonzero if we should suppress the automatic demangling of identifiers
149 in linker error messages. Set from COLLECT_NO_DEMANGLE. */
150 int no_demangle;
152 /* Linked lists of constructor and destructor names. */
154 struct id
156 struct id *next;
157 int sequence;
158 char name[1];
161 struct head
163 struct id *first;
164 struct id *last;
165 int number;
168 /* Enumeration giving which pass this is for scanning the program file. */
170 enum pass {
171 PASS_FIRST, /* without constructors */
172 PASS_OBJ, /* individual objects */
173 PASS_LIB, /* looking for shared libraries */
174 PASS_SECOND /* with constructors linked in */
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 static void scan_prog_file (const char *, enum pass);
292 #ifdef SCAN_LIBRARIES
293 static void scan_libraries (const char *);
294 #endif
295 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
296 static int is_in_args (const char *, const char **, const char **);
297 #endif
298 #ifdef COLLECT_EXPORT_LIST
299 #if 0
300 static int is_in_list (const char *, struct id *);
301 #endif
302 static void write_aix_file (FILE *, struct id *);
303 static char *resolve_lib_name (const char *);
304 #endif
305 static char *extract_string (const char **);
307 /* Delete tempfiles and exit function. */
309 void
310 collect_exit (int status)
312 if (c_file != 0 && c_file[0])
313 maybe_unlink (c_file);
315 if (o_file != 0 && o_file[0])
316 maybe_unlink (o_file);
318 #ifdef COLLECT_EXPORT_LIST
319 if (export_file != 0 && export_file[0])
320 maybe_unlink (export_file);
321 #endif
323 if (ldout != 0 && ldout[0])
325 dump_file (ldout, stdout);
326 maybe_unlink (ldout);
329 if (lderrout != 0 && lderrout[0])
331 dump_file (lderrout, stderr);
332 maybe_unlink (lderrout);
335 if (status != 0 && output_file != 0 && output_file[0])
336 maybe_unlink (output_file);
338 if (response_file)
339 maybe_unlink (response_file);
341 exit (status);
345 /* Notify user of a non-error. */
346 void
347 notice (const char *cmsgid, ...)
349 va_list ap;
351 va_start (ap, cmsgid);
352 vfprintf (stderr, _(cmsgid), ap);
353 va_end (ap);
356 /* Die when sys call fails. */
358 void
359 fatal_perror (const char * cmsgid, ...)
361 int e = errno;
362 va_list ap;
364 va_start (ap, cmsgid);
365 fprintf (stderr, "collect2: ");
366 vfprintf (stderr, _(cmsgid), ap);
367 fprintf (stderr, ": %s\n", xstrerror (e));
368 va_end (ap);
370 collect_exit (FATAL_EXIT_CODE);
373 /* Just die. */
375 void
376 fatal (const char * cmsgid, ...)
378 va_list ap;
380 va_start (ap, cmsgid);
381 fprintf (stderr, "collect2: ");
382 vfprintf (stderr, _(cmsgid), ap);
383 fprintf (stderr, "\n");
384 va_end (ap);
386 collect_exit (FATAL_EXIT_CODE);
389 /* Write error message. */
391 void
392 error (const char * gmsgid, ...)
394 va_list ap;
396 va_start (ap, gmsgid);
397 fprintf (stderr, "collect2: ");
398 vfprintf (stderr, _(gmsgid), ap);
399 fprintf (stderr, "\n");
400 va_end(ap);
403 /* In case obstack is linked in, and abort is defined to fancy_abort,
404 provide a default entry. */
406 void
407 fancy_abort (const char *file, int line, const char *func)
409 fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
412 static void
413 handler (int signo)
415 if (c_file != 0 && c_file[0])
416 maybe_unlink (c_file);
418 if (o_file != 0 && o_file[0])
419 maybe_unlink (o_file);
421 if (ldout != 0 && ldout[0])
422 maybe_unlink (ldout);
424 if (lderrout != 0 && lderrout[0])
425 maybe_unlink (lderrout);
427 #ifdef COLLECT_EXPORT_LIST
428 if (export_file != 0 && export_file[0])
429 maybe_unlink (export_file);
430 #endif
432 if (response_file)
433 maybe_unlink (response_file);
435 signal (signo, SIG_DFL);
436 raise (signo);
441 file_exists (const char *name)
443 return access (name, R_OK) == 0;
446 /* Parse a reasonable subset of shell quoting syntax. */
448 static char *
449 extract_string (const char **pp)
451 const char *p = *pp;
452 int backquote = 0;
453 int inside = 0;
455 for (;;)
457 char c = *p;
458 if (c == '\0')
459 break;
460 ++p;
461 if (backquote)
462 obstack_1grow (&temporary_obstack, c);
463 else if (! inside && c == ' ')
464 break;
465 else if (! inside && c == '\\')
466 backquote = 1;
467 else if (c == '\'')
468 inside = !inside;
469 else
470 obstack_1grow (&temporary_obstack, c);
473 obstack_1grow (&temporary_obstack, '\0');
474 *pp = p;
475 return XOBFINISH (&temporary_obstack, char *);
478 void
479 dump_file (const char *name, FILE *to)
481 FILE *stream = fopen (name, "r");
483 if (stream == 0)
484 return;
485 while (1)
487 int c;
488 while (c = getc (stream),
489 c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
490 obstack_1grow (&temporary_obstack, c);
491 if (obstack_object_size (&temporary_obstack) > 0)
493 const char *word, *p;
494 char *result;
495 obstack_1grow (&temporary_obstack, '\0');
496 word = XOBFINISH (&temporary_obstack, const char *);
498 if (*word == '.')
499 ++word, putc ('.', to);
500 p = word;
501 if (!strncmp (p, USER_LABEL_PREFIX, strlen (USER_LABEL_PREFIX)))
502 p += strlen (USER_LABEL_PREFIX);
504 #ifdef HAVE_LD_DEMANGLE
505 result = 0;
506 #else
507 if (no_demangle)
508 result = 0;
509 else
510 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI | DMGL_VERBOSE);
511 #endif
513 if (result)
515 int diff;
516 fputs (result, to);
518 diff = strlen (word) - strlen (result);
519 while (diff > 0 && c == ' ')
520 --diff, putc (' ', to);
521 if (diff < 0 && c == ' ')
523 while (diff < 0 && c == ' ')
524 ++diff, c = getc (stream);
525 if (!ISSPACE (c))
527 /* Make sure we output at least one space, or
528 the demangled symbol name will run into
529 whatever text follows. */
530 putc (' ', to);
534 free (result);
536 else
537 fputs (word, to);
539 fflush (to);
540 obstack_free (&temporary_obstack, temporary_firstobj);
542 if (c == EOF)
543 break;
544 putc (c, to);
546 fclose (stream);
549 /* Return the kind of symbol denoted by name S. */
551 static symkind
552 is_ctor_dtor (const char *s)
554 struct names { const char *const name; const int len; symkind ret;
555 const int two_underscores; };
557 const struct names *p;
558 int ch;
559 const char *orig_s = s;
561 static const struct names special[] = {
562 #ifndef NO_DOLLAR_IN_LABEL
563 { "GLOBAL__I$", sizeof ("GLOBAL__I$")-1, SYM_CTOR, 0 },
564 { "GLOBAL__D$", sizeof ("GLOBAL__D$")-1, SYM_DTOR, 0 },
565 #else
566 #ifndef NO_DOT_IN_LABEL
567 { "GLOBAL__I.", sizeof ("GLOBAL__I.")-1, SYM_CTOR, 0 },
568 { "GLOBAL__D.", sizeof ("GLOBAL__D.")-1, SYM_DTOR, 0 },
569 #endif /* NO_DOT_IN_LABEL */
570 #endif /* NO_DOLLAR_IN_LABEL */
571 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, SYM_CTOR, 0 },
572 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, SYM_DTOR, 0 },
573 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, SYM_DWEH, 0 },
574 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, SYM_INIT, 0 },
575 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, SYM_FINI, 0 },
576 { NULL, 0, SYM_REGULAR, 0 }
579 while ((ch = *s) == '_')
580 ++s;
582 if (s == orig_s)
583 return SYM_REGULAR;
585 for (p = &special[0]; p->len > 0; p++)
587 if (ch == p->name[0]
588 && (!p->two_underscores || ((s - orig_s) >= 2))
589 && strncmp(s, p->name, p->len) == 0)
591 return p->ret;
594 return SYM_REGULAR;
597 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
598 and one from the PATH variable. */
600 static struct path_prefix cpath, path;
602 #ifdef CROSS_DIRECTORY_STRUCTURE
603 /* This is the name of the target machine. We use it to form the name
604 of the files to execute. */
606 static const char *const target_machine = TARGET_MACHINE;
607 #endif
609 /* Search for NAME using prefix list PPREFIX. We only look for executable
610 files.
612 Return 0 if not found, otherwise return its name, allocated with malloc. */
614 static char *
615 find_a_file (struct path_prefix *pprefix, const char *name)
617 char *temp;
618 struct prefix_list *pl;
619 int len = pprefix->max_len + strlen (name) + 1;
621 if (debug)
622 fprintf (stderr, "Looking for '%s'\n", name);
624 #ifdef HOST_EXECUTABLE_SUFFIX
625 len += strlen (HOST_EXECUTABLE_SUFFIX);
626 #endif
628 temp = XNEWVEC (char, len);
630 /* Determine the filename to execute (special case for absolute paths). */
632 if (IS_ABSOLUTE_PATH (name))
634 if (access (name, X_OK) == 0)
636 strcpy (temp, name);
638 if (debug)
639 fprintf (stderr, " - found: absolute path\n");
641 return temp;
644 #ifdef HOST_EXECUTABLE_SUFFIX
645 /* Some systems have a suffix for executable files.
646 So try appending that. */
647 strcpy (temp, name);
648 strcat (temp, HOST_EXECUTABLE_SUFFIX);
650 if (access (temp, X_OK) == 0)
651 return temp;
652 #endif
654 if (debug)
655 fprintf (stderr, " - failed to locate using absolute path\n");
657 else
658 for (pl = pprefix->plist; pl; pl = pl->next)
660 struct stat st;
662 strcpy (temp, pl->prefix);
663 strcat (temp, name);
665 if (stat (temp, &st) >= 0
666 && ! S_ISDIR (st.st_mode)
667 && access (temp, X_OK) == 0)
668 return temp;
670 #ifdef HOST_EXECUTABLE_SUFFIX
671 /* Some systems have a suffix for executable files.
672 So try appending that. */
673 strcat (temp, HOST_EXECUTABLE_SUFFIX);
675 if (stat (temp, &st) >= 0
676 && ! S_ISDIR (st.st_mode)
677 && access (temp, X_OK) == 0)
678 return temp;
679 #endif
682 if (debug && pprefix->plist == NULL)
683 fprintf (stderr, " - failed: no entries in prefix list\n");
685 free (temp);
686 return 0;
689 /* Add an entry for PREFIX to prefix list PPREFIX. */
691 static void
692 add_prefix (struct path_prefix *pprefix, const char *prefix)
694 struct prefix_list *pl, **prev;
695 int len;
697 if (pprefix->plist)
699 for (pl = pprefix->plist; pl->next; pl = pl->next)
701 prev = &pl->next;
703 else
704 prev = &pprefix->plist;
706 /* Keep track of the longest prefix. */
708 len = strlen (prefix);
709 if (len > pprefix->max_len)
710 pprefix->max_len = len;
712 pl = XNEW (struct prefix_list);
713 pl->prefix = xstrdup (prefix);
715 if (*prev)
716 pl->next = *prev;
717 else
718 pl->next = (struct prefix_list *) 0;
719 *prev = pl;
722 /* Take the value of the environment variable ENV, break it into a path, and
723 add of the entries to PPREFIX. */
725 static void
726 prefix_from_env (const char *env, struct path_prefix *pprefix)
728 const char *p;
729 GET_ENVIRONMENT (p, env);
731 if (p)
732 prefix_from_string (p, pprefix);
735 static void
736 prefix_from_string (const char *p, struct path_prefix *pprefix)
738 const char *startp, *endp;
739 char *nstore = XNEWVEC (char, strlen (p) + 3);
741 if (debug)
742 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
744 startp = endp = p;
745 while (1)
747 if (*endp == PATH_SEPARATOR || *endp == 0)
749 strncpy (nstore, startp, endp-startp);
750 if (endp == startp)
752 strcpy (nstore, "./");
754 else if (! IS_DIR_SEPARATOR (endp[-1]))
756 nstore[endp-startp] = DIR_SEPARATOR;
757 nstore[endp-startp+1] = 0;
759 else
760 nstore[endp-startp] = 0;
762 if (debug)
763 fprintf (stderr, " - add prefix: %s\n", nstore);
765 add_prefix (pprefix, nstore);
766 if (*endp == 0)
767 break;
768 endp = startp = endp + 1;
770 else
771 endp++;
773 free (nstore);
776 /* Main program. */
779 main (int argc, char **argv)
781 static const char *const ld_suffix = "ld";
782 static const char *const real_ld_suffix = "real-ld";
783 static const char *const collect_ld_suffix = "collect-ld";
784 static const char *const nm_suffix = "nm";
785 static const char *const gnm_suffix = "gnm";
786 #ifdef LDD_SUFFIX
787 static const char *const ldd_suffix = LDD_SUFFIX;
788 #endif
789 static const char *const strip_suffix = "strip";
790 static const char *const gstrip_suffix = "gstrip";
792 #ifdef CROSS_DIRECTORY_STRUCTURE
793 /* If we look for a program in the compiler directories, we just use
794 the short name, since these directories are already system-specific.
795 But it we look for a program in the system directories, we need to
796 qualify the program name with the target machine. */
798 const char *const full_ld_suffix =
799 concat(target_machine, "-", ld_suffix, NULL);
800 const char *const full_nm_suffix =
801 concat (target_machine, "-", nm_suffix, NULL);
802 const char *const full_gnm_suffix =
803 concat (target_machine, "-", gnm_suffix, NULL);
804 #ifdef LDD_SUFFIX
805 const char *const full_ldd_suffix =
806 concat (target_machine, "-", ldd_suffix, NULL);
807 #endif
808 const char *const full_strip_suffix =
809 concat (target_machine, "-", strip_suffix, NULL);
810 const char *const full_gstrip_suffix =
811 concat (target_machine, "-", gstrip_suffix, NULL);
812 #else
813 const char *const full_ld_suffix = ld_suffix;
814 const char *const full_nm_suffix = nm_suffix;
815 const char *const full_gnm_suffix = gnm_suffix;
816 #ifdef LDD_SUFFIX
817 const char *const full_ldd_suffix = ldd_suffix;
818 #endif
819 const char *const full_strip_suffix = strip_suffix;
820 const char *const full_gstrip_suffix = gstrip_suffix;
821 #endif /* CROSS_DIRECTORY_STRUCTURE */
823 const char *arg;
824 FILE *outf;
825 #ifdef COLLECT_EXPORT_LIST
826 FILE *exportf;
827 #endif
828 const char *ld_file_name;
829 const char *p;
830 char **c_argv;
831 const char **c_ptr;
832 char **ld1_argv;
833 const char **ld1;
834 char **ld2_argv;
835 const char **ld2;
836 char **object_lst;
837 const char **object;
838 int first_file;
839 int num_c_args;
840 char **old_argv;
842 old_argv = argv;
843 expandargv (&argc, &argv);
844 if (argv != old_argv)
845 at_file_supplied = 1;
847 num_c_args = argc + 9;
849 no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
851 /* Suppress demangling by the real linker, which may be broken. */
852 putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
854 #if defined (COLLECT2_HOST_INITIALIZATION)
855 /* Perform system dependent initialization, if necessary. */
856 COLLECT2_HOST_INITIALIZATION;
857 #endif
859 #ifdef SIGCHLD
860 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
861 receive the signal. A different setting is inheritable */
862 signal (SIGCHLD, SIG_DFL);
863 #endif
865 /* Unlock the stdio streams. */
866 unlock_std_streams ();
868 gcc_init_libintl ();
870 /* Do not invoke xcalloc before this point, since locale needs to be
871 set first, in case a diagnostic is issued. */
873 ld1_argv = XCNEWVEC (char *, argc + 4);
874 ld1 = CONST_CAST2 (const char **, char **, ld1_argv);
875 ld2_argv = XCNEWVEC (char *, argc + 11);
876 ld2 = CONST_CAST2 (const char **, char **, ld2_argv);
877 object_lst = XCNEWVEC (char *, argc);
878 object = CONST_CAST2 (const char **, char **, object_lst);
880 #ifdef DEBUG
881 debug = 1;
882 #endif
884 /* Parse command line early for instances of -debug. This allows
885 the debug flag to be set before functions like find_a_file()
886 are called. */
888 int i;
890 for (i = 1; argv[i] != NULL; i ++)
892 if (! strcmp (argv[i], "-debug"))
893 debug = 1;
895 vflag = debug;
898 #ifndef DEFAULT_A_OUT_NAME
899 output_file = "a.out";
900 #else
901 output_file = DEFAULT_A_OUT_NAME;
902 #endif
904 obstack_begin (&temporary_obstack, 0);
905 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
907 #ifndef HAVE_LD_DEMANGLE
908 current_demangling_style = auto_demangling;
909 #endif
910 p = getenv ("COLLECT_GCC_OPTIONS");
911 while (p && *p)
913 const char *q = extract_string (&p);
914 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
915 num_c_args++;
917 obstack_free (&temporary_obstack, temporary_firstobj);
919 /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
920 -fno-exceptions -w */
921 num_c_args += 5;
923 c_argv = XCNEWVEC (char *, num_c_args);
924 c_ptr = CONST_CAST2 (const char **, char **, c_argv);
926 if (argc < 2)
927 fatal ("no arguments");
929 #ifdef SIGQUIT
930 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
931 signal (SIGQUIT, handler);
932 #endif
933 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
934 signal (SIGINT, handler);
935 #ifdef SIGALRM
936 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
937 signal (SIGALRM, handler);
938 #endif
939 #ifdef SIGHUP
940 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
941 signal (SIGHUP, handler);
942 #endif
943 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
944 signal (SIGSEGV, handler);
945 #ifdef SIGBUS
946 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
947 signal (SIGBUS, handler);
948 #endif
950 /* Extract COMPILER_PATH and PATH into our prefix list. */
951 prefix_from_env ("COMPILER_PATH", &cpath);
952 prefix_from_env ("PATH", &path);
954 /* Try to discover a valid linker/nm/strip to use. */
956 /* Maybe we know the right file to use (if not cross). */
957 ld_file_name = 0;
958 #ifdef DEFAULT_LINKER
959 if (access (DEFAULT_LINKER, X_OK) == 0)
960 ld_file_name = DEFAULT_LINKER;
961 if (ld_file_name == 0)
962 #endif
963 #ifdef REAL_LD_FILE_NAME
964 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
965 if (ld_file_name == 0)
966 #endif
967 /* Search the (target-specific) compiler dirs for ld'. */
968 ld_file_name = find_a_file (&cpath, real_ld_suffix);
969 /* Likewise for `collect-ld'. */
970 if (ld_file_name == 0)
971 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
972 /* Search the compiler directories for `ld'. We have protection against
973 recursive calls in find_a_file. */
974 if (ld_file_name == 0)
975 ld_file_name = find_a_file (&cpath, ld_suffix);
976 /* Search the ordinary system bin directories
977 for `ld' (if native linking) or `TARGET-ld' (if cross). */
978 if (ld_file_name == 0)
979 ld_file_name = find_a_file (&path, full_ld_suffix);
981 #ifdef REAL_NM_FILE_NAME
982 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
983 if (nm_file_name == 0)
984 #endif
985 nm_file_name = find_a_file (&cpath, gnm_suffix);
986 if (nm_file_name == 0)
987 nm_file_name = find_a_file (&path, full_gnm_suffix);
988 if (nm_file_name == 0)
989 nm_file_name = find_a_file (&cpath, nm_suffix);
990 if (nm_file_name == 0)
991 nm_file_name = find_a_file (&path, full_nm_suffix);
993 #ifdef LDD_SUFFIX
994 ldd_file_name = find_a_file (&cpath, ldd_suffix);
995 if (ldd_file_name == 0)
996 ldd_file_name = find_a_file (&path, full_ldd_suffix);
997 #endif
999 #ifdef REAL_STRIP_FILE_NAME
1000 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1001 if (strip_file_name == 0)
1002 #endif
1003 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1004 if (strip_file_name == 0)
1005 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1006 if (strip_file_name == 0)
1007 strip_file_name = find_a_file (&cpath, strip_suffix);
1008 if (strip_file_name == 0)
1009 strip_file_name = find_a_file (&path, full_strip_suffix);
1011 /* Determine the full path name of the C compiler to use. */
1012 c_file_name = getenv ("COLLECT_GCC");
1013 if (c_file_name == 0)
1015 #ifdef CROSS_DIRECTORY_STRUCTURE
1016 c_file_name = concat (target_machine, "-gcc", NULL);
1017 #else
1018 c_file_name = "gcc";
1019 #endif
1022 p = find_a_file (&cpath, c_file_name);
1024 /* Here it should be safe to use the system search path since we should have
1025 already qualified the name of the compiler when it is needed. */
1026 if (p == 0)
1027 p = find_a_file (&path, c_file_name);
1029 if (p)
1030 c_file_name = p;
1032 *ld1++ = *ld2++ = ld_file_name;
1034 /* Make temp file names. */
1035 c_file = make_temp_file (".c");
1036 o_file = make_temp_file (".o");
1037 #ifdef COLLECT_EXPORT_LIST
1038 export_file = make_temp_file (".x");
1039 #endif
1040 ldout = make_temp_file (".ld");
1041 lderrout = make_temp_file (".le");
1042 *c_ptr++ = c_file_name;
1043 *c_ptr++ = "-x";
1044 *c_ptr++ = "c";
1045 *c_ptr++ = "-c";
1046 *c_ptr++ = "-o";
1047 *c_ptr++ = o_file;
1049 #ifdef COLLECT_EXPORT_LIST
1050 /* Generate a list of directories from LIBPATH. */
1051 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1052 /* Add to this list also two standard directories where
1053 AIX loader always searches for libraries. */
1054 add_prefix (&libpath_lib_dirs, "/lib");
1055 add_prefix (&libpath_lib_dirs, "/usr/lib");
1056 #endif
1058 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1060 AIX support needs to know if -shared has been specified before
1061 parsing commandline arguments. */
1063 p = getenv ("COLLECT_GCC_OPTIONS");
1064 while (p && *p)
1066 const char *q = extract_string (&p);
1067 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1068 *c_ptr++ = xstrdup (q);
1069 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1070 *c_ptr++ = xstrdup (q);
1071 if (strcmp (q, "-shared") == 0)
1072 shared_obj = 1;
1073 if (*q == '-' && q[1] == 'B')
1075 *c_ptr++ = xstrdup (q);
1076 if (q[2] == 0)
1078 q = extract_string (&p);
1079 *c_ptr++ = xstrdup (q);
1083 obstack_free (&temporary_obstack, temporary_firstobj);
1084 *c_ptr++ = "-fno-profile-arcs";
1085 *c_ptr++ = "-fno-test-coverage";
1086 *c_ptr++ = "-fno-branch-probabilities";
1087 *c_ptr++ = "-fno-exceptions";
1088 *c_ptr++ = "-w";
1090 /* !!! When GCC calls collect2,
1091 it does not know whether it is calling collect2 or ld.
1092 So collect2 cannot meaningfully understand any options
1093 except those ld understands.
1094 If you propose to make GCC pass some other option,
1095 just imagine what will happen if ld is really ld!!! */
1097 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1098 /* After the first file, put in the c++ rt0. */
1100 first_file = 1;
1101 #ifdef HAVE_LD_DEMANGLE
1102 if (!demangle_flag && !no_demangle)
1103 demangle_flag = "--demangle";
1104 if (demangle_flag)
1105 *ld1++ = *ld2++ = demangle_flag;
1106 #endif
1107 while ((arg = *++argv) != (char *) 0)
1109 *ld1++ = *ld2++ = arg;
1111 if (arg[0] == '-')
1113 switch (arg[1])
1115 #ifdef COLLECT_EXPORT_LIST
1116 /* We want to disable automatic exports on AIX when user
1117 explicitly puts an export list in command line */
1118 case 'b':
1119 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1120 export_flag = 1;
1121 else if (arg[2] == '6' && arg[3] == '4')
1122 aix64_flag = 1;
1123 else if (arg[2] == 'r' && arg[3] == 't' && arg[4] == 'l')
1124 aixrtl_flag = 1;
1125 break;
1126 #endif
1128 case 'd':
1129 if (!strcmp (arg, "-debug"))
1131 /* Already parsed. */
1132 ld1--;
1133 ld2--;
1135 if (!strcmp (arg, "-dynamic-linker") && argv[1])
1137 ++argv;
1138 *ld1++ = *ld2++ = *argv;
1140 break;
1142 case 'l':
1143 if (first_file)
1145 /* place o_file BEFORE this argument! */
1146 first_file = 0;
1147 ld2--;
1148 *ld2++ = o_file;
1149 *ld2++ = arg;
1151 #ifdef COLLECT_EXPORT_LIST
1153 /* Resolving full library name. */
1154 const char *s = resolve_lib_name (arg+2);
1156 /* Saving a full library name. */
1157 add_to_list (&libs, s);
1159 #endif
1160 break;
1162 #ifdef COLLECT_EXPORT_LIST
1163 /* Saving directories where to search for libraries. */
1164 case 'L':
1165 add_prefix (&cmdline_lib_dirs, arg+2);
1166 break;
1167 #else
1168 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1169 case 'L':
1170 if (is_in_args (arg, (const char **) ld1_argv, ld1-1))
1171 --ld1;
1172 break;
1173 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1174 #endif
1176 case 'o':
1177 if (arg[2] == '\0')
1178 output_file = *ld1++ = *ld2++ = *++argv;
1179 else if (1
1180 #ifdef SWITCHES_NEED_SPACES
1181 && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1182 #endif
1185 output_file = &arg[2];
1186 break;
1188 case 'r':
1189 if (arg[2] == '\0')
1190 rflag = 1;
1191 break;
1193 case 's':
1194 if (arg[2] == '\0' && do_collecting)
1196 /* We must strip after the nm run, otherwise C++ linking
1197 will not work. Thus we strip in the second ld run, or
1198 else with strip if there is no second ld run. */
1199 strip_flag = 1;
1200 ld1--;
1202 break;
1204 case 'v':
1205 if (arg[2] == '\0')
1206 vflag = 1;
1207 break;
1209 case '-':
1210 if (strcmp (arg, "--no-demangle") == 0)
1212 demangle_flag = arg;
1213 no_demangle = 1;
1214 ld1--;
1215 ld2--;
1217 else if (strncmp (arg, "--demangle", 10) == 0)
1219 demangle_flag = arg;
1220 no_demangle = 0;
1221 #ifndef HAVE_LD_DEMANGLE
1222 if (arg[10] == '=')
1224 enum demangling_styles style
1225 = cplus_demangle_name_to_style (arg+11);
1226 if (style == unknown_demangling)
1227 error ("unknown demangling style '%s'", arg+11);
1228 else
1229 current_demangling_style = style;
1231 #endif
1232 ld1--;
1233 ld2--;
1235 else if (strncmp (arg, "--sysroot=", 10) == 0)
1236 target_system_root = arg + 10;
1237 break;
1240 else if ((p = strrchr (arg, '.')) != (char *) 0
1241 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1242 || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1243 || strcmp (p, ".obj") == 0))
1245 if (first_file)
1247 first_file = 0;
1248 if (p[1] == 'o')
1249 *ld2++ = o_file;
1250 else
1252 /* place o_file BEFORE this argument! */
1253 ld2--;
1254 *ld2++ = o_file;
1255 *ld2++ = arg;
1258 if (p[1] == 'o' || p[1] == 'l')
1259 *object++ = arg;
1260 #ifdef COLLECT_EXPORT_LIST
1261 /* libraries can be specified directly, i.e. without -l flag. */
1262 else
1264 /* Saving a full library name. */
1265 add_to_list (&libs, arg);
1267 #endif
1271 #ifdef COLLECT_EXPORT_LIST
1272 /* This is added only for debugging purposes. */
1273 if (debug)
1275 fprintf (stderr, "List of libraries:\n");
1276 dump_list (stderr, "\t", libs.first);
1279 /* The AIX linker will discard static constructors in object files if
1280 nothing else in the file is referenced, so look at them first. */
1282 const char **export_object_lst = (const char **)object_lst;
1284 while (export_object_lst < object)
1285 scan_prog_file (*export_object_lst++, PASS_OBJ);
1288 struct id *list = libs.first;
1290 for (; list; list = list->next)
1291 scan_prog_file (list->name, PASS_FIRST);
1294 if (exports.first)
1296 char *buf = concat ("-bE:", export_file, NULL);
1298 *ld1++ = buf;
1299 *ld2++ = buf;
1301 exportf = fopen (export_file, "w");
1302 if (exportf == (FILE *) 0)
1303 fatal_perror ("fopen %s", export_file);
1304 write_aix_file (exportf, exports.first);
1305 if (fclose (exportf))
1306 fatal_perror ("fclose %s", export_file);
1308 #endif
1310 *c_ptr++ = c_file;
1311 *c_ptr = *ld1 = *object = (char *) 0;
1313 if (vflag)
1315 notice ("collect2 version %s", version_string);
1316 #ifdef TARGET_VERSION
1317 TARGET_VERSION;
1318 #endif
1319 fprintf (stderr, "\n");
1322 if (debug)
1324 const char *ptr;
1325 fprintf (stderr, "ld_file_name = %s\n",
1326 (ld_file_name ? ld_file_name : "not found"));
1327 fprintf (stderr, "c_file_name = %s\n",
1328 (c_file_name ? c_file_name : "not found"));
1329 fprintf (stderr, "nm_file_name = %s\n",
1330 (nm_file_name ? nm_file_name : "not found"));
1331 #ifdef LDD_SUFFIX
1332 fprintf (stderr, "ldd_file_name = %s\n",
1333 (ldd_file_name ? ldd_file_name : "not found"));
1334 #endif
1335 fprintf (stderr, "strip_file_name = %s\n",
1336 (strip_file_name ? strip_file_name : "not found"));
1337 fprintf (stderr, "c_file = %s\n",
1338 (c_file ? c_file : "not found"));
1339 fprintf (stderr, "o_file = %s\n",
1340 (o_file ? o_file : "not found"));
1342 ptr = getenv ("COLLECT_GCC_OPTIONS");
1343 if (ptr)
1344 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1346 ptr = getenv ("COLLECT_GCC");
1347 if (ptr)
1348 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1350 ptr = getenv ("COMPILER_PATH");
1351 if (ptr)
1352 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1354 ptr = getenv (LIBRARY_PATH_ENV);
1355 if (ptr)
1356 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1358 fprintf (stderr, "\n");
1361 /* Load the program, searching all libraries and attempting to provide
1362 undefined symbols from repository information. */
1364 /* On AIX we do this later. */
1365 #ifndef COLLECT_EXPORT_LIST
1366 do_tlink (ld1_argv, object_lst);
1367 #endif
1369 /* If -r or they will be run via some other method, do not build the
1370 constructor or destructor list, just return now. */
1371 if (rflag
1372 #ifndef COLLECT_EXPORT_LIST
1373 || ! do_collecting
1374 #endif
1377 #ifdef COLLECT_EXPORT_LIST
1378 /* Do the link we avoided above if we are exiting. */
1379 do_tlink (ld1_argv, object_lst);
1381 /* But make sure we delete the export file we may have created. */
1382 if (export_file != 0 && export_file[0])
1383 maybe_unlink (export_file);
1384 #endif
1385 maybe_unlink (c_file);
1386 maybe_unlink (o_file);
1387 return 0;
1390 /* Examine the namelist with nm and search it for static constructors
1391 and destructors to call.
1392 Write the constructor and destructor tables to a .s file and reload. */
1394 /* On AIX we already scanned for global constructors/destructors. */
1395 #ifndef COLLECT_EXPORT_LIST
1396 scan_prog_file (output_file, PASS_FIRST);
1397 #endif
1399 #ifdef SCAN_LIBRARIES
1400 scan_libraries (output_file);
1401 #endif
1403 if (debug)
1405 notice ("%d constructor(s) found\n", constructors.number);
1406 notice ("%d destructor(s) found\n", destructors.number);
1407 notice ("%d frame table(s) found\n", frame_tables.number);
1410 if (constructors.number == 0 && destructors.number == 0
1411 && frame_tables.number == 0
1412 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1413 /* If we will be running these functions ourselves, we want to emit
1414 stubs into the shared library so that we do not have to relink
1415 dependent programs when we add static objects. */
1416 && ! shared_obj
1417 #endif
1420 #ifdef COLLECT_EXPORT_LIST
1421 /* Do tlink without additional code generation. */
1422 do_tlink (ld1_argv, object_lst);
1423 #endif
1424 /* Strip now if it was requested on the command line. */
1425 if (strip_flag)
1427 char **real_strip_argv = XCNEWVEC (char *, 3);
1428 const char ** strip_argv = CONST_CAST2 (const char **, char **,
1429 real_strip_argv);
1431 strip_argv[0] = strip_file_name;
1432 strip_argv[1] = output_file;
1433 strip_argv[2] = (char *) 0;
1434 fork_execute ("strip", real_strip_argv);
1437 #ifdef COLLECT_EXPORT_LIST
1438 maybe_unlink (export_file);
1439 #endif
1440 maybe_unlink (c_file);
1441 maybe_unlink (o_file);
1442 return 0;
1445 /* Sort ctor and dtor lists by priority. */
1446 sort_ids (&constructors);
1447 sort_ids (&destructors);
1449 maybe_unlink(output_file);
1450 outf = fopen (c_file, "w");
1451 if (outf == (FILE *) 0)
1452 fatal_perror ("fopen %s", c_file);
1454 write_c_file (outf, c_file);
1456 if (fclose (outf))
1457 fatal_perror ("fclose %s", c_file);
1459 /* Tell the linker that we have initializer and finalizer functions. */
1460 #ifdef LD_INIT_SWITCH
1461 #ifdef COLLECT_EXPORT_LIST
1462 *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1463 #else
1464 *ld2++ = LD_INIT_SWITCH;
1465 *ld2++ = initname;
1466 *ld2++ = LD_FINI_SWITCH;
1467 *ld2++ = fininame;
1468 #endif
1469 #endif
1471 #ifdef COLLECT_EXPORT_LIST
1472 if (shared_obj)
1474 /* If we did not add export flag to link arguments before, add it to
1475 second link phase now. No new exports should have been added. */
1476 if (! exports.first)
1477 *ld2++ = concat ("-bE:", export_file, NULL);
1479 #ifndef LD_INIT_SWITCH
1480 add_to_list (&exports, initname);
1481 add_to_list (&exports, fininame);
1482 add_to_list (&exports, "_GLOBAL__DI");
1483 add_to_list (&exports, "_GLOBAL__DD");
1484 #endif
1485 exportf = fopen (export_file, "w");
1486 if (exportf == (FILE *) 0)
1487 fatal_perror ("fopen %s", export_file);
1488 write_aix_file (exportf, exports.first);
1489 if (fclose (exportf))
1490 fatal_perror ("fclose %s", export_file);
1492 #endif
1494 /* End of arguments to second link phase. */
1495 *ld2 = (char*) 0;
1497 if (debug)
1499 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1500 output_file, c_file);
1501 write_c_file (stderr, "stderr");
1502 fprintf (stderr, "========== end of c_file\n\n");
1503 #ifdef COLLECT_EXPORT_LIST
1504 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1505 write_aix_file (stderr, exports.first);
1506 fprintf (stderr, "========== end of export_file\n\n");
1507 #endif
1510 /* Assemble the constructor and destructor tables.
1511 Link the tables in with the rest of the program. */
1513 fork_execute ("gcc", c_argv);
1514 #ifdef COLLECT_EXPORT_LIST
1515 /* On AIX we must call tlink because of possible templates resolution. */
1516 do_tlink (ld2_argv, object_lst);
1517 #else
1518 /* Otherwise, simply call ld because tlink is already done. */
1519 fork_execute ("ld", ld2_argv);
1521 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1522 constructors/destructors in shared libraries. */
1523 scan_prog_file (output_file, PASS_SECOND);
1524 #endif
1526 maybe_unlink (c_file);
1527 maybe_unlink (o_file);
1529 #ifdef COLLECT_EXPORT_LIST
1530 maybe_unlink (export_file);
1531 #endif
1533 return 0;
1537 /* Wait for a process to finish, and exit if a nonzero status is found. */
1540 collect_wait (const char *prog, struct pex_obj *pex)
1542 int status;
1544 if (!pex_get_status (pex, 1, &status))
1545 fatal_perror ("can't get program status");
1546 pex_free (pex);
1548 if (status)
1550 if (WIFSIGNALED (status))
1552 int sig = WTERMSIG (status);
1553 error ("%s terminated with signal %d [%s]%s",
1554 prog, sig, strsignal(sig),
1555 WCOREDUMP(status) ? ", core dumped" : "");
1556 collect_exit (FATAL_EXIT_CODE);
1559 if (WIFEXITED (status))
1560 return WEXITSTATUS (status);
1562 return 0;
1565 static void
1566 do_wait (const char *prog, struct pex_obj *pex)
1568 int ret = collect_wait (prog, pex);
1569 if (ret != 0)
1571 error ("%s returned %d exit status", prog, ret);
1572 collect_exit (ret);
1575 if (response_file)
1577 unlink (response_file);
1578 response_file = NULL;
1583 /* Execute a program, and wait for the reply. */
1585 struct pex_obj *
1586 collect_execute (const char *prog, char **argv, const char *outname,
1587 const char *errname)
1589 struct pex_obj *pex;
1590 const char *errmsg;
1591 int err;
1592 char *response_arg = NULL;
1593 char *response_argv[3] ATTRIBUTE_UNUSED;
1595 if (HAVE_GNU_LD && at_file_supplied && argv[0] != NULL)
1597 /* If using @file arguments, create a temporary file and put the
1598 contents of argv into it. Then change argv to an array corresponding
1599 to a single argument @FILE, where FILE is the temporary filename. */
1601 char **current_argv = argv + 1;
1602 char *argv0 = argv[0];
1603 int status;
1604 FILE *f;
1606 /* Note: we assume argv contains at least one element; this is
1607 checked above. */
1609 response_file = make_temp_file ("");
1611 f = fopen (response_file, "w");
1613 if (f == NULL)
1614 fatal ("could not open response file %s", response_file);
1616 status = writeargv (current_argv, f);
1618 if (status)
1619 fatal ("could not write to response file %s", response_file);
1621 status = fclose (f);
1623 if (EOF == status)
1624 fatal ("could not close response file %s", response_file);
1626 response_arg = concat ("@", response_file, NULL);
1627 response_argv[0] = argv0;
1628 response_argv[1] = response_arg;
1629 response_argv[2] = NULL;
1631 argv = response_argv;
1634 if (vflag || debug)
1636 char **p_argv;
1637 const char *str;
1639 if (argv[0])
1640 fprintf (stderr, "%s", argv[0]);
1641 else
1642 notice ("[cannot find %s]", prog);
1644 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1645 fprintf (stderr, " %s", str);
1647 fprintf (stderr, "\n");
1650 fflush (stdout);
1651 fflush (stderr);
1653 /* If we cannot find a program we need, complain error. Do this here
1654 since we might not end up needing something that we could not find. */
1656 if (argv[0] == 0)
1657 fatal ("cannot find '%s'", prog);
1659 pex = pex_init (0, "collect2", NULL);
1660 if (pex == NULL)
1661 fatal_perror ("pex_init failed");
1663 errmsg = pex_run (pex, PEX_LAST | PEX_SEARCH, argv[0], argv, outname,
1664 errname, &err);
1665 if (errmsg != NULL)
1667 if (err != 0)
1669 errno = err;
1670 fatal_perror (errmsg);
1672 else
1673 fatal (errmsg);
1676 if (response_arg)
1677 free (response_arg);
1679 return pex;
1682 static void
1683 fork_execute (const char *prog, char **argv)
1685 struct pex_obj *pex;
1687 pex = collect_execute (prog, argv, NULL, NULL);
1688 do_wait (prog, pex);
1691 /* Unlink a file unless we are debugging. */
1693 static void
1694 maybe_unlink (const char *file)
1696 if (!debug)
1697 unlink_if_ordinary (file);
1698 else
1699 notice ("[Leaving %s]\n", file);
1703 static long sequence_number = 0;
1705 /* Add a name to a linked list. */
1707 static void
1708 add_to_list (struct head *head_ptr, const char *name)
1710 struct id *newid
1711 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1712 struct id *p;
1713 strcpy (newid->name, name);
1715 if (head_ptr->first)
1716 head_ptr->last->next = newid;
1717 else
1718 head_ptr->first = newid;
1720 /* Check for duplicate symbols. */
1721 for (p = head_ptr->first;
1722 strcmp (name, p->name) != 0;
1723 p = p->next)
1725 if (p != newid)
1727 head_ptr->last->next = 0;
1728 free (newid);
1729 return;
1732 newid->sequence = ++sequence_number;
1733 head_ptr->last = newid;
1734 head_ptr->number++;
1737 /* Grab the init priority number from an init function name that
1738 looks like "_GLOBAL_.I.12345.foo". */
1740 static int
1741 extract_init_priority (const char *name)
1743 int pos = 0, pri;
1745 while (name[pos] == '_')
1746 ++pos;
1747 pos += 10; /* strlen ("GLOBAL__X_") */
1749 /* Extract init_p number from ctor/dtor name. */
1750 pri = atoi (name + pos);
1751 return pri ? pri : DEFAULT_INIT_PRIORITY;
1754 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1755 ctors will be run from right to left, dtors from left to right. */
1757 static void
1758 sort_ids (struct head *head_ptr)
1760 /* id holds the current element to insert. id_next holds the next
1761 element to insert. id_ptr iterates through the already sorted elements
1762 looking for the place to insert id. */
1763 struct id *id, *id_next, **id_ptr;
1765 id = head_ptr->first;
1767 /* We don't have any sorted elements yet. */
1768 head_ptr->first = NULL;
1770 for (; id; id = id_next)
1772 id_next = id->next;
1773 id->sequence = extract_init_priority (id->name);
1775 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1776 if (*id_ptr == NULL
1777 /* If the sequence numbers are the same, we put the id from the
1778 file later on the command line later in the list. */
1779 || id->sequence > (*id_ptr)->sequence
1780 /* Hack: do lexical compare, too.
1781 || (id->sequence == (*id_ptr)->sequence
1782 && strcmp (id->name, (*id_ptr)->name) > 0) */
1785 id->next = *id_ptr;
1786 *id_ptr = id;
1787 break;
1791 /* Now set the sequence numbers properly so write_c_file works. */
1792 for (id = head_ptr->first; id; id = id->next)
1793 id->sequence = ++sequence_number;
1796 /* Write: `prefix', the names on list LIST, `suffix'. */
1798 static void
1799 write_list (FILE *stream, const char *prefix, struct id *list)
1801 while (list)
1803 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1804 list = list->next;
1808 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1809 /* Given a STRING, return nonzero if it occurs in the list in range
1810 [ARGS_BEGIN,ARGS_END). */
1812 static int
1813 is_in_args (const char *string, const char **args_begin,
1814 const char **args_end)
1816 const char **args_pointer;
1817 for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1818 if (strcmp (string, *args_pointer) == 0)
1819 return 1;
1820 return 0;
1822 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1824 #ifdef COLLECT_EXPORT_LIST
1825 /* This function is really used only on AIX, but may be useful. */
1826 #if 0
1827 static int
1828 is_in_list (const char *prefix, struct id *list)
1830 while (list)
1832 if (!strcmp (prefix, list->name)) return 1;
1833 list = list->next;
1835 return 0;
1837 #endif
1838 #endif /* COLLECT_EXPORT_LIST */
1840 /* Added for debugging purpose. */
1841 #ifdef COLLECT_EXPORT_LIST
1842 static void
1843 dump_list (FILE *stream, const char *prefix, struct id *list)
1845 while (list)
1847 fprintf (stream, "%s%s,\n", prefix, list->name);
1848 list = list->next;
1851 #endif
1853 #if 0
1854 static void
1855 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
1857 while (list)
1859 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1860 list = list->next;
1863 #endif
1865 static void
1866 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
1868 while (list)
1870 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1871 prefix, list->sequence, list->name);
1872 list = list->next;
1876 /* Write out the constructor and destructor tables statically (for a shared
1877 object), along with the functions to execute them. */
1879 static void
1880 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
1882 const char *p, *q;
1883 char *prefix, *r;
1884 int frames = (frame_tables.number > 0);
1886 /* Figure out name of output_file, stripping off .so version. */
1887 p = strrchr (output_file, '/');
1888 if (p == 0)
1889 p = output_file;
1890 else
1891 p++;
1892 q = p;
1893 while (q)
1895 q = strchr (q,'.');
1896 if (q == 0)
1898 q = p + strlen (p);
1899 break;
1901 else
1903 if (strncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
1905 q += strlen (SHLIB_SUFFIX);
1906 break;
1908 else
1909 q++;
1912 /* q points to null at end of the string (or . of the .so version) */
1913 prefix = XNEWVEC (char, q - p + 1);
1914 strncpy (prefix, p, q - p);
1915 prefix[q - p] = 0;
1916 for (r = prefix; *r; r++)
1917 if (!ISALNUM ((unsigned char)*r))
1918 *r = '_';
1919 if (debug)
1920 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1921 output_file, prefix);
1923 initname = concat ("_GLOBAL__FI_", prefix, NULL);
1924 fininame = concat ("_GLOBAL__FD_", prefix, NULL);
1926 free (prefix);
1928 /* Write the tables as C code. */
1930 fprintf (stream, "static int count;\n");
1931 fprintf (stream, "typedef void entry_pt();\n");
1932 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1934 if (frames)
1936 write_list_with_asm (stream, "extern void *", frame_tables.first);
1938 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1939 write_list (stream, "\t\t&", frame_tables.first);
1940 fprintf (stream, "\t0\n};\n");
1942 /* This must match what's in frame.h. */
1943 fprintf (stream, "struct object {\n");
1944 fprintf (stream, " void *pc_begin;\n");
1945 fprintf (stream, " void *pc_end;\n");
1946 fprintf (stream, " void *fde_begin;\n");
1947 fprintf (stream, " void *fde_array;\n");
1948 fprintf (stream, " __SIZE_TYPE__ count;\n");
1949 fprintf (stream, " struct object *next;\n");
1950 fprintf (stream, "};\n");
1952 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1953 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1955 fprintf (stream, "static void reg_frame () {\n");
1956 fprintf (stream, "\tstatic struct object ob;\n");
1957 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1958 fprintf (stream, "\t}\n");
1960 fprintf (stream, "static void dereg_frame () {\n");
1961 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1962 fprintf (stream, "\t}\n");
1965 fprintf (stream, "void %s() {\n", initname);
1966 if (constructors.number > 0 || frames)
1968 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1969 write_list (stream, "\t\t", constructors.first);
1970 if (frames)
1971 fprintf (stream, "\treg_frame,\n");
1972 fprintf (stream, "\t};\n");
1973 fprintf (stream, "\tentry_pt **p;\n");
1974 fprintf (stream, "\tif (count++ != 0) return;\n");
1975 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1976 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1978 else
1979 fprintf (stream, "\t++count;\n");
1980 fprintf (stream, "}\n");
1981 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1982 fprintf (stream, "void %s() {\n", fininame);
1983 if (destructors.number > 0 || frames)
1985 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1986 write_list (stream, "\t\t", destructors.first);
1987 if (frames)
1988 fprintf (stream, "\tdereg_frame,\n");
1989 fprintf (stream, "\t};\n");
1990 fprintf (stream, "\tentry_pt **p;\n");
1991 fprintf (stream, "\tif (--count != 0) return;\n");
1992 fprintf (stream, "\tp = dtors;\n");
1993 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1994 destructors.number + frames);
1996 fprintf (stream, "}\n");
1998 if (shared_obj)
2000 COLLECT_SHARED_INIT_FUNC(stream, initname);
2001 COLLECT_SHARED_FINI_FUNC(stream, fininame);
2005 /* Write the constructor/destructor tables. */
2007 #ifndef LD_INIT_SWITCH
2008 static void
2009 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2011 /* Write the tables as C code. */
2013 int frames = (frame_tables.number > 0);
2015 fprintf (stream, "typedef void entry_pt();\n\n");
2017 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2019 if (frames)
2021 write_list_with_asm (stream, "extern void *", frame_tables.first);
2023 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2024 write_list (stream, "\t\t&", frame_tables.first);
2025 fprintf (stream, "\t0\n};\n");
2027 /* This must match what's in frame.h. */
2028 fprintf (stream, "struct object {\n");
2029 fprintf (stream, " void *pc_begin;\n");
2030 fprintf (stream, " void *pc_end;\n");
2031 fprintf (stream, " void *fde_begin;\n");
2032 fprintf (stream, " void *fde_array;\n");
2033 fprintf (stream, " __SIZE_TYPE__ count;\n");
2034 fprintf (stream, " struct object *next;\n");
2035 fprintf (stream, "};\n");
2037 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2038 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2040 fprintf (stream, "static void reg_frame () {\n");
2041 fprintf (stream, "\tstatic struct object ob;\n");
2042 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2043 fprintf (stream, "\t}\n");
2045 fprintf (stream, "static void dereg_frame () {\n");
2046 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2047 fprintf (stream, "\t}\n");
2050 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2051 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2052 write_list (stream, "\t", constructors.first);
2053 if (frames)
2054 fprintf (stream, "\treg_frame,\n");
2055 fprintf (stream, "\t0\n};\n\n");
2057 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2059 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2060 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2061 write_list (stream, "\t", destructors.first);
2062 if (frames)
2063 fprintf (stream, "\tdereg_frame,\n");
2064 fprintf (stream, "\t0\n};\n\n");
2066 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2067 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2069 #endif /* ! LD_INIT_SWITCH */
2071 static void
2072 write_c_file (FILE *stream, const char *name)
2074 #ifndef LD_INIT_SWITCH
2075 if (! shared_obj)
2076 write_c_file_glob (stream, name);
2077 else
2078 #endif
2079 write_c_file_stat (stream, name);
2082 #ifdef COLLECT_EXPORT_LIST
2083 static void
2084 write_aix_file (FILE *stream, struct id *list)
2086 for (; list; list = list->next)
2088 fputs (list->name, stream);
2089 putc ('\n', stream);
2092 #endif
2094 #ifdef OBJECT_FORMAT_NONE
2096 /* Generic version to scan the name list of the loaded program for
2097 the symbols g++ uses for static constructors and destructors.
2099 The constructor table begins at __CTOR_LIST__ and contains a count
2100 of the number of pointers (or -1 if the constructors are built in a
2101 separate section by the linker), followed by the pointers to the
2102 constructor functions, terminated with a null pointer. The
2103 destructor table has the same format, and begins at __DTOR_LIST__. */
2105 static void
2106 scan_prog_file (const char *prog_name, enum pass which_pass)
2108 void (*int_handler) (int);
2109 #ifdef SIGQUIT
2110 void (*quit_handler) (int);
2111 #endif
2112 char *real_nm_argv[4];
2113 const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2114 int argc = 0;
2115 struct pex_obj *pex;
2116 const char *errmsg;
2117 int err;
2118 char *p, buf[1024];
2119 FILE *inf;
2121 if (which_pass == PASS_SECOND)
2122 return;
2124 /* If we do not have an `nm', complain. */
2125 if (nm_file_name == 0)
2126 fatal ("cannot find 'nm'");
2128 nm_argv[argc++] = nm_file_name;
2129 if (NM_FLAGS[0] != '\0')
2130 nm_argv[argc++] = NM_FLAGS;
2132 nm_argv[argc++] = prog_name;
2133 nm_argv[argc++] = (char *) 0;
2135 /* Trace if needed. */
2136 if (vflag)
2138 const char **p_argv;
2139 const char *str;
2141 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2142 fprintf (stderr, " %s", str);
2144 fprintf (stderr, "\n");
2147 fflush (stdout);
2148 fflush (stderr);
2150 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2151 if (pex == NULL)
2152 fatal_perror ("pex_init failed");
2154 errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, NULL, &err);
2155 if (errmsg != NULL)
2157 if (err != 0)
2159 errno = err;
2160 fatal_perror (errmsg);
2162 else
2163 fatal (errmsg);
2166 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2167 #ifdef SIGQUIT
2168 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2169 #endif
2171 inf = pex_read_output (pex, 0);
2172 if (inf == NULL)
2173 fatal_perror ("can't open nm output");
2175 if (debug)
2176 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2178 /* Read each line of nm output. */
2179 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2181 int ch, ch2;
2182 char *name, *end;
2184 /* If it contains a constructor or destructor name, add the name
2185 to the appropriate list. */
2187 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2188 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2189 break;
2191 if (ch != '_')
2192 continue;
2194 name = p;
2195 /* Find the end of the symbol name.
2196 Do not include `|', because Encore nm can tack that on the end. */
2197 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2198 end++)
2199 continue;
2202 *end = '\0';
2203 switch (is_ctor_dtor (name))
2205 case SYM_CTOR:
2206 if (which_pass != PASS_LIB)
2207 add_to_list (&constructors, name);
2208 break;
2210 case SYM_DTOR:
2211 if (which_pass != PASS_LIB)
2212 add_to_list (&destructors, name);
2213 break;
2215 case SYM_INIT:
2216 if (which_pass != PASS_LIB)
2217 fatal ("init function found in object %s", prog_name);
2218 #ifndef LD_INIT_SWITCH
2219 add_to_list (&constructors, name);
2220 #endif
2221 break;
2223 case SYM_FINI:
2224 if (which_pass != PASS_LIB)
2225 fatal ("fini function found in object %s", prog_name);
2226 #ifndef LD_FINI_SWITCH
2227 add_to_list (&destructors, name);
2228 #endif
2229 break;
2231 case SYM_DWEH:
2232 if (which_pass != PASS_LIB)
2233 add_to_list (&frame_tables, name);
2234 break;
2236 default: /* not a constructor or destructor */
2237 continue;
2240 if (debug)
2241 fprintf (stderr, "\t%s\n", buf);
2244 if (debug)
2245 fprintf (stderr, "\n");
2247 do_wait (nm_file_name, pex);
2249 signal (SIGINT, int_handler);
2250 #ifdef SIGQUIT
2251 signal (SIGQUIT, quit_handler);
2252 #endif
2255 #ifdef LDD_SUFFIX
2257 /* Use the List Dynamic Dependencies program to find shared libraries that
2258 the output file depends upon and their initialization/finalization
2259 routines, if any. */
2261 static void
2262 scan_libraries (const char *prog_name)
2264 static struct head libraries; /* list of shared libraries found */
2265 struct id *list;
2266 void (*int_handler) (int);
2267 #ifdef SIGQUIT
2268 void (*quit_handler) (int);
2269 #endif
2270 char *real_ldd_argv[4];
2271 const char **ldd_argv = (const char **) real_ldd_argv;
2272 int argc = 0;
2273 struct pex_obj *pex;
2274 const char *errmsg;
2275 int err;
2276 char buf[1024];
2277 FILE *inf;
2279 /* If we do not have an `ldd', complain. */
2280 if (ldd_file_name == 0)
2282 error ("cannot find 'ldd'");
2283 return;
2286 ldd_argv[argc++] = ldd_file_name;
2287 ldd_argv[argc++] = prog_name;
2288 ldd_argv[argc++] = (char *) 0;
2290 /* Trace if needed. */
2291 if (vflag)
2293 const char **p_argv;
2294 const char *str;
2296 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2297 fprintf (stderr, " %s", str);
2299 fprintf (stderr, "\n");
2302 fflush (stdout);
2303 fflush (stderr);
2305 pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2306 if (pex == NULL)
2307 fatal_perror ("pex_init failed");
2309 errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2310 if (errmsg != NULL)
2312 if (err != 0)
2314 errno = err;
2315 fatal_perror (errmsg);
2317 else
2318 fatal (errmsg);
2321 int_handler = (void (*) (int)) signal (SIGINT, SIG_IGN);
2322 #ifdef SIGQUIT
2323 quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2324 #endif
2326 inf = pex_read_output (pex, 0);
2327 if (inf == NULL)
2328 fatal_perror ("can't open ldd output");
2330 if (debug)
2331 notice ("\nldd output with constructors/destructors.\n");
2333 /* Read each line of ldd output. */
2334 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2336 int ch2;
2337 char *name, *end, *p = buf;
2339 /* Extract names of libraries and add to list. */
2340 PARSE_LDD_OUTPUT (p);
2341 if (p == 0)
2342 continue;
2344 name = p;
2345 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2346 fatal ("dynamic dependency %s not found", buf);
2348 /* Find the end of the symbol name. */
2349 for (end = p;
2350 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2351 end++)
2352 continue;
2353 *end = '\0';
2355 if (access (name, R_OK) == 0)
2356 add_to_list (&libraries, name);
2357 else
2358 fatal ("unable to open dynamic dependency '%s'", buf);
2360 if (debug)
2361 fprintf (stderr, "\t%s\n", buf);
2363 if (debug)
2364 fprintf (stderr, "\n");
2366 do_wait (ldd_file_name, pex);
2368 signal (SIGINT, int_handler);
2369 #ifdef SIGQUIT
2370 signal (SIGQUIT, quit_handler);
2371 #endif
2373 /* Now iterate through the library list adding their symbols to
2374 the list. */
2375 for (list = libraries.first; list; list = list->next)
2376 scan_prog_file (list->name, PASS_LIB);
2379 #endif /* LDD_SUFFIX */
2381 #endif /* OBJECT_FORMAT_NONE */
2385 * COFF specific stuff.
2388 #ifdef OBJECT_FORMAT_COFF
2390 #if defined (EXTENDED_COFF)
2392 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2393 # define GCC_SYMENT SYMR
2394 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2395 # define GCC_SYMINC(X) (1)
2396 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2397 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2399 #else
2401 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2402 # define GCC_SYMENT SYMENT
2403 # if defined (C_WEAKEXT)
2404 # define GCC_OK_SYMBOL(X) \
2405 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2406 ((X).n_scnum > N_UNDEF) && \
2407 (aix64_flag \
2408 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2409 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2410 # define GCC_UNDEF_SYMBOL(X) \
2411 (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2412 ((X).n_scnum == N_UNDEF))
2413 # else
2414 # define GCC_OK_SYMBOL(X) \
2415 (((X).n_sclass == C_EXT) && \
2416 ((X).n_scnum > N_UNDEF) && \
2417 (aix64_flag \
2418 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2419 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2420 # define GCC_UNDEF_SYMBOL(X) \
2421 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2422 # endif
2423 # define GCC_SYMINC(X) ((X).n_numaux+1)
2424 # define GCC_SYMZERO(X) 0
2426 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2427 #if TARGET_AIX_VERSION >= 51
2428 # define GCC_CHECK_HDR(X) \
2429 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2430 || (HEADER (X).f_magic == 0767 && aix64_flag))
2431 #else
2432 # define GCC_CHECK_HDR(X) \
2433 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2434 || (HEADER (X).f_magic == 0757 && aix64_flag))
2435 #endif
2437 #endif
2439 #ifdef COLLECT_EXPORT_LIST
2440 /* Array of standard AIX libraries which should not
2441 be scanned for ctors/dtors. */
2442 static const char *const aix_std_libs[] = {
2443 "/unix",
2444 "/lib/libc.a",
2445 "/lib/libm.a",
2446 "/lib/libc_r.a",
2447 "/lib/libm_r.a",
2448 "/usr/lib/libc.a",
2449 "/usr/lib/libm.a",
2450 "/usr/lib/libc_r.a",
2451 "/usr/lib/libm_r.a",
2452 "/usr/lib/threads/libc.a",
2453 "/usr/ccs/lib/libc.a",
2454 "/usr/ccs/lib/libm.a",
2455 "/usr/ccs/lib/libc_r.a",
2456 "/usr/ccs/lib/libm_r.a",
2457 NULL
2460 /* This function checks the filename and returns 1
2461 if this name matches the location of a standard AIX library. */
2462 static int ignore_library (const char *);
2463 static int
2464 ignore_library (const char *name)
2466 const char *const *p;
2467 size_t length;
2469 if (target_system_root[0] != '\0')
2471 length = strlen (target_system_root);
2472 if (strncmp (name, target_system_root, length) != 0)
2473 return 0;
2474 name += length;
2476 for (p = &aix_std_libs[0]; *p != NULL; ++p)
2477 if (strcmp (name, *p) == 0)
2478 return 1;
2479 return 0;
2481 #endif /* COLLECT_EXPORT_LIST */
2483 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2484 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2485 #endif
2487 /* COFF version to scan the name list of the loaded program for
2488 the symbols g++ uses for static constructors and destructors.
2490 The constructor table begins at __CTOR_LIST__ and contains a count
2491 of the number of pointers (or -1 if the constructors are built in a
2492 separate section by the linker), followed by the pointers to the
2493 constructor functions, terminated with a null pointer. The
2494 destructor table has the same format, and begins at __DTOR_LIST__. */
2496 static void
2497 scan_prog_file (const char *prog_name, enum pass which_pass)
2499 LDFILE *ldptr = NULL;
2500 int sym_index, sym_count;
2501 int is_shared = 0;
2503 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2504 return;
2506 #ifdef COLLECT_EXPORT_LIST
2507 /* We do not need scanning for some standard C libraries. */
2508 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2509 return;
2511 /* On AIX we have a loop, because there is not much difference
2512 between an object and an archive. This trick allows us to
2513 eliminate scan_libraries() function. */
2516 #endif
2517 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2518 non-const char * filename parameter, even though it will not
2519 modify that string. So we must cast away const-ness here,
2520 using CONST_CAST to prevent complaints from -Wcast-qual. */
2521 if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
2523 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2524 fatal ("%s: not a COFF file", prog_name);
2526 if (GCC_CHECK_HDR (ldptr))
2528 sym_count = GCC_SYMBOLS (ldptr);
2529 sym_index = GCC_SYMZERO (ldptr);
2531 #ifdef COLLECT_EXPORT_LIST
2532 /* Is current archive member a shared object? */
2533 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2534 #endif
2536 while (sym_index < sym_count)
2538 GCC_SYMENT symbol;
2540 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2541 break;
2542 sym_index += GCC_SYMINC (symbol);
2544 if (GCC_OK_SYMBOL (symbol))
2546 char *name;
2548 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2549 continue; /* Should never happen. */
2551 #ifdef XCOFF_DEBUGGING_INFO
2552 /* All AIX function names have a duplicate entry
2553 beginning with a dot. */
2554 if (*name == '.')
2555 ++name;
2556 #endif
2558 switch (is_ctor_dtor (name))
2560 case SYM_CTOR:
2561 if (! is_shared)
2562 add_to_list (&constructors, name);
2563 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2564 if (which_pass == PASS_OBJ)
2565 add_to_list (&exports, name);
2566 #endif
2567 break;
2569 case SYM_DTOR:
2570 if (! is_shared)
2571 add_to_list (&destructors, name);
2572 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2573 if (which_pass == PASS_OBJ)
2574 add_to_list (&exports, name);
2575 #endif
2576 break;
2578 #ifdef COLLECT_EXPORT_LIST
2579 case SYM_INIT:
2580 #ifndef LD_INIT_SWITCH
2581 if (is_shared)
2582 add_to_list (&constructors, name);
2583 #endif
2584 break;
2586 case SYM_FINI:
2587 #ifndef LD_INIT_SWITCH
2588 if (is_shared)
2589 add_to_list (&destructors, name);
2590 #endif
2591 break;
2592 #endif
2594 case SYM_DWEH:
2595 if (! is_shared)
2596 add_to_list (&frame_tables, name);
2597 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2598 if (which_pass == PASS_OBJ)
2599 add_to_list (&exports, name);
2600 #endif
2601 break;
2603 default: /* not a constructor or destructor */
2604 #ifdef COLLECT_EXPORT_LIST
2605 /* Explicitly export all global symbols when
2606 building a shared object on AIX, but do not
2607 re-export symbols from another shared object
2608 and do not export symbols if the user
2609 provides an explicit export list. */
2610 if (shared_obj && !is_shared
2611 && which_pass == PASS_OBJ && !export_flag)
2612 add_to_list (&exports, name);
2613 #endif
2614 continue;
2617 if (debug)
2618 #if !defined(EXTENDED_COFF)
2619 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2620 symbol.n_scnum, symbol.n_sclass,
2621 (symbol.n_type ? "0" : ""), symbol.n_type,
2622 name);
2623 #else
2624 fprintf (stderr,
2625 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2626 symbol.iss, (long) symbol.value, symbol.index, name);
2627 #endif
2631 #ifdef COLLECT_EXPORT_LIST
2632 else
2634 /* If archive contains both 32-bit and 64-bit objects,
2635 we want to skip objects in other mode so mismatch normal. */
2636 if (debug)
2637 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2638 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2640 #endif
2642 else
2644 fatal ("%s: cannot open as COFF file", prog_name);
2646 #ifdef COLLECT_EXPORT_LIST
2647 /* On AIX loop continues while there are more members in archive. */
2649 while (ldclose (ldptr) == FAILURE);
2650 #else
2651 /* Otherwise we simply close ldptr. */
2652 (void) ldclose(ldptr);
2653 #endif
2655 #endif /* OBJECT_FORMAT_COFF */
2657 #ifdef COLLECT_EXPORT_LIST
2658 /* Given a library name without "lib" prefix, this function
2659 returns a full library name including a path. */
2660 static char *
2661 resolve_lib_name (const char *name)
2663 char *lib_buf;
2664 int i, j, l = 0;
2665 /* Library extensions for AIX dynamic linking. */
2666 const char * const libexts[2] = {"a", "so"};
2668 for (i = 0; libpaths[i]; i++)
2669 if (libpaths[i]->max_len > l)
2670 l = libpaths[i]->max_len;
2672 lib_buf = XNEWVEC (char, l + strlen(name) + 10);
2674 for (i = 0; libpaths[i]; i++)
2676 struct prefix_list *list = libpaths[i]->plist;
2677 for (; list; list = list->next)
2679 /* The following lines are needed because path_prefix list
2680 may contain directories both with trailing '/' and
2681 without it. */
2682 const char *p = "";
2683 if (list->prefix[strlen(list->prefix)-1] != '/')
2684 p = "/";
2685 for (j = 0; j < 2; j++)
2687 sprintf (lib_buf, "%s%slib%s.%s",
2688 list->prefix, p, name,
2689 libexts[(j + aixrtl_flag) % 2]);
2690 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2691 if (file_exists (lib_buf))
2693 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2694 return (lib_buf);
2699 if (debug)
2700 fprintf (stderr, "not found\n");
2701 else
2702 fatal ("library lib%s not found", name);
2703 return (NULL);
2705 #endif /* COLLECT_EXPORT_LIST */