OSDN Git Service

Wrap comment.
[pf3gnuchains/gcc-fork.git] / gcc / collect2.c
1 /* Collect static initialization info into data structures that can be
2    traversed by C++ initialization and finalization routines.
3    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2001 Free Software Foundation, Inc.
5    Contributed by Chris Smith (csmith@convex.com).
6    Heavily modified by Michael Meissner (meissner@cygnus.com),
7    Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify it under
12 the terms of the GNU General Public License as published by the Free
13 Software Foundation; either version 2, or (at your option) any later
14 version.
15
16 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17 WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19 for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING.  If not, write to the Free
23 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
24 02111-1307, USA.  */
25
26
27 /* Build tables of static constructors and destructors and run ld.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include <signal.h>
32 #if ! defined( SIGCHLD ) && defined( SIGCLD )
33 #  define SIGCHLD SIGCLD
34 #endif
35
36 #ifdef vfork /* Autoconf may define this to fork for us.  */
37 # define VFORK_STRING "fork"
38 #else
39 # define VFORK_STRING "vfork"
40 #endif
41 #ifdef HAVE_VFORK_H
42 #include <vfork.h>
43 #endif
44 #ifdef VMS
45 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
46                lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
47 #endif /* VMS */
48
49 #ifndef LIBRARY_PATH_ENV
50 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
51 #endif
52
53 #define COLLECT
54
55 #include "collect2.h"
56 #include "demangle.h"
57 #include "obstack.h"
58 #include "intl.h"
59 #include "version.h"
60
61 /* Obstack allocation and deallocation routines.  */
62 #define obstack_chunk_alloc xmalloc
63 #define obstack_chunk_free free
64 \f
65 /* On certain systems, we have code that works by scanning the object file
66    directly.  But this code uses system-specific header files and library
67    functions, so turn it off in a cross-compiler.  Likewise, the names of
68    the utilities are not correct for a cross-compiler; we have to hope that
69    cross-versions are in the proper directories.  */
70
71 #ifdef CROSS_COMPILE
72 #undef SUNOS4_SHARED_LIBRARIES
73 #undef OBJECT_FORMAT_COFF
74 #undef OBJECT_FORMAT_ROSE
75 #undef MD_EXEC_PREFIX
76 #undef REAL_LD_FILE_NAME
77 #undef REAL_NM_FILE_NAME
78 #undef REAL_STRIP_FILE_NAME
79 #endif
80
81 /* If we cannot use a special method, use the ordinary one:
82    run nm to find what symbols are present.
83    In a cross-compiler, this means you need a cross nm,
84    but that is not quite as unpleasant as special headers.  */
85
86 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
87 #define OBJECT_FORMAT_NONE
88 #endif
89
90 #ifdef OBJECT_FORMAT_COFF
91
92 #include <a.out.h>
93 #include <ar.h>
94
95 #ifdef UMAX
96 #include <sgs.h>
97 #endif
98
99 /* Many versions of ldfcn.h define these.  */
100 #ifdef FREAD
101 #undef FREAD
102 #undef FWRITE
103 #endif
104
105 #include <ldfcn.h>
106
107 /* Some systems have an ISCOFF macro, but others do not.  In some cases
108    the macro may be wrong.  MY_ISCOFF is defined in tm.h files for machines
109    that either do not have an ISCOFF macro in /usr/include or for those 
110    where it is wrong.  */
111
112 #ifndef MY_ISCOFF
113 #define MY_ISCOFF(X) ISCOFF (X)
114 #endif
115
116 #endif /* OBJECT_FORMAT_COFF */
117
118 #ifdef OBJECT_FORMAT_ROSE
119
120 #ifdef _OSF_SOURCE
121 #define USE_MMAP
122 #endif
123
124 #ifdef USE_MMAP
125 #include <sys/mman.h>
126 #endif
127
128 #include <unistd.h>
129 #include <mach_o_format.h>
130 #include <mach_o_header.h>
131 #include <mach_o_vals.h>
132 #include <mach_o_types.h>
133
134 #endif /* OBJECT_FORMAT_ROSE */
135
136 #ifdef OBJECT_FORMAT_NONE
137
138 /* Default flags to pass to nm.  */
139 #ifndef NM_FLAGS
140 #define NM_FLAGS "-n"
141 #endif
142
143 #endif /* OBJECT_FORMAT_NONE */
144
145 /* Some systems use __main in a way incompatible with its use in gcc, in these
146    cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
147    give the same symbol without quotes for an alternative entry point.  You
148    must define both, or neither.  */
149 #ifndef NAME__MAIN
150 #define NAME__MAIN "__main"
151 #define SYMBOL__MAIN __main
152 #endif
153
154 /* This must match tree.h.  */
155 #define DEFAULT_INIT_PRIORITY 65535
156
157 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
158 #define SCAN_LIBRARIES
159 #endif
160
161 #ifdef USE_COLLECT2
162 int do_collecting = 1;
163 #else
164 int do_collecting = 0;
165 #endif
166
167 /* Nonzero if we should suppress the automatic demangling of identifiers
168    in linker error messages.  Set from COLLECT_NO_DEMANGLE.  */
169 int no_demangle;
170 \f
171 /* Linked lists of constructor and destructor names.  */
172
173 struct id 
174 {
175   struct id *next;
176   int sequence;
177   char name[1];
178 };
179
180 struct head
181 {
182   struct id *first;
183   struct id *last;
184   int number;
185 };
186
187 /* Enumeration giving which pass this is for scanning the program file.  */
188
189 enum pass {
190   PASS_FIRST,                           /* without constructors */
191   PASS_OBJ,                             /* individual objects */
192   PASS_LIB,                             /* looking for shared libraries */
193   PASS_SECOND                           /* with constructors linked in */
194 };
195
196 int vflag;                              /* true if -v */
197 static int rflag;                       /* true if -r */
198 static int strip_flag;                  /* true if -s */
199 #ifdef COLLECT_EXPORT_LIST
200 static int export_flag;                 /* true if -bE */
201 static int aix64_flag;                  /* true if -b64 */
202 #endif
203
204 int debug;                              /* true if -debug */
205
206 static int shared_obj;                  /* true if -shared */
207
208 static const char *c_file;              /* <xxx>.c for constructor/destructor list.  */
209 static const char *o_file;              /* <xxx>.o for constructor/destructor list.  */
210 #ifdef COLLECT_EXPORT_LIST
211 static const char *export_file;         /* <xxx>.x for AIX export list.  */
212 #endif
213 const char *ldout;                      /* File for ld errors.  */
214 static const char *output_file;         /* Output file for ld.  */
215 static const char *nm_file_name;        /* pathname of nm */
216 #ifdef LDD_SUFFIX
217 static const char *ldd_file_name;       /* pathname of ldd (or equivalent) */
218 #endif
219 static const char *strip_file_name;             /* pathname of strip */
220 const char *c_file_name;                /* pathname of gcc */
221 static char *initname, *fininame;       /* names of init and fini funcs */
222
223 static struct head constructors;        /* list of constructors found */
224 static struct head destructors;         /* list of destructors found */
225 #ifdef COLLECT_EXPORT_LIST
226 static struct head exports;             /* list of exported symbols */
227 #endif
228 static struct head frame_tables;        /* list of frame unwind info tables */
229
230 struct obstack temporary_obstack;
231 struct obstack permanent_obstack;
232 char * temporary_firstobj;
233
234 /* Holds the return value of pexecute.  */
235 int pexecute_pid;
236
237 /* Defined in the automatically-generated underscore.c.  */
238 extern int prepends_underscore;
239
240 #ifndef GET_ENV_PATH_LIST
241 #define GET_ENV_PATH_LIST(VAR,NAME)     do { (VAR) = getenv (NAME); } while (0)
242 #endif
243
244 /* Structure to hold all the directories in which to search for files to
245    execute.  */
246
247 struct prefix_list
248 {
249   const char *prefix;         /* String to prepend to the path.  */
250   struct prefix_list *next;   /* Next in linked list.  */
251 };
252
253 struct path_prefix
254 {
255   struct prefix_list *plist;  /* List of prefixes to try */
256   int max_len;                /* Max length of a prefix in PLIST */
257   const char *name;           /* Name of this list (used in config stuff) */
258 };
259
260 #ifdef COLLECT_EXPORT_LIST
261 /* Lists to keep libraries to be scanned for global constructors/destructors.  */
262 static struct head libs;                    /* list of libraries */
263 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
264 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
265 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
266                                           &libpath_lib_dirs, NULL};
267 static const char *const libexts[3] = {"a", "so", NULL};  /* possible library extensions */
268 #endif
269
270 static void handler             PARAMS ((int));
271 static int is_ctor_dtor         PARAMS ((const char *));
272 static char *find_a_file        PARAMS ((struct path_prefix *, const char *));
273 static void add_prefix          PARAMS ((struct path_prefix *, const char *));
274 static void prefix_from_env     PARAMS ((const char *, struct path_prefix *));
275 static void prefix_from_string  PARAMS ((const char *, struct path_prefix *));
276 static void do_wait             PARAMS ((const char *));
277 static void fork_execute        PARAMS ((const char *, char **));
278 static void maybe_unlink        PARAMS ((const char *));
279 static void add_to_list         PARAMS ((struct head *, const char *));
280 static int extract_init_priority PARAMS ((const char *));
281 static void sort_ids            PARAMS ((struct head *));
282 static void write_list          PARAMS ((FILE *, const char *, struct id *));
283 #ifdef COLLECT_EXPORT_LIST
284 static void dump_list           PARAMS ((FILE *, const char *, struct id *));
285 #endif
286 #if 0
287 static void dump_prefix_list    PARAMS ((FILE *, const char *, struct prefix_list *));
288 #endif
289 static void write_list_with_asm PARAMS ((FILE *, const char *, struct id *));
290 static void write_c_file        PARAMS ((FILE *, const char *));
291 static void write_c_file_stat   PARAMS ((FILE *, const char *));
292 #ifndef LD_INIT_SWITCH
293 static void write_c_file_glob   PARAMS ((FILE *, const char *));
294 #endif
295 static void scan_prog_file      PARAMS ((const char *, enum pass));
296 #ifdef SCAN_LIBRARIES
297 static void scan_libraries      PARAMS ((const char *));
298 #endif
299 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
300 static int is_in_args           PARAMS ((const char *, const char **, const char **));
301 #endif
302 #ifdef COLLECT_EXPORT_LIST
303 #if 0
304 static int is_in_list           PARAMS ((const char *, struct id *));
305 #endif
306 static void write_aix_file      PARAMS ((FILE *, struct id *));
307 static char *resolve_lib_name   PARAMS ((const char *));
308 static int ignore_library       PARAMS ((const char *));
309 #endif
310 static char *extract_string     PARAMS ((const char **));
311 \f
312 #ifndef HAVE_DUP2
313 static int dup2 PARAMS ((int, int));
314 static int
315 dup2 (oldfd, newfd)
316      int oldfd;
317      int newfd;
318 {
319   int fdtmp[256];
320   int fdx = 0;
321   int fd;
322  
323   if (oldfd == newfd)
324     return oldfd;
325   close (newfd);
326   while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
327     fdtmp[fdx++] = fd;
328   while (fdx > 0)
329     close (fdtmp[--fdx]);
330
331   return fd;
332 }
333 #endif /* ! HAVE_DUP2 */
334 \f
335 /* Delete tempfiles and exit function.  */
336
337 void
338 collect_exit (status)
339      int status;
340 {
341   if (c_file != 0 && c_file[0])
342     maybe_unlink (c_file);
343
344   if (o_file != 0 && o_file[0])
345     maybe_unlink (o_file);
346
347 #ifdef COLLECT_EXPORT_LIST
348   if (export_file != 0 && export_file[0])
349     maybe_unlink (export_file);
350 #endif
351
352   if (ldout != 0 && ldout[0])
353     {
354       dump_file (ldout);
355       maybe_unlink (ldout);
356     }
357
358   if (status != 0 && output_file != 0 && output_file[0])
359     maybe_unlink (output_file);
360
361   exit (status);
362 }
363
364 \f
365 /* Notify user of a non-error.  */
366 void
367 notice VPARAMS ((const char *msgid, ...))
368 {
369   VA_OPEN (ap, msgid);
370   VA_FIXEDARG (ap, const char *, msgid);
371
372   vfprintf (stderr, _(msgid), ap);
373   VA_CLOSE (ap);
374 }
375
376 /* Die when sys call fails.  */
377
378 void
379 fatal_perror VPARAMS ((const char * msgid, ...))
380 {
381   int e = errno;
382
383   VA_OPEN (ap, msgid);
384   VA_FIXEDARG (ap, const char *, msgid);
385
386   fprintf (stderr, "collect2: ");
387   vfprintf (stderr, _(msgid), ap);
388   fprintf (stderr, ": %s\n", xstrerror (e));
389   VA_CLOSE (ap);
390
391   collect_exit (FATAL_EXIT_CODE);
392 }
393
394 /* Just die.  */
395
396 void
397 fatal VPARAMS ((const char * msgid, ...))
398 {
399   VA_OPEN (ap, msgid);
400   VA_FIXEDARG (ap, const char *, msgid);
401   
402   fprintf (stderr, "collect2: ");
403   vfprintf (stderr, _(msgid), ap);
404   fprintf (stderr, "\n");
405   VA_CLOSE (ap);
406
407   collect_exit (FATAL_EXIT_CODE);
408 }
409
410 /* Write error message.  */
411
412 void
413 error VPARAMS ((const char * msgid, ...))
414 {
415   VA_OPEN (ap, msgid);
416   VA_FIXEDARG (ap, const char *, msgid);
417
418   fprintf (stderr, "collect2: ");
419   vfprintf (stderr, _(msgid), ap);
420   fprintf (stderr, "\n");
421   VA_CLOSE(ap);
422 }
423
424 /* In case obstack is linked in, and abort is defined to fancy_abort,
425    provide a default entry.  */
426
427 void
428 fancy_abort ()
429 {
430   fatal ("internal error");
431 }
432 \f
433 static void
434 handler (signo)
435      int signo;
436 {
437   if (c_file != 0 && c_file[0])
438     maybe_unlink (c_file);
439
440   if (o_file != 0 && o_file[0])
441     maybe_unlink (o_file);
442
443   if (ldout != 0 && ldout[0])
444     maybe_unlink (ldout);
445
446 #ifdef COLLECT_EXPORT_LIST
447   if (export_file != 0 && export_file[0])
448     maybe_unlink (export_file);
449 #endif
450
451   signal (signo, SIG_DFL);
452   kill (getpid (), signo);
453 }
454
455 \f
456 int
457 file_exists (name)
458      const char *name;
459 {
460   return access (name, R_OK) == 0;
461 }
462
463 /* Parse a reasonable subset of shell quoting syntax.  */
464
465 static char *
466 extract_string (pp)
467      const char **pp;
468 {
469   const char *p = *pp;
470   int backquote = 0;
471   int inside = 0;
472
473   for (;;)
474     {
475       char c = *p;
476       if (c == '\0')
477         break;
478       ++p;
479       if (backquote)
480         obstack_1grow (&temporary_obstack, c);
481       else if (! inside && c == ' ')
482         break;
483       else if (! inside && c == '\\')
484         backquote = 1;
485       else if (c == '\'')
486         inside = !inside;
487       else
488         obstack_1grow (&temporary_obstack, c);
489     }
490
491   obstack_1grow (&temporary_obstack, '\0');
492   *pp = p;
493   return obstack_finish (&temporary_obstack);
494 }
495 \f
496 void
497 dump_file (name)
498      const char *name;
499 {
500   FILE *stream = fopen (name, "r");
501
502   if (stream == 0)
503     return;
504   while (1)
505     {
506       int c;
507       while (c = getc (stream),
508              c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
509         obstack_1grow (&temporary_obstack, c);
510       if (obstack_object_size (&temporary_obstack) > 0)
511         {
512           const char *word, *p;
513           char *result;
514           obstack_1grow (&temporary_obstack, '\0');
515           word = obstack_finish (&temporary_obstack);
516
517           if (*word == '.')
518             ++word, putc ('.', stderr);
519           p = word;
520           if (*p == '_' && prepends_underscore)
521             ++p;
522
523           if (no_demangle)
524             result = 0;
525           else
526             result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
527
528           if (result)
529             {
530               int diff;
531               fputs (result, stderr);
532
533               diff = strlen (word) - strlen (result);
534               while (diff > 0 && c == ' ')
535                 --diff, putc (' ', stderr);
536               while (diff < 0 && c == ' ')
537                 ++diff, c = getc (stream);
538
539               free (result);
540             }
541           else
542             fputs (word, stderr);
543
544           fflush (stderr);
545           obstack_free (&temporary_obstack, temporary_firstobj);
546         }
547       if (c == EOF)
548         break;
549       putc (c, stderr);
550     }
551   fclose (stream);
552 }
553 \f
554 /* Decide whether the given symbol is: a constructor (1), a destructor
555    (2), a routine in a shared object that calls all the constructors
556    (3) or destructors (4), a DWARF exception-handling table (5), or
557    nothing special (0).  */
558
559 static int
560 is_ctor_dtor (s)
561      const char *s;
562 {
563   struct names { const char *const name; const int len; const int ret;
564     const int two_underscores; };
565
566   struct names *p;
567   int ch;
568   const char *orig_s = s;
569
570   static struct names special[] = {
571     { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
572     { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
573     { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
574     { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
575     { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
576 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
577                          cfront has its own linker procedure to collect them;
578                          if collect2 gets them too, they get collected twice
579                          when the cfront procedure is run and the compiler used
580                          for linking happens to be GCC.  */
581     { "sti__", sizeof ("sti__")-1, 1, 1 },
582     { "std__", sizeof ("std__")-1, 2, 1 },
583 #endif /* CFRONT_LOSSAGE */
584     { NULL, 0, 0, 0 }
585   };
586
587   while ((ch = *s) == '_')
588     ++s;
589
590   if (s == orig_s)
591     return 0;
592
593   for (p = &special[0]; p->len > 0; p++)
594     {
595       if (ch == p->name[0]
596           && (!p->two_underscores || ((s - orig_s) >= 2))
597           && strncmp(s, p->name, p->len) == 0)
598         {
599           return p->ret;
600         }
601     }
602   return 0;
603 }
604 \f
605 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
606    and one from the PATH variable.  */
607
608 static struct path_prefix cpath, path;
609
610 #ifdef CROSS_COMPILE
611 /* This is the name of the target machine.  We use it to form the name
612    of the files to execute.  */
613
614 static const char *const target_machine = TARGET_MACHINE;
615 #endif
616
617 /* Search for NAME using prefix list PPREFIX.  We only look for executable
618    files. 
619
620    Return 0 if not found, otherwise return its name, allocated with malloc.  */
621
622 static char *
623 find_a_file (pprefix, name)
624      struct path_prefix *pprefix;
625      const char *name;
626 {
627   char *temp;
628   struct prefix_list *pl;
629   int len = pprefix->max_len + strlen (name) + 1;
630
631   if (debug)
632     fprintf (stderr, "Looking for '%s'\n", name);
633   
634 #ifdef HOST_EXECUTABLE_SUFFIX
635   len += strlen (HOST_EXECUTABLE_SUFFIX);
636 #endif
637
638   temp = xmalloc (len);
639
640   /* Determine the filename to execute (special case for absolute paths).  */
641
642   if (*name == '/'
643 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
644       || (*name && name[1] == ':')
645 #endif
646       )
647     {
648       if (access (name, X_OK) == 0)
649         {
650           strcpy (temp, name);
651
652           if (debug)
653             fprintf (stderr, "  - found: absolute path\n");
654           
655           return temp;
656         }
657
658 #ifdef HOST_EXECUTABLE_SUFFIX
659         /* Some systems have a suffix for executable files.
660            So try appending that.  */
661       strcpy (temp, name);
662         strcat (temp, HOST_EXECUTABLE_SUFFIX);
663         
664         if (access (temp, X_OK) == 0)
665           return temp;
666 #endif
667
668       if (debug)
669         fprintf (stderr, "  - failed to locate using absolute path\n");
670     }
671   else
672     for (pl = pprefix->plist; pl; pl = pl->next)
673       {
674         struct stat st;
675
676         strcpy (temp, pl->prefix);
677         strcat (temp, name);
678         
679         if (stat (temp, &st) >= 0
680             && ! S_ISDIR (st.st_mode)
681             && access (temp, X_OK) == 0)
682           return temp;
683
684 #ifdef HOST_EXECUTABLE_SUFFIX
685         /* Some systems have a suffix for executable files.
686            So try appending that.  */
687         strcat (temp, HOST_EXECUTABLE_SUFFIX);
688         
689         if (stat (temp, &st) >= 0
690             && ! S_ISDIR (st.st_mode)
691             && access (temp, X_OK) == 0)
692           return temp;
693 #endif
694       }
695
696   if (debug && pprefix->plist == NULL)
697     fprintf (stderr, "  - failed: no entries in prefix list\n");
698
699   free (temp);
700   return 0;
701 }
702
703 /* Add an entry for PREFIX to prefix list PPREFIX.  */
704
705 static void
706 add_prefix (pprefix, prefix)
707      struct path_prefix *pprefix;
708      const char *prefix;
709 {
710   struct prefix_list *pl, **prev;
711   int len;
712
713   if (pprefix->plist)
714     {
715       for (pl = pprefix->plist; pl->next; pl = pl->next)
716         ;
717       prev = &pl->next;
718     }
719   else
720     prev = &pprefix->plist;
721
722   /* Keep track of the longest prefix */
723
724   len = strlen (prefix);
725   if (len > pprefix->max_len)
726     pprefix->max_len = len;
727
728   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
729   pl->prefix = xstrdup (prefix);
730
731   if (*prev)
732     pl->next = *prev;
733   else
734     pl->next = (struct prefix_list *) 0;
735   *prev = pl;
736 }
737 \f
738 /* Take the value of the environment variable ENV, break it into a path, and
739    add of the entries to PPREFIX.  */
740
741 static void
742 prefix_from_env (env, pprefix)
743      const char *env;
744      struct path_prefix *pprefix;
745 {
746   const char *p;
747   GET_ENV_PATH_LIST (p, env);
748
749   if (p)
750     prefix_from_string (p, pprefix);
751 }
752
753 static void
754 prefix_from_string (p, pprefix)
755      const char *p;
756      struct path_prefix *pprefix;
757 {
758   const char *startp, *endp;
759   char *nstore = (char *) xmalloc (strlen (p) + 3);
760
761   if (debug)
762     fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
763   
764   startp = endp = p;
765   while (1)
766     {
767       if (*endp == PATH_SEPARATOR || *endp == 0)
768         {
769           strncpy (nstore, startp, endp-startp);
770           if (endp == startp)
771             {
772               strcpy (nstore, "./");
773             }
774           else if (! IS_DIR_SEPARATOR (endp[-1]))
775             {
776               nstore[endp-startp] = DIR_SEPARATOR;
777               nstore[endp-startp+1] = 0;
778             }
779           else
780             nstore[endp-startp] = 0;
781
782           if (debug)
783             fprintf (stderr, "  - add prefix: %s\n", nstore);
784           
785           add_prefix (pprefix, nstore);
786           if (*endp == 0)
787             break;
788           endp = startp = endp + 1;
789         }
790       else
791         endp++;
792     }
793 }
794 \f
795 /* Main program.  */
796
797 int main                PARAMS ((int, char *[]));
798 int
799 main (argc, argv)
800      int argc;
801      char *argv[];
802 {
803   static const char *const ld_suffix    = "ld";
804   static const char *const real_ld_suffix = "real-ld";
805   static const char *const collect_ld_suffix = "collect-ld";
806   static const char *const nm_suffix    = "nm";
807   static const char *const gnm_suffix   = "gnm";
808 #ifdef LDD_SUFFIX
809   static const char *const ldd_suffix   = LDD_SUFFIX;
810 #endif
811   static const char *const strip_suffix = "strip";
812   static const char *const gstrip_suffix = "gstrip";
813
814 #ifdef CROSS_COMPILE
815   /* If we look for a program in the compiler directories, we just use
816      the short name, since these directories are already system-specific.
817      But it we look for a program in the system directories, we need to
818      qualify the program name with the target machine.  */
819
820   const char *const full_ld_suffix =
821     concat(target_machine, "-", ld_suffix, NULL);
822   const char *const full_nm_suffix =
823     concat (target_machine, "-", nm_suffix, NULL);
824   const char *const full_gnm_suffix =
825     concat (target_machine, "-", gnm_suffix, NULL);
826 #ifdef LDD_SUFFIX
827   const char *const full_ldd_suffix =
828     concat (target_machine, "-", ldd_suffix, NULL);
829 #endif
830   const char *const full_strip_suffix =
831     concat (target_machine, "-", strip_suffix, NULL);
832   const char *const full_gstrip_suffix =
833     concat (target_machine, "-", gstrip_suffix, NULL);
834 #else
835   const char *const full_ld_suffix      = ld_suffix;
836   const char *const full_nm_suffix      = nm_suffix;
837   const char *const full_gnm_suffix     = gnm_suffix;
838 #ifdef LDD_SUFFIX
839   const char *const full_ldd_suffix     = ldd_suffix;
840 #endif
841   const char *const full_strip_suffix   = strip_suffix;
842   const char *const full_gstrip_suffix  = gstrip_suffix;
843 #endif /* CROSS_COMPILE */
844
845   const char *arg;
846   FILE *outf;
847 #ifdef COLLECT_EXPORT_LIST
848   FILE *exportf;
849 #endif
850   const char *ld_file_name;
851   const char *p;
852   char **c_argv;
853   const char **c_ptr;
854   char **ld1_argv;
855   const char **ld1;
856   char **ld2_argv;
857   const char **ld2;
858   char **object_lst;
859   const char **object;
860   int first_file;
861   int num_c_args        = argc+9;
862
863   no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
864
865   /* Suppress demangling by the real linker, which may be broken.  */
866   putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
867
868 #if defined (COLLECT2_HOST_INITIALIZATION)
869   /* Perform system dependent initialization, if necessary.  */
870   COLLECT2_HOST_INITIALIZATION;
871 #endif
872
873 #ifdef SIGCHLD
874   /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
875      receive the signal.  A different setting is inheritable */
876   signal (SIGCHLD, SIG_DFL);
877 #endif
878
879   gcc_init_libintl ();
880
881   /* Do not invoke xcalloc before this point, since locale needs to be
882      set first, in case a diagnostic is issued.  */
883
884   ld1 = (const char **)(ld1_argv = (char **) xcalloc(sizeof (char *), argc+3));
885   ld2 = (const char **)(ld2_argv = (char **) xcalloc(sizeof (char *), argc+10));
886   object = (const char **)(object_lst = (char **) xcalloc(sizeof (char *), argc));
887
888 #ifdef DEBUG
889   debug = 1;
890 #endif
891
892   /* Parse command line early for instances of -debug.  This allows
893      the debug flag to be set before functions like find_a_file()
894      are called.  */
895   {
896     int i;
897     
898     for (i = 1; argv[i] != NULL; i ++)
899       if (! strcmp (argv[i], "-debug"))
900         debug = 1;
901     vflag = debug;
902   }
903
904 #ifndef DEFAULT_A_OUT_NAME
905   output_file = "a.out";
906 #else
907   output_file = DEFAULT_A_OUT_NAME;
908 #endif
909
910   obstack_begin (&temporary_obstack, 0);
911   obstack_begin (&permanent_obstack, 0);
912   temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
913
914   current_demangling_style = auto_demangling;
915   p = getenv ("COLLECT_GCC_OPTIONS");
916   while (p && *p)
917     {
918       const char *q = extract_string (&p);
919       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
920         num_c_args++;
921     }
922   obstack_free (&temporary_obstack, temporary_firstobj);
923
924   /* -fno-exceptions -w */
925   num_c_args += 2;
926
927   c_ptr = (const char **)
928     (c_argv = (char **) xcalloc (sizeof (char *), num_c_args));
929
930   if (argc < 2)
931     fatal ("no arguments");
932
933 #ifdef SIGQUIT
934   if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
935     signal (SIGQUIT, handler);
936 #endif
937   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
938     signal (SIGINT, handler);
939 #ifdef SIGALRM
940   if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
941     signal (SIGALRM, handler);
942 #endif
943 #ifdef SIGHUP
944   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
945     signal (SIGHUP, handler);
946 #endif
947   if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
948     signal (SIGSEGV, handler);
949 #ifdef SIGBUS
950   if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
951     signal (SIGBUS, handler);
952 #endif
953
954   /* Extract COMPILER_PATH and PATH into our prefix list.  */
955   prefix_from_env ("COMPILER_PATH", &cpath);
956   prefix_from_env ("PATH", &path);
957
958   /* Try to discover a valid linker/nm/strip to use.  */
959
960   /* Maybe we know the right file to use (if not cross).  */
961   ld_file_name = 0;
962 #ifdef DEFAULT_LINKER
963   if (access (DEFAULT_LINKER, X_OK) == 0)
964     ld_file_name = DEFAULT_LINKER;
965   if (ld_file_name == 0)
966 #endif
967 #ifdef REAL_LD_FILE_NAME
968   ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
969   if (ld_file_name == 0)
970 #endif
971   /* Search the (target-specific) compiler dirs for ld'.  */
972   ld_file_name = find_a_file (&cpath, real_ld_suffix);
973   /* Likewise for `collect-ld'.  */
974   if (ld_file_name == 0)
975     ld_file_name = find_a_file (&cpath, collect_ld_suffix);
976   /* Search the compiler directories for `ld'.  We have protection against
977      recursive calls in find_a_file.  */
978   if (ld_file_name == 0)
979     ld_file_name = find_a_file (&cpath, ld_suffix);
980   /* Search the ordinary system bin directories
981      for `ld' (if native linking) or `TARGET-ld' (if cross).  */
982   if (ld_file_name == 0)
983     ld_file_name = find_a_file (&path, full_ld_suffix);
984
985 #ifdef REAL_NM_FILE_NAME
986   nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
987   if (nm_file_name == 0)
988 #endif
989   nm_file_name = find_a_file (&cpath, gnm_suffix);
990   if (nm_file_name == 0)
991     nm_file_name = find_a_file (&path, full_gnm_suffix);
992   if (nm_file_name == 0)
993     nm_file_name = find_a_file (&cpath, nm_suffix);
994   if (nm_file_name == 0)
995     nm_file_name = find_a_file (&path, full_nm_suffix);
996
997 #ifdef LDD_SUFFIX
998   ldd_file_name = find_a_file (&cpath, ldd_suffix);
999   if (ldd_file_name == 0)
1000     ldd_file_name = find_a_file (&path, full_ldd_suffix);
1001 #endif
1002
1003 #ifdef REAL_STRIP_FILE_NAME
1004   strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1005   if (strip_file_name == 0)
1006 #endif
1007   strip_file_name = find_a_file (&cpath, gstrip_suffix);
1008   if (strip_file_name == 0)
1009     strip_file_name = find_a_file (&path, full_gstrip_suffix);
1010   if (strip_file_name == 0)
1011     strip_file_name = find_a_file (&cpath, strip_suffix);
1012   if (strip_file_name == 0)
1013     strip_file_name = find_a_file (&path, full_strip_suffix);
1014
1015   /* Determine the full path name of the C compiler to use.  */
1016   c_file_name = getenv ("COLLECT_GCC");
1017   if (c_file_name == 0)
1018     {
1019 #ifdef CROSS_COMPILE
1020       c_file_name = concat (target_machine, "-gcc", NULL);
1021 #else
1022       c_file_name = "gcc";
1023 #endif
1024     }
1025
1026   p = find_a_file (&cpath, c_file_name);
1027
1028   /* Here it should be safe to use the system search path since we should have
1029      already qualified the name of the compiler when it is needed.  */
1030   if (p == 0)
1031     p = find_a_file (&path, c_file_name);
1032
1033   if (p)
1034     c_file_name = p;
1035
1036   *ld1++ = *ld2++ = ld_file_name;
1037
1038   /* Make temp file names.  */
1039   c_file = make_temp_file (".c");
1040   o_file = make_temp_file (".o");
1041 #ifdef COLLECT_EXPORT_LIST
1042   export_file = make_temp_file (".x");
1043 #endif
1044   ldout = make_temp_file (".ld");
1045   *c_ptr++ = c_file_name;
1046   *c_ptr++ = "-x";
1047   *c_ptr++ = "c";
1048   *c_ptr++ = "-c";
1049   *c_ptr++ = "-o";
1050   *c_ptr++ = o_file;
1051
1052 #ifdef COLLECT_EXPORT_LIST
1053   /* Generate a list of directories from LIBPATH.  */
1054   prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1055   /* Add to this list also two standard directories where
1056      AIX loader always searches for libraries.  */
1057   add_prefix (&libpath_lib_dirs, "/lib");
1058   add_prefix (&libpath_lib_dirs, "/usr/lib");
1059 #endif
1060
1061   /* Get any options that the upper GCC wants to pass to the sub-GCC.  
1062
1063      AIX support needs to know if -shared has been specified before
1064      parsing commandline arguments.  */
1065
1066   p = getenv ("COLLECT_GCC_OPTIONS");
1067   while (p && *p)
1068     {
1069       const char *q = extract_string (&p);
1070       if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1071         *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1072       if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1073         *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1074       if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1075         shared_obj = 1;
1076       if (*q == '-' && q[1] == 'B')
1077         {
1078           *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1079           if (q[2] == 0)
1080             {
1081               q = extract_string (&p);
1082               *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1083             }
1084         }
1085     }
1086   obstack_free (&temporary_obstack, temporary_firstobj);
1087   *c_ptr++ = "-fno-exceptions";
1088   *c_ptr++ = "-w";
1089
1090   /* !!! When GCC calls collect2,
1091      it does not know whether it is calling collect2 or ld.
1092      So collect2 cannot meaningfully understand any options
1093      except those ld understands.
1094      If you propose to make GCC pass some other option,
1095      just imagine what will happen if ld is really ld!!!  */
1096
1097   /* Parse arguments.  Remember output file spec, pass the rest to ld.  */
1098   /* After the first file, put in the c++ rt0.  */
1099
1100   first_file = 1;
1101   while ((arg = *++argv) != (char *) 0)
1102     {
1103       *ld1++ = *ld2++ = arg;
1104
1105       if (arg[0] == '-')
1106         {
1107           switch (arg[1])
1108             {
1109 #ifdef COLLECT_EXPORT_LIST
1110             /* We want to disable automatic exports on AIX when user
1111                explicitly puts an export list in command line */
1112             case 'b':
1113               if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1114                 export_flag = 1;
1115               else if (arg[2] == '6' && arg[3] == '4')
1116                 aix64_flag = 1;
1117               break;
1118 #endif
1119
1120             case 'd':
1121               if (!strcmp (arg, "-debug"))
1122                 {
1123                   /* Already parsed.  */
1124                   ld1--;
1125                   ld2--;
1126                 }
1127               break;
1128
1129             case 'l':
1130               if (first_file)
1131                 {
1132                   /* place o_file BEFORE this argument! */
1133                   first_file = 0;
1134                   ld2--;
1135                   *ld2++ = o_file;
1136                   *ld2++ = arg;
1137                 }
1138 #ifdef COLLECT_EXPORT_LIST
1139               {
1140                 /* Resolving full library name.  */
1141                 const char *s = resolve_lib_name (arg+2);
1142
1143                 /* Saving a full library name.  */
1144                 add_to_list (&libs, s);
1145               }
1146 #endif
1147               break;
1148
1149 #ifdef COLLECT_EXPORT_LIST
1150             /* Saving directories where to search for libraries.  */
1151             case 'L':
1152               add_prefix (&cmdline_lib_dirs, arg+2);
1153               break;
1154 #else 
1155 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1156             case 'L':
1157               if (is_in_args (arg, (const char **) ld1_argv, ld1-1))
1158                 --ld1;
1159               break;
1160 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1161 #endif
1162
1163             case 'o':
1164               if (arg[2] == '\0')
1165                 output_file = *ld1++ = *ld2++ = *++argv;
1166               else if (1
1167 #ifdef SWITCHES_NEED_SPACES
1168                        && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1169 #endif
1170                        )
1171
1172                 output_file = &arg[2];
1173               break;
1174
1175             case 'r':
1176               if (arg[2] == '\0')
1177                 rflag = 1;
1178               break;
1179
1180             case 's':
1181               if (arg[2] == '\0' && do_collecting)
1182                 {
1183                   /* We must strip after the nm run, otherwise C++ linking
1184                      will not work.  Thus we strip in the second ld run, or
1185                      else with strip if there is no second ld run.  */
1186                   strip_flag = 1;
1187                   ld1--;
1188                 }
1189               break;
1190
1191             case 'v':
1192               if (arg[2] == '\0')
1193                 vflag = 1;
1194               break;
1195             }
1196         }
1197       else if ((p = strrchr (arg, '.')) != (char *) 0
1198                && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1199                    || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1200                    || strcmp (p, ".obj") == 0))
1201         {
1202           if (first_file)
1203             {
1204               first_file = 0;
1205               if (p[1] == 'o')
1206                 *ld2++ = o_file;
1207               else
1208                 {
1209                   /* place o_file BEFORE this argument! */
1210                   ld2--;
1211                   *ld2++ = o_file;
1212                   *ld2++ = arg;
1213                 }
1214             }
1215           if (p[1] == 'o' || p[1] == 'l')
1216             *object++ = arg;
1217 #ifdef COLLECT_EXPORT_LIST
1218           /* libraries can be specified directly, i.e. without -l flag.  */
1219           else
1220             { 
1221               /* Saving a full library name.  */
1222               add_to_list (&libs, arg);
1223             }
1224 #endif
1225         }
1226     }
1227
1228 #ifdef COLLECT_EXPORT_LIST
1229   /* This is added only for debugging purposes.  */
1230   if (debug)
1231     {
1232       fprintf (stderr, "List of libraries:\n");
1233       dump_list (stderr, "\t", libs.first);
1234     }
1235
1236   /* The AIX linker will discard static constructors in object files if
1237      nothing else in the file is referenced, so look at them first.  */
1238   {
1239       const char **export_object_lst = (const char **)object_lst;
1240
1241       while (export_object_lst < object)
1242         scan_prog_file (*export_object_lst++, PASS_OBJ);
1243   }
1244   {
1245     struct id *list = libs.first;
1246
1247     for (; list; list = list->next)
1248       scan_prog_file (list->name, PASS_FIRST);
1249   }
1250
1251   if (exports.first)
1252     {
1253       char *buf = concat ("-bE:", export_file, NULL);
1254       
1255       *ld1++ = buf;
1256       *ld2++ = buf;
1257
1258       exportf = fopen (export_file, "w");
1259       if (exportf == (FILE *) 0)
1260         fatal_perror ("fopen %s", export_file);
1261       write_aix_file (exportf, exports.first);
1262       if (fclose (exportf))
1263         fatal_perror ("fclose %s", export_file);
1264     }
1265 #endif
1266
1267   *c_ptr++ = c_file;
1268   *c_ptr = *ld1 = *object = (char *) 0;
1269
1270   if (vflag)
1271     {
1272       notice ("collect2 version %s", version_string);
1273 #ifdef TARGET_VERSION
1274       TARGET_VERSION;
1275 #endif
1276       fprintf (stderr, "\n");
1277     }
1278
1279   if (debug)
1280     {
1281       const char *ptr;
1282       fprintf (stderr, "ld_file_name        = %s\n",
1283                (ld_file_name ? ld_file_name : "not found"));
1284       fprintf (stderr, "c_file_name         = %s\n",
1285                (c_file_name ? c_file_name : "not found"));
1286       fprintf (stderr, "nm_file_name        = %s\n",
1287                (nm_file_name ? nm_file_name : "not found"));
1288 #ifdef LDD_SUFFIX
1289       fprintf (stderr, "ldd_file_name       = %s\n",
1290                (ldd_file_name ? ldd_file_name : "not found"));
1291 #endif
1292       fprintf (stderr, "strip_file_name     = %s\n",
1293                (strip_file_name ? strip_file_name : "not found"));
1294       fprintf (stderr, "c_file              = %s\n",
1295                (c_file ? c_file : "not found"));
1296       fprintf (stderr, "o_file              = %s\n",
1297                (o_file ? o_file : "not found"));
1298
1299       ptr = getenv ("COLLECT_GCC_OPTIONS");
1300       if (ptr)
1301         fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1302
1303       ptr = getenv ("COLLECT_GCC");
1304       if (ptr)
1305         fprintf (stderr, "COLLECT_GCC         = %s\n", ptr);
1306
1307       ptr = getenv ("COMPILER_PATH");
1308       if (ptr)
1309         fprintf (stderr, "COMPILER_PATH       = %s\n", ptr);
1310
1311       ptr = getenv (LIBRARY_PATH_ENV);
1312       if (ptr)
1313         fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1314
1315       fprintf (stderr, "\n");
1316     }
1317
1318   /* Load the program, searching all libraries and attempting to provide
1319      undefined symbols from repository information.  */
1320
1321   /* On AIX we do this later.  */
1322 #ifndef COLLECT_EXPORT_LIST
1323   do_tlink (ld1_argv, object_lst);
1324 #endif
1325
1326   /* If -r or they will be run via some other method, do not build the
1327      constructor or destructor list, just return now.  */
1328   if (rflag
1329 #ifndef COLLECT_EXPORT_LIST
1330       || ! do_collecting
1331 #endif
1332       )
1333     {
1334 #ifdef COLLECT_EXPORT_LIST
1335       /* Do the link we avoided above if we are exiting.  */
1336       do_tlink (ld1_argv, object_lst);
1337
1338       /* But make sure we delete the export file we may have created.  */
1339       if (export_file != 0 && export_file[0])
1340         maybe_unlink (export_file);
1341 #endif
1342       maybe_unlink (c_file);
1343       maybe_unlink (o_file);
1344       return 0;
1345     }
1346
1347   /* Examine the namelist with nm and search it for static constructors
1348      and destructors to call.
1349      Write the constructor and destructor tables to a .s file and reload.  */
1350
1351   /* On AIX we already scanned for global constructors/destructors.  */
1352 #ifndef COLLECT_EXPORT_LIST
1353   scan_prog_file (output_file, PASS_FIRST);
1354 #endif
1355
1356 #ifdef SCAN_LIBRARIES
1357   scan_libraries (output_file);
1358 #endif
1359
1360   if (debug)
1361     {
1362       notice ("%d constructor(s) found\n", constructors.number);
1363       notice ("%d destructor(s)  found\n", destructors.number);
1364       notice ("%d frame table(s) found\n", frame_tables.number);
1365     }
1366
1367   if (constructors.number == 0 && destructors.number == 0
1368       && frame_tables.number == 0
1369 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1370       /* If we will be running these functions ourselves, we want to emit
1371          stubs into the shared library so that we do not have to relink
1372          dependent programs when we add static objects.  */
1373       && ! shared_obj
1374 #endif
1375       )
1376     {
1377 #ifdef COLLECT_EXPORT_LIST
1378       /* Do tlink without additional code generation */
1379       do_tlink (ld1_argv, object_lst);
1380 #endif
1381       /* Strip now if it was requested on the command line.  */
1382       if (strip_flag)
1383         {
1384           char **real_strip_argv = (char **) xcalloc (sizeof (char *), 3);
1385           const char ** strip_argv = (const char **) real_strip_argv;
1386           
1387           strip_argv[0] = strip_file_name;
1388           strip_argv[1] = output_file;
1389           strip_argv[2] = (char *) 0;
1390           fork_execute ("strip", real_strip_argv);
1391         }
1392
1393 #ifdef COLLECT_EXPORT_LIST
1394       maybe_unlink (export_file);
1395 #endif
1396       maybe_unlink (c_file);
1397       maybe_unlink (o_file);
1398       return 0;
1399     }
1400
1401   /* Sort ctor and dtor lists by priority.  */
1402   sort_ids (&constructors);
1403   sort_ids (&destructors);
1404
1405   maybe_unlink(output_file);
1406   outf = fopen (c_file, "w");
1407   if (outf == (FILE *) 0)
1408     fatal_perror ("fopen %s", c_file);
1409
1410   write_c_file (outf, c_file);
1411
1412   if (fclose (outf))
1413     fatal_perror ("fclose %s", c_file);
1414
1415   /* Tell the linker that we have initializer and finalizer functions.  */
1416 #ifdef LD_INIT_SWITCH
1417 #ifdef COLLECT_EXPORT_LIST
1418   *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1419 #else
1420   *ld2++ = LD_INIT_SWITCH;
1421   *ld2++ = initname;
1422   *ld2++ = LD_FINI_SWITCH;
1423   *ld2++ = fininame;
1424 #endif
1425 #endif
1426
1427 #ifdef COLLECT_EXPORT_LIST
1428   if (shared_obj)
1429     {
1430       /* If we did not add export flag to link arguments before, add it to
1431          second link phase now.  No new exports should have been added.  */
1432       if (! exports.first)
1433         *ld2++ = concat ("-bE:", export_file, NULL);
1434
1435       add_to_list (&exports, initname);
1436       add_to_list (&exports, fininame);
1437       add_to_list (&exports, "_GLOBAL__DI");
1438       add_to_list (&exports, "_GLOBAL__DD");
1439       exportf = fopen (export_file, "w");
1440       if (exportf == (FILE *) 0)
1441         fatal_perror ("fopen %s", export_file);
1442       write_aix_file (exportf, exports.first);
1443       if (fclose (exportf))
1444         fatal_perror ("fclose %s", export_file);
1445     }
1446 #endif
1447
1448   /* End of arguments to second link phase.  */
1449   *ld2 = (char*) 0;
1450
1451   if (debug)
1452     {
1453       fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1454                output_file, c_file);
1455       write_c_file (stderr, "stderr");
1456       fprintf (stderr, "========== end of c_file\n\n");
1457 #ifdef COLLECT_EXPORT_LIST
1458       fprintf (stderr, "\n========== export_file = %s\n", export_file);
1459       write_aix_file (stderr, exports.first);
1460       fprintf (stderr, "========== end of export_file\n\n");
1461 #endif
1462     }
1463
1464   /* Assemble the constructor and destructor tables.
1465      Link the tables in with the rest of the program.  */
1466
1467   fork_execute ("gcc",  c_argv);
1468 #ifdef COLLECT_EXPORT_LIST
1469   /* On AIX we must call tlink because of possible templates resolution */
1470   do_tlink (ld2_argv, object_lst);
1471 #else
1472   /* Otherwise, simply call ld because tlink is already done */
1473   fork_execute ("ld", ld2_argv);
1474
1475   /* Let scan_prog_file do any final mods (OSF/rose needs this for
1476      constructors/destructors in shared libraries.  */
1477   scan_prog_file (output_file, PASS_SECOND);
1478 #endif 
1479
1480   maybe_unlink (c_file);
1481   maybe_unlink (o_file);
1482
1483 #ifdef COLLECT_EXPORT_LIST
1484   maybe_unlink (export_file);
1485 #endif
1486
1487   return 0;
1488 }
1489
1490 \f
1491 /* Wait for a process to finish, and exit if a non-zero status is found.  */
1492
1493 int
1494 collect_wait (prog)
1495      const char *prog;
1496 {
1497   int status;
1498
1499   pwait (pexecute_pid, &status, 0);
1500   if (status)
1501     {
1502       if (WIFSIGNALED (status))
1503         {
1504           int sig = WTERMSIG (status);
1505           error ("%s terminated with signal %d [%s]%s",
1506                  prog, sig, strsignal(sig),
1507                  status & 0200 ? "" : ", core dumped");
1508           collect_exit (FATAL_EXIT_CODE);
1509         }
1510
1511       if (WIFEXITED (status))
1512         return WEXITSTATUS (status);
1513     }
1514   return 0;
1515 }
1516
1517 static void
1518 do_wait (prog)
1519      const char *prog;
1520 {
1521   int ret = collect_wait (prog);
1522   if (ret != 0)
1523     {
1524       error ("%s returned %d exit status", prog, ret);
1525       collect_exit (ret);
1526     }
1527 }
1528
1529 \f
1530 /* Execute a program, and wait for the reply.  */
1531
1532 void
1533 collect_execute (prog, argv, redir)
1534      const char *prog;
1535      char **argv;
1536      const char *redir;
1537 {
1538   char *errmsg_fmt;
1539   char *errmsg_arg;
1540   int redir_handle = -1;
1541   int stdout_save = -1;
1542   int stderr_save = -1;
1543
1544   if (vflag || debug)
1545     {
1546       char **p_argv;
1547       const char *str;
1548
1549       if (argv[0])
1550         fprintf (stderr, "%s", argv[0]);
1551       else
1552         notice ("[cannot find %s]", prog);
1553
1554       for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1555         fprintf (stderr, " %s", str);
1556
1557       fprintf (stderr, "\n");
1558     }
1559
1560   fflush (stdout);
1561   fflush (stderr);
1562
1563   /* If we cannot find a program we need, complain error.  Do this here
1564      since we might not end up needing something that we could not find.  */
1565
1566   if (argv[0] == 0)
1567     fatal ("cannot find `%s'", prog);
1568
1569   if (redir)
1570     {
1571       /* Open response file.  */
1572       redir_handle = open (redir, O_WRONLY | O_TRUNC | O_CREAT);
1573
1574       /* Duplicate the stdout and stderr file handles
1575          so they can be restored later.  */
1576       stdout_save = dup (STDOUT_FILENO);
1577       if (stdout_save == -1)
1578         fatal_perror ("redirecting stdout: %s", redir);
1579       stderr_save = dup (STDERR_FILENO);
1580       if (stderr_save == -1)
1581         fatal_perror ("redirecting stdout: %s", redir);
1582
1583       /* Redirect stdout & stderr to our response file.  */
1584       dup2 (redir_handle, STDOUT_FILENO);
1585       dup2 (redir_handle, STDERR_FILENO);
1586     }
1587
1588   pexecute_pid = pexecute (argv[0], argv, argv[0], NULL,
1589                            &errmsg_fmt, &errmsg_arg,
1590                            (PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH));
1591
1592   if (redir)
1593     {
1594       /* Restore stdout and stderr to their previous settings.  */
1595       dup2 (stdout_save, STDOUT_FILENO);
1596       dup2 (stderr_save, STDERR_FILENO);
1597
1598       /* Close response file.  */
1599       close (redir_handle);
1600     }
1601
1602  if (pexecute_pid == -1)
1603    fatal_perror (errmsg_fmt, errmsg_arg);
1604 }
1605
1606 static void
1607 fork_execute (prog, argv)
1608      const char *prog;
1609      char **argv;
1610 {
1611   collect_execute (prog, argv, NULL);
1612   do_wait (prog);
1613 }
1614 \f
1615 /* Unlink a file unless we are debugging.  */
1616
1617 static void
1618 maybe_unlink (file)
1619      const char *file;
1620 {
1621   if (!debug)
1622     unlink (file);
1623   else
1624     notice ("[Leaving %s]\n", file);
1625 }
1626
1627 \f
1628 static long sequence_number = 0;
1629
1630 /* Add a name to a linked list.  */
1631
1632 static void
1633 add_to_list (head_ptr, name)
1634      struct head *head_ptr;
1635      const char *name;
1636 {
1637   struct id *newid
1638     = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1639   struct id *p;
1640   strcpy (newid->name, name);
1641
1642   if (head_ptr->first)
1643     head_ptr->last->next = newid;
1644   else
1645     head_ptr->first = newid;
1646
1647   /* Check for duplicate symbols.  */
1648   for (p = head_ptr->first;
1649        strcmp (name, p->name) != 0;
1650        p = p->next)
1651     ;
1652   if (p != newid)
1653     {
1654       head_ptr->last->next = 0;
1655       free (newid);
1656       return;
1657     }
1658
1659   newid->sequence = ++sequence_number;
1660   head_ptr->last = newid;
1661   head_ptr->number++;
1662 }
1663
1664 /* Grab the init priority number from an init function name that
1665    looks like "_GLOBAL_.I.12345.foo".  */
1666
1667 static int
1668 extract_init_priority (name)
1669      const char *name;
1670 {
1671   int pos = 0, pri;
1672
1673   while (name[pos] == '_')
1674     ++pos;
1675   pos += 10; /* strlen ("GLOBAL__X_") */
1676
1677   /* Extract init_p number from ctor/dtor name.  */
1678   pri = atoi (name + pos);
1679   return pri ? pri : DEFAULT_INIT_PRIORITY;
1680 }
1681
1682 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1683    ctors will be run from right to left, dtors from left to right.  */
1684
1685 static void
1686 sort_ids (head_ptr)
1687      struct head *head_ptr;
1688 {
1689   /* id holds the current element to insert.  id_next holds the next
1690      element to insert.  id_ptr iterates through the already sorted elements
1691      looking for the place to insert id.  */
1692   struct id *id, *id_next, **id_ptr;
1693
1694   id = head_ptr->first;
1695
1696   /* We don't have any sorted elements yet.  */
1697   head_ptr->first = NULL;
1698
1699   for (; id; id = id_next)
1700     {
1701       id_next = id->next;
1702       id->sequence = extract_init_priority (id->name);
1703
1704       for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1705         if (*id_ptr == NULL
1706             /* If the sequence numbers are the same, we put the id from the
1707                file later on the command line later in the list.  */
1708             || id->sequence > (*id_ptr)->sequence
1709             /* Hack: do lexical compare, too.
1710             || (id->sequence == (*id_ptr)->sequence
1711                 && strcmp (id->name, (*id_ptr)->name) > 0) */
1712             )
1713           {
1714             id->next = *id_ptr;
1715             *id_ptr = id;
1716             break;
1717           }
1718     }
1719
1720   /* Now set the sequence numbers properly so write_c_file works.  */
1721   for (id = head_ptr->first; id; id = id->next)
1722     id->sequence = ++sequence_number;
1723 }
1724
1725 /* Write: `prefix', the names on list LIST, `suffix'.  */
1726
1727 static void
1728 write_list (stream, prefix, list)
1729      FILE *stream;
1730      const char *prefix;
1731      struct id *list;
1732 {
1733   while (list)
1734     {
1735       fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1736       list = list->next;
1737     }
1738 }
1739
1740 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1741 /* Given a STRING, return nonzero if it occurs in the list in range
1742    [ARGS_BEGIN,ARGS_END).  */
1743
1744 static int
1745 is_in_args (string, args_begin, args_end)
1746      const char *string;
1747      const char **args_begin;
1748      const char **args_end;
1749 {
1750   const char **args_pointer;
1751   for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1752     if (strcmp (string, *args_pointer) == 0)
1753       return 1;
1754   return 0;
1755 }
1756 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1757
1758 #ifdef COLLECT_EXPORT_LIST
1759 /* This function is really used only on AIX, but may be useful.  */
1760 #if 0
1761 static int
1762 is_in_list (prefix, list)
1763      const char *prefix;
1764      struct id *list;
1765 {
1766   while (list)
1767     {
1768       if (!strcmp (prefix, list->name)) return 1;
1769       list = list->next;
1770     }
1771     return 0;
1772 }
1773 #endif
1774 #endif /* COLLECT_EXPORT_LIST */
1775
1776 /* Added for debugging purpose.  */
1777 #ifdef COLLECT_EXPORT_LIST
1778 static void
1779 dump_list (stream, prefix, list)
1780      FILE *stream;
1781      const char *prefix;
1782      struct id *list;
1783 {
1784   while (list)
1785     {
1786       fprintf (stream, "%s%s,\n", prefix, list->name);
1787       list = list->next;
1788     }
1789 }
1790 #endif
1791
1792 #if 0
1793 static void
1794 dump_prefix_list (stream, prefix, list)
1795      FILE *stream;
1796      const char *prefix;
1797      struct prefix_list *list;
1798 {
1799   while (list)
1800     {
1801       fprintf (stream, "%s%s,\n", prefix, list->prefix);
1802       list = list->next;
1803     }
1804 }
1805 #endif
1806
1807 static void
1808 write_list_with_asm (stream, prefix, list)
1809      FILE *stream;
1810      const char *prefix;
1811      struct id *list;
1812 {
1813   while (list)
1814     {
1815       fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1816                prefix, list->sequence, list->name);
1817       list = list->next;
1818     }
1819 }
1820
1821 /* Write out the constructor and destructor tables statically (for a shared
1822    object), along with the functions to execute them.  */
1823
1824 static void
1825 write_c_file_stat (stream, name)
1826      FILE *stream;
1827      const char *name ATTRIBUTE_UNUSED;
1828 {
1829   const char *p, *q;
1830   char *prefix, *r;
1831   int frames = (frame_tables.number > 0);
1832
1833   /* Figure out name of output_file, stripping off .so version.  */
1834   p = strrchr (output_file, '/');
1835   if (p == 0)
1836     p = output_file;
1837   else
1838     p++;
1839   q = p;
1840   while (q)
1841     {
1842       q = strchr (q,'.');
1843       if (q == 0)
1844         {
1845           q = p + strlen (p);
1846           break;
1847         }
1848       else
1849         {
1850           if (strncmp (q, ".so", 3) == 0)
1851             {
1852               q += 3;
1853               break;
1854             }
1855           else
1856             q++;
1857         }
1858     }
1859   /* q points to null at end of the string (or . of the .so version) */
1860   prefix = xmalloc (q - p + 1);
1861   strncpy (prefix, p, q - p);
1862   prefix[q - p] = 0;
1863   for (r = prefix; *r; r++)
1864     if (!ISALNUM ((unsigned char)*r))
1865       *r = '_';
1866   if (debug)
1867     notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1868             output_file, prefix);
1869
1870   initname = concat ("_GLOBAL__FI_", prefix, NULL);
1871   fininame = concat ("_GLOBAL__FD_", prefix, NULL);
1872
1873   free (prefix);
1874
1875   /* Write the tables as C code  */
1876
1877   fprintf (stream, "static int count;\n");
1878   fprintf (stream, "typedef void entry_pt();\n");
1879   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1880
1881   if (frames)
1882     {
1883       write_list_with_asm (stream, "extern void *", frame_tables.first);
1884
1885       fprintf (stream, "\tstatic void *frame_table[] = {\n");
1886       write_list (stream, "\t\t&", frame_tables.first);
1887       fprintf (stream, "\t0\n};\n");
1888
1889       /* This must match what's in frame.h.  */
1890       fprintf (stream, "struct object {\n");
1891       fprintf (stream, "  void *pc_begin;\n");
1892       fprintf (stream, "  void *pc_end;\n");
1893       fprintf (stream, "  void *fde_begin;\n");
1894       fprintf (stream, "  void *fde_array;\n");
1895       fprintf (stream, "  __SIZE_TYPE__ count;\n");
1896       fprintf (stream, "  struct object *next;\n");
1897       fprintf (stream, "};\n");
1898
1899       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1900       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1901
1902       fprintf (stream, "static void reg_frame () {\n");
1903       fprintf (stream, "\tstatic struct object ob;\n");
1904       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1905       fprintf (stream, "\t}\n");
1906
1907       fprintf (stream, "static void dereg_frame () {\n");
1908       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1909       fprintf (stream, "\t}\n");
1910     }
1911
1912   fprintf (stream, "void %s() {\n", initname);
1913   if (constructors.number > 0 || frames)
1914     {
1915       fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1916       write_list (stream, "\t\t", constructors.first);
1917       if (frames)
1918         fprintf (stream, "\treg_frame,\n");
1919       fprintf (stream, "\t};\n");
1920       fprintf (stream, "\tentry_pt **p;\n");
1921       fprintf (stream, "\tif (count++ != 0) return;\n");
1922       fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1923       fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1924     }
1925   else
1926     fprintf (stream, "\t++count;\n");
1927   fprintf (stream, "}\n");
1928   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1929   fprintf (stream, "void %s() {\n", fininame);
1930   if (destructors.number > 0 || frames)
1931     {
1932       fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1933       write_list (stream, "\t\t", destructors.first);
1934       if (frames)
1935         fprintf (stream, "\tdereg_frame,\n");
1936       fprintf (stream, "\t};\n");
1937       fprintf (stream, "\tentry_pt **p;\n");
1938       fprintf (stream, "\tif (--count != 0) return;\n");
1939       fprintf (stream, "\tp = dtors;\n");
1940       fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1941                destructors.number + frames);
1942     }
1943   fprintf (stream, "}\n");
1944
1945   if (shared_obj)
1946     {
1947       fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
1948       fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
1949     }
1950 }
1951
1952 /* Write the constructor/destructor tables.  */
1953
1954 #ifndef LD_INIT_SWITCH
1955 static void
1956 write_c_file_glob (stream, name)
1957      FILE *stream;
1958      const char *name ATTRIBUTE_UNUSED;
1959 {
1960   /* Write the tables as C code  */
1961
1962   int frames = (frame_tables.number > 0);
1963
1964   fprintf (stream, "typedef void entry_pt();\n\n");
1965     
1966   write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1967
1968   if (frames)
1969     {
1970       write_list_with_asm (stream, "extern void *", frame_tables.first);
1971
1972       fprintf (stream, "\tstatic void *frame_table[] = {\n");
1973       write_list (stream, "\t\t&", frame_tables.first);
1974       fprintf (stream, "\t0\n};\n");
1975
1976       /* This must match what's in frame.h.  */
1977       fprintf (stream, "struct object {\n");
1978       fprintf (stream, "  void *pc_begin;\n");
1979       fprintf (stream, "  void *pc_end;\n");
1980       fprintf (stream, "  void *fde_begin;\n");
1981       fprintf (stream, "  void *fde_array;\n");
1982       fprintf (stream, "  __SIZE_TYPE__ count;\n");
1983       fprintf (stream, "  struct object *next;\n");
1984       fprintf (stream, "};\n");
1985
1986       fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1987       fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1988
1989       fprintf (stream, "static void reg_frame () {\n");
1990       fprintf (stream, "\tstatic struct object ob;\n");
1991       fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1992       fprintf (stream, "\t}\n");
1993
1994       fprintf (stream, "static void dereg_frame () {\n");
1995       fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1996       fprintf (stream, "\t}\n");
1997     }
1998
1999   fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2000   fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2001   write_list (stream, "\t", constructors.first);
2002   if (frames)
2003     fprintf (stream, "\treg_frame,\n");
2004   fprintf (stream, "\t0\n};\n\n");
2005
2006   write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2007
2008   fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2009   fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2010   write_list (stream, "\t", destructors.first);
2011   if (frames)
2012     fprintf (stream, "\tdereg_frame,\n");
2013   fprintf (stream, "\t0\n};\n\n");
2014
2015   fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2016   fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2017 }
2018 #endif /* ! LD_INIT_SWITCH */
2019
2020 static void
2021 write_c_file (stream, name)
2022      FILE *stream;
2023      const char *name;
2024 {
2025   fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2026 #ifndef LD_INIT_SWITCH
2027   if (! shared_obj)
2028     write_c_file_glob (stream, name);
2029   else
2030 #endif
2031     write_c_file_stat (stream, name);
2032   fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2033 }
2034
2035 #ifdef COLLECT_EXPORT_LIST
2036 static void
2037 write_aix_file (stream, list)
2038      FILE *stream;
2039      struct id *list;
2040 {
2041   for (; list; list = list->next)
2042     {
2043       fputs (list->name, stream);
2044       putc ('\n', stream);
2045     }
2046 }
2047 #endif
2048 \f
2049 #ifdef OBJECT_FORMAT_NONE
2050
2051 /* Generic version to scan the name list of the loaded program for
2052    the symbols g++ uses for static constructors and destructors.
2053
2054    The constructor table begins at __CTOR_LIST__ and contains a count
2055    of the number of pointers (or -1 if the constructors are built in a
2056    separate section by the linker), followed by the pointers to the
2057    constructor functions, terminated with a null pointer.  The
2058    destructor table has the same format, and begins at __DTOR_LIST__.  */
2059
2060 static void
2061 scan_prog_file (prog_name, which_pass)
2062      const char *prog_name;
2063      enum pass which_pass;
2064 {
2065   void (*int_handler) PARAMS ((int));
2066   void (*quit_handler) PARAMS ((int));
2067   char *real_nm_argv[4];
2068   const char **nm_argv = (const char **) real_nm_argv;
2069   int pid;
2070   int argc = 0;
2071   int pipe_fd[2];
2072   char *p, buf[1024];
2073   FILE *inf;
2074
2075   if (which_pass == PASS_SECOND)
2076     return;
2077
2078   /* If we do not have an `nm', complain.  */
2079   if (nm_file_name == 0)
2080     fatal ("cannot find `nm'");
2081
2082   nm_argv[argc++] = nm_file_name;
2083   if (NM_FLAGS[0] != '\0')
2084     nm_argv[argc++] = NM_FLAGS;
2085
2086   nm_argv[argc++] = prog_name;
2087   nm_argv[argc++] = (char *) 0;
2088
2089   if (pipe (pipe_fd) < 0)
2090     fatal_perror ("pipe");
2091
2092   inf = fdopen (pipe_fd[0], "r");
2093   if (inf == (FILE *) 0)
2094     fatal_perror ("fdopen");
2095
2096   /* Trace if needed.  */
2097   if (vflag)
2098     {
2099       const char **p_argv;
2100       const char *str;
2101
2102       for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2103         fprintf (stderr, " %s", str);
2104
2105       fprintf (stderr, "\n");
2106     }
2107
2108   fflush (stdout);
2109   fflush (stderr);
2110
2111   /* Spawn child nm on pipe */
2112   pid = vfork ();
2113   if (pid == -1)
2114     fatal_perror (VFORK_STRING);
2115
2116   if (pid == 0)                 /* child context */
2117     {
2118       /* setup stdout */
2119       if (dup2 (pipe_fd[1], 1) < 0)
2120         fatal_perror ("dup2 %d 1", pipe_fd[1]);
2121
2122       if (close (pipe_fd[0]) < 0)
2123         fatal_perror ("close %d", pipe_fd[0]);
2124
2125       if (close (pipe_fd[1]) < 0)
2126         fatal_perror ("close %d", pipe_fd[1]);
2127
2128       execv (nm_file_name, real_nm_argv);
2129       fatal_perror ("execvp %s", nm_file_name);
2130     }
2131
2132   /* Parent context from here on.  */
2133   int_handler  = (void (*) PARAMS ((int))) signal (SIGINT,  SIG_IGN);
2134 #ifdef SIGQUIT
2135   quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2136 #endif
2137
2138   if (close (pipe_fd[1]) < 0)
2139     fatal_perror ("close %d", pipe_fd[1]);
2140
2141   if (debug)
2142     fprintf (stderr, "\nnm output with constructors/destructors.\n");
2143
2144   /* Read each line of nm output.  */
2145   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2146     {
2147       int ch, ch2;
2148       char *name, *end;
2149
2150       /* If it contains a constructor or destructor name, add the name
2151          to the appropriate list.  */
2152
2153       for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2154         if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2155           break;
2156
2157       if (ch != '_')
2158         continue;
2159   
2160       name = p;
2161       /* Find the end of the symbol name.
2162          Do not include `|', because Encore nm can tack that on the end.  */
2163       for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2164            end++)
2165         continue;
2166
2167
2168       *end = '\0';
2169       switch (is_ctor_dtor (name))
2170         {
2171         case 1:
2172           if (which_pass != PASS_LIB)
2173             add_to_list (&constructors, name);
2174           break;
2175
2176         case 2:
2177           if (which_pass != PASS_LIB)
2178             add_to_list (&destructors, name);
2179           break;
2180
2181         case 3:
2182           if (which_pass != PASS_LIB)
2183             fatal ("init function found in object %s", prog_name);
2184 #ifndef LD_INIT_SWITCH
2185           add_to_list (&constructors, name);
2186 #endif
2187           break;
2188
2189         case 4:
2190           if (which_pass != PASS_LIB)
2191             fatal ("fini function found in object %s", prog_name);
2192 #ifndef LD_FINI_SWITCH
2193           add_to_list (&destructors, name);
2194 #endif
2195           break;
2196
2197         case 5:
2198           if (which_pass != PASS_LIB)
2199             add_to_list (&frame_tables, name);
2200           break;
2201
2202         default:                /* not a constructor or destructor */
2203           continue;
2204         }
2205
2206       if (debug)
2207         fprintf (stderr, "\t%s\n", buf);
2208     }
2209
2210   if (debug)
2211     fprintf (stderr, "\n");
2212
2213   if (fclose (inf) != 0)
2214     fatal_perror ("fclose");
2215
2216   do_wait (nm_file_name);
2217
2218   signal (SIGINT,  int_handler);
2219 #ifdef SIGQUIT
2220   signal (SIGQUIT, quit_handler);
2221 #endif
2222 }
2223
2224 #if SUNOS4_SHARED_LIBRARIES
2225
2226 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2227    that the output file depends upon and their initialization/finalization
2228    routines, if any.  */
2229
2230 #include <a.out.h>
2231 #include <fcntl.h>
2232 #include <link.h>
2233 #include <sys/mman.h>
2234 #include <sys/param.h>
2235 #include <unistd.h>
2236 #include <sys/dir.h>
2237
2238 /* pointers to the object file */
2239 unsigned object;        /* address of memory mapped file */
2240 unsigned objsize;       /* size of memory mapped to file */
2241 char * code;            /* pointer to code segment */
2242 char * data;            /* pointer to data segment */
2243 struct nlist *symtab;   /* pointer to symbol table */
2244 struct link_dynamic *ld;
2245 struct link_dynamic_2 *ld_2;
2246 struct head libraries;
2247
2248 /* Map the file indicated by NAME into memory and store its address.  */
2249
2250 static void mapfile                     PARAMS ((const char *));
2251
2252 static void
2253 mapfile (name)
2254      const char *name;
2255 {
2256   int fp;
2257   struct stat s;
2258   if ((fp = open (name, O_RDONLY)) == -1)
2259     fatal ("unable to open file '%s'", name);
2260   if (fstat (fp, &s) == -1)
2261     fatal ("unable to stat file '%s'", name);
2262
2263   objsize = s.st_size;
2264   object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2265                             fp, 0);
2266   if (object == (unsigned)-1)
2267     fatal ("unable to mmap file '%s'", name);
2268
2269   close (fp);
2270 }
2271
2272 /* Helpers for locatelib.  */
2273
2274 static const char *libname;
2275
2276 static int libselect                    PARAMS ((struct direct *));
2277
2278 static int
2279 libselect (d)
2280      struct direct *d;
2281 {
2282   return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2283 }
2284
2285 /* If one file has an additional numeric extension past LIBNAME, then put
2286    that one first in the sort.  If both files have additional numeric
2287    extensions, then put the one with the higher number first in the sort.
2288
2289    We must verify that the extension is numeric, because Sun saves the
2290    original versions of patched libraries with a .FCS extension.  Files with
2291    invalid extensions must go last in the sort, so that they will not be used.  */
2292 static int libcompare           PARAMS ((struct direct **, struct direct **));
2293
2294 static int
2295 libcompare (d1, d2)
2296      struct direct **d1, **d2;
2297 {
2298   int i1, i2 = strlen (libname);
2299   char *e1 = (*d1)->d_name + i2;
2300   char *e2 = (*d2)->d_name + i2;
2301
2302   while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2303          && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2304     {
2305       ++e1;
2306       ++e2;
2307       i1 = strtol (e1, &e1, 10);
2308       i2 = strtol (e2, &e2, 10);
2309       if (i1 != i2)
2310         return i1 - i2;
2311     }
2312
2313   if (*e1)
2314     {
2315       /* It has a valid numeric extension, prefer this one.  */
2316       if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2317         return 1;
2318       /* It has an invalid numeric extension, must prefer the other one.  */
2319       else
2320         return -1;
2321     }
2322   else if (*e2)
2323     {
2324       /* It has a valid numeric extension, prefer this one.  */
2325       if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2326         return -1;
2327       /* It has an invalid numeric extension, must prefer the other one.  */
2328       else
2329         return 1;
2330     }
2331   else
2332     return 0;
2333 }
2334
2335 /* Given the name NAME of a dynamic dependency, find its pathname and add
2336    it to the list of libraries.  */
2337 static void locatelib                   PARAMS ((const char *));
2338
2339 static void
2340 locatelib (name)
2341      const char *name;
2342 {
2343   static const char **l;
2344   static int cnt;
2345   char buf[MAXPATHLEN];
2346   char *p, *q;
2347   const char **pp;
2348
2349   if (l == 0)
2350     {
2351       char *ld_rules;
2352       char *ldr = 0;
2353       /* counting elements in array, need 1 extra for null */
2354       cnt = 1;  
2355       ld_rules = (char *) (ld_2->ld_rules + code);
2356       if (ld_rules)
2357         {
2358           cnt++;
2359           for (; *ld_rules != 0; ld_rules++)
2360             if (*ld_rules == ':')
2361               cnt++;
2362           ld_rules = (char *) (ld_2->ld_rules + code);
2363           ldr = xstrdup (ld_rules);
2364         }
2365       p = getenv ("LD_LIBRARY_PATH");
2366       q = 0;
2367       if (p)
2368         {
2369           cnt++;
2370           for (q = p ; *q != 0; q++)
2371             if (*q == ':')
2372               cnt++;
2373           q = xstrdup (p);
2374         }
2375       l = (const char **) xmalloc ((cnt + 3) * sizeof (char *));
2376       pp = l;
2377       if (ldr)
2378         {
2379           *pp++ = ldr;
2380           for (; *ldr != 0; ldr++) 
2381             if (*ldr == ':')
2382               {
2383                 *ldr++ = 0;
2384                 *pp++ = ldr;
2385               }
2386         }
2387       if (q)
2388         {
2389           *pp++ = q;
2390           for (; *q != 0; q++) 
2391             if (*q == ':')
2392               {
2393                 *q++ = 0;
2394                 *pp++ = q;
2395               }
2396         }
2397       /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2398       *pp++ = "/lib";
2399       *pp++ = "/usr/lib";
2400       *pp++ = "/usr/local/lib";
2401       *pp = 0;
2402     }
2403   libname = name;
2404   for (pp = l; *pp != 0 ; pp++)
2405     {
2406       struct direct **namelist;
2407       int entries;
2408       if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2409         {
2410           sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2411           add_to_list (&libraries, buf);
2412           if (debug)
2413             fprintf (stderr, "%s\n", buf);
2414           break;
2415         }
2416     }
2417   if (*pp == 0)
2418     {
2419       if (debug)
2420         notice ("not found\n");
2421       else
2422         fatal ("dynamic dependency %s not found", name);
2423     }
2424 }
2425
2426 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2427    that it depends upon and any constructors or destructors they contain.  */
2428
2429 static void 
2430 scan_libraries (prog_name)
2431      const char *prog_name;
2432 {
2433   struct exec *header;
2434   char *base;
2435   struct link_object *lo;
2436   char buff[MAXPATHLEN];
2437   struct id *list;
2438
2439   mapfile (prog_name);
2440   header = (struct exec *)object;
2441   if (N_BADMAG (*header))
2442     fatal ("bad magic number in file '%s'", prog_name);
2443   if (header->a_dynamic == 0)
2444     return;
2445
2446   code = (char *) (N_TXTOFF (*header) + (long) header);
2447   data = (char *) (N_DATOFF (*header) + (long) header);
2448   symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2449
2450   if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2451     {
2452       /* shared object */
2453       ld = (struct link_dynamic *) (symtab->n_value + code);
2454       base = code;
2455     }
2456   else
2457     {
2458       /* executable */
2459       ld = (struct link_dynamic *) data;
2460       base = code-PAGSIZ;
2461     }
2462
2463   if (debug)
2464     notice ("dynamic dependencies.\n");
2465
2466   ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2467   for (lo = (struct link_object *) ld_2->ld_need; lo;
2468        lo = (struct link_object *) lo->lo_next)
2469     {
2470       char *name;
2471       lo = (struct link_object *) ((long) lo + code);
2472       name = (char *) (code + lo->lo_name);
2473       if (lo->lo_library)
2474         {
2475           if (debug)
2476             fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2477           sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2478           locatelib (buff);
2479         }
2480       else
2481         {
2482           if (debug)
2483             fprintf (stderr, "\t%s\n", name);
2484           add_to_list (&libraries, name);
2485         }
2486     }
2487
2488   if (debug)
2489     fprintf (stderr, "\n");
2490
2491   /* now iterate through the library list adding their symbols to
2492      the list.  */
2493   for (list = libraries.first; list; list = list->next)
2494     scan_prog_file (list->name, PASS_LIB);
2495 }
2496
2497 #else  /* SUNOS4_SHARED_LIBRARIES */
2498 #ifdef LDD_SUFFIX
2499
2500 /* Use the List Dynamic Dependencies program to find shared libraries that
2501    the output file depends upon and their initialization/finalization
2502    routines, if any.  */
2503
2504 static void 
2505 scan_libraries (prog_name)
2506      const char *prog_name;
2507 {
2508   static struct head libraries;         /* list of shared libraries found */
2509   struct id *list;
2510   void (*int_handler) PARAMS ((int));
2511   void (*quit_handler) PARAMS ((int));
2512   char *real_ldd_argv[4];
2513   const char **ldd_argv = (const char **) real_ldd_argv;
2514   int pid;
2515   int argc = 0;
2516   int pipe_fd[2];
2517   char buf[1024];
2518   FILE *inf;
2519
2520   /* If we do not have an `ldd', complain.  */
2521   if (ldd_file_name == 0)
2522     {
2523       error ("cannot find `ldd'");
2524       return;
2525     }
2526
2527   ldd_argv[argc++] = ldd_file_name;
2528   ldd_argv[argc++] = prog_name;
2529   ldd_argv[argc++] = (char *) 0;
2530
2531   if (pipe (pipe_fd) < 0)
2532     fatal_perror ("pipe");
2533
2534   inf = fdopen (pipe_fd[0], "r");
2535   if (inf == (FILE *) 0)
2536     fatal_perror ("fdopen");
2537
2538   /* Trace if needed.  */
2539   if (vflag)
2540     {
2541       const char **p_argv;
2542       const char *str;
2543
2544       for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2545         fprintf (stderr, " %s", str);
2546
2547       fprintf (stderr, "\n");
2548     }
2549
2550   fflush (stdout);
2551   fflush (stderr);
2552
2553   /* Spawn child ldd on pipe */
2554   pid = vfork ();
2555   if (pid == -1)
2556     fatal_perror (VFORK_STRING);
2557
2558   if (pid == 0)                 /* child context */
2559     {
2560       /* setup stdout */
2561       if (dup2 (pipe_fd[1], 1) < 0)
2562         fatal_perror ("dup2 %d 1", pipe_fd[1]);
2563
2564       if (close (pipe_fd[0]) < 0)
2565         fatal_perror ("close %d", pipe_fd[0]);
2566
2567       if (close (pipe_fd[1]) < 0)
2568         fatal_perror ("close %d", pipe_fd[1]);
2569
2570       execv (ldd_file_name, real_ldd_argv);
2571       fatal_perror ("execv %s", ldd_file_name);
2572     }
2573
2574   /* Parent context from here on.  */
2575   int_handler  = (void (*) PARAMS ((int))) signal (SIGINT,  SIG_IGN);
2576 #ifdef SIGQUIT
2577   quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2578 #endif
2579
2580   if (close (pipe_fd[1]) < 0)
2581     fatal_perror ("close %d", pipe_fd[1]);
2582
2583   if (debug)
2584     notice ("\nldd output with constructors/destructors.\n");
2585
2586   /* Read each line of ldd output.  */
2587   while (fgets (buf, sizeof buf, inf) != (char *) 0)
2588     {
2589       int ch2;
2590       char *name, *end, *p = buf;
2591
2592       /* Extract names of libraries and add to list.  */
2593       PARSE_LDD_OUTPUT (p);
2594       if (p == 0)
2595         continue;
2596
2597       name = p;
2598       if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2599         fatal ("dynamic dependency %s not found", buf);
2600
2601       /* Find the end of the symbol name.  */
2602       for (end = p; 
2603            (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2604            end++)
2605         continue;
2606       *end = '\0';
2607
2608       if (access (name, R_OK) == 0)
2609         add_to_list (&libraries, name);
2610       else
2611         fatal ("unable to open dynamic dependency '%s'", buf);
2612
2613       if (debug)
2614         fprintf (stderr, "\t%s\n", buf);
2615     }
2616   if (debug)
2617     fprintf (stderr, "\n");
2618
2619   if (fclose (inf) != 0)
2620     fatal_perror ("fclose");
2621
2622   do_wait (ldd_file_name);
2623
2624   signal (SIGINT,  int_handler);
2625 #ifdef SIGQUIT
2626   signal (SIGQUIT, quit_handler);
2627 #endif
2628
2629   /* now iterate through the library list adding their symbols to
2630      the list.  */
2631   for (list = libraries.first; list; list = list->next)
2632     scan_prog_file (list->name, PASS_LIB);
2633 }
2634
2635 #endif /* LDD_SUFFIX */
2636 #endif /* SUNOS4_SHARED_LIBRARIES */
2637
2638 #endif /* OBJECT_FORMAT_NONE */
2639
2640 \f
2641 /*
2642  * COFF specific stuff.
2643  */
2644
2645 #ifdef OBJECT_FORMAT_COFF
2646
2647 #if defined(EXTENDED_COFF)
2648
2649 #   define GCC_SYMBOLS(X)       (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2650 #   define GCC_SYMENT           SYMR
2651 #   define GCC_OK_SYMBOL(X)     ((X).st == stProc || (X).st == stGlobal)
2652 #   define GCC_SYMINC(X)        (1)
2653 #   define GCC_SYMZERO(X)       (SYMHEADER(X).isymMax)
2654 #   define GCC_CHECK_HDR(X)     (PSYMTAB(X) != 0)
2655
2656 #else
2657
2658 #   define GCC_SYMBOLS(X)       (HEADER(ldptr).f_nsyms)
2659 #   define GCC_SYMENT           SYMENT
2660 #   define GCC_OK_SYMBOL(X) \
2661      (((X).n_sclass == C_EXT) && \
2662       ((X).n_scnum > N_UNDEF) && \
2663       (aix64_flag \
2664        || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2665            || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2666 #   define GCC_UNDEF_SYMBOL(X) \
2667      (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2668 #   define GCC_SYMINC(X)        ((X).n_numaux+1)
2669 #   define GCC_SYMZERO(X)       0
2670
2671 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2672 #ifdef _AIX51
2673 #   define GCC_CHECK_HDR(X) \
2674      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2675       || (HEADER (X).f_magic == 0767 && aix64_flag))
2676 #else
2677 #   define GCC_CHECK_HDR(X) \
2678      ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2679       || (HEADER (X).f_magic == 0757 && aix64_flag))
2680 #endif
2681
2682 #endif
2683
2684 extern char *ldgetname ();
2685
2686 /* COFF version to scan the name list of the loaded program for
2687    the symbols g++ uses for static constructors and destructors.
2688
2689    The constructor table begins at __CTOR_LIST__ and contains a count
2690    of the number of pointers (or -1 if the constructors are built in a
2691    separate section by the linker), followed by the pointers to the
2692    constructor functions, terminated with a null pointer.  The
2693    destructor table has the same format, and begins at __DTOR_LIST__.  */
2694
2695 static void
2696 scan_prog_file (prog_name, which_pass)
2697      const char *prog_name;
2698      enum pass which_pass;
2699 {
2700   LDFILE *ldptr = NULL;
2701   int sym_index, sym_count;
2702   int is_shared = 0;
2703
2704   if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2705     return;
2706
2707 #ifdef COLLECT_EXPORT_LIST
2708   /* We do not need scanning for some standard C libraries.  */
2709   if (which_pass == PASS_FIRST && ignore_library (prog_name))
2710     return;
2711
2712   /* On AIX we have a loop, because there is not much difference
2713      between an object and an archive. This trick allows us to
2714      eliminate scan_libraries() function.  */
2715   do
2716     {
2717 #endif
2718       /* Some platforms (e.g. OSF4) declare ldopen as taking a
2719          non-const char * filename parameter, even though it will not
2720          modify that string.  So we must cast away const-ness here,
2721          which will cause -Wcast-qual to burp.  */
2722       if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2723         {
2724           if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2725             fatal ("%s: not a COFF file", prog_name);
2726
2727           if (GCC_CHECK_HDR (ldptr))
2728             {
2729               sym_count = GCC_SYMBOLS (ldptr);
2730               sym_index = GCC_SYMZERO (ldptr);
2731
2732 #ifdef COLLECT_EXPORT_LIST
2733               /* Is current archive member a shared object?  */
2734               is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2735 #endif
2736
2737               while (sym_index < sym_count)
2738                 {
2739                   GCC_SYMENT symbol;
2740
2741                   if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2742                     break;
2743                   sym_index += GCC_SYMINC (symbol);
2744
2745                   if (GCC_OK_SYMBOL (symbol))
2746                     {
2747                       char *name;
2748
2749                       if ((name = ldgetname (ldptr, &symbol)) == NULL)
2750                         continue;               /* should never happen */
2751
2752 #ifdef XCOFF_DEBUGGING_INFO
2753                       /* All AIX function names have a duplicate entry
2754                          beginning with a dot.  */
2755                       if (*name == '.')
2756                         ++name;
2757 #endif
2758
2759                       switch (is_ctor_dtor (name))
2760                         {
2761                         case 1:
2762                           if (! is_shared)
2763                             add_to_list (&constructors, name);
2764 #ifdef COLLECT_EXPORT_LIST
2765                           if (which_pass == PASS_OBJ)
2766                             add_to_list (&exports, name);
2767 #endif
2768                           break;
2769
2770                         case 2:
2771                           if (! is_shared)
2772                             add_to_list (&destructors, name);
2773 #ifdef COLLECT_EXPORT_LIST
2774                           if (which_pass == PASS_OBJ)
2775                             add_to_list (&exports, name);
2776 #endif
2777                           break;
2778
2779 #ifdef COLLECT_EXPORT_LIST
2780                         case 3:
2781 #ifndef LD_INIT_SWITCH
2782                           if (is_shared)
2783                             add_to_list (&constructors, name);
2784 #endif
2785                           break;
2786
2787                         case 4:
2788 #ifndef LD_INIT_SWITCH
2789                           if (is_shared)
2790                             add_to_list (&destructors, name);
2791 #endif
2792                           break;
2793 #endif
2794
2795                         case 5:
2796                           if (! is_shared)
2797                             add_to_list (&frame_tables, name);
2798 #ifdef COLLECT_EXPORT_LIST
2799                           if (which_pass == PASS_OBJ)
2800                             add_to_list (&exports, name);
2801 #endif
2802                           break;
2803
2804                         default:        /* not a constructor or destructor */
2805 #ifdef COLLECT_EXPORT_LIST
2806                           /* If we are building a shared object on AIX we need
2807                              to explicitly export all global symbols.  */
2808                           if (shared_obj) 
2809                             {
2810                               if (which_pass == PASS_OBJ && (! export_flag))
2811                                 add_to_list (&exports, name);
2812                             }
2813 #endif
2814                           continue;
2815                         }
2816
2817                       if (debug)
2818 #if !defined(EXTENDED_COFF)
2819                         fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2820                                  symbol.n_scnum, symbol.n_sclass,
2821                                  (symbol.n_type ? "0" : ""), symbol.n_type,
2822                                  name);
2823 #else
2824                         fprintf (stderr,
2825                                  "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2826                                  symbol.iss, (long) symbol.value, symbol.index, name);
2827 #endif
2828                     }
2829                 }
2830             }
2831 #ifdef COLLECT_EXPORT_LIST
2832           else
2833             {
2834               /* If archive contains both 32-bit and 64-bit objects,
2835                  we want to skip objects in other mode so mismatch normal.  */
2836               if (debug)
2837                 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2838                          prog_name, HEADER (ldptr).f_magic, aix64_flag);
2839             }
2840 #endif
2841         }
2842       else
2843         {
2844           fatal ("%s: cannot open as COFF file", prog_name);
2845         }
2846 #ifdef COLLECT_EXPORT_LIST
2847       /* On AIX loop continues while there are more members in archive.  */
2848     }
2849   while (ldclose (ldptr) == FAILURE);
2850 #else
2851   /* Otherwise we simply close ldptr.  */
2852   (void) ldclose(ldptr);
2853 #endif
2854 }
2855
2856
2857 #ifdef COLLECT_EXPORT_LIST
2858 /* Given a library name without "lib" prefix, this function
2859    returns a full library name including a path.  */
2860 static char *
2861 resolve_lib_name (name)
2862      const char *name;
2863 {
2864   char *lib_buf;
2865   int i, j, l = 0;
2866
2867   for (i = 0; libpaths[i]; i++)
2868     if (libpaths[i]->max_len > l)
2869       l = libpaths[i]->max_len;
2870
2871   lib_buf = xmalloc (l + strlen(name) + 10);
2872
2873   for (i = 0; libpaths[i]; i++)
2874     {
2875       struct prefix_list *list = libpaths[i]->plist;
2876       for (; list; list = list->next)
2877         {
2878           /* The following lines are needed because path_prefix list
2879              may contain directories both with trailing '/' and
2880              without it.  */
2881           const char *p = "";
2882           if (list->prefix[strlen(list->prefix)-1] != '/')
2883             p = "/";
2884           for (j = 0; libexts[j]; j++)
2885             {
2886               sprintf (lib_buf, "%s%slib%s.%s",
2887                        list->prefix, p, name, libexts[j]);
2888 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2889               if (file_exists (lib_buf))
2890                 {
2891 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2892                   return (lib_buf);
2893                 }
2894             }
2895         }
2896     }
2897   if (debug)
2898     fprintf (stderr, "not found\n");
2899   else
2900     fatal ("library lib%s not found", name);
2901   return (NULL);
2902 }
2903
2904 /* Array of standard AIX libraries which should not
2905    be scanned for ctors/dtors.  */
2906 static const char *const aix_std_libs[] = {
2907   "/unix",
2908   "/lib/libc.a",
2909   "/lib/libm.a",
2910   "/lib/libc_r.a",
2911   "/lib/libm_r.a",
2912   "/usr/lib/libc.a",
2913   "/usr/lib/libm.a",
2914   "/usr/lib/libc_r.a",
2915   "/usr/lib/libm_r.a",
2916   "/usr/lib/threads/libc.a",
2917   "/usr/ccs/lib/libc.a",
2918   "/usr/ccs/lib/libm.a",
2919   "/usr/ccs/lib/libc_r.a",
2920   "/usr/ccs/lib/libm_r.a",
2921   NULL
2922 };
2923
2924 /* This function checks the filename and returns 1
2925    if this name matches the location of a standard AIX library.  */
2926 static int
2927 ignore_library (name)
2928      const char *name;
2929 {
2930   const char *const *p = &aix_std_libs[0];
2931   while (*p++ != NULL)
2932     if (! strcmp (name, *p)) return 1;
2933   return 0;
2934 }
2935 #endif
2936
2937 #endif /* OBJECT_FORMAT_COFF */
2938
2939 \f
2940 /*
2941  * OSF/rose specific stuff.
2942  */
2943
2944 #ifdef OBJECT_FORMAT_ROSE
2945
2946 /* Union of the various load commands */
2947
2948 typedef union load_union
2949 {
2950   ldc_header_t                  hdr;    /* common header */
2951   load_cmd_map_command_t        map;    /* map indexing other load cmds */
2952   interpreter_command_t         iprtr;  /* interpreter pathname */
2953   strings_command_t             str;    /* load commands strings section */
2954   region_command_t              region; /* region load command */
2955   reloc_command_t               reloc;  /* relocation section */
2956   package_command_t             pkg;    /* package load command */
2957   symbols_command_t             sym;    /* symbol sections */
2958   entry_command_t               ent;    /* program start section */
2959   gen_info_command_t            info;   /* object information */
2960   func_table_command_t          func;   /* function constructors/destructors */
2961 } load_union_t;
2962
2963 /* Structure to point to load command and data section in memory.  */
2964
2965 typedef struct load_all
2966 {
2967   load_union_t *load;                   /* load command */
2968   char *section;                        /* pointer to section */
2969 } load_all_t;
2970
2971 /* Structure to contain information about a file mapped into memory.  */
2972
2973 struct file_info
2974 {
2975   char *start;                          /* start of map */
2976   char *name;                           /* filename */
2977   long  size;                           /* size of the file */
2978   long  rounded_size;                   /* size rounded to page boundary */
2979   int   fd;                             /* file descriptor */
2980   int   rw;                             /* != 0 if opened read/write */
2981   int   use_mmap;                       /* != 0 if mmap'ed */
2982 };
2983
2984 extern int decode_mach_o_hdr ();
2985 extern int encode_mach_o_hdr ();
2986
2987 static void add_func_table      PARAMS ((mo_header_t *, load_all_t *,
2988                                        symbol_info_t *, int));
2989 static void print_header        PARAMS ((mo_header_t *));
2990 static void print_load_command  PARAMS ((load_union_t *, size_t, int));
2991 static void bad_header          PARAMS ((int));
2992 static struct file_info *read_file  PARAMS ((const char *, int, int));
2993 static void end_file            PARAMS ((struct file_info *));
2994 \f
2995 /* OSF/rose specific version to scan the name list of the loaded
2996    program for the symbols g++ uses for static constructors and
2997    destructors.
2998
2999    The constructor table begins at __CTOR_LIST__ and contains a count
3000    of the number of pointers (or -1 if the constructors are built in a
3001    separate section by the linker), followed by the pointers to the
3002    constructor functions, terminated with a null pointer.  The
3003    destructor table has the same format, and begins at __DTOR_LIST__.  */
3004
3005 static void
3006 scan_prog_file (prog_name, which_pass)
3007      const char *prog_name;
3008      enum pass which_pass;
3009 {
3010   char *obj;
3011   mo_header_t hdr;
3012   load_all_t *load_array;
3013   load_all_t *load_end;
3014   load_all_t *load_cmd;
3015   int symbol_load_cmds;
3016   off_t offset;
3017   int i;
3018   int num_syms;
3019   int status;
3020   char *str_sect;
3021   struct file_info *obj_file;
3022   int prog_fd;
3023   mo_lcid_t cmd_strings   = -1;
3024   symbol_info_t *main_sym = 0;
3025   int rw                  = (which_pass != PASS_FIRST);
3026
3027   prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3028   if (prog_fd < 0)
3029     fatal_perror ("open %s", prog_name);
3030
3031   obj_file = read_file (prog_name, prog_fd, rw);
3032   obj = obj_file->start;
3033
3034   status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3035   if (status != MO_HDR_CONV_SUCCESS)
3036     bad_header (status);
3037
3038
3039   /* Do some basic sanity checks.  Note we explicitly use the big endian magic number,
3040      since the hardware will automatically swap bytes for us on loading little endian
3041      integers.  */
3042
3043 #ifndef CROSS_COMPILE
3044   if (hdr.moh_magic != MOH_MAGIC_MSB
3045       || hdr.moh_header_version != MOH_HEADER_VERSION
3046       || hdr.moh_byte_order != OUR_BYTE_ORDER
3047       || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3048       || hdr.moh_cpu_type != OUR_CPU_TYPE
3049       || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3050       || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3051     {
3052       fatal ("incompatibilities between object file & expected values");
3053     }
3054 #endif
3055
3056   if (debug)
3057     print_header (&hdr);
3058
3059   offset = hdr.moh_first_cmd_off;
3060   load_end = load_array
3061     = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3062
3063   /* Build array of load commands, calculating the offsets */
3064   for (i = 0; i < hdr.moh_n_load_cmds; i++)
3065     {
3066       load_union_t *load_hdr;           /* load command header */
3067
3068       load_cmd = load_end++;
3069       load_hdr = (load_union_t *) (obj + offset);
3070
3071       /* If modifying the program file, copy the header.  */
3072       if (rw)
3073         {
3074           load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3075           memcpy ((char *)ptr, (char *)load_hdr, load_hdr->hdr.ldci_cmd_size);
3076           load_hdr = ptr;
3077
3078           /* null out old command map, because we will rewrite at the end.  */
3079           if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3080             {
3081               cmd_strings = ptr->map.lcm_ld_cmd_strings;
3082               ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3083             }
3084         }
3085
3086       load_cmd->load = load_hdr;
3087       if (load_hdr->hdr.ldci_section_off > 0)
3088         load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3089
3090       if (debug)
3091         print_load_command (load_hdr, offset, i);
3092
3093       offset += load_hdr->hdr.ldci_cmd_size;
3094     }
3095
3096   /* If the last command is the load command map and is not undefined,
3097      decrement the count of load commands.  */
3098   if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3099     {
3100       load_end--;
3101       hdr.moh_n_load_cmds--;
3102     }
3103
3104   /* Go through and process each symbol table section.  */
3105   symbol_load_cmds = 0;
3106   for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3107     {
3108       load_union_t *load_hdr = load_cmd->load;
3109
3110       if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3111         {
3112           symbol_load_cmds++;
3113
3114           if (debug)
3115             {
3116               const char *kind = "unknown";
3117
3118               switch (load_hdr->sym.symc_kind)
3119                 {
3120                 case SYMC_IMPORTS:         kind = "imports"; break;
3121                 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3122                 case SYMC_STABS:           kind = "stabs";   break;
3123                 }
3124
3125               notice ("\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3126                       symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3127             }
3128
3129           if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3130             continue;
3131
3132           str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3133           if (str_sect == (char *) 0)
3134             fatal ("string section missing");
3135
3136           if (load_cmd->section == (char *) 0)
3137             fatal ("section pointer missing");
3138
3139           num_syms = load_hdr->sym.symc_nentries;
3140           for (i = 0; i < num_syms; i++)
3141             {
3142               symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3143               char *name = sym->si_name.symbol_name + str_sect;
3144
3145               if (name[0] != '_')
3146                 continue;
3147
3148               if (rw)
3149                 {
3150                   char *n = name + strlen (name) - strlen (NAME__MAIN);
3151
3152                   if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3153                     continue;
3154                   while (n != name)
3155                     if (*--n != '_')
3156                       continue;
3157
3158                   main_sym = sym;
3159                 }
3160               else
3161                 {
3162                   switch (is_ctor_dtor (name))
3163                     {
3164                     case 1:
3165                       add_to_list (&constructors, name);
3166                       break;
3167
3168                     case 2:
3169                       add_to_list (&destructors, name);
3170                       break;
3171
3172                     default:    /* not a constructor or destructor */
3173                       continue;
3174                     }
3175                 }
3176
3177               if (debug)
3178                 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3179                          sym->si_type, sym->si_sc_type, sym->si_flags, name);
3180             }
3181         }
3182     }
3183
3184   if (symbol_load_cmds == 0)
3185     fatal ("no symbol table found");
3186
3187   /* Update the program file now, rewrite header and load commands.  At present,
3188      we assume that there is enough space after the last load command to insert
3189      one more.  Since the first section written out is page aligned, and the
3190      number of load commands is small, this is ok for the present.  */
3191
3192   if (rw)
3193     {
3194       load_union_t *load_map;
3195       size_t size;
3196
3197       if (cmd_strings == -1)
3198         fatal ("no cmd_strings found");
3199
3200       /* Add __main to initializer list.
3201          If we are building a program instead of a shared library, do not
3202          do anything, since in the current version, you cannot do mallocs
3203          and such in the constructors.  */
3204
3205       if (main_sym != (symbol_info_t *) 0
3206           && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3207         add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3208
3209       if (debug)
3210         notice ("\nUpdating header and load commands.\n\n");
3211
3212       hdr.moh_n_load_cmds++;
3213       size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3214
3215       /* Create new load command map.  */
3216       if (debug)
3217         notice ("load command map, %d cmds, new size %ld.\n",
3218                 (int) hdr.moh_n_load_cmds, (long) size);
3219
3220       load_map = (load_union_t *) xcalloc (1, size);
3221       load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3222       load_map->map.ldc_header.ldci_cmd_size = size;
3223       load_map->map.lcm_ld_cmd_strings = cmd_strings;
3224       load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3225       load_array[hdr.moh_n_load_cmds-1].load = load_map;
3226
3227       offset = hdr.moh_first_cmd_off;
3228       for (i = 0; i < hdr.moh_n_load_cmds; i++)
3229         {
3230           load_map->map.lcm_map[i] = offset;
3231           if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3232             hdr.moh_load_map_cmd_off = offset;
3233
3234           offset += load_array[i].load->hdr.ldci_cmd_size;
3235         }
3236
3237       hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3238
3239       if (debug)
3240         print_header (&hdr);
3241
3242       /* Write header */
3243       status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3244       if (status != MO_HDR_CONV_SUCCESS)
3245         bad_header (status);
3246
3247       if (debug)
3248         notice ("writing load commands.\n\n");
3249
3250       /* Write load commands */
3251       offset = hdr.moh_first_cmd_off;
3252       for (i = 0; i < hdr.moh_n_load_cmds; i++)
3253         {
3254           load_union_t *load_hdr = load_array[i].load;
3255           size_t size = load_hdr->hdr.ldci_cmd_size;
3256
3257           if (debug)
3258             print_load_command (load_hdr, offset, i);
3259
3260           bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3261           offset += size;
3262         }
3263     }
3264
3265   end_file (obj_file);
3266
3267   if (close (prog_fd))
3268     fatal_perror ("close %s", prog_name);
3269
3270   if (debug)
3271     fprintf (stderr, "\n");
3272 }
3273
3274 \f
3275 /* Add a function table to the load commands to call a function
3276    on initiation or termination of the process.  */
3277
3278 static void
3279 add_func_table (hdr_p, load_array, sym, type)
3280      mo_header_t *hdr_p;                /* pointer to global header */
3281      load_all_t *load_array;            /* array of ptrs to load cmds */
3282      symbol_info_t *sym;                /* pointer to symbol entry */
3283      int type;                          /* fntc_type value */
3284 {
3285   /* Add a new load command.  */
3286   int num_cmds = ++hdr_p->moh_n_load_cmds;
3287   int load_index = num_cmds - 1;
3288   size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3289   load_union_t *ptr = xcalloc (1, size);
3290   load_all_t *load_cmd;
3291   int i;
3292
3293   /* Set the unresolved address bit in the header to force the loader to be
3294      used, since kernel exec does not call the initialization functions.  */
3295   hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3296
3297   load_cmd = &load_array[load_index];
3298   load_cmd->load = ptr;
3299   load_cmd->section = (char *) 0;
3300
3301   /* Fill in func table load command.  */
3302   ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3303   ptr->func.ldc_header.ldci_cmd_size = size;
3304   ptr->func.ldc_header.ldci_section_off = 0;
3305   ptr->func.ldc_header.ldci_section_len = 0;
3306   ptr->func.fntc_type = type;
3307   ptr->func.fntc_nentries = 1;
3308
3309   /* copy address, turn it from abs. address to (region,offset) if necessary.  */
3310   /* Is the symbol already expressed as (region, offset)?  */
3311   if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3312     {
3313       ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3314       ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3315     }
3316
3317   /* If not, figure out which region it's in.  */
3318   else
3319     {
3320       mo_vm_addr_t addr = sym->si_value.abs_val;
3321       int found = 0;
3322
3323       for (i = 0; i < load_index; i++)
3324         {
3325           if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3326             {
3327               region_command_t *region_ptr = &load_array[i].load->region;
3328
3329               if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3330                   && addr >= region_ptr->regc_addr.vm_addr
3331                   && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3332                 {
3333                   ptr->func.fntc_entry_loc[0].adr_lcid = i;
3334                   ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3335                   found++;
3336                   break;
3337                 }
3338             }
3339         }
3340
3341       if (!found)
3342         fatal ("could not convert 0x%l.8x into a region", addr);
3343     }
3344
3345   if (debug)
3346     notice ("%s function, region %d, offset = %ld (0x%.8lx)\n",
3347             type == FNTC_INITIALIZATION ? "init" : "term",
3348             (int) ptr->func.fntc_entry_loc[i].adr_lcid,
3349             (long) ptr->func.fntc_entry_loc[i].adr_sctoff,
3350             (long) ptr->func.fntc_entry_loc[i].adr_sctoff);
3351
3352 }
3353
3354 \f
3355 /* Print the global header for an OSF/rose object.  */
3356
3357 static void
3358 print_header (hdr_ptr)
3359      mo_header_t *hdr_ptr;
3360 {
3361   fprintf (stderr, "\nglobal header:\n");
3362   fprintf (stderr, "\tmoh_magic            = 0x%.8lx\n", hdr_ptr->moh_magic);
3363   fprintf (stderr, "\tmoh_major_version    = %d\n", (int)hdr_ptr->moh_major_version);
3364   fprintf (stderr, "\tmoh_minor_version    = %d\n", (int)hdr_ptr->moh_minor_version);
3365   fprintf (stderr, "\tmoh_header_version   = %d\n", (int)hdr_ptr->moh_header_version);
3366   fprintf (stderr, "\tmoh_max_page_size    = %d\n", (int)hdr_ptr->moh_max_page_size);
3367   fprintf (stderr, "\tmoh_byte_order       = %d\n", (int)hdr_ptr->moh_byte_order);
3368   fprintf (stderr, "\tmoh_data_rep_id      = %d\n", (int)hdr_ptr->moh_data_rep_id);
3369   fprintf (stderr, "\tmoh_cpu_type         = %d\n", (int)hdr_ptr->moh_cpu_type);
3370   fprintf (stderr, "\tmoh_cpu_subtype      = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3371   fprintf (stderr, "\tmoh_vendor_type      = %d\n", (int)hdr_ptr->moh_vendor_type);
3372   fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3373   fprintf (stderr, "\tmoh_first_cmd_off    = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3374   fprintf (stderr, "\tmoh_sizeofcmds       = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3375   fprintf (stderr, "\tmon_n_load_cmds      = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3376   fprintf (stderr, "\tmoh_flags            = 0x%.8lx", (long)hdr_ptr->moh_flags);
3377
3378   if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3379     fprintf (stderr, ", relocatable");
3380
3381   if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3382     fprintf (stderr, ", linkable");
3383
3384   if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3385     fprintf (stderr, ", execable");
3386
3387   if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3388     fprintf (stderr, ", executable");
3389
3390   if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3391     fprintf (stderr, ", unresolved");
3392
3393   fprintf (stderr, "\n\n");
3394   return;
3395 }
3396
3397 \f
3398 /* Print a short summary of a load command.  */
3399
3400 static void
3401 print_load_command (load_hdr, offset, number)
3402      load_union_t *load_hdr;
3403      size_t offset;
3404      int number;
3405 {
3406   mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3407   const char *type_str = (char *) 0;
3408
3409   switch (type)
3410     {
3411     case LDC_UNDEFINED:   type_str = "UNDEFINED";       break;
3412     case LDC_CMD_MAP:     type_str = "CMD_MAP";         break;
3413     case LDC_INTERPRETER: type_str = "INTERPRETER";     break;
3414     case LDC_STRINGS:     type_str = "STRINGS";         break;
3415     case LDC_REGION:      type_str = "REGION";          break;
3416     case LDC_RELOC:       type_str = "RELOC";           break;
3417     case LDC_PACKAGE:     type_str = "PACKAGE";         break;
3418     case LDC_SYMBOLS:     type_str = "SYMBOLS";         break;
3419     case LDC_ENTRY:       type_str = "ENTRY";           break;
3420     case LDC_FUNC_TABLE:  type_str = "FUNC_TABLE";      break;
3421     case LDC_GEN_INFO:    type_str = "GEN_INFO";        break;
3422     }
3423
3424   fprintf (stderr,
3425            "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3426            number,
3427            (long) load_hdr->hdr.ldci_cmd_size,
3428            (long) offset,
3429            (long) load_hdr->hdr.ldci_section_off,
3430            (long) load_hdr->hdr.ldci_section_len);
3431
3432   if (type_str == (char *) 0)
3433     fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3434
3435   else if (type != LDC_REGION)
3436     fprintf (stderr, ", ty: %s\n", type_str);
3437
3438   else
3439     {
3440       const char *region = "";
3441       switch (load_hdr->region.regc_usage_type)
3442         {
3443         case REG_TEXT_T:        region = ", .text";     break;
3444         case REG_DATA_T:        region = ", .data";     break;
3445         case REG_BSS_T:         region = ", .bss";      break;
3446         case REG_GLUE_T:        region = ", .glue";     break;
3447 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3448         case REG_RDATA_T:       region = ", .rdata";    break;
3449         case REG_SDATA_T:       region = ", .sdata";    break;
3450         case REG_SBSS_T:        region = ", .sbss";     break;
3451 #endif
3452         }
3453
3454       fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3455                type_str,
3456                (long) load_hdr->region.regc_vm_addr,
3457                (long) load_hdr->region.regc_vm_size,
3458                region);
3459     }
3460
3461   return;
3462 }
3463
3464 \f
3465 /* Fatal error when {en,de}code_mach_o_header fails.  */
3466
3467 static void
3468 bad_header (status)
3469      int status;
3470 {
3471   switch (status)
3472     {
3473     case MO_ERROR_BAD_MAGIC:            fatal ("bad magic number");
3474     case MO_ERROR_BAD_HDR_VERS:         fatal ("bad header version");
3475     case MO_ERROR_BAD_RAW_HDR_VERS:     fatal ("bad raw header version");
3476     case MO_ERROR_BUF2SML:              fatal ("raw header buffer too small");
3477     case MO_ERROR_OLD_RAW_HDR_FILE:     fatal ("old raw header file");
3478     case MO_ERROR_UNSUPPORTED_VERS:     fatal ("unsupported version");
3479     default:
3480       fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3481     }
3482 }
3483
3484 \f
3485 /* Read a file into a memory buffer.  */
3486
3487 static struct file_info *
3488 read_file (name, fd, rw)
3489      const char *name;          /* filename */
3490      int fd;                    /* file descriptor */
3491      int rw;                    /* read/write */
3492 {
3493   struct stat stat_pkt;
3494   struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3495 #ifdef USE_MMAP
3496   static int page_size;
3497 #endif
3498
3499   if (fstat (fd, &stat_pkt) < 0)
3500     fatal_perror ("fstat %s", name);
3501
3502   p->name         = name;
3503   p->size         = stat_pkt.st_size;
3504   p->rounded_size = stat_pkt.st_size;
3505   p->fd           = fd;
3506   p->rw           = rw;
3507
3508 #ifdef USE_MMAP
3509   if (debug)
3510     fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3511
3512   if (page_size == 0)
3513     page_size = sysconf (_SC_PAGE_SIZE);
3514
3515   p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3516   p->start = mmap ((caddr_t) 0,
3517                    (rw) ? p->rounded_size : p->size,
3518                    (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3519                    MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3520                    fd,
3521                    0L);
3522
3523   if (p->start != (char *) 0 && p->start != (char *) -1)
3524     p->use_mmap = 1;
3525
3526   else
3527 #endif /* USE_MMAP */
3528     {
3529       long len;
3530
3531       if (debug)
3532         fprintf (stderr, "read %s\n", name);
3533
3534       p->use_mmap = 0;
3535       p->start = xmalloc (p->size);
3536       if (lseek (fd, 0L, SEEK_SET) < 0)
3537         fatal_perror ("lseek %s 0", name);
3538
3539       len = read (fd, p->start, p->size);
3540       if (len < 0)
3541         fatal_perror ("read %s", name);
3542
3543       if (len != p->size)
3544         fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3545     }
3546
3547   return p;
3548 }
3549 \f
3550 /* Do anything necessary to write a file back from memory.  */
3551
3552 static void
3553 end_file (ptr)
3554      struct file_info *ptr;     /* file information block */
3555 {
3556 #ifdef USE_MMAP
3557   if (ptr->use_mmap)
3558     {
3559       if (ptr->rw)
3560         {
3561           if (debug)
3562             fprintf (stderr, "msync %s\n", ptr->name);
3563
3564           if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3565             fatal_perror ("msync %s", ptr->name);
3566         }
3567
3568       if (debug)
3569         fprintf (stderr, "munmap %s\n", ptr->name);
3570
3571       if (munmap (ptr->start, ptr->size))
3572         fatal_perror ("munmap %s", ptr->name);
3573     }
3574   else
3575 #endif /* USE_MMAP */
3576     {
3577       if (ptr->rw)
3578         {
3579           long len;
3580
3581           if (debug)
3582             fprintf (stderr, "write %s\n", ptr->name);
3583
3584           if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3585             fatal_perror ("lseek %s 0", ptr->name);
3586
3587           len = write (ptr->fd, ptr->start, ptr->size);
3588           if (len < 0)
3589             fatal_perror ("write %s", ptr->name);
3590
3591           if (len != ptr->size)
3592             fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3593         }
3594
3595       free (ptr->start);
3596     }
3597
3598   free (ptr);
3599 }
3600
3601 #endif /* OBJECT_FORMAT_ROSE */