OSDN Git Service

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