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