OSDN Git Service

2009-08-20 Thomas Koenig <tkoenig@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / collect2.c
1 /* Collect static initialization info into data structures that can be
2    traversed by C++ initialization and finalization routines.
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
5    Free Software Foundation, Inc.
6    Contributed by Chris Smith (csmith@convex.com).
7    Heavily modified by Michael Meissner (meissner@cygnus.com),
8    Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
9
10 This file is part of GCC.
11
12 GCC is free software; you can redistribute it and/or modify it under
13 the terms of the GNU General Public License as published by the Free
14 Software Foundation; either version 3, or (at your option) any later
15 version.
16
17 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
18 WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20 for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING3.  If not see
24 <http://www.gnu.org/licenses/>.  */
25
26
27 /* Build tables of static constructors and destructors and run ld.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include <signal.h>
34 #if ! defined( SIGCHLD ) && defined( SIGCLD )
35 #  define SIGCHLD SIGCLD
36 #endif
37
38 #ifndef LIBRARY_PATH_ENV
39 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
40 #endif
41
42 #define COLLECT
43
44 #include "collect2.h"
45 #include "collect2-aix.h"
46 #include "demangle.h"
47 #include "obstack.h"
48 #include "intl.h"
49 #include "version.h"
50 \f
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.  */
56
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
66
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.  */
71
72 #if !defined (OBJECT_FORMAT_COFF)
73 #define OBJECT_FORMAT_NONE
74 #endif
75
76 #ifdef OBJECT_FORMAT_COFF
77
78 #ifndef CROSS_DIRECTORY_STRUCTURE
79 #include <a.out.h>
80 #include <ar.h>
81
82 #ifdef UMAX
83 #include <sgs.h>
84 #endif
85
86 /* Many versions of ldfcn.h define these.  */
87 #ifdef FREAD
88 #undef FREAD
89 #undef FWRITE
90 #endif
91
92 #include <ldfcn.h>
93 #endif
94
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.  */
99
100 #ifndef MY_ISCOFF
101 #define MY_ISCOFF(X) ISCOFF (X)
102 #endif
103
104 #endif /* OBJECT_FORMAT_COFF */
105
106 #ifdef OBJECT_FORMAT_NONE
107
108 /* Default flags to pass to nm.  */
109 #ifndef NM_FLAGS
110 #define NM_FLAGS "-n"
111 #endif
112
113 #endif /* OBJECT_FORMAT_NONE */
114
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
121
122 /* This must match tree.h.  */
123 #define DEFAULT_INIT_PRIORITY 65535
124
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
133
134 #ifdef LDD_SUFFIX
135 #define SCAN_LIBRARIES
136 #endif
137
138 #ifndef SHLIB_SUFFIX
139 #define SHLIB_SUFFIX ".so"
140 #endif
141
142 #ifdef USE_COLLECT2
143 int do_collecting = 1;
144 #else
145 int do_collecting = 0;
146 #endif
147
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;
151 \f
152 /* Linked lists of constructor and destructor names.  */
153
154 struct id
155 {
156   struct id *next;
157   int sequence;
158   char name[1];
159 };
160
161 struct head
162 {
163   struct id *first;
164   struct id *last;
165   int number;
166 };
167
168 /* Enumeration giving which pass this is for scanning the program file.  */
169
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 */
175 };
176
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
186
187 int debug;                              /* true if -debug */
188
189 static int shared_obj;                  /* true if -shared */
190
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 */
206
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 */
213
214 static bool at_file_supplied;           /* Whether to use @file arguments */
215 static char *response_file;             /* Name of any current response file */
216
217 struct obstack temporary_obstack;
218 char * temporary_firstobj;
219
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
227
228 /* Structure to hold all the directories in which to search for files to
229    execute.  */
230
231 struct prefix_list
232 {
233   const char *prefix;         /* String to prepend to the path.  */
234   struct prefix_list *next;   /* Next in linked list.  */
235 };
236
237 struct path_prefix
238 {
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) */
242 };
243
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
252
253 /* Special kinds of symbols that a name may denote.  */
254
255 typedef enum {
256   SYM_REGULAR = 0,  /* nothing special  */
257
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;
264
265 static symkind is_ctor_dtor (const char *);
266
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 **);
306 \f
307 /* Delete tempfiles and exit function.  */
308
309 void
310 collect_exit (int status)
311 {
312   if (c_file != 0 && c_file[0])
313     maybe_unlink (c_file);
314
315   if (o_file != 0 && o_file[0])
316     maybe_unlink (o_file);
317
318 #ifdef COLLECT_EXPORT_LIST
319   if (export_file != 0 && export_file[0])
320     maybe_unlink (export_file);
321 #endif
322
323   if (ldout != 0 && ldout[0])
324     {
325       dump_file (ldout, stdout);
326       maybe_unlink (ldout);
327     }
328
329   if (lderrout != 0 && lderrout[0])
330     {
331       dump_file (lderrout, stderr);
332       maybe_unlink (lderrout);
333     }
334
335   if (status != 0 && output_file != 0 && output_file[0])
336     maybe_unlink (output_file);
337
338   if (response_file)
339     maybe_unlink (response_file);
340
341   exit (status);
342 }
343
344 \f
345 /* Notify user of a non-error.  */
346 void
347 notice (const char *cmsgid, ...)
348 {
349   va_list ap;
350
351   va_start (ap, cmsgid);
352   vfprintf (stderr, _(cmsgid), ap);
353   va_end (ap);
354 }
355
356 /* Die when sys call fails.  */
357
358 void
359 fatal_perror (const char * cmsgid, ...)
360 {
361   int e = errno;
362   va_list ap;
363
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);
369
370   collect_exit (FATAL_EXIT_CODE);
371 }
372
373 /* Just die.  */
374
375 void
376 fatal (const char * cmsgid, ...)
377 {
378   va_list ap;
379
380   va_start (ap, cmsgid);
381   fprintf (stderr, "collect2: ");
382   vfprintf (stderr, _(cmsgid), ap);
383   fprintf (stderr, "\n");
384   va_end (ap);
385
386   collect_exit (FATAL_EXIT_CODE);
387 }
388
389 /* Write error message.  */
390
391 void
392 error (const char * gmsgid, ...)
393 {
394   va_list ap;
395
396   va_start (ap, gmsgid);
397   fprintf (stderr, "collect2: ");
398   vfprintf (stderr, _(gmsgid), ap);
399   fprintf (stderr, "\n");
400   va_end(ap);
401 }
402
403 /* In case obstack is linked in, and abort is defined to fancy_abort,
404    provide a default entry.  */
405
406 void
407 fancy_abort (const char *file, int line, const char *func)
408 {
409   fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
410 }
411 \f
412 static void
413 handler (int signo)
414 {
415   if (c_file != 0 && c_file[0])
416     maybe_unlink (c_file);
417
418   if (o_file != 0 && o_file[0])
419     maybe_unlink (o_file);
420
421   if (ldout != 0 && ldout[0])
422     maybe_unlink (ldout);
423
424   if (lderrout != 0 && lderrout[0])
425     maybe_unlink (lderrout);
426
427 #ifdef COLLECT_EXPORT_LIST
428   if (export_file != 0 && export_file[0])
429     maybe_unlink (export_file);
430 #endif
431
432   if (response_file)
433     maybe_unlink (response_file);
434
435   signal (signo, SIG_DFL);
436   raise (signo);
437 }
438
439 \f
440 int
441 file_exists (const char *name)
442 {
443   return access (name, R_OK) == 0;
444 }
445
446 /* Parse a reasonable subset of shell quoting syntax.  */
447
448 static char *
449 extract_string (const char **pp)
450 {
451   const char *p = *pp;
452   int backquote = 0;
453   int inside = 0;
454
455   for (;;)
456     {
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);
471     }
472
473   obstack_1grow (&temporary_obstack, '\0');
474   *pp = p;
475   return XOBFINISH (&temporary_obstack, char *);
476 }
477 \f
478 void
479 dump_file (const char *name, FILE *to)
480 {
481   FILE *stream = fopen (name, "r");
482
483   if (stream == 0)
484     return;
485   while (1)
486     {
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)
492         {
493           const char *word, *p;
494           char *result;
495           obstack_1grow (&temporary_obstack, '\0');
496           word = XOBFINISH (&temporary_obstack, const char *);
497
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);
503
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
512
513           if (result)
514             {
515               int diff;
516               fputs (result, to);
517
518               diff = strlen (word) - strlen (result);
519               while (diff > 0 && c == ' ')
520                 --diff, putc (' ', to);
521               if (diff < 0 && c == ' ')
522                 {
523                   while (diff < 0 && c == ' ')
524                     ++diff, c = getc (stream);
525                   if (!ISSPACE (c))
526                     {
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);
531                     }
532                 }
533
534               free (result);
535             }
536           else
537             fputs (word, to);
538
539           fflush (to);
540           obstack_free (&temporary_obstack, temporary_firstobj);
541         }
542       if (c == EOF)
543         break;
544       putc (c, to);
545     }
546   fclose (stream);
547 }
548 \f
549 /* Return the kind of symbol denoted by name S.  */
550
551 static symkind
552 is_ctor_dtor (const char *s)
553 {
554   struct names { const char *const name; const int len; symkind ret;
555     const int two_underscores; };
556
557   const struct names *p;
558   int ch;
559   const char *orig_s = s;
560
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 }
577   };
578
579   while ((ch = *s) == '_')
580     ++s;
581
582   if (s == orig_s)
583     return SYM_REGULAR;
584
585   for (p = &special[0]; p->len > 0; p++)
586     {
587       if (ch == p->name[0]
588           && (!p->two_underscores || ((s - orig_s) >= 2))
589           && strncmp(s, p->name, p->len) == 0)
590         {
591           return p->ret;
592         }
593     }
594   return SYM_REGULAR;
595 }
596 \f
597 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
598    and one from the PATH variable.  */
599
600 static struct path_prefix cpath, path;
601
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.  */
605
606 static const char *const target_machine = TARGET_MACHINE;
607 #endif
608
609 /* Search for NAME using prefix list PPREFIX.  We only look for executable
610    files.
611
612    Return 0 if not found, otherwise return its name, allocated with malloc.  */
613
614 static char *
615 find_a_file (struct path_prefix *pprefix, const char *name)
616 {
617   char *temp;
618   struct prefix_list *pl;
619   int len = pprefix->max_len + strlen (name) + 1;
620
621   if (debug)
622     fprintf (stderr, "Looking for '%s'\n", name);
623
624 #ifdef HOST_EXECUTABLE_SUFFIX
625   len += strlen (HOST_EXECUTABLE_SUFFIX);
626 #endif
627
628   temp = XNEWVEC (char, len);
629
630   /* Determine the filename to execute (special case for absolute paths).  */
631
632   if (IS_ABSOLUTE_PATH (name))
633     {
634       if (access (name, X_OK) == 0)
635         {
636           strcpy (temp, name);
637
638           if (debug)
639             fprintf (stderr, "  - found: absolute path\n");
640
641           return temp;
642         }
643
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);
649
650         if (access (temp, X_OK) == 0)
651           return temp;
652 #endif
653
654       if (debug)
655         fprintf (stderr, "  - failed to locate using absolute path\n");
656     }
657   else
658     for (pl = pprefix->plist; pl; pl = pl->next)
659       {
660         struct stat st;
661
662         strcpy (temp, pl->prefix);
663         strcat (temp, name);
664
665         if (stat (temp, &st) >= 0
666             && ! S_ISDIR (st.st_mode)
667             && access (temp, X_OK) == 0)
668           return temp;
669
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);
674
675         if (stat (temp, &st) >= 0
676             && ! S_ISDIR (st.st_mode)
677             && access (temp, X_OK) == 0)
678           return temp;
679 #endif
680       }
681
682   if (debug && pprefix->plist == NULL)
683     fprintf (stderr, "  - failed: no entries in prefix list\n");
684
685   free (temp);
686   return 0;
687 }
688
689 /* Add an entry for PREFIX to prefix list PPREFIX.  */
690
691 static void
692 add_prefix (struct path_prefix *pprefix, const char *prefix)
693 {
694   struct prefix_list *pl, **prev;
695   int len;
696
697   if (pprefix->plist)
698     {
699       for (pl = pprefix->plist; pl->next; pl = pl->next)
700         ;
701       prev = &pl->next;
702     }
703   else
704     prev = &pprefix->plist;
705
706   /* Keep track of the longest prefix.  */
707
708   len = strlen (prefix);
709   if (len > pprefix->max_len)
710     pprefix->max_len = len;
711
712   pl = XNEW (struct prefix_list);
713   pl->prefix = xstrdup (prefix);
714
715   if (*prev)
716     pl->next = *prev;
717   else
718     pl->next = (struct prefix_list *) 0;
719   *prev = pl;
720 }
721 \f
722 /* Take the value of the environment variable ENV, break it into a path, and
723    add of the entries to PPREFIX.  */
724
725 static void
726 prefix_from_env (const char *env, struct path_prefix *pprefix)
727 {
728   const char *p;
729   GET_ENVIRONMENT (p, env);
730
731   if (p)
732     prefix_from_string (p, pprefix);
733 }
734
735 static void
736 prefix_from_string (const char *p, struct path_prefix *pprefix)
737 {
738   const char *startp, *endp;
739   char *nstore = XNEWVEC (char, strlen (p) + 3);
740
741   if (debug)
742     fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
743
744   startp = endp = p;
745   while (1)
746     {
747       if (*endp == PATH_SEPARATOR || *endp == 0)
748         {
749           strncpy (nstore, startp, endp-startp);
750           if (endp == startp)
751             {
752               strcpy (nstore, "./");
753             }
754           else if (! IS_DIR_SEPARATOR (endp[-1]))
755             {
756               nstore[endp-startp] = DIR_SEPARATOR;
757               nstore[endp-startp+1] = 0;
758             }
759           else
760             nstore[endp-startp] = 0;
761
762           if (debug)
763             fprintf (stderr, "  - add prefix: %s\n", nstore);
764
765           add_prefix (pprefix, nstore);
766           if (*endp == 0)
767             break;
768           endp = startp = endp + 1;
769         }
770       else
771         endp++;
772     }
773   free (nstore);
774 }
775 \f
776 /* Main program.  */
777
778 int
779 main (int argc, char **argv)
780 {
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";
791
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.  */
797
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 */
822
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;
841
842   old_argv = argv;
843   expandargv (&argc, &argv);
844   if (argv != old_argv)
845     at_file_supplied = 1;
846
847   num_c_args = argc + 9;
848
849   no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
850
851   /* Suppress demangling by the real linker, which may be broken.  */
852   putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
853
854 #if defined (COLLECT2_HOST_INITIALIZATION)
855   /* Perform system dependent initialization, if necessary.  */
856   COLLECT2_HOST_INITIALIZATION;
857 #endif
858
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
864
865   /* Unlock the stdio streams.  */
866   unlock_std_streams ();
867
868   gcc_init_libintl ();
869
870   /* Do not invoke xcalloc before this point, since locale needs to be
871      set first, in case a diagnostic is issued.  */
872
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);
879
880 #ifdef DEBUG
881   debug = 1;
882 #endif
883
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.  */
887   {
888     int i;
889
890     for (i = 1; argv[i] != NULL; i ++)
891       {
892         if (! strcmp (argv[i], "-debug"))
893           debug = 1;
894       }
895     vflag = debug;
896   }
897
898 #ifndef DEFAULT_A_OUT_NAME
899   output_file = "a.out";
900 #else
901   output_file = DEFAULT_A_OUT_NAME;
902 #endif
903
904   obstack_begin (&temporary_obstack, 0);
905   temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
906
907 #ifndef HAVE_LD_DEMANGLE
908   current_demangling_style = auto_demangling;
909 #endif
910   p = getenv ("COLLECT_GCC_OPTIONS");
911   while (p && *p)
912     {
913       const char *q = extract_string (&p);
914       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
915         num_c_args++;
916     }
917   obstack_free (&temporary_obstack, temporary_firstobj);
918
919   /* -fno-profile-arcs -fno-test-coverage -fno-branch-probabilities
920      -fno-exceptions -w */
921   num_c_args += 5;
922
923   c_argv = XCNEWVEC (char *, num_c_args);
924   c_ptr = CONST_CAST2 (const char **, char **, c_argv);
925
926   if (argc < 2)
927     fatal ("no arguments");
928
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
949
950   /* Extract COMPILER_PATH and PATH into our prefix list.  */
951   prefix_from_env ("COMPILER_PATH", &cpath);
952   prefix_from_env ("PATH", &path);
953
954   /* Try to discover a valid linker/nm/strip to use.  */
955
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);
980
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);
992
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
998
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);
1010
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)
1014     {
1015 #ifdef CROSS_DIRECTORY_STRUCTURE
1016       c_file_name = concat (target_machine, "-gcc", NULL);
1017 #else
1018       c_file_name = "gcc";
1019 #endif
1020     }
1021
1022   p = find_a_file (&cpath, c_file_name);
1023
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);
1028
1029   if (p)
1030     c_file_name = p;
1031
1032   *ld1++ = *ld2++ = ld_file_name;
1033
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;
1048
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
1057
1058   /* Get any options that the upper GCC wants to pass to the sub-GCC.
1059
1060      AIX support needs to know if -shared has been specified before
1061      parsing commandline arguments.  */
1062
1063   p = getenv ("COLLECT_GCC_OPTIONS");
1064   while (p && *p)
1065     {
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')
1074         {
1075           *c_ptr++ = xstrdup (q);
1076           if (q[2] == 0)
1077             {
1078               q = extract_string (&p);
1079               *c_ptr++ = xstrdup (q);
1080             }
1081         }
1082     }
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";
1089
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!!!  */
1096
1097   /* Parse arguments.  Remember output file spec, pass the rest to ld.  */
1098   /* After the first file, put in the c++ rt0.  */
1099
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)
1108     {
1109       *ld1++ = *ld2++ = arg;
1110
1111       if (arg[0] == '-')
1112         {
1113           switch (arg[1])
1114             {
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
1127
1128             case 'd':
1129               if (!strcmp (arg, "-debug"))
1130                 {
1131                   /* Already parsed.  */
1132                   ld1--;
1133                   ld2--;
1134                 }
1135               if (!strcmp (arg, "-dynamic-linker") && argv[1])
1136                 {
1137                   ++argv;
1138                   *ld1++ = *ld2++ = *argv;
1139                 }
1140               break;
1141
1142             case 'l':
1143               if (first_file)
1144                 {
1145                   /* place o_file BEFORE this argument! */
1146                   first_file = 0;
1147                   ld2--;
1148                   *ld2++ = o_file;
1149                   *ld2++ = arg;
1150                 }
1151 #ifdef COLLECT_EXPORT_LIST
1152               {
1153                 /* Resolving full library name.  */
1154                 const char *s = resolve_lib_name (arg+2);
1155
1156                 /* Saving a full library name.  */
1157                 add_to_list (&libs, s);
1158               }
1159 #endif
1160               break;
1161
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,
1171                               CONST_CAST2 (const char **, char **, ld1_argv),
1172                               ld1 - 1))
1173                 --ld1;
1174               break;
1175 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1176 #endif
1177
1178             case 'o':
1179               if (arg[2] == '\0')
1180                 output_file = *ld1++ = *ld2++ = *++argv;
1181               else if (1
1182 #ifdef SWITCHES_NEED_SPACES
1183                        && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1184 #endif
1185                        )
1186
1187                 output_file = &arg[2];
1188               break;
1189
1190             case 'r':
1191               if (arg[2] == '\0')
1192                 rflag = 1;
1193               break;
1194
1195             case 's':
1196               if (arg[2] == '\0' && do_collecting)
1197                 {
1198                   /* We must strip after the nm run, otherwise C++ linking
1199                      will not work.  Thus we strip in the second ld run, or
1200                      else with strip if there is no second ld run.  */
1201                   strip_flag = 1;
1202                   ld1--;
1203                 }
1204               break;
1205
1206             case 'v':
1207               if (arg[2] == '\0')
1208                 vflag = 1;
1209               break;
1210
1211             case '-':
1212               if (strcmp (arg, "--no-demangle") == 0)
1213                 {
1214                   demangle_flag = arg;
1215                   no_demangle = 1;
1216                   ld1--;
1217                   ld2--;
1218                 }
1219               else if (strncmp (arg, "--demangle", 10) == 0)
1220                 {
1221                   demangle_flag = arg;
1222                   no_demangle = 0;
1223 #ifndef HAVE_LD_DEMANGLE
1224                   if (arg[10] == '=')
1225                     {
1226                       enum demangling_styles style
1227                         = cplus_demangle_name_to_style (arg+11);
1228                       if (style == unknown_demangling)
1229                         error ("unknown demangling style '%s'", arg+11);
1230                       else
1231                         current_demangling_style = style;
1232                     }
1233 #endif
1234                   ld1--;
1235                   ld2--;
1236                 }
1237               else if (strncmp (arg, "--sysroot=", 10) == 0)
1238                 target_system_root = arg + 10;
1239               break;
1240             }
1241         }
1242       else if ((p = strrchr (arg, '.')) != (char *) 0
1243                && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1244                    || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1245                    || strcmp (p, ".obj") == 0))
1246         {
1247           if (first_file)
1248             {
1249               first_file = 0;
1250               if (p[1] == 'o')
1251                 *ld2++ = o_file;
1252               else
1253                 {
1254                   /* place o_file BEFORE this argument! */
1255                   ld2--;
1256                   *ld2++ = o_file;
1257                   *ld2++ = arg;
1258                 }
1259             }
1260           if (p[1] == 'o' || p[1] == 'l')
1261             *object++ = arg;
1262 #ifdef COLLECT_EXPORT_LIST
1263           /* libraries can be specified directly, i.e. without -l flag.  */
1264           else
1265             {
1266               /* Saving a full library name.  */
1267               add_to_list (&libs, arg);
1268             }
1269 #endif
1270         }
1271     }
1272
1273 #ifdef COLLECT_EXPORT_LIST
1274   /* This is added only for debugging purposes.  */
1275   if (debug)
1276     {
1277       fprintf (stderr, "List of libraries:\n");
1278       dump_list (stderr, "\t", libs.first);
1279     }
1280
1281   /* The AIX linker will discard static constructors in object files if
1282      nothing else in the file is referenced, so look at them first.  */
1283   {
1284       const char **export_object_lst 
1285         = CONST_CAST2 (const char **, char **, object_lst);
1286
1287       while (export_object_lst < object)
1288         scan_prog_file (*export_object_lst++, PASS_OBJ);
1289   }
1290   {
1291     struct id *list = libs.first;
1292
1293     for (; list; list = list->next)
1294       scan_prog_file (list->name, PASS_FIRST);
1295   }
1296
1297   if (exports.first)
1298     {
1299       char *buf = concat ("-bE:", export_file, NULL);
1300
1301       *ld1++ = buf;
1302       *ld2++ = buf;
1303
1304       exportf = fopen (export_file, "w");
1305       if (exportf == (FILE *) 0)
1306         fatal_perror ("fopen %s", export_file);
1307       write_aix_file (exportf, exports.first);
1308       if (fclose (exportf))
1309         fatal_perror ("fclose %s", export_file);
1310     }
1311 #endif
1312
1313   *c_ptr++ = c_file;
1314   *c_ptr = *ld1 = *object = (char *) 0;
1315
1316   if (vflag)
1317     {
1318       notice ("collect2 version %s", version_string);
1319 #ifdef TARGET_VERSION
1320       TARGET_VERSION;
1321 #endif
1322       fprintf (stderr, "\n");
1323     }
1324
1325   if (debug)
1326     {
1327       const char *ptr;
1328       fprintf (stderr, "ld_file_name        = %s\n",
1329                (ld_file_name ? ld_file_name : "not found"));
1330       fprintf (stderr, "c_file_name         = %s\n",
1331                (c_file_name ? c_file_name : "not found"));
1332       fprintf (stderr, "nm_file_name        = %s\n",
1333                (nm_file_name ? nm_file_name : "not found"));
1334 #ifdef LDD_SUFFIX
1335       fprintf (stderr, "ldd_file_name       = %s\n",
1336                (ldd_file_name ? ldd_file_name : "not found"));
1337 #endif
1338       fprintf (stderr, "strip_file_name     = %s\n",
1339                (strip_file_name ? strip_file_name : "not found"));
1340       fprintf (stderr, "c_file              = %s\n",
1341                (c_file ? c_file : "not found"));
1342       fprintf (stderr, "o_file              = %s\n",
1343                (o_file ? o_file : "not found"));
1344
1345       ptr = getenv ("COLLECT_GCC_OPTIONS");
1346       if (ptr)
1347         fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1348
1349       ptr = getenv ("COLLECT_GCC");
1350       if (ptr)
1351         fprintf (stderr, "COLLECT_GCC         = %s\n", ptr);
1352
1353       ptr = getenv ("COMPILER_PATH");
1354       if (ptr)
1355         fprintf (stderr, "COMPILER_PATH       = %s\n", ptr);
1356
1357       ptr = getenv (LIBRARY_PATH_ENV);
1358       if (ptr)
1359         fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1360
1361       fprintf (stderr, "\n");
1362     }
1363
1364   /* Load the program, searching all libraries and attempting to provide
1365      undefined symbols from repository information.  */
1366
1367   /* On AIX we do this later.  */
1368 #ifndef COLLECT_EXPORT_LIST
1369   do_tlink (ld1_argv, object_lst);
1370 #endif
1371
1372   /* If -r or they will be run via some other method, do not build the
1373      constructor or destructor list, just return now.  */
1374   if (rflag
1375 #ifndef COLLECT_EXPORT_LIST
1376       || ! do_collecting
1377 #endif
1378       )
1379     {
1380 #ifdef COLLECT_EXPORT_LIST
1381       /* Do the link we avoided above if we are exiting.  */
1382       do_tlink (ld1_argv, object_lst);
1383
1384       /* But make sure we delete the export file we may have created.  */
1385       if (export_file != 0 && export_file[0])
1386         maybe_unlink (export_file);
1387 #endif
1388       maybe_unlink (c_file);
1389       maybe_unlink (o_file);
1390       return 0;
1391     }
1392
1393   /* Examine the namelist with nm and search it for static constructors
1394      and destructors to call.
1395      Write the constructor and destructor tables to a .s file and reload.  */
1396
1397   /* On AIX we already scanned for global constructors/destructors.  */
1398 #ifndef COLLECT_EXPORT_LIST
1399   scan_prog_file (output_file, PASS_FIRST);
1400 #endif
1401
1402 #ifdef SCAN_LIBRARIES
1403   scan_libraries (output_file);
1404 #endif
1405
1406   if (debug)
1407     {
1408       notice ("%d constructor(s) found\n", constructors.number);
1409       notice ("%d destructor(s)  found\n", destructors.number);
1410       notice ("%d frame table(s) found\n", frame_tables.number);
1411     }
1412
1413   if (constructors.number == 0 && destructors.number == 0
1414       && frame_tables.number == 0
1415 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1416       /* If we will be running these functions ourselves, we want to emit
1417          stubs into the shared library so that we do not have to relink
1418          dependent programs when we add static objects.  */
1419       && ! shared_obj
1420 #endif
1421       )
1422     {
1423 #ifdef COLLECT_EXPORT_LIST
1424       /* Do tlink without additional code generation.  */
1425       do_tlink (ld1_argv, object_lst);
1426 #endif
1427       /* Strip now if it was requested on the command line.  */
1428       if (strip_flag)
1429         {
1430           char **real_strip_argv = XCNEWVEC (char *, 3);
1431           const char ** strip_argv = CONST_CAST2 (const char **, char **,
1432                                                   real_strip_argv);
1433
1434           strip_argv[0] = strip_file_name;
1435           strip_argv[1] = output_file;
1436           strip_argv[2] = (char *) 0;
1437           fork_execute ("strip", real_strip_argv);
1438         }
1439
1440 #ifdef COLLECT_EXPORT_LIST
1441       maybe_unlink (export_file);
1442 #endif
1443       maybe_unlink (c_file);
1444       maybe_unlink (o_file);
1445       return 0;
1446     }
1447
1448   /* Sort ctor and dtor lists by priority.  */
1449   sort_ids (&constructors);
1450   sort_ids (&destructors);
1451
1452   maybe_unlink(output_file);
1453   outf = fopen (c_file, "w");
1454   if (outf == (FILE *) 0)
1455     fatal_perror ("fopen %s", c_file);
1456
1457   write_c_file (outf, c_file);
1458
1459   if (fclose (outf))
1460     fatal_perror ("fclose %s", c_file);
1461
1462   /* Tell the linker that we have initializer and finalizer functions.  */
1463 #ifdef LD_INIT_SWITCH
1464 #ifdef COLLECT_EXPORT_LIST
1465   *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1466 #else
1467   *ld2++ = LD_INIT_SWITCH;
1468   *ld2++ = initname;
1469   *ld2++ = LD_FINI_SWITCH;
1470   *ld2++ = fininame;
1471 #endif
1472 #endif
1473
1474 #ifdef COLLECT_EXPORT_LIST
1475   if (shared_obj)
1476     {
1477       /* If we did not add export flag to link arguments before, add it to
1478          second link phase now.  No new exports should have been added.  */
1479       if (! exports.first)
1480         *ld2++ = concat ("-bE:", export_file, NULL);
1481
1482 #ifndef LD_INIT_SWITCH
1483       add_to_list (&exports, initname);
1484       add_to_list (&exports, fininame);
1485       add_to_list (&exports, "_GLOBAL__DI");
1486       add_to_list (&exports, "_GLOBAL__DD");
1487 #endif
1488       exportf = fopen (export_file, "w");
1489       if (exportf == (FILE *) 0)
1490         fatal_perror ("fopen %s", export_file);
1491       write_aix_file (exportf, exports.first);
1492       if (fclose (exportf))
1493         fatal_perror ("fclose %s", export_file);
1494     }
1495 #endif
1496
1497   /* End of arguments to second link phase.  */
1498   *ld2 = (char*) 0;
1499
1500   if (debug)
1501     {
1502       fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1503                output_file, c_file);
1504       write_c_file (stderr, "stderr");
1505       fprintf (stderr, "========== end of c_file\n\n");
1506 #ifdef COLLECT_EXPORT_LIST
1507       fprintf (stderr, "\n========== export_file = %s\n", export_file);
1508       write_aix_file (stderr, exports.first);
1509       fprintf (stderr, "========== end of export_file\n\n");
1510 #endif
1511     }
1512
1513   /* Assemble the constructor and destructor tables.
1514      Link the tables in with the rest of the program.  */
1515
1516   fork_execute ("gcc",  c_argv);
1517 #ifdef COLLECT_EXPORT_LIST
1518   /* On AIX we must call tlink because of possible templates resolution.  */
1519   do_tlink (ld2_argv, object_lst);
1520 #else
1521   /* Otherwise, simply call ld because tlink is already done.  */
1522   fork_execute ("ld", ld2_argv);
1523
1524   /* Let scan_prog_file do any final mods (OSF/rose needs this for
1525      constructors/destructors in shared libraries.  */
1526   scan_prog_file (output_file, PASS_SECOND);
1527 #endif
1528
1529   maybe_unlink (c_file);
1530   maybe_unlink (o_file);
1531
1532 #ifdef COLLECT_EXPORT_LIST
1533   maybe_unlink (export_file);
1534 #endif
1535
1536   return 0;
1537 }
1538
1539 \f
1540 /* Wait for a process to finish, and exit if a nonzero status is found.  */
1541
1542 int
1543 collect_wait (const char *prog, struct pex_obj *pex)
1544 {
1545   int status;
1546
1547   if (!pex_get_status (pex, 1, &status))
1548     fatal_perror ("can't get program status");
1549   pex_free (pex);
1550
1551   if (status)
1552     {
1553       if (WIFSIGNALED (status))
1554         {
1555           int sig = WTERMSIG (status);
1556           error ("%s terminated with signal %d [%s]%s",
1557                  prog, sig, strsignal(sig),
1558                  WCOREDUMP(status) ? ", core dumped" : "");
1559           collect_exit (FATAL_EXIT_CODE);
1560         }
1561
1562       if (WIFEXITED (status))
1563         return WEXITSTATUS (status);
1564     }
1565   return 0;
1566 }
1567
1568 static void
1569 do_wait (const char *prog, struct pex_obj *pex)
1570 {
1571   int ret = collect_wait (prog, pex);
1572   if (ret != 0)
1573     {
1574       error ("%s returned %d exit status", prog, ret);
1575       collect_exit (ret);
1576     }
1577
1578   if (response_file)
1579     {
1580       unlink (response_file);
1581       response_file = NULL;
1582     }
1583 }
1584
1585 \f
1586 /* Execute a program, and wait for the reply.  */
1587
1588 struct pex_obj *
1589 collect_execute (const char *prog, char **argv, const char *outname,
1590                  const char *errname)
1591 {
1592   struct pex_obj *pex;
1593   const char *errmsg;
1594   int err;
1595   char *response_arg = NULL;
1596   char *response_argv[3] ATTRIBUTE_UNUSED;
1597
1598   if (HAVE_GNU_LD && at_file_supplied && argv[0] != NULL)
1599     {
1600       /* If using @file arguments, create a temporary file and put the
1601          contents of argv into it.  Then change argv to an array corresponding
1602          to a single argument @FILE, where FILE is the temporary filename.  */
1603
1604       char **current_argv = argv + 1;
1605       char *argv0 = argv[0];
1606       int status;
1607       FILE *f;
1608
1609       /* Note: we assume argv contains at least one element; this is
1610          checked above.  */
1611
1612       response_file = make_temp_file ("");
1613
1614       f = fopen (response_file, "w");
1615
1616       if (f == NULL)
1617         fatal ("could not open response file %s", response_file);
1618
1619       status = writeargv (current_argv, f);
1620
1621       if (status)
1622         fatal ("could not write to response file %s", response_file);
1623
1624       status = fclose (f);
1625
1626       if (EOF == status)
1627         fatal ("could not close response file %s", response_file);
1628
1629       response_arg = concat ("@", response_file, NULL);
1630       response_argv[0] = argv0;
1631       response_argv[1] = response_arg;
1632       response_argv[2] = NULL;
1633
1634       argv = response_argv;
1635     }
1636
1637   if (vflag || debug)
1638     {
1639       char **p_argv;
1640       const char *str;
1641
1642       if (argv[0])
1643         fprintf (stderr, "%s", argv[0]);
1644       else
1645         notice ("[cannot find %s]", prog);
1646
1647       for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1648         fprintf (stderr, " %s", str);
1649
1650       fprintf (stderr, "\n");
1651     }
1652
1653   fflush (stdout);
1654   fflush (stderr);
1655
1656   /* If we cannot find a program we need, complain error.  Do this here
1657      since we might not end up needing something that we could not find.  */
1658
1659   if (argv[0] == 0)
1660     fatal ("cannot find '%s'", prog);
1661
1662   pex = pex_init (0, "collect2", NULL);
1663   if (pex == NULL)
1664     fatal_perror ("pex_init failed");
1665
1666   errmsg = pex_run (pex, PEX_LAST | PEX_SEARCH, argv[0], argv, outname,
1667                     errname, &err);
1668   if (errmsg != NULL)
1669     {
1670       if (err != 0)
1671         {
1672           errno = err;
1673           fatal_perror (errmsg);
1674         }
1675       else
1676         fatal (errmsg);
1677     }
1678
1679   if (response_arg)
1680     free (response_arg);
1681
1682   return pex;
1683 }
1684
1685 static void
1686 fork_execute (const char *prog, char **argv)
1687 {
1688   struct pex_obj *pex;
1689
1690   pex = collect_execute (prog, argv, NULL, NULL);
1691   do_wait (prog, pex);
1692 }
1693 \f
1694 /* Unlink a file unless we are debugging.  */
1695
1696 static void
1697 maybe_unlink (const char *file)
1698 {
1699   if (!debug)
1700     unlink_if_ordinary (file);
1701   else
1702     notice ("[Leaving %s]\n", file);
1703 }
1704
1705 \f
1706 static long sequence_number = 0;
1707
1708 /* Add a name to a linked list.  */
1709
1710 static void
1711 add_to_list (struct head *head_ptr, const char *name)
1712 {
1713   struct id *newid
1714     = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1715   struct id *p;
1716   strcpy (newid->name, name);
1717
1718   if (head_ptr->first)
1719     head_ptr->last->next = newid;
1720   else
1721     head_ptr->first = newid;
1722
1723   /* Check for duplicate symbols.  */
1724   for (p = head_ptr->first;
1725        strcmp (name, p->name) != 0;
1726        p = p->next)
1727     ;
1728   if (p != newid)
1729     {
1730       head_ptr->last->next = 0;
1731       free (newid);
1732       return;
1733     }
1734
1735   newid->sequence = ++sequence_number;
1736   head_ptr->last = newid;
1737   head_ptr->number++;
1738 }
1739
1740 /* Grab the init priority number from an init function name that
1741    looks like "_GLOBAL_.I.12345.foo".  */
1742
1743 static int
1744 extract_init_priority (const char *name)
1745 {
1746   int pos = 0, pri;
1747
1748   while (name[pos] == '_')
1749     ++pos;
1750   pos += 10; /* strlen ("GLOBAL__X_") */
1751
1752   /* Extract init_p number from ctor/dtor name.  */
1753   pri = atoi (name + pos);
1754   return pri ? pri : DEFAULT_INIT_PRIORITY;
1755 }
1756
1757 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1758    ctors will be run from right to left, dtors from left to right.  */
1759
1760 static void
1761 sort_ids (struct head *head_ptr)
1762 {
1763   /* id holds the current element to insert.  id_next holds the next
1764      element to insert.  id_ptr iterates through the already sorted elements
1765      looking for the place to insert id.  */
1766   struct id *id, *id_next, **id_ptr;
1767
1768   id = head_ptr->first;
1769
1770   /* We don't have any sorted elements yet.  */
1771   head_ptr->first = NULL;
1772
1773   for (; id; id = id_next)
1774     {
1775       id_next = id->next;
1776       id->sequence = extract_init_priority (id->name);
1777
1778       for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1779         if (*id_ptr == NULL
1780             /* If the sequence numbers are the same, we put the id from the
1781                file later on the command line later in the list.  */
1782             || id->sequence > (*id_ptr)->sequence
1783             /* Hack: do lexical compare, too.
1784             || (id->sequence == (*id_ptr)->sequence
1785                 && strcmp (id->name, (*id_ptr)->name) > 0) */
1786             )
1787           {
1788             id->next = *id_ptr;
1789             *id_ptr = id;
1790             break;
1791           }
1792     }
1793
1794   /* Now set the sequence numbers properly so write_c_file works.  */
1795   for (id = head_ptr->first; id; id = id->next)
1796     id->sequence = ++sequence_number;
1797 }
1798
1799 /* Write: `prefix', the names on list LIST, `suffix'.  */
1800
1801 static void
1802 write_list (FILE *stream, const char *prefix, struct id *list)
1803 {
1804   while (list)
1805     {
1806       fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1807       list = list->next;
1808     }
1809 }
1810
1811 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1812 /* Given a STRING, return nonzero if it occurs in the list in range
1813    [ARGS_BEGIN,ARGS_END).  */
1814
1815 static int
1816 is_in_args (const char *string, const char **args_begin,
1817             const char **args_end)
1818 {
1819   const char **args_pointer;
1820   for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1821     if (strcmp (string, *args_pointer) == 0)
1822       return 1;
1823   return 0;
1824 }
1825 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1826
1827 #ifdef COLLECT_EXPORT_LIST
1828 /* This function is really used only on AIX, but may be useful.  */
1829 #if 0
1830 static int
1831 is_in_list (const char *prefix, struct id *list)
1832 {
1833   while (list)
1834     {
1835       if (!strcmp (prefix, list->name)) return 1;
1836       list = list->next;
1837     }
1838     return 0;
1839 }
1840 #endif
1841 #endif /* COLLECT_EXPORT_LIST */
1842
1843 /* Added for debugging purpose.  */
1844 #ifdef COLLECT_EXPORT_LIST
1845 static void
1846 dump_list (FILE *stream, const char *prefix, struct id *list)
1847 {
1848   while (list)
1849     {
1850       fprintf (stream, "%s%s,\n", prefix, list->name);
1851       list = list->next;
1852     }
1853 }
1854 #endif
1855
1856 #if 0
1857 static void
1858 dump_prefix_list (FILE *stream, const char *prefix, struct prefix_list *list)
1859 {
1860   while (list)
1861     {
1862       fprintf (stream, "%s%s,\n", prefix, list->prefix);
1863       list = list->next;
1864     }
1865 }
1866 #endif
1867
1868 static void
1869 write_list_with_asm (FILE *stream, const char *prefix, struct id *list)
1870 {
1871   while (list)
1872     {
1873       fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1874                prefix, list->sequence, list->name);
1875       list = list->next;
1876     }
1877 }
1878
1879 /* Write out the constructor and destructor tables statically (for a shared
1880    object), along with the functions to execute them.  */
1881
1882 static void
1883 write_c_file_stat (FILE *stream, const char *name ATTRIBUTE_UNUSED)
1884 {
1885   const char *p, *q;
1886   char *prefix, *r;
1887   int frames = (frame_tables.number > 0);
1888
1889   /* Figure out name of output_file, stripping off .so version.  */
1890   p = strrchr (output_file, '/');
1891   if (p == 0)
1892     p = output_file;
1893   else
1894     p++;
1895   q = p;
1896   while (q)
1897     {
1898       q = strchr (q,'.');
1899       if (q == 0)
1900         {
1901           q = p + strlen (p);
1902           break;
1903         }
1904       else
1905         {
1906           if (strncmp (q, SHLIB_SUFFIX, strlen (SHLIB_SUFFIX)) == 0)
1907             {
1908               q += strlen (SHLIB_SUFFIX);
1909               break;
1910             }
1911           else
1912             q++;
1913         }
1914     }
1915   /* q points to null at end of the string (or . of the .so version) */
1916   prefix = XNEWVEC (char, q - p + 1);
1917   strncpy (prefix, p, q - p);
1918   prefix[q - p] = 0;
1919   for (r = prefix; *r; r++)
1920     if (!ISALNUM ((unsigned char)*r))
1921       *r = '_';
1922   if (debug)
1923     notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1924             output_file, prefix);
1925
1926   initname = concat ("_GLOBAL__FI_", prefix, NULL);
1927   fininame = concat ("_GLOBAL__FD_", prefix, NULL);
1928
1929   free (prefix);
1930
1931   /* Write the tables as C code.  */
1932
1933   fprintf (stream, "static int count;\n");
1934   fprintf (stream, "typedef void entry_pt();\n");
1935   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1936
1937   if (frames)
1938     {
1939       write_list_with_asm (stream, "extern void *", frame_tables.first);
1940
1941       fprintf (stream, "\tstatic void *frame_table[] = {\n");
1942       write_list (stream, "\t\t&", frame_tables.first);
1943       fprintf (stream, "\t0\n};\n");
1944
1945       /* This must match what's in frame.h.  */
1946       fprintf (stream, "struct object {\n");
1947       fprintf (stream, "  void *pc_begin;\n");
1948       fprintf (stream, "  void *pc_end;\n");
1949       fprintf (stream, "  void *fde_begin;\n");
1950       fprintf (stream, "  void *fde_array;\n");
1951       fprintf (stream, "  __SIZE_TYPE__ count;\n");
1952       fprintf (stream, "  struct object *next;\n");
1953       fprintf (stream, "};\n");
1954
1955       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1956       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1957
1958       fprintf (stream, "static void reg_frame () {\n");
1959       fprintf (stream, "\tstatic struct object ob;\n");
1960       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1961       fprintf (stream, "\t}\n");
1962
1963       fprintf (stream, "static void dereg_frame () {\n");
1964       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1965       fprintf (stream, "\t}\n");
1966     }
1967
1968   fprintf (stream, "void %s() {\n", initname);
1969   if (constructors.number > 0 || frames)
1970     {
1971       fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1972       write_list (stream, "\t\t", constructors.first);
1973       if (frames)
1974         fprintf (stream, "\treg_frame,\n");
1975       fprintf (stream, "\t};\n");
1976       fprintf (stream, "\tentry_pt **p;\n");
1977       fprintf (stream, "\tif (count++ != 0) return;\n");
1978       fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1979       fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1980     }
1981   else
1982     fprintf (stream, "\t++count;\n");
1983   fprintf (stream, "}\n");
1984   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1985   fprintf (stream, "void %s() {\n", fininame);
1986   if (destructors.number > 0 || frames)
1987     {
1988       fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1989       write_list (stream, "\t\t", destructors.first);
1990       if (frames)
1991         fprintf (stream, "\tdereg_frame,\n");
1992       fprintf (stream, "\t};\n");
1993       fprintf (stream, "\tentry_pt **p;\n");
1994       fprintf (stream, "\tif (--count != 0) return;\n");
1995       fprintf (stream, "\tp = dtors;\n");
1996       fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1997                destructors.number + frames);
1998     }
1999   fprintf (stream, "}\n");
2000
2001   if (shared_obj)
2002     {
2003       COLLECT_SHARED_INIT_FUNC(stream, initname);
2004       COLLECT_SHARED_FINI_FUNC(stream, fininame);
2005     }
2006 }
2007
2008 /* Write the constructor/destructor tables.  */
2009
2010 #ifndef LD_INIT_SWITCH
2011 static void
2012 write_c_file_glob (FILE *stream, const char *name ATTRIBUTE_UNUSED)
2013 {
2014   /* Write the tables as C code.  */
2015
2016   int frames = (frame_tables.number > 0);
2017
2018   fprintf (stream, "typedef void entry_pt();\n\n");
2019
2020   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2021
2022   if (frames)
2023     {
2024       write_list_with_asm (stream, "extern void *", frame_tables.first);
2025
2026       fprintf (stream, "\tstatic void *frame_table[] = {\n");
2027       write_list (stream, "\t\t&", frame_tables.first);
2028       fprintf (stream, "\t0\n};\n");
2029
2030       /* This must match what's in frame.h.  */
2031       fprintf (stream, "struct object {\n");
2032       fprintf (stream, "  void *pc_begin;\n");
2033       fprintf (stream, "  void *pc_end;\n");
2034       fprintf (stream, "  void *fde_begin;\n");
2035       fprintf (stream, "  void *fde_array;\n");
2036       fprintf (stream, "  __SIZE_TYPE__ count;\n");
2037       fprintf (stream, "  struct object *next;\n");
2038       fprintf (stream, "};\n");
2039
2040       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2041       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2042
2043       fprintf (stream, "static void reg_frame () {\n");
2044       fprintf (stream, "\tstatic struct object ob;\n");
2045       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2046       fprintf (stream, "\t}\n");
2047
2048       fprintf (stream, "static void dereg_frame () {\n");
2049       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2050       fprintf (stream, "\t}\n");
2051     }
2052
2053   fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2054   fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2055   write_list (stream, "\t", constructors.first);
2056   if (frames)
2057     fprintf (stream, "\treg_frame,\n");
2058   fprintf (stream, "\t0\n};\n\n");
2059
2060   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2061
2062   fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2063   fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2064   write_list (stream, "\t", destructors.first);
2065   if (frames)
2066     fprintf (stream, "\tdereg_frame,\n");
2067   fprintf (stream, "\t0\n};\n\n");
2068
2069   fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2070   fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2071 }
2072 #endif /* ! LD_INIT_SWITCH */
2073
2074 static void
2075 write_c_file (FILE *stream, const char *name)
2076 {
2077 #ifndef LD_INIT_SWITCH
2078   if (! shared_obj)
2079     write_c_file_glob (stream, name);
2080   else
2081 #endif
2082     write_c_file_stat (stream, name);
2083 }
2084
2085 #ifdef COLLECT_EXPORT_LIST
2086 static void
2087 write_aix_file (FILE *stream, struct id *list)
2088 {
2089   for (; list; list = list->next)
2090     {
2091       fputs (list->name, stream);
2092       putc ('\n', stream);
2093     }
2094 }
2095 #endif
2096 \f
2097 #ifdef OBJECT_FORMAT_NONE
2098
2099 /* Generic version to scan the name list of the loaded program for
2100    the symbols g++ uses for static constructors and destructors.
2101
2102    The constructor table begins at __CTOR_LIST__ and contains a count
2103    of the number of pointers (or -1 if the constructors are built in a
2104    separate section by the linker), followed by the pointers to the
2105    constructor functions, terminated with a null pointer.  The
2106    destructor table has the same format, and begins at __DTOR_LIST__.  */
2107
2108 static void
2109 scan_prog_file (const char *prog_name, enum pass which_pass)
2110 {
2111   void (*int_handler) (int);
2112 #ifdef SIGQUIT
2113   void (*quit_handler) (int);
2114 #endif
2115   char *real_nm_argv[4];
2116   const char **nm_argv = CONST_CAST2 (const char **, char**, real_nm_argv);
2117   int argc = 0;
2118   struct pex_obj *pex;
2119   const char *errmsg;
2120   int err;
2121   char *p, buf[1024];
2122   FILE *inf;
2123
2124   if (which_pass == PASS_SECOND)
2125     return;
2126
2127   /* If we do not have an `nm', complain.  */
2128   if (nm_file_name == 0)
2129     fatal ("cannot find 'nm'");
2130
2131   nm_argv[argc++] = nm_file_name;
2132   if (NM_FLAGS[0] != '\0')
2133     nm_argv[argc++] = NM_FLAGS;
2134
2135   nm_argv[argc++] = prog_name;
2136   nm_argv[argc++] = (char *) 0;
2137
2138   /* Trace if needed.  */
2139   if (vflag)
2140     {
2141       const char **p_argv;
2142       const char *str;
2143
2144       for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2145         fprintf (stderr, " %s", str);
2146
2147       fprintf (stderr, "\n");
2148     }
2149
2150   fflush (stdout);
2151   fflush (stderr);
2152
2153   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2154   if (pex == NULL)
2155     fatal_perror ("pex_init failed");
2156
2157   errmsg = pex_run (pex, 0, nm_file_name, real_nm_argv, NULL, NULL, &err);
2158   if (errmsg != NULL)
2159     {
2160       if (err != 0)
2161         {
2162           errno = err;
2163           fatal_perror (errmsg);
2164         }
2165       else
2166         fatal (errmsg);
2167     }
2168
2169   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2170 #ifdef SIGQUIT
2171   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2172 #endif
2173
2174   inf = pex_read_output (pex, 0);
2175   if (inf == NULL)
2176     fatal_perror ("can't open nm output");
2177
2178   if (debug)
2179     fprintf (stderr, "\nnm output with constructors/destructors.\n");
2180
2181   /* Read each line of nm output.  */
2182   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2183     {
2184       int ch, ch2;
2185       char *name, *end;
2186
2187       /* If it contains a constructor or destructor name, add the name
2188          to the appropriate list.  */
2189
2190       for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2191         if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2192           break;
2193
2194       if (ch != '_')
2195         continue;
2196
2197       name = p;
2198       /* Find the end of the symbol name.
2199          Do not include `|', because Encore nm can tack that on the end.  */
2200       for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2201            end++)
2202         continue;
2203
2204
2205       *end = '\0';
2206       switch (is_ctor_dtor (name))
2207         {
2208         case SYM_CTOR:
2209           if (which_pass != PASS_LIB)
2210             add_to_list (&constructors, name);
2211           break;
2212
2213         case SYM_DTOR:
2214           if (which_pass != PASS_LIB)
2215             add_to_list (&destructors, name);
2216           break;
2217
2218         case SYM_INIT:
2219           if (which_pass != PASS_LIB)
2220             fatal ("init function found in object %s", prog_name);
2221 #ifndef LD_INIT_SWITCH
2222           add_to_list (&constructors, name);
2223 #endif
2224           break;
2225
2226         case SYM_FINI:
2227           if (which_pass != PASS_LIB)
2228             fatal ("fini function found in object %s", prog_name);
2229 #ifndef LD_FINI_SWITCH
2230           add_to_list (&destructors, name);
2231 #endif
2232           break;
2233
2234         case SYM_DWEH:
2235           if (which_pass != PASS_LIB)
2236             add_to_list (&frame_tables, name);
2237           break;
2238
2239         default:                /* not a constructor or destructor */
2240           continue;
2241         }
2242
2243       if (debug)
2244         fprintf (stderr, "\t%s\n", buf);
2245     }
2246
2247   if (debug)
2248     fprintf (stderr, "\n");
2249
2250   do_wait (nm_file_name, pex);
2251
2252   signal (SIGINT,  int_handler);
2253 #ifdef SIGQUIT
2254   signal (SIGQUIT, quit_handler);
2255 #endif
2256 }
2257
2258 #ifdef LDD_SUFFIX
2259
2260 /* Use the List Dynamic Dependencies program to find shared libraries that
2261    the output file depends upon and their initialization/finalization
2262    routines, if any.  */
2263
2264 static void
2265 scan_libraries (const char *prog_name)
2266 {
2267   static struct head libraries;         /* list of shared libraries found */
2268   struct id *list;
2269   void (*int_handler) (int);
2270 #ifdef SIGQUIT
2271   void (*quit_handler) (int);
2272 #endif
2273   char *real_ldd_argv[4];
2274   const char **ldd_argv = CONST_CAST2 (const char **, char **, real_ldd_argv);
2275   int argc = 0;
2276   struct pex_obj *pex;
2277   const char *errmsg;
2278   int err;
2279   char buf[1024];
2280   FILE *inf;
2281
2282   /* If we do not have an `ldd', complain.  */
2283   if (ldd_file_name == 0)
2284     {
2285       error ("cannot find 'ldd'");
2286       return;
2287     }
2288
2289   ldd_argv[argc++] = ldd_file_name;
2290   ldd_argv[argc++] = prog_name;
2291   ldd_argv[argc++] = (char *) 0;
2292
2293   /* Trace if needed.  */
2294   if (vflag)
2295     {
2296       const char **p_argv;
2297       const char *str;
2298
2299       for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2300         fprintf (stderr, " %s", str);
2301
2302       fprintf (stderr, "\n");
2303     }
2304
2305   fflush (stdout);
2306   fflush (stderr);
2307
2308   pex = pex_init (PEX_USE_PIPES, "collect2", NULL);
2309   if (pex == NULL)
2310     fatal_perror ("pex_init failed");
2311
2312   errmsg = pex_run (pex, 0, ldd_file_name, real_ldd_argv, NULL, NULL, &err);
2313   if (errmsg != NULL)
2314     {
2315       if (err != 0)
2316         {
2317           errno = err;
2318           fatal_perror (errmsg);
2319         }
2320       else
2321         fatal (errmsg);
2322     }
2323
2324   int_handler  = (void (*) (int)) signal (SIGINT,  SIG_IGN);
2325 #ifdef SIGQUIT
2326   quit_handler = (void (*) (int)) signal (SIGQUIT, SIG_IGN);
2327 #endif
2328
2329   inf = pex_read_output (pex, 0);
2330   if (inf == NULL)
2331     fatal_perror ("can't open ldd output");
2332
2333   if (debug)
2334     notice ("\nldd output with constructors/destructors.\n");
2335
2336   /* Read each line of ldd output.  */
2337   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2338     {
2339       int ch2;
2340       char *name, *end, *p = buf;
2341
2342       /* Extract names of libraries and add to list.  */
2343       PARSE_LDD_OUTPUT (p);
2344       if (p == 0)
2345         continue;
2346
2347       name = p;
2348       if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2349         fatal ("dynamic dependency %s not found", buf);
2350
2351       /* Find the end of the symbol name.  */
2352       for (end = p;
2353            (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2354            end++)
2355         continue;
2356       *end = '\0';
2357
2358       if (access (name, R_OK) == 0)
2359         add_to_list (&libraries, name);
2360       else
2361         fatal ("unable to open dynamic dependency '%s'", buf);
2362
2363       if (debug)
2364         fprintf (stderr, "\t%s\n", buf);
2365     }
2366   if (debug)
2367     fprintf (stderr, "\n");
2368
2369   do_wait (ldd_file_name, pex);
2370
2371   signal (SIGINT,  int_handler);
2372 #ifdef SIGQUIT
2373   signal (SIGQUIT, quit_handler);
2374 #endif
2375
2376   /* Now iterate through the library list adding their symbols to
2377      the list.  */
2378   for (list = libraries.first; list; list = list->next)
2379     scan_prog_file (list->name, PASS_LIB);
2380 }
2381
2382 #endif /* LDD_SUFFIX */
2383
2384 #endif /* OBJECT_FORMAT_NONE */
2385
2386 \f
2387 /*
2388  * COFF specific stuff.
2389  */
2390
2391 #ifdef OBJECT_FORMAT_COFF
2392
2393 #if defined (EXTENDED_COFF)
2394
2395 #   define GCC_SYMBOLS(X)       (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2396 #   define GCC_SYMENT           SYMR
2397 #   define GCC_OK_SYMBOL(X)     ((X).st == stProc || (X).st == stGlobal)
2398 #   define GCC_SYMINC(X)        (1)
2399 #   define GCC_SYMZERO(X)       (SYMHEADER(X).isymMax)
2400 #   define GCC_CHECK_HDR(X)     (PSYMTAB(X) != 0)
2401
2402 #else
2403
2404 #   define GCC_SYMBOLS(X)       (HEADER(ldptr).f_nsyms)
2405 #   define GCC_SYMENT           SYMENT
2406 #   if defined (C_WEAKEXT)
2407 #     define GCC_OK_SYMBOL(X) \
2408        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2409         ((X).n_scnum > N_UNDEF) && \
2410         (aix64_flag \
2411          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2412              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2413 #     define GCC_UNDEF_SYMBOL(X) \
2414        (((X).n_sclass == C_EXT || (X).n_sclass == C_WEAKEXT) && \
2415         ((X).n_scnum == N_UNDEF))
2416 #   else
2417 #     define GCC_OK_SYMBOL(X) \
2418        (((X).n_sclass == C_EXT) && \
2419         ((X).n_scnum > N_UNDEF) && \
2420         (aix64_flag \
2421          || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2422              || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2423 #     define GCC_UNDEF_SYMBOL(X) \
2424        (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2425 #   endif
2426 #   define GCC_SYMINC(X)        ((X).n_numaux+1)
2427 #   define GCC_SYMZERO(X)       0
2428
2429 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2430 #if TARGET_AIX_VERSION >= 51
2431 #   define GCC_CHECK_HDR(X) \
2432      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2433       || (HEADER (X).f_magic == 0767 && aix64_flag))
2434 #else
2435 #   define GCC_CHECK_HDR(X) \
2436      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2437       || (HEADER (X).f_magic == 0757 && aix64_flag))
2438 #endif
2439
2440 #endif
2441
2442 #ifdef COLLECT_EXPORT_LIST
2443 /* Array of standard AIX libraries which should not
2444    be scanned for ctors/dtors.  */
2445 static const char *const aix_std_libs[] = {
2446   "/unix",
2447   "/lib/libc.a",
2448   "/lib/libm.a",
2449   "/lib/libc_r.a",
2450   "/lib/libm_r.a",
2451   "/usr/lib/libc.a",
2452   "/usr/lib/libm.a",
2453   "/usr/lib/libc_r.a",
2454   "/usr/lib/libm_r.a",
2455   "/usr/lib/threads/libc.a",
2456   "/usr/ccs/lib/libc.a",
2457   "/usr/ccs/lib/libm.a",
2458   "/usr/ccs/lib/libc_r.a",
2459   "/usr/ccs/lib/libm_r.a",
2460   NULL
2461 };
2462
2463 /* This function checks the filename and returns 1
2464    if this name matches the location of a standard AIX library.  */
2465 static int ignore_library (const char *);
2466 static int
2467 ignore_library (const char *name)
2468 {
2469   const char *const *p;
2470   size_t length;
2471
2472   if (target_system_root[0] != '\0')
2473     {
2474       length = strlen (target_system_root);
2475       if (strncmp (name, target_system_root, length) != 0)
2476         return 0;
2477       name += length;
2478     }
2479   for (p = &aix_std_libs[0]; *p != NULL; ++p)
2480     if (strcmp (name, *p) == 0)
2481       return 1;
2482   return 0;
2483 }
2484 #endif /* COLLECT_EXPORT_LIST */
2485
2486 #if defined (HAVE_DECL_LDGETNAME) && !HAVE_DECL_LDGETNAME
2487 extern char *ldgetname (LDFILE *, GCC_SYMENT *);
2488 #endif
2489
2490 /* COFF version to scan the name list of the loaded program for
2491    the symbols g++ uses for static constructors and destructors.
2492
2493    The constructor table begins at __CTOR_LIST__ and contains a count
2494    of the number of pointers (or -1 if the constructors are built in a
2495    separate section by the linker), followed by the pointers to the
2496    constructor functions, terminated with a null pointer.  The
2497    destructor table has the same format, and begins at __DTOR_LIST__.  */
2498
2499 static void
2500 scan_prog_file (const char *prog_name, enum pass which_pass)
2501 {
2502   LDFILE *ldptr = NULL;
2503   int sym_index, sym_count;
2504   int is_shared = 0;
2505
2506   if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2507     return;
2508
2509 #ifdef COLLECT_EXPORT_LIST
2510   /* We do not need scanning for some standard C libraries.  */
2511   if (which_pass == PASS_FIRST && ignore_library (prog_name))
2512     return;
2513
2514   /* On AIX we have a loop, because there is not much difference
2515      between an object and an archive. This trick allows us to
2516      eliminate scan_libraries() function.  */
2517   do
2518     {
2519 #endif
2520       /* Some platforms (e.g. OSF4) declare ldopen as taking a
2521          non-const char * filename parameter, even though it will not
2522          modify that string.  So we must cast away const-ness here,
2523          using CONST_CAST to prevent complaints from -Wcast-qual.  */
2524       if ((ldptr = ldopen (CONST_CAST (char *, prog_name), ldptr)) != NULL)
2525         {
2526           if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2527             fatal ("%s: not a COFF file", prog_name);
2528
2529           if (GCC_CHECK_HDR (ldptr))
2530             {
2531               sym_count = GCC_SYMBOLS (ldptr);
2532               sym_index = GCC_SYMZERO (ldptr);
2533
2534 #ifdef COLLECT_EXPORT_LIST
2535               /* Is current archive member a shared object?  */
2536               is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2537 #endif
2538
2539               while (sym_index < sym_count)
2540                 {
2541                   GCC_SYMENT symbol;
2542
2543                   if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2544                     break;
2545                   sym_index += GCC_SYMINC (symbol);
2546
2547                   if (GCC_OK_SYMBOL (symbol))
2548                     {
2549                       char *name;
2550
2551                       if ((name = ldgetname (ldptr, &symbol)) == NULL)
2552                         continue;               /* Should never happen.  */
2553
2554 #ifdef XCOFF_DEBUGGING_INFO
2555                       /* All AIX function names have a duplicate entry
2556                          beginning with a dot.  */
2557                       if (*name == '.')
2558                         ++name;
2559 #endif
2560
2561                       switch (is_ctor_dtor (name))
2562                         {
2563                         case SYM_CTOR:
2564                           if (! is_shared)
2565                             add_to_list (&constructors, name);
2566 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2567                           if (which_pass == PASS_OBJ)
2568                             add_to_list (&exports, name);
2569 #endif
2570                           break;
2571
2572                         case SYM_DTOR:
2573                           if (! is_shared)
2574                             add_to_list (&destructors, name);
2575 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2576                           if (which_pass == PASS_OBJ)
2577                             add_to_list (&exports, name);
2578 #endif
2579                           break;
2580
2581 #ifdef COLLECT_EXPORT_LIST
2582                         case SYM_INIT:
2583 #ifndef LD_INIT_SWITCH
2584                           if (is_shared)
2585                             add_to_list (&constructors, name);
2586 #endif
2587                           break;
2588
2589                         case SYM_FINI:
2590 #ifndef LD_INIT_SWITCH
2591                           if (is_shared)
2592                             add_to_list (&destructors, name);
2593 #endif
2594                           break;
2595 #endif
2596
2597                         case SYM_DWEH:
2598                           if (! is_shared)
2599                             add_to_list (&frame_tables, name);
2600 #if defined (COLLECT_EXPORT_LIST) && !defined (LD_INIT_SWITCH)
2601                           if (which_pass == PASS_OBJ)
2602                             add_to_list (&exports, name);
2603 #endif
2604                           break;
2605
2606                         default:        /* not a constructor or destructor */
2607 #ifdef COLLECT_EXPORT_LIST
2608                           /* Explicitly export all global symbols when
2609                              building a shared object on AIX, but do not
2610                              re-export symbols from another shared object
2611                              and do not export symbols if the user
2612                              provides an explicit export list.  */
2613                           if (shared_obj && !is_shared
2614                               && which_pass == PASS_OBJ && !export_flag)
2615                             add_to_list (&exports, name);
2616 #endif
2617                           continue;
2618                         }
2619
2620                       if (debug)
2621 #if !defined(EXTENDED_COFF)
2622                         fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2623                                  symbol.n_scnum, symbol.n_sclass,
2624                                  (symbol.n_type ? "0" : ""), symbol.n_type,
2625                                  name);
2626 #else
2627                         fprintf (stderr,
2628                                  "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2629                                  symbol.iss, (long) symbol.value, symbol.index, name);
2630 #endif
2631                     }
2632                 }
2633             }
2634 #ifdef COLLECT_EXPORT_LIST
2635           else
2636             {
2637               /* If archive contains both 32-bit and 64-bit objects,
2638                  we want to skip objects in other mode so mismatch normal.  */
2639               if (debug)
2640                 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2641                          prog_name, HEADER (ldptr).f_magic, aix64_flag);
2642             }
2643 #endif
2644         }
2645       else
2646         {
2647           fatal ("%s: cannot open as COFF file", prog_name);
2648         }
2649 #ifdef COLLECT_EXPORT_LIST
2650       /* On AIX loop continues while there are more members in archive.  */
2651     }
2652   while (ldclose (ldptr) == FAILURE);
2653 #else
2654   /* Otherwise we simply close ldptr.  */
2655   (void) ldclose(ldptr);
2656 #endif
2657 }
2658 #endif /* OBJECT_FORMAT_COFF */
2659
2660 #ifdef COLLECT_EXPORT_LIST
2661 /* Given a library name without "lib" prefix, this function
2662    returns a full library name including a path.  */
2663 static char *
2664 resolve_lib_name (const char *name)
2665 {
2666   char *lib_buf;
2667   int i, j, l = 0;
2668   /* Library extensions for AIX dynamic linking.  */
2669   const char * const libexts[2] = {"a", "so"};
2670
2671   for (i = 0; libpaths[i]; i++)
2672     if (libpaths[i]->max_len > l)
2673       l = libpaths[i]->max_len;
2674
2675   lib_buf = XNEWVEC (char, l + strlen(name) + 10);
2676
2677   for (i = 0; libpaths[i]; i++)
2678     {
2679       struct prefix_list *list = libpaths[i]->plist;
2680       for (; list; list = list->next)
2681         {
2682           /* The following lines are needed because path_prefix list
2683              may contain directories both with trailing '/' and
2684              without it.  */
2685           const char *p = "";
2686           if (list->prefix[strlen(list->prefix)-1] != '/')
2687             p = "/";
2688           for (j = 0; j < 2; j++)
2689             {
2690               sprintf (lib_buf, "%s%slib%s.%s",
2691                        list->prefix, p, name,
2692                        libexts[(j + aixrtl_flag) % 2]);
2693               if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2694               if (file_exists (lib_buf))
2695                 {
2696                   if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2697                   return (lib_buf);
2698                 }
2699             }
2700         }
2701     }
2702   if (debug)
2703     fprintf (stderr, "not found\n");
2704   else
2705     fatal ("library lib%s not found", name);
2706   return (NULL);
2707 }
2708 #endif /* COLLECT_EXPORT_LIST */