OSDN Git Service

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