home *** CD-ROM | disk | FTP | other *** search
/ OpenStep (Enterprise) / OpenStepENTCD.toast / OEDEV / GNUSRC.Z / collect2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-13  |  80.4 KB  |  3,270 lines

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