OSDN Git Service

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