OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-stable/] [gcc-4.5.1/] [gcc/] [collect2.c] - Blame information for rev 865

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.