1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93, 94, 95, 96, 1997 Free Software Foundation, Inc.
4 Contributed by Chris Smith (csmith@convex.com).
5 Heavily modified by Michael Meissner (meissner@cygnus.com),
6 Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
8 This file is part of GNU CC.
10 GNU CC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
15 GNU CC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with GNU CC; see the file COPYING. If not, write to
22 the Free Software Foundation, 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA. */
26 /* Build tables of static constructors and destructors and run ld. */
29 #include <sys/types.h>
53 #include "gansidecl.h"
60 extern char *sys_errlist[];
66 /* Obstack allocation and deallocation routines. */
67 #define obstack_chunk_alloc xmalloc
68 #define obstack_chunk_free free
81 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
84 #define WTERMSIG(S) ((S) & 0x7f)
87 #define WIFEXITED(S) (((S) & 0xff) == 0)
90 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
93 extern char *choose_temp_base ();
95 /* On certain systems, we have code that works by scanning the object file
96 directly. But this code uses system-specific header files and library
97 functions, so turn it off in a cross-compiler. Likewise, the names of
98 the utilities aren't correct for a cross-compiler; we have to hope that
99 cross-versions are in the proper directories. */
102 #undef SUNOS4_SHARED_LIBRARIES
103 #undef OBJECT_FORMAT_COFF
104 #undef OBJECT_FORMAT_ROSE
105 #undef MD_EXEC_PREFIX
106 #undef REAL_LD_FILE_NAME
107 #undef REAL_NM_FILE_NAME
108 #undef REAL_STRIP_FILE_NAME
111 /* If we can't use a special method, use the ordinary one:
112 run nm to find what symbols are present.
113 In a cross-compiler, this means you need a cross nm,
114 but that isn't quite as unpleasant as special headers. */
116 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
117 #define OBJECT_FORMAT_NONE
120 #ifdef OBJECT_FORMAT_COFF
129 /* Many versions of ldfcn.h define these. */
137 /* Some systems have an ISCOFF macro, but others do not. In some cases
138 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
139 that either do not have an ISCOFF macro in /usr/include or for those
140 where it is wrong. */
143 #define MY_ISCOFF(X) ISCOFF (X)
146 #ifdef XCOFF_DEBUGGING_INFO
147 #define XCOFF_SCAN_LIBS
150 #endif /* OBJECT_FORMAT_COFF */
152 #ifdef OBJECT_FORMAT_ROSE
159 #include <sys/mman.h>
163 #include <mach_o_format.h>
164 #include <mach_o_header.h>
165 #include <mach_o_vals.h>
166 #include <mach_o_types.h>
168 #endif /* OBJECT_FORMAT_ROSE */
170 #ifdef OBJECT_FORMAT_NONE
172 /* Default flags to pass to nm. */
174 #define NM_FLAGS "-p"
177 #endif /* OBJECT_FORMAT_NONE */
179 /* Some systems use __main in a way incompatible with its use in gcc, in these
180 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
181 give the same symbol without quotes for an alternative entry point. You
182 must define both, or neither. */
184 #define NAME__MAIN "__main"
185 #define SYMBOL__MAIN __main
188 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES || defined(XCOFF_SCAN_LIBS)
189 #define SCAN_LIBRARIES
193 int do_collecting = 1;
195 int do_collecting = 0;
198 /* Linked lists of constructor and destructor names. */
214 /* Enumeration giving which pass this is for scanning the program file. */
217 PASS_FIRST, /* without constructors */
218 PASS_OBJ, /* individual objects */
219 PASS_LIB, /* looking for shared libraries */
220 PASS_SECOND /* with constructors linked in */
223 #ifndef NO_SYS_SIGLIST
224 #ifndef SYS_SIGLIST_DECLARED
225 extern char *sys_siglist[];
228 extern char *version_string;
230 int vflag; /* true if -v */
231 static int rflag; /* true if -r */
232 static int strip_flag; /* true if -s */
234 int debug; /* true if -debug */
236 static int shared_obj; /* true if -shared */
238 static int temp_filename_length; /* Length of temp_filename */
239 static char *temp_filename; /* Base of temp filenames */
240 static char *c_file; /* <xxx>.c for constructor/destructor list. */
241 static char *o_file; /* <xxx>.o for constructor/destructor list. */
242 static char *export_file; /* <xxx>.x for AIX export list. */
243 char *ldout; /* File for ld errors. */
244 static char *output_file; /* Output file for ld. */
245 static char *nm_file_name; /* pathname of nm */
246 static char *ldd_file_name; /* pathname of ldd (or equivalent) */
247 static char *strip_file_name; /* pathname of strip */
248 char *c_file_name; /* pathname of gcc */
249 static char *initname, *fininame; /* names of init and fini funcs */
251 static struct head constructors; /* list of constructors found */
252 static struct head destructors; /* list of destructors found */
253 static struct head exports; /* list of exported symbols */
254 static struct head frame_tables; /* list of frame unwind info tables */
256 struct obstack temporary_obstack;
257 struct obstack permanent_obstack;
258 char * temporary_firstobj;
260 /* Defined in the automatically-generated underscore.c. */
261 extern int prepends_underscore;
263 extern char *getenv ();
264 extern char *mktemp ();
265 extern FILE *fdopen ();
267 /* Structure to hold all the directories in which to search for files to
272 char *prefix; /* String to prepend to the path. */
273 struct prefix_list *next; /* Next in linked list. */
278 struct prefix_list *plist; /* List of prefixes to try */
279 int max_len; /* Max length of a prefix in PLIST */
280 char *name; /* Name of this list (used in config stuff) */
283 void collect_exit PROTO((int));
284 void collect_execute PROTO((char *, char **, char *));
285 void dump_file PROTO((char *));
286 static void handler PROTO((int));
287 static int is_ctor_dtor PROTO((char *));
288 static int is_in_prefix_list PROTO((struct path_prefix *, char *, int));
289 static char *find_a_file PROTO((struct path_prefix *, char *));
290 static void add_prefix PROTO((struct path_prefix *, char *));
291 static void prefix_from_env PROTO((char *, struct path_prefix *));
292 static void prefix_from_string PROTO((char *, struct path_prefix *));
293 static void do_wait PROTO((char *));
294 static void fork_execute PROTO((char *, char **));
295 static void maybe_unlink PROTO((char *));
296 static void add_to_list PROTO((struct head *, char *));
297 static void write_list PROTO((FILE *, char *, struct id *));
298 static void write_list_with_asm PROTO((FILE *, char *, struct id *));
299 static void write_c_file PROTO((FILE *, char *));
300 static void write_export_file PROTO((FILE *));
301 static void scan_prog_file PROTO((char *, enum pass));
302 static void scan_libraries PROTO((char *));
307 #ifdef NEED_DECLARATION_INDEX
308 extern char *index ();
311 #ifdef NEED_DECLARATION_RINDEX
312 extern char *rindex ();
315 #ifdef NEED_DECLARATION_FREE
332 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
335 close (fdtmp[--fdx]);
351 static char buffer[30];
355 if (e > 0 && e < sys_nerr)
356 return sys_errlist[e];
358 sprintf (buffer, "Unknown error %d", e);
363 /* Delete tempfiles and exit function. */
366 collect_exit (status)
369 if (c_file != 0 && c_file[0])
370 maybe_unlink (c_file);
372 if (o_file != 0 && o_file[0])
373 maybe_unlink (o_file);
375 if (export_file != 0 && export_file[0])
376 maybe_unlink (export_file);
378 if (ldout != 0 && ldout[0])
381 maybe_unlink (ldout);
384 if (status != 0 && output_file != 0 && output_file[0])
385 maybe_unlink (output_file);
391 /* Die when sys call fails. */
394 fatal_perror (string, arg1, arg2, arg3)
395 char *string, *arg1, *arg2, *arg3;
399 fprintf (stderr, "collect2: ");
400 fprintf (stderr, string, arg1, arg2, arg3);
401 fprintf (stderr, ": %s\n", my_strerror (e));
402 collect_exit (FATAL_EXIT_CODE);
408 fatal (string, arg1, arg2, arg3)
409 char *string, *arg1, *arg2, *arg3;
411 fprintf (stderr, "collect2: ");
412 fprintf (stderr, string, arg1, arg2, arg3);
413 fprintf (stderr, "\n");
414 collect_exit (FATAL_EXIT_CODE);
417 /* Write error message. */
420 error (string, arg1, arg2, arg3, arg4)
421 char *string, *arg1, *arg2, *arg3, *arg4;
423 fprintf (stderr, "collect2: ");
424 fprintf (stderr, string, arg1, arg2, arg3, arg4);
425 fprintf (stderr, "\n");
428 /* In case obstack is linked in, and abort is defined to fancy_abort,
429 provide a default entry. */
434 fatal ("internal error");
442 if (c_file != 0 && c_file[0])
443 maybe_unlink (c_file);
445 if (o_file != 0 && o_file[0])
446 maybe_unlink (o_file);
448 if (ldout != 0 && ldout[0])
449 maybe_unlink (ldout);
451 if (export_file != 0 && export_file[0])
452 maybe_unlink (export_file);
454 signal (signo, SIG_DFL);
455 kill (getpid (), signo);
460 xcalloc (size1, size2)
463 char *ptr = (char *) calloc (size1, size2);
467 fatal ("out of memory");
475 char *ptr = (char *) malloc (size);
479 fatal ("out of memory");
488 register char *value = (char *) realloc (ptr, size);
490 fatal ("virtual memory exhausted");
498 return access (name, R_OK) == 0;
501 /* Make a copy of a string INPUT with size SIZE. */
504 savestring (input, size)
508 char *output = (char *) xmalloc (size + 1);
509 bcopy (input, output, size);
514 /* Parse a reasonable subset of shell quoting syntax. */
531 obstack_1grow (&temporary_obstack, c);
532 else if (! inside && c == ' ')
534 else if (! inside && c == '\\')
539 obstack_1grow (&temporary_obstack, c);
542 obstack_1grow (&temporary_obstack, '\0');
544 return obstack_finish (&temporary_obstack);
551 FILE *stream = fopen (name, "r");
552 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
559 while (c = getc (stream),
560 c != EOF && (isalnum (c) || c == '_' || c == '$' || c == '.'))
561 obstack_1grow (&temporary_obstack, c);
562 if (obstack_object_size (&temporary_obstack) > 0)
564 char *word, *p, *result;
565 obstack_1grow (&temporary_obstack, '\0');
566 word = obstack_finish (&temporary_obstack);
569 ++word, putc ('.', stderr);
571 if (*p == '_' && prepends_underscore)
577 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
582 fputs (result, stderr);
584 diff = strlen (word) - strlen (result);
586 --diff, putc (' ', stderr);
587 while (diff < 0 && c == ' ')
588 ++diff, c = getc (stream);
593 fputs (word, stderr);
596 obstack_free (&temporary_obstack, temporary_firstobj);
605 /* Decide whether the given symbol is:
606 a constructor (1), a destructor (2), or neither (0). */
612 struct names { char *name; int len; int ret; int two_underscores; };
614 register struct names *p;
616 register char *orig_s = s;
618 static struct names special[] = {
619 #ifdef NO_DOLLAR_IN_LABEL
620 #ifdef NO_DOT_IN_LABEL
621 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
622 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
623 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
625 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
626 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
627 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
630 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
631 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
632 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
634 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
635 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
636 #ifdef CFRONT_LOSSAGE /* Don't collect cfront initialization functions.
637 cfront has its own linker procedure to collect them;
638 if collect2 gets them too, they get collected twice
639 when the cfront procedure is run and the compiler used
640 for linking happens to be GCC. */
641 { "sti__", sizeof ("sti__")-1, 1, 1 },
642 { "std__", sizeof ("std__")-1, 2, 1 },
643 #endif /* CFRONT_LOSSAGE */
647 while ((ch = *s) == '_')
653 for (p = &special[0]; p->len > 0; p++)
656 && (!p->two_underscores || ((s - orig_s) >= 2))
657 && strncmp(s, p->name, p->len) == 0)
665 /* Routine to add variables to the environment. */
673 #ifndef VMS /* nor about VMS */
675 extern char **environ;
676 char **old_environ = environ;
683 while ((ch = *p++) != '\0' && ch != '=')
689 /* Search for replacing an existing environment variable, and
690 count the number of total environment variables. */
691 for (envp = old_environ; *envp; envp++)
694 if (!strncmp (str, *envp, name_len))
701 /* Add a new environment variable */
702 environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
704 bcopy ((char *) old_environ, (char *) (environ + 1),
705 sizeof (char *) * (num_envs+1));
711 #endif /* HAVE_PUTENV */
713 /* By default, colon separates directories in a path. */
714 #ifndef PATH_SEPARATOR
715 #define PATH_SEPARATOR ':'
718 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
719 and one from the PATH variable. */
721 static struct path_prefix cpath, path;
724 /* This is the name of the target machine. We use it to form the name
725 of the files to execute. */
727 static char *target_machine = TARGET_MACHINE;
730 /* Names under which we were executed. Never return one of those files in our
733 static struct path_prefix our_file_names;
735 /* Determine if STRING is in PPREFIX.
737 This utility is currently only used to look up file names. Prefix lists
738 record directory names. This matters to us because the latter has a
739 trailing slash, so I've added a flag to handle both. */
742 is_in_prefix_list (pprefix, string, filep)
743 struct path_prefix *pprefix;
747 struct prefix_list *pl;
751 int len = strlen (string);
753 for (pl = pprefix->plist; pl; pl = pl->next)
755 if (strncmp (pl->prefix, string, len) == 0
756 && strcmp (pl->prefix + len, "/") == 0)
762 for (pl = pprefix->plist; pl; pl = pl->next)
764 if (strcmp (pl->prefix, string) == 0)
772 /* Search for NAME using prefix list PPREFIX. We only look for executable
775 Return 0 if not found, otherwise return its name, allocated with malloc. */
778 find_a_file (pprefix, name)
779 struct path_prefix *pprefix;
783 struct prefix_list *pl;
784 int len = pprefix->max_len + strlen (name) + 1;
786 #ifdef EXECUTABLE_SUFFIX
787 len += strlen (EXECUTABLE_SUFFIX);
790 temp = xmalloc (len);
792 /* Determine the filename to execute (special case for absolute paths). */
796 if (access (name, X_OK) == 0)
803 for (pl = pprefix->plist; pl; pl = pl->next)
805 strcpy (temp, pl->prefix);
807 if (! is_in_prefix_list (&our_file_names, temp, 1)
808 /* This is a kludge, but there seems no way around it. */
809 && strcmp (temp, "./ld") != 0
810 && access (temp, X_OK) == 0)
813 #ifdef EXECUTABLE_SUFFIX
814 /* Some systems have a suffix for executable files.
815 So try appending that. */
816 strcat (temp, EXECUTABLE_SUFFIX);
817 if (! is_in_prefix_list (&our_file_names, temp, 1)
818 && access (temp, X_OK) == 0)
827 /* Add an entry for PREFIX to prefix list PPREFIX. */
830 add_prefix (pprefix, prefix)
831 struct path_prefix *pprefix;
834 struct prefix_list *pl, **prev;
839 for (pl = pprefix->plist; pl->next; pl = pl->next)
844 prev = &pprefix->plist;
846 /* Keep track of the longest prefix */
848 len = strlen (prefix);
849 if (len > pprefix->max_len)
850 pprefix->max_len = len;
852 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
853 pl->prefix = savestring (prefix, len);
858 pl->next = (struct prefix_list *) 0;
862 /* Take the value of the environment variable ENV, break it into a path, and
863 add of the entries to PPREFIX. */
866 prefix_from_env (env, pprefix)
868 struct path_prefix *pprefix;
870 char *p = getenv (env);
873 prefix_from_string (p, pprefix);
877 prefix_from_string (p, pprefix)
879 struct path_prefix *pprefix;
882 char *nstore = (char *) xmalloc (strlen (p) + 3);
887 if (*endp == PATH_SEPARATOR || *endp == 0)
889 strncpy (nstore, startp, endp-startp);
892 strcpy (nstore, "./");
894 else if (endp[-1] != '/')
896 nstore[endp-startp] = '/';
897 nstore[endp-startp+1] = 0;
900 nstore[endp-startp] = 0;
902 add_prefix (pprefix, nstore);
905 endp = startp = endp + 1;
919 char *ld_suffix = "ld";
920 char *full_ld_suffix = ld_suffix;
921 char *real_ld_suffix = "real-ld";
922 char *full_real_ld_suffix = real_ld_suffix;
923 char *collect_ld_suffix = "collect-ld";
924 char *nm_suffix = "nm";
925 char *full_nm_suffix = nm_suffix;
926 char *gnm_suffix = "gnm";
927 char *full_gnm_suffix = gnm_suffix;
929 char *ldd_suffix = LDD_SUFFIX;
930 char *full_ldd_suffix = ldd_suffix;
932 char *strip_suffix = "strip";
933 char *full_strip_suffix = strip_suffix;
934 char *gstrip_suffix = "gstrip";
935 char *full_gstrip_suffix = gstrip_suffix;
937 FILE *outf, *exportf;
944 char **ld1_argv = (char **) xcalloc (sizeof (char *), argc+3);
945 char **ld1 = ld1_argv;
946 char **ld2_argv = (char **) xcalloc (sizeof (char *), argc+6);
947 char **ld2 = ld2_argv;
948 char **object_lst = (char **) xcalloc (sizeof (char *), argc);
949 char **object = object_lst;
951 int num_c_args = argc+7;
958 #ifndef DEFAULT_A_OUT_NAME
959 output_file = "a.out";
961 output_file = DEFAULT_A_OUT_NAME;
964 obstack_begin (&temporary_obstack, 0);
965 obstack_begin (&permanent_obstack, 0);
966 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
967 current_demangling_style = gnu_demangling;
969 /* We must check that we do not call ourselves in an infinite
970 recursion loop. We append the name used for us to the COLLECT_NAMES
971 environment variable.
973 In practice, collect will rarely invoke itself. This can happen now
974 that we are no longer called gld. A perfect example is when running
975 gcc in a build directory that has been installed. When looking for
976 ld's, we'll find our installed version and believe that's the real ld. */
978 /* We must also append COLLECT_NAME to COLLECT_NAMES to watch for the
979 previous version of collect (the one that used COLLECT_NAME and only
980 handled two levels of recursion). If we don't we may mutually recurse
981 forever. This can happen (I think) when bootstrapping the old version
982 and a new one is installed (rare, but we should handle it).
983 ??? Hopefully references to COLLECT_NAME can be removed at some point. */
985 collect_name = (char *) getenv ("COLLECT_NAME");
986 collect_names = (char *) getenv ("COLLECT_NAMES");
988 p = (char *) xmalloc (strlen ("COLLECT_NAMES=")
989 + (collect_name ? strlen (collect_name) + 1 : 0)
990 + (collect_names ? strlen (collect_names) + 1 : 0)
991 + strlen (argv[0]) + 1);
992 strcpy (p, "COLLECT_NAMES=");
993 if (collect_name != 0)
994 sprintf (p + strlen (p), "%s%c", collect_name, PATH_SEPARATOR);
995 if (collect_names != 0)
996 sprintf (p + strlen (p), "%s%c", collect_names, PATH_SEPARATOR);
1000 prefix_from_env ("COLLECT_NAMES", &our_file_names);
1002 /* Set environment variable COLLECT_NAME to our name so the previous version
1003 of collect won't find us. If it does we'll mutually recurse forever.
1004 This can happen when bootstrapping the new version and an old version is
1006 ??? Hopefully this bit of code can be removed at some point. */
1008 p = xmalloc (strlen ("COLLECT_NAME=") + strlen (argv[0]) + 1);
1009 sprintf (p, "COLLECT_NAME=%s", argv[0]);
1012 p = (char *) getenv ("COLLECT_GCC_OPTIONS");
1015 char *q = extract_string (&p);
1016 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1019 obstack_free (&temporary_obstack, temporary_firstobj);
1022 c_ptr = c_argv = (char **) xcalloc (sizeof (char *), num_c_args);
1025 fatal ("no arguments");
1028 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1029 signal (SIGQUIT, handler);
1031 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1032 signal (SIGINT, handler);
1034 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1035 signal (SIGALRM, handler);
1038 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1039 signal (SIGHUP, handler);
1041 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1042 signal (SIGSEGV, handler);
1044 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1045 signal (SIGBUS, handler);
1048 /* Extract COMPILER_PATH and PATH into our prefix list. */
1049 prefix_from_env ("COMPILER_PATH", &cpath);
1050 prefix_from_env ("PATH", &path);
1052 #ifdef CROSS_COMPILE
1053 /* If we look for a program in the compiler directories, we just use
1054 the short name, since these directories are already system-specific.
1055 But it we look for a took in the system directories, we need to
1056 qualify the program name with the target machine. */
1059 = xcalloc (strlen (ld_suffix) + strlen (target_machine) + 2, 1);
1060 strcpy (full_ld_suffix, target_machine);
1061 strcat (full_ld_suffix, "-");
1062 strcat (full_ld_suffix, ld_suffix);
1065 = xcalloc (strlen (real_ld_suffix) + strlen (target_machine) + 2, 1);
1066 strcpy (full_real_ld_suffix, target_machine);
1067 strcat (full_real_ld_suffix, "-");
1068 strcat (full_real_ld_suffix, real_ld_suffix);
1072 = xcalloc (strlen (gld_suffix) + strlen (target_machine) + 2, 1);
1073 strcpy (full_gld_suffix, target_machine);
1074 strcat (full_gld_suffix, "-");
1075 strcat (full_gld_suffix, gld_suffix);
1079 = xcalloc (strlen (nm_suffix) + strlen (target_machine) + 2, 1);
1080 strcpy (full_nm_suffix, target_machine);
1081 strcat (full_nm_suffix, "-");
1082 strcat (full_nm_suffix, nm_suffix);
1085 = xcalloc (strlen (gnm_suffix) + strlen (target_machine) + 2, 1);
1086 strcpy (full_gnm_suffix, target_machine);
1087 strcat (full_gnm_suffix, "-");
1088 strcat (full_gnm_suffix, gnm_suffix);
1092 = xcalloc (strlen (ldd_suffix) + strlen (target_machine) + 2, 1);
1093 strcpy (full_ldd_suffix, target_machine);
1094 strcat (full_ldd_suffix, "-");
1095 strcat (full_ldd_suffix, ldd_suffix);
1099 = xcalloc (strlen (strip_suffix) + strlen (target_machine) + 2, 1);
1100 strcpy (full_strip_suffix, target_machine);
1101 strcat (full_strip_suffix, "-");
1102 strcat (full_strip_suffix, strip_suffix);
1105 = xcalloc (strlen (gstrip_suffix) + strlen (target_machine) + 2, 1);
1106 strcpy (full_gstrip_suffix, target_machine);
1107 strcat (full_gstrip_suffix, "-");
1108 strcat (full_gstrip_suffix, gstrip_suffix);
1109 #endif /* CROSS_COMPILE */
1111 /* Try to discover a valid linker/nm/strip to use. */
1113 /* Maybe we know the right file to use (if not cross). */
1114 #ifdef REAL_LD_FILE_NAME
1115 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1116 if (ld_file_name == 0)
1118 /* Search the (target-specific) compiler dirs for ld'. */
1119 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1120 /* Likewise for `collect-ld'. */
1121 if (ld_file_name == 0)
1122 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1123 /* Search the compiler directories for `ld'. We have protection against
1124 recursive calls in find_a_file. */
1125 if (ld_file_name == 0)
1126 ld_file_name = find_a_file (&cpath, ld_suffix);
1127 /* Search the ordinary system bin directories
1128 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1129 if (ld_file_name == 0)
1130 ld_file_name = find_a_file (&path, full_ld_suffix);
1132 /* If we've invoked ourselves, try again with LD_FILE_NAME. */
1134 if (collect_names != 0)
1136 if (ld_file_name != 0)
1138 argv[0] = ld_file_name;
1139 execvp (argv[0], argv);
1141 fatal ("cannot find `ld'");
1144 #ifdef REAL_NM_FILE_NAME
1145 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1146 if (nm_file_name == 0)
1148 nm_file_name = find_a_file (&cpath, gnm_suffix);
1149 if (nm_file_name == 0)
1150 nm_file_name = find_a_file (&path, full_gnm_suffix);
1151 if (nm_file_name == 0)
1152 nm_file_name = find_a_file (&cpath, nm_suffix);
1153 if (nm_file_name == 0)
1154 nm_file_name = find_a_file (&path, full_nm_suffix);
1157 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1158 if (ldd_file_name == 0)
1159 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1162 #ifdef REAL_STRIP_FILE_NAME
1163 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1164 if (strip_file_name == 0)
1166 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1167 if (strip_file_name == 0)
1168 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1169 if (strip_file_name == 0)
1170 strip_file_name = find_a_file (&cpath, strip_suffix);
1171 if (strip_file_name == 0)
1172 strip_file_name = find_a_file (&path, full_strip_suffix);
1174 /* Determine the full path name of the C compiler to use. */
1175 c_file_name = getenv ("COLLECT_GCC");
1176 if (c_file_name == 0)
1178 #ifdef CROSS_COMPILE
1179 c_file_name = xcalloc (sizeof ("gcc-") + strlen (target_machine) + 1, 1);
1180 strcpy (c_file_name, target_machine);
1181 strcat (c_file_name, "-gcc");
1183 c_file_name = "gcc";
1187 p = find_a_file (&cpath, c_file_name);
1189 /* Here it should be safe to use the system search path since we should have
1190 already qualified the name of the compiler when it is needed. */
1192 p = find_a_file (&path, c_file_name);
1197 *ld1++ = *ld2++ = ld_file_name;
1199 /* Make temp file names. */
1200 temp_filename = choose_temp_base ();
1201 temp_filename_length = strlen (temp_filename);
1202 c_file = xcalloc (temp_filename_length + sizeof (".c"), 1);
1203 o_file = xcalloc (temp_filename_length + sizeof (".o"), 1);
1204 export_file = xmalloc (temp_filename_length + sizeof (".x"));
1205 ldout = xmalloc (temp_filename_length + sizeof (".ld"));
1206 sprintf (ldout, "%s.ld", temp_filename);
1207 sprintf (c_file, "%s.c", temp_filename);
1208 sprintf (o_file, "%s.o", temp_filename);
1209 sprintf (export_file, "%s.x", temp_filename);
1210 *c_ptr++ = c_file_name;
1215 /* !!! When GCC calls collect2,
1216 it does not know whether it is calling collect2 or ld.
1217 So collect2 cannot meaningfully understand any options
1218 except those ld understands.
1219 If you propose to make GCC pass some other option,
1220 just imagine what will happen if ld is really ld!!! */
1222 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1223 /* After the first file, put in the c++ rt0. */
1226 while ((arg = *++argv) != (char *) 0)
1228 *ld1++ = *ld2++ = arg;
1235 if (!strcmp (arg, "-debug"))
1247 /* place o_file BEFORE this argument! */
1257 output_file = *ld1++ = *ld2++ = *++argv;
1259 output_file = &arg[2];
1268 if (arg[2] == '\0' && do_collecting)
1270 /* We must strip after the nm run, otherwise C++ linking
1271 won't work. Thus we strip in the second ld run, or
1272 else with strip if there is no second ld run. */
1284 else if ((p = rindex (arg, '.')) != (char *) 0
1285 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0))
1294 /* place o_file BEFORE this argument! */
1305 /* Get any options that the upper GCC wants to pass to the sub-GCC. */
1306 p = (char *) getenv ("COLLECT_GCC_OPTIONS");
1309 char *q = extract_string (&p);
1310 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1311 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1312 if (strncmp (q, "-shared", sizeof ("shared") - 1) == 0)
1315 obstack_free (&temporary_obstack, temporary_firstobj);
1316 *c_ptr++ = "-fno-exceptions";
1318 #ifdef COLLECT_EXPORT_LIST
1319 /* The AIX linker will discard static constructors in object files if
1320 nothing else in the file is referenced, so look at them first. */
1321 while (object_lst < object)
1322 scan_prog_file (*object_lst++, PASS_OBJ);
1325 char *buf = alloca (strlen (export_file) + 5);
1326 sprintf (buf, "-bE:%s", export_file);
1329 exportf = fopen (export_file, "w");
1330 if (exportf == (FILE *) 0)
1331 fatal_perror ("%s", export_file);
1332 write_export_file (exportf);
1333 if (fclose (exportf))
1334 fatal_perror ("closing %s", export_file);
1339 *object = *c_ptr = *ld1 = (char *) 0;
1343 fprintf (stderr, "collect2 version %s", version_string);
1344 #ifdef TARGET_VERSION
1347 fprintf (stderr, "\n");
1353 fprintf (stderr, "ld_file_name = %s\n",
1354 (ld_file_name ? ld_file_name : "not found"));
1355 fprintf (stderr, "c_file_name = %s\n",
1356 (c_file_name ? c_file_name : "not found"));
1357 fprintf (stderr, "nm_file_name = %s\n",
1358 (nm_file_name ? nm_file_name : "not found"));
1360 fprintf (stderr, "ldd_file_name = %s\n",
1361 (ldd_file_name ? ldd_file_name : "not found"));
1363 fprintf (stderr, "strip_file_name = %s\n",
1364 (strip_file_name ? strip_file_name : "not found"));
1365 fprintf (stderr, "c_file = %s\n",
1366 (c_file ? c_file : "not found"));
1367 fprintf (stderr, "o_file = %s\n",
1368 (o_file ? o_file : "not found"));
1370 ptr = getenv ("COLLECT_NAMES");
1372 fprintf (stderr, "COLLECT_NAMES = %s\n", ptr);
1374 ptr = getenv ("COLLECT_GCC_OPTIONS");
1376 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1378 ptr = getenv ("COLLECT_GCC");
1380 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1382 ptr = getenv ("COMPILER_PATH");
1384 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1386 ptr = getenv ("LIBRARY_PATH");
1388 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1390 fprintf (stderr, "\n");
1393 /* Load the program, searching all libraries and attempting to provide
1394 undefined symbols from repository information. */
1396 do_tlink (ld1_argv, object_lst);
1398 /* If -r or they'll be run via some other method, don't build the
1399 constructor or destructor list, just return now. */
1400 if (rflag || ! do_collecting)
1402 /* But make sure we delete the export file we may have created. */
1403 if (export_file != 0 && export_file[0])
1404 maybe_unlink (export_file);
1408 /* Examine the namelist with nm and search it for static constructors
1409 and destructors to call.
1410 Write the constructor and destructor tables to a .s file and reload. */
1412 scan_prog_file (output_file, PASS_FIRST);
1414 #ifdef SCAN_LIBRARIES
1415 scan_libraries (output_file);
1420 fprintf (stderr, "%d constructor(s) found\n", constructors.number);
1421 fprintf (stderr, "%d destructor(s) found\n", destructors.number);
1424 if (constructors.number == 0 && destructors.number == 0
1425 && frame_tables.number == 0
1426 #ifdef SCAN_LIBRARIES
1427 /* If we will be running these functions ourselves, we want to emit
1428 stubs into the shared library so that we don't have to relink
1429 dependent programs when we add static objects. */
1434 /* Strip now if it was requested on the command line. */
1437 char **strip_argv = (char **) xcalloc (sizeof (char *), 3);
1438 strip_argv[0] = strip_file_name;
1439 strip_argv[1] = output_file;
1440 strip_argv[2] = (char *) 0;
1441 fork_execute ("strip", strip_argv);
1444 #ifdef COLLECT_EXPORT_LIST
1445 maybe_unlink (export_file);
1450 maybe_unlink(output_file);
1451 outf = fopen (c_file, "w");
1452 if (outf == (FILE *) 0)
1453 fatal_perror ("%s", c_file);
1455 write_c_file (outf, c_file);
1458 fatal_perror ("closing %s", c_file);
1460 /* Tell the linker that we have initializer and finalizer functions. */
1461 #ifdef LD_INIT_SWITCH
1462 *ld2++ = LD_INIT_SWITCH;
1464 *ld2++ = LD_FINI_SWITCH;
1469 #ifdef COLLECT_EXPORT_LIST
1472 add_to_list (&exports, initname);
1473 add_to_list (&exports, fininame);
1474 add_to_list (&exports, "_GLOBAL__DI");
1475 add_to_list (&exports, "_GLOBAL__DD");
1476 exportf = fopen (export_file, "w");
1477 if (exportf == (FILE *) 0)
1478 fatal_perror ("%s", export_file);
1479 write_export_file (exportf);
1480 if (fclose (exportf))
1481 fatal_perror ("closing %s", export_file);
1487 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1488 output_file, c_file);
1489 write_c_file (stderr, "stderr");
1490 fprintf (stderr, "========== end of c_file\n\n");
1491 #ifdef COLLECT_EXPORT_LIST
1492 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1493 write_export_file (stderr);
1494 fprintf (stderr, "========== end of export_file\n\n");
1498 /* Assemble the constructor and destructor tables.
1499 Link the tables in with the rest of the program. */
1501 fork_execute ("gcc", c_argv);
1502 fork_execute ("ld", ld2_argv);
1504 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1505 constructors/destructors in shared libraries. */
1506 scan_prog_file (output_file, PASS_SECOND);
1508 maybe_unlink (c_file);
1509 maybe_unlink (o_file);
1510 maybe_unlink (export_file);
1515 /* Wait for a process to finish, and exit if a non-zero status is found. */
1526 if (WIFSIGNALED (status))
1528 int sig = WTERMSIG (status);
1529 #ifdef NO_SYS_SIGLIST
1530 error ("%s terminated with signal %d %s",
1533 (status & 0200) ? ", core dumped" : "");
1535 error ("%s terminated with signal %d [%s]%s",
1539 (status & 0200) ? ", core dumped" : "");
1542 collect_exit (FATAL_EXIT_CODE);
1545 if (WIFEXITED (status))
1546 return WEXITSTATUS (status);
1555 int ret = collect_wait (prog);
1558 error ("%s returned %d exit status", prog, ret);
1564 /* Fork and execute a program, and wait for the reply. */
1567 collect_execute (prog, argv, redir)
1580 fprintf (stderr, "%s", argv[0]);
1582 fprintf (stderr, "[cannot find %s]", prog);
1584 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1585 fprintf (stderr, " %s", str);
1587 fprintf (stderr, "\n");
1593 /* If we can't find a program we need, complain error. Do this here
1594 since we might not end up needing something that we couldn't find. */
1597 fatal ("cannot find `%s'", prog);
1603 fatal_perror ("fork");
1605 fatal_perror ("vfork");
1609 if (pid == 0) /* child context */
1614 if (freopen (redir, "a", stdout) == NULL)
1615 fatal_perror ("redirecting stdout: %s", redir);
1616 if (freopen (redir, "a", stderr) == NULL)
1617 fatal_perror ("redirecting stderr: %s", redir);
1620 execvp (argv[0], argv);
1621 fatal_perror ("executing %s", prog);
1626 fork_execute (prog, argv)
1630 collect_execute (prog, argv, NULL);
1634 /* Unlink a file unless we are debugging. */
1643 fprintf (stderr, "[Leaving %s]\n", file);
1647 /* Add a name to a linked list. */
1650 add_to_list (head_ptr, name)
1651 struct head *head_ptr;
1655 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1657 static long sequence_number = 0;
1658 strcpy (newid->name, name);
1660 if (head_ptr->first)
1661 head_ptr->last->next = newid;
1663 head_ptr->first = newid;
1665 /* Check for duplicate symbols. */
1666 for (p = head_ptr->first;
1667 strcmp (name, p->name) != 0;
1672 head_ptr->last->next = 0;
1677 newid->sequence = ++sequence_number;
1678 head_ptr->last = newid;
1682 /* Write: `prefix', the names on list LIST, `suffix'. */
1685 write_list (stream, prefix, list)
1692 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1698 write_list_with_asm (stream, prefix, list)
1705 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1706 prefix, list->sequence, list->name);
1711 /* Write out the constructor and destructor tables statically (for a shared
1712 object), along with the functions to execute them. */
1715 write_c_file_stat (stream, name)
1719 char *prefix, *p, *q;
1720 int frames = (frame_tables.number > 0);
1722 /* Figure out name of output_file, stripping off .so version. */
1723 p = rindex (output_file, '/');
1725 p = (char *) output_file;
1739 if (strncmp (q, ".so", 3) == 0)
1748 /* q points to null at end of the string (or . of the .so version) */
1749 prefix = xmalloc (q - p + 1);
1750 strncpy (prefix, p, q - p);
1752 for (q = prefix; *q; q++)
1756 fprintf (stderr, "\nwrite_c_file - output name is %s, prefix is %s\n",
1757 output_file, prefix);
1759 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1760 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1761 sprintf (initname, INIT_NAME_FORMAT, prefix);
1763 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1764 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1765 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1769 /* Write the tables as C code */
1771 fprintf (stream, "static int count;\n");
1772 fprintf (stream, "typedef void entry_pt();\n");
1773 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1777 write_list_with_asm (stream, "extern void *", frame_tables.first);
1779 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1780 write_list (stream, "\t\t&", frame_tables.first);
1781 fprintf (stream, "\t0\n};\n");
1783 /* This must match what's in frame.h. */
1784 fprintf (stream, "struct object {\n");
1785 fprintf (stream, " void *pc_begin;\n");
1786 fprintf (stream, " void *pc_end;\n");
1787 fprintf (stream, " void *fde_begin;\n");
1788 fprintf (stream, " void *fde_array;\n");
1789 fprintf (stream, " __SIZE_TYPE__ count;\n");
1790 fprintf (stream, " struct object *next;\n");
1791 fprintf (stream, "};\n");
1793 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1794 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1796 fprintf (stream, "static void reg_frame () {\n");
1797 fprintf (stream, "\tstatic struct object ob;\n");
1798 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1799 fprintf (stream, "\t}\n");
1801 fprintf (stream, "static void dereg_frame () {\n");
1802 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1803 fprintf (stream, "\t}\n");
1806 fprintf (stream, "void %s() {\n", initname);
1807 if (constructors.number > 0 || frames)
1809 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1810 write_list (stream, "\t\t", constructors.first);
1812 fprintf (stream, "\treg_frame,\n");
1813 fprintf (stream, "\t};\n");
1814 fprintf (stream, "\tentry_pt **p;\n");
1815 fprintf (stream, "\tif (count++ != 0) return;\n");
1816 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1817 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1820 fprintf (stream, "\t++count;\n");
1821 fprintf (stream, "}\n");
1822 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1823 fprintf (stream, "void %s() {\n", fininame);
1824 if (destructors.number > 0 || frames)
1826 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1827 write_list (stream, "\t\t", destructors.first);
1829 fprintf (stream, "\tdereg_frame,\n");
1830 fprintf (stream, "\t};\n");
1831 fprintf (stream, "\tentry_pt **p;\n");
1832 fprintf (stream, "\tif (--count != 0) return;\n");
1833 fprintf (stream, "\tp = dtors;\n");
1834 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1835 destructors.number + frames);
1837 fprintf (stream, "}\n");
1841 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
1842 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
1846 /* Write the constructor/destructor tables. */
1849 write_c_file_glob (stream, name)
1853 /* Write the tables as C code */
1855 int frames = (frame_tables.number > 0);
1857 fprintf (stream, "typedef void entry_pt();\n\n");
1859 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1863 write_list_with_asm (stream, "extern void *", frame_tables.first);
1865 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1866 write_list (stream, "\t\t&", frame_tables.first);
1867 fprintf (stream, "\t0\n};\n");
1869 /* This must match what's in frame.h. */
1870 fprintf (stream, "struct object {\n");
1871 fprintf (stream, " void *pc_begin;\n");
1872 fprintf (stream, " void *pc_end;\n");
1873 fprintf (stream, " void *fde_begin;\n");
1874 fprintf (stream, " void *fde_array;\n");
1875 fprintf (stream, " __SIZE_TYPE__ count;\n");
1876 fprintf (stream, " struct object *next;\n");
1877 fprintf (stream, "};\n");
1879 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1880 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1882 fprintf (stream, "static void reg_frame () {\n");
1883 fprintf (stream, "\tstatic struct object ob;\n");
1884 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1885 fprintf (stream, "\t}\n");
1887 fprintf (stream, "static void dereg_frame () {\n");
1888 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1889 fprintf (stream, "\t}\n");
1892 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
1893 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
1894 write_list (stream, "\t", constructors.first);
1896 fprintf (stream, "\treg_frame,\n");
1897 fprintf (stream, "\t0\n};\n\n");
1899 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1901 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
1902 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
1903 write_list (stream, "\t", destructors.first);
1905 fprintf (stream, "\tdereg_frame,\n");
1906 fprintf (stream, "\t0\n};\n\n");
1908 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
1909 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
1913 write_c_file (stream, name)
1917 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
1918 #ifndef LD_INIT_SWITCH
1920 write_c_file_glob (stream, name);
1923 write_c_file_stat (stream, name);
1924 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
1928 write_export_file (stream)
1931 struct id *list = exports.first;
1932 for (; list; list = list->next)
1933 fprintf (stream, "%s\n", list->name);
1936 #ifdef OBJECT_FORMAT_NONE
1938 /* Generic version to scan the name list of the loaded program for
1939 the symbols g++ uses for static constructors and destructors.
1941 The constructor table begins at __CTOR_LIST__ and contains a count
1942 of the number of pointers (or -1 if the constructors are built in a
1943 separate section by the linker), followed by the pointers to the
1944 constructor functions, terminated with a null pointer. The
1945 destructor table has the same format, and begins at __DTOR_LIST__. */
1948 scan_prog_file (prog_name, which_pass)
1950 enum pass which_pass;
1952 void (*int_handler) ();
1953 void (*quit_handler) ();
1961 if (which_pass == PASS_SECOND)
1964 /* If we don't have an `nm', complain. */
1965 if (nm_file_name == 0)
1966 fatal ("cannot find `nm'");
1968 nm_argv[argc++] = nm_file_name;
1969 if (NM_FLAGS[0] != '\0')
1970 nm_argv[argc++] = NM_FLAGS;
1972 nm_argv[argc++] = prog_name;
1973 nm_argv[argc++] = (char *) 0;
1975 if (pipe (pipe_fd) < 0)
1976 fatal_perror ("pipe");
1978 inf = fdopen (pipe_fd[0], "r");
1979 if (inf == (FILE *) 0)
1980 fatal_perror ("fdopen");
1982 /* Trace if needed. */
1988 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
1989 fprintf (stderr, " %s", str);
1991 fprintf (stderr, "\n");
1997 /* Spawn child nm on pipe */
2002 fatal_perror ("fork");
2004 fatal_perror ("vfork");
2008 if (pid == 0) /* child context */
2011 if (dup2 (pipe_fd[1], 1) < 0)
2012 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2014 if (close (pipe_fd[0]) < 0)
2015 fatal_perror ("close (%d)", pipe_fd[0]);
2017 if (close (pipe_fd[1]) < 0)
2018 fatal_perror ("close (%d)", pipe_fd[1]);
2020 execv (nm_file_name, nm_argv);
2021 fatal_perror ("executing %s", nm_file_name);
2024 /* Parent context from here on. */
2025 int_handler = (void (*) ())signal (SIGINT, SIG_IGN);
2027 quit_handler = (void (*) ())signal (SIGQUIT, SIG_IGN);
2030 if (close (pipe_fd[1]) < 0)
2031 fatal_perror ("close (%d)", pipe_fd[1]);
2034 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2036 /* Read each line of nm output. */
2037 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2042 /* If it contains a constructor or destructor name, add the name
2043 to the appropriate list. */
2045 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2046 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2053 /* Find the end of the symbol name.
2054 Don't include `|', because Encore nm can tack that on the end. */
2055 for (end = p; (ch2 = *end) != '\0' && !isspace (ch2) && ch2 != '|';
2061 switch (is_ctor_dtor (name))
2064 if (which_pass != PASS_LIB)
2065 add_to_list (&constructors, name);
2069 if (which_pass != PASS_LIB)
2070 add_to_list (&destructors, name);
2074 if (which_pass != PASS_LIB)
2075 fatal ("init function found in object %s", prog_name);
2076 #ifndef LD_INIT_SWITCH
2077 add_to_list (&constructors, name);
2082 if (which_pass != PASS_LIB)
2083 fatal ("fini function found in object %s", prog_name);
2084 #ifndef LD_FINI_SWITCH
2085 add_to_list (&destructors, name);
2090 if (which_pass != PASS_LIB)
2091 add_to_list (&frame_tables, name);
2093 default: /* not a constructor or destructor */
2098 fprintf (stderr, "\t%s\n", buf);
2102 fprintf (stderr, "\n");
2104 if (fclose (inf) != 0)
2105 fatal_perror ("fclose of pipe");
2107 do_wait (nm_file_name);
2109 signal (SIGINT, int_handler);
2111 signal (SIGQUIT, quit_handler);
2115 #if SUNOS4_SHARED_LIBRARIES
2117 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2118 that the output file depends upon and their initialization/finalization
2119 routines, if any. */
2124 #include <sys/mman.h>
2125 #include <sys/param.h>
2127 #include <sys/dir.h>
2129 /* pointers to the object file */
2130 unsigned object; /* address of memory mapped file */
2131 unsigned objsize; /* size of memory mapped to file */
2132 char * code; /* pointer to code segment */
2133 char * data; /* pointer to data segment */
2134 struct nlist *symtab; /* pointer to symbol table */
2135 struct link_dynamic *ld;
2136 struct link_dynamic_2 *ld_2;
2137 struct head libraries;
2139 /* Map the file indicated by NAME into memory and store its address. */
2147 if ((fp = open (name, O_RDONLY)) == -1)
2148 fatal ("unable to open file '%s'", name);
2149 if (fstat (fp, &s) == -1)
2150 fatal ("unable to stat file '%s'", name);
2152 objsize = s.st_size;
2153 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2156 fatal ("unable to mmap file '%s'", name);
2161 /* Helpers for locatelib. */
2163 static char *libname;
2169 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2172 /* If one file has an additional numeric extension past LIBNAME, then put
2173 that one first in the sort. If both files have additional numeric
2174 extensions, then put the one with the higher number first in the sort.
2176 We must verify that the extension is numeric, because Sun saves the
2177 original versions of patched libraries with a .FCS extension. Files with
2178 invalid extensions must go last in the sort, so that they won't be used. */
2182 struct direct **d1, **d2;
2184 int i1, i2 = strlen (libname);
2185 char *e1 = (*d1)->d_name + i2;
2186 char *e2 = (*d2)->d_name + i2;
2188 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2189 && e1[1] && isdigit (e1[1]) && e2[1] && isdigit (e2[1]))
2193 i1 = strtol (e1, &e1, 10);
2194 i2 = strtol (e2, &e2, 10);
2201 /* It has a valid numeric extension, prefer this one. */
2202 if (*e1 == '.' && e1[1] && isdigit (e1[1]))
2204 /* It has a invalid numeric extension, must prefer the other one. */
2210 /* It has a valid numeric extension, prefer this one. */
2211 if (*e2 == '.' && e2[1] && isdigit (e2[1]))
2213 /* It has a invalid numeric extension, must prefer the other one. */
2221 /* Given the name NAME of a dynamic dependency, find its pathname and add
2222 it to the list of libraries. */
2230 char buf[MAXPATHLEN];
2238 /* counting elements in array, need 1 extra for null */
2240 ld_rules = (char *) (ld_2->ld_rules + code);
2244 for (; *ld_rules != 0; ld_rules++)
2245 if (*ld_rules == ':')
2247 ld_rules = (char *) (ld_2->ld_rules + code);
2248 ldr = (char *) malloc (strlen (ld_rules) + 1);
2249 strcpy (ldr, ld_rules);
2251 p = getenv ("LD_LIBRARY_PATH");
2256 for (q = p ; *q != 0; q++)
2259 q = (char *) malloc (strlen (p) + 1);
2262 l = (char **) malloc ((cnt + 3) * sizeof (char *));
2267 for (; *ldr != 0; ldr++)
2277 for (; *q != 0; q++)
2284 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2287 *pp++ = "/usr/local/lib";
2291 for (pp = l; *pp != 0 ; pp++)
2293 struct direct **namelist;
2295 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2297 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2298 add_to_list (&libraries, buf);
2300 fprintf (stderr, "%s\n", buf);
2307 fprintf (stderr, "not found\n");
2309 fatal ("dynamic dependency %s not found", name);
2313 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2314 that it depends upon and any constructors or destructors they contain. */
2317 scan_libraries (prog_name)
2320 struct exec *header;
2322 struct link_object *lo;
2323 char buff[MAXPATHLEN];
2326 mapfile (prog_name);
2327 header = (struct exec *)object;
2328 if (N_BADMAG (*header))
2329 fatal ("bad magic number in file '%s'", prog_name);
2330 if (header->a_dynamic == 0)
2333 code = (char *) (N_TXTOFF (*header) + (long) header);
2334 data = (char *) (N_DATOFF (*header) + (long) header);
2335 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2337 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2340 ld = (struct link_dynamic *) (symtab->n_value + code);
2346 ld = (struct link_dynamic *) data;
2351 fprintf (stderr, "dynamic dependencies.\n");
2353 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2354 for (lo = (struct link_object *) ld_2->ld_need; lo;
2355 lo = (struct link_object *) lo->lo_next)
2358 lo = (struct link_object *) ((long) lo + code);
2359 name = (char *) (code + lo->lo_name);
2363 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2364 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2370 fprintf (stderr, "\t%s\n", name);
2371 add_to_list (&libraries, name);
2376 fprintf (stderr, "\n");
2378 /* now iterate through the library list adding their symbols to
2380 for (list = libraries.first; list; list = list->next)
2381 scan_prog_file (list->name, PASS_LIB);
2384 #else /* SUNOS4_SHARED_LIBRARIES */
2387 /* Use the List Dynamic Dependencies program to find shared libraries that
2388 the output file depends upon and their initialization/finalization
2389 routines, if any. */
2392 scan_libraries (prog_name)
2395 static struct head libraries; /* list of shared libraries found */
2397 void (*int_handler) ();
2398 void (*quit_handler) ();
2406 /* If we don't have an `ldd', complain. */
2407 if (ldd_file_name == 0)
2409 error ("cannot find `ldd'");
2413 ldd_argv[argc++] = ldd_file_name;
2414 ldd_argv[argc++] = prog_name;
2415 ldd_argv[argc++] = (char *) 0;
2417 if (pipe (pipe_fd) < 0)
2418 fatal_perror ("pipe");
2420 inf = fdopen (pipe_fd[0], "r");
2421 if (inf == (FILE *) 0)
2422 fatal_perror ("fdopen");
2424 /* Trace if needed. */
2430 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2431 fprintf (stderr, " %s", str);
2433 fprintf (stderr, "\n");
2439 /* Spawn child ldd on pipe */
2444 fatal_perror ("fork");
2446 fatal_perror ("vfork");
2450 if (pid == 0) /* child context */
2453 if (dup2 (pipe_fd[1], 1) < 0)
2454 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2456 if (close (pipe_fd[0]) < 0)
2457 fatal_perror ("close (%d)", pipe_fd[0]);
2459 if (close (pipe_fd[1]) < 0)
2460 fatal_perror ("close (%d)", pipe_fd[1]);
2462 execv (ldd_file_name, ldd_argv);
2463 fatal_perror ("executing %s", ldd_file_name);
2466 /* Parent context from here on. */
2467 int_handler = (void (*) ()) signal (SIGINT, SIG_IGN);
2469 quit_handler = (void (*) ()) signal (SIGQUIT, SIG_IGN);
2472 if (close (pipe_fd[1]) < 0)
2473 fatal_perror ("close (%d)", pipe_fd[1]);
2476 fprintf (stderr, "\nldd output with constructors/destructors.\n");
2478 /* Read each line of ldd output. */
2479 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2482 char *name, *end, *p = buf;
2484 /* Extract names of libraries and add to list. */
2485 PARSE_LDD_OUTPUT (p);
2490 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2491 fatal ("dynamic dependency %s not found", buf);
2493 /* Find the end of the symbol name. */
2495 (ch2 = *end) != '\0' && ch2 != '\n' && !isspace (ch2) && ch2 != '|';
2500 if (access (name, R_OK) == 0)
2501 add_to_list (&libraries, name);
2503 fatal ("unable to open dynamic dependency '%s'", buf);
2506 fprintf (stderr, "\t%s\n", buf);
2509 fprintf (stderr, "\n");
2511 if (fclose (inf) != 0)
2512 fatal_perror ("fclose of pipe");
2514 do_wait (ldd_file_name);
2516 signal (SIGINT, int_handler);
2518 signal (SIGQUIT, quit_handler);
2521 /* now iterate through the library list adding their symbols to
2523 for (list = libraries.first; list; list = list->next)
2524 scan_prog_file (list->name, PASS_LIB);
2527 #endif /* LDD_SUFFIX */
2528 #endif /* SUNOS4_SHARED_LIBRARIES */
2530 #endif /* OBJECT_FORMAT_NONE */
2534 * COFF specific stuff.
2537 #ifdef OBJECT_FORMAT_COFF
2539 #if defined(EXTENDED_COFF)
2540 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2541 # define GCC_SYMENT SYMR
2542 # define GCC_OK_SYMBOL(X) ((X).st == stProc && (X).sc == scText)
2543 # define GCC_SYMINC(X) (1)
2544 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2545 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2547 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2548 # define GCC_SYMENT SYMENT
2549 # define GCC_OK_SYMBOL(X) \
2550 (((X).n_sclass == C_EXT) && \
2551 (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) || \
2552 ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT)))
2553 # define GCC_SYMINC(X) ((X).n_numaux+1)
2554 # define GCC_SYMZERO(X) 0
2555 # define GCC_CHECK_HDR(X) (1)
2558 extern char *ldgetname ();
2560 /* COFF version to scan the name list of the loaded program for
2561 the symbols g++ uses for static constructors and destructors.
2563 The constructor table begins at __CTOR_LIST__ and contains a count
2564 of the number of pointers (or -1 if the constructors are built in a
2565 separate section by the linker), followed by the pointers to the
2566 constructor functions, terminated with a null pointer. The
2567 destructor table has the same format, and begins at __DTOR_LIST__. */
2570 scan_prog_file (prog_name, which_pass)
2572 enum pass which_pass;
2574 LDFILE *ldptr = NULL;
2575 int sym_index, sym_count;
2577 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2580 if ((ldptr = ldopen (prog_name, ldptr)) == NULL)
2581 fatal ("%s: can't open as COFF file", prog_name);
2583 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2584 fatal ("%s: not a COFF file", prog_name);
2586 if (GCC_CHECK_HDR (ldptr))
2588 sym_count = GCC_SYMBOLS (ldptr);
2589 sym_index = GCC_SYMZERO (ldptr);
2590 while (sym_index < sym_count)
2594 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2596 sym_index += GCC_SYMINC (symbol);
2598 if (GCC_OK_SYMBOL (symbol))
2602 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2603 continue; /* should never happen */
2605 #ifdef XCOFF_DEBUGGING_INFO
2606 /* All AIX function names have a duplicate entry beginning
2612 switch (is_ctor_dtor (name))
2615 add_to_list (&constructors, name);
2616 if (which_pass == PASS_OBJ)
2617 add_to_list (&exports, name);
2621 add_to_list (&destructors, name);
2622 if (which_pass == PASS_OBJ)
2623 add_to_list (&exports, name);
2626 default: /* not a constructor or destructor */
2630 #if !defined(EXTENDED_COFF)
2632 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2633 symbol.n_scnum, symbol.n_sclass,
2634 (symbol.n_type ? "0" : ""), symbol.n_type,
2638 fprintf (stderr, "\tiss = %5d, value = %5d, index = %5d, name = %s\n",
2639 symbol.iss, symbol.value, symbol.index, name);
2645 (void) ldclose(ldptr);
2648 #ifdef XCOFF_SCAN_LIBS
2649 /* Scan imported AIX libraries for GCC static ctors and dtors.
2650 FIXME: it is possible to link an executable without the actual import
2651 library by using an "import file" - a text file listing symbols
2652 exported by a library. To support this, we would have to scan
2653 import files as well as actual shared binaries to find GCC ctors.
2654 TODO: use memory mapping instead of 'ld' routines, files are already
2655 memory mapped, but we could eliminate the extra in-memory copies.
2656 Is it worth the effort? */
2659 scan_libraries (prog_name)
2664 static struct path_prefix libpath; /* we should only do this once */
2666 if ((ldptr = ldopen (prog_name, ldptr)) == NULL)
2667 fatal ("%s: can't open as COFF file", prog_name);
2669 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2670 fatal ("%s: not a COFF file", prog_name);
2672 /* find and read loader section */
2673 if (ldnshread (ldptr, _LOADER, &ldsh))
2679 FSEEK (ldptr, ldsh.s_scnptr, BEGINNING);
2680 FREAD (&ldh, sizeof (ldh), 1, ldptr);
2681 /* read import library list */
2682 impbuf = alloca (ldh.l_istlen);
2683 FSEEK (ldptr, ldh.l_impoff + ldsh.s_scnptr, BEGINNING);
2684 FREAD (impbuf, ldh.l_istlen, 1, ldptr);
2687 fprintf (stderr, "LIBPATH=%s\n", impbuf);
2688 prefix_from_string (impbuf, &libpath);
2690 /* skip LIBPATH and empty base and member fields */
2691 impbuf += strlen (impbuf) + 3;
2692 for (entry = 1; entry < ldh.l_nimpid; ++entry)
2694 char *impath = impbuf;
2695 char *implib = impath + strlen (impath) + 1;
2696 char *impmem = implib + strlen (implib) + 1;
2697 char *soname = NULL;
2700 LDFILE *libptr = NULL;
2701 struct prefix_list *pl;
2704 impbuf = impmem + strlen (impmem) + 1;
2706 fprintf (stderr, "PATH+BASE=%s%s\n", impath, implib);
2707 /* Skip AIX kernel exports */
2708 if (*impath == '/' && *(impath+1) == '\0'
2709 && strcmp (implib, "unix") == 0)
2711 pathlen = strlen (impath);
2712 trial = alloca (MAX (pathlen + 1, libpath.max_len)
2713 + strlen (implib) + 1);
2716 strcpy (trial, impath);
2717 if (impath[pathlen - 1] != '/')
2718 trial[pathlen++] = '/';
2719 strcpy (trial + pathlen, implib);
2720 if (access (trial, R_OK) == 0)
2724 for (pl = libpath.plist; pl; pl = pl->next)
2726 strcpy (trial, pl->prefix);
2727 strcat (trial, implib);
2728 if (access (trial, R_OK) == 0)
2736 fatal ("%s: library not found", implib);
2739 fprintf (stderr, "%s (%s)\n", soname, impmem);
2741 fprintf (stderr, "%s\n", soname);
2745 /* scan imported shared objects for GCC GLOBAL ctors */
2747 if ((libptr = ldopen (soname, libptr)) == NULL)
2748 fatal ("%s: can't open import library", soname);
2749 if (TYPE (libptr) == ARTYPE)
2753 fatal ("%s: no archive member specified", soname);
2754 ldahread (libptr, &ah);
2755 if (strcmp (ah.ar_name, impmem))
2758 type = HEADER (libptr).f_magic;
2759 if (HEADER (libptr).f_flags & F_SHROBJ)
2766 if (!ldnshread (libptr, _LOADER, &soldsh))
2767 fatal ("%s: not an import library", soname);
2768 FSEEK (libptr, soldsh.s_scnptr, BEGINNING);
2769 if (FREAD (&soldh, sizeof (soldh), 1, libptr) != 1)
2770 fatal ("%s: can't read loader section", soname);
2771 /*fprintf (stderr, "\tscanning %s\n", soname);*/
2772 symcnt = soldh.l_nsyms;
2773 lsyms = (LDSYM *) alloca (symcnt * sizeof (*lsyms));
2774 symcnt = FREAD (lsyms, sizeof (*lsyms), symcnt, libptr);
2775 ldstrings = alloca (soldh.l_stlen);
2776 FSEEK (libptr, soldsh.s_scnptr+soldh.l_stoff, BEGINNING);
2777 FREAD (ldstrings, soldh.l_stlen, 1, libptr);
2778 for (i = 0; i < symcnt; ++i)
2780 LDSYM *l = lsyms + i;
2781 if (LDR_EXPORT (*l))
2785 expname = l->l_name;
2786 else if (l->l_offset < soldh.l_stlen)
2787 expname = ldstrings + l->l_offset;
2788 switch (is_ctor_dtor (expname))
2792 fprintf (stderr, "\t%s\n", expname);
2793 add_to_list (&constructors, expname);
2797 add_to_list (&destructors, expname);
2800 default: /* not a constructor or destructor */
2807 fprintf (stderr, "%s: type = %04X flags = %04X\n",
2808 ah.ar_name, type, HEADER (libptr).f_flags);
2810 while (ldclose (libptr) == FAILURE);
2811 /* printf (stderr, "closed %s\n", soname); */
2815 #endif /* XCOFF_SCAN_LIBS */
2817 #endif /* OBJECT_FORMAT_COFF */
2821 * OSF/rose specific stuff.
2824 #ifdef OBJECT_FORMAT_ROSE
2826 /* Union of the various load commands */
2828 typedef union load_union
2830 ldc_header_t hdr; /* common header */
2831 load_cmd_map_command_t map; /* map indexing other load cmds */
2832 interpreter_command_t iprtr; /* interpreter pathname */
2833 strings_command_t str; /* load commands strings section */
2834 region_command_t region; /* region load command */
2835 reloc_command_t reloc; /* relocation section */
2836 package_command_t pkg; /* package load command */
2837 symbols_command_t sym; /* symbol sections */
2838 entry_command_t ent; /* program start section */
2839 gen_info_command_t info; /* object information */
2840 func_table_command_t func; /* function constructors/destructors */
2843 /* Structure to point to load command and data section in memory. */
2845 typedef struct load_all
2847 load_union_t *load; /* load command */
2848 char *section; /* pointer to section */
2851 /* Structure to contain information about a file mapped into memory. */
2855 char *start; /* start of map */
2856 char *name; /* filename */
2857 long size; /* size of the file */
2858 long rounded_size; /* size rounded to page boundary */
2859 int fd; /* file descriptor */
2860 int rw; /* != 0 if opened read/write */
2861 int use_mmap; /* != 0 if mmap'ed */
2864 extern int decode_mach_o_hdr ();
2865 extern int encode_mach_o_hdr ();
2867 static void add_func_table PROTO((mo_header_t *, load_all_t *,
2868 symbol_info_t *, int));
2869 static void print_header PROTO((mo_header_t *));
2870 static void print_load_command PROTO((load_union_t *, size_t, int));
2871 static void bad_header PROTO((int));
2872 static struct file_info *read_file PROTO((char *, int, int));
2873 static void end_file PROTO((struct file_info *));
2875 /* OSF/rose specific version to scan the name list of the loaded
2876 program for the symbols g++ uses for static constructors and
2879 The constructor table begins at __CTOR_LIST__ and contains a count
2880 of the number of pointers (or -1 if the constructors are built in a
2881 separate section by the linker), followed by the pointers to the
2882 constructor functions, terminated with a null pointer. The
2883 destructor table has the same format, and begins at __DTOR_LIST__. */
2886 scan_prog_file (prog_name, which_pass)
2888 enum pass which_pass;
2892 load_all_t *load_array;
2893 load_all_t *load_end;
2894 load_all_t *load_cmd;
2895 int symbol_load_cmds;
2901 struct file_info *obj_file;
2903 mo_lcid_t cmd_strings = -1;
2904 symbol_info_t *main_sym = 0;
2905 int rw = (which_pass != PASS_FIRST);
2907 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
2909 fatal_perror ("can't read %s", prog_name);
2911 obj_file = read_file (prog_name, prog_fd, rw);
2912 obj = obj_file->start;
2914 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
2915 if (status != MO_HDR_CONV_SUCCESS)
2916 bad_header (status);
2919 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
2920 since the hardware will automatically swap bytes for us on loading little endian
2923 #ifndef CROSS_COMPILE
2924 if (hdr.moh_magic != MOH_MAGIC_MSB
2925 || hdr.moh_header_version != MOH_HEADER_VERSION
2926 || hdr.moh_byte_order != OUR_BYTE_ORDER
2927 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
2928 || hdr.moh_cpu_type != OUR_CPU_TYPE
2929 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
2930 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
2932 fatal ("incompatibilities between object file & expected values");
2937 print_header (&hdr);
2939 offset = hdr.moh_first_cmd_off;
2940 load_end = load_array
2941 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
2943 /* Build array of load commands, calculating the offsets */
2944 for (i = 0; i < hdr.moh_n_load_cmds; i++)
2946 load_union_t *load_hdr; /* load command header */
2948 load_cmd = load_end++;
2949 load_hdr = (load_union_t *) (obj + offset);
2951 /* If modifying the program file, copy the header. */
2954 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
2955 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
2958 /* null out old command map, because we will rewrite at the end. */
2959 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
2961 cmd_strings = ptr->map.lcm_ld_cmd_strings;
2962 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
2966 load_cmd->load = load_hdr;
2967 if (load_hdr->hdr.ldci_section_off > 0)
2968 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
2971 print_load_command (load_hdr, offset, i);
2973 offset += load_hdr->hdr.ldci_cmd_size;
2976 /* If the last command is the load command map and is not undefined,
2977 decrement the count of load commands. */
2978 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
2981 hdr.moh_n_load_cmds--;
2984 /* Go through and process each symbol table section. */
2985 symbol_load_cmds = 0;
2986 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
2988 load_union_t *load_hdr = load_cmd->load;
2990 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
2996 char *kind = "unknown";
2998 switch (load_hdr->sym.symc_kind)
3000 case SYMC_IMPORTS: kind = "imports"; break;
3001 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3002 case SYMC_STABS: kind = "stabs"; break;
3005 fprintf (stderr, "\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3006 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3009 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3012 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3013 if (str_sect == (char *) 0)
3014 fatal ("string section missing");
3016 if (load_cmd->section == (char *) 0)
3017 fatal ("section pointer missing");
3019 num_syms = load_hdr->sym.symc_nentries;
3020 for (i = 0; i < num_syms; i++)
3022 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3023 char *name = sym->si_name.symbol_name + str_sect;
3030 char *n = name + strlen (name) - strlen (NAME__MAIN);
3032 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3042 switch (is_ctor_dtor (name))
3045 add_to_list (&constructors, name);
3049 add_to_list (&destructors, name);
3052 default: /* not a constructor or destructor */
3058 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3059 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3064 if (symbol_load_cmds == 0)
3065 fatal ("no symbol table found");
3067 /* Update the program file now, rewrite header and load commands. At present,
3068 we assume that there is enough space after the last load command to insert
3069 one more. Since the first section written out is page aligned, and the
3070 number of load commands is small, this is ok for the present. */
3074 load_union_t *load_map;
3077 if (cmd_strings == -1)
3078 fatal ("no cmd_strings found");
3080 /* Add __main to initializer list.
3081 If we are building a program instead of a shared library, don't
3082 do anything, since in the current version, you cannot do mallocs
3083 and such in the constructors. */
3085 if (main_sym != (symbol_info_t *) 0
3086 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3087 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3090 fprintf (stderr, "\nUpdating header and load commands.\n\n");
3092 hdr.moh_n_load_cmds++;
3093 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3095 /* Create new load command map. */
3097 fprintf (stderr, "load command map, %d cmds, new size %ld.\n",
3098 (int)hdr.moh_n_load_cmds, (long)size);
3100 load_map = (load_union_t *) xcalloc (1, size);
3101 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3102 load_map->map.ldc_header.ldci_cmd_size = size;
3103 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3104 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3105 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3107 offset = hdr.moh_first_cmd_off;
3108 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3110 load_map->map.lcm_map[i] = offset;
3111 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3112 hdr.moh_load_map_cmd_off = offset;
3114 offset += load_array[i].load->hdr.ldci_cmd_size;
3117 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3120 print_header (&hdr);
3123 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3124 if (status != MO_HDR_CONV_SUCCESS)
3125 bad_header (status);
3128 fprintf (stderr, "writing load commands.\n\n");
3130 /* Write load commands */
3131 offset = hdr.moh_first_cmd_off;
3132 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3134 load_union_t *load_hdr = load_array[i].load;
3135 size_t size = load_hdr->hdr.ldci_cmd_size;
3138 print_load_command (load_hdr, offset, i);
3140 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3145 end_file (obj_file);
3147 if (close (prog_fd))
3148 fatal_perror ("closing %s", prog_name);
3151 fprintf (stderr, "\n");
3155 /* Add a function table to the load commands to call a function
3156 on initiation or termination of the process. */
3159 add_func_table (hdr_p, load_array, sym, type)
3160 mo_header_t *hdr_p; /* pointer to global header */
3161 load_all_t *load_array; /* array of ptrs to load cmds */
3162 symbol_info_t *sym; /* pointer to symbol entry */
3163 int type; /* fntc_type value */
3165 /* Add a new load command. */
3166 int num_cmds = ++hdr_p->moh_n_load_cmds;
3167 int load_index = num_cmds - 1;
3168 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3169 load_union_t *ptr = xcalloc (1, size);
3170 load_all_t *load_cmd;
3173 /* Set the unresolved address bit in the header to force the loader to be
3174 used, since kernel exec does not call the initialization functions. */
3175 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3177 load_cmd = &load_array[load_index];
3178 load_cmd->load = ptr;
3179 load_cmd->section = (char *) 0;
3181 /* Fill in func table load command. */
3182 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3183 ptr->func.ldc_header.ldci_cmd_size = size;
3184 ptr->func.ldc_header.ldci_section_off = 0;
3185 ptr->func.ldc_header.ldci_section_len = 0;
3186 ptr->func.fntc_type = type;
3187 ptr->func.fntc_nentries = 1;
3189 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3190 /* Is the symbol already expressed as (region, offset)? */
3191 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3193 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3194 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3197 /* If not, figure out which region it's in. */
3200 mo_vm_addr_t addr = sym->si_value.abs_val;
3203 for (i = 0; i < load_index; i++)
3205 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3207 region_command_t *region_ptr = &load_array[i].load->region;
3209 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3210 && addr >= region_ptr->regc_addr.vm_addr
3211 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3213 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3214 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3222 fatal ("could not convert 0x%l.8x into a region", addr);
3227 "%s function, region %d, offset = %ld (0x%.8lx)\n",
3228 (type == FNTC_INITIALIZATION) ? "init" : "term",
3229 (int)ptr->func.fntc_entry_loc[i].adr_lcid,
3230 (long)ptr->func.fntc_entry_loc[i].adr_sctoff,
3231 (long)ptr->func.fntc_entry_loc[i].adr_sctoff);
3236 /* Print the global header for an OSF/rose object. */
3239 print_header (hdr_ptr)
3240 mo_header_t *hdr_ptr;
3242 fprintf (stderr, "\nglobal header:\n");
3243 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3244 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3245 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3246 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3247 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3248 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3249 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3250 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3251 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3252 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3253 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3254 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3255 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3256 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3257 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3259 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3260 fprintf (stderr, ", relocatable");
3262 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3263 fprintf (stderr, ", linkable");
3265 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3266 fprintf (stderr, ", execable");
3268 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3269 fprintf (stderr, ", executable");
3271 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3272 fprintf (stderr, ", unresolved");
3274 fprintf (stderr, "\n\n");
3279 /* Print a short summary of a load command. */
3282 print_load_command (load_hdr, offset, number)
3283 load_union_t *load_hdr;
3287 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3288 char *type_str = (char *) 0;
3292 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3293 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3294 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3295 case LDC_STRINGS: type_str = "STRINGS"; break;
3296 case LDC_REGION: type_str = "REGION"; break;
3297 case LDC_RELOC: type_str = "RELOC"; break;
3298 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3299 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3300 case LDC_ENTRY: type_str = "ENTRY"; break;
3301 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3302 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3306 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3308 (long) load_hdr->hdr.ldci_cmd_size,
3310 (long) load_hdr->hdr.ldci_section_off,
3311 (long) load_hdr->hdr.ldci_section_len);
3313 if (type_str == (char *) 0)
3314 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3316 else if (type != LDC_REGION)
3317 fprintf (stderr, ", ty: %s\n", type_str);
3322 switch (load_hdr->region.regc_usage_type)
3324 case REG_TEXT_T: region = ", .text"; break;
3325 case REG_DATA_T: region = ", .data"; break;
3326 case REG_BSS_T: region = ", .bss"; break;
3327 case REG_GLUE_T: region = ", .glue"; break;
3328 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3329 case REG_RDATA_T: region = ", .rdata"; break;
3330 case REG_SDATA_T: region = ", .sdata"; break;
3331 case REG_SBSS_T: region = ", .sbss"; break;
3335 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3337 (long) load_hdr->region.regc_vm_addr,
3338 (long) load_hdr->region.regc_vm_size,
3346 /* Fatal error when {en,de}code_mach_o_header fails. */
3352 char *msg = (char *) 0;
3356 case MO_ERROR_BAD_MAGIC: msg = "bad magic number"; break;
3357 case MO_ERROR_BAD_HDR_VERS: msg = "bad header version"; break;
3358 case MO_ERROR_BAD_RAW_HDR_VERS: msg = "bad raw header version"; break;
3359 case MO_ERROR_BUF2SML: msg = "raw header buffer too small"; break;
3360 case MO_ERROR_OLD_RAW_HDR_FILE: msg = "old raw header file"; break;
3361 case MO_ERROR_UNSUPPORTED_VERS: msg = "unsupported version"; break;
3364 if (msg == (char *) 0)
3365 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3371 /* Read a file into a memory buffer. */
3373 static struct file_info *
3374 read_file (name, fd, rw)
3375 char *name; /* filename */
3376 int fd; /* file descriptor */
3377 int rw; /* read/write */
3379 struct stat stat_pkt;
3380 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3382 static int page_size;
3385 if (fstat (fd, &stat_pkt) < 0)
3386 fatal_perror ("fstat %s", name);
3389 p->size = stat_pkt.st_size;
3390 p->rounded_size = stat_pkt.st_size;
3396 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3399 page_size = sysconf (_SC_PAGE_SIZE);
3401 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3402 p->start = mmap ((caddr_t) 0,
3403 (rw) ? p->rounded_size : p->size,
3404 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3405 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3409 if (p->start != (char *) 0 && p->start != (char *) -1)
3413 #endif /* USE_MMAP */
3418 fprintf (stderr, "read %s\n", name);
3421 p->start = xmalloc (p->size);
3422 if (lseek (fd, 0L, SEEK_SET) < 0)
3423 fatal_perror ("lseek to 0 on %s", name);
3425 len = read (fd, p->start, p->size);
3427 fatal_perror ("read %s", name);
3430 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3436 /* Do anything necessary to write a file back from memory. */
3440 struct file_info *ptr; /* file information block */
3448 fprintf (stderr, "msync %s\n", ptr->name);
3450 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3451 fatal_perror ("msync %s", ptr->name);
3455 fprintf (stderr, "munmap %s\n", ptr->name);
3457 if (munmap (ptr->start, ptr->size))
3458 fatal_perror ("munmap %s", ptr->name);
3461 #endif /* USE_MMAP */
3468 fprintf (stderr, "write %s\n", ptr->name);
3470 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3471 fatal_perror ("lseek to 0 on %s", ptr->name);
3473 len = write (ptr->fd, ptr->start, ptr->size);
3475 fatal_perror ("write %s", ptr->name);
3477 if (len != ptr->size)
3478 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3487 #endif /* OBJECT_FORMAT_ROSE */