1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4 1999, 2000, 2001 Free Software Foundation, Inc.
5 Contributed by Chris Smith (csmith@convex.com).
6 Heavily modified by Michael Meissner (meissner@cygnus.com),
7 Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
9 This file is part of GCC.
11 GCC is free software; you can redistribute it and/or modify it under
12 the terms of the GNU General Public License as published by the Free
13 Software Foundation; either version 2, or (at your option) any later
16 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17 WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING. If not, write to the Free
23 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
27 /* Build tables of static constructors and destructors and run ld. */
32 #if ! defined( SIGCHLD ) && defined( SIGCLD )
33 # define SIGCHLD SIGCLD
36 #ifdef vfork /* Autoconf may define this to fork for us. */
37 # define VFORK_STRING "fork"
39 # define VFORK_STRING "vfork"
45 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
46 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
49 #ifndef LIBRARY_PATH_ENV
50 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
61 /* Obstack allocation and deallocation routines. */
62 #define obstack_chunk_alloc xmalloc
63 #define obstack_chunk_free free
65 /* On certain systems, we have code that works by scanning the object file
66 directly. But this code uses system-specific header files and library
67 functions, so turn it off in a cross-compiler. Likewise, the names of
68 the utilities are not correct for a cross-compiler; we have to hope that
69 cross-versions are in the proper directories. */
72 #undef SUNOS4_SHARED_LIBRARIES
73 #undef OBJECT_FORMAT_COFF
74 #undef OBJECT_FORMAT_ROSE
76 #undef REAL_LD_FILE_NAME
77 #undef REAL_NM_FILE_NAME
78 #undef REAL_STRIP_FILE_NAME
81 /* If we cannot use a special method, use the ordinary one:
82 run nm to find what symbols are present.
83 In a cross-compiler, this means you need a cross nm,
84 but that is not quite as unpleasant as special headers. */
86 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
87 #define OBJECT_FORMAT_NONE
90 #ifdef OBJECT_FORMAT_COFF
99 /* Many versions of ldfcn.h define these. */
107 /* Some systems have an ISCOFF macro, but others do not. In some cases
108 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
109 that either do not have an ISCOFF macro in /usr/include or for those
110 where it is wrong. */
113 #define MY_ISCOFF(X) ISCOFF (X)
116 #endif /* OBJECT_FORMAT_COFF */
118 #ifdef OBJECT_FORMAT_ROSE
125 #include <sys/mman.h>
129 #include <mach_o_format.h>
130 #include <mach_o_header.h>
131 #include <mach_o_vals.h>
132 #include <mach_o_types.h>
134 #endif /* OBJECT_FORMAT_ROSE */
136 #ifdef OBJECT_FORMAT_NONE
138 /* Default flags to pass to nm. */
140 #define NM_FLAGS "-n"
143 #endif /* OBJECT_FORMAT_NONE */
145 /* Some systems use __main in a way incompatible with its use in gcc, in these
146 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
147 give the same symbol without quotes for an alternative entry point. You
148 must define both, or neither. */
150 #define NAME__MAIN "__main"
151 #define SYMBOL__MAIN __main
154 /* This must match tree.h. */
155 #define DEFAULT_INIT_PRIORITY 65535
157 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
158 #define SCAN_LIBRARIES
162 int do_collecting = 1;
164 int do_collecting = 0;
167 /* Nonzero if we should suppress the automatic demangling of identifiers
168 in linker error messages. Set from COLLECT_NO_DEMANGLE. */
171 /* Linked lists of constructor and destructor names. */
187 /* Enumeration giving which pass this is for scanning the program file. */
190 PASS_FIRST, /* without constructors */
191 PASS_OBJ, /* individual objects */
192 PASS_LIB, /* looking for shared libraries */
193 PASS_SECOND /* with constructors linked in */
196 int vflag; /* true if -v */
197 static int rflag; /* true if -r */
198 static int strip_flag; /* true if -s */
199 #ifdef COLLECT_EXPORT_LIST
200 static int export_flag; /* true if -bE */
201 static int aix64_flag; /* true if -b64 */
204 int debug; /* true if -debug */
206 static int shared_obj; /* true if -shared */
208 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
209 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
210 #ifdef COLLECT_EXPORT_LIST
211 static const char *export_file; /* <xxx>.x for AIX export list. */
213 const char *ldout; /* File for ld errors. */
214 static const char *output_file; /* Output file for ld. */
215 static const char *nm_file_name; /* pathname of nm */
217 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
219 static const char *strip_file_name; /* pathname of strip */
220 const char *c_file_name; /* pathname of gcc */
221 static char *initname, *fininame; /* names of init and fini funcs */
223 static struct head constructors; /* list of constructors found */
224 static struct head destructors; /* list of destructors found */
225 #ifdef COLLECT_EXPORT_LIST
226 static struct head exports; /* list of exported symbols */
228 static struct head frame_tables; /* list of frame unwind info tables */
230 struct obstack temporary_obstack;
231 struct obstack permanent_obstack;
232 char * temporary_firstobj;
234 /* Holds the return value of pexecute. */
237 /* Defined in the automatically-generated underscore.c. */
238 extern int prepends_underscore;
240 #ifndef GET_ENV_PATH_LIST
241 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
244 /* Structure to hold all the directories in which to search for files to
249 const char *prefix; /* String to prepend to the path. */
250 struct prefix_list *next; /* Next in linked list. */
255 struct prefix_list *plist; /* List of prefixes to try */
256 int max_len; /* Max length of a prefix in PLIST */
257 const char *name; /* Name of this list (used in config stuff) */
260 #ifdef COLLECT_EXPORT_LIST
261 /* Lists to keep libraries to be scanned for global constructors/destructors. */
262 static struct head libs; /* list of libraries */
263 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
264 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
265 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
266 &libpath_lib_dirs, NULL};
267 static const char *const libexts[3] = {"a", "so", NULL}; /* possible library extensions */
270 static void handler PARAMS ((int));
271 static int is_ctor_dtor PARAMS ((const char *));
272 static char *find_a_file PARAMS ((struct path_prefix *, const char *));
273 static void add_prefix PARAMS ((struct path_prefix *, const char *));
274 static void prefix_from_env PARAMS ((const char *, struct path_prefix *));
275 static void prefix_from_string PARAMS ((const char *, struct path_prefix *));
276 static void do_wait PARAMS ((const char *));
277 static void fork_execute PARAMS ((const char *, char **));
278 static void maybe_unlink PARAMS ((const char *));
279 static void add_to_list PARAMS ((struct head *, const char *));
280 static int extract_init_priority PARAMS ((const char *));
281 static void sort_ids PARAMS ((struct head *));
282 static void write_list PARAMS ((FILE *, const char *, struct id *));
283 #ifdef COLLECT_EXPORT_LIST
284 static void dump_list PARAMS ((FILE *, const char *, struct id *));
287 static void dump_prefix_list PARAMS ((FILE *, const char *, struct prefix_list *));
289 static void write_list_with_asm PARAMS ((FILE *, const char *, struct id *));
290 static void write_c_file PARAMS ((FILE *, const char *));
291 static void write_c_file_stat PARAMS ((FILE *, const char *));
292 #ifndef LD_INIT_SWITCH
293 static void write_c_file_glob PARAMS ((FILE *, const char *));
295 static void scan_prog_file PARAMS ((const char *, enum pass));
296 #ifdef SCAN_LIBRARIES
297 static void scan_libraries PARAMS ((const char *));
299 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
300 static int is_in_args PARAMS ((const char *, const char **, const char **));
302 #ifdef COLLECT_EXPORT_LIST
304 static int is_in_list PARAMS ((const char *, struct id *));
306 static void write_aix_file PARAMS ((FILE *, struct id *));
307 static char *resolve_lib_name PARAMS ((const char *));
308 static int ignore_library PARAMS ((const char *));
310 static char *extract_string PARAMS ((const char **));
313 static int dup2 PARAMS ((int, int));
326 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
329 close (fdtmp[--fdx]);
333 #endif /* ! HAVE_DUP2 */
335 /* Delete tempfiles and exit function. */
338 collect_exit (status)
341 if (c_file != 0 && c_file[0])
342 maybe_unlink (c_file);
344 if (o_file != 0 && o_file[0])
345 maybe_unlink (o_file);
347 #ifdef COLLECT_EXPORT_LIST
348 if (export_file != 0 && export_file[0])
349 maybe_unlink (export_file);
352 if (ldout != 0 && ldout[0])
355 maybe_unlink (ldout);
358 if (status != 0 && output_file != 0 && output_file[0])
359 maybe_unlink (output_file);
365 /* Notify user of a non-error. */
367 notice VPARAMS ((const char *msgid, ...))
370 VA_FIXEDARG (ap, const char *, msgid);
372 vfprintf (stderr, _(msgid), ap);
376 /* Die when sys call fails. */
379 fatal_perror VPARAMS ((const char * msgid, ...))
384 VA_FIXEDARG (ap, const char *, msgid);
386 fprintf (stderr, "collect2: ");
387 vfprintf (stderr, _(msgid), ap);
388 fprintf (stderr, ": %s\n", xstrerror (e));
391 collect_exit (FATAL_EXIT_CODE);
397 fatal VPARAMS ((const char * msgid, ...))
400 VA_FIXEDARG (ap, const char *, msgid);
402 fprintf (stderr, "collect2: ");
403 vfprintf (stderr, _(msgid), ap);
404 fprintf (stderr, "\n");
407 collect_exit (FATAL_EXIT_CODE);
410 /* Write error message. */
413 error VPARAMS ((const char * msgid, ...))
416 VA_FIXEDARG (ap, const char *, msgid);
418 fprintf (stderr, "collect2: ");
419 vfprintf (stderr, _(msgid), ap);
420 fprintf (stderr, "\n");
424 /* In case obstack is linked in, and abort is defined to fancy_abort,
425 provide a default entry. */
430 fatal ("internal error");
437 if (c_file != 0 && c_file[0])
438 maybe_unlink (c_file);
440 if (o_file != 0 && o_file[0])
441 maybe_unlink (o_file);
443 if (ldout != 0 && ldout[0])
444 maybe_unlink (ldout);
446 #ifdef COLLECT_EXPORT_LIST
447 if (export_file != 0 && export_file[0])
448 maybe_unlink (export_file);
451 signal (signo, SIG_DFL);
452 kill (getpid (), signo);
460 return access (name, R_OK) == 0;
463 /* Parse a reasonable subset of shell quoting syntax. */
480 obstack_1grow (&temporary_obstack, c);
481 else if (! inside && c == ' ')
483 else if (! inside && c == '\\')
488 obstack_1grow (&temporary_obstack, c);
491 obstack_1grow (&temporary_obstack, '\0');
493 return obstack_finish (&temporary_obstack);
500 FILE *stream = fopen (name, "r");
507 while (c = getc (stream),
508 c != EOF && (ISIDNUM (c) || c == '$' || c == '.'))
509 obstack_1grow (&temporary_obstack, c);
510 if (obstack_object_size (&temporary_obstack) > 0)
512 const char *word, *p;
514 obstack_1grow (&temporary_obstack, '\0');
515 word = obstack_finish (&temporary_obstack);
518 ++word, putc ('.', stderr);
520 if (*p == '_' && prepends_underscore)
526 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
531 fputs (result, stderr);
533 diff = strlen (word) - strlen (result);
534 while (diff > 0 && c == ' ')
535 --diff, putc (' ', stderr);
536 while (diff < 0 && c == ' ')
537 ++diff, c = getc (stream);
542 fputs (word, stderr);
545 obstack_free (&temporary_obstack, temporary_firstobj);
554 /* Decide whether the given symbol is: a constructor (1), a destructor
555 (2), a routine in a shared object that calls all the constructors
556 (3) or destructors (4), a DWARF exception-handling table (5), or
557 nothing special (0). */
563 struct names { const char *const name; const int len; const int ret;
564 const int two_underscores; };
568 const char *orig_s = s;
570 static struct names special[] = {
571 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
572 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
573 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
574 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
575 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
576 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
577 cfront has its own linker procedure to collect them;
578 if collect2 gets them too, they get collected twice
579 when the cfront procedure is run and the compiler used
580 for linking happens to be GCC. */
581 { "sti__", sizeof ("sti__")-1, 1, 1 },
582 { "std__", sizeof ("std__")-1, 2, 1 },
583 #endif /* CFRONT_LOSSAGE */
587 while ((ch = *s) == '_')
593 for (p = &special[0]; p->len > 0; p++)
596 && (!p->two_underscores || ((s - orig_s) >= 2))
597 && strncmp(s, p->name, p->len) == 0)
605 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
606 and one from the PATH variable. */
608 static struct path_prefix cpath, path;
611 /* This is the name of the target machine. We use it to form the name
612 of the files to execute. */
614 static const char *const target_machine = TARGET_MACHINE;
617 /* Search for NAME using prefix list PPREFIX. We only look for executable
620 Return 0 if not found, otherwise return its name, allocated with malloc. */
623 find_a_file (pprefix, name)
624 struct path_prefix *pprefix;
628 struct prefix_list *pl;
629 int len = pprefix->max_len + strlen (name) + 1;
632 fprintf (stderr, "Looking for '%s'\n", name);
634 #ifdef HOST_EXECUTABLE_SUFFIX
635 len += strlen (HOST_EXECUTABLE_SUFFIX);
638 temp = xmalloc (len);
640 /* Determine the filename to execute (special case for absolute paths). */
643 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
644 || (*name && name[1] == ':')
648 if (access (name, X_OK) == 0)
653 fprintf (stderr, " - found: absolute path\n");
658 #ifdef HOST_EXECUTABLE_SUFFIX
659 /* Some systems have a suffix for executable files.
660 So try appending that. */
662 strcat (temp, HOST_EXECUTABLE_SUFFIX);
664 if (access (temp, X_OK) == 0)
669 fprintf (stderr, " - failed to locate using absolute path\n");
672 for (pl = pprefix->plist; pl; pl = pl->next)
676 strcpy (temp, pl->prefix);
679 if (stat (temp, &st) >= 0
680 && ! S_ISDIR (st.st_mode)
681 && access (temp, X_OK) == 0)
684 #ifdef HOST_EXECUTABLE_SUFFIX
685 /* Some systems have a suffix for executable files.
686 So try appending that. */
687 strcat (temp, HOST_EXECUTABLE_SUFFIX);
689 if (stat (temp, &st) >= 0
690 && ! S_ISDIR (st.st_mode)
691 && access (temp, X_OK) == 0)
696 if (debug && pprefix->plist == NULL)
697 fprintf (stderr, " - failed: no entries in prefix list\n");
703 /* Add an entry for PREFIX to prefix list PPREFIX. */
706 add_prefix (pprefix, prefix)
707 struct path_prefix *pprefix;
710 struct prefix_list *pl, **prev;
715 for (pl = pprefix->plist; pl->next; pl = pl->next)
720 prev = &pprefix->plist;
722 /* Keep track of the longest prefix */
724 len = strlen (prefix);
725 if (len > pprefix->max_len)
726 pprefix->max_len = len;
728 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
729 pl->prefix = xstrdup (prefix);
734 pl->next = (struct prefix_list *) 0;
738 /* Take the value of the environment variable ENV, break it into a path, and
739 add of the entries to PPREFIX. */
742 prefix_from_env (env, pprefix)
744 struct path_prefix *pprefix;
747 GET_ENV_PATH_LIST (p, env);
750 prefix_from_string (p, pprefix);
754 prefix_from_string (p, pprefix)
756 struct path_prefix *pprefix;
758 const char *startp, *endp;
759 char *nstore = (char *) xmalloc (strlen (p) + 3);
762 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
767 if (*endp == PATH_SEPARATOR || *endp == 0)
769 strncpy (nstore, startp, endp-startp);
772 strcpy (nstore, "./");
774 else if (! IS_DIR_SEPARATOR (endp[-1]))
776 nstore[endp-startp] = DIR_SEPARATOR;
777 nstore[endp-startp+1] = 0;
780 nstore[endp-startp] = 0;
783 fprintf (stderr, " - add prefix: %s\n", nstore);
785 add_prefix (pprefix, nstore);
788 endp = startp = endp + 1;
797 int main PARAMS ((int, char *[]));
803 static const char *const ld_suffix = "ld";
804 static const char *const real_ld_suffix = "real-ld";
805 static const char *const collect_ld_suffix = "collect-ld";
806 static const char *const nm_suffix = "nm";
807 static const char *const gnm_suffix = "gnm";
809 static const char *const ldd_suffix = LDD_SUFFIX;
811 static const char *const strip_suffix = "strip";
812 static const char *const gstrip_suffix = "gstrip";
815 /* If we look for a program in the compiler directories, we just use
816 the short name, since these directories are already system-specific.
817 But it we look for a program in the system directories, we need to
818 qualify the program name with the target machine. */
820 const char *const full_ld_suffix =
821 concat(target_machine, "-", ld_suffix, NULL);
822 const char *const full_nm_suffix =
823 concat (target_machine, "-", nm_suffix, NULL);
824 const char *const full_gnm_suffix =
825 concat (target_machine, "-", gnm_suffix, NULL);
827 const char *const full_ldd_suffix =
828 concat (target_machine, "-", ldd_suffix, NULL);
830 const char *const full_strip_suffix =
831 concat (target_machine, "-", strip_suffix, NULL);
832 const char *const full_gstrip_suffix =
833 concat (target_machine, "-", gstrip_suffix, NULL);
835 const char *const full_ld_suffix = ld_suffix;
836 const char *const full_nm_suffix = nm_suffix;
837 const char *const full_gnm_suffix = gnm_suffix;
839 const char *const full_ldd_suffix = ldd_suffix;
841 const char *const full_strip_suffix = strip_suffix;
842 const char *const full_gstrip_suffix = gstrip_suffix;
843 #endif /* CROSS_COMPILE */
847 #ifdef COLLECT_EXPORT_LIST
850 const char *ld_file_name;
861 int num_c_args = argc+9;
863 no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
865 /* Suppress demangling by the real linker, which may be broken. */
866 putenv (xstrdup ("COLLECT_NO_DEMANGLE="));
868 #if defined (COLLECT2_HOST_INITIALIZATION)
869 /* Perform system dependent initialization, if necessary. */
870 COLLECT2_HOST_INITIALIZATION;
874 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
875 receive the signal. A different setting is inheritable */
876 signal (SIGCHLD, SIG_DFL);
881 /* Do not invoke xcalloc before this point, since locale needs to be
882 set first, in case a diagnostic is issued. */
884 ld1 = (const char **)(ld1_argv = (char **) xcalloc(sizeof (char *), argc+3));
885 ld2 = (const char **)(ld2_argv = (char **) xcalloc(sizeof (char *), argc+10));
886 object = (const char **)(object_lst = (char **) xcalloc(sizeof (char *), argc));
892 /* Parse command line early for instances of -debug. This allows
893 the debug flag to be set before functions like find_a_file()
898 for (i = 1; argv[i] != NULL; i ++)
899 if (! strcmp (argv[i], "-debug"))
904 #ifndef DEFAULT_A_OUT_NAME
905 output_file = "a.out";
907 output_file = DEFAULT_A_OUT_NAME;
910 obstack_begin (&temporary_obstack, 0);
911 obstack_begin (&permanent_obstack, 0);
912 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
914 current_demangling_style = auto_demangling;
915 p = getenv ("COLLECT_GCC_OPTIONS");
918 const char *q = extract_string (&p);
919 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
922 obstack_free (&temporary_obstack, temporary_firstobj);
924 /* -fno-exceptions -w */
927 c_ptr = (const char **)
928 (c_argv = (char **) xcalloc (sizeof (char *), num_c_args));
931 fatal ("no arguments");
934 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
935 signal (SIGQUIT, handler);
937 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
938 signal (SIGINT, handler);
940 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
941 signal (SIGALRM, handler);
944 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
945 signal (SIGHUP, handler);
947 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
948 signal (SIGSEGV, handler);
950 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
951 signal (SIGBUS, handler);
954 /* Extract COMPILER_PATH and PATH into our prefix list. */
955 prefix_from_env ("COMPILER_PATH", &cpath);
956 prefix_from_env ("PATH", &path);
958 /* Try to discover a valid linker/nm/strip to use. */
960 /* Maybe we know the right file to use (if not cross). */
962 #ifdef DEFAULT_LINKER
963 if (access (DEFAULT_LINKER, X_OK) == 0)
964 ld_file_name = DEFAULT_LINKER;
965 if (ld_file_name == 0)
967 #ifdef REAL_LD_FILE_NAME
968 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
969 if (ld_file_name == 0)
971 /* Search the (target-specific) compiler dirs for ld'. */
972 ld_file_name = find_a_file (&cpath, real_ld_suffix);
973 /* Likewise for `collect-ld'. */
974 if (ld_file_name == 0)
975 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
976 /* Search the compiler directories for `ld'. We have protection against
977 recursive calls in find_a_file. */
978 if (ld_file_name == 0)
979 ld_file_name = find_a_file (&cpath, ld_suffix);
980 /* Search the ordinary system bin directories
981 for `ld' (if native linking) or `TARGET-ld' (if cross). */
982 if (ld_file_name == 0)
983 ld_file_name = find_a_file (&path, full_ld_suffix);
985 #ifdef REAL_NM_FILE_NAME
986 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
987 if (nm_file_name == 0)
989 nm_file_name = find_a_file (&cpath, gnm_suffix);
990 if (nm_file_name == 0)
991 nm_file_name = find_a_file (&path, full_gnm_suffix);
992 if (nm_file_name == 0)
993 nm_file_name = find_a_file (&cpath, nm_suffix);
994 if (nm_file_name == 0)
995 nm_file_name = find_a_file (&path, full_nm_suffix);
998 ldd_file_name = find_a_file (&cpath, ldd_suffix);
999 if (ldd_file_name == 0)
1000 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1003 #ifdef REAL_STRIP_FILE_NAME
1004 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1005 if (strip_file_name == 0)
1007 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1008 if (strip_file_name == 0)
1009 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1010 if (strip_file_name == 0)
1011 strip_file_name = find_a_file (&cpath, strip_suffix);
1012 if (strip_file_name == 0)
1013 strip_file_name = find_a_file (&path, full_strip_suffix);
1015 /* Determine the full path name of the C compiler to use. */
1016 c_file_name = getenv ("COLLECT_GCC");
1017 if (c_file_name == 0)
1019 #ifdef CROSS_COMPILE
1020 c_file_name = concat (target_machine, "-gcc", NULL);
1022 c_file_name = "gcc";
1026 p = find_a_file (&cpath, c_file_name);
1028 /* Here it should be safe to use the system search path since we should have
1029 already qualified the name of the compiler when it is needed. */
1031 p = find_a_file (&path, c_file_name);
1036 *ld1++ = *ld2++ = ld_file_name;
1038 /* Make temp file names. */
1039 c_file = make_temp_file (".c");
1040 o_file = make_temp_file (".o");
1041 #ifdef COLLECT_EXPORT_LIST
1042 export_file = make_temp_file (".x");
1044 ldout = make_temp_file (".ld");
1045 *c_ptr++ = c_file_name;
1052 #ifdef COLLECT_EXPORT_LIST
1053 /* Generate a list of directories from LIBPATH. */
1054 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1055 /* Add to this list also two standard directories where
1056 AIX loader always searches for libraries. */
1057 add_prefix (&libpath_lib_dirs, "/lib");
1058 add_prefix (&libpath_lib_dirs, "/usr/lib");
1061 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1063 AIX support needs to know if -shared has been specified before
1064 parsing commandline arguments. */
1066 p = getenv ("COLLECT_GCC_OPTIONS");
1069 const char *q = extract_string (&p);
1070 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1071 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1072 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1073 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1074 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1076 if (*q == '-' && q[1] == 'B')
1078 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1081 q = extract_string (&p);
1082 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1086 obstack_free (&temporary_obstack, temporary_firstobj);
1087 *c_ptr++ = "-fno-exceptions";
1090 /* !!! When GCC calls collect2,
1091 it does not know whether it is calling collect2 or ld.
1092 So collect2 cannot meaningfully understand any options
1093 except those ld understands.
1094 If you propose to make GCC pass some other option,
1095 just imagine what will happen if ld is really ld!!! */
1097 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1098 /* After the first file, put in the c++ rt0. */
1101 while ((arg = *++argv) != (char *) 0)
1103 *ld1++ = *ld2++ = arg;
1109 #ifdef COLLECT_EXPORT_LIST
1110 /* We want to disable automatic exports on AIX when user
1111 explicitly puts an export list in command line */
1113 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1115 else if (arg[2] == '6' && arg[3] == '4')
1121 if (!strcmp (arg, "-debug"))
1123 /* Already parsed. */
1132 /* place o_file BEFORE this argument! */
1138 #ifdef COLLECT_EXPORT_LIST
1140 /* Resolving full library name. */
1141 const char *s = resolve_lib_name (arg+2);
1143 /* Saving a full library name. */
1144 add_to_list (&libs, s);
1149 #ifdef COLLECT_EXPORT_LIST
1150 /* Saving directories where to search for libraries. */
1152 add_prefix (&cmdline_lib_dirs, arg+2);
1155 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1157 if (is_in_args (arg, (const char **) ld1_argv, ld1-1))
1160 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1165 output_file = *ld1++ = *ld2++ = *++argv;
1167 #ifdef SWITCHES_NEED_SPACES
1168 && ! strchr (SWITCHES_NEED_SPACES, arg[1])
1172 output_file = &arg[2];
1181 if (arg[2] == '\0' && do_collecting)
1183 /* We must strip after the nm run, otherwise C++ linking
1184 will not work. Thus we strip in the second ld run, or
1185 else with strip if there is no second ld run. */
1197 else if ((p = strrchr (arg, '.')) != (char *) 0
1198 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1199 || strcmp (p, ".so") == 0 || strcmp (p, ".lo") == 0
1200 || strcmp (p, ".obj") == 0))
1209 /* place o_file BEFORE this argument! */
1215 if (p[1] == 'o' || p[1] == 'l')
1217 #ifdef COLLECT_EXPORT_LIST
1218 /* libraries can be specified directly, i.e. without -l flag. */
1221 /* Saving a full library name. */
1222 add_to_list (&libs, arg);
1228 #ifdef COLLECT_EXPORT_LIST
1229 /* This is added only for debugging purposes. */
1232 fprintf (stderr, "List of libraries:\n");
1233 dump_list (stderr, "\t", libs.first);
1236 /* The AIX linker will discard static constructors in object files if
1237 nothing else in the file is referenced, so look at them first. */
1239 const char **export_object_lst = (const char **)object_lst;
1241 while (export_object_lst < object)
1242 scan_prog_file (*export_object_lst++, PASS_OBJ);
1245 struct id *list = libs.first;
1247 for (; list; list = list->next)
1248 scan_prog_file (list->name, PASS_FIRST);
1253 char *buf = concat ("-bE:", export_file, NULL);
1258 exportf = fopen (export_file, "w");
1259 if (exportf == (FILE *) 0)
1260 fatal_perror ("fopen %s", export_file);
1261 write_aix_file (exportf, exports.first);
1262 if (fclose (exportf))
1263 fatal_perror ("fclose %s", export_file);
1268 *c_ptr = *ld1 = *object = (char *) 0;
1272 notice ("collect2 version %s", version_string);
1273 #ifdef TARGET_VERSION
1276 fprintf (stderr, "\n");
1282 fprintf (stderr, "ld_file_name = %s\n",
1283 (ld_file_name ? ld_file_name : "not found"));
1284 fprintf (stderr, "c_file_name = %s\n",
1285 (c_file_name ? c_file_name : "not found"));
1286 fprintf (stderr, "nm_file_name = %s\n",
1287 (nm_file_name ? nm_file_name : "not found"));
1289 fprintf (stderr, "ldd_file_name = %s\n",
1290 (ldd_file_name ? ldd_file_name : "not found"));
1292 fprintf (stderr, "strip_file_name = %s\n",
1293 (strip_file_name ? strip_file_name : "not found"));
1294 fprintf (stderr, "c_file = %s\n",
1295 (c_file ? c_file : "not found"));
1296 fprintf (stderr, "o_file = %s\n",
1297 (o_file ? o_file : "not found"));
1299 ptr = getenv ("COLLECT_GCC_OPTIONS");
1301 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1303 ptr = getenv ("COLLECT_GCC");
1305 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1307 ptr = getenv ("COMPILER_PATH");
1309 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1311 ptr = getenv (LIBRARY_PATH_ENV);
1313 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1315 fprintf (stderr, "\n");
1318 /* Load the program, searching all libraries and attempting to provide
1319 undefined symbols from repository information. */
1321 /* On AIX we do this later. */
1322 #ifndef COLLECT_EXPORT_LIST
1323 do_tlink (ld1_argv, object_lst);
1326 /* If -r or they will be run via some other method, do not build the
1327 constructor or destructor list, just return now. */
1329 #ifndef COLLECT_EXPORT_LIST
1334 #ifdef COLLECT_EXPORT_LIST
1335 /* Do the link we avoided above if we are exiting. */
1336 do_tlink (ld1_argv, object_lst);
1338 /* But make sure we delete the export file we may have created. */
1339 if (export_file != 0 && export_file[0])
1340 maybe_unlink (export_file);
1342 maybe_unlink (c_file);
1343 maybe_unlink (o_file);
1347 /* Examine the namelist with nm and search it for static constructors
1348 and destructors to call.
1349 Write the constructor and destructor tables to a .s file and reload. */
1351 /* On AIX we already scanned for global constructors/destructors. */
1352 #ifndef COLLECT_EXPORT_LIST
1353 scan_prog_file (output_file, PASS_FIRST);
1356 #ifdef SCAN_LIBRARIES
1357 scan_libraries (output_file);
1362 notice ("%d constructor(s) found\n", constructors.number);
1363 notice ("%d destructor(s) found\n", destructors.number);
1364 notice ("%d frame table(s) found\n", frame_tables.number);
1367 if (constructors.number == 0 && destructors.number == 0
1368 && frame_tables.number == 0
1369 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1370 /* If we will be running these functions ourselves, we want to emit
1371 stubs into the shared library so that we do not have to relink
1372 dependent programs when we add static objects. */
1377 #ifdef COLLECT_EXPORT_LIST
1378 /* Do tlink without additional code generation */
1379 do_tlink (ld1_argv, object_lst);
1381 /* Strip now if it was requested on the command line. */
1384 char **real_strip_argv = (char **) xcalloc (sizeof (char *), 3);
1385 const char ** strip_argv = (const char **) real_strip_argv;
1387 strip_argv[0] = strip_file_name;
1388 strip_argv[1] = output_file;
1389 strip_argv[2] = (char *) 0;
1390 fork_execute ("strip", real_strip_argv);
1393 #ifdef COLLECT_EXPORT_LIST
1394 maybe_unlink (export_file);
1396 maybe_unlink (c_file);
1397 maybe_unlink (o_file);
1401 /* Sort ctor and dtor lists by priority. */
1402 sort_ids (&constructors);
1403 sort_ids (&destructors);
1405 maybe_unlink(output_file);
1406 outf = fopen (c_file, "w");
1407 if (outf == (FILE *) 0)
1408 fatal_perror ("fopen %s", c_file);
1410 write_c_file (outf, c_file);
1413 fatal_perror ("fclose %s", c_file);
1415 /* Tell the linker that we have initializer and finalizer functions. */
1416 #ifdef LD_INIT_SWITCH
1417 #ifdef COLLECT_EXPORT_LIST
1418 *ld2++ = concat (LD_INIT_SWITCH, ":", initname, ":", fininame, NULL);
1420 *ld2++ = LD_INIT_SWITCH;
1422 *ld2++ = LD_FINI_SWITCH;
1427 #ifdef COLLECT_EXPORT_LIST
1430 /* If we did not add export flag to link arguments before, add it to
1431 second link phase now. No new exports should have been added. */
1432 if (! exports.first)
1433 *ld2++ = concat ("-bE:", export_file, NULL);
1435 add_to_list (&exports, initname);
1436 add_to_list (&exports, fininame);
1437 add_to_list (&exports, "_GLOBAL__DI");
1438 add_to_list (&exports, "_GLOBAL__DD");
1439 exportf = fopen (export_file, "w");
1440 if (exportf == (FILE *) 0)
1441 fatal_perror ("fopen %s", export_file);
1442 write_aix_file (exportf, exports.first);
1443 if (fclose (exportf))
1444 fatal_perror ("fclose %s", export_file);
1448 /* End of arguments to second link phase. */
1453 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1454 output_file, c_file);
1455 write_c_file (stderr, "stderr");
1456 fprintf (stderr, "========== end of c_file\n\n");
1457 #ifdef COLLECT_EXPORT_LIST
1458 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1459 write_aix_file (stderr, exports.first);
1460 fprintf (stderr, "========== end of export_file\n\n");
1464 /* Assemble the constructor and destructor tables.
1465 Link the tables in with the rest of the program. */
1467 fork_execute ("gcc", c_argv);
1468 #ifdef COLLECT_EXPORT_LIST
1469 /* On AIX we must call tlink because of possible templates resolution */
1470 do_tlink (ld2_argv, object_lst);
1472 /* Otherwise, simply call ld because tlink is already done */
1473 fork_execute ("ld", ld2_argv);
1475 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1476 constructors/destructors in shared libraries. */
1477 scan_prog_file (output_file, PASS_SECOND);
1480 maybe_unlink (c_file);
1481 maybe_unlink (o_file);
1483 #ifdef COLLECT_EXPORT_LIST
1484 maybe_unlink (export_file);
1491 /* Wait for a process to finish, and exit if a non-zero status is found. */
1499 pwait (pexecute_pid, &status, 0);
1502 if (WIFSIGNALED (status))
1504 int sig = WTERMSIG (status);
1505 error ("%s terminated with signal %d [%s]%s",
1506 prog, sig, strsignal(sig),
1507 status & 0200 ? "" : ", core dumped");
1508 collect_exit (FATAL_EXIT_CODE);
1511 if (WIFEXITED (status))
1512 return WEXITSTATUS (status);
1521 int ret = collect_wait (prog);
1524 error ("%s returned %d exit status", prog, ret);
1530 /* Execute a program, and wait for the reply. */
1533 collect_execute (prog, argv, redir)
1540 int redir_handle = -1;
1541 int stdout_save = -1;
1542 int stderr_save = -1;
1550 fprintf (stderr, "%s", argv[0]);
1552 notice ("[cannot find %s]", prog);
1554 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1555 fprintf (stderr, " %s", str);
1557 fprintf (stderr, "\n");
1563 /* If we cannot find a program we need, complain error. Do this here
1564 since we might not end up needing something that we could not find. */
1567 fatal ("cannot find `%s'", prog);
1571 /* Open response file. */
1572 redir_handle = open (redir, O_WRONLY | O_TRUNC | O_CREAT);
1574 /* Duplicate the stdout and stderr file handles
1575 so they can be restored later. */
1576 stdout_save = dup (STDOUT_FILENO);
1577 if (stdout_save == -1)
1578 fatal_perror ("redirecting stdout: %s", redir);
1579 stderr_save = dup (STDERR_FILENO);
1580 if (stderr_save == -1)
1581 fatal_perror ("redirecting stdout: %s", redir);
1583 /* Redirect stdout & stderr to our response file. */
1584 dup2 (redir_handle, STDOUT_FILENO);
1585 dup2 (redir_handle, STDERR_FILENO);
1588 pexecute_pid = pexecute (argv[0], argv, argv[0], NULL,
1589 &errmsg_fmt, &errmsg_arg,
1590 (PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH));
1594 /* Restore stdout and stderr to their previous settings. */
1595 dup2 (stdout_save, STDOUT_FILENO);
1596 dup2 (stderr_save, STDERR_FILENO);
1598 /* Close response file. */
1599 close (redir_handle);
1602 if (pexecute_pid == -1)
1603 fatal_perror (errmsg_fmt, errmsg_arg);
1607 fork_execute (prog, argv)
1611 collect_execute (prog, argv, NULL);
1615 /* Unlink a file unless we are debugging. */
1624 notice ("[Leaving %s]\n", file);
1628 static long sequence_number = 0;
1630 /* Add a name to a linked list. */
1633 add_to_list (head_ptr, name)
1634 struct head *head_ptr;
1638 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1640 strcpy (newid->name, name);
1642 if (head_ptr->first)
1643 head_ptr->last->next = newid;
1645 head_ptr->first = newid;
1647 /* Check for duplicate symbols. */
1648 for (p = head_ptr->first;
1649 strcmp (name, p->name) != 0;
1654 head_ptr->last->next = 0;
1659 newid->sequence = ++sequence_number;
1660 head_ptr->last = newid;
1664 /* Grab the init priority number from an init function name that
1665 looks like "_GLOBAL_.I.12345.foo". */
1668 extract_init_priority (name)
1673 while (name[pos] == '_')
1675 pos += 10; /* strlen ("GLOBAL__X_") */
1677 /* Extract init_p number from ctor/dtor name. */
1678 pri = atoi (name + pos);
1679 return pri ? pri : DEFAULT_INIT_PRIORITY;
1682 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1683 ctors will be run from right to left, dtors from left to right. */
1687 struct head *head_ptr;
1689 /* id holds the current element to insert. id_next holds the next
1690 element to insert. id_ptr iterates through the already sorted elements
1691 looking for the place to insert id. */
1692 struct id *id, *id_next, **id_ptr;
1694 id = head_ptr->first;
1696 /* We don't have any sorted elements yet. */
1697 head_ptr->first = NULL;
1699 for (; id; id = id_next)
1702 id->sequence = extract_init_priority (id->name);
1704 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1706 /* If the sequence numbers are the same, we put the id from the
1707 file later on the command line later in the list. */
1708 || id->sequence > (*id_ptr)->sequence
1709 /* Hack: do lexical compare, too.
1710 || (id->sequence == (*id_ptr)->sequence
1711 && strcmp (id->name, (*id_ptr)->name) > 0) */
1720 /* Now set the sequence numbers properly so write_c_file works. */
1721 for (id = head_ptr->first; id; id = id->next)
1722 id->sequence = ++sequence_number;
1725 /* Write: `prefix', the names on list LIST, `suffix'. */
1728 write_list (stream, prefix, list)
1735 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1740 #if LINK_ELIMINATE_DUPLICATE_LDIRECTORIES
1741 /* Given a STRING, return nonzero if it occurs in the list in range
1742 [ARGS_BEGIN,ARGS_END). */
1745 is_in_args (string, args_begin, args_end)
1747 const char **args_begin;
1748 const char **args_end;
1750 const char **args_pointer;
1751 for (args_pointer = args_begin; args_pointer != args_end; ++args_pointer)
1752 if (strcmp (string, *args_pointer) == 0)
1756 #endif /* LINK_ELIMINATE_DUPLICATE_LDIRECTORIES */
1758 #ifdef COLLECT_EXPORT_LIST
1759 /* This function is really used only on AIX, but may be useful. */
1762 is_in_list (prefix, list)
1768 if (!strcmp (prefix, list->name)) return 1;
1774 #endif /* COLLECT_EXPORT_LIST */
1776 /* Added for debugging purpose. */
1777 #ifdef COLLECT_EXPORT_LIST
1779 dump_list (stream, prefix, list)
1786 fprintf (stream, "%s%s,\n", prefix, list->name);
1794 dump_prefix_list (stream, prefix, list)
1797 struct prefix_list *list;
1801 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1808 write_list_with_asm (stream, prefix, list)
1815 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1816 prefix, list->sequence, list->name);
1821 /* Write out the constructor and destructor tables statically (for a shared
1822 object), along with the functions to execute them. */
1825 write_c_file_stat (stream, name)
1827 const char *name ATTRIBUTE_UNUSED;
1831 int frames = (frame_tables.number > 0);
1833 /* Figure out name of output_file, stripping off .so version. */
1834 p = strrchr (output_file, '/');
1850 if (strncmp (q, ".so", 3) == 0)
1859 /* q points to null at end of the string (or . of the .so version) */
1860 prefix = xmalloc (q - p + 1);
1861 strncpy (prefix, p, q - p);
1863 for (r = prefix; *r; r++)
1864 if (!ISALNUM ((unsigned char)*r))
1867 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1868 output_file, prefix);
1870 initname = concat ("_GLOBAL__FI_", prefix, NULL);
1871 fininame = concat ("_GLOBAL__FD_", prefix, NULL);
1875 /* Write the tables as C code */
1877 fprintf (stream, "static int count;\n");
1878 fprintf (stream, "typedef void entry_pt();\n");
1879 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1883 write_list_with_asm (stream, "extern void *", frame_tables.first);
1885 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1886 write_list (stream, "\t\t&", frame_tables.first);
1887 fprintf (stream, "\t0\n};\n");
1889 /* This must match what's in frame.h. */
1890 fprintf (stream, "struct object {\n");
1891 fprintf (stream, " void *pc_begin;\n");
1892 fprintf (stream, " void *pc_end;\n");
1893 fprintf (stream, " void *fde_begin;\n");
1894 fprintf (stream, " void *fde_array;\n");
1895 fprintf (stream, " __SIZE_TYPE__ count;\n");
1896 fprintf (stream, " struct object *next;\n");
1897 fprintf (stream, "};\n");
1899 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1900 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1902 fprintf (stream, "static void reg_frame () {\n");
1903 fprintf (stream, "\tstatic struct object ob;\n");
1904 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1905 fprintf (stream, "\t}\n");
1907 fprintf (stream, "static void dereg_frame () {\n");
1908 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1909 fprintf (stream, "\t}\n");
1912 fprintf (stream, "void %s() {\n", initname);
1913 if (constructors.number > 0 || frames)
1915 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1916 write_list (stream, "\t\t", constructors.first);
1918 fprintf (stream, "\treg_frame,\n");
1919 fprintf (stream, "\t};\n");
1920 fprintf (stream, "\tentry_pt **p;\n");
1921 fprintf (stream, "\tif (count++ != 0) return;\n");
1922 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1923 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1926 fprintf (stream, "\t++count;\n");
1927 fprintf (stream, "}\n");
1928 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1929 fprintf (stream, "void %s() {\n", fininame);
1930 if (destructors.number > 0 || frames)
1932 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1933 write_list (stream, "\t\t", destructors.first);
1935 fprintf (stream, "\tdereg_frame,\n");
1936 fprintf (stream, "\t};\n");
1937 fprintf (stream, "\tentry_pt **p;\n");
1938 fprintf (stream, "\tif (--count != 0) return;\n");
1939 fprintf (stream, "\tp = dtors;\n");
1940 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1941 destructors.number + frames);
1943 fprintf (stream, "}\n");
1947 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
1948 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
1952 /* Write the constructor/destructor tables. */
1954 #ifndef LD_INIT_SWITCH
1956 write_c_file_glob (stream, name)
1958 const char *name ATTRIBUTE_UNUSED;
1960 /* Write the tables as C code */
1962 int frames = (frame_tables.number > 0);
1964 fprintf (stream, "typedef void entry_pt();\n\n");
1966 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1970 write_list_with_asm (stream, "extern void *", frame_tables.first);
1972 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1973 write_list (stream, "\t\t&", frame_tables.first);
1974 fprintf (stream, "\t0\n};\n");
1976 /* This must match what's in frame.h. */
1977 fprintf (stream, "struct object {\n");
1978 fprintf (stream, " void *pc_begin;\n");
1979 fprintf (stream, " void *pc_end;\n");
1980 fprintf (stream, " void *fde_begin;\n");
1981 fprintf (stream, " void *fde_array;\n");
1982 fprintf (stream, " __SIZE_TYPE__ count;\n");
1983 fprintf (stream, " struct object *next;\n");
1984 fprintf (stream, "};\n");
1986 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1987 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1989 fprintf (stream, "static void reg_frame () {\n");
1990 fprintf (stream, "\tstatic struct object ob;\n");
1991 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1992 fprintf (stream, "\t}\n");
1994 fprintf (stream, "static void dereg_frame () {\n");
1995 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1996 fprintf (stream, "\t}\n");
1999 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2000 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2001 write_list (stream, "\t", constructors.first);
2003 fprintf (stream, "\treg_frame,\n");
2004 fprintf (stream, "\t0\n};\n\n");
2006 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2008 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2009 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2010 write_list (stream, "\t", destructors.first);
2012 fprintf (stream, "\tdereg_frame,\n");
2013 fprintf (stream, "\t0\n};\n\n");
2015 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2016 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2018 #endif /* ! LD_INIT_SWITCH */
2021 write_c_file (stream, name)
2025 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2026 #ifndef LD_INIT_SWITCH
2028 write_c_file_glob (stream, name);
2031 write_c_file_stat (stream, name);
2032 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2035 #ifdef COLLECT_EXPORT_LIST
2037 write_aix_file (stream, list)
2041 for (; list; list = list->next)
2043 fputs (list->name, stream);
2044 putc ('\n', stream);
2049 #ifdef OBJECT_FORMAT_NONE
2051 /* Generic version to scan the name list of the loaded program for
2052 the symbols g++ uses for static constructors and destructors.
2054 The constructor table begins at __CTOR_LIST__ and contains a count
2055 of the number of pointers (or -1 if the constructors are built in a
2056 separate section by the linker), followed by the pointers to the
2057 constructor functions, terminated with a null pointer. The
2058 destructor table has the same format, and begins at __DTOR_LIST__. */
2061 scan_prog_file (prog_name, which_pass)
2062 const char *prog_name;
2063 enum pass which_pass;
2065 void (*int_handler) PARAMS ((int));
2066 void (*quit_handler) PARAMS ((int));
2067 char *real_nm_argv[4];
2068 const char **nm_argv = (const char **) real_nm_argv;
2075 if (which_pass == PASS_SECOND)
2078 /* If we do not have an `nm', complain. */
2079 if (nm_file_name == 0)
2080 fatal ("cannot find `nm'");
2082 nm_argv[argc++] = nm_file_name;
2083 if (NM_FLAGS[0] != '\0')
2084 nm_argv[argc++] = NM_FLAGS;
2086 nm_argv[argc++] = prog_name;
2087 nm_argv[argc++] = (char *) 0;
2089 if (pipe (pipe_fd) < 0)
2090 fatal_perror ("pipe");
2092 inf = fdopen (pipe_fd[0], "r");
2093 if (inf == (FILE *) 0)
2094 fatal_perror ("fdopen");
2096 /* Trace if needed. */
2099 const char **p_argv;
2102 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2103 fprintf (stderr, " %s", str);
2105 fprintf (stderr, "\n");
2111 /* Spawn child nm on pipe */
2114 fatal_perror (VFORK_STRING);
2116 if (pid == 0) /* child context */
2119 if (dup2 (pipe_fd[1], 1) < 0)
2120 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2122 if (close (pipe_fd[0]) < 0)
2123 fatal_perror ("close %d", pipe_fd[0]);
2125 if (close (pipe_fd[1]) < 0)
2126 fatal_perror ("close %d", pipe_fd[1]);
2128 execv (nm_file_name, real_nm_argv);
2129 fatal_perror ("execvp %s", nm_file_name);
2132 /* Parent context from here on. */
2133 int_handler = (void (*) PARAMS ((int))) signal (SIGINT, SIG_IGN);
2135 quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2138 if (close (pipe_fd[1]) < 0)
2139 fatal_perror ("close %d", pipe_fd[1]);
2142 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2144 /* Read each line of nm output. */
2145 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2150 /* If it contains a constructor or destructor name, add the name
2151 to the appropriate list. */
2153 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2154 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2161 /* Find the end of the symbol name.
2162 Do not include `|', because Encore nm can tack that on the end. */
2163 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2169 switch (is_ctor_dtor (name))
2172 if (which_pass != PASS_LIB)
2173 add_to_list (&constructors, name);
2177 if (which_pass != PASS_LIB)
2178 add_to_list (&destructors, name);
2182 if (which_pass != PASS_LIB)
2183 fatal ("init function found in object %s", prog_name);
2184 #ifndef LD_INIT_SWITCH
2185 add_to_list (&constructors, name);
2190 if (which_pass != PASS_LIB)
2191 fatal ("fini function found in object %s", prog_name);
2192 #ifndef LD_FINI_SWITCH
2193 add_to_list (&destructors, name);
2198 if (which_pass != PASS_LIB)
2199 add_to_list (&frame_tables, name);
2202 default: /* not a constructor or destructor */
2207 fprintf (stderr, "\t%s\n", buf);
2211 fprintf (stderr, "\n");
2213 if (fclose (inf) != 0)
2214 fatal_perror ("fclose");
2216 do_wait (nm_file_name);
2218 signal (SIGINT, int_handler);
2220 signal (SIGQUIT, quit_handler);
2224 #if SUNOS4_SHARED_LIBRARIES
2226 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2227 that the output file depends upon and their initialization/finalization
2228 routines, if any. */
2233 #include <sys/mman.h>
2234 #include <sys/param.h>
2236 #include <sys/dir.h>
2238 /* pointers to the object file */
2239 unsigned object; /* address of memory mapped file */
2240 unsigned objsize; /* size of memory mapped to file */
2241 char * code; /* pointer to code segment */
2242 char * data; /* pointer to data segment */
2243 struct nlist *symtab; /* pointer to symbol table */
2244 struct link_dynamic *ld;
2245 struct link_dynamic_2 *ld_2;
2246 struct head libraries;
2248 /* Map the file indicated by NAME into memory and store its address. */
2250 static void mapfile PARAMS ((const char *));
2258 if ((fp = open (name, O_RDONLY)) == -1)
2259 fatal ("unable to open file '%s'", name);
2260 if (fstat (fp, &s) == -1)
2261 fatal ("unable to stat file '%s'", name);
2263 objsize = s.st_size;
2264 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2266 if (object == (unsigned)-1)
2267 fatal ("unable to mmap file '%s'", name);
2272 /* Helpers for locatelib. */
2274 static const char *libname;
2276 static int libselect PARAMS ((struct direct *));
2282 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2285 /* If one file has an additional numeric extension past LIBNAME, then put
2286 that one first in the sort. If both files have additional numeric
2287 extensions, then put the one with the higher number first in the sort.
2289 We must verify that the extension is numeric, because Sun saves the
2290 original versions of patched libraries with a .FCS extension. Files with
2291 invalid extensions must go last in the sort, so that they will not be used. */
2292 static int libcompare PARAMS ((struct direct **, struct direct **));
2296 struct direct **d1, **d2;
2298 int i1, i2 = strlen (libname);
2299 char *e1 = (*d1)->d_name + i2;
2300 char *e2 = (*d2)->d_name + i2;
2302 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2303 && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2307 i1 = strtol (e1, &e1, 10);
2308 i2 = strtol (e2, &e2, 10);
2315 /* It has a valid numeric extension, prefer this one. */
2316 if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2318 /* It has an invalid numeric extension, must prefer the other one. */
2324 /* It has a valid numeric extension, prefer this one. */
2325 if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2327 /* It has an invalid numeric extension, must prefer the other one. */
2335 /* Given the name NAME of a dynamic dependency, find its pathname and add
2336 it to the list of libraries. */
2337 static void locatelib PARAMS ((const char *));
2343 static const char **l;
2345 char buf[MAXPATHLEN];
2353 /* counting elements in array, need 1 extra for null */
2355 ld_rules = (char *) (ld_2->ld_rules + code);
2359 for (; *ld_rules != 0; ld_rules++)
2360 if (*ld_rules == ':')
2362 ld_rules = (char *) (ld_2->ld_rules + code);
2363 ldr = xstrdup (ld_rules);
2365 p = getenv ("LD_LIBRARY_PATH");
2370 for (q = p ; *q != 0; q++)
2375 l = (const char **) xmalloc ((cnt + 3) * sizeof (char *));
2380 for (; *ldr != 0; ldr++)
2390 for (; *q != 0; q++)
2397 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2400 *pp++ = "/usr/local/lib";
2404 for (pp = l; *pp != 0 ; pp++)
2406 struct direct **namelist;
2408 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2410 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2411 add_to_list (&libraries, buf);
2413 fprintf (stderr, "%s\n", buf);
2420 notice ("not found\n");
2422 fatal ("dynamic dependency %s not found", name);
2426 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2427 that it depends upon and any constructors or destructors they contain. */
2430 scan_libraries (prog_name)
2431 const char *prog_name;
2433 struct exec *header;
2435 struct link_object *lo;
2436 char buff[MAXPATHLEN];
2439 mapfile (prog_name);
2440 header = (struct exec *)object;
2441 if (N_BADMAG (*header))
2442 fatal ("bad magic number in file '%s'", prog_name);
2443 if (header->a_dynamic == 0)
2446 code = (char *) (N_TXTOFF (*header) + (long) header);
2447 data = (char *) (N_DATOFF (*header) + (long) header);
2448 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2450 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2453 ld = (struct link_dynamic *) (symtab->n_value + code);
2459 ld = (struct link_dynamic *) data;
2464 notice ("dynamic dependencies.\n");
2466 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2467 for (lo = (struct link_object *) ld_2->ld_need; lo;
2468 lo = (struct link_object *) lo->lo_next)
2471 lo = (struct link_object *) ((long) lo + code);
2472 name = (char *) (code + lo->lo_name);
2476 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2477 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2483 fprintf (stderr, "\t%s\n", name);
2484 add_to_list (&libraries, name);
2489 fprintf (stderr, "\n");
2491 /* now iterate through the library list adding their symbols to
2493 for (list = libraries.first; list; list = list->next)
2494 scan_prog_file (list->name, PASS_LIB);
2497 #else /* SUNOS4_SHARED_LIBRARIES */
2500 /* Use the List Dynamic Dependencies program to find shared libraries that
2501 the output file depends upon and their initialization/finalization
2502 routines, if any. */
2505 scan_libraries (prog_name)
2506 const char *prog_name;
2508 static struct head libraries; /* list of shared libraries found */
2510 void (*int_handler) PARAMS ((int));
2511 void (*quit_handler) PARAMS ((int));
2512 char *real_ldd_argv[4];
2513 const char **ldd_argv = (const char **) real_ldd_argv;
2520 /* If we do not have an `ldd', complain. */
2521 if (ldd_file_name == 0)
2523 error ("cannot find `ldd'");
2527 ldd_argv[argc++] = ldd_file_name;
2528 ldd_argv[argc++] = prog_name;
2529 ldd_argv[argc++] = (char *) 0;
2531 if (pipe (pipe_fd) < 0)
2532 fatal_perror ("pipe");
2534 inf = fdopen (pipe_fd[0], "r");
2535 if (inf == (FILE *) 0)
2536 fatal_perror ("fdopen");
2538 /* Trace if needed. */
2541 const char **p_argv;
2544 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2545 fprintf (stderr, " %s", str);
2547 fprintf (stderr, "\n");
2553 /* Spawn child ldd on pipe */
2556 fatal_perror (VFORK_STRING);
2558 if (pid == 0) /* child context */
2561 if (dup2 (pipe_fd[1], 1) < 0)
2562 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2564 if (close (pipe_fd[0]) < 0)
2565 fatal_perror ("close %d", pipe_fd[0]);
2567 if (close (pipe_fd[1]) < 0)
2568 fatal_perror ("close %d", pipe_fd[1]);
2570 execv (ldd_file_name, real_ldd_argv);
2571 fatal_perror ("execv %s", ldd_file_name);
2574 /* Parent context from here on. */
2575 int_handler = (void (*) PARAMS ((int))) signal (SIGINT, SIG_IGN);
2577 quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2580 if (close (pipe_fd[1]) < 0)
2581 fatal_perror ("close %d", pipe_fd[1]);
2584 notice ("\nldd output with constructors/destructors.\n");
2586 /* Read each line of ldd output. */
2587 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2590 char *name, *end, *p = buf;
2592 /* Extract names of libraries and add to list. */
2593 PARSE_LDD_OUTPUT (p);
2598 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2599 fatal ("dynamic dependency %s not found", buf);
2601 /* Find the end of the symbol name. */
2603 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2608 if (access (name, R_OK) == 0)
2609 add_to_list (&libraries, name);
2611 fatal ("unable to open dynamic dependency '%s'", buf);
2614 fprintf (stderr, "\t%s\n", buf);
2617 fprintf (stderr, "\n");
2619 if (fclose (inf) != 0)
2620 fatal_perror ("fclose");
2622 do_wait (ldd_file_name);
2624 signal (SIGINT, int_handler);
2626 signal (SIGQUIT, quit_handler);
2629 /* now iterate through the library list adding their symbols to
2631 for (list = libraries.first; list; list = list->next)
2632 scan_prog_file (list->name, PASS_LIB);
2635 #endif /* LDD_SUFFIX */
2636 #endif /* SUNOS4_SHARED_LIBRARIES */
2638 #endif /* OBJECT_FORMAT_NONE */
2642 * COFF specific stuff.
2645 #ifdef OBJECT_FORMAT_COFF
2647 #if defined(EXTENDED_COFF)
2649 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2650 # define GCC_SYMENT SYMR
2651 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2652 # define GCC_SYMINC(X) (1)
2653 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2654 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2658 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2659 # define GCC_SYMENT SYMENT
2660 # define GCC_OK_SYMBOL(X) \
2661 (((X).n_sclass == C_EXT) && \
2662 ((X).n_scnum > N_UNDEF) && \
2664 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2665 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2666 # define GCC_UNDEF_SYMBOL(X) \
2667 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2668 # define GCC_SYMINC(X) ((X).n_numaux+1)
2669 # define GCC_SYMZERO(X) 0
2671 /* 0757 = U803XTOCMAGIC (AIX 4.3) and 0767 = U64_TOCMAGIC (AIX V5) */
2673 # define GCC_CHECK_HDR(X) \
2674 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2675 || (HEADER (X).f_magic == 0767 && aix64_flag))
2677 # define GCC_CHECK_HDR(X) \
2678 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2679 || (HEADER (X).f_magic == 0757 && aix64_flag))
2684 extern char *ldgetname ();
2686 /* COFF version to scan the name list of the loaded program for
2687 the symbols g++ uses for static constructors and destructors.
2689 The constructor table begins at __CTOR_LIST__ and contains a count
2690 of the number of pointers (or -1 if the constructors are built in a
2691 separate section by the linker), followed by the pointers to the
2692 constructor functions, terminated with a null pointer. The
2693 destructor table has the same format, and begins at __DTOR_LIST__. */
2696 scan_prog_file (prog_name, which_pass)
2697 const char *prog_name;
2698 enum pass which_pass;
2700 LDFILE *ldptr = NULL;
2701 int sym_index, sym_count;
2704 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2707 #ifdef COLLECT_EXPORT_LIST
2708 /* We do not need scanning for some standard C libraries. */
2709 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2712 /* On AIX we have a loop, because there is not much difference
2713 between an object and an archive. This trick allows us to
2714 eliminate scan_libraries() function. */
2718 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2719 non-const char * filename parameter, even though it will not
2720 modify that string. So we must cast away const-ness here,
2721 which will cause -Wcast-qual to burp. */
2722 if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2724 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2725 fatal ("%s: not a COFF file", prog_name);
2727 if (GCC_CHECK_HDR (ldptr))
2729 sym_count = GCC_SYMBOLS (ldptr);
2730 sym_index = GCC_SYMZERO (ldptr);
2732 #ifdef COLLECT_EXPORT_LIST
2733 /* Is current archive member a shared object? */
2734 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2737 while (sym_index < sym_count)
2741 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2743 sym_index += GCC_SYMINC (symbol);
2745 if (GCC_OK_SYMBOL (symbol))
2749 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2750 continue; /* should never happen */
2752 #ifdef XCOFF_DEBUGGING_INFO
2753 /* All AIX function names have a duplicate entry
2754 beginning with a dot. */
2759 switch (is_ctor_dtor (name))
2763 add_to_list (&constructors, name);
2764 #ifdef COLLECT_EXPORT_LIST
2765 if (which_pass == PASS_OBJ)
2766 add_to_list (&exports, name);
2772 add_to_list (&destructors, name);
2773 #ifdef COLLECT_EXPORT_LIST
2774 if (which_pass == PASS_OBJ)
2775 add_to_list (&exports, name);
2779 #ifdef COLLECT_EXPORT_LIST
2781 #ifndef LD_INIT_SWITCH
2783 add_to_list (&constructors, name);
2788 #ifndef LD_INIT_SWITCH
2790 add_to_list (&destructors, name);
2797 add_to_list (&frame_tables, name);
2798 #ifdef COLLECT_EXPORT_LIST
2799 if (which_pass == PASS_OBJ)
2800 add_to_list (&exports, name);
2804 default: /* not a constructor or destructor */
2805 #ifdef COLLECT_EXPORT_LIST
2806 /* If we are building a shared object on AIX we need
2807 to explicitly export all global symbols. */
2810 if (which_pass == PASS_OBJ && (! export_flag))
2811 add_to_list (&exports, name);
2818 #if !defined(EXTENDED_COFF)
2819 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2820 symbol.n_scnum, symbol.n_sclass,
2821 (symbol.n_type ? "0" : ""), symbol.n_type,
2825 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2826 symbol.iss, (long) symbol.value, symbol.index, name);
2831 #ifdef COLLECT_EXPORT_LIST
2834 /* If archive contains both 32-bit and 64-bit objects,
2835 we want to skip objects in other mode so mismatch normal. */
2837 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2838 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2844 fatal ("%s: cannot open as COFF file", prog_name);
2846 #ifdef COLLECT_EXPORT_LIST
2847 /* On AIX loop continues while there are more members in archive. */
2849 while (ldclose (ldptr) == FAILURE);
2851 /* Otherwise we simply close ldptr. */
2852 (void) ldclose(ldptr);
2857 #ifdef COLLECT_EXPORT_LIST
2858 /* Given a library name without "lib" prefix, this function
2859 returns a full library name including a path. */
2861 resolve_lib_name (name)
2867 for (i = 0; libpaths[i]; i++)
2868 if (libpaths[i]->max_len > l)
2869 l = libpaths[i]->max_len;
2871 lib_buf = xmalloc (l + strlen(name) + 10);
2873 for (i = 0; libpaths[i]; i++)
2875 struct prefix_list *list = libpaths[i]->plist;
2876 for (; list; list = list->next)
2878 /* The following lines are needed because path_prefix list
2879 may contain directories both with trailing '/' and
2882 if (list->prefix[strlen(list->prefix)-1] != '/')
2884 for (j = 0; libexts[j]; j++)
2886 sprintf (lib_buf, "%s%slib%s.%s",
2887 list->prefix, p, name, libexts[j]);
2888 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2889 if (file_exists (lib_buf))
2891 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2898 fprintf (stderr, "not found\n");
2900 fatal ("library lib%s not found", name);
2904 /* Array of standard AIX libraries which should not
2905 be scanned for ctors/dtors. */
2906 static const char *const aix_std_libs[] = {
2914 "/usr/lib/libc_r.a",
2915 "/usr/lib/libm_r.a",
2916 "/usr/lib/threads/libc.a",
2917 "/usr/ccs/lib/libc.a",
2918 "/usr/ccs/lib/libm.a",
2919 "/usr/ccs/lib/libc_r.a",
2920 "/usr/ccs/lib/libm_r.a",
2924 /* This function checks the filename and returns 1
2925 if this name matches the location of a standard AIX library. */
2927 ignore_library (name)
2930 const char *const *p = &aix_std_libs[0];
2931 while (*p++ != NULL)
2932 if (! strcmp (name, *p)) return 1;
2937 #endif /* OBJECT_FORMAT_COFF */
2941 * OSF/rose specific stuff.
2944 #ifdef OBJECT_FORMAT_ROSE
2946 /* Union of the various load commands */
2948 typedef union load_union
2950 ldc_header_t hdr; /* common header */
2951 load_cmd_map_command_t map; /* map indexing other load cmds */
2952 interpreter_command_t iprtr; /* interpreter pathname */
2953 strings_command_t str; /* load commands strings section */
2954 region_command_t region; /* region load command */
2955 reloc_command_t reloc; /* relocation section */
2956 package_command_t pkg; /* package load command */
2957 symbols_command_t sym; /* symbol sections */
2958 entry_command_t ent; /* program start section */
2959 gen_info_command_t info; /* object information */
2960 func_table_command_t func; /* function constructors/destructors */
2963 /* Structure to point to load command and data section in memory. */
2965 typedef struct load_all
2967 load_union_t *load; /* load command */
2968 char *section; /* pointer to section */
2971 /* Structure to contain information about a file mapped into memory. */
2975 char *start; /* start of map */
2976 char *name; /* filename */
2977 long size; /* size of the file */
2978 long rounded_size; /* size rounded to page boundary */
2979 int fd; /* file descriptor */
2980 int rw; /* != 0 if opened read/write */
2981 int use_mmap; /* != 0 if mmap'ed */
2984 extern int decode_mach_o_hdr ();
2985 extern int encode_mach_o_hdr ();
2987 static void add_func_table PARAMS ((mo_header_t *, load_all_t *,
2988 symbol_info_t *, int));
2989 static void print_header PARAMS ((mo_header_t *));
2990 static void print_load_command PARAMS ((load_union_t *, size_t, int));
2991 static void bad_header PARAMS ((int));
2992 static struct file_info *read_file PARAMS ((const char *, int, int));
2993 static void end_file PARAMS ((struct file_info *));
2995 /* OSF/rose specific version to scan the name list of the loaded
2996 program for the symbols g++ uses for static constructors and
2999 The constructor table begins at __CTOR_LIST__ and contains a count
3000 of the number of pointers (or -1 if the constructors are built in a
3001 separate section by the linker), followed by the pointers to the
3002 constructor functions, terminated with a null pointer. The
3003 destructor table has the same format, and begins at __DTOR_LIST__. */
3006 scan_prog_file (prog_name, which_pass)
3007 const char *prog_name;
3008 enum pass which_pass;
3012 load_all_t *load_array;
3013 load_all_t *load_end;
3014 load_all_t *load_cmd;
3015 int symbol_load_cmds;
3021 struct file_info *obj_file;
3023 mo_lcid_t cmd_strings = -1;
3024 symbol_info_t *main_sym = 0;
3025 int rw = (which_pass != PASS_FIRST);
3027 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3029 fatal_perror ("open %s", prog_name);
3031 obj_file = read_file (prog_name, prog_fd, rw);
3032 obj = obj_file->start;
3034 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3035 if (status != MO_HDR_CONV_SUCCESS)
3036 bad_header (status);
3039 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3040 since the hardware will automatically swap bytes for us on loading little endian
3043 #ifndef CROSS_COMPILE
3044 if (hdr.moh_magic != MOH_MAGIC_MSB
3045 || hdr.moh_header_version != MOH_HEADER_VERSION
3046 || hdr.moh_byte_order != OUR_BYTE_ORDER
3047 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3048 || hdr.moh_cpu_type != OUR_CPU_TYPE
3049 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3050 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3052 fatal ("incompatibilities between object file & expected values");
3057 print_header (&hdr);
3059 offset = hdr.moh_first_cmd_off;
3060 load_end = load_array
3061 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3063 /* Build array of load commands, calculating the offsets */
3064 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3066 load_union_t *load_hdr; /* load command header */
3068 load_cmd = load_end++;
3069 load_hdr = (load_union_t *) (obj + offset);
3071 /* If modifying the program file, copy the header. */
3074 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3075 memcpy ((char *)ptr, (char *)load_hdr, load_hdr->hdr.ldci_cmd_size);
3078 /* null out old command map, because we will rewrite at the end. */
3079 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3081 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3082 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3086 load_cmd->load = load_hdr;
3087 if (load_hdr->hdr.ldci_section_off > 0)
3088 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3091 print_load_command (load_hdr, offset, i);
3093 offset += load_hdr->hdr.ldci_cmd_size;
3096 /* If the last command is the load command map and is not undefined,
3097 decrement the count of load commands. */
3098 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3101 hdr.moh_n_load_cmds--;
3104 /* Go through and process each symbol table section. */
3105 symbol_load_cmds = 0;
3106 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3108 load_union_t *load_hdr = load_cmd->load;
3110 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3116 const char *kind = "unknown";
3118 switch (load_hdr->sym.symc_kind)
3120 case SYMC_IMPORTS: kind = "imports"; break;
3121 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3122 case SYMC_STABS: kind = "stabs"; break;
3125 notice ("\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3126 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3129 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3132 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3133 if (str_sect == (char *) 0)
3134 fatal ("string section missing");
3136 if (load_cmd->section == (char *) 0)
3137 fatal ("section pointer missing");
3139 num_syms = load_hdr->sym.symc_nentries;
3140 for (i = 0; i < num_syms; i++)
3142 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3143 char *name = sym->si_name.symbol_name + str_sect;
3150 char *n = name + strlen (name) - strlen (NAME__MAIN);
3152 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3162 switch (is_ctor_dtor (name))
3165 add_to_list (&constructors, name);
3169 add_to_list (&destructors, name);
3172 default: /* not a constructor or destructor */
3178 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3179 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3184 if (symbol_load_cmds == 0)
3185 fatal ("no symbol table found");
3187 /* Update the program file now, rewrite header and load commands. At present,
3188 we assume that there is enough space after the last load command to insert
3189 one more. Since the first section written out is page aligned, and the
3190 number of load commands is small, this is ok for the present. */
3194 load_union_t *load_map;
3197 if (cmd_strings == -1)
3198 fatal ("no cmd_strings found");
3200 /* Add __main to initializer list.
3201 If we are building a program instead of a shared library, do not
3202 do anything, since in the current version, you cannot do mallocs
3203 and such in the constructors. */
3205 if (main_sym != (symbol_info_t *) 0
3206 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3207 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3210 notice ("\nUpdating header and load commands.\n\n");
3212 hdr.moh_n_load_cmds++;
3213 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3215 /* Create new load command map. */
3217 notice ("load command map, %d cmds, new size %ld.\n",
3218 (int) hdr.moh_n_load_cmds, (long) size);
3220 load_map = (load_union_t *) xcalloc (1, size);
3221 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3222 load_map->map.ldc_header.ldci_cmd_size = size;
3223 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3224 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3225 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3227 offset = hdr.moh_first_cmd_off;
3228 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3230 load_map->map.lcm_map[i] = offset;
3231 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3232 hdr.moh_load_map_cmd_off = offset;
3234 offset += load_array[i].load->hdr.ldci_cmd_size;
3237 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3240 print_header (&hdr);
3243 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3244 if (status != MO_HDR_CONV_SUCCESS)
3245 bad_header (status);
3248 notice ("writing load commands.\n\n");
3250 /* Write load commands */
3251 offset = hdr.moh_first_cmd_off;
3252 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3254 load_union_t *load_hdr = load_array[i].load;
3255 size_t size = load_hdr->hdr.ldci_cmd_size;
3258 print_load_command (load_hdr, offset, i);
3260 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3265 end_file (obj_file);
3267 if (close (prog_fd))
3268 fatal_perror ("close %s", prog_name);
3271 fprintf (stderr, "\n");
3275 /* Add a function table to the load commands to call a function
3276 on initiation or termination of the process. */
3279 add_func_table (hdr_p, load_array, sym, type)
3280 mo_header_t *hdr_p; /* pointer to global header */
3281 load_all_t *load_array; /* array of ptrs to load cmds */
3282 symbol_info_t *sym; /* pointer to symbol entry */
3283 int type; /* fntc_type value */
3285 /* Add a new load command. */
3286 int num_cmds = ++hdr_p->moh_n_load_cmds;
3287 int load_index = num_cmds - 1;
3288 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3289 load_union_t *ptr = xcalloc (1, size);
3290 load_all_t *load_cmd;
3293 /* Set the unresolved address bit in the header to force the loader to be
3294 used, since kernel exec does not call the initialization functions. */
3295 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3297 load_cmd = &load_array[load_index];
3298 load_cmd->load = ptr;
3299 load_cmd->section = (char *) 0;
3301 /* Fill in func table load command. */
3302 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3303 ptr->func.ldc_header.ldci_cmd_size = size;
3304 ptr->func.ldc_header.ldci_section_off = 0;
3305 ptr->func.ldc_header.ldci_section_len = 0;
3306 ptr->func.fntc_type = type;
3307 ptr->func.fntc_nentries = 1;
3309 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3310 /* Is the symbol already expressed as (region, offset)? */
3311 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3313 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3314 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3317 /* If not, figure out which region it's in. */
3320 mo_vm_addr_t addr = sym->si_value.abs_val;
3323 for (i = 0; i < load_index; i++)
3325 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3327 region_command_t *region_ptr = &load_array[i].load->region;
3329 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3330 && addr >= region_ptr->regc_addr.vm_addr
3331 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3333 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3334 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3342 fatal ("could not convert 0x%l.8x into a region", addr);
3346 notice ("%s function, region %d, offset = %ld (0x%.8lx)\n",
3347 type == FNTC_INITIALIZATION ? "init" : "term",
3348 (int) ptr->func.fntc_entry_loc[i].adr_lcid,
3349 (long) ptr->func.fntc_entry_loc[i].adr_sctoff,
3350 (long) ptr->func.fntc_entry_loc[i].adr_sctoff);
3355 /* Print the global header for an OSF/rose object. */
3358 print_header (hdr_ptr)
3359 mo_header_t *hdr_ptr;
3361 fprintf (stderr, "\nglobal header:\n");
3362 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3363 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3364 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3365 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3366 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3367 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3368 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3369 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3370 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3371 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3372 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3373 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3374 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3375 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3376 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3378 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3379 fprintf (stderr, ", relocatable");
3381 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3382 fprintf (stderr, ", linkable");
3384 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3385 fprintf (stderr, ", execable");
3387 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3388 fprintf (stderr, ", executable");
3390 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3391 fprintf (stderr, ", unresolved");
3393 fprintf (stderr, "\n\n");
3398 /* Print a short summary of a load command. */
3401 print_load_command (load_hdr, offset, number)
3402 load_union_t *load_hdr;
3406 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3407 const char *type_str = (char *) 0;
3411 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3412 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3413 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3414 case LDC_STRINGS: type_str = "STRINGS"; break;
3415 case LDC_REGION: type_str = "REGION"; break;
3416 case LDC_RELOC: type_str = "RELOC"; break;
3417 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3418 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3419 case LDC_ENTRY: type_str = "ENTRY"; break;
3420 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3421 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3425 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3427 (long) load_hdr->hdr.ldci_cmd_size,
3429 (long) load_hdr->hdr.ldci_section_off,
3430 (long) load_hdr->hdr.ldci_section_len);
3432 if (type_str == (char *) 0)
3433 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3435 else if (type != LDC_REGION)
3436 fprintf (stderr, ", ty: %s\n", type_str);
3440 const char *region = "";
3441 switch (load_hdr->region.regc_usage_type)
3443 case REG_TEXT_T: region = ", .text"; break;
3444 case REG_DATA_T: region = ", .data"; break;
3445 case REG_BSS_T: region = ", .bss"; break;
3446 case REG_GLUE_T: region = ", .glue"; break;
3447 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3448 case REG_RDATA_T: region = ", .rdata"; break;
3449 case REG_SDATA_T: region = ", .sdata"; break;
3450 case REG_SBSS_T: region = ", .sbss"; break;
3454 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3456 (long) load_hdr->region.regc_vm_addr,
3457 (long) load_hdr->region.regc_vm_size,
3465 /* Fatal error when {en,de}code_mach_o_header fails. */
3473 case MO_ERROR_BAD_MAGIC: fatal ("bad magic number");
3474 case MO_ERROR_BAD_HDR_VERS: fatal ("bad header version");
3475 case MO_ERROR_BAD_RAW_HDR_VERS: fatal ("bad raw header version");
3476 case MO_ERROR_BUF2SML: fatal ("raw header buffer too small");
3477 case MO_ERROR_OLD_RAW_HDR_FILE: fatal ("old raw header file");
3478 case MO_ERROR_UNSUPPORTED_VERS: fatal ("unsupported version");
3480 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3485 /* Read a file into a memory buffer. */
3487 static struct file_info *
3488 read_file (name, fd, rw)
3489 const char *name; /* filename */
3490 int fd; /* file descriptor */
3491 int rw; /* read/write */
3493 struct stat stat_pkt;
3494 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3496 static int page_size;
3499 if (fstat (fd, &stat_pkt) < 0)
3500 fatal_perror ("fstat %s", name);
3503 p->size = stat_pkt.st_size;
3504 p->rounded_size = stat_pkt.st_size;
3510 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3513 page_size = sysconf (_SC_PAGE_SIZE);
3515 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3516 p->start = mmap ((caddr_t) 0,
3517 (rw) ? p->rounded_size : p->size,
3518 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3519 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3523 if (p->start != (char *) 0 && p->start != (char *) -1)
3527 #endif /* USE_MMAP */
3532 fprintf (stderr, "read %s\n", name);
3535 p->start = xmalloc (p->size);
3536 if (lseek (fd, 0L, SEEK_SET) < 0)
3537 fatal_perror ("lseek %s 0", name);
3539 len = read (fd, p->start, p->size);
3541 fatal_perror ("read %s", name);
3544 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3550 /* Do anything necessary to write a file back from memory. */
3554 struct file_info *ptr; /* file information block */
3562 fprintf (stderr, "msync %s\n", ptr->name);
3564 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3565 fatal_perror ("msync %s", ptr->name);
3569 fprintf (stderr, "munmap %s\n", ptr->name);
3571 if (munmap (ptr->start, ptr->size))
3572 fatal_perror ("munmap %s", ptr->name);
3575 #endif /* USE_MMAP */
3582 fprintf (stderr, "write %s\n", ptr->name);
3584 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3585 fatal_perror ("lseek %s 0", ptr->name);
3587 len = write (ptr->fd, ptr->start, ptr->size);
3589 fatal_perror ("write %s", ptr->name);
3591 if (len != ptr->size)
3592 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3601 #endif /* OBJECT_FORMAT_ROSE */