OSDN Git Service

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