OSDN Git Service

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