1 /* Collect static initialization info into data structures
2 that can be traversed by C++ initialization and finalization
5 Copyright (C) 1992, 1993, 1994, 1995, 1996 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).
10 This file is part of GNU CC.
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)
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.
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. */
28 /* Build tables of static constructors and destructors and run ld. */
31 #include <sys/types.h>
43 #include "gansidecl.h"
51 extern const char *const sys_errlist[];
53 extern char *sys_errlist[];
60 /* Obstack allocation and deallocation routines. */
61 #define obstack_chunk_alloc xmalloc
62 #define obstack_chunk_free free
75 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
78 #define WTERMSIG(S) ((S) & 0x7f)
81 #define WIFEXITED(S) (((S) & 0xff) == 0)
84 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
87 extern char *choose_temp_base ();
89 /* On certain systems, we have code that works by scanning the object file
90 directly. But this code uses system-specific header files and library
91 functions, so turn it off in a cross-compiler. Likewise, the names of
92 the utilities aren't correct for a cross-compiler; we have to hope that
93 cross-versions are in the proper directories. */
96 #undef SUNOS4_SHARED_LIBRARIES
97 #undef OBJECT_FORMAT_COFF
98 #undef OBJECT_FORMAT_ROSE
100 #undef REAL_LD_FILE_NAME
101 #undef REAL_NM_FILE_NAME
102 #undef REAL_STRIP_FILE_NAME
105 /* If we can't use a special method, use the ordinary one:
106 run nm to find what symbols are present.
107 In a cross-compiler, this means you need a cross nm,
108 but that isn't quite as unpleasant as special headers. */
110 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
111 #define OBJECT_FORMAT_NONE
114 #ifdef OBJECT_FORMAT_COFF
123 /* Many versions of ldfcn.h define these. */
131 /* Some systems have an ISCOFF macro, but others do not. In some cases
132 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
133 that either do not have an ISCOFF macro in /usr/include or for those
134 where it is wrong. */
137 #define MY_ISCOFF(X) ISCOFF (X)
140 #ifdef XCOFF_DEBUGGING_INFO
141 #define XCOFF_SCAN_LIBS
144 #endif /* OBJECT_FORMAT_COFF */
146 #ifdef OBJECT_FORMAT_ROSE
153 #include <sys/mman.h>
157 #include <mach_o_format.h>
158 #include <mach_o_header.h>
159 #include <mach_o_vals.h>
160 #include <mach_o_types.h>
162 #endif /* OBJECT_FORMAT_ROSE */
164 #ifdef OBJECT_FORMAT_NONE
166 /* Default flags to pass to nm. */
168 #define NM_FLAGS "-p"
171 #endif /* OBJECT_FORMAT_NONE */
173 /* Some systems use __main in a way incompatible with its use in gcc, in these
174 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
175 give the same symbol without quotes for an alternative entry point. You
176 must define both, or neither. */
178 #define NAME__MAIN "__main"
179 #define SYMBOL__MAIN __main
182 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES || defined(XCOFF_SCAN_LIBS)
183 #define SCAN_LIBRARIES
187 int do_collecting = 1;
189 int do_collecting = 0;
192 /* Linked lists of constructor and destructor names. */
208 /* Enumeration giving which pass this is for scanning the program file. */
211 PASS_FIRST, /* without constructors */
212 PASS_OBJ, /* individual objects */
213 PASS_LIB, /* looking for shared libraries */
214 PASS_SECOND /* with constructors linked in */
217 #ifndef NO_SYS_SIGLIST
218 #ifndef DONT_DECLARE_SYS_SIGLIST
219 extern char *sys_siglist[];
222 extern char *version_string;
224 int vflag; /* true if -v */
225 static int rflag; /* true if -r */
226 static int strip_flag; /* true if -s */
228 int debug; /* true if -debug */
230 static int shared_obj; /* true if -shared */
232 static int temp_filename_length; /* Length of temp_filename */
233 static char *temp_filename; /* Base of temp filenames */
234 static char *c_file; /* <xxx>.c for constructor/destructor list. */
235 static char *o_file; /* <xxx>.o for constructor/destructor list. */
236 static char *export_file; /* <xxx>.x for AIX export list. */
237 char *ldout; /* File for ld errors. */
238 static char *output_file; /* Output file for ld. */
239 static char *nm_file_name; /* pathname of nm */
240 static char *ldd_file_name; /* pathname of ldd (or equivalent) */
241 static char *strip_file_name; /* pathname of strip */
242 char *c_file_name; /* pathname of gcc */
243 static char *initname, *fininame; /* names of init and fini funcs */
245 static struct head constructors; /* list of constructors found */
246 static struct head destructors; /* list of destructors found */
247 static struct head exports; /* list of exported symbols */
249 struct obstack temporary_obstack;
250 struct obstack permanent_obstack;
251 char * temporary_firstobj;
253 /* Defined in the automatically-generated underscore.c. */
254 extern int prepends_underscore;
256 extern char *getenv ();
257 extern char *mktemp ();
258 extern FILE *fdopen ();
260 /* Structure to hold all the directories in which to search for files to
265 char *prefix; /* String to prepend to the path. */
266 struct prefix_list *next; /* Next in linked list. */
271 struct prefix_list *plist; /* List of prefixes to try */
272 int max_len; /* Max length of a prefix in PLIST */
273 char *name; /* Name of this list (used in config stuff) */
276 void collect_exit PROTO((int));
277 void collect_execute PROTO((char *, char **, char *));
278 void dump_file PROTO((char *));
279 static void handler PROTO((int));
280 static int is_ctor_dtor PROTO((char *));
281 static int is_in_prefix_list PROTO((struct path_prefix *, char *, int));
282 static char *find_a_file PROTO((struct path_prefix *, char *));
283 static void add_prefix PROTO((struct path_prefix *, char *));
284 static void prefix_from_env PROTO((char *, struct path_prefix *));
285 static void prefix_from_string PROTO((char *, struct path_prefix *));
286 static void do_wait PROTO((char *));
287 static void fork_execute PROTO((char *, char **));
288 static void maybe_unlink PROTO((char *));
289 static void add_to_list PROTO((struct head *, char *));
290 static void write_list PROTO((FILE *, char *, struct id *));
291 static void write_list_with_asm PROTO((FILE *, char *, struct id *));
292 static void write_c_file PROTO((FILE *, char *));
293 static void write_export_file PROTO((FILE *));
294 static void scan_prog_file PROTO((char *, enum pass));
295 static void scan_libraries PROTO((char *));
300 extern char *index ();
301 extern char *rindex ();
317 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
320 close (fdtmp[--fdx]);
336 static char buffer[30];
340 if (e > 0 && e < sys_nerr)
341 return sys_errlist[e];
343 sprintf (buffer, "Unknown error %d", e);
348 /* Delete tempfiles and exit function. */
351 collect_exit (status)
354 if (c_file != 0 && c_file[0])
355 maybe_unlink (c_file);
357 if (o_file != 0 && o_file[0])
358 maybe_unlink (o_file);
360 if (export_file != 0 && export_file[0])
361 maybe_unlink (export_file);
363 if (ldout != 0 && ldout[0])
366 maybe_unlink (ldout);
369 if (status != 0 && output_file != 0 && output_file[0])
370 maybe_unlink (output_file);
376 /* Die when sys call fails. */
379 fatal_perror (string, arg1, arg2, arg3)
380 char *string, *arg1, *arg2, *arg3;
384 fprintf (stderr, "collect2: ");
385 fprintf (stderr, string, arg1, arg2, arg3);
386 fprintf (stderr, ": %s\n", my_strerror (e));
393 fatal (string, arg1, arg2, arg3)
394 char *string, *arg1, *arg2, *arg3;
396 fprintf (stderr, "collect2: ");
397 fprintf (stderr, string, arg1, arg2, arg3);
398 fprintf (stderr, "\n");
402 /* Write error message. */
405 error (string, arg1, arg2, arg3, arg4)
406 char *string, *arg1, *arg2, *arg3, *arg4;
408 fprintf (stderr, "collect2: ");
409 fprintf (stderr, string, arg1, arg2, arg3, arg4);
410 fprintf (stderr, "\n");
413 /* In case obstack is linked in, and abort is defined to fancy_abort,
414 provide a default entry. */
419 fatal ("internal error");
427 if (c_file != 0 && c_file[0])
428 maybe_unlink (c_file);
430 if (o_file != 0 && o_file[0])
431 maybe_unlink (o_file);
433 if (ldout != 0 && ldout[0])
434 maybe_unlink (ldout);
436 if (export_file != 0 && export_file[0])
437 maybe_unlink (export_file);
439 signal (signo, SIG_DFL);
440 kill (getpid (), signo);
445 xcalloc (size1, size2)
448 char *ptr = (char *) calloc (size1, size2);
452 fatal ("out of memory");
460 char *ptr = (char *) malloc (size);
464 fatal ("out of memory");
473 register char *value = (char *) realloc (ptr, size);
475 fatal ("virtual memory exhausted");
483 return access (name, R_OK) == 0;
486 /* Make a copy of a string INPUT with size SIZE. */
489 savestring (input, size)
493 char *output = (char *) xmalloc (size + 1);
494 bcopy (input, output, size);
503 FILE *stream = fopen (name, "r");
504 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
511 while (c = getc (stream),
512 c != EOF && (isalnum (c) || c == '_' || c == '$' || c == '.'))
513 obstack_1grow (&temporary_obstack, c);
514 if (obstack_object_size (&temporary_obstack) > 0)
516 char *word, *p, *result;
517 obstack_1grow (&temporary_obstack, '\0');
518 word = obstack_finish (&temporary_obstack);
521 ++word, putc ('.', stderr);
523 if (*p == '_' && prepends_underscore)
529 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
534 fputs (result, stderr);
536 diff = strlen (word) - strlen (result);
538 --diff, putc (' ', stderr);
539 while (diff < 0 && c == ' ')
540 ++diff, c = getc (stream);
545 fputs (word, stderr);
548 obstack_free (&temporary_obstack, temporary_firstobj);
556 /* Decide whether the given symbol is:
557 a constructor (1), a destructor (2), or neither (0). */
563 struct names { char *name; int len; int ret; int two_underscores; };
565 register struct names *p;
567 register char *orig_s = s;
569 static struct names special[] = {
570 #ifdef NO_DOLLAR_IN_LABEL
571 #ifdef NO_DOT_IN_LABEL
572 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
573 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
575 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
576 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
579 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
580 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
582 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
583 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
584 #ifdef CFRONT_LOSSAGE /* Don't collect cfront initialization functions.
585 cfront has its own linker procedure to collect them;
586 if collect2 gets them too, they get collected twice
587 when the cfront procedure is run and the compiler used
588 for linking happens to be GCC. */
589 { "sti__", sizeof ("sti__")-1, 1, 1 },
590 { "std__", sizeof ("std__")-1, 2, 1 },
591 #endif /* CFRONT_LOSSAGE */
595 while ((ch = *s) == '_')
601 for (p = &special[0]; p->len > 0; p++)
604 && (!p->two_underscores || ((s - orig_s) >= 2))
605 && strncmp(s, p->name, p->len) == 0)
613 /* Routine to add variables to the environment. */
621 #ifndef VMS /* nor about VMS */
623 extern char **environ;
624 char **old_environ = environ;
631 while ((ch = *p++) != '\0' && ch != '=')
637 /* Search for replacing an existing environment variable, and
638 count the number of total environment variables. */
639 for (envp = old_environ; *envp; envp++)
642 if (!strncmp (str, *envp, name_len))
649 /* Add a new environment variable */
650 environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
652 bcopy ((char *) old_environ, (char *) (environ + 1),
653 sizeof (char *) * (num_envs+1));
659 #endif /* HAVE_PUTENV */
661 /* By default, colon separates directories in a path. */
662 #ifndef PATH_SEPARATOR
663 #define PATH_SEPARATOR ':'
666 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
667 and one from the PATH variable. */
669 static struct path_prefix cpath, path;
672 /* This is the name of the target machine. We use it to form the name
673 of the files to execute. */
675 static char *target_machine = TARGET_MACHINE;
678 /* Names under which we were executed. Never return one of those files in our
681 static struct path_prefix our_file_names;
683 /* Determine if STRING is in PPREFIX.
685 This utility is currently only used to look up file names. Prefix lists
686 record directory names. This matters to us because the latter has a
687 trailing slash, so I've added a flag to handle both. */
690 is_in_prefix_list (pprefix, string, filep)
691 struct path_prefix *pprefix;
695 struct prefix_list *pl;
699 int len = strlen (string);
701 for (pl = pprefix->plist; pl; pl = pl->next)
703 if (strncmp (pl->prefix, string, len) == 0
704 && strcmp (pl->prefix + len, "/") == 0)
710 for (pl = pprefix->plist; pl; pl = pl->next)
712 if (strcmp (pl->prefix, string) == 0)
720 /* Search for NAME using prefix list PPREFIX. We only look for executable
723 Return 0 if not found, otherwise return its name, allocated with malloc. */
726 find_a_file (pprefix, name)
727 struct path_prefix *pprefix;
731 struct prefix_list *pl;
732 int len = pprefix->max_len + strlen (name) + 1;
734 #ifdef EXECUTABLE_SUFFIX
735 len += strlen (EXECUTABLE_SUFFIX);
738 temp = xmalloc (len);
740 /* Determine the filename to execute (special case for absolute paths). */
744 if (access (name, X_OK) == 0)
751 for (pl = pprefix->plist; pl; pl = pl->next)
753 strcpy (temp, pl->prefix);
755 if (! is_in_prefix_list (&our_file_names, temp, 1)
756 /* This is a kludge, but there seems no way around it. */
757 && strcmp (temp, "./ld") != 0
758 && access (temp, X_OK) == 0)
761 #ifdef EXECUTABLE_SUFFIX
762 /* Some systems have a suffix for executable files.
763 So try appending that. */
764 strcat (temp, EXECUTABLE_SUFFIX);
765 if (! is_in_prefix_list (&our_file_names, temp, 1)
766 && access (temp, X_OK) == 0)
775 /* Add an entry for PREFIX to prefix list PPREFIX. */
778 add_prefix (pprefix, prefix)
779 struct path_prefix *pprefix;
782 struct prefix_list *pl, **prev;
787 for (pl = pprefix->plist; pl->next; pl = pl->next)
792 prev = &pprefix->plist;
794 /* Keep track of the longest prefix */
796 len = strlen (prefix);
797 if (len > pprefix->max_len)
798 pprefix->max_len = len;
800 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
801 pl->prefix = savestring (prefix, len);
806 pl->next = (struct prefix_list *) 0;
810 /* Take the value of the environment variable ENV, break it into a path, and
811 add of the entries to PPREFIX. */
814 prefix_from_env (env, pprefix)
816 struct path_prefix *pprefix;
818 char *p = getenv (env);
821 prefix_from_string (p, pprefix);
825 prefix_from_string (p, pprefix)
827 struct path_prefix *pprefix;
830 char *nstore = (char *) xmalloc (strlen (p) + 3);
835 if (*endp == PATH_SEPARATOR || *endp == 0)
837 strncpy (nstore, startp, endp-startp);
840 strcpy (nstore, "./");
842 else if (endp[-1] != '/')
844 nstore[endp-startp] = '/';
845 nstore[endp-startp+1] = 0;
848 nstore[endp-startp] = 0;
850 add_prefix (pprefix, nstore);
853 endp = startp = endp + 1;
867 char *ld_suffix = "ld";
868 char *full_ld_suffix = ld_suffix;
869 char *real_ld_suffix = "real-ld";
870 char *full_real_ld_suffix = real_ld_suffix;
871 char *collect_ld_suffix = "collect-ld";
872 char *nm_suffix = "nm";
873 char *full_nm_suffix = nm_suffix;
874 char *gnm_suffix = "gnm";
875 char *full_gnm_suffix = gnm_suffix;
877 char *ldd_suffix = LDD_SUFFIX;
878 char *full_ldd_suffix = ldd_suffix;
880 char *strip_suffix = "strip";
881 char *full_strip_suffix = strip_suffix;
882 char *gstrip_suffix = "gstrip";
883 char *full_gstrip_suffix = gstrip_suffix;
885 FILE *outf, *exportf;
892 char **ld1_argv = (char **) xcalloc (sizeof (char *), argc+3);
893 char **ld1 = ld1_argv;
894 char **ld2_argv = (char **) xcalloc (sizeof (char *), argc+6);
895 char **ld2 = ld2_argv;
896 char **object_lst = (char **) xcalloc (sizeof (char *), argc);
897 char **object = object_lst;
899 int num_c_args = argc+7;
906 #ifndef DEFAULT_A_OUT_NAME
907 output_file = "a.out";
909 output_file = DEFAULT_A_OUT_NAME;
912 obstack_begin (&temporary_obstack, 0);
913 obstack_begin (&permanent_obstack, 0);
914 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
915 current_demangling_style = gnu_demangling;
917 /* We must check that we do not call ourselves in an infinite
918 recursion loop. We append the name used for us to the COLLECT_NAMES
919 environment variable.
921 In practice, collect will rarely invoke itself. This can happen now
922 that we are no longer called gld. A perfect example is when running
923 gcc in a build directory that has been installed. When looking for
924 ld's, we'll find our installed version and believe that's the real ld. */
926 /* We must also append COLLECT_NAME to COLLECT_NAMES to watch for the
927 previous version of collect (the one that used COLLECT_NAME and only
928 handled two levels of recursion). If we don't we may mutually recurse
929 forever. This can happen (I think) when bootstrapping the old version
930 and a new one is installed (rare, but we should handle it).
931 ??? Hopefully references to COLLECT_NAME can be removed at some point. */
933 collect_name = (char *) getenv ("COLLECT_NAME");
934 collect_names = (char *) getenv ("COLLECT_NAMES");
936 p = (char *) xmalloc (strlen ("COLLECT_NAMES=")
937 + (collect_name ? strlen (collect_name) + 1 : 0)
938 + (collect_names ? strlen (collect_names) + 1 : 0)
939 + strlen (argv[0]) + 1);
940 strcpy (p, "COLLECT_NAMES=");
941 if (collect_name != 0)
942 sprintf (p + strlen (p), "%s%c", collect_name, PATH_SEPARATOR);
943 if (collect_names != 0)
944 sprintf (p + strlen (p), "%s%c", collect_names, PATH_SEPARATOR);
948 prefix_from_env ("COLLECT_NAMES", &our_file_names);
950 /* Set environment variable COLLECT_NAME to our name so the previous version
951 of collect won't find us. If it does we'll mutually recurse forever.
952 This can happen when bootstrapping the new version and an old version is
954 ??? Hopefully this bit of code can be removed at some point. */
956 p = xmalloc (strlen ("COLLECT_NAME=") + strlen (argv[0]) + 1);
957 sprintf (p, "COLLECT_NAME=%s", argv[0]);
960 p = (char *) getenv ("COLLECT_GCC_OPTIONS");
965 while (*q && *q != ' ') q++;
966 if (*p == '-' && p[1] == 'm')
973 c_ptr = c_argv = (char **) xcalloc (sizeof (char *), num_c_args);
976 fatal ("no arguments");
979 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
980 signal (SIGQUIT, handler);
982 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
983 signal (SIGINT, handler);
985 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
986 signal (SIGALRM, handler);
989 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
990 signal (SIGHUP, handler);
992 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
993 signal (SIGSEGV, handler);
995 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
996 signal (SIGBUS, handler);
999 /* Extract COMPILER_PATH and PATH into our prefix list. */
1000 prefix_from_env ("COMPILER_PATH", &cpath);
1001 prefix_from_env ("PATH", &path);
1003 #ifdef CROSS_COMPILE
1004 /* If we look for a program in the compiler directories, we just use
1005 the short name, since these directories are already system-specific.
1006 But it we look for a took in the system directories, we need to
1007 qualify the program name with the target machine. */
1010 = xcalloc (strlen (ld_suffix) + strlen (target_machine) + 2, 1);
1011 strcpy (full_ld_suffix, target_machine);
1012 strcat (full_ld_suffix, "-");
1013 strcat (full_ld_suffix, ld_suffix);
1016 = xcalloc (strlen (real_ld_suffix) + strlen (target_machine) + 2, 1);
1017 strcpy (full_real_ld_suffix, target_machine);
1018 strcat (full_real_ld_suffix, "-");
1019 strcat (full_real_ld_suffix, real_ld_suffix);
1023 = xcalloc (strlen (gld_suffix) + strlen (target_machine) + 2, 1);
1024 strcpy (full_gld_suffix, target_machine);
1025 strcat (full_gld_suffix, "-");
1026 strcat (full_gld_suffix, gld_suffix);
1030 = xcalloc (strlen (nm_suffix) + strlen (target_machine) + 2, 1);
1031 strcpy (full_nm_suffix, target_machine);
1032 strcat (full_nm_suffix, "-");
1033 strcat (full_nm_suffix, nm_suffix);
1036 = xcalloc (strlen (gnm_suffix) + strlen (target_machine) + 2, 1);
1037 strcpy (full_gnm_suffix, target_machine);
1038 strcat (full_gnm_suffix, "-");
1039 strcat (full_gnm_suffix, gnm_suffix);
1043 = xcalloc (strlen (ldd_suffix) + strlen (target_machine) + 2, 1);
1044 strcpy (full_ldd_suffix, target_machine);
1045 strcat (full_ldd_suffix, "-");
1046 strcat (full_ldd_suffix, ldd_suffix);
1050 = xcalloc (strlen (strip_suffix) + strlen (target_machine) + 2, 1);
1051 strcpy (full_strip_suffix, target_machine);
1052 strcat (full_strip_suffix, "-");
1053 strcat (full_strip_suffix, strip_suffix);
1056 = xcalloc (strlen (gstrip_suffix) + strlen (target_machine) + 2, 1);
1057 strcpy (full_gstrip_suffix, target_machine);
1058 strcat (full_gstrip_suffix, "-");
1059 strcat (full_gstrip_suffix, gstrip_suffix);
1060 #endif /* CROSS_COMPILE */
1062 /* Try to discover a valid linker/nm/strip to use. */
1064 /* Maybe we know the right file to use (if not cross). */
1065 #ifdef REAL_LD_FILE_NAME
1066 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1067 if (ld_file_name == 0)
1069 /* Search the (target-specific) compiler dirs for ld'. */
1070 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1071 /* Likewise for `collect-ld'. */
1072 if (ld_file_name == 0)
1073 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1074 /* Search the compiler directories for `ld'. We have protection against
1075 recursive calls in find_a_file. */
1076 if (ld_file_name == 0)
1077 ld_file_name = find_a_file (&cpath, ld_suffix);
1078 /* Search the ordinary system bin directories
1079 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1080 if (ld_file_name == 0)
1081 ld_file_name = find_a_file (&path, full_ld_suffix);
1083 /* If we've invoked ourselves, try again with LD_FILE_NAME. */
1085 if (collect_names != 0)
1087 if (ld_file_name != 0)
1089 argv[0] = ld_file_name;
1090 execvp (argv[0], argv);
1092 fatal ("cannot find `ld'");
1095 #ifdef REAL_NM_FILE_NAME
1096 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1097 if (nm_file_name == 0)
1099 nm_file_name = find_a_file (&cpath, gnm_suffix);
1100 if (nm_file_name == 0)
1101 nm_file_name = find_a_file (&path, full_gnm_suffix);
1102 if (nm_file_name == 0)
1103 nm_file_name = find_a_file (&cpath, nm_suffix);
1104 if (nm_file_name == 0)
1105 nm_file_name = find_a_file (&path, full_nm_suffix);
1108 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1109 if (ldd_file_name == 0)
1110 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1113 #ifdef REAL_STRIP_FILE_NAME
1114 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1115 if (strip_file_name == 0)
1117 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1118 if (strip_file_name == 0)
1119 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1120 if (strip_file_name == 0)
1121 strip_file_name = find_a_file (&cpath, strip_suffix);
1122 if (strip_file_name == 0)
1123 strip_file_name = find_a_file (&path, full_strip_suffix);
1125 /* Determine the full path name of the C compiler to use. */
1126 c_file_name = getenv ("COLLECT_GCC");
1127 if (c_file_name == 0)
1129 #ifdef CROSS_COMPILE
1130 c_file_name = xcalloc (sizeof ("gcc-") + strlen (target_machine) + 1, 1);
1131 strcpy (c_file_name, target_machine);
1132 strcat (c_file_name, "-gcc");
1134 c_file_name = "gcc";
1138 p = find_a_file (&cpath, c_file_name);
1140 /* Here it should be safe to use the system search path since we should have
1141 already qualified the name of the compiler when it is needed. */
1143 p = find_a_file (&path, c_file_name);
1148 *ld1++ = *ld2++ = ld_file_name;
1150 /* Make temp file names. */
1151 temp_filename = choose_temp_base ();
1152 temp_filename_length = strlen (temp_filename);
1153 c_file = xcalloc (temp_filename_length + sizeof (".c"), 1);
1154 o_file = xcalloc (temp_filename_length + sizeof (".o"), 1);
1155 export_file = xmalloc (temp_filename_length + sizeof (".x"));
1156 ldout = xmalloc (temp_filename_length + sizeof (".ld"));
1157 sprintf (ldout, "%s.ld", temp_filename);
1158 sprintf (c_file, "%s.c", temp_filename);
1159 sprintf (o_file, "%s.o", temp_filename);
1160 sprintf (export_file, "%s.x", temp_filename);
1161 *c_ptr++ = c_file_name;
1166 /* !!! When GCC calls collect2,
1167 it does not know whether it is calling collect2 or ld.
1168 So collect2 cannot meaningfully understand any options
1169 except those ld understands.
1170 If you propose to make GCC pass some other option,
1171 just imagine what will happen if ld is really ld!!! */
1173 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1174 /* After the first file, put in the c++ rt0. */
1177 while ((arg = *++argv) != (char *) 0)
1179 *ld1++ = *ld2++ = arg;
1186 if (!strcmp (arg, "-debug"))
1198 /* place o_file BEFORE this argument! */
1208 output_file = *ld1++ = *ld2++ = *++argv;
1210 output_file = &arg[2];
1219 if (arg[2] == '\0' && do_collecting)
1221 /* We must strip after the nm run, otherwise C++ linking
1222 won't work. Thus we strip in the second ld run, or
1223 else with strip if there is no second ld run. */
1235 else if ((p = rindex (arg, '.')) != (char *) 0
1236 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0))
1245 /* place o_file BEFORE this argument! */
1256 /* Get any options that the upper GCC wants to pass to the sub-GCC. */
1257 p = (char *) getenv ("COLLECT_GCC_OPTIONS");
1262 while (*q && *q != ' ') q++;
1263 if (*p == '-' && (p[1] == 'm' || p[1] == 'f'))
1264 *c_ptr++ = savestring (p, q - p);
1265 if (strncmp (p, "-shared", sizeof ("shared") - 1) == 0)
1272 #ifdef COLLECT_EXPORT_LIST
1273 /* The AIX linker will discard static constructors in object files if
1274 nothing else in the file is referenced, so look at them first. */
1275 while (object_lst < object)
1276 scan_prog_file (*object_lst++, PASS_OBJ);
1279 char *buf = alloca (strlen (export_file) + 5);
1280 sprintf (buf, "-bE:%s", export_file);
1283 exportf = fopen (export_file, "w");
1284 if (exportf == (FILE *) 0)
1285 fatal_perror ("%s", export_file);
1286 write_export_file (exportf);
1287 if (fclose (exportf))
1288 fatal_perror ("closing %s", export_file);
1293 *object = *c_ptr = *ld1 = (char *) 0;
1297 fprintf (stderr, "collect2 version %s", version_string);
1298 #ifdef TARGET_VERSION
1301 fprintf (stderr, "\n");
1307 fprintf (stderr, "ld_file_name = %s\n",
1308 (ld_file_name ? ld_file_name : "not found"));
1309 fprintf (stderr, "c_file_name = %s\n",
1310 (c_file_name ? c_file_name : "not found"));
1311 fprintf (stderr, "nm_file_name = %s\n",
1312 (nm_file_name ? nm_file_name : "not found"));
1314 fprintf (stderr, "ldd_file_name = %s\n",
1315 (ldd_file_name ? ldd_file_name : "not found"));
1317 fprintf (stderr, "strip_file_name = %s\n",
1318 (strip_file_name ? strip_file_name : "not found"));
1319 fprintf (stderr, "c_file = %s\n",
1320 (c_file ? c_file : "not found"));
1321 fprintf (stderr, "o_file = %s\n",
1322 (o_file ? o_file : "not found"));
1324 ptr = getenv ("COLLECT_NAMES");
1326 fprintf (stderr, "COLLECT_NAMES = %s\n", ptr);
1328 ptr = getenv ("COLLECT_GCC_OPTIONS");
1330 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1332 ptr = getenv ("COLLECT_GCC");
1334 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1336 ptr = getenv ("COMPILER_PATH");
1338 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1340 ptr = getenv ("LIBRARY_PATH");
1342 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1344 fprintf (stderr, "\n");
1347 /* Load the program, searching all libraries. */
1349 collect_execute ("ld", ld1_argv, ldout);
1354 /* If -r or they'll be run via some other method, don't build the
1355 constructor or destructor list, just return now. */
1356 if (rflag || ! do_collecting)
1359 /* Examine the namelist with nm and search it for static constructors
1360 and destructors to call.
1361 Write the constructor and destructor tables to a .s file and reload. */
1363 scan_prog_file (output_file, PASS_FIRST);
1365 #ifdef SCAN_LIBRARIES
1366 scan_libraries (output_file);
1371 fprintf (stderr, "%d constructor(s) found\n", constructors.number);
1372 fprintf (stderr, "%d destructor(s) found\n", destructors.number);
1375 if (constructors.number == 0 && destructors.number == 0
1377 /* If we will be running these functions ourselves, we want to emit
1378 stubs into the shared library so that we don't have to relink
1379 dependent programs when we add static objects. */
1384 /* Strip now if it was requested on the command line. */
1387 char **strip_argv = (char **) xcalloc (sizeof (char *), 3);
1388 strip_argv[0] = strip_file_name;
1389 strip_argv[1] = output_file;
1390 strip_argv[2] = (char *) 0;
1391 fork_execute ("strip", strip_argv);
1394 #ifdef COLLECT_EXPORT_LIST
1395 maybe_unlink (export_file);
1400 maybe_unlink(output_file);
1401 outf = fopen (c_file, "w");
1402 if (outf == (FILE *) 0)
1403 fatal_perror ("%s", c_file);
1405 write_c_file (outf, c_file);
1408 fatal_perror ("closing %s", c_file);
1410 /* Tell the linker that we have initializer and finalizer functions. */
1411 #ifdef LD_INIT_SWITCH
1412 *ld2++ = LD_INIT_SWITCH;
1414 *ld2++ = LD_FINI_SWITCH;
1419 #ifdef COLLECT_EXPORT_LIST
1422 add_to_list (&exports, initname);
1423 add_to_list (&exports, fininame);
1424 add_to_list (&exports, "_GLOBAL__DI");
1425 add_to_list (&exports, "_GLOBAL__DD");
1426 exportf = fopen (export_file, "w");
1427 if (exportf == (FILE *) 0)
1428 fatal_perror ("%s", export_file);
1429 write_export_file (exportf);
1430 if (fclose (exportf))
1431 fatal_perror ("closing %s", export_file);
1437 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1438 output_file, c_file);
1439 write_c_file (stderr, "stderr");
1440 fprintf (stderr, "========== end of c_file\n\n");
1441 #ifdef COLLECT_EXPORT_LIST
1442 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1443 write_export_file (stderr);
1444 fprintf (stderr, "========== end of export_file\n\n");
1448 /* Assemble the constructor and destructor tables.
1449 Link the tables in with the rest of the program. */
1451 fork_execute ("gcc", c_argv);
1452 fork_execute ("ld", ld2_argv);
1454 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1455 constructors/destructors in shared libraries. */
1456 scan_prog_file (output_file, PASS_SECOND);
1458 maybe_unlink (c_file);
1459 maybe_unlink (o_file);
1460 maybe_unlink (export_file);
1465 /* Wait for a process to finish, and exit if a non-zero status is found. */
1476 if (WIFSIGNALED (status))
1478 int sig = WTERMSIG (status);
1479 #ifdef NO_SYS_SIGLIST
1480 error ("%s terminated with signal %d %s",
1483 (status & 0200) ? ", core dumped" : "");
1485 error ("%s terminated with signal %d [%s]%s",
1489 (status & 0200) ? ", core dumped" : "");
1495 if (WIFEXITED (status))
1496 return WEXITSTATUS (status);
1505 int ret = collect_wait (prog);
1508 error ("%s returned %d exit status", prog, ret);
1514 /* Fork and execute a program, and wait for the reply. */
1517 collect_execute (prog, argv, redir)
1530 fprintf (stderr, "%s", argv[0]);
1532 fprintf (stderr, "[cannot find %s]", prog);
1534 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1535 fprintf (stderr, " %s", str);
1537 fprintf (stderr, "\n");
1543 /* If we can't find a program we need, complain error. Do this here
1544 since we might not end up needing something that we couldn't find. */
1547 fatal ("cannot find `%s'", prog);
1553 fatal_perror ("fork");
1555 fatal_perror ("vfork");
1559 if (pid == 0) /* child context */
1564 if (freopen (redir, "a", stdout) == NULL)
1565 fatal_perror ("redirecting stdout");
1566 if (freopen (redir, "a", stderr) == NULL)
1567 fatal_perror ("redirecting stderr");
1570 execvp (argv[0], argv);
1571 fatal_perror ("executing %s", prog);
1576 fork_execute (prog, argv)
1580 collect_execute (prog, argv, NULL);
1584 /* Unlink a file unless we are debugging. */
1593 fprintf (stderr, "[Leaving %s]\n", file);
1597 /* Add a name to a linked list. */
1600 add_to_list (head_ptr, name)
1601 struct head *head_ptr;
1605 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1607 static long sequence_number = 0;
1608 strcpy (newid->name, name);
1610 if (head_ptr->first)
1611 head_ptr->last->next = newid;
1613 head_ptr->first = newid;
1615 /* Check for duplicate symbols. */
1616 for (p = head_ptr->first;
1617 strcmp (name, p->name) != 0;
1622 head_ptr->last->next = 0;
1627 newid->sequence = ++sequence_number;
1628 head_ptr->last = newid;
1632 /* Write: `prefix', the names on list LIST, `suffix'. */
1635 write_list (stream, prefix, list)
1642 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1648 write_list_with_asm (stream, prefix, list)
1655 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1656 prefix, list->sequence, list->name);
1661 /* Write out the constructor and destructor tables statically (for a shared
1662 object), along with the functions to execute them. */
1665 write_c_file_stat (stream, name)
1669 char *prefix, *p, *q;
1671 /* Figure out name of output_file, stripping off .so version. */
1672 p = rindex (output_file, '/');
1674 p = (char *) output_file;
1688 if (strncmp (q, ".so", 3) == 0)
1697 /* q points to null at end of the string (or . of the .so version) */
1698 prefix = xmalloc (q - p + 1);
1699 strncpy (prefix, p, q - p);
1701 for (q = prefix; *q; q++)
1705 fprintf (stderr, "\nwrite_c_file - output name is %s, prefix is %s\n",
1706 output_file, prefix);
1708 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1709 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1710 sprintf (initname, INIT_NAME_FORMAT, prefix);
1712 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1713 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1714 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1718 /* Write the tables as C code */
1720 fprintf (stream, "static int count;\n");
1721 fprintf (stream, "typedef void entry_pt();\n");
1722 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1723 fprintf (stream, "void %s() {\n", initname);
1724 if (constructors.number > 0)
1726 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1727 write_list (stream, "\t\t", constructors.first);
1728 fprintf (stream, "\t};\n");
1729 fprintf (stream, "\tentry_pt **p;\n");
1730 fprintf (stream, "\tif (count++ != 0) return;\n");
1731 fprintf (stream, "\tp = ctors + %d;\n", constructors.number);
1732 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1735 fprintf (stream, "\t++count;\n");
1736 fprintf (stream, "}\n");
1737 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1738 fprintf (stream, "void %s() {\n", fininame);
1739 if (destructors.number > 0)
1741 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1742 write_list (stream, "\t\t", destructors.first);
1743 fprintf (stream, "\t};\n");
1744 fprintf (stream, "\tentry_pt **p;\n");
1745 fprintf (stream, "\tif (--count != 0) return;\n");
1746 fprintf (stream, "\tp = dtors;\n");
1747 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1748 destructors.number);
1750 fprintf (stream, "}\n");
1754 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
1755 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
1759 /* Write the constructor/destructor tables. */
1762 write_c_file_glob (stream, name)
1766 /* Write the tables as C code */
1768 fprintf (stream, "typedef void entry_pt();\n\n");
1770 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1772 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
1773 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number);
1774 write_list (stream, "\t", constructors.first);
1775 fprintf (stream, "\t0\n};\n\n");
1777 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1779 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
1780 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number);
1781 write_list (stream, "\t", destructors.first);
1782 fprintf (stream, "\t0\n};\n\n");
1784 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
1785 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
1789 write_c_file (stream, name)
1793 #ifndef LD_INIT_SWITCH
1795 write_c_file_glob (stream, name);
1798 write_c_file_stat (stream, name);
1802 write_export_file (stream)
1805 struct id *list = exports.first;
1806 for (; list; list = list->next)
1807 fprintf (stream, "%s\n", list->name);
1810 #ifdef OBJECT_FORMAT_NONE
1812 /* Generic version to scan the name list of the loaded program for
1813 the symbols g++ uses for static constructors and destructors.
1815 The constructor table begins at __CTOR_LIST__ and contains a count
1816 of the number of pointers (or -1 if the constructors are built in a
1817 separate section by the linker), followed by the pointers to the
1818 constructor functions, terminated with a null pointer. The
1819 destructor table has the same format, and begins at __DTOR_LIST__. */
1822 scan_prog_file (prog_name, which_pass)
1824 enum pass which_pass;
1826 void (*int_handler) ();
1827 void (*quit_handler) ();
1835 if (which_pass == PASS_SECOND)
1838 /* If we don't have an `nm', complain. */
1839 if (nm_file_name == 0)
1840 fatal ("cannot find `nm'");
1842 nm_argv[argc++] = nm_file_name;
1843 if (NM_FLAGS[0] != '\0')
1844 nm_argv[argc++] = NM_FLAGS;
1846 nm_argv[argc++] = prog_name;
1847 nm_argv[argc++] = (char *) 0;
1849 if (pipe (pipe_fd) < 0)
1850 fatal_perror ("pipe");
1852 inf = fdopen (pipe_fd[0], "r");
1853 if (inf == (FILE *) 0)
1854 fatal_perror ("fdopen");
1856 /* Trace if needed. */
1862 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
1863 fprintf (stderr, " %s", str);
1865 fprintf (stderr, "\n");
1871 /* Spawn child nm on pipe */
1876 fatal_perror ("fork");
1878 fatal_perror ("vfork");
1882 if (pid == 0) /* child context */
1885 if (dup2 (pipe_fd[1], 1) < 0)
1886 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
1888 if (close (pipe_fd[0]) < 0)
1889 fatal_perror ("close (%d)", pipe_fd[0]);
1891 if (close (pipe_fd[1]) < 0)
1892 fatal_perror ("close (%d)", pipe_fd[1]);
1894 execv (nm_file_name, nm_argv);
1895 fatal_perror ("executing %s", nm_file_name);
1898 /* Parent context from here on. */
1899 int_handler = (void (*) ())signal (SIGINT, SIG_IGN);
1901 quit_handler = (void (*) ())signal (SIGQUIT, SIG_IGN);
1904 if (close (pipe_fd[1]) < 0)
1905 fatal_perror ("close (%d)", pipe_fd[1]);
1908 fprintf (stderr, "\nnm output with constructors/destructors.\n");
1910 /* Read each line of nm output. */
1911 while (fgets (buf, sizeof buf, inf) != (char *) 0)
1916 /* If it contains a constructor or destructor name, add the name
1917 to the appropriate list. */
1919 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
1920 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
1927 /* Find the end of the symbol name.
1928 Don't include `|', because Encore nm can tack that on the end. */
1929 for (end = p; (ch2 = *end) != '\0' && !isspace (ch2) && ch2 != '|';
1935 switch (is_ctor_dtor (name))
1938 if (which_pass != PASS_LIB)
1939 add_to_list (&constructors, name);
1943 if (which_pass != PASS_LIB)
1944 add_to_list (&destructors, name);
1948 if (which_pass != PASS_LIB)
1949 fatal ("init function found in object %s", prog_name);
1950 #ifndef LD_INIT_SWITCH
1951 add_to_list (&constructors, name);
1956 if (which_pass != PASS_LIB)
1957 fatal ("fini function found in object %s", prog_name);
1958 #ifndef LD_FINI_SWITCH
1959 add_to_list (&destructors, name);
1963 default: /* not a constructor or destructor */
1968 fprintf (stderr, "\t%s\n", buf);
1972 fprintf (stderr, "\n");
1974 if (fclose (inf) != 0)
1975 fatal_perror ("fclose of pipe");
1977 do_wait (nm_file_name);
1979 signal (SIGINT, int_handler);
1981 signal (SIGQUIT, quit_handler);
1985 #if SUNOS4_SHARED_LIBRARIES
1987 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
1988 that the output file depends upon and their initialization/finalization
1989 routines, if any. */
1994 #include <sys/mman.h>
1995 #include <sys/param.h>
1997 #include <sys/dir.h>
1999 /* pointers to the object file */
2000 unsigned object; /* address of memory mapped file */
2001 unsigned objsize; /* size of memory mapped to file */
2002 char * code; /* pointer to code segment */
2003 char * data; /* pointer to data segment */
2004 struct nlist *symtab; /* pointer to symbol table */
2005 struct link_dynamic *ld;
2006 struct link_dynamic_2 *ld_2;
2007 struct head libraries;
2009 /* Map the file indicated by NAME into memory and store its address. */
2017 if ((fp = open (name, O_RDONLY)) == -1)
2018 fatal ("unable to open file '%s'", name);
2019 if (fstat (fp, &s) == -1)
2020 fatal ("unable to stat file '%s'", name);
2022 objsize = s.st_size;
2023 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2026 fatal ("unable to mmap file '%s'", name);
2031 /* Helpers for locatelib. */
2033 static char *libname;
2039 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2042 /* If one file has an additional numeric extension past LIBNAME, then put
2043 that one first in the sort. If both files have additional numeric
2044 extensions, then put the one with the higher number first in the sort.
2046 We must verify that the extension is numeric, because Sun saves the
2047 original versions of patched libraries with a .FCS extension. Files with
2048 invalid extensions must go last in the sort, so that they won't be used. */
2052 struct direct **d1, **d2;
2054 int i1, i2 = strlen (libname);
2055 char *e1 = (*d1)->d_name + i2;
2056 char *e2 = (*d2)->d_name + i2;
2058 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2059 && e1[1] && isdigit (e1[1]) && e2[1] && isdigit (e2[1]))
2063 i1 = strtol (e1, &e1, 10);
2064 i2 = strtol (e2, &e2, 10);
2071 /* It has a valid numeric extension, prefer this one. */
2072 if (*e1 == '.' && e1[1] && isdigit (e1[1]))
2074 /* It has a invalid numeric extension, must prefer the other one. */
2080 /* It has a valid numeric extension, prefer this one. */
2081 if (*e2 == '.' && e2[1] && isdigit (e2[1]))
2083 /* It has a invalid numeric extension, must prefer the other one. */
2091 /* Given the name NAME of a dynamic dependency, find its pathname and add
2092 it to the list of libraries. */
2100 char buf[MAXPATHLEN];
2108 /* counting elements in array, need 1 extra for null */
2110 ld_rules = (char *) (ld_2->ld_rules + code);
2114 for (; *ld_rules != 0; ld_rules++)
2115 if (*ld_rules == ':')
2117 ld_rules = (char *) (ld_2->ld_rules + code);
2118 ldr = (char *) malloc (strlen (ld_rules) + 1);
2119 strcpy (ldr, ld_rules);
2121 p = getenv ("LD_LIBRARY_PATH");
2126 for (q = p ; *q != 0; q++)
2129 q = (char *) malloc (strlen (p) + 1);
2132 l = (char **) malloc ((cnt + 3) * sizeof (char *));
2137 for (; *ldr != 0; ldr++)
2147 for (; *q != 0; q++)
2154 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2157 *pp++ = "/usr/local/lib";
2161 for (pp = l; *pp != 0 ; pp++)
2163 struct direct **namelist;
2165 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2167 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2168 add_to_list (&libraries, buf);
2170 fprintf (stderr, "%s\n", buf);
2177 fprintf (stderr, "not found\n");
2179 fatal ("dynamic dependency %s not found", name);
2183 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2184 that it depends upon and any constructors or destructors they contain. */
2187 scan_libraries (prog_name)
2190 struct exec *header;
2192 struct link_object *lo;
2193 char buff[MAXPATHLEN];
2196 mapfile (prog_name);
2197 header = (struct exec *)object;
2198 if (N_BADMAG (*header))
2199 fatal ("bad magic number in file '%s'", prog_name);
2200 if (header->a_dynamic == 0)
2203 code = (char *) (N_TXTOFF (*header) + (long) header);
2204 data = (char *) (N_DATOFF (*header) + (long) header);
2205 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2207 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2210 ld = (struct link_dynamic *) (symtab->n_value + code);
2216 ld = (struct link_dynamic *) data;
2221 fprintf (stderr, "dynamic dependencies.\n");
2223 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2224 for (lo = (struct link_object *) ld_2->ld_need; lo;
2225 lo = (struct link_object *) lo->lo_next)
2228 lo = (struct link_object *) ((long) lo + code);
2229 name = (char *) (code + lo->lo_name);
2233 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2234 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2240 fprintf (stderr, "\t%s\n", name);
2241 add_to_list (&libraries, name);
2246 fprintf (stderr, "\n");
2248 /* now iterate through the library list adding their symbols to
2250 for (list = libraries.first; list; list = list->next)
2251 scan_prog_file (list->name, PASS_LIB);
2254 #else /* SUNOS4_SHARED_LIBRARIES */
2257 /* Use the List Dynamic Dependencies program to find shared libraries that
2258 the output file depends upon and their initialization/finalization
2259 routines, if any. */
2262 scan_libraries (prog_name)
2265 static struct head libraries; /* list of shared libraries found */
2267 void (*int_handler) ();
2268 void (*quit_handler) ();
2276 /* If we don't have an `ldd', complain. */
2277 if (ldd_file_name == 0)
2279 error ("cannot find `ldd'");
2283 ldd_argv[argc++] = ldd_file_name;
2284 ldd_argv[argc++] = prog_name;
2285 ldd_argv[argc++] = (char *) 0;
2287 if (pipe (pipe_fd) < 0)
2288 fatal_perror ("pipe");
2290 inf = fdopen (pipe_fd[0], "r");
2291 if (inf == (FILE *) 0)
2292 fatal_perror ("fdopen");
2294 /* Trace if needed. */
2300 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2301 fprintf (stderr, " %s", str);
2303 fprintf (stderr, "\n");
2309 /* Spawn child ldd on pipe */
2314 fatal_perror ("fork");
2316 fatal_perror ("vfork");
2320 if (pid == 0) /* child context */
2323 if (dup2 (pipe_fd[1], 1) < 0)
2324 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2326 if (close (pipe_fd[0]) < 0)
2327 fatal_perror ("close (%d)", pipe_fd[0]);
2329 if (close (pipe_fd[1]) < 0)
2330 fatal_perror ("close (%d)", pipe_fd[1]);
2332 execv (ldd_file_name, ldd_argv);
2333 fatal_perror ("executing %s", ldd_file_name);
2336 /* Parent context from here on. */
2337 int_handler = (void (*) ()) signal (SIGINT, SIG_IGN);
2339 quit_handler = (void (*) ()) signal (SIGQUIT, SIG_IGN);
2342 if (close (pipe_fd[1]) < 0)
2343 fatal_perror ("close (%d)", pipe_fd[1]);
2346 fprintf (stderr, "\nldd output with constructors/destructors.\n");
2348 /* Read each line of ldd output. */
2349 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2352 char *name, *end, *p = buf;
2354 /* Extract names of libraries and add to list. */
2355 PARSE_LDD_OUTPUT (p);
2360 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2361 fatal ("dynamic dependency %s not found", buf);
2363 /* Find the end of the symbol name. */
2365 (ch2 = *end) != '\0' && ch2 != '\n' && !isspace (ch2) && ch2 != '|';
2370 if (access (name, R_OK) == 0)
2371 add_to_list (&libraries, name);
2373 fatal ("unable to open dynamic dependency '%s'", buf);
2376 fprintf (stderr, "\t%s\n", buf);
2379 fprintf (stderr, "\n");
2381 if (fclose (inf) != 0)
2382 fatal_perror ("fclose of pipe");
2384 do_wait (ldd_file_name);
2386 signal (SIGINT, int_handler);
2388 signal (SIGQUIT, quit_handler);
2391 /* now iterate through the library list adding their symbols to
2393 for (list = libraries.first; list; list = list->next)
2394 scan_prog_file (list->name, PASS_LIB);
2397 #endif /* LDD_SUFFIX */
2398 #endif /* SUNOS4_SHARED_LIBRARIES */
2400 #endif /* OBJECT_FORMAT_NONE */
2404 * COFF specific stuff.
2407 #ifdef OBJECT_FORMAT_COFF
2409 #if defined(EXTENDED_COFF)
2410 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2411 # define GCC_SYMENT SYMR
2412 # define GCC_OK_SYMBOL(X) ((X).st == stProc && (X).sc == scText)
2413 # define GCC_SYMINC(X) (1)
2414 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2415 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2417 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2418 # define GCC_SYMENT SYMENT
2419 # define GCC_OK_SYMBOL(X) \
2420 (((X).n_sclass == C_EXT) && \
2421 (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) || \
2422 ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT)))
2423 # define GCC_SYMINC(X) ((X).n_numaux+1)
2424 # define GCC_SYMZERO(X) 0
2425 # define GCC_CHECK_HDR(X) (1)
2428 extern char *ldgetname ();
2430 /* COFF version to scan the name list of the loaded program for
2431 the symbols g++ uses for static constructors and destructors.
2433 The constructor table begins at __CTOR_LIST__ and contains a count
2434 of the number of pointers (or -1 if the constructors are built in a
2435 separate section by the linker), followed by the pointers to the
2436 constructor functions, terminated with a null pointer. The
2437 destructor table has the same format, and begins at __DTOR_LIST__. */
2440 scan_prog_file (prog_name, which_pass)
2442 enum pass which_pass;
2444 LDFILE *ldptr = NULL;
2445 int sym_index, sym_count;
2447 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2450 if ((ldptr = ldopen (prog_name, ldptr)) == NULL)
2451 fatal ("%s: can't open as COFF file", prog_name);
2453 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2454 fatal ("%s: not a COFF file", prog_name);
2456 if (GCC_CHECK_HDR (ldptr))
2458 sym_count = GCC_SYMBOLS (ldptr);
2459 sym_index = GCC_SYMZERO (ldptr);
2460 while (sym_index < sym_count)
2464 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2466 sym_index += GCC_SYMINC (symbol);
2468 if (GCC_OK_SYMBOL (symbol))
2472 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2473 continue; /* should never happen */
2475 #ifdef XCOFF_DEBUGGING_INFO
2476 /* All AIX function names have a duplicate entry beginning
2482 switch (is_ctor_dtor (name))
2485 add_to_list (&constructors, name);
2486 if (which_pass == PASS_OBJ)
2487 add_to_list (&exports, name);
2491 add_to_list (&destructors, name);
2492 if (which_pass == PASS_OBJ)
2493 add_to_list (&exports, name);
2496 default: /* not a constructor or destructor */
2500 #if !defined(EXTENDED_COFF)
2502 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2503 symbol.n_scnum, symbol.n_sclass,
2504 (symbol.n_type ? "0" : ""), symbol.n_type,
2508 fprintf (stderr, "\tiss = %5d, value = %5d, index = %5d, name = %s\n",
2509 symbol.iss, symbol.value, symbol.index, name);
2515 (void) ldclose(ldptr);
2518 #ifdef XCOFF_SCAN_LIBS
2519 /* Scan imported AIX libraries for GCC static ctors and dtors.
2520 FIXME: it is possible to link an executable without the actual import
2521 library by using an "import file" - a text file listing symbols
2522 exported by a library. To support this, we would have to scan
2523 import files as well as actual shared binaries to find GCC ctors.
2524 TODO: use memory mapping instead of 'ld' routines, files are already
2525 memory mapped, but we could eliminate the extra in-memory copies.
2526 Is it worth the effort? */
2529 scan_libraries (prog_name)
2534 static struct path_prefix libpath; /* we should only do this once */
2536 if ((ldptr = ldopen (prog_name, ldptr)) == NULL)
2537 fatal ("%s: can't open as COFF file", prog_name);
2539 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2540 fatal ("%s: not a COFF file", prog_name);
2542 /* find and read loader section */
2543 if (ldnshread (ldptr, _LOADER, &ldsh))
2549 FSEEK (ldptr, ldsh.s_scnptr, BEGINNING);
2550 FREAD (&ldh, sizeof (ldh), 1, ldptr);
2551 /* read import library list */
2552 impbuf = alloca (ldh.l_istlen);
2553 FSEEK (ldptr, ldh.l_impoff + ldsh.s_scnptr, BEGINNING);
2554 FREAD (impbuf, ldh.l_istlen, 1, ldptr);
2557 fprintf (stderr, "LIBPATH=%s\n", impbuf);
2558 prefix_from_string (impbuf, &libpath);
2560 /* skip LIBPATH and empty base and member fields */
2561 impbuf += strlen (impbuf) + 3;
2562 for (entry = 1; entry < ldh.l_nimpid; ++entry)
2564 char *impath = impbuf;
2565 char *implib = impath + strlen (impath) + 1;
2566 char *impmem = implib + strlen (implib) + 1;
2567 char *soname = NULL;
2570 LDFILE *libptr = NULL;
2571 struct prefix_list *pl;
2574 impbuf = impmem + strlen (impmem) + 1;
2576 fprintf (stderr, "PATH+BASE=%s%s\n", impath, implib);
2577 /* Skip AIX kernel exports */
2578 if (*impath == '/' && *(impath+1) == '\0'
2579 && strcmp (implib, "unix") == 0)
2581 pathlen = strlen (impath);
2582 trial = alloca (MAX (pathlen + 1, libpath.max_len)
2583 + strlen (implib) + 1);
2586 strcpy (trial, impath);
2587 if (impath[pathlen - 1] != '/')
2588 trial[pathlen++] = '/';
2589 strcpy (trial + pathlen, implib);
2590 if (access (trial, R_OK) == 0)
2594 for (pl = libpath.plist; pl; pl = pl->next)
2596 strcpy (trial, pl->prefix);
2597 strcat (trial, implib);
2598 if (access (trial, R_OK) == 0)
2606 fatal ("%s: library not found", implib);
2609 fprintf (stderr, "%s (%s)\n", soname, impmem);
2611 fprintf (stderr, "%s\n", soname);
2615 /* scan imported shared objects for GCC GLOBAL ctors */
2617 if ((libptr = ldopen (soname, libptr)) == NULL)
2618 fatal ("%s: can't open import library", soname);
2619 if (TYPE (libptr) == ARTYPE)
2623 fatal ("%s: no archive member specified", soname);
2624 ldahread (libptr, &ah);
2625 if (strcmp (ah.ar_name, impmem))
2628 type = HEADER (libptr).f_magic;
2629 if (HEADER (libptr).f_flags & F_SHROBJ)
2636 if (!ldnshread (libptr, _LOADER, &soldsh))
2637 fatal ("%s: not an import library", soname);
2638 FSEEK (libptr, soldsh.s_scnptr, BEGINNING);
2639 if (FREAD (&soldh, sizeof (soldh), 1, libptr) != 1)
2640 fatal ("%s: can't read loader section", soname);
2641 /*fprintf (stderr, "\tscanning %s\n", soname);*/
2642 symcnt = soldh.l_nsyms;
2643 lsyms = (LDSYM *) alloca (symcnt * sizeof (*lsyms));
2644 symcnt = FREAD (lsyms, sizeof (*lsyms), symcnt, libptr);
2645 ldstrings = alloca (soldh.l_stlen);
2646 FSEEK (libptr, soldsh.s_scnptr+soldh.l_stoff, BEGINNING);
2647 FREAD (ldstrings, soldh.l_stlen, 1, libptr);
2648 for (i = 0; i < symcnt; ++i)
2650 LDSYM *l = lsyms + i;
2651 if (LDR_EXPORT (*l))
2655 expname = l->l_name;
2656 else if (l->l_offset < soldh.l_stlen)
2657 expname = ldstrings + l->l_offset;
2658 switch (is_ctor_dtor (expname))
2662 fprintf (stderr, "\t%s\n", expname);
2663 add_to_list (&constructors, expname);
2667 add_to_list (&destructors, expname);
2670 default: /* not a constructor or destructor */
2677 fprintf (stderr, "%s: type = %04X flags = %04X\n",
2678 ah.ar_name, type, HEADER (libptr).f_flags);
2680 while (ldclose (libptr) == FAILURE);
2681 /* printf (stderr, "closed %s\n", soname); */
2685 #endif /* XCOFF_SCAN_LIBS */
2687 #endif /* OBJECT_FORMAT_COFF */
2691 * OSF/rose specific stuff.
2694 #ifdef OBJECT_FORMAT_ROSE
2696 /* Union of the various load commands */
2698 typedef union load_union
2700 ldc_header_t hdr; /* common header */
2701 load_cmd_map_command_t map; /* map indexing other load cmds */
2702 interpreter_command_t iprtr; /* interpreter pathname */
2703 strings_command_t str; /* load commands strings section */
2704 region_command_t region; /* region load command */
2705 reloc_command_t reloc; /* relocation section */
2706 package_command_t pkg; /* package load command */
2707 symbols_command_t sym; /* symbol sections */
2708 entry_command_t ent; /* program start section */
2709 gen_info_command_t info; /* object information */
2710 func_table_command_t func; /* function constructors/destructors */
2713 /* Structure to point to load command and data section in memory. */
2715 typedef struct load_all
2717 load_union_t *load; /* load command */
2718 char *section; /* pointer to section */
2721 /* Structure to contain information about a file mapped into memory. */
2725 char *start; /* start of map */
2726 char *name; /* filename */
2727 long size; /* size of the file */
2728 long rounded_size; /* size rounded to page boundary */
2729 int fd; /* file descriptor */
2730 int rw; /* != 0 if opened read/write */
2731 int use_mmap; /* != 0 if mmap'ed */
2734 extern int decode_mach_o_hdr ();
2735 extern int encode_mach_o_hdr ();
2737 static void add_func_table PROTO((mo_header_t *, load_all_t *,
2738 symbol_info_t *, int));
2739 static void print_header PROTO((mo_header_t *));
2740 static void print_load_command PROTO((load_union_t *, size_t, int));
2741 static void bad_header PROTO((int));
2742 static struct file_info *read_file PROTO((char *, int, int));
2743 static void end_file PROTO((struct file_info *));
2745 /* OSF/rose specific version to scan the name list of the loaded
2746 program for the symbols g++ uses for static constructors and
2749 The constructor table begins at __CTOR_LIST__ and contains a count
2750 of the number of pointers (or -1 if the constructors are built in a
2751 separate section by the linker), followed by the pointers to the
2752 constructor functions, terminated with a null pointer. The
2753 destructor table has the same format, and begins at __DTOR_LIST__. */
2756 scan_prog_file (prog_name, which_pass)
2758 enum pass which_pass;
2762 load_all_t *load_array;
2763 load_all_t *load_end;
2764 load_all_t *load_cmd;
2765 int symbol_load_cmds;
2771 struct file_info *obj_file;
2773 mo_lcid_t cmd_strings = -1;
2774 symbol_info_t *main_sym = 0;
2775 int rw = (which_pass != PASS_FIRST);
2777 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
2779 fatal_perror ("can't read %s", prog_name);
2781 obj_file = read_file (prog_name, prog_fd, rw);
2782 obj = obj_file->start;
2784 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
2785 if (status != MO_HDR_CONV_SUCCESS)
2786 bad_header (status);
2789 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
2790 since the hardware will automatically swap bytes for us on loading little endian
2793 #ifndef CROSS_COMPILE
2794 if (hdr.moh_magic != MOH_MAGIC_MSB
2795 || hdr.moh_header_version != MOH_HEADER_VERSION
2796 || hdr.moh_byte_order != OUR_BYTE_ORDER
2797 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
2798 || hdr.moh_cpu_type != OUR_CPU_TYPE
2799 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
2800 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
2802 fatal ("incompatibilities between object file & expected values");
2807 print_header (&hdr);
2809 offset = hdr.moh_first_cmd_off;
2810 load_end = load_array
2811 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
2813 /* Build array of load commands, calculating the offsets */
2814 for (i = 0; i < hdr.moh_n_load_cmds; i++)
2816 load_union_t *load_hdr; /* load command header */
2818 load_cmd = load_end++;
2819 load_hdr = (load_union_t *) (obj + offset);
2821 /* If modifying the program file, copy the header. */
2824 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
2825 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
2828 /* null out old command map, because we will rewrite at the end. */
2829 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
2831 cmd_strings = ptr->map.lcm_ld_cmd_strings;
2832 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
2836 load_cmd->load = load_hdr;
2837 if (load_hdr->hdr.ldci_section_off > 0)
2838 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
2841 print_load_command (load_hdr, offset, i);
2843 offset += load_hdr->hdr.ldci_cmd_size;
2846 /* If the last command is the load command map and is not undefined,
2847 decrement the count of load commands. */
2848 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
2851 hdr.moh_n_load_cmds--;
2854 /* Go through and process each symbol table section. */
2855 symbol_load_cmds = 0;
2856 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
2858 load_union_t *load_hdr = load_cmd->load;
2860 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
2866 char *kind = "unknown";
2868 switch (load_hdr->sym.symc_kind)
2870 case SYMC_IMPORTS: kind = "imports"; break;
2871 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
2872 case SYMC_STABS: kind = "stabs"; break;
2875 fprintf (stderr, "\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
2876 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
2879 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
2882 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
2883 if (str_sect == (char *) 0)
2884 fatal ("string section missing");
2886 if (load_cmd->section == (char *) 0)
2887 fatal ("section pointer missing");
2889 num_syms = load_hdr->sym.symc_nentries;
2890 for (i = 0; i < num_syms; i++)
2892 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
2893 char *name = sym->si_name.symbol_name + str_sect;
2900 char *n = name + strlen (name) - strlen (NAME__MAIN);
2902 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
2912 switch (is_ctor_dtor (name))
2915 add_to_list (&constructors, name);
2919 add_to_list (&destructors, name);
2922 default: /* not a constructor or destructor */
2928 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
2929 sym->si_type, sym->si_sc_type, sym->si_flags, name);
2934 if (symbol_load_cmds == 0)
2935 fatal ("no symbol table found");
2937 /* Update the program file now, rewrite header and load commands. At present,
2938 we assume that there is enough space after the last load command to insert
2939 one more. Since the first section written out is page aligned, and the
2940 number of load commands is small, this is ok for the present. */
2944 load_union_t *load_map;
2947 if (cmd_strings == -1)
2948 fatal ("no cmd_strings found");
2950 /* Add __main to initializer list.
2951 If we are building a program instead of a shared library, don't
2952 do anything, since in the current version, you cannot do mallocs
2953 and such in the constructors. */
2955 if (main_sym != (symbol_info_t *) 0
2956 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
2957 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
2960 fprintf (stderr, "\nUpdating header and load commands.\n\n");
2962 hdr.moh_n_load_cmds++;
2963 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
2965 /* Create new load command map. */
2967 fprintf (stderr, "load command map, %d cmds, new size %ld.\n",
2968 (int)hdr.moh_n_load_cmds, (long)size);
2970 load_map = (load_union_t *) xcalloc (1, size);
2971 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
2972 load_map->map.ldc_header.ldci_cmd_size = size;
2973 load_map->map.lcm_ld_cmd_strings = cmd_strings;
2974 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
2975 load_array[hdr.moh_n_load_cmds-1].load = load_map;
2977 offset = hdr.moh_first_cmd_off;
2978 for (i = 0; i < hdr.moh_n_load_cmds; i++)
2980 load_map->map.lcm_map[i] = offset;
2981 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
2982 hdr.moh_load_map_cmd_off = offset;
2984 offset += load_array[i].load->hdr.ldci_cmd_size;
2987 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
2990 print_header (&hdr);
2993 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
2994 if (status != MO_HDR_CONV_SUCCESS)
2995 bad_header (status);
2998 fprintf (stderr, "writing load commands.\n\n");
3000 /* Write load commands */
3001 offset = hdr.moh_first_cmd_off;
3002 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3004 load_union_t *load_hdr = load_array[i].load;
3005 size_t size = load_hdr->hdr.ldci_cmd_size;
3008 print_load_command (load_hdr, offset, i);
3010 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3015 end_file (obj_file);
3017 if (close (prog_fd))
3018 fatal_perror ("closing %s", prog_name);
3021 fprintf (stderr, "\n");
3025 /* Add a function table to the load commands to call a function
3026 on initiation or termination of the process. */
3029 add_func_table (hdr_p, load_array, sym, type)
3030 mo_header_t *hdr_p; /* pointer to global header */
3031 load_all_t *load_array; /* array of ptrs to load cmds */
3032 symbol_info_t *sym; /* pointer to symbol entry */
3033 int type; /* fntc_type value */
3035 /* Add a new load command. */
3036 int num_cmds = ++hdr_p->moh_n_load_cmds;
3037 int load_index = num_cmds - 1;
3038 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3039 load_union_t *ptr = xcalloc (1, size);
3040 load_all_t *load_cmd;
3043 /* Set the unresolved address bit in the header to force the loader to be
3044 used, since kernel exec does not call the initialization functions. */
3045 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3047 load_cmd = &load_array[load_index];
3048 load_cmd->load = ptr;
3049 load_cmd->section = (char *) 0;
3051 /* Fill in func table load command. */
3052 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3053 ptr->func.ldc_header.ldci_cmd_size = size;
3054 ptr->func.ldc_header.ldci_section_off = 0;
3055 ptr->func.ldc_header.ldci_section_len = 0;
3056 ptr->func.fntc_type = type;
3057 ptr->func.fntc_nentries = 1;
3059 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3060 /* Is the symbol already expressed as (region, offset)? */
3061 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3063 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3064 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3067 /* If not, figure out which region it's in. */
3070 mo_vm_addr_t addr = sym->si_value.abs_val;
3073 for (i = 0; i < load_index; i++)
3075 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3077 region_command_t *region_ptr = &load_array[i].load->region;
3079 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3080 && addr >= region_ptr->regc_addr.vm_addr
3081 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3083 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3084 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3092 fatal ("could not convert 0x%l.8x into a region", addr);
3097 "%s function, region %d, offset = %ld (0x%.8lx)\n",
3098 (type == FNTC_INITIALIZATION) ? "init" : "term",
3099 (int)ptr->func.fntc_entry_loc[i].adr_lcid,
3100 (long)ptr->func.fntc_entry_loc[i].adr_sctoff,
3101 (long)ptr->func.fntc_entry_loc[i].adr_sctoff);
3106 /* Print the global header for an OSF/rose object. */
3109 print_header (hdr_ptr)
3110 mo_header_t *hdr_ptr;
3112 fprintf (stderr, "\nglobal header:\n");
3113 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3114 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3115 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3116 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3117 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3118 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3119 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3120 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3121 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3122 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3123 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3124 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3125 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3126 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3127 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3129 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3130 fprintf (stderr, ", relocatable");
3132 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3133 fprintf (stderr, ", linkable");
3135 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3136 fprintf (stderr, ", execable");
3138 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3139 fprintf (stderr, ", executable");
3141 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3142 fprintf (stderr, ", unresolved");
3144 fprintf (stderr, "\n\n");
3149 /* Print a short summary of a load command. */
3152 print_load_command (load_hdr, offset, number)
3153 load_union_t *load_hdr;
3157 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3158 char *type_str = (char *) 0;
3162 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3163 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3164 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3165 case LDC_STRINGS: type_str = "STRINGS"; break;
3166 case LDC_REGION: type_str = "REGION"; break;
3167 case LDC_RELOC: type_str = "RELOC"; break;
3168 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3169 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3170 case LDC_ENTRY: type_str = "ENTRY"; break;
3171 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3172 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3176 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3178 (long) load_hdr->hdr.ldci_cmd_size,
3180 (long) load_hdr->hdr.ldci_section_off,
3181 (long) load_hdr->hdr.ldci_section_len);
3183 if (type_str == (char *) 0)
3184 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3186 else if (type != LDC_REGION)
3187 fprintf (stderr, ", ty: %s\n", type_str);
3192 switch (load_hdr->region.regc_usage_type)
3194 case REG_TEXT_T: region = ", .text"; break;
3195 case REG_DATA_T: region = ", .data"; break;
3196 case REG_BSS_T: region = ", .bss"; break;
3197 case REG_GLUE_T: region = ", .glue"; break;
3198 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3199 case REG_RDATA_T: region = ", .rdata"; break;
3200 case REG_SDATA_T: region = ", .sdata"; break;
3201 case REG_SBSS_T: region = ", .sbss"; break;
3205 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3207 (long) load_hdr->region.regc_vm_addr,
3208 (long) load_hdr->region.regc_vm_size,
3216 /* Fatal error when {en,de}code_mach_o_header fails. */
3222 char *msg = (char *) 0;
3226 case MO_ERROR_BAD_MAGIC: msg = "bad magic number"; break;
3227 case MO_ERROR_BAD_HDR_VERS: msg = "bad header version"; break;
3228 case MO_ERROR_BAD_RAW_HDR_VERS: msg = "bad raw header version"; break;
3229 case MO_ERROR_BUF2SML: msg = "raw header buffer too small"; break;
3230 case MO_ERROR_OLD_RAW_HDR_FILE: msg = "old raw header file"; break;
3231 case MO_ERROR_UNSUPPORTED_VERS: msg = "unsupported version"; break;
3234 if (msg == (char *) 0)
3235 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3241 /* Read a file into a memory buffer. */
3243 static struct file_info *
3244 read_file (name, fd, rw)
3245 char *name; /* filename */
3246 int fd; /* file descriptor */
3247 int rw; /* read/write */
3249 struct stat stat_pkt;
3250 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3252 static int page_size;
3255 if (fstat (fd, &stat_pkt) < 0)
3256 fatal_perror ("fstat %s", name);
3259 p->size = stat_pkt.st_size;
3260 p->rounded_size = stat_pkt.st_size;
3266 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3269 page_size = sysconf (_SC_PAGE_SIZE);
3271 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3272 p->start = mmap ((caddr_t) 0,
3273 (rw) ? p->rounded_size : p->size,
3274 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3275 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3279 if (p->start != (char *) 0 && p->start != (char *) -1)
3283 #endif /* USE_MMAP */
3288 fprintf (stderr, "read %s\n", name);
3291 p->start = xmalloc (p->size);
3292 if (lseek (fd, 0L, SEEK_SET) < 0)
3293 fatal_perror ("lseek to 0 on %s", name);
3295 len = read (fd, p->start, p->size);
3297 fatal_perror ("read %s", name);
3300 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3306 /* Do anything necessary to write a file back from memory. */
3310 struct file_info *ptr; /* file information block */
3318 fprintf (stderr, "msync %s\n", ptr->name);
3320 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3321 fatal_perror ("msync %s", ptr->name);
3325 fprintf (stderr, "munmap %s\n", ptr->name);
3327 if (munmap (ptr->start, ptr->size))
3328 fatal_perror ("munmap %s", ptr->name);
3331 #endif /* USE_MMAP */
3338 fprintf (stderr, "write %s\n", ptr->name);
3340 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3341 fatal_perror ("lseek to 0 on %s", ptr->name);
3343 len = write (ptr->fd, ptr->start, ptr->size);
3345 fatal_perror ("write %s", ptr->name);
3347 if (len != ptr->size)
3348 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3357 #endif /* OBJECT_FORMAT_ROSE */