* decl.c (grokdeclarator): Remove const and volatile from type after
[official-gcc.git] / gcc / collect2.c
blob169c3beda466713ae479536bdba9c53d445a18d1
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93-97, 1998 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)
13 any later version.
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. */
28 #include "config.h"
29 #include "system.h"
30 #include <signal.h>
31 #include <sys/stat.h>
33 #define COLLECT
35 #include "demangle.h"
36 #include "obstack.h"
37 #include "gansidecl.h"
39 #ifndef HAVE_STRERROR
40 extern char *sys_errlist[];
41 extern int sys_nerr;
42 #else
43 char *strerror();
44 #endif
46 /* Obstack allocation and deallocation routines. */
47 #define obstack_chunk_alloc xmalloc
48 #define obstack_chunk_free free
50 #ifdef USG
51 #define vfork fork
52 #endif
54 #ifndef WIFSIGNALED
55 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
56 #endif
57 #ifndef WTERMSIG
58 #define WTERMSIG(S) ((S) & 0x7f)
59 #endif
60 #ifndef WIFEXITED
61 #define WIFEXITED(S) (((S) & 0xff) == 0)
62 #endif
63 #ifndef WEXITSTATUS
64 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
65 #endif
67 extern char *choose_temp_base ();
69 /* On certain systems, we have code that works by scanning the object file
70 directly. But this code uses system-specific header files and library
71 functions, so turn it off in a cross-compiler. Likewise, the names of
72 the utilities are not correct for a cross-compiler; we have to hope that
73 cross-versions are in the proper directories. */
75 #ifdef CROSS_COMPILE
76 #undef SUNOS4_SHARED_LIBRARIES
77 #undef OBJECT_FORMAT_COFF
78 #undef OBJECT_FORMAT_ROSE
79 #undef MD_EXEC_PREFIX
80 #undef REAL_LD_FILE_NAME
81 #undef REAL_NM_FILE_NAME
82 #undef REAL_STRIP_FILE_NAME
83 #endif
85 /* If we cannot use a special method, use the ordinary one:
86 run nm to find what symbols are present.
87 In a cross-compiler, this means you need a cross nm,
88 but that is not quite as unpleasant as special headers. */
90 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
91 #define OBJECT_FORMAT_NONE
92 #endif
94 #ifdef OBJECT_FORMAT_COFF
96 #include <a.out.h>
97 #include <ar.h>
99 #ifdef UMAX
100 #include <sgs.h>
101 #endif
103 /* Many versions of ldfcn.h define these. */
104 #ifdef FREAD
105 #undef FREAD
106 #undef FWRITE
107 #endif
109 #include <ldfcn.h>
111 /* Some systems have an ISCOFF macro, but others do not. In some cases
112 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
113 that either do not have an ISCOFF macro in /usr/include or for those
114 where it is wrong. */
116 #ifndef MY_ISCOFF
117 #define MY_ISCOFF(X) ISCOFF (X)
118 #endif
120 #endif /* OBJECT_FORMAT_COFF */
122 #ifdef OBJECT_FORMAT_ROSE
124 #ifdef _OSF_SOURCE
125 #define USE_MMAP
126 #endif
128 #ifdef USE_MMAP
129 #include <sys/mman.h>
130 #endif
132 #include <unistd.h>
133 #include <mach_o_format.h>
134 #include <mach_o_header.h>
135 #include <mach_o_vals.h>
136 #include <mach_o_types.h>
138 #endif /* OBJECT_FORMAT_ROSE */
140 #ifdef OBJECT_FORMAT_NONE
142 /* Default flags to pass to nm. */
143 #ifndef NM_FLAGS
144 #define NM_FLAGS "-p"
145 #endif
147 #endif /* OBJECT_FORMAT_NONE */
149 /* Some systems use __main in a way incompatible with its use in gcc, in these
150 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
151 give the same symbol without quotes for an alternative entry point. You
152 must define both, or neither. */
153 #ifndef NAME__MAIN
154 #define NAME__MAIN "__main"
155 #define SYMBOL__MAIN __main
156 #endif
158 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
159 #define SCAN_LIBRARIES
160 #endif
162 #ifdef USE_COLLECT2
163 int do_collecting = 1;
164 #else
165 int do_collecting = 0;
166 #endif
168 /* Linked lists of constructor and destructor names. */
170 struct id
172 struct id *next;
173 int sequence;
174 char name[1];
177 struct head
179 struct id *first;
180 struct id *last;
181 int number;
184 /* Enumeration giving which pass this is for scanning the program file. */
186 enum pass {
187 PASS_FIRST, /* without constructors */
188 PASS_OBJ, /* individual objects */
189 PASS_LIB, /* looking for shared libraries */
190 PASS_SECOND /* with constructors linked in */
193 #ifndef NO_SYS_SIGLIST
194 #ifndef SYS_SIGLIST_DECLARED
195 extern char *sys_siglist[];
196 #endif
197 #endif
198 extern char *version_string;
200 int vflag; /* true if -v */
201 static int rflag; /* true if -r */
202 static int strip_flag; /* true if -s */
203 #ifdef COLLECT_EXPORT_LIST
204 static int export_flag; /* true if -bE */
205 #endif
207 int debug; /* true if -debug */
209 static int shared_obj; /* true if -shared */
211 static int temp_filename_length; /* Length of temp_filename */
212 static char *temp_filename; /* Base of temp filenames */
213 static char *c_file; /* <xxx>.c for constructor/destructor list. */
214 static char *o_file; /* <xxx>.o for constructor/destructor list. */
215 #ifdef COLLECT_EXPORT_LIST
216 static char *export_file; /* <xxx>.x for AIX export list. */
217 static char *import_file; /* <xxx>.p for AIX import list. */
218 #endif
219 char *ldout; /* File for ld errors. */
220 static char *output_file; /* Output file for ld. */
221 static char *nm_file_name; /* pathname of nm */
222 #ifdef LDD_SUFFIX
223 static char *ldd_file_name; /* pathname of ldd (or equivalent) */
224 #endif
225 static char *strip_file_name; /* pathname of strip */
226 char *c_file_name; /* pathname of gcc */
227 static char *initname, *fininame; /* names of init and fini funcs */
229 static struct head constructors; /* list of constructors found */
230 static struct head destructors; /* list of destructors found */
231 #ifdef COLLECT_EXPORT_LIST
232 static struct head exports; /* list of exported symbols */
233 static struct head imports; /* list of imported symbols */
234 static struct head undefined; /* list of undefined symbols */
235 #endif
236 static struct head frame_tables; /* list of frame unwind info tables */
238 struct obstack temporary_obstack;
239 struct obstack permanent_obstack;
240 char * temporary_firstobj;
242 /* Defined in the automatically-generated underscore.c. */
243 extern int prepends_underscore;
245 extern char *getenv ();
246 extern char *mktemp ();
247 extern FILE *fdopen ();
249 #ifndef GET_ENVIRONMENT
250 #define GET_ENVIRONMENT(ENV_VALUE,ENV_NAME) ENV_VALUE = getenv (ENV_NAME)
251 #endif
253 /* Structure to hold all the directories in which to search for files to
254 execute. */
256 struct prefix_list
258 char *prefix; /* String to prepend to the path. */
259 struct prefix_list *next; /* Next in linked list. */
262 struct path_prefix
264 struct prefix_list *plist; /* List of prefixes to try */
265 int max_len; /* Max length of a prefix in PLIST */
266 char *name; /* Name of this list (used in config stuff) */
269 #ifdef COLLECT_EXPORT_LIST
270 /* Lists to keep libraries to be scanned for global constructors/destructors. */
271 static struct head libs; /* list of libraries */
272 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
273 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
274 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
275 &libpath_lib_dirs, NULL};
276 static char *libexts[3] = {"a", "so", NULL}; /* possible library extentions */
277 #endif
279 void collect_exit PROTO((int));
280 void collect_execute PROTO((char *, char **, char *));
281 void dump_file PROTO((char *));
282 static void handler PROTO((int));
283 static int is_ctor_dtor PROTO((char *));
284 static int is_in_prefix_list PROTO((struct path_prefix *, char *, int));
285 static char *find_a_file PROTO((struct path_prefix *, char *));
286 static void add_prefix PROTO((struct path_prefix *, char *));
287 static void prefix_from_env PROTO((char *, struct path_prefix *));
288 static void prefix_from_string PROTO((char *, struct path_prefix *));
289 static void do_wait PROTO((char *));
290 static void fork_execute PROTO((char *, char **));
291 static void maybe_unlink PROTO((char *));
292 static void add_to_list PROTO((struct head *, char *));
293 static void write_list PROTO((FILE *, char *, struct id *));
294 static void dump_list PROTO((FILE *, char *, struct id *));
295 static void dump_prefix_list PROTO((FILE *, char *, struct prefix_list *));
296 static int is_in_list PROTO((char *, struct id *));
297 static void write_list_with_asm PROTO((FILE *, char *, struct id *));
298 static void write_c_file PROTO((FILE *, char *));
299 static void scan_prog_file PROTO((char *, enum pass));
300 #ifdef SCAN_LIBRARIES
301 static void scan_libraries PROTO((char *));
302 #endif
303 #ifdef COLLECT_EXPORT_LIST
304 static void write_export_file PROTO((FILE *));
305 static void write_import_file PROTO((FILE *));
306 static char *resolve_lib_name PROTO((char *));
307 static int use_import_list PROTO((char *));
308 static int ignore_library PROTO((char *));
309 #endif
311 char *xcalloc ();
312 char *xmalloc ();
315 #ifdef NO_DUP2
317 dup2 (oldfd, newfd)
318 int oldfd;
319 int newfd;
321 int fdtmp[256];
322 int fdx = 0;
323 int fd;
325 if (oldfd == newfd)
326 return oldfd;
327 close (newfd);
328 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
329 fdtmp[fdx++] = fd;
330 while (fdx > 0)
331 close (fdtmp[--fdx]);
333 return fd;
335 #endif
337 char *
338 my_strerror (e)
339 int e;
342 #ifdef HAVE_STRERROR
343 return strerror (e);
345 #else
347 static char buffer[30];
348 if (!e)
349 return "";
351 if (e > 0 && e < sys_nerr)
352 return sys_errlist[e];
354 sprintf (buffer, "Unknown error %d", e);
355 return buffer;
356 #endif
359 /* Delete tempfiles and exit function. */
361 void
362 collect_exit (status)
363 int status;
365 if (c_file != 0 && c_file[0])
366 maybe_unlink (c_file);
368 if (o_file != 0 && o_file[0])
369 maybe_unlink (o_file);
371 #ifdef COLLECT_EXPORT_LIST
372 if (export_file != 0 && export_file[0])
373 maybe_unlink (export_file);
375 if (import_file != 0 && import_file[0])
376 maybe_unlink (import_file);
377 #endif
379 if (ldout != 0 && ldout[0])
381 dump_file (ldout);
382 maybe_unlink (ldout);
385 if (status != 0 && output_file != 0 && output_file[0])
386 maybe_unlink (output_file);
388 exit (status);
392 /* Die when sys call fails. */
394 void
395 fatal_perror (string, arg1, arg2, arg3)
396 char *string, *arg1, *arg2, *arg3;
398 int e = errno;
400 fprintf (stderr, "collect2: ");
401 fprintf (stderr, string, arg1, arg2, arg3);
402 fprintf (stderr, ": %s\n", my_strerror (e));
403 collect_exit (FATAL_EXIT_CODE);
406 /* Just die. */
408 void
409 fatal (string, arg1, arg2, arg3)
410 char *string, *arg1, *arg2, *arg3;
412 fprintf (stderr, "collect2: ");
413 fprintf (stderr, string, arg1, arg2, arg3);
414 fprintf (stderr, "\n");
415 collect_exit (FATAL_EXIT_CODE);
418 /* Write error message. */
420 void
421 error (string, arg1, arg2, arg3, arg4)
422 char *string, *arg1, *arg2, *arg3, *arg4;
424 fprintf (stderr, "collect2: ");
425 fprintf (stderr, string, arg1, arg2, arg3, arg4);
426 fprintf (stderr, "\n");
429 /* In case obstack is linked in, and abort is defined to fancy_abort,
430 provide a default entry. */
432 void
433 fancy_abort ()
435 fatal ("internal error");
439 static void
440 handler (signo)
441 int signo;
443 if (c_file != 0 && c_file[0])
444 maybe_unlink (c_file);
446 if (o_file != 0 && o_file[0])
447 maybe_unlink (o_file);
449 if (ldout != 0 && ldout[0])
450 maybe_unlink (ldout);
452 #ifdef COLLECT_EXPORT_LIST
453 if (export_file != 0 && export_file[0])
454 maybe_unlink (export_file);
456 if (import_file != 0 && import_file[0])
457 maybe_unlink (import_file);
458 #endif
460 signal (signo, SIG_DFL);
461 kill (getpid (), signo);
465 char *
466 xcalloc (size1, size2)
467 int size1, size2;
469 char *ptr = (char *) calloc (size1, size2);
470 if (ptr)
471 return ptr;
473 fatal ("out of memory");
474 return (char *) 0;
477 char *
478 xmalloc (size)
479 unsigned size;
481 char *ptr = (char *) malloc (size);
482 if (ptr)
483 return ptr;
485 fatal ("out of memory");
486 return (char *) 0;
489 char *
490 xrealloc (ptr, size)
491 char *ptr;
492 unsigned size;
494 register char *value = (char *) realloc (ptr, size);
495 if (value == 0)
496 fatal ("virtual memory exhausted");
497 return value;
501 file_exists (name)
502 char *name;
504 return access (name, R_OK) == 0;
507 /* Make a copy of a string INPUT with size SIZE. */
509 char *
510 savestring (input, size)
511 char *input;
512 int size;
514 char *output = (char *) xmalloc (size + 1);
515 bcopy (input, output, size);
516 output[size] = 0;
517 return output;
520 /* Parse a reasonable subset of shell quoting syntax. */
522 static char *
523 extract_string (pp)
524 char **pp;
526 char *p = *pp;
527 int backquote = 0;
528 int inside = 0;
530 for (;;)
532 char c = *p;
533 if (c == '\0')
534 break;
535 ++p;
536 if (backquote)
537 obstack_1grow (&temporary_obstack, c);
538 else if (! inside && c == ' ')
539 break;
540 else if (! inside && c == '\\')
541 backquote = 1;
542 else if (c == '\'')
543 inside = !inside;
544 else
545 obstack_1grow (&temporary_obstack, c);
548 obstack_1grow (&temporary_obstack, '\0');
549 *pp = p;
550 return obstack_finish (&temporary_obstack);
553 void
554 dump_file (name)
555 char *name;
557 FILE *stream = fopen (name, "r");
558 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
560 if (stream == 0)
561 return;
562 while (1)
564 int c;
565 while (c = getc (stream),
566 c != EOF && (isalnum (c) || c == '_' || c == '$' || c == '.'))
567 obstack_1grow (&temporary_obstack, c);
568 if (obstack_object_size (&temporary_obstack) > 0)
570 char *word, *p, *result;
571 obstack_1grow (&temporary_obstack, '\0');
572 word = obstack_finish (&temporary_obstack);
574 if (*word == '.')
575 ++word, putc ('.', stderr);
576 p = word;
577 if (*p == '_' && prepends_underscore)
578 ++p;
580 if (no_demangle)
581 result = 0;
582 else
583 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
585 if (result)
587 int diff;
588 fputs (result, stderr);
590 diff = strlen (word) - strlen (result);
591 while (diff > 0)
592 --diff, putc (' ', stderr);
593 while (diff < 0 && c == ' ')
594 ++diff, c = getc (stream);
596 free (result);
598 else
599 fputs (word, stderr);
601 fflush (stderr);
602 obstack_free (&temporary_obstack, temporary_firstobj);
604 if (c == EOF)
605 break;
606 putc (c, stderr);
608 fclose (stream);
611 /* Decide whether the given symbol is:
612 a constructor (1), a destructor (2), or neither (0). */
614 static int
615 is_ctor_dtor (s)
616 char *s;
618 struct names { char *name; int len; int ret; int two_underscores; };
620 register struct names *p;
621 register int ch;
622 register char *orig_s = s;
624 static struct names special[] = {
625 #ifdef NO_DOLLAR_IN_LABEL
626 #ifdef NO_DOT_IN_LABEL
627 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
628 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
629 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
630 #else
631 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
632 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
633 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
634 #endif
635 #else
636 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
637 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
638 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
639 #endif
640 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
641 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
642 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
643 cfront has its own linker procedure to collect them;
644 if collect2 gets them too, they get collected twice
645 when the cfront procedure is run and the compiler used
646 for linking happens to be GCC. */
647 { "sti__", sizeof ("sti__")-1, 1, 1 },
648 { "std__", sizeof ("std__")-1, 2, 1 },
649 #endif /* CFRONT_LOSSAGE */
650 { NULL, 0, 0, 0 }
653 while ((ch = *s) == '_')
654 ++s;
656 if (s == orig_s)
657 return 0;
659 for (p = &special[0]; p->len > 0; p++)
661 if (ch == p->name[0]
662 && (!p->two_underscores || ((s - orig_s) >= 2))
663 && strncmp(s, p->name, p->len) == 0)
665 return p->ret;
668 return 0;
671 /* Routine to add variables to the environment. */
673 #ifndef HAVE_PUTENV
676 putenv (str)
677 char *str;
679 #ifndef VMS /* nor about VMS */
681 extern char **environ;
682 char **old_environ = environ;
683 char **envp;
684 int num_envs = 0;
685 int name_len = 1;
686 char *p = str;
687 int ch;
689 while ((ch = *p++) != '\0' && ch != '=')
690 name_len++;
692 if (!ch)
693 abort ();
695 /* Search for replacing an existing environment variable, and
696 count the number of total environment variables. */
697 for (envp = old_environ; *envp; envp++)
699 num_envs++;
700 if (!strncmp (str, *envp, name_len))
702 *envp = str;
703 return 0;
707 /* Add a new environment variable */
708 environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
709 *environ = str;
710 bcopy ((char *) old_environ, (char *) (environ + 1),
711 sizeof (char *) * (num_envs+1));
713 return 0;
714 #endif /* VMS */
717 #endif /* HAVE_PUTENV */
719 /* By default, colon separates directories in a path. */
720 #ifndef PATH_SEPARATOR
721 #define PATH_SEPARATOR ':'
722 #endif
724 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
725 and one from the PATH variable. */
727 static struct path_prefix cpath, path;
729 #ifdef CROSS_COMPILE
730 /* This is the name of the target machine. We use it to form the name
731 of the files to execute. */
733 static char *target_machine = TARGET_MACHINE;
734 #endif
736 /* Names under which we were executed. Never return one of those files in our
737 searches. */
739 static struct path_prefix our_file_names;
741 /* Determine if STRING is in PPREFIX.
743 This utility is currently only used to look up file names. Prefix lists
744 record directory names. This matters to us because the latter has a
745 trailing slash, so I've added a flag to handle both. */
747 static int
748 is_in_prefix_list (pprefix, string, filep)
749 struct path_prefix *pprefix;
750 char *string;
751 int filep;
753 struct prefix_list *pl;
755 if (filep)
757 int len = strlen (string);
759 for (pl = pprefix->plist; pl; pl = pl->next)
761 if (strncmp (pl->prefix, string, len) == 0
762 && strcmp (pl->prefix + len, "/") == 0)
763 return 1;
766 else
768 for (pl = pprefix->plist; pl; pl = pl->next)
770 if (strcmp (pl->prefix, string) == 0)
771 return 1;
775 return 0;
778 /* Search for NAME using prefix list PPREFIX. We only look for executable
779 files.
781 Return 0 if not found, otherwise return its name, allocated with malloc. */
783 static char *
784 find_a_file (pprefix, name)
785 struct path_prefix *pprefix;
786 char *name;
788 char *temp;
789 struct prefix_list *pl;
790 int len = pprefix->max_len + strlen (name) + 1;
792 if (debug)
793 fprintf (stderr, "Looking for '%s'\n", name);
795 #ifdef EXECUTABLE_SUFFIX
796 len += strlen (EXECUTABLE_SUFFIX);
797 #endif
799 temp = xmalloc (len);
801 /* Determine the filename to execute (special case for absolute paths). */
803 if (*name == '/'
804 #ifdef DIR_SEPARATOR
805 || (DIR_SEPARATOR == '\\' && name[1] == ':'
806 && (name[2] == DIR_SEPARATOR || name[2] == '/'))
807 #endif
810 if (access (name, X_OK) == 0)
812 strcpy (temp, name);
814 if (debug)
815 fprintf (stderr, " - found: absolute path\n");
817 return temp;
820 if (debug)
821 fprintf (stderr, " - failed to locate using absolute path\n");
823 else
824 for (pl = pprefix->plist; pl; pl = pl->next)
826 strcpy (temp, pl->prefix);
827 strcat (temp, name);
829 if (debug)
830 fprintf (stderr, " - try: %s\n", temp);
832 if (! is_in_prefix_list (&our_file_names, temp, 1)
833 /* This is a kludge, but there seems no way around it. */
834 && strcmp (temp, "./ld") != 0
835 && access (temp, X_OK) == 0)
837 if (debug)
838 fprintf (stderr, " - found!\n");
840 return temp;
843 #ifdef EXECUTABLE_SUFFIX
844 /* Some systems have a suffix for executable files.
845 So try appending that. */
846 strcat (temp, EXECUTABLE_SUFFIX);
848 if (debug)
849 fprintf (stderr, " - try: %s\n", temp);
851 if (! is_in_prefix_list (&our_file_names, temp, 1)
852 && access (temp, X_OK) == 0)
854 if (debug)
855 fprintf (stderr, " - found! (Uses executable suffix)\n");
857 return temp;
859 #endif
860 if (debug && pl->next == NULL)
861 fprintf (stderr, " - failed to locate using relative paths\n");
864 if (debug && pprefix->plist == NULL)
865 fprintf (stderr, " - failed: no entries in prefix list\n");
867 free (temp);
868 return 0;
871 /* Add an entry for PREFIX to prefix list PPREFIX. */
873 static void
874 add_prefix (pprefix, prefix)
875 struct path_prefix *pprefix;
876 char *prefix;
878 struct prefix_list *pl, **prev;
879 int len;
881 if (pprefix->plist)
883 for (pl = pprefix->plist; pl->next; pl = pl->next)
885 prev = &pl->next;
887 else
888 prev = &pprefix->plist;
890 /* Keep track of the longest prefix */
892 len = strlen (prefix);
893 if (len > pprefix->max_len)
894 pprefix->max_len = len;
896 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
897 pl->prefix = savestring (prefix, len);
899 if (*prev)
900 pl->next = *prev;
901 else
902 pl->next = (struct prefix_list *) 0;
903 *prev = pl;
906 /* Take the value of the environment variable ENV, break it into a path, and
907 add of the entries to PPREFIX. */
909 static void
910 prefix_from_env (env, pprefix)
911 char *env;
912 struct path_prefix *pprefix;
914 char *p;
915 GET_ENVIRONMENT (p, env);
917 if (p)
918 prefix_from_string (p, pprefix);
921 static void
922 prefix_from_string (p, pprefix)
923 char *p;
924 struct path_prefix *pprefix;
926 char *startp, *endp;
927 char *nstore = (char *) xmalloc (strlen (p) + 3);
929 if (debug)
930 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
932 startp = endp = p;
933 while (1)
935 if (*endp == PATH_SEPARATOR || *endp == 0)
937 strncpy (nstore, startp, endp-startp);
938 if (endp == startp)
940 strcpy (nstore, "./");
942 else if (endp[-1] != '/')
944 nstore[endp-startp] = '/';
945 nstore[endp-startp+1] = 0;
947 else
948 nstore[endp-startp] = 0;
950 if (debug)
951 fprintf (stderr, " - add prefix: %s\n", nstore);
953 add_prefix (pprefix, nstore);
954 if (*endp == 0)
955 break;
956 endp = startp = endp + 1;
958 else
959 endp++;
963 /* Main program. */
966 main (argc, argv)
967 int argc;
968 char *argv[];
970 char *ld_suffix = "ld";
971 char *full_ld_suffix = ld_suffix;
972 char *real_ld_suffix = "real-ld";
973 char *collect_ld_suffix = "collect-ld";
974 char *nm_suffix = "nm";
975 char *full_nm_suffix = nm_suffix;
976 char *gnm_suffix = "gnm";
977 char *full_gnm_suffix = gnm_suffix;
978 #ifdef LDD_SUFFIX
979 char *ldd_suffix = LDD_SUFFIX;
980 char *full_ldd_suffix = ldd_suffix;
981 #endif
982 char *strip_suffix = "strip";
983 char *full_strip_suffix = strip_suffix;
984 char *gstrip_suffix = "gstrip";
985 char *full_gstrip_suffix = gstrip_suffix;
986 char *arg;
987 FILE *outf;
988 #ifdef COLLECT_EXPORT_LIST
989 FILE *exportf;
990 FILE *importf;
991 #endif
992 char *ld_file_name;
993 char *collect_name;
994 char *collect_names;
995 char *p;
996 char **c_argv;
997 char **c_ptr;
998 char **ld1_argv = (char **) xcalloc (sizeof (char *), argc+3);
999 char **ld1 = ld1_argv;
1000 char **ld2_argv = (char **) xcalloc (sizeof (char *), argc+6);
1001 char **ld2 = ld2_argv;
1002 char **object_lst = (char **) xcalloc (sizeof (char *), argc);
1003 char **object = object_lst;
1004 int first_file;
1005 int num_c_args = argc+7;
1007 #ifdef DEBUG
1008 debug = 1;
1009 #endif
1011 /* Parse command line early for instances of -debug. This allows
1012 the debug flag to be set before functions like find_a_file()
1013 are called. */
1015 int i;
1017 for (i = 1; argv[i] != NULL; i ++)
1018 if (! strcmp (argv[i], "-debug"))
1019 debug = 1;
1020 vflag = debug;
1023 #ifndef DEFAULT_A_OUT_NAME
1024 output_file = "a.out";
1025 #else
1026 output_file = DEFAULT_A_OUT_NAME;
1027 #endif
1029 obstack_begin (&temporary_obstack, 0);
1030 obstack_begin (&permanent_obstack, 0);
1031 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
1032 current_demangling_style = gnu_demangling;
1034 /* We must check that we do not call ourselves in an infinite
1035 recursion loop. We append the name used for us to the COLLECT_NAMES
1036 environment variable.
1038 In practice, collect will rarely invoke itself. This can happen now
1039 that we are no longer called gld. A perfect example is when running
1040 gcc in a build directory that has been installed. When looking for
1041 ld's, we will find our installed version and believe that's the real ld. */
1043 /* We must also append COLLECT_NAME to COLLECT_NAMES to watch for the
1044 previous version of collect (the one that used COLLECT_NAME and only
1045 handled two levels of recursion). If we do not we may mutually recurse
1046 forever. This can happen (I think) when bootstrapping the old version
1047 and a new one is installed (rare, but we should handle it).
1048 ??? Hopefully references to COLLECT_NAME can be removed at some point. */
1050 GET_ENVIRONMENT (collect_name, "COLLECT_NAME");
1051 GET_ENVIRONMENT (collect_names, "COLLECT_NAMES");
1053 p = (char *) xmalloc (strlen ("COLLECT_NAMES=")
1054 + (collect_name ? strlen (collect_name) + 1 : 0)
1055 + (collect_names ? strlen (collect_names) + 1 : 0)
1056 + strlen (argv[0]) + 1);
1057 strcpy (p, "COLLECT_NAMES=");
1058 if (collect_name != 0)
1059 sprintf (p + strlen (p), "%s%c", collect_name, PATH_SEPARATOR);
1060 if (collect_names != 0)
1061 sprintf (p + strlen (p), "%s%c", collect_names, PATH_SEPARATOR);
1062 strcat (p, argv[0]);
1063 putenv (p);
1065 prefix_from_env ("COLLECT_NAMES", &our_file_names);
1067 /* Set environment variable COLLECT_NAME to our name so the previous version
1068 of collect will not find us. If it does we will mutually recurse forever.
1069 This can happen when bootstrapping the new version and an old version is
1070 installed.
1071 ??? Hopefully this bit of code can be removed at some point. */
1073 p = xmalloc (strlen ("COLLECT_NAME=") + strlen (argv[0]) + 1);
1074 sprintf (p, "COLLECT_NAME=%s", argv[0]);
1075 putenv (p);
1077 p = getenv ("COLLECT_GCC_OPTIONS");
1078 while (p && *p)
1080 char *q = extract_string (&p);
1081 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1082 num_c_args++;
1084 obstack_free (&temporary_obstack, temporary_firstobj);
1085 ++num_c_args;
1087 c_ptr = c_argv = (char **) xcalloc (sizeof (char *), num_c_args);
1089 if (argc < 2)
1090 fatal ("no arguments");
1092 #ifdef SIGQUIT
1093 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1094 signal (SIGQUIT, handler);
1095 #endif
1096 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1097 signal (SIGINT, handler);
1098 #ifdef SIGALRM
1099 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1100 signal (SIGALRM, handler);
1101 #endif
1102 #ifdef SIGHUP
1103 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1104 signal (SIGHUP, handler);
1105 #endif
1106 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1107 signal (SIGSEGV, handler);
1108 #ifdef SIGBUS
1109 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1110 signal (SIGBUS, handler);
1111 #endif
1113 /* Extract COMPILER_PATH and PATH into our prefix list. */
1114 prefix_from_env ("COMPILER_PATH", &cpath);
1115 prefix_from_env ("PATH", &path);
1117 #ifdef CROSS_COMPILE
1118 /* If we look for a program in the compiler directories, we just use
1119 the short name, since these directories are already system-specific.
1120 But it we look for a program in the system directories, we need to
1121 qualify the program name with the target machine. */
1123 full_ld_suffix
1124 = xcalloc (strlen (ld_suffix) + strlen (target_machine) + 2, 1);
1125 strcpy (full_ld_suffix, target_machine);
1126 strcat (full_ld_suffix, "-");
1127 strcat (full_ld_suffix, ld_suffix);
1129 #if 0
1130 full_gld_suffix
1131 = xcalloc (strlen (gld_suffix) + strlen (target_machine) + 2, 1);
1132 strcpy (full_gld_suffix, target_machine);
1133 strcat (full_gld_suffix, "-");
1134 strcat (full_gld_suffix, gld_suffix);
1135 #endif
1137 full_nm_suffix
1138 = xcalloc (strlen (nm_suffix) + strlen (target_machine) + 2, 1);
1139 strcpy (full_nm_suffix, target_machine);
1140 strcat (full_nm_suffix, "-");
1141 strcat (full_nm_suffix, nm_suffix);
1143 full_gnm_suffix
1144 = xcalloc (strlen (gnm_suffix) + strlen (target_machine) + 2, 1);
1145 strcpy (full_gnm_suffix, target_machine);
1146 strcat (full_gnm_suffix, "-");
1147 strcat (full_gnm_suffix, gnm_suffix);
1149 #ifdef LDD_SUFFIX
1150 full_ldd_suffix
1151 = xcalloc (strlen (ldd_suffix) + strlen (target_machine) + 2, 1);
1152 strcpy (full_ldd_suffix, target_machine);
1153 strcat (full_ldd_suffix, "-");
1154 strcat (full_ldd_suffix, ldd_suffix);
1155 #endif
1157 full_strip_suffix
1158 = xcalloc (strlen (strip_suffix) + strlen (target_machine) + 2, 1);
1159 strcpy (full_strip_suffix, target_machine);
1160 strcat (full_strip_suffix, "-");
1161 strcat (full_strip_suffix, strip_suffix);
1163 full_gstrip_suffix
1164 = xcalloc (strlen (gstrip_suffix) + strlen (target_machine) + 2, 1);
1165 strcpy (full_gstrip_suffix, target_machine);
1166 strcat (full_gstrip_suffix, "-");
1167 strcat (full_gstrip_suffix, gstrip_suffix);
1168 #endif /* CROSS_COMPILE */
1170 /* Try to discover a valid linker/nm/strip to use. */
1172 /* Maybe we know the right file to use (if not cross). */
1173 #ifdef REAL_LD_FILE_NAME
1174 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1175 if (ld_file_name == 0)
1176 #endif
1177 /* Search the (target-specific) compiler dirs for ld'. */
1178 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1179 /* Likewise for `collect-ld'. */
1180 if (ld_file_name == 0)
1181 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1182 /* Search the compiler directories for `ld'. We have protection against
1183 recursive calls in find_a_file. */
1184 if (ld_file_name == 0)
1185 ld_file_name = find_a_file (&cpath, ld_suffix);
1186 /* Search the ordinary system bin directories
1187 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1188 if (ld_file_name == 0)
1189 ld_file_name = find_a_file (&path, full_ld_suffix);
1191 /* If we've invoked ourselves, try again with LD_FILE_NAME. */
1193 if (collect_names != 0)
1195 if (ld_file_name != 0)
1197 argv[0] = ld_file_name;
1198 execvp (argv[0], argv);
1200 fatal ("cannot find `ld' (%s)", ld_file_name);
1203 #ifdef REAL_NM_FILE_NAME
1204 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1205 if (nm_file_name == 0)
1206 #endif
1207 nm_file_name = find_a_file (&cpath, gnm_suffix);
1208 if (nm_file_name == 0)
1209 nm_file_name = find_a_file (&path, full_gnm_suffix);
1210 if (nm_file_name == 0)
1211 nm_file_name = find_a_file (&cpath, nm_suffix);
1212 if (nm_file_name == 0)
1213 nm_file_name = find_a_file (&path, full_nm_suffix);
1215 #ifdef LDD_SUFFIX
1216 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1217 if (ldd_file_name == 0)
1218 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1219 #endif
1221 #ifdef REAL_STRIP_FILE_NAME
1222 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1223 if (strip_file_name == 0)
1224 #endif
1225 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1226 if (strip_file_name == 0)
1227 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1228 if (strip_file_name == 0)
1229 strip_file_name = find_a_file (&cpath, strip_suffix);
1230 if (strip_file_name == 0)
1231 strip_file_name = find_a_file (&path, full_strip_suffix);
1233 /* Determine the full path name of the C compiler to use. */
1234 c_file_name = getenv ("COLLECT_GCC");
1235 if (c_file_name == 0)
1237 #ifdef CROSS_COMPILE
1238 c_file_name = xcalloc (sizeof ("gcc-") + strlen (target_machine) + 1, 1);
1239 strcpy (c_file_name, target_machine);
1240 strcat (c_file_name, "-gcc");
1241 #else
1242 c_file_name = "gcc";
1243 #endif
1246 p = find_a_file (&cpath, c_file_name);
1248 /* Here it should be safe to use the system search path since we should have
1249 already qualified the name of the compiler when it is needed. */
1250 if (p == 0)
1251 p = find_a_file (&path, c_file_name);
1253 if (p)
1254 c_file_name = p;
1256 *ld1++ = *ld2++ = ld_file_name;
1258 /* Make temp file names. */
1259 temp_filename = choose_temp_base ();
1260 temp_filename_length = strlen (temp_filename);
1261 c_file = xcalloc (temp_filename_length + sizeof (".c"), 1);
1262 o_file = xcalloc (temp_filename_length + sizeof (".o"), 1);
1263 #ifdef COLLECT_EXPORT_LIST
1264 export_file = xmalloc (temp_filename_length + sizeof (".x"));
1265 import_file = xmalloc (temp_filename_length + sizeof (".p"));
1266 #endif
1267 ldout = xmalloc (temp_filename_length + sizeof (".ld"));
1268 sprintf (ldout, "%s.ld", temp_filename);
1269 sprintf (c_file, "%s.c", temp_filename);
1270 sprintf (o_file, "%s.o", temp_filename);
1271 #ifdef COLLECT_EXPORT_LIST
1272 sprintf (export_file, "%s.x", temp_filename);
1273 sprintf (import_file, "%s.p", temp_filename);
1274 #endif
1275 *c_ptr++ = c_file_name;
1276 *c_ptr++ = "-c";
1277 *c_ptr++ = "-o";
1278 *c_ptr++ = o_file;
1280 #ifdef COLLECT_EXPORT_LIST
1281 /* Generate a list of directories from LIBPATH. */
1282 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1283 /* Add to this list also two standard directories where
1284 AIX loader always searches for libraries. */
1285 add_prefix (&libpath_lib_dirs, "/lib");
1286 add_prefix (&libpath_lib_dirs, "/usr/lib");
1287 #endif
1289 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1291 AIX support needs to know if -shared has been specified before
1292 parsing commandline arguments. */
1294 p = getenv ("COLLECT_GCC_OPTIONS");
1295 while (p && *p)
1297 char *q = extract_string (&p);
1298 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1299 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1300 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1301 shared_obj = 1;
1303 obstack_free (&temporary_obstack, temporary_firstobj);
1304 *c_ptr++ = "-fno-exceptions";
1306 /* !!! When GCC calls collect2,
1307 it does not know whether it is calling collect2 or ld.
1308 So collect2 cannot meaningfully understand any options
1309 except those ld understands.
1310 If you propose to make GCC pass some other option,
1311 just imagine what will happen if ld is really ld!!! */
1313 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1314 /* After the first file, put in the c++ rt0. */
1316 first_file = 1;
1317 while ((arg = *++argv) != (char *) 0)
1319 *ld1++ = *ld2++ = arg;
1321 if (arg[0] == '-')
1323 switch (arg[1])
1325 #ifdef COLLECT_EXPORT_LIST
1326 /* We want to disable automatic exports on AIX when user
1327 explicitly puts an export list in command line */
1328 case 'b':
1329 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1330 export_flag = 1;
1331 break;
1332 #endif
1334 case 'd':
1335 if (!strcmp (arg, "-debug"))
1337 /* Already parsed. */
1338 ld1--;
1339 ld2--;
1341 break;
1343 case 'l':
1344 if (first_file)
1346 /* place o_file BEFORE this argument! */
1347 first_file = 0;
1348 ld2--;
1349 *ld2++ = o_file;
1350 *ld2++ = arg;
1352 #ifdef COLLECT_EXPORT_LIST
1354 /* Resolving full library name. */
1355 char *s = resolve_lib_name (arg+2);
1357 /* If we will use an import list for this library,
1358 we should exclude it from ld args. */
1359 if (use_import_list (s))
1361 ld1--;
1362 ld2--;
1365 /* Saving a full library name. */
1366 add_to_list (&libs, s);
1368 #endif
1369 break;
1371 #ifdef COLLECT_EXPORT_LIST
1372 /* Saving directories where to search for libraries. */
1373 case 'L':
1374 add_prefix (&cmdline_lib_dirs, arg+2);
1375 break;
1376 #endif
1378 case 'o':
1379 if (arg[2] == '\0')
1380 output_file = *ld1++ = *ld2++ = *++argv;
1381 else
1382 output_file = &arg[2];
1383 break;
1385 case 'r':
1386 if (arg[2] == '\0')
1387 rflag = 1;
1388 break;
1390 case 's':
1391 if (arg[2] == '\0' && do_collecting)
1393 /* We must strip after the nm run, otherwise C++ linking
1394 will not work. Thus we strip in the second ld run, or
1395 else with strip if there is no second ld run. */
1396 strip_flag = 1;
1397 ld1--;
1399 break;
1401 case 'v':
1402 if (arg[2] == '\0')
1403 vflag = 1;
1404 break;
1407 else if ((p = rindex (arg, '.')) != (char *) 0
1408 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1409 || strcmp (p, ".so") == 0))
1411 if (first_file)
1413 first_file = 0;
1414 if (p[1] == 'o')
1415 *ld2++ = o_file;
1416 else
1418 /* place o_file BEFORE this argument! */
1419 ld2--;
1420 *ld2++ = o_file;
1421 *ld2++ = arg;
1424 if (p[1] == 'o')
1425 *object++ = arg;
1426 #ifdef COLLECT_EXPORT_LIST
1427 /* libraries can be specified directly, i.e. without -l flag. */
1428 else
1430 /* If we will use an import list for this library,
1431 we should exclude it from ld args. */
1432 if (use_import_list (arg))
1434 ld1--;
1435 ld2--;
1438 /* Saving a full library name. */
1439 add_to_list (&libs, arg);
1441 #endif
1445 #ifdef COLLECT_EXPORT_LIST
1446 /* This is added only for debugging purposes. */
1447 if (debug)
1449 fprintf (stderr, "List of libraries:\n");
1450 dump_list (stderr, "\t", libs.first);
1453 /* The AIX linker will discard static constructors in object files if
1454 nothing else in the file is referenced, so look at them first. */
1456 char **export_object_lst = object_lst;
1457 while (export_object_lst < object)
1458 scan_prog_file (*export_object_lst++, PASS_OBJ);
1461 struct id *list = libs.first;
1462 for (; list; list = list->next)
1463 scan_prog_file (list->name, PASS_FIRST);
1466 char *buf1 = alloca (strlen (export_file) + 5);
1467 char *buf2 = alloca (strlen (import_file) + 5);
1468 sprintf (buf1, "-bE:%s", export_file);
1469 sprintf (buf2, "-bI:%s", import_file);
1470 *ld1++ = buf1;
1471 *ld2++ = buf1;
1472 *ld1++ = buf2;
1473 *ld2++ = buf2;
1474 exportf = fopen (export_file, "w");
1475 if (exportf == (FILE *) 0)
1476 fatal_perror ("%s", export_file);
1477 write_export_file (exportf);
1478 if (fclose (exportf))
1479 fatal_perror ("closing %s", export_file);
1480 importf = fopen (import_file, "w");
1481 if (importf == (FILE *) 0)
1482 fatal_perror ("%s", import_file);
1483 write_import_file (importf);
1484 if (fclose (importf))
1485 fatal_perror ("closing %s", import_file);
1487 #endif
1489 *c_ptr++ = c_file;
1490 *object = *c_ptr = *ld1 = (char *) 0;
1492 if (vflag)
1494 fprintf (stderr, "collect2 version %s", version_string);
1495 #ifdef TARGET_VERSION
1496 TARGET_VERSION;
1497 #endif
1498 fprintf (stderr, "\n");
1501 if (debug)
1503 char *ptr;
1504 fprintf (stderr, "ld_file_name = %s\n",
1505 (ld_file_name ? ld_file_name : "not found"));
1506 fprintf (stderr, "c_file_name = %s\n",
1507 (c_file_name ? c_file_name : "not found"));
1508 fprintf (stderr, "nm_file_name = %s\n",
1509 (nm_file_name ? nm_file_name : "not found"));
1510 #ifdef LDD_SUFFIX
1511 fprintf (stderr, "ldd_file_name = %s\n",
1512 (ldd_file_name ? ldd_file_name : "not found"));
1513 #endif
1514 fprintf (stderr, "strip_file_name = %s\n",
1515 (strip_file_name ? strip_file_name : "not found"));
1516 fprintf (stderr, "c_file = %s\n",
1517 (c_file ? c_file : "not found"));
1518 fprintf (stderr, "o_file = %s\n",
1519 (o_file ? o_file : "not found"));
1521 ptr = getenv ("COLLECT_NAMES");
1522 if (ptr)
1523 fprintf (stderr, "COLLECT_NAMES = %s\n", ptr);
1525 ptr = getenv ("COLLECT_GCC_OPTIONS");
1526 if (ptr)
1527 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1529 ptr = getenv ("COLLECT_GCC");
1530 if (ptr)
1531 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1533 ptr = getenv ("COMPILER_PATH");
1534 if (ptr)
1535 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1537 ptr = getenv ("LIBRARY_PATH");
1538 if (ptr)
1539 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1541 fprintf (stderr, "\n");
1544 /* Load the program, searching all libraries and attempting to provide
1545 undefined symbols from repository information. */
1547 /* On AIX we do this later. */
1548 #ifndef COLLECT_EXPORT_LIST
1549 do_tlink (ld1_argv, object_lst);
1550 #endif
1552 /* If -r or they will be run via some other method, do not build the
1553 constructor or destructor list, just return now. */
1554 if (rflag || ! do_collecting)
1556 #ifdef COLLECT_EXPORT_LIST
1557 /* But make sure we delete the export file we may have created. */
1558 if (export_file != 0 && export_file[0])
1559 maybe_unlink (export_file);
1560 if (import_file != 0 && import_file[0])
1561 maybe_unlink (import_file);
1562 #endif
1563 return 0;
1566 /* Examine the namelist with nm and search it for static constructors
1567 and destructors to call.
1568 Write the constructor and destructor tables to a .s file and reload. */
1570 /* On AIX we already done scanning for global constructors/destructors. */
1571 #ifndef COLLECT_EXPORT_LIST
1572 scan_prog_file (output_file, PASS_FIRST);
1573 #endif
1575 #ifdef SCAN_LIBRARIES
1576 scan_libraries (output_file);
1577 #endif
1579 if (debug)
1581 fprintf (stderr, "%d constructor(s) found\n", constructors.number);
1582 fprintf (stderr, "%d destructor(s) found\n", destructors.number);
1585 if (constructors.number == 0 && destructors.number == 0
1586 && frame_tables.number == 0
1587 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1588 /* If we will be running these functions ourselves, we want to emit
1589 stubs into the shared library so that we do not have to relink
1590 dependent programs when we add static objects. */
1591 && ! shared_obj
1592 #endif
1595 #ifdef COLLECT_EXPORT_LIST
1596 /* Doing tlink without additional code generation */
1597 do_tlink (ld1_argv, object_lst);
1598 #endif
1599 /* Strip now if it was requested on the command line. */
1600 if (strip_flag)
1602 char **strip_argv = (char **) xcalloc (sizeof (char *), 3);
1603 strip_argv[0] = strip_file_name;
1604 strip_argv[1] = output_file;
1605 strip_argv[2] = (char *) 0;
1606 fork_execute ("strip", strip_argv);
1609 #ifdef COLLECT_EXPORT_LIST
1610 maybe_unlink (export_file);
1611 maybe_unlink (import_file);
1612 #endif
1613 return 0;
1616 maybe_unlink(output_file);
1617 outf = fopen (c_file, "w");
1618 if (outf == (FILE *) 0)
1619 fatal_perror ("%s", c_file);
1621 write_c_file (outf, c_file);
1623 if (fclose (outf))
1624 fatal_perror ("closing %s", c_file);
1626 /* Tell the linker that we have initializer and finalizer functions. */
1627 #ifdef LD_INIT_SWITCH
1628 *ld2++ = LD_INIT_SWITCH;
1629 *ld2++ = initname;
1630 *ld2++ = LD_FINI_SWITCH;
1631 *ld2++ = fininame;
1632 #endif
1633 *ld2 = (char*) 0;
1635 #ifdef COLLECT_EXPORT_LIST
1636 if (shared_obj)
1638 add_to_list (&exports, initname);
1639 add_to_list (&exports, fininame);
1640 add_to_list (&exports, "_GLOBAL__DI");
1641 add_to_list (&exports, "_GLOBAL__DD");
1642 exportf = fopen (export_file, "w");
1643 if (exportf == (FILE *) 0)
1644 fatal_perror ("%s", export_file);
1645 write_export_file (exportf);
1646 if (fclose (exportf))
1647 fatal_perror ("closing %s", export_file);
1649 #endif
1651 if (debug)
1653 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1654 output_file, c_file);
1655 write_c_file (stderr, "stderr");
1656 fprintf (stderr, "========== end of c_file\n\n");
1657 #ifdef COLLECT_EXPORT_LIST
1658 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1659 write_export_file (stderr);
1660 fprintf (stderr, "========== end of export_file\n\n");
1661 #endif
1664 /* Assemble the constructor and destructor tables.
1665 Link the tables in with the rest of the program. */
1667 fork_execute ("gcc", c_argv);
1668 #ifdef COLLECT_EXPORT_LIST
1669 /* On AIX we must call tlink because of possible templates resolution */
1670 do_tlink (ld2_argv, object_lst);
1671 #else
1672 /* Otherwise, simply call ld because tlink is already done */
1673 fork_execute ("ld", ld2_argv);
1675 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1676 constructors/destructors in shared libraries. */
1677 scan_prog_file (output_file, PASS_SECOND);
1678 #endif
1680 maybe_unlink (c_file);
1681 maybe_unlink (o_file);
1683 #ifdef COLLECT_EXPORT_LIST
1684 maybe_unlink (export_file);
1685 maybe_unlink (import_file);
1686 #endif
1688 return 0;
1692 /* Wait for a process to finish, and exit if a non-zero status is found. */
1695 collect_wait (prog)
1696 char *prog;
1698 int status;
1700 wait (&status);
1701 if (status)
1703 if (WIFSIGNALED (status))
1705 int sig = WTERMSIG (status);
1706 #ifdef NO_SYS_SIGLIST
1707 error ("%s terminated with signal %d %s",
1708 prog,
1709 sig,
1710 (status & 0200) ? ", core dumped" : "");
1711 #else
1712 error ("%s terminated with signal %d [%s]%s",
1713 prog,
1714 sig,
1715 sys_siglist[sig],
1716 (status & 0200) ? ", core dumped" : "");
1717 #endif
1719 collect_exit (FATAL_EXIT_CODE);
1722 if (WIFEXITED (status))
1723 return WEXITSTATUS (status);
1725 return 0;
1728 static void
1729 do_wait (prog)
1730 char *prog;
1732 int ret = collect_wait (prog);
1733 if (ret != 0)
1735 error ("%s returned %d exit status", prog, ret);
1736 collect_exit (ret);
1741 /* Fork and execute a program, and wait for the reply. */
1743 void
1744 collect_execute (prog, argv, redir)
1745 char *prog;
1746 char **argv;
1747 char *redir;
1749 int pid;
1751 if (vflag || debug)
1753 char **p_argv;
1754 char *str;
1756 if (argv[0])
1757 fprintf (stderr, "%s", argv[0]);
1758 else
1759 fprintf (stderr, "[cannot find %s]", prog);
1761 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1762 fprintf (stderr, " %s", str);
1764 fprintf (stderr, "\n");
1767 fflush (stdout);
1768 fflush (stderr);
1770 /* If we cannot find a program we need, complain error. Do this here
1771 since we might not end up needing something that we could not find. */
1773 if (argv[0] == 0)
1774 fatal ("cannot find `%s'", prog);
1776 pid = vfork ();
1777 if (pid == -1)
1779 #ifdef vfork
1780 fatal_perror ("fork");
1781 #else
1782 fatal_perror ("vfork");
1783 #endif
1786 if (pid == 0) /* child context */
1788 if (redir)
1790 unlink (redir);
1791 if (freopen (redir, "a", stdout) == NULL)
1792 fatal_perror ("redirecting stdout: %s", redir);
1793 if (freopen (redir, "a", stderr) == NULL)
1794 fatal_perror ("redirecting stderr: %s", redir);
1797 execvp (argv[0], argv);
1798 fatal_perror ("executing %s", prog);
1802 static void
1803 fork_execute (prog, argv)
1804 char *prog;
1805 char **argv;
1807 collect_execute (prog, argv, NULL);
1808 do_wait (prog);
1811 /* Unlink a file unless we are debugging. */
1813 static void
1814 maybe_unlink (file)
1815 char *file;
1817 if (!debug)
1818 unlink (file);
1819 else
1820 fprintf (stderr, "[Leaving %s]\n", file);
1824 /* Add a name to a linked list. */
1826 static void
1827 add_to_list (head_ptr, name)
1828 struct head *head_ptr;
1829 char *name;
1831 struct id *newid
1832 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1833 struct id *p;
1834 static long sequence_number = 0;
1835 strcpy (newid->name, name);
1837 if (head_ptr->first)
1838 head_ptr->last->next = newid;
1839 else
1840 head_ptr->first = newid;
1842 /* Check for duplicate symbols. */
1843 for (p = head_ptr->first;
1844 strcmp (name, p->name) != 0;
1845 p = p->next)
1847 if (p != newid)
1849 head_ptr->last->next = 0;
1850 free (newid);
1851 return;
1854 newid->sequence = ++sequence_number;
1855 head_ptr->last = newid;
1856 head_ptr->number++;
1859 /* Write: `prefix', the names on list LIST, `suffix'. */
1861 static void
1862 write_list (stream, prefix, list)
1863 FILE *stream;
1864 char *prefix;
1865 struct id *list;
1867 while (list)
1869 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1870 list = list->next;
1874 /* This function is really used only on AIX, but may be useful. */
1875 static int
1876 is_in_list (prefix, list)
1877 char *prefix;
1878 struct id *list;
1880 while (list)
1882 if (!strcmp (prefix, list->name)) return 1;
1883 list = list->next;
1885 return 0;
1888 /* Added for debugging purpose. */
1889 static void
1890 dump_list (stream, prefix, list)
1891 FILE *stream;
1892 char *prefix;
1893 struct id *list;
1895 while (list)
1897 fprintf (stream, "%s%s,\n", prefix, list->name);
1898 list = list->next;
1902 static void
1903 dump_prefix_list (stream, prefix, list)
1904 FILE *stream;
1905 char *prefix;
1906 struct prefix_list *list;
1908 while (list)
1910 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1911 list = list->next;
1915 static void
1916 write_list_with_asm (stream, prefix, list)
1917 FILE *stream;
1918 char *prefix;
1919 struct id *list;
1921 while (list)
1923 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1924 prefix, list->sequence, list->name);
1925 list = list->next;
1929 /* Write out the constructor and destructor tables statically (for a shared
1930 object), along with the functions to execute them. */
1932 static void
1933 write_c_file_stat (stream, name)
1934 FILE *stream;
1935 char *name;
1937 char *prefix, *p, *q;
1938 int frames = (frame_tables.number > 0);
1940 /* Figure out name of output_file, stripping off .so version. */
1941 p = rindex (output_file, '/');
1942 if (p == 0)
1943 p = (char *) output_file;
1944 else
1945 p++;
1946 q = p;
1947 while (q)
1949 q = index (q,'.');
1950 if (q == 0)
1952 q = p + strlen (p);
1953 break;
1955 else
1957 if (strncmp (q, ".so", 3) == 0)
1959 q += 3;
1960 break;
1962 else
1963 q++;
1966 /* q points to null at end of the string (or . of the .so version) */
1967 prefix = xmalloc (q - p + 1);
1968 strncpy (prefix, p, q - p);
1969 prefix[q - p] = 0;
1970 for (q = prefix; *q; q++)
1971 if (!isalnum (*q))
1972 *q = '_';
1973 if (debug)
1974 fprintf (stderr, "\nwrite_c_file - output name is %s, prefix is %s\n",
1975 output_file, prefix);
1977 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1978 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1979 sprintf (initname, INIT_NAME_FORMAT, prefix);
1981 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1982 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1983 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1985 free (prefix);
1987 /* Write the tables as C code */
1989 fprintf (stream, "static int count;\n");
1990 fprintf (stream, "typedef void entry_pt();\n");
1991 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1993 if (frames)
1995 write_list_with_asm (stream, "extern void *", frame_tables.first);
1997 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1998 write_list (stream, "\t\t&", frame_tables.first);
1999 fprintf (stream, "\t0\n};\n");
2001 /* This must match what's in frame.h. */
2002 fprintf (stream, "struct object {\n");
2003 fprintf (stream, " void *pc_begin;\n");
2004 fprintf (stream, " void *pc_end;\n");
2005 fprintf (stream, " void *fde_begin;\n");
2006 fprintf (stream, " void *fde_array;\n");
2007 fprintf (stream, " __SIZE_TYPE__ count;\n");
2008 fprintf (stream, " struct object *next;\n");
2009 fprintf (stream, "};\n");
2011 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2012 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2014 fprintf (stream, "static void reg_frame () {\n");
2015 fprintf (stream, "\tstatic struct object ob;\n");
2016 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2017 fprintf (stream, "\t}\n");
2019 fprintf (stream, "static void dereg_frame () {\n");
2020 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2021 fprintf (stream, "\t}\n");
2024 fprintf (stream, "void %s() {\n", initname);
2025 if (constructors.number > 0 || frames)
2027 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2028 write_list (stream, "\t\t", constructors.first);
2029 if (frames)
2030 fprintf (stream, "\treg_frame,\n");
2031 fprintf (stream, "\t};\n");
2032 fprintf (stream, "\tentry_pt **p;\n");
2033 fprintf (stream, "\tif (count++ != 0) return;\n");
2034 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2035 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2037 else
2038 fprintf (stream, "\t++count;\n");
2039 fprintf (stream, "}\n");
2040 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2041 fprintf (stream, "void %s() {\n", fininame);
2042 if (destructors.number > 0 || frames)
2044 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2045 write_list (stream, "\t\t", destructors.first);
2046 if (frames)
2047 fprintf (stream, "\tdereg_frame,\n");
2048 fprintf (stream, "\t};\n");
2049 fprintf (stream, "\tentry_pt **p;\n");
2050 fprintf (stream, "\tif (--count != 0) return;\n");
2051 fprintf (stream, "\tp = dtors;\n");
2052 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2053 destructors.number + frames);
2055 fprintf (stream, "}\n");
2057 if (shared_obj)
2059 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
2060 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
2064 /* Write the constructor/destructor tables. */
2066 #ifndef LD_INIT_SWITCH
2067 static void
2068 write_c_file_glob (stream, name)
2069 FILE *stream;
2070 char *name;
2072 /* Write the tables as C code */
2074 int frames = (frame_tables.number > 0);
2076 fprintf (stream, "typedef void entry_pt();\n\n");
2078 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2080 if (frames)
2082 write_list_with_asm (stream, "extern void *", frame_tables.first);
2084 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2085 write_list (stream, "\t\t&", frame_tables.first);
2086 fprintf (stream, "\t0\n};\n");
2088 /* This must match what's in frame.h. */
2089 fprintf (stream, "struct object {\n");
2090 fprintf (stream, " void *pc_begin;\n");
2091 fprintf (stream, " void *pc_end;\n");
2092 fprintf (stream, " void *fde_begin;\n");
2093 fprintf (stream, " void *fde_array;\n");
2094 fprintf (stream, " __SIZE_TYPE__ count;\n");
2095 fprintf (stream, " struct object *next;\n");
2096 fprintf (stream, "};\n");
2098 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2099 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2101 fprintf (stream, "static void reg_frame () {\n");
2102 fprintf (stream, "\tstatic struct object ob;\n");
2103 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2104 fprintf (stream, "\t}\n");
2106 fprintf (stream, "static void dereg_frame () {\n");
2107 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2108 fprintf (stream, "\t}\n");
2111 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2112 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2113 write_list (stream, "\t", constructors.first);
2114 if (frames)
2115 fprintf (stream, "\treg_frame,\n");
2116 fprintf (stream, "\t0\n};\n\n");
2118 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2120 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2121 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2122 write_list (stream, "\t", destructors.first);
2123 if (frames)
2124 fprintf (stream, "\tdereg_frame,\n");
2125 fprintf (stream, "\t0\n};\n\n");
2127 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2128 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2130 #endif /* ! LD_INIT_SWITCH */
2132 static void
2133 write_c_file (stream, name)
2134 FILE *stream;
2135 char *name;
2137 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2138 #ifndef LD_INIT_SWITCH
2139 if (! shared_obj)
2140 write_c_file_glob (stream, name);
2141 else
2142 #endif
2143 write_c_file_stat (stream, name);
2144 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2147 #ifdef COLLECT_EXPORT_LIST
2148 static void
2149 write_export_file (stream)
2150 FILE *stream;
2152 struct id *list = exports.first;
2153 for (; list; list = list->next)
2154 fprintf (stream, "%s\n", list->name);
2157 static void
2158 write_import_file (stream)
2159 FILE *stream;
2161 struct id *list = imports.first;
2162 fprintf (stream, "%s\n", "#! .");
2163 for (; list; list = list->next)
2164 fprintf (stream, "%s\n", list->name);
2166 #endif
2168 #ifdef OBJECT_FORMAT_NONE
2170 /* Generic version to scan the name list of the loaded program for
2171 the symbols g++ uses for static constructors and destructors.
2173 The constructor table begins at __CTOR_LIST__ and contains a count
2174 of the number of pointers (or -1 if the constructors are built in a
2175 separate section by the linker), followed by the pointers to the
2176 constructor functions, terminated with a null pointer. The
2177 destructor table has the same format, and begins at __DTOR_LIST__. */
2179 static void
2180 scan_prog_file (prog_name, which_pass)
2181 char *prog_name;
2182 enum pass which_pass;
2184 void (*int_handler) ();
2185 void (*quit_handler) ();
2186 char *nm_argv[4];
2187 int pid;
2188 int argc = 0;
2189 int pipe_fd[2];
2190 char *p, buf[1024];
2191 FILE *inf;
2193 if (which_pass == PASS_SECOND)
2194 return;
2196 /* If we do not have an `nm', complain. */
2197 if (nm_file_name == 0)
2198 fatal ("cannot find `nm'");
2200 nm_argv[argc++] = nm_file_name;
2201 if (NM_FLAGS[0] != '\0')
2202 nm_argv[argc++] = NM_FLAGS;
2204 nm_argv[argc++] = prog_name;
2205 nm_argv[argc++] = (char *) 0;
2207 if (pipe (pipe_fd) < 0)
2208 fatal_perror ("pipe");
2210 inf = fdopen (pipe_fd[0], "r");
2211 if (inf == (FILE *) 0)
2212 fatal_perror ("fdopen");
2214 /* Trace if needed. */
2215 if (vflag)
2217 char **p_argv;
2218 char *str;
2220 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2221 fprintf (stderr, " %s", str);
2223 fprintf (stderr, "\n");
2226 fflush (stdout);
2227 fflush (stderr);
2229 /* Spawn child nm on pipe */
2230 pid = vfork ();
2231 if (pid == -1)
2233 #ifdef vfork
2234 fatal_perror ("fork");
2235 #else
2236 fatal_perror ("vfork");
2237 #endif
2240 if (pid == 0) /* child context */
2242 /* setup stdout */
2243 if (dup2 (pipe_fd[1], 1) < 0)
2244 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2246 if (close (pipe_fd[0]) < 0)
2247 fatal_perror ("close (%d)", pipe_fd[0]);
2249 if (close (pipe_fd[1]) < 0)
2250 fatal_perror ("close (%d)", pipe_fd[1]);
2252 execv (nm_file_name, nm_argv);
2253 fatal_perror ("executing %s", nm_file_name);
2256 /* Parent context from here on. */
2257 int_handler = (void (*) ())signal (SIGINT, SIG_IGN);
2258 #ifdef SIGQUIT
2259 quit_handler = (void (*) ())signal (SIGQUIT, SIG_IGN);
2260 #endif
2262 if (close (pipe_fd[1]) < 0)
2263 fatal_perror ("close (%d)", pipe_fd[1]);
2265 if (debug)
2266 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2268 /* Read each line of nm output. */
2269 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2271 int ch, ch2;
2272 char *name, *end;
2274 /* If it contains a constructor or destructor name, add the name
2275 to the appropriate list. */
2277 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2278 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2279 break;
2281 if (ch != '_')
2282 continue;
2284 name = p;
2285 /* Find the end of the symbol name.
2286 Do not include `|', because Encore nm can tack that on the end. */
2287 for (end = p; (ch2 = *end) != '\0' && !isspace (ch2) && ch2 != '|';
2288 end++)
2289 continue;
2292 *end = '\0';
2293 switch (is_ctor_dtor (name))
2295 case 1:
2296 if (which_pass != PASS_LIB)
2297 add_to_list (&constructors, name);
2298 break;
2300 case 2:
2301 if (which_pass != PASS_LIB)
2302 add_to_list (&destructors, name);
2303 break;
2305 case 3:
2306 if (which_pass != PASS_LIB)
2307 fatal ("init function found in object %s", prog_name);
2308 #ifndef LD_INIT_SWITCH
2309 add_to_list (&constructors, name);
2310 #endif
2311 break;
2313 case 4:
2314 if (which_pass != PASS_LIB)
2315 fatal ("fini function found in object %s", prog_name);
2316 #ifndef LD_FINI_SWITCH
2317 add_to_list (&destructors, name);
2318 #endif
2319 break;
2321 case 5:
2322 if (which_pass != PASS_LIB)
2323 add_to_list (&frame_tables, name);
2325 default: /* not a constructor or destructor */
2326 continue;
2329 if (debug)
2330 fprintf (stderr, "\t%s\n", buf);
2333 if (debug)
2334 fprintf (stderr, "\n");
2336 if (fclose (inf) != 0)
2337 fatal_perror ("fclose of pipe");
2339 do_wait (nm_file_name);
2341 signal (SIGINT, int_handler);
2342 #ifdef SIGQUIT
2343 signal (SIGQUIT, quit_handler);
2344 #endif
2347 #if SUNOS4_SHARED_LIBRARIES
2349 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2350 that the output file depends upon and their initialization/finalization
2351 routines, if any. */
2353 #include <a.out.h>
2354 #include <fcntl.h>
2355 #include <link.h>
2356 #include <sys/mman.h>
2357 #include <sys/param.h>
2358 #include <unistd.h>
2359 #include <sys/dir.h>
2361 /* pointers to the object file */
2362 unsigned object; /* address of memory mapped file */
2363 unsigned objsize; /* size of memory mapped to file */
2364 char * code; /* pointer to code segment */
2365 char * data; /* pointer to data segment */
2366 struct nlist *symtab; /* pointer to symbol table */
2367 struct link_dynamic *ld;
2368 struct link_dynamic_2 *ld_2;
2369 struct head libraries;
2371 /* Map the file indicated by NAME into memory and store its address. */
2373 static void
2374 mapfile (name)
2375 char *name;
2377 int fp;
2378 struct stat s;
2379 if ((fp = open (name, O_RDONLY)) == -1)
2380 fatal ("unable to open file '%s'", name);
2381 if (fstat (fp, &s) == -1)
2382 fatal ("unable to stat file '%s'", name);
2384 objsize = s.st_size;
2385 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2386 fp, 0);
2387 if (object == -1)
2388 fatal ("unable to mmap file '%s'", name);
2390 close (fp);
2393 /* Helpers for locatelib. */
2395 static char *libname;
2397 static int
2398 libselect (d)
2399 struct direct *d;
2401 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2404 /* If one file has an additional numeric extension past LIBNAME, then put
2405 that one first in the sort. If both files have additional numeric
2406 extensions, then put the one with the higher number first in the sort.
2408 We must verify that the extension is numeric, because Sun saves the
2409 original versions of patched libraries with a .FCS extension. Files with
2410 invalid extensions must go last in the sort, so that they will not be used. */
2412 static int
2413 libcompare (d1, d2)
2414 struct direct **d1, **d2;
2416 int i1, i2 = strlen (libname);
2417 char *e1 = (*d1)->d_name + i2;
2418 char *e2 = (*d2)->d_name + i2;
2420 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2421 && e1[1] && isdigit (e1[1]) && e2[1] && isdigit (e2[1]))
2423 ++e1;
2424 ++e2;
2425 i1 = strtol (e1, &e1, 10);
2426 i2 = strtol (e2, &e2, 10);
2427 if (i1 != i2)
2428 return i1 - i2;
2431 if (*e1)
2433 /* It has a valid numeric extension, prefer this one. */
2434 if (*e1 == '.' && e1[1] && isdigit (e1[1]))
2435 return 1;
2436 /* It has a invalid numeric extension, must prefer the other one. */
2437 else
2438 return -1;
2440 else if (*e2)
2442 /* It has a valid numeric extension, prefer this one. */
2443 if (*e2 == '.' && e2[1] && isdigit (e2[1]))
2444 return -1;
2445 /* It has a invalid numeric extension, must prefer the other one. */
2446 else
2447 return 1;
2449 else
2450 return 0;
2453 /* Given the name NAME of a dynamic dependency, find its pathname and add
2454 it to the list of libraries. */
2456 static void
2457 locatelib (name)
2458 char *name;
2460 static char **l;
2461 static int cnt;
2462 char buf[MAXPATHLEN];
2463 char *p, *q;
2464 char **pp;
2466 if (l == 0)
2468 char *ld_rules;
2469 char *ldr = 0;
2470 /* counting elements in array, need 1 extra for null */
2471 cnt = 1;
2472 ld_rules = (char *) (ld_2->ld_rules + code);
2473 if (ld_rules)
2475 cnt++;
2476 for (; *ld_rules != 0; ld_rules++)
2477 if (*ld_rules == ':')
2478 cnt++;
2479 ld_rules = (char *) (ld_2->ld_rules + code);
2480 ldr = (char *) malloc (strlen (ld_rules) + 1);
2481 strcpy (ldr, ld_rules);
2483 p = getenv ("LD_LIBRARY_PATH");
2484 q = 0;
2485 if (p)
2487 cnt++;
2488 for (q = p ; *q != 0; q++)
2489 if (*q == ':')
2490 cnt++;
2491 q = (char *) malloc (strlen (p) + 1);
2492 strcpy (q, p);
2494 l = (char **) malloc ((cnt + 3) * sizeof (char *));
2495 pp = l;
2496 if (ldr)
2498 *pp++ = ldr;
2499 for (; *ldr != 0; ldr++)
2500 if (*ldr == ':')
2502 *ldr++ = 0;
2503 *pp++ = ldr;
2506 if (q)
2508 *pp++ = q;
2509 for (; *q != 0; q++)
2510 if (*q == ':')
2512 *q++ = 0;
2513 *pp++ = q;
2516 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2517 *pp++ = "/lib";
2518 *pp++ = "/usr/lib";
2519 *pp++ = "/usr/local/lib";
2520 *pp = 0;
2522 libname = name;
2523 for (pp = l; *pp != 0 ; pp++)
2525 struct direct **namelist;
2526 int entries;
2527 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2529 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2530 add_to_list (&libraries, buf);
2531 if (debug)
2532 fprintf (stderr, "%s\n", buf);
2533 break;
2536 if (*pp == 0)
2538 if (debug)
2539 fprintf (stderr, "not found\n");
2540 else
2541 fatal ("dynamic dependency %s not found", name);
2545 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2546 that it depends upon and any constructors or destructors they contain. */
2548 static void
2549 scan_libraries (prog_name)
2550 char *prog_name;
2552 struct exec *header;
2553 char *base;
2554 struct link_object *lo;
2555 char buff[MAXPATHLEN];
2556 struct id *list;
2558 mapfile (prog_name);
2559 header = (struct exec *)object;
2560 if (N_BADMAG (*header))
2561 fatal ("bad magic number in file '%s'", prog_name);
2562 if (header->a_dynamic == 0)
2563 return;
2565 code = (char *) (N_TXTOFF (*header) + (long) header);
2566 data = (char *) (N_DATOFF (*header) + (long) header);
2567 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2569 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2571 /* shared object */
2572 ld = (struct link_dynamic *) (symtab->n_value + code);
2573 base = code;
2575 else
2577 /* executable */
2578 ld = (struct link_dynamic *) data;
2579 base = code-PAGSIZ;
2582 if (debug)
2583 fprintf (stderr, "dynamic dependencies.\n");
2585 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2586 for (lo = (struct link_object *) ld_2->ld_need; lo;
2587 lo = (struct link_object *) lo->lo_next)
2589 char *name;
2590 lo = (struct link_object *) ((long) lo + code);
2591 name = (char *) (code + lo->lo_name);
2592 if (lo->lo_library)
2594 if (debug)
2595 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2596 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2597 locatelib (buff);
2599 else
2601 if (debug)
2602 fprintf (stderr, "\t%s\n", name);
2603 add_to_list (&libraries, name);
2607 if (debug)
2608 fprintf (stderr, "\n");
2610 /* now iterate through the library list adding their symbols to
2611 the list. */
2612 for (list = libraries.first; list; list = list->next)
2613 scan_prog_file (list->name, PASS_LIB);
2616 #else /* SUNOS4_SHARED_LIBRARIES */
2617 #ifdef LDD_SUFFIX
2619 /* Use the List Dynamic Dependencies program to find shared libraries that
2620 the output file depends upon and their initialization/finalization
2621 routines, if any. */
2623 static void
2624 scan_libraries (prog_name)
2625 char *prog_name;
2627 static struct head libraries; /* list of shared libraries found */
2628 struct id *list;
2629 void (*int_handler) ();
2630 void (*quit_handler) ();
2631 char *ldd_argv[4];
2632 int pid;
2633 int argc = 0;
2634 int pipe_fd[2];
2635 char buf[1024];
2636 FILE *inf;
2638 /* If we do not have an `ldd', complain. */
2639 if (ldd_file_name == 0)
2641 error ("cannot find `ldd'");
2642 return;
2645 ldd_argv[argc++] = ldd_file_name;
2646 ldd_argv[argc++] = prog_name;
2647 ldd_argv[argc++] = (char *) 0;
2649 if (pipe (pipe_fd) < 0)
2650 fatal_perror ("pipe");
2652 inf = fdopen (pipe_fd[0], "r");
2653 if (inf == (FILE *) 0)
2654 fatal_perror ("fdopen");
2656 /* Trace if needed. */
2657 if (vflag)
2659 char **p_argv;
2660 char *str;
2662 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2663 fprintf (stderr, " %s", str);
2665 fprintf (stderr, "\n");
2668 fflush (stdout);
2669 fflush (stderr);
2671 /* Spawn child ldd on pipe */
2672 pid = vfork ();
2673 if (pid == -1)
2675 #ifdef vfork
2676 fatal_perror ("fork");
2677 #else
2678 fatal_perror ("vfork");
2679 #endif
2682 if (pid == 0) /* child context */
2684 /* setup stdout */
2685 if (dup2 (pipe_fd[1], 1) < 0)
2686 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2688 if (close (pipe_fd[0]) < 0)
2689 fatal_perror ("close (%d)", pipe_fd[0]);
2691 if (close (pipe_fd[1]) < 0)
2692 fatal_perror ("close (%d)", pipe_fd[1]);
2694 execv (ldd_file_name, ldd_argv);
2695 fatal_perror ("executing %s", ldd_file_name);
2698 /* Parent context from here on. */
2699 int_handler = (void (*) ()) signal (SIGINT, SIG_IGN);
2700 #ifdef SIGQUIT
2701 quit_handler = (void (*) ()) signal (SIGQUIT, SIG_IGN);
2702 #endif
2704 if (close (pipe_fd[1]) < 0)
2705 fatal_perror ("close (%d)", pipe_fd[1]);
2707 if (debug)
2708 fprintf (stderr, "\nldd output with constructors/destructors.\n");
2710 /* Read each line of ldd output. */
2711 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2713 int ch, ch2;
2714 char *name, *end, *p = buf;
2716 /* Extract names of libraries and add to list. */
2717 PARSE_LDD_OUTPUT (p);
2718 if (p == 0)
2719 continue;
2721 name = p;
2722 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2723 fatal ("dynamic dependency %s not found", buf);
2725 /* Find the end of the symbol name. */
2726 for (end = p;
2727 (ch2 = *end) != '\0' && ch2 != '\n' && !isspace (ch2) && ch2 != '|';
2728 end++)
2729 continue;
2730 *end = '\0';
2732 if (access (name, R_OK) == 0)
2733 add_to_list (&libraries, name);
2734 else
2735 fatal ("unable to open dynamic dependency '%s'", buf);
2737 if (debug)
2738 fprintf (stderr, "\t%s\n", buf);
2740 if (debug)
2741 fprintf (stderr, "\n");
2743 if (fclose (inf) != 0)
2744 fatal_perror ("fclose of pipe");
2746 do_wait (ldd_file_name);
2748 signal (SIGINT, int_handler);
2749 #ifdef SIGQUIT
2750 signal (SIGQUIT, quit_handler);
2751 #endif
2753 /* now iterate through the library list adding their symbols to
2754 the list. */
2755 for (list = libraries.first; list; list = list->next)
2756 scan_prog_file (list->name, PASS_LIB);
2759 #endif /* LDD_SUFFIX */
2760 #endif /* SUNOS4_SHARED_LIBRARIES */
2762 #endif /* OBJECT_FORMAT_NONE */
2766 * COFF specific stuff.
2769 #ifdef OBJECT_FORMAT_COFF
2771 #if defined(EXTENDED_COFF)
2772 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2773 # define GCC_SYMENT SYMR
2774 # define GCC_OK_SYMBOL(X) ((X).st == stProc && (X).sc == scText)
2775 # define GCC_SYMINC(X) (1)
2776 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2777 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2778 #else
2779 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2780 # define GCC_SYMENT SYMENT
2781 # define GCC_OK_SYMBOL(X) \
2782 (((X).n_sclass == C_EXT) && \
2783 ((X).n_scnum > N_UNDEF) && \
2784 (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) || \
2785 ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT)))
2786 # define GCC_UNDEF_SYMBOL(X) \
2787 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2788 # define GCC_SYMINC(X) ((X).n_numaux+1)
2789 # define GCC_SYMZERO(X) 0
2790 # define GCC_CHECK_HDR(X) (1)
2791 #endif
2793 extern char *ldgetname ();
2795 /* COFF version to scan the name list of the loaded program for
2796 the symbols g++ uses for static constructors and destructors.
2798 The constructor table begins at __CTOR_LIST__ and contains a count
2799 of the number of pointers (or -1 if the constructors are built in a
2800 separate section by the linker), followed by the pointers to the
2801 constructor functions, terminated with a null pointer. The
2802 destructor table has the same format, and begins at __DTOR_LIST__. */
2804 static void
2805 scan_prog_file (prog_name, which_pass)
2806 char *prog_name;
2807 enum pass which_pass;
2809 LDFILE *ldptr = NULL;
2810 int sym_index, sym_count;
2811 int is_shared = 0;
2812 #ifdef COLLECT_EXPORT_LIST
2813 /* Should we generate an import list for given prog_name? */
2814 int import_flag = (which_pass == PASS_OBJ ? 0 : use_import_list (prog_name));
2815 #endif
2817 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2818 return;
2820 #ifdef COLLECT_EXPORT_LIST
2821 /* We do not need scanning for some standard C libraries. */
2822 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2823 return;
2825 /* On AIX we have a loop, because there is not much difference
2826 between an object and an archive. This trick allows us to
2827 eliminate scan_libraries() function. */
2830 #endif
2831 if ((ldptr = ldopen (prog_name, ldptr)) != NULL)
2834 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2835 fatal ("%s: not a COFF file", prog_name);
2837 #ifdef COLLECT_EXPORT_LIST
2838 /* Is current archive member a shared object? */
2839 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2840 #endif
2841 if (GCC_CHECK_HDR (ldptr))
2843 sym_count = GCC_SYMBOLS (ldptr);
2844 sym_index = GCC_SYMZERO (ldptr);
2845 while (sym_index < sym_count)
2847 GCC_SYMENT symbol;
2849 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2850 break;
2851 sym_index += GCC_SYMINC (symbol);
2853 if (GCC_OK_SYMBOL (symbol))
2855 char *name;
2857 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2858 continue; /* should never happen */
2860 #ifdef XCOFF_DEBUGGING_INFO
2861 /* All AIX function names have a duplicate entry
2862 beginning with a dot. */
2863 if (*name == '.')
2864 ++name;
2865 #endif
2867 switch (is_ctor_dtor (name))
2869 case 1:
2870 if (! is_shared) add_to_list (&constructors, name);
2871 #ifdef COLLECT_EXPORT_LIST
2872 if (which_pass == PASS_OBJ)
2873 add_to_list (&exports, name);
2874 /* If this symbol was undefined and we are building
2875 an import list, we should add a symbol to this
2876 list. */
2877 else
2878 if (import_flag
2879 && is_in_list (name, undefined.first))
2880 add_to_list (&imports, name);
2881 #endif
2882 break;
2884 case 2:
2885 if (! is_shared) add_to_list (&destructors, name);
2886 #ifdef COLLECT_EXPORT_LIST
2887 if (which_pass == PASS_OBJ)
2888 add_to_list (&exports, name);
2889 /* If this symbol was undefined and we are building
2890 an import list, we should add a symbol to this
2891 list. */
2892 else
2893 if (import_flag
2894 && is_in_list (name, undefined.first))
2895 add_to_list (&imports, name);
2896 #endif
2897 break;
2899 #ifdef COLLECT_EXPORT_LIST
2900 case 3:
2901 if (is_shared)
2902 add_to_list (&constructors, name);
2903 break;
2905 case 4:
2906 if (is_shared)
2907 add_to_list (&destructors, name);
2908 break;
2909 #endif
2911 default: /* not a constructor or destructor */
2912 #ifdef COLLECT_EXPORT_LIST
2913 /* If we are building a shared object on AIX we need
2914 to explicitly export all global symbols or add
2915 them to import list. */
2916 if (shared_obj)
2918 if (which_pass == PASS_OBJ && (! export_flag))
2919 add_to_list (&exports, name);
2920 else if (! is_shared && which_pass == PASS_FIRST
2921 && import_flag
2922 && is_in_list(name, undefined.first))
2923 add_to_list (&imports, name);
2925 #endif
2926 continue;
2929 #if !defined(EXTENDED_COFF)
2930 if (debug)
2931 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2932 symbol.n_scnum, symbol.n_sclass,
2933 (symbol.n_type ? "0" : ""), symbol.n_type,
2934 name);
2935 #else
2936 if (debug)
2937 fprintf (stderr,
2938 "\tiss = %5d, value = %5d, index = %5d, name = %s\n",
2939 symbol.iss, symbol.value, symbol.index, name);
2940 #endif
2942 #ifdef COLLECT_EXPORT_LIST
2943 /* If we are building a shared object we should collect
2944 information about undefined symbols for later
2945 import list generation. */
2946 else if (shared_obj && GCC_UNDEF_SYMBOL (symbol))
2948 char *name;
2950 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2951 continue; /* should never happen */
2953 /* All AIX function names have a duplicate entry
2954 beginning with a dot. */
2955 if (*name == '.')
2956 ++name;
2957 add_to_list (&undefined, name);
2959 #endif
2963 else
2965 fatal ("%s: cannot open as COFF file", prog_name);
2967 #ifdef COLLECT_EXPORT_LIST
2968 /* On AIX loop continues while there are more members in archive. */
2970 while (ldclose (ldptr) == FAILURE);
2971 #else
2972 /* Otherwise we simply close ldptr. */
2973 (void) ldclose(ldptr);
2974 #endif
2978 #ifdef COLLECT_EXPORT_LIST
2980 /* This new function is used to decide whether we should
2981 generate import list for an object or to use it directly. */
2982 static int
2983 use_import_list (prog_name)
2984 char *prog_name;
2986 char *p;
2988 /* If we do not build a shared object then import list should not be used. */
2989 if (! shared_obj) return 0;
2991 /* Currently we check only for libgcc, but this can be changed in future. */
2992 p = strstr (prog_name, "libgcc.a");
2993 if (p != 0 && (strlen (p) == sizeof ("libgcc.a") - 1))
2994 return 1;
2995 return 0;
2998 /* Given a library name without "lib" prefix, this function
2999 returns a full library name including a path. */
3000 static char *
3001 resolve_lib_name (name)
3002 char *name;
3004 char *lib_buf;
3005 int i, j, l = 0;
3007 for (i = 0; libpaths[i]; i++)
3008 if (libpaths[i]->max_len > l)
3009 l = libpaths[i]->max_len;
3011 lib_buf = xmalloc (l + strlen(name) + 10);
3013 for (i = 0; libpaths[i]; i++)
3015 struct prefix_list *list = libpaths[i]->plist;
3016 for (; list; list = list->next)
3018 for (j = 0; libexts[j]; j++)
3020 /* The following lines are needed because path_prefix list
3021 may contain directories both with trailing '/' and
3022 without it. */
3023 char *p = "";
3024 if (list->prefix[strlen(list->prefix)-1] != '/')
3025 p = "/";
3026 sprintf (lib_buf, "%s%slib%s.%s",
3027 list->prefix, p, name, libexts[j]);
3028 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
3029 if (file_exists (lib_buf))
3031 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
3032 return (lib_buf);
3037 if (debug)
3038 fprintf (stderr, "not found\n");
3039 else
3040 fatal ("Library lib%s not found", name);
3041 return (NULL);
3044 /* Array of standard AIX libraries which should not
3045 be scanned for ctors/dtors. */
3046 static char* aix_std_libs[] = {
3047 "/unix",
3048 "/lib/libc.a",
3049 "/lib/libc_r.a",
3050 "/usr/lib/libc.a",
3051 "/usr/lib/libc_r.a",
3052 "/usr/lib/threads/libc.a",
3053 "/usr/ccs/lib/libc.a",
3054 "/usr/ccs/lib/libc_r.a",
3055 NULL
3058 /* This function checks the filename and returns 1
3059 if this name matches the location of a standard AIX library. */
3060 static int
3061 ignore_library (name)
3062 char *name;
3064 char **p = &aix_std_libs[0];
3065 while (*p++ != NULL)
3066 if (! strcmp (name, *p)) return 1;
3067 return 0;
3070 #endif
3072 #endif /* OBJECT_FORMAT_COFF */
3076 * OSF/rose specific stuff.
3079 #ifdef OBJECT_FORMAT_ROSE
3081 /* Union of the various load commands */
3083 typedef union load_union
3085 ldc_header_t hdr; /* common header */
3086 load_cmd_map_command_t map; /* map indexing other load cmds */
3087 interpreter_command_t iprtr; /* interpreter pathname */
3088 strings_command_t str; /* load commands strings section */
3089 region_command_t region; /* region load command */
3090 reloc_command_t reloc; /* relocation section */
3091 package_command_t pkg; /* package load command */
3092 symbols_command_t sym; /* symbol sections */
3093 entry_command_t ent; /* program start section */
3094 gen_info_command_t info; /* object information */
3095 func_table_command_t func; /* function constructors/destructors */
3096 } load_union_t;
3098 /* Structure to point to load command and data section in memory. */
3100 typedef struct load_all
3102 load_union_t *load; /* load command */
3103 char *section; /* pointer to section */
3104 } load_all_t;
3106 /* Structure to contain information about a file mapped into memory. */
3108 struct file_info
3110 char *start; /* start of map */
3111 char *name; /* filename */
3112 long size; /* size of the file */
3113 long rounded_size; /* size rounded to page boundary */
3114 int fd; /* file descriptor */
3115 int rw; /* != 0 if opened read/write */
3116 int use_mmap; /* != 0 if mmap'ed */
3119 extern int decode_mach_o_hdr ();
3120 extern int encode_mach_o_hdr ();
3122 static void add_func_table PROTO((mo_header_t *, load_all_t *,
3123 symbol_info_t *, int));
3124 static void print_header PROTO((mo_header_t *));
3125 static void print_load_command PROTO((load_union_t *, size_t, int));
3126 static void bad_header PROTO((int));
3127 static struct file_info *read_file PROTO((char *, int, int));
3128 static void end_file PROTO((struct file_info *));
3130 /* OSF/rose specific version to scan the name list of the loaded
3131 program for the symbols g++ uses for static constructors and
3132 destructors.
3134 The constructor table begins at __CTOR_LIST__ and contains a count
3135 of the number of pointers (or -1 if the constructors are built in a
3136 separate section by the linker), followed by the pointers to the
3137 constructor functions, terminated with a null pointer. The
3138 destructor table has the same format, and begins at __DTOR_LIST__. */
3140 static void
3141 scan_prog_file (prog_name, which_pass)
3142 char *prog_name;
3143 enum pass which_pass;
3145 char *obj;
3146 mo_header_t hdr;
3147 load_all_t *load_array;
3148 load_all_t *load_end;
3149 load_all_t *load_cmd;
3150 int symbol_load_cmds;
3151 off_t offset;
3152 int i;
3153 int num_syms;
3154 int status;
3155 char *str_sect;
3156 struct file_info *obj_file;
3157 int prog_fd;
3158 mo_lcid_t cmd_strings = -1;
3159 symbol_info_t *main_sym = 0;
3160 int rw = (which_pass != PASS_FIRST);
3162 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3163 if (prog_fd < 0)
3164 fatal_perror ("cannot read %s", prog_name);
3166 obj_file = read_file (prog_name, prog_fd, rw);
3167 obj = obj_file->start;
3169 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3170 if (status != MO_HDR_CONV_SUCCESS)
3171 bad_header (status);
3174 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3175 since the hardware will automatically swap bytes for us on loading little endian
3176 integers. */
3178 #ifndef CROSS_COMPILE
3179 if (hdr.moh_magic != MOH_MAGIC_MSB
3180 || hdr.moh_header_version != MOH_HEADER_VERSION
3181 || hdr.moh_byte_order != OUR_BYTE_ORDER
3182 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3183 || hdr.moh_cpu_type != OUR_CPU_TYPE
3184 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3185 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3187 fatal ("incompatibilities between object file & expected values");
3189 #endif
3191 if (debug)
3192 print_header (&hdr);
3194 offset = hdr.moh_first_cmd_off;
3195 load_end = load_array
3196 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3198 /* Build array of load commands, calculating the offsets */
3199 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3201 load_union_t *load_hdr; /* load command header */
3203 load_cmd = load_end++;
3204 load_hdr = (load_union_t *) (obj + offset);
3206 /* If modifying the program file, copy the header. */
3207 if (rw)
3209 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3210 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
3211 load_hdr = ptr;
3213 /* null out old command map, because we will rewrite at the end. */
3214 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3216 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3217 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3221 load_cmd->load = load_hdr;
3222 if (load_hdr->hdr.ldci_section_off > 0)
3223 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3225 if (debug)
3226 print_load_command (load_hdr, offset, i);
3228 offset += load_hdr->hdr.ldci_cmd_size;
3231 /* If the last command is the load command map and is not undefined,
3232 decrement the count of load commands. */
3233 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3235 load_end--;
3236 hdr.moh_n_load_cmds--;
3239 /* Go through and process each symbol table section. */
3240 symbol_load_cmds = 0;
3241 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3243 load_union_t *load_hdr = load_cmd->load;
3245 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3247 symbol_load_cmds++;
3249 if (debug)
3251 char *kind = "unknown";
3253 switch (load_hdr->sym.symc_kind)
3255 case SYMC_IMPORTS: kind = "imports"; break;
3256 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3257 case SYMC_STABS: kind = "stabs"; break;
3260 fprintf (stderr, "\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3261 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3264 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3265 continue;
3267 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3268 if (str_sect == (char *) 0)
3269 fatal ("string section missing");
3271 if (load_cmd->section == (char *) 0)
3272 fatal ("section pointer missing");
3274 num_syms = load_hdr->sym.symc_nentries;
3275 for (i = 0; i < num_syms; i++)
3277 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3278 char *name = sym->si_name.symbol_name + str_sect;
3280 if (name[0] != '_')
3281 continue;
3283 if (rw)
3285 char *n = name + strlen (name) - strlen (NAME__MAIN);
3287 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3288 continue;
3289 while (n != name)
3290 if (*--n != '_')
3291 continue;
3293 main_sym = sym;
3295 else
3297 switch (is_ctor_dtor (name))
3299 case 1:
3300 add_to_list (&constructors, name);
3301 break;
3303 case 2:
3304 add_to_list (&destructors, name);
3305 break;
3307 default: /* not a constructor or destructor */
3308 continue;
3312 if (debug)
3313 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3314 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3319 if (symbol_load_cmds == 0)
3320 fatal ("no symbol table found");
3322 /* Update the program file now, rewrite header and load commands. At present,
3323 we assume that there is enough space after the last load command to insert
3324 one more. Since the first section written out is page aligned, and the
3325 number of load commands is small, this is ok for the present. */
3327 if (rw)
3329 load_union_t *load_map;
3330 size_t size;
3332 if (cmd_strings == -1)
3333 fatal ("no cmd_strings found");
3335 /* Add __main to initializer list.
3336 If we are building a program instead of a shared library, do not
3337 do anything, since in the current version, you cannot do mallocs
3338 and such in the constructors. */
3340 if (main_sym != (symbol_info_t *) 0
3341 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3342 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3344 if (debug)
3345 fprintf (stderr, "\nUpdating header and load commands.\n\n");
3347 hdr.moh_n_load_cmds++;
3348 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3350 /* Create new load command map. */
3351 if (debug)
3352 fprintf (stderr, "load command map, %d cmds, new size %ld.\n",
3353 (int)hdr.moh_n_load_cmds, (long)size);
3355 load_map = (load_union_t *) xcalloc (1, size);
3356 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3357 load_map->map.ldc_header.ldci_cmd_size = size;
3358 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3359 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3360 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3362 offset = hdr.moh_first_cmd_off;
3363 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3365 load_map->map.lcm_map[i] = offset;
3366 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3367 hdr.moh_load_map_cmd_off = offset;
3369 offset += load_array[i].load->hdr.ldci_cmd_size;
3372 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3374 if (debug)
3375 print_header (&hdr);
3377 /* Write header */
3378 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3379 if (status != MO_HDR_CONV_SUCCESS)
3380 bad_header (status);
3382 if (debug)
3383 fprintf (stderr, "writing load commands.\n\n");
3385 /* Write load commands */
3386 offset = hdr.moh_first_cmd_off;
3387 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3389 load_union_t *load_hdr = load_array[i].load;
3390 size_t size = load_hdr->hdr.ldci_cmd_size;
3392 if (debug)
3393 print_load_command (load_hdr, offset, i);
3395 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3396 offset += size;
3400 end_file (obj_file);
3402 if (close (prog_fd))
3403 fatal_perror ("closing %s", prog_name);
3405 if (debug)
3406 fprintf (stderr, "\n");
3410 /* Add a function table to the load commands to call a function
3411 on initiation or termination of the process. */
3413 static void
3414 add_func_table (hdr_p, load_array, sym, type)
3415 mo_header_t *hdr_p; /* pointer to global header */
3416 load_all_t *load_array; /* array of ptrs to load cmds */
3417 symbol_info_t *sym; /* pointer to symbol entry */
3418 int type; /* fntc_type value */
3420 /* Add a new load command. */
3421 int num_cmds = ++hdr_p->moh_n_load_cmds;
3422 int load_index = num_cmds - 1;
3423 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3424 load_union_t *ptr = xcalloc (1, size);
3425 load_all_t *load_cmd;
3426 int i;
3428 /* Set the unresolved address bit in the header to force the loader to be
3429 used, since kernel exec does not call the initialization functions. */
3430 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3432 load_cmd = &load_array[load_index];
3433 load_cmd->load = ptr;
3434 load_cmd->section = (char *) 0;
3436 /* Fill in func table load command. */
3437 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3438 ptr->func.ldc_header.ldci_cmd_size = size;
3439 ptr->func.ldc_header.ldci_section_off = 0;
3440 ptr->func.ldc_header.ldci_section_len = 0;
3441 ptr->func.fntc_type = type;
3442 ptr->func.fntc_nentries = 1;
3444 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3445 /* Is the symbol already expressed as (region, offset)? */
3446 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3448 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3449 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3452 /* If not, figure out which region it's in. */
3453 else
3455 mo_vm_addr_t addr = sym->si_value.abs_val;
3456 int found = 0;
3458 for (i = 0; i < load_index; i++)
3460 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3462 region_command_t *region_ptr = &load_array[i].load->region;
3464 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3465 && addr >= region_ptr->regc_addr.vm_addr
3466 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3468 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3469 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3470 found++;
3471 break;
3476 if (!found)
3477 fatal ("could not convert 0x%l.8x into a region", addr);
3480 if (debug)
3481 fprintf (stderr,
3482 "%s function, region %d, offset = %ld (0x%.8lx)\n",
3483 (type == FNTC_INITIALIZATION) ? "init" : "term",
3484 (int)ptr->func.fntc_entry_loc[i].adr_lcid,
3485 (long)ptr->func.fntc_entry_loc[i].adr_sctoff,
3486 (long)ptr->func.fntc_entry_loc[i].adr_sctoff);
3491 /* Print the global header for an OSF/rose object. */
3493 static void
3494 print_header (hdr_ptr)
3495 mo_header_t *hdr_ptr;
3497 fprintf (stderr, "\nglobal header:\n");
3498 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3499 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3500 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3501 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3502 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3503 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3504 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3505 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3506 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3507 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3508 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3509 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3510 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3511 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3512 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3514 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3515 fprintf (stderr, ", relocatable");
3517 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3518 fprintf (stderr, ", linkable");
3520 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3521 fprintf (stderr, ", execable");
3523 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3524 fprintf (stderr, ", executable");
3526 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3527 fprintf (stderr, ", unresolved");
3529 fprintf (stderr, "\n\n");
3530 return;
3534 /* Print a short summary of a load command. */
3536 static void
3537 print_load_command (load_hdr, offset, number)
3538 load_union_t *load_hdr;
3539 size_t offset;
3540 int number;
3542 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3543 char *type_str = (char *) 0;
3545 switch (type)
3547 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3548 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3549 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3550 case LDC_STRINGS: type_str = "STRINGS"; break;
3551 case LDC_REGION: type_str = "REGION"; break;
3552 case LDC_RELOC: type_str = "RELOC"; break;
3553 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3554 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3555 case LDC_ENTRY: type_str = "ENTRY"; break;
3556 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3557 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3560 fprintf (stderr,
3561 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3562 number,
3563 (long) load_hdr->hdr.ldci_cmd_size,
3564 (long) offset,
3565 (long) load_hdr->hdr.ldci_section_off,
3566 (long) load_hdr->hdr.ldci_section_len);
3568 if (type_str == (char *) 0)
3569 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3571 else if (type != LDC_REGION)
3572 fprintf (stderr, ", ty: %s\n", type_str);
3574 else
3576 char *region = "";
3577 switch (load_hdr->region.regc_usage_type)
3579 case REG_TEXT_T: region = ", .text"; break;
3580 case REG_DATA_T: region = ", .data"; break;
3581 case REG_BSS_T: region = ", .bss"; break;
3582 case REG_GLUE_T: region = ", .glue"; break;
3583 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3584 case REG_RDATA_T: region = ", .rdata"; break;
3585 case REG_SDATA_T: region = ", .sdata"; break;
3586 case REG_SBSS_T: region = ", .sbss"; break;
3587 #endif
3590 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3591 type_str,
3592 (long) load_hdr->region.regc_vm_addr,
3593 (long) load_hdr->region.regc_vm_size,
3594 region);
3597 return;
3601 /* Fatal error when {en,de}code_mach_o_header fails. */
3603 static void
3604 bad_header (status)
3605 int status;
3607 char *msg = (char *) 0;
3609 switch (status)
3611 case MO_ERROR_BAD_MAGIC: msg = "bad magic number"; break;
3612 case MO_ERROR_BAD_HDR_VERS: msg = "bad header version"; break;
3613 case MO_ERROR_BAD_RAW_HDR_VERS: msg = "bad raw header version"; break;
3614 case MO_ERROR_BUF2SML: msg = "raw header buffer too small"; break;
3615 case MO_ERROR_OLD_RAW_HDR_FILE: msg = "old raw header file"; break;
3616 case MO_ERROR_UNSUPPORTED_VERS: msg = "unsupported version"; break;
3619 if (msg == (char *) 0)
3620 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3621 else
3622 fatal ("%s", msg);
3626 /* Read a file into a memory buffer. */
3628 static struct file_info *
3629 read_file (name, fd, rw)
3630 char *name; /* filename */
3631 int fd; /* file descriptor */
3632 int rw; /* read/write */
3634 struct stat stat_pkt;
3635 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3636 #ifdef USE_MMAP
3637 static int page_size;
3638 #endif
3640 if (fstat (fd, &stat_pkt) < 0)
3641 fatal_perror ("fstat %s", name);
3643 p->name = name;
3644 p->size = stat_pkt.st_size;
3645 p->rounded_size = stat_pkt.st_size;
3646 p->fd = fd;
3647 p->rw = rw;
3649 #ifdef USE_MMAP
3650 if (debug)
3651 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3653 if (page_size == 0)
3654 page_size = sysconf (_SC_PAGE_SIZE);
3656 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3657 p->start = mmap ((caddr_t) 0,
3658 (rw) ? p->rounded_size : p->size,
3659 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3660 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3662 0L);
3664 if (p->start != (char *) 0 && p->start != (char *) -1)
3665 p->use_mmap = 1;
3667 else
3668 #endif /* USE_MMAP */
3670 long len;
3672 if (debug)
3673 fprintf (stderr, "read %s\n", name);
3675 p->use_mmap = 0;
3676 p->start = xmalloc (p->size);
3677 if (lseek (fd, 0L, SEEK_SET) < 0)
3678 fatal_perror ("lseek to 0 on %s", name);
3680 len = read (fd, p->start, p->size);
3681 if (len < 0)
3682 fatal_perror ("read %s", name);
3684 if (len != p->size)
3685 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3688 return p;
3691 /* Do anything necessary to write a file back from memory. */
3693 static void
3694 end_file (ptr)
3695 struct file_info *ptr; /* file information block */
3697 #ifdef USE_MMAP
3698 if (ptr->use_mmap)
3700 if (ptr->rw)
3702 if (debug)
3703 fprintf (stderr, "msync %s\n", ptr->name);
3705 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3706 fatal_perror ("msync %s", ptr->name);
3709 if (debug)
3710 fprintf (stderr, "munmap %s\n", ptr->name);
3712 if (munmap (ptr->start, ptr->size))
3713 fatal_perror ("munmap %s", ptr->name);
3715 else
3716 #endif /* USE_MMAP */
3718 if (ptr->rw)
3720 long len;
3722 if (debug)
3723 fprintf (stderr, "write %s\n", ptr->name);
3725 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3726 fatal_perror ("lseek to 0 on %s", ptr->name);
3728 len = write (ptr->fd, ptr->start, ptr->size);
3729 if (len < 0)
3730 fatal_perror ("write %s", ptr->name);
3732 if (len != ptr->size)
3733 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3736 free (ptr->start);
3739 free (ptr);
3742 #endif /* OBJECT_FORMAT_ROSE */