allow all arm targets to use -mstructure-size-boundary=XX
[official-gcc.git] / gcc / collect2.c
blobfbd59648c936b506c1911d0bafea0dba0b174977
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93-98, 1999 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>
32 #ifdef vfork /* Autoconf may define this to fork for us. */
33 # define VFORK_STRING "fork"
34 #else
35 # define VFORK_STRING "vfork"
36 #endif
37 #ifdef HAVE_VFORK_H
38 #include <vfork.h>
39 #endif
40 #ifdef VMS
41 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
42 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
43 #endif /* VMS */
45 #define COLLECT
47 #include "collect2.h"
48 #include "demangle.h"
49 #include "obstack.h"
50 #include "intl.h"
52 #ifndef DIR_SEPARATOR
53 # define DIR_SEPARATOR '/'
54 # define IS_DIR_SEPARATOR(ch) ((ch) == '/')
55 #else /* DIR_SEPARATOR */
56 # ifndef DIR_SEPARATOR_2
57 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
58 # else /* DIR_SEPARATOR && DIR_SEPARATOR_2 */
59 # define IS_DIR_SEPARATOR(ch) \
60 (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
61 # endif /* DIR_SEPARATOR && DIR_SEPARATOR_2 */
62 #endif /* DIR_SEPARATOR */
64 /* Obstack allocation and deallocation routines. */
65 #define obstack_chunk_alloc xmalloc
66 #define obstack_chunk_free free
68 /* On certain systems, we have code that works by scanning the object file
69 directly. But this code uses system-specific header files and library
70 functions, so turn it off in a cross-compiler. Likewise, the names of
71 the utilities are not correct for a cross-compiler; we have to hope that
72 cross-versions are in the proper directories. */
74 #ifdef CROSS_COMPILE
75 #undef SUNOS4_SHARED_LIBRARIES
76 #undef OBJECT_FORMAT_COFF
77 #undef OBJECT_FORMAT_ROSE
78 #undef MD_EXEC_PREFIX
79 #undef REAL_LD_FILE_NAME
80 #undef REAL_NM_FILE_NAME
81 #undef REAL_STRIP_FILE_NAME
82 #endif
84 /* If we cannot use a special method, use the ordinary one:
85 run nm to find what symbols are present.
86 In a cross-compiler, this means you need a cross nm,
87 but that is not quite as unpleasant as special headers. */
89 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
90 #define OBJECT_FORMAT_NONE
91 #endif
93 #ifdef OBJECT_FORMAT_COFF
95 #include <a.out.h>
96 #include <ar.h>
98 #ifdef UMAX
99 #include <sgs.h>
100 #endif
102 /* Many versions of ldfcn.h define these. */
103 #ifdef FREAD
104 #undef FREAD
105 #undef FWRITE
106 #endif
108 #include <ldfcn.h>
110 /* Some systems have an ISCOFF macro, but others do not. In some cases
111 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
112 that either do not have an ISCOFF macro in /usr/include or for those
113 where it is wrong. */
115 #ifndef MY_ISCOFF
116 #define MY_ISCOFF(X) ISCOFF (X)
117 #endif
119 #endif /* OBJECT_FORMAT_COFF */
121 #ifdef OBJECT_FORMAT_ROSE
123 #ifdef _OSF_SOURCE
124 #define USE_MMAP
125 #endif
127 #ifdef USE_MMAP
128 #include <sys/mman.h>
129 #endif
131 #include <unistd.h>
132 #include <mach_o_format.h>
133 #include <mach_o_header.h>
134 #include <mach_o_vals.h>
135 #include <mach_o_types.h>
137 #endif /* OBJECT_FORMAT_ROSE */
139 #ifdef OBJECT_FORMAT_NONE
141 /* Default flags to pass to nm. */
142 #ifndef NM_FLAGS
143 #define NM_FLAGS "-n"
144 #endif
146 #endif /* OBJECT_FORMAT_NONE */
148 /* Some systems use __main in a way incompatible with its use in gcc, in these
149 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
150 give the same symbol without quotes for an alternative entry point. You
151 must define both, or neither. */
152 #ifndef NAME__MAIN
153 #define NAME__MAIN "__main"
154 #define SYMBOL__MAIN __main
155 #endif
157 /* This must match tree.h. */
158 #define DEFAULT_INIT_PRIORITY 65535
160 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
161 #define SCAN_LIBRARIES
162 #endif
164 #ifdef USE_COLLECT2
165 int do_collecting = 1;
166 #else
167 int do_collecting = 0;
168 #endif
170 /* Linked lists of constructor and destructor names. */
172 struct id
174 struct id *next;
175 int sequence;
176 char name[1];
179 struct head
181 struct id *first;
182 struct id *last;
183 int number;
186 /* Enumeration giving which pass this is for scanning the program file. */
188 enum pass {
189 PASS_FIRST, /* without constructors */
190 PASS_OBJ, /* individual objects */
191 PASS_LIB, /* looking for shared libraries */
192 PASS_SECOND /* with constructors linked in */
195 extern char *version_string;
197 int vflag; /* true if -v */
198 static int rflag; /* true if -r */
199 static int strip_flag; /* true if -s */
200 #ifdef COLLECT_EXPORT_LIST
201 static int export_flag; /* true if -bE */
202 static int aix64_flag; /* true if -b64 */
203 #endif
205 int debug; /* true if -debug */
207 static int shared_obj; /* true if -shared */
209 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
210 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
211 #ifdef COLLECT_EXPORT_LIST
212 static const char *export_file; /* <xxx>.x for AIX export list. */
213 static const char *import_file; /* <xxx>.p for AIX import list. */
214 #endif
215 const char *ldout; /* File for ld errors. */
216 static const char *output_file; /* Output file for ld. */
217 static const char *nm_file_name; /* pathname of nm */
218 #ifdef LDD_SUFFIX
219 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
220 #endif
221 static const char *strip_file_name; /* pathname of strip */
222 const char *c_file_name; /* pathname of gcc */
223 static char *initname, *fininame; /* names of init and fini funcs */
225 static struct head constructors; /* list of constructors found */
226 static struct head destructors; /* list of destructors found */
227 #ifdef COLLECT_EXPORT_LIST
228 static struct head exports; /* list of exported symbols */
229 static struct head imports; /* list of imported symbols */
230 static struct head undefined; /* list of undefined symbols */
231 #endif
232 static struct head frame_tables; /* list of frame unwind info tables */
234 struct obstack temporary_obstack;
235 struct obstack permanent_obstack;
236 char * temporary_firstobj;
238 /* Holds the return value of pexecute. */
239 int pexecute_pid;
241 /* Defined in the automatically-generated underscore.c. */
242 extern int prepends_underscore;
244 #ifndef GET_ENV_PATH_LIST
245 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
246 #endif
248 /* Structure to hold all the directories in which to search for files to
249 execute. */
251 struct prefix_list
253 const char *prefix; /* String to prepend to the path. */
254 struct prefix_list *next; /* Next in linked list. */
257 struct path_prefix
259 struct prefix_list *plist; /* List of prefixes to try */
260 int max_len; /* Max length of a prefix in PLIST */
261 const char *name; /* Name of this list (used in config stuff) */
264 #ifdef COLLECT_EXPORT_LIST
265 /* Lists to keep libraries to be scanned for global constructors/destructors. */
266 static struct head libs; /* list of libraries */
267 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
268 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
269 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
270 &libpath_lib_dirs, NULL};
271 static const char *libexts[3] = {"a", "so", NULL}; /* possible library extentions */
272 #endif
274 static void handler PROTO((int));
275 static int is_ctor_dtor PROTO((const char *));
276 static char *find_a_file PROTO((struct path_prefix *, const char *));
277 static void add_prefix PROTO((struct path_prefix *, const char *));
278 static void prefix_from_env PROTO((const char *, struct path_prefix *));
279 static void prefix_from_string PROTO((const char *, struct path_prefix *));
280 static void do_wait PROTO((const char *));
281 static void fork_execute PROTO((const char *, char **));
282 static void maybe_unlink PROTO((const char *));
283 static void add_to_list PROTO((struct head *, const char *));
284 static int extract_init_priority PROTO((const char *));
285 static void sort_ids PROTO((struct head *));
286 static void write_list PROTO((FILE *, const char *, struct id *));
287 #ifdef COLLECT_EXPORT_LIST
288 static void dump_list PROTO((FILE *, const char *, struct id *));
289 #endif
290 #if 0
291 static void dump_prefix_list PROTO((FILE *, const char *, struct prefix_list *));
292 #endif
293 static void write_list_with_asm PROTO((FILE *, const char *, struct id *));
294 static void write_c_file PROTO((FILE *, const char *));
295 static void write_c_file_stat PROTO((FILE *, const char *));
296 #ifndef LD_INIT_SWITCH
297 static void write_c_file_glob PROTO((FILE *, const char *));
298 #endif
299 static void scan_prog_file PROTO((const char *, enum pass));
300 #ifdef SCAN_LIBRARIES
301 static void scan_libraries PROTO((const char *));
302 #endif
303 #ifdef COLLECT_EXPORT_LIST
304 static int is_in_list PROTO((const char *, struct id *));
305 static void write_aix_file PROTO((FILE *, struct id *));
306 static char *resolve_lib_name PROTO((const char *));
307 static int use_import_list PROTO((const char *));
308 static int ignore_library PROTO((const char *));
309 #endif
310 static char *extract_string PROTO((const char **));
312 #ifdef NO_DUP2
314 dup2 (oldfd, newfd)
315 int oldfd;
316 int newfd;
318 int fdtmp[256];
319 int fdx = 0;
320 int fd;
322 if (oldfd == newfd)
323 return oldfd;
324 close (newfd);
325 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
326 fdtmp[fdx++] = fd;
327 while (fdx > 0)
328 close (fdtmp[--fdx]);
330 return fd;
332 #endif
334 /* Delete tempfiles and exit function. */
336 void
337 collect_exit (status)
338 int status;
340 if (c_file != 0 && c_file[0])
341 maybe_unlink (c_file);
343 if (o_file != 0 && o_file[0])
344 maybe_unlink (o_file);
346 #ifdef COLLECT_EXPORT_LIST
347 if (export_file != 0 && export_file[0])
348 maybe_unlink (export_file);
350 if (import_file != 0 && import_file[0])
351 maybe_unlink (import_file);
352 #endif
354 if (ldout != 0 && ldout[0])
356 dump_file (ldout);
357 maybe_unlink (ldout);
360 if (status != 0 && output_file != 0 && output_file[0])
361 maybe_unlink (output_file);
363 exit (status);
367 /* Notify user of a non-error. */
368 void
369 notice VPROTO((const char *msgid, ...))
371 #ifndef ANSI_PROTOTYPES
372 const char *msgid;
373 #endif
374 va_list ap;
376 VA_START (ap, msgid);
378 #ifndef ANSI_PROTOTYPES
379 msgid = va_arg (ap, const char *);
380 #endif
382 vfprintf (stderr, _(msgid), ap);
383 va_end (ap);
386 /* Die when sys call fails. */
388 void
389 fatal_perror VPROTO((const char * msgid, ...))
391 #ifndef ANSI_PROTOTYPES
392 const char *msgid;
393 #endif
394 int e = errno;
395 va_list ap;
397 VA_START (ap, msgid);
399 #ifndef ANSI_PROTOTYPES
400 msgid = va_arg (ap, const char *);
401 #endif
403 fprintf (stderr, "collect2: ");
404 vfprintf (stderr, _(msgid), ap);
405 fprintf (stderr, ": %s\n", xstrerror (e));
406 va_end (ap);
408 collect_exit (FATAL_EXIT_CODE);
411 /* Just die. */
413 void
414 fatal VPROTO((const char * msgid, ...))
416 #ifndef ANSI_PROTOTYPES
417 const char *msgid;
418 #endif
419 va_list ap;
421 VA_START (ap, msgid);
423 #ifndef ANSI_PROTOTYPES
424 msgid = va_arg (ap, const char *);
425 #endif
427 fprintf (stderr, "collect2: ");
428 vfprintf (stderr, _(msgid), ap);
429 fprintf (stderr, "\n");
430 va_end (ap);
432 collect_exit (FATAL_EXIT_CODE);
435 /* Write error message. */
437 void
438 error VPROTO((const char * msgid, ...))
440 #ifndef ANSI_PROTOTYPES
441 const char * msgid;
442 #endif
443 va_list ap;
445 VA_START (ap, msgid);
447 #ifndef ANSI_PROTOTYPES
448 msgid = va_arg (ap, const char *);
449 #endif
451 fprintf (stderr, "collect2: ");
452 vfprintf (stderr, _(msgid), ap);
453 fprintf (stderr, "\n");
454 va_end(ap);
457 /* In case obstack is linked in, and abort is defined to fancy_abort,
458 provide a default entry. */
460 void
461 fancy_abort ()
463 fatal ("internal error");
466 static void
467 handler (signo)
468 int signo;
470 if (c_file != 0 && c_file[0])
471 maybe_unlink (c_file);
473 if (o_file != 0 && o_file[0])
474 maybe_unlink (o_file);
476 if (ldout != 0 && ldout[0])
477 maybe_unlink (ldout);
479 #ifdef COLLECT_EXPORT_LIST
480 if (export_file != 0 && export_file[0])
481 maybe_unlink (export_file);
483 if (import_file != 0 && import_file[0])
484 maybe_unlink (import_file);
485 #endif
487 signal (signo, SIG_DFL);
488 kill (getpid (), signo);
493 file_exists (name)
494 const char *name;
496 return access (name, R_OK) == 0;
499 /* Parse a reasonable subset of shell quoting syntax. */
501 static char *
502 extract_string (pp)
503 const char **pp;
505 const char *p = *pp;
506 int backquote = 0;
507 int inside = 0;
509 for (;;)
511 char c = *p;
512 if (c == '\0')
513 break;
514 ++p;
515 if (backquote)
516 obstack_1grow (&temporary_obstack, c);
517 else if (! inside && c == ' ')
518 break;
519 else if (! inside && c == '\\')
520 backquote = 1;
521 else if (c == '\'')
522 inside = !inside;
523 else
524 obstack_1grow (&temporary_obstack, c);
527 obstack_1grow (&temporary_obstack, '\0');
528 *pp = p;
529 return obstack_finish (&temporary_obstack);
532 void
533 dump_file (name)
534 const char *name;
536 FILE *stream = fopen (name, "r");
537 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
539 if (stream == 0)
540 return;
541 while (1)
543 int c;
544 while (c = getc (stream),
545 c != EOF && (ISALNUM (c) || c == '_' || c == '$' || c == '.'))
546 obstack_1grow (&temporary_obstack, c);
547 if (obstack_object_size (&temporary_obstack) > 0)
549 const char *word, *p;
550 char *result;
551 obstack_1grow (&temporary_obstack, '\0');
552 word = obstack_finish (&temporary_obstack);
554 if (*word == '.')
555 ++word, putc ('.', stderr);
556 p = word;
557 if (*p == '_' && prepends_underscore)
558 ++p;
560 if (no_demangle)
561 result = 0;
562 else
563 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
565 if (result)
567 int diff;
568 fputs (result, stderr);
570 diff = strlen (word) - strlen (result);
571 while (diff > 0)
572 --diff, putc (' ', stderr);
573 while (diff < 0 && c == ' ')
574 ++diff, c = getc (stream);
576 free (result);
578 else
579 fputs (word, stderr);
581 fflush (stderr);
582 obstack_free (&temporary_obstack, temporary_firstobj);
584 if (c == EOF)
585 break;
586 putc (c, stderr);
588 fclose (stream);
591 /* Decide whether the given symbol is:
592 a constructor (1), a destructor (2), or neither (0). */
594 static int
595 is_ctor_dtor (s)
596 const char *s;
598 struct names { const char *name; int len; int ret; int two_underscores; };
600 register struct names *p;
601 register int ch;
602 register const char *orig_s = s;
604 static struct names special[] = {
605 #ifdef NO_DOLLAR_IN_LABEL
606 #ifdef NO_DOT_IN_LABEL
607 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
608 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
609 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
610 #else
611 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
612 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
613 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
614 #endif
615 #else
616 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
617 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
618 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
619 #endif
620 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
621 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
622 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
623 cfront has its own linker procedure to collect them;
624 if collect2 gets them too, they get collected twice
625 when the cfront procedure is run and the compiler used
626 for linking happens to be GCC. */
627 { "sti__", sizeof ("sti__")-1, 1, 1 },
628 { "std__", sizeof ("std__")-1, 2, 1 },
629 #endif /* CFRONT_LOSSAGE */
630 { NULL, 0, 0, 0 }
633 while ((ch = *s) == '_')
634 ++s;
636 if (s == orig_s)
637 return 0;
639 for (p = &special[0]; p->len > 0; p++)
641 if (ch == p->name[0]
642 && (!p->two_underscores || ((s - orig_s) >= 2))
643 && strncmp(s, p->name, p->len) == 0)
645 return p->ret;
648 return 0;
651 /* By default, colon separates directories in a path. */
652 #ifndef PATH_SEPARATOR
653 #define PATH_SEPARATOR ':'
654 #endif
656 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
657 and one from the PATH variable. */
659 static struct path_prefix cpath, path;
661 #ifdef CROSS_COMPILE
662 /* This is the name of the target machine. We use it to form the name
663 of the files to execute. */
665 static const char *const target_machine = TARGET_MACHINE;
666 #endif
668 /* Search for NAME using prefix list PPREFIX. We only look for executable
669 files.
671 Return 0 if not found, otherwise return its name, allocated with malloc. */
673 static char *
674 find_a_file (pprefix, name)
675 struct path_prefix *pprefix;
676 const char *name;
678 char *temp;
679 struct prefix_list *pl;
680 int len = pprefix->max_len + strlen (name) + 1;
682 if (debug)
683 fprintf (stderr, "Looking for '%s'\n", name);
685 #ifdef EXECUTABLE_SUFFIX
686 len += strlen (EXECUTABLE_SUFFIX);
687 #endif
689 temp = xmalloc (len);
691 /* Determine the filename to execute (special case for absolute paths). */
693 if (*name == '/'
694 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
695 || (*name && name[1] == ':')
696 #endif
699 if (access (name, X_OK) == 0)
701 strcpy (temp, name);
703 if (debug)
704 fprintf (stderr, " - found: absolute path\n");
706 return temp;
709 #ifdef EXECUTABLE_SUFFIX
710 /* Some systems have a suffix for executable files.
711 So try appending that. */
712 strcpy (temp, name);
713 strcat (temp, EXECUTABLE_SUFFIX);
715 if (access (temp, X_OK) == 0)
716 return temp;
717 #endif
719 if (debug)
720 fprintf (stderr, " - failed to locate using absolute path\n");
722 else
723 for (pl = pprefix->plist; pl; pl = pl->next)
725 struct stat st;
727 strcpy (temp, pl->prefix);
728 strcat (temp, name);
730 if (stat (temp, &st) >= 0
731 && ! S_ISDIR (st.st_mode)
732 && access (temp, X_OK) == 0)
733 return temp;
735 #ifdef EXECUTABLE_SUFFIX
736 /* Some systems have a suffix for executable files.
737 So try appending that. */
738 strcat (temp, EXECUTABLE_SUFFIX);
740 if (stat (temp, &st) >= 0
741 && ! S_ISDIR (st.st_mode)
742 && access (temp, X_OK) == 0)
743 return temp;
744 #endif
747 if (debug && pprefix->plist == NULL)
748 fprintf (stderr, " - failed: no entries in prefix list\n");
750 free (temp);
751 return 0;
754 /* Add an entry for PREFIX to prefix list PPREFIX. */
756 static void
757 add_prefix (pprefix, prefix)
758 struct path_prefix *pprefix;
759 const char *prefix;
761 struct prefix_list *pl, **prev;
762 int len;
764 if (pprefix->plist)
766 for (pl = pprefix->plist; pl->next; pl = pl->next)
768 prev = &pl->next;
770 else
771 prev = &pprefix->plist;
773 /* Keep track of the longest prefix */
775 len = strlen (prefix);
776 if (len > pprefix->max_len)
777 pprefix->max_len = len;
779 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
780 pl->prefix = xstrdup (prefix);
782 if (*prev)
783 pl->next = *prev;
784 else
785 pl->next = (struct prefix_list *) 0;
786 *prev = pl;
789 /* Take the value of the environment variable ENV, break it into a path, and
790 add of the entries to PPREFIX. */
792 static void
793 prefix_from_env (env, pprefix)
794 const char *env;
795 struct path_prefix *pprefix;
797 const char *p;
798 GET_ENV_PATH_LIST (p, env);
800 if (p)
801 prefix_from_string (p, pprefix);
804 static void
805 prefix_from_string (p, pprefix)
806 const char *p;
807 struct path_prefix *pprefix;
809 const char *startp, *endp;
810 char *nstore = (char *) xmalloc (strlen (p) + 3);
812 if (debug)
813 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
815 startp = endp = p;
816 while (1)
818 if (*endp == PATH_SEPARATOR || *endp == 0)
820 strncpy (nstore, startp, endp-startp);
821 if (endp == startp)
823 strcpy (nstore, "./");
825 else if (! IS_DIR_SEPARATOR (endp[-1]))
827 nstore[endp-startp] = DIR_SEPARATOR;
828 nstore[endp-startp+1] = 0;
830 else
831 nstore[endp-startp] = 0;
833 if (debug)
834 fprintf (stderr, " - add prefix: %s\n", nstore);
836 add_prefix (pprefix, nstore);
837 if (*endp == 0)
838 break;
839 endp = startp = endp + 1;
841 else
842 endp++;
846 /* Main program. */
848 int main PROTO ((int, char *[]));
850 main (argc, argv)
851 int argc;
852 char *argv[];
854 const char *ld_suffix = "ld";
855 const char *full_ld_suffix = ld_suffix;
856 const char *real_ld_suffix = "real-ld";
857 const char *collect_ld_suffix = "collect-ld";
858 const char *nm_suffix = "nm";
859 const char *full_nm_suffix = nm_suffix;
860 const char *gnm_suffix = "gnm";
861 const char *full_gnm_suffix = gnm_suffix;
862 #ifdef LDD_SUFFIX
863 const char *ldd_suffix = LDD_SUFFIX;
864 const char *full_ldd_suffix = ldd_suffix;
865 #endif
866 const char *strip_suffix = "strip";
867 const char *full_strip_suffix = strip_suffix;
868 const char *gstrip_suffix = "gstrip";
869 const char *full_gstrip_suffix = gstrip_suffix;
870 const char *arg;
871 FILE *outf;
872 #ifdef COLLECT_EXPORT_LIST
873 FILE *exportf;
874 FILE *importf;
875 #endif
876 const char *ld_file_name;
877 const char *p;
878 char **c_argv;
879 const char **c_ptr;
880 char **ld1_argv;
881 const char **ld1;
882 char **ld2_argv;
883 const char **ld2;
884 char **object_lst;
885 const char **object;
886 int first_file;
887 int num_c_args = argc+9;
889 #if defined (COLLECT2_HOST_INITIALIZATION)
890 /* Perform system dependant initialization, if neccessary. */
891 COLLECT2_HOST_INITIALIZATION;
892 #endif
894 #ifdef HAVE_LC_MESSAGES
895 setlocale (LC_MESSAGES, "");
896 #endif
897 (void) bindtextdomain (PACKAGE, localedir);
898 (void) textdomain (PACKAGE);
900 /* Do not invoke xcalloc before this point, since locale needs to be
901 set first, in case a diagnostic is issued. */
903 ld1 = (const char **)(ld1_argv = (char **) xcalloc(sizeof (char *), argc+3));
904 ld2 = (const char **)(ld2_argv = (char **) xcalloc(sizeof (char *), argc+6));
905 object = (const char **)(object_lst = (char **) xcalloc(sizeof (char *), argc));
907 #ifdef DEBUG
908 debug = 1;
909 #endif
911 /* Parse command line early for instances of -debug. This allows
912 the debug flag to be set before functions like find_a_file()
913 are called. */
915 int i;
917 for (i = 1; argv[i] != NULL; i ++)
918 if (! strcmp (argv[i], "-debug"))
919 debug = 1;
920 vflag = debug;
923 #ifndef DEFAULT_A_OUT_NAME
924 output_file = "a.out";
925 #else
926 output_file = DEFAULT_A_OUT_NAME;
927 #endif
929 obstack_begin (&temporary_obstack, 0);
930 obstack_begin (&permanent_obstack, 0);
931 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
933 current_demangling_style = gnu_demangling;
934 p = getenv ("COLLECT_GCC_OPTIONS");
935 while (p && *p)
937 const char *q = extract_string (&p);
938 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
939 num_c_args++;
941 obstack_free (&temporary_obstack, temporary_firstobj);
943 /* -fno-exceptions -w */
944 num_c_args += 2;
946 c_ptr = (const char **)
947 (c_argv = (char **) xcalloc (sizeof (char *), num_c_args));
949 if (argc < 2)
950 fatal ("no arguments");
952 #ifdef SIGQUIT
953 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
954 signal (SIGQUIT, handler);
955 #endif
956 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
957 signal (SIGINT, handler);
958 #ifdef SIGALRM
959 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
960 signal (SIGALRM, handler);
961 #endif
962 #ifdef SIGHUP
963 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
964 signal (SIGHUP, handler);
965 #endif
966 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
967 signal (SIGSEGV, handler);
968 #ifdef SIGBUS
969 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
970 signal (SIGBUS, handler);
971 #endif
973 /* Extract COMPILER_PATH and PATH into our prefix list. */
974 prefix_from_env ("COMPILER_PATH", &cpath);
975 prefix_from_env ("PATH", &path);
977 #ifdef CROSS_COMPILE
978 /* If we look for a program in the compiler directories, we just use
979 the short name, since these directories are already system-specific.
980 But it we look for a program in the system directories, we need to
981 qualify the program name with the target machine. */
983 full_ld_suffix = concat(target_machine, "-", ld_suffix, NULL);
985 #if 0
986 full_gld_suffix = concat (target_machine, "-", gld_suffix, NULL);
987 #endif
989 full_nm_suffix = concat (target_machine, "-", nm_suffix, NULL);
991 full_gnm_suffix = concat (target_machine, "-", gnm_suffix, NULL);
993 #ifdef LDD_SUFFIX
994 full_ldd_suffix = concat (target_machine, "-", ldd_suffix, NULL);
995 #endif
997 full_strip_suffix = concat (target_machine, "-", strip_suffix, NULL);
999 full_gstrip_suffix = concat (target_machine, "-", gstrip_suffix, NULL);
1000 #endif /* CROSS_COMPILE */
1002 /* Try to discover a valid linker/nm/strip to use. */
1004 /* Maybe we know the right file to use (if not cross). */
1005 ld_file_name = 0;
1006 #ifdef DEFAULT_LINKER
1007 if (access (DEFAULT_LINKER, X_OK) == 0)
1008 ld_file_name = DEFAULT_LINKER;
1009 if (ld_file_name == 0)
1010 #endif
1011 #ifdef REAL_LD_FILE_NAME
1012 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1013 if (ld_file_name == 0)
1014 #endif
1015 /* Search the (target-specific) compiler dirs for ld'. */
1016 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1017 /* Likewise for `collect-ld'. */
1018 if (ld_file_name == 0)
1019 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1020 /* Search the compiler directories for `ld'. We have protection against
1021 recursive calls in find_a_file. */
1022 if (ld_file_name == 0)
1023 ld_file_name = find_a_file (&cpath, ld_suffix);
1024 /* Search the ordinary system bin directories
1025 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1026 if (ld_file_name == 0)
1027 ld_file_name = find_a_file (&path, full_ld_suffix);
1029 #ifdef REAL_NM_FILE_NAME
1030 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1031 if (nm_file_name == 0)
1032 #endif
1033 nm_file_name = find_a_file (&cpath, gnm_suffix);
1034 if (nm_file_name == 0)
1035 nm_file_name = find_a_file (&path, full_gnm_suffix);
1036 if (nm_file_name == 0)
1037 nm_file_name = find_a_file (&cpath, nm_suffix);
1038 if (nm_file_name == 0)
1039 nm_file_name = find_a_file (&path, full_nm_suffix);
1041 #ifdef LDD_SUFFIX
1042 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1043 if (ldd_file_name == 0)
1044 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1045 #endif
1047 #ifdef REAL_STRIP_FILE_NAME
1048 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1049 if (strip_file_name == 0)
1050 #endif
1051 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1052 if (strip_file_name == 0)
1053 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1054 if (strip_file_name == 0)
1055 strip_file_name = find_a_file (&cpath, strip_suffix);
1056 if (strip_file_name == 0)
1057 strip_file_name = find_a_file (&path, full_strip_suffix);
1059 /* Determine the full path name of the C compiler to use. */
1060 c_file_name = getenv ("COLLECT_GCC");
1061 if (c_file_name == 0)
1063 #ifdef CROSS_COMPILE
1064 c_file_name = concat (target_machine, "-gcc", NULL);
1065 #else
1066 c_file_name = "gcc";
1067 #endif
1070 p = find_a_file (&cpath, c_file_name);
1072 /* Here it should be safe to use the system search path since we should have
1073 already qualified the name of the compiler when it is needed. */
1074 if (p == 0)
1075 p = find_a_file (&path, c_file_name);
1077 if (p)
1078 c_file_name = p;
1080 *ld1++ = *ld2++ = ld_file_name;
1082 /* Make temp file names. */
1083 c_file = make_temp_file (".c");
1084 o_file = make_temp_file (".o");
1085 #ifdef COLLECT_EXPORT_LIST
1086 export_file = make_temp_file (".x");
1087 import_file = make_temp_file (".p");
1088 #endif
1089 ldout = make_temp_file (".ld");
1090 *c_ptr++ = c_file_name;
1091 *c_ptr++ = "-x";
1092 *c_ptr++ = "c";
1093 *c_ptr++ = "-c";
1094 *c_ptr++ = "-o";
1095 *c_ptr++ = o_file;
1097 #ifdef COLLECT_EXPORT_LIST
1098 /* Generate a list of directories from LIBPATH. */
1099 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1100 /* Add to this list also two standard directories where
1101 AIX loader always searches for libraries. */
1102 add_prefix (&libpath_lib_dirs, "/lib");
1103 add_prefix (&libpath_lib_dirs, "/usr/lib");
1104 #endif
1106 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1108 AIX support needs to know if -shared has been specified before
1109 parsing commandline arguments. */
1111 p = getenv ("COLLECT_GCC_OPTIONS");
1112 while (p && *p)
1114 const char *q = extract_string (&p);
1115 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1116 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1117 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1118 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1119 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1120 shared_obj = 1;
1122 obstack_free (&temporary_obstack, temporary_firstobj);
1123 *c_ptr++ = "-fno-exceptions";
1124 *c_ptr++ = "-w";
1126 /* !!! When GCC calls collect2,
1127 it does not know whether it is calling collect2 or ld.
1128 So collect2 cannot meaningfully understand any options
1129 except those ld understands.
1130 If you propose to make GCC pass some other option,
1131 just imagine what will happen if ld is really ld!!! */
1133 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1134 /* After the first file, put in the c++ rt0. */
1136 first_file = 1;
1137 while ((arg = *++argv) != (char *) 0)
1139 *ld1++ = *ld2++ = arg;
1141 if (arg[0] == '-')
1143 switch (arg[1])
1145 #ifdef COLLECT_EXPORT_LIST
1146 /* We want to disable automatic exports on AIX when user
1147 explicitly puts an export list in command line */
1148 case 'b':
1149 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1150 export_flag = 1;
1151 else if (arg[2] == '6' && arg[3] == '4')
1152 aix64_flag = 1;
1153 break;
1154 #endif
1156 case 'd':
1157 if (!strcmp (arg, "-debug"))
1159 /* Already parsed. */
1160 ld1--;
1161 ld2--;
1163 break;
1165 case 'l':
1166 if (first_file)
1168 /* place o_file BEFORE this argument! */
1169 first_file = 0;
1170 ld2--;
1171 *ld2++ = o_file;
1172 *ld2++ = arg;
1174 #ifdef COLLECT_EXPORT_LIST
1176 /* Resolving full library name. */
1177 const char *s = resolve_lib_name (arg+2);
1179 /* If we will use an import list for this library,
1180 we should exclude it from ld args. */
1181 if (use_import_list (s))
1183 ld1--;
1184 ld2--;
1187 /* Saving a full library name. */
1188 add_to_list (&libs, s);
1190 #endif
1191 break;
1193 #ifdef COLLECT_EXPORT_LIST
1194 /* Saving directories where to search for libraries. */
1195 case 'L':
1196 add_prefix (&cmdline_lib_dirs, arg+2);
1197 break;
1198 #endif
1200 case 'o':
1201 if (arg[2] == '\0')
1202 output_file = *ld1++ = *ld2++ = *++argv;
1203 else
1204 output_file = &arg[2];
1205 break;
1207 case 'r':
1208 if (arg[2] == '\0')
1209 rflag = 1;
1210 break;
1212 case 's':
1213 if (arg[2] == '\0' && do_collecting)
1215 /* We must strip after the nm run, otherwise C++ linking
1216 will not work. Thus we strip in the second ld run, or
1217 else with strip if there is no second ld run. */
1218 strip_flag = 1;
1219 ld1--;
1221 break;
1223 case 'v':
1224 if (arg[2] == '\0')
1225 vflag = 1;
1226 break;
1229 else if ((p = rindex (arg, '.')) != (char *) 0
1230 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1231 || strcmp (p, ".so") == 0))
1233 if (first_file)
1235 first_file = 0;
1236 if (p[1] == 'o')
1237 *ld2++ = o_file;
1238 else
1240 /* place o_file BEFORE this argument! */
1241 ld2--;
1242 *ld2++ = o_file;
1243 *ld2++ = arg;
1246 if (p[1] == 'o')
1247 *object++ = arg;
1248 #ifdef COLLECT_EXPORT_LIST
1249 /* libraries can be specified directly, i.e. without -l flag. */
1250 else
1252 /* If we will use an import list for this library,
1253 we should exclude it from ld args. */
1254 if (use_import_list (arg))
1256 ld1--;
1257 ld2--;
1260 /* Saving a full library name. */
1261 add_to_list (&libs, arg);
1263 #endif
1267 #ifdef COLLECT_EXPORT_LIST
1268 /* This is added only for debugging purposes. */
1269 if (debug)
1271 fprintf (stderr, "List of libraries:\n");
1272 dump_list (stderr, "\t", libs.first);
1275 /* The AIX linker will discard static constructors in object files if
1276 nothing else in the file is referenced, so look at them first. */
1278 char **export_object_lst = object_lst;
1280 while (export_object_lst < object)
1281 scan_prog_file (*export_object_lst++, PASS_OBJ);
1284 struct id *list = libs.first;
1286 for (; list; list = list->next)
1287 scan_prog_file (list->name, PASS_FIRST);
1290 if (exports.first)
1292 char *buf = xmalloc (strlen (export_file) + 5);
1294 sprintf (buf, "-bE:%s", export_file);
1295 *ld1++ = buf;
1296 *ld2++ = buf;
1298 exportf = fopen (export_file, "w");
1299 if (exportf == (FILE *) 0)
1300 fatal_perror ("fopen %s", export_file);
1301 write_aix_file (exportf, exports.first);
1302 if (fclose (exportf))
1303 fatal_perror ("fclose %s", export_file);
1306 if (imports.first)
1308 char *buf = xmalloc (strlen (import_file) + 5);
1310 sprintf (buf, "-bI:%s", import_file);
1311 *ld1++ = buf;
1312 *ld2++ = buf;
1314 importf = fopen (import_file, "w");
1315 if (importf == (FILE *) 0)
1316 fatal_perror ("%s", import_file);
1317 fputs ("#! .\n", importf);
1318 write_aix_file (importf, imports.first);
1319 if (fclose (importf))
1320 fatal_perror ("fclose %s", import_file);
1322 #endif
1324 *c_ptr++ = c_file;
1325 *c_ptr = *ld1 = *object = (char *) 0;
1327 if (vflag)
1329 notice ("collect2 version %s", version_string);
1330 #ifdef TARGET_VERSION
1331 TARGET_VERSION;
1332 #endif
1333 fprintf (stderr, "\n");
1336 if (debug)
1338 const char *ptr;
1339 fprintf (stderr, "ld_file_name = %s\n",
1340 (ld_file_name ? ld_file_name : "not found"));
1341 fprintf (stderr, "c_file_name = %s\n",
1342 (c_file_name ? c_file_name : "not found"));
1343 fprintf (stderr, "nm_file_name = %s\n",
1344 (nm_file_name ? nm_file_name : "not found"));
1345 #ifdef LDD_SUFFIX
1346 fprintf (stderr, "ldd_file_name = %s\n",
1347 (ldd_file_name ? ldd_file_name : "not found"));
1348 #endif
1349 fprintf (stderr, "strip_file_name = %s\n",
1350 (strip_file_name ? strip_file_name : "not found"));
1351 fprintf (stderr, "c_file = %s\n",
1352 (c_file ? c_file : "not found"));
1353 fprintf (stderr, "o_file = %s\n",
1354 (o_file ? o_file : "not found"));
1356 ptr = getenv ("COLLECT_GCC_OPTIONS");
1357 if (ptr)
1358 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1360 ptr = getenv ("COLLECT_GCC");
1361 if (ptr)
1362 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1364 ptr = getenv ("COMPILER_PATH");
1365 if (ptr)
1366 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1368 ptr = getenv ("LIBRARY_PATH");
1369 if (ptr)
1370 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1372 fprintf (stderr, "\n");
1375 /* Load the program, searching all libraries and attempting to provide
1376 undefined symbols from repository information. */
1378 /* On AIX we do this later. */
1379 #ifndef COLLECT_EXPORT_LIST
1380 do_tlink (ld1_argv, object_lst);
1381 #endif
1383 /* If -r or they will be run via some other method, do not build the
1384 constructor or destructor list, just return now. */
1385 if (rflag
1386 #ifndef COLLECT_EXPORT_LIST
1387 || ! do_collecting
1388 #endif
1391 #ifdef COLLECT_EXPORT_LIST
1392 /* Do the link we avoided above if we are exiting. */
1393 do_tlink (ld1_argv, object_lst);
1395 /* But make sure we delete the export file we may have created. */
1396 if (export_file != 0 && export_file[0])
1397 maybe_unlink (export_file);
1398 if (import_file != 0 && import_file[0])
1399 maybe_unlink (import_file);
1400 #endif
1401 maybe_unlink (c_file);
1402 maybe_unlink (o_file);
1403 return 0;
1406 /* Examine the namelist with nm and search it for static constructors
1407 and destructors to call.
1408 Write the constructor and destructor tables to a .s file and reload. */
1410 /* On AIX we already scanned for global constructors/destructors. */
1411 #ifndef COLLECT_EXPORT_LIST
1412 scan_prog_file (output_file, PASS_FIRST);
1413 #endif
1415 #ifdef SCAN_LIBRARIES
1416 scan_libraries (output_file);
1417 #endif
1419 if (debug)
1421 notice ("%d constructor(s) found\n", constructors.number);
1422 notice ("%d destructor(s) found\n", destructors.number);
1423 notice ("%d frame table(s) found\n", frame_tables.number);
1426 if (constructors.number == 0 && destructors.number == 0
1427 && frame_tables.number == 0
1428 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1429 /* If we will be running these functions ourselves, we want to emit
1430 stubs into the shared library so that we do not have to relink
1431 dependent programs when we add static objects. */
1432 && ! shared_obj
1433 #endif
1436 #ifdef COLLECT_EXPORT_LIST
1437 /* Do tlink without additional code generation */
1438 do_tlink (ld1_argv, object_lst);
1439 #endif
1440 /* Strip now if it was requested on the command line. */
1441 if (strip_flag)
1443 char **real_strip_argv = (char **) xcalloc (sizeof (char *), 3);
1444 const char ** strip_argv = (const char **) real_strip_argv;
1446 strip_argv[0] = strip_file_name;
1447 strip_argv[1] = output_file;
1448 strip_argv[2] = (char *) 0;
1449 fork_execute ("strip", real_strip_argv);
1452 #ifdef COLLECT_EXPORT_LIST
1453 maybe_unlink (export_file);
1454 maybe_unlink (import_file);
1455 #endif
1456 maybe_unlink (c_file);
1457 maybe_unlink (o_file);
1458 return 0;
1461 /* Sort ctor and dtor lists by priority. */
1462 sort_ids (&constructors);
1463 sort_ids (&destructors);
1465 maybe_unlink(output_file);
1466 outf = fopen (c_file, "w");
1467 if (outf == (FILE *) 0)
1468 fatal_perror ("fopen %s", c_file);
1470 write_c_file (outf, c_file);
1472 if (fclose (outf))
1473 fatal_perror ("fclose %s", c_file);
1475 /* Tell the linker that we have initializer and finalizer functions. */
1476 #ifdef LD_INIT_SWITCH
1477 *ld2++ = LD_INIT_SWITCH;
1478 *ld2++ = initname;
1479 *ld2++ = LD_FINI_SWITCH;
1480 *ld2++ = fininame;
1481 #endif
1483 #ifdef COLLECT_EXPORT_LIST
1484 if (shared_obj)
1486 /* If we did not add export flag to link arguments before, add it to
1487 second link phase now. No new exports should have been added. */
1488 if (! exports.first)
1490 char *buf = xmalloc (strlen (export_file) + 5);
1492 sprintf (buf, "-bE:%s", export_file);
1493 *ld2++ = buf;
1496 add_to_list (&exports, initname);
1497 add_to_list (&exports, fininame);
1498 add_to_list (&exports, "_GLOBAL__DI");
1499 add_to_list (&exports, "_GLOBAL__DD");
1500 exportf = fopen (export_file, "w");
1501 if (exportf == (FILE *) 0)
1502 fatal_perror ("fopen %s", export_file);
1503 write_aix_file (exportf, exports.first);
1504 if (fclose (exportf))
1505 fatal_perror ("fclose %s", export_file);
1507 #endif
1509 /* End of arguments to second link phase. */
1510 *ld2 = (char*) 0;
1512 if (debug)
1514 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1515 output_file, c_file);
1516 write_c_file (stderr, "stderr");
1517 fprintf (stderr, "========== end of c_file\n\n");
1518 #ifdef COLLECT_EXPORT_LIST
1519 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1520 write_aix_file (stderr, exports.first);
1521 fprintf (stderr, "========== end of export_file\n\n");
1522 #endif
1525 /* Assemble the constructor and destructor tables.
1526 Link the tables in with the rest of the program. */
1528 fork_execute ("gcc", c_argv);
1529 #ifdef COLLECT_EXPORT_LIST
1530 /* On AIX we must call tlink because of possible templates resolution */
1531 do_tlink (ld2_argv, object_lst);
1532 #else
1533 /* Otherwise, simply call ld because tlink is already done */
1534 fork_execute ("ld", ld2_argv);
1536 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1537 constructors/destructors in shared libraries. */
1538 scan_prog_file (output_file, PASS_SECOND);
1539 #endif
1541 maybe_unlink (c_file);
1542 maybe_unlink (o_file);
1544 #ifdef COLLECT_EXPORT_LIST
1545 maybe_unlink (export_file);
1546 maybe_unlink (import_file);
1547 #endif
1549 return 0;
1553 /* Wait for a process to finish, and exit if a non-zero status is found. */
1556 collect_wait (prog)
1557 const char *prog;
1559 int status;
1561 pwait (pexecute_pid, &status, 0);
1562 if (status)
1564 if (WIFSIGNALED (status))
1566 int sig = WTERMSIG (status);
1567 error ((status & 0200
1568 ? "%s terminated with signal %d [%s]"
1569 : "%s terminated with signal %d [%s], core dumped"),
1570 prog,
1571 sig,
1572 strsignal(sig));
1573 collect_exit (FATAL_EXIT_CODE);
1576 if (WIFEXITED (status))
1577 return WEXITSTATUS (status);
1579 return 0;
1582 static void
1583 do_wait (prog)
1584 const char *prog;
1586 int ret = collect_wait (prog);
1587 if (ret != 0)
1589 error ("%s returned %d exit status", prog, ret);
1590 collect_exit (ret);
1595 /* Execute a program, and wait for the reply. */
1597 void
1598 collect_execute (prog, argv, redir)
1599 const char *prog;
1600 char **argv;
1601 const char *redir;
1603 char *errmsg_fmt;
1604 char *errmsg_arg;
1605 int redir_handle = -1;
1606 int stdout_save = -1;
1607 int stderr_save = -1;
1609 if (vflag || debug)
1611 char **p_argv;
1612 const char *str;
1614 if (argv[0])
1615 fprintf (stderr, "%s", argv[0]);
1616 else
1617 notice ("[cannot find %s]", prog);
1619 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1620 fprintf (stderr, " %s", str);
1622 fprintf (stderr, "\n");
1625 fflush (stdout);
1626 fflush (stderr);
1628 /* If we cannot find a program we need, complain error. Do this here
1629 since we might not end up needing something that we could not find. */
1631 if (argv[0] == 0)
1632 fatal ("cannot find `%s'", prog);
1634 if (redir)
1636 /* Open response file. */
1637 redir_handle = open (redir, O_WRONLY | O_TRUNC | O_CREAT);
1639 /* Duplicate the stdout and stderr file handles
1640 so they can be restored later. */
1641 stdout_save = dup (STDOUT_FILENO);
1642 if (stdout_save == -1)
1643 fatal_perror ("redirecting stdout: %s", redir);
1644 stderr_save = dup (STDERR_FILENO);
1645 if (stderr_save == -1)
1646 fatal_perror ("redirecting stdout: %s", redir);
1648 /* Redirect stdout & stderr to our response file. */
1649 dup2 (redir_handle, STDOUT_FILENO);
1650 dup2 (redir_handle, STDERR_FILENO);
1653 pexecute_pid = pexecute (argv[0], argv, argv[0], NULL,
1654 &errmsg_fmt, &errmsg_arg,
1655 (PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH));
1657 if (redir)
1659 /* Restore stdout and stderr to their previous settings. */
1660 dup2 (stdout_save, STDOUT_FILENO);
1661 dup2 (stderr_save, STDERR_FILENO);
1663 /* Close reponse file. */
1664 close (redir_handle);
1667 if (pexecute_pid == -1)
1668 fatal_perror (errmsg_fmt, errmsg_arg);
1671 static void
1672 fork_execute (prog, argv)
1673 const char *prog;
1674 char **argv;
1676 collect_execute (prog, argv, NULL);
1677 do_wait (prog);
1680 /* Unlink a file unless we are debugging. */
1682 static void
1683 maybe_unlink (file)
1684 const char *file;
1686 if (!debug)
1687 unlink (file);
1688 else
1689 notice ("[Leaving %s]\n", file);
1693 static long sequence_number = 0;
1695 /* Add a name to a linked list. */
1697 static void
1698 add_to_list (head_ptr, name)
1699 struct head *head_ptr;
1700 const char *name;
1702 struct id *newid
1703 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1704 struct id *p;
1705 strcpy (newid->name, name);
1707 if (head_ptr->first)
1708 head_ptr->last->next = newid;
1709 else
1710 head_ptr->first = newid;
1712 /* Check for duplicate symbols. */
1713 for (p = head_ptr->first;
1714 strcmp (name, p->name) != 0;
1715 p = p->next)
1717 if (p != newid)
1719 head_ptr->last->next = 0;
1720 free (newid);
1721 return;
1724 newid->sequence = ++sequence_number;
1725 head_ptr->last = newid;
1726 head_ptr->number++;
1729 /* Grab the init priority number from an init function name that
1730 looks like "_GLOBAL_.I.12345.foo". */
1732 static int
1733 extract_init_priority (name)
1734 const char *name;
1736 int pos = 0, pri;
1738 while (name[pos] == '_')
1739 ++pos;
1740 pos += 10; /* strlen ("GLOBAL__X_") */
1742 /* Extract init_p number from ctor/dtor name. */
1743 pri = atoi (name + pos);
1744 return pri ? pri : DEFAULT_INIT_PRIORITY;
1747 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1748 ctors will be run from right to left, dtors from left to right. */
1750 static void
1751 sort_ids (head_ptr)
1752 struct head *head_ptr;
1754 /* id holds the current element to insert. id_next holds the next
1755 element to insert. id_ptr iterates through the already sorted elements
1756 looking for the place to insert id. */
1757 struct id *id, *id_next, **id_ptr;
1759 id = head_ptr->first;
1761 /* We don't have any sorted elements yet. */
1762 head_ptr->first = NULL;
1764 for (; id; id = id_next)
1766 id_next = id->next;
1767 id->sequence = extract_init_priority (id->name);
1769 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1770 if (*id_ptr == NULL
1771 /* If the sequence numbers are the same, we put the id from the
1772 file later on the command line later in the list. */
1773 || id->sequence > (*id_ptr)->sequence
1774 /* Hack: do lexical compare, too.
1775 || (id->sequence == (*id_ptr)->sequence
1776 && strcmp (id->name, (*id_ptr)->name) > 0) */
1779 id->next = *id_ptr;
1780 *id_ptr = id;
1781 break;
1785 /* Now set the sequence numbers properly so write_c_file works. */
1786 for (id = head_ptr->first; id; id = id->next)
1787 id->sequence = ++sequence_number;
1790 /* Write: `prefix', the names on list LIST, `suffix'. */
1792 static void
1793 write_list (stream, prefix, list)
1794 FILE *stream;
1795 const char *prefix;
1796 struct id *list;
1798 while (list)
1800 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1801 list = list->next;
1805 #ifdef COLLECT_EXPORT_LIST
1806 /* This function is really used only on AIX, but may be useful. */
1807 static int
1808 is_in_list (prefix, list)
1809 const char *prefix;
1810 struct id *list;
1812 while (list)
1814 if (!strcmp (prefix, list->name)) return 1;
1815 list = list->next;
1817 return 0;
1819 #endif
1821 /* Added for debugging purpose. */
1822 #ifdef COLLECT_EXPORT_LIST
1823 static void
1824 dump_list (stream, prefix, list)
1825 FILE *stream;
1826 const char *prefix;
1827 struct id *list;
1829 while (list)
1831 fprintf (stream, "%s%s,\n", prefix, list->name);
1832 list = list->next;
1835 #endif
1837 #if 0
1838 static void
1839 dump_prefix_list (stream, prefix, list)
1840 FILE *stream;
1841 const char *prefix;
1842 struct prefix_list *list;
1844 while (list)
1846 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1847 list = list->next;
1850 #endif
1852 static void
1853 write_list_with_asm (stream, prefix, list)
1854 FILE *stream;
1855 const char *prefix;
1856 struct id *list;
1858 while (list)
1860 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1861 prefix, list->sequence, list->name);
1862 list = list->next;
1866 /* Write out the constructor and destructor tables statically (for a shared
1867 object), along with the functions to execute them. */
1869 static void
1870 write_c_file_stat (stream, name)
1871 FILE *stream;
1872 const char *name ATTRIBUTE_UNUSED;
1874 const char *p, *q;
1875 char *prefix, *r;
1876 int frames = (frame_tables.number > 0);
1878 /* Figure out name of output_file, stripping off .so version. */
1879 p = rindex (output_file, '/');
1880 if (p == 0)
1881 p = output_file;
1882 else
1883 p++;
1884 q = p;
1885 while (q)
1887 q = index (q,'.');
1888 if (q == 0)
1890 q = p + strlen (p);
1891 break;
1893 else
1895 if (strncmp (q, ".so", 3) == 0)
1897 q += 3;
1898 break;
1900 else
1901 q++;
1904 /* q points to null at end of the string (or . of the .so version) */
1905 prefix = xmalloc (q - p + 1);
1906 strncpy (prefix, p, q - p);
1907 prefix[q - p] = 0;
1908 for (r = prefix; *r; r++)
1909 if (!ISALNUM ((unsigned char)*r))
1910 *r = '_';
1911 if (debug)
1912 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1913 output_file, prefix);
1915 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1916 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1917 sprintf (initname, INIT_NAME_FORMAT, prefix);
1919 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1920 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1921 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1923 free (prefix);
1925 /* Write the tables as C code */
1927 fprintf (stream, "static int count;\n");
1928 fprintf (stream, "typedef void entry_pt();\n");
1929 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1931 if (frames)
1933 write_list_with_asm (stream, "extern void *", frame_tables.first);
1935 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1936 write_list (stream, "\t\t&", frame_tables.first);
1937 fprintf (stream, "\t0\n};\n");
1939 /* This must match what's in frame.h. */
1940 fprintf (stream, "struct object {\n");
1941 fprintf (stream, " void *pc_begin;\n");
1942 fprintf (stream, " void *pc_end;\n");
1943 fprintf (stream, " void *fde_begin;\n");
1944 fprintf (stream, " void *fde_array;\n");
1945 fprintf (stream, " __SIZE_TYPE__ count;\n");
1946 fprintf (stream, " struct object *next;\n");
1947 fprintf (stream, "};\n");
1949 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1950 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1952 fprintf (stream, "static void reg_frame () {\n");
1953 fprintf (stream, "\tstatic struct object ob;\n");
1954 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1955 fprintf (stream, "\t}\n");
1957 fprintf (stream, "static void dereg_frame () {\n");
1958 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1959 fprintf (stream, "\t}\n");
1962 fprintf (stream, "void %s() {\n", initname);
1963 if (constructors.number > 0 || frames)
1965 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1966 write_list (stream, "\t\t", constructors.first);
1967 if (frames)
1968 fprintf (stream, "\treg_frame,\n");
1969 fprintf (stream, "\t};\n");
1970 fprintf (stream, "\tentry_pt **p;\n");
1971 fprintf (stream, "\tif (count++ != 0) return;\n");
1972 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1973 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1975 else
1976 fprintf (stream, "\t++count;\n");
1977 fprintf (stream, "}\n");
1978 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1979 fprintf (stream, "void %s() {\n", fininame);
1980 if (destructors.number > 0 || frames)
1982 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1983 write_list (stream, "\t\t", destructors.first);
1984 if (frames)
1985 fprintf (stream, "\tdereg_frame,\n");
1986 fprintf (stream, "\t};\n");
1987 fprintf (stream, "\tentry_pt **p;\n");
1988 fprintf (stream, "\tif (--count != 0) return;\n");
1989 fprintf (stream, "\tp = dtors;\n");
1990 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1991 destructors.number + frames);
1993 fprintf (stream, "}\n");
1995 if (shared_obj)
1997 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
1998 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
2002 /* Write the constructor/destructor tables. */
2004 #ifndef LD_INIT_SWITCH
2005 static void
2006 write_c_file_glob (stream, name)
2007 FILE *stream;
2008 const char *name ATTRIBUTE_UNUSED;
2010 /* Write the tables as C code */
2012 int frames = (frame_tables.number > 0);
2014 fprintf (stream, "typedef void entry_pt();\n\n");
2016 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2018 if (frames)
2020 write_list_with_asm (stream, "extern void *", frame_tables.first);
2022 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2023 write_list (stream, "\t\t&", frame_tables.first);
2024 fprintf (stream, "\t0\n};\n");
2026 /* This must match what's in frame.h. */
2027 fprintf (stream, "struct object {\n");
2028 fprintf (stream, " void *pc_begin;\n");
2029 fprintf (stream, " void *pc_end;\n");
2030 fprintf (stream, " void *fde_begin;\n");
2031 fprintf (stream, " void *fde_array;\n");
2032 fprintf (stream, " __SIZE_TYPE__ count;\n");
2033 fprintf (stream, " struct object *next;\n");
2034 fprintf (stream, "};\n");
2036 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2037 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2039 fprintf (stream, "static void reg_frame () {\n");
2040 fprintf (stream, "\tstatic struct object ob;\n");
2041 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2042 fprintf (stream, "\t}\n");
2044 fprintf (stream, "static void dereg_frame () {\n");
2045 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2046 fprintf (stream, "\t}\n");
2049 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2050 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2051 write_list (stream, "\t", constructors.first);
2052 if (frames)
2053 fprintf (stream, "\treg_frame,\n");
2054 fprintf (stream, "\t0\n};\n\n");
2056 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2058 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2059 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2060 write_list (stream, "\t", destructors.first);
2061 if (frames)
2062 fprintf (stream, "\tdereg_frame,\n");
2063 fprintf (stream, "\t0\n};\n\n");
2065 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2066 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2068 #endif /* ! LD_INIT_SWITCH */
2070 static void
2071 write_c_file (stream, name)
2072 FILE *stream;
2073 const char *name;
2075 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2076 #ifndef LD_INIT_SWITCH
2077 if (! shared_obj)
2078 write_c_file_glob (stream, name);
2079 else
2080 #endif
2081 write_c_file_stat (stream, name);
2082 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2085 #ifdef COLLECT_EXPORT_LIST
2086 static void
2087 write_aix_file (stream, list)
2088 FILE *stream;
2089 struct id *list;
2091 for (; list; list = list->next)
2093 fputs (list->name, stream);
2094 putc ('\n', stream);
2097 #endif
2099 #ifdef OBJECT_FORMAT_NONE
2101 /* Generic version to scan the name list of the loaded program for
2102 the symbols g++ uses for static constructors and destructors.
2104 The constructor table begins at __CTOR_LIST__ and contains a count
2105 of the number of pointers (or -1 if the constructors are built in a
2106 separate section by the linker), followed by the pointers to the
2107 constructor functions, terminated with a null pointer. The
2108 destructor table has the same format, and begins at __DTOR_LIST__. */
2110 static void
2111 scan_prog_file (prog_name, which_pass)
2112 const char *prog_name;
2113 enum pass which_pass;
2115 void (*int_handler) PROTO ((int));
2116 void (*quit_handler) PROTO ((int));
2117 char *real_nm_argv[4];
2118 const char **nm_argv = (const char **) real_nm_argv;
2119 int pid;
2120 int argc = 0;
2121 int pipe_fd[2];
2122 char *p, buf[1024];
2123 FILE *inf;
2125 if (which_pass == PASS_SECOND)
2126 return;
2128 /* If we do not have an `nm', complain. */
2129 if (nm_file_name == 0)
2130 fatal ("cannot find `nm'");
2132 nm_argv[argc++] = nm_file_name;
2133 if (NM_FLAGS[0] != '\0')
2134 nm_argv[argc++] = NM_FLAGS;
2136 nm_argv[argc++] = prog_name;
2137 nm_argv[argc++] = (char *) 0;
2139 if (pipe (pipe_fd) < 0)
2140 fatal_perror ("pipe");
2142 inf = fdopen (pipe_fd[0], "r");
2143 if (inf == (FILE *) 0)
2144 fatal_perror ("fdopen");
2146 /* Trace if needed. */
2147 if (vflag)
2149 const char **p_argv;
2150 const char *str;
2152 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2153 fprintf (stderr, " %s", str);
2155 fprintf (stderr, "\n");
2158 fflush (stdout);
2159 fflush (stderr);
2161 /* Spawn child nm on pipe */
2162 pid = vfork ();
2163 if (pid == -1)
2164 fatal_perror (VFORK_STRING);
2166 if (pid == 0) /* child context */
2168 /* setup stdout */
2169 if (dup2 (pipe_fd[1], 1) < 0)
2170 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2172 if (close (pipe_fd[0]) < 0)
2173 fatal_perror ("close %d", pipe_fd[0]);
2175 if (close (pipe_fd[1]) < 0)
2176 fatal_perror ("close %d", pipe_fd[1]);
2178 execv (nm_file_name, real_nm_argv);
2179 fatal_perror ("execvp %s", nm_file_name);
2182 /* Parent context from here on. */
2183 int_handler = (void (*) PROTO ((int))) signal (SIGINT, SIG_IGN);
2184 #ifdef SIGQUIT
2185 quit_handler = (void (*) PROTO ((int))) signal (SIGQUIT, SIG_IGN);
2186 #endif
2188 if (close (pipe_fd[1]) < 0)
2189 fatal_perror ("close %d", pipe_fd[1]);
2191 if (debug)
2192 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2194 /* Read each line of nm output. */
2195 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2197 int ch, ch2;
2198 char *name, *end;
2200 /* If it contains a constructor or destructor name, add the name
2201 to the appropriate list. */
2203 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2204 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2205 break;
2207 if (ch != '_')
2208 continue;
2210 name = p;
2211 /* Find the end of the symbol name.
2212 Do not include `|', because Encore nm can tack that on the end. */
2213 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2214 end++)
2215 continue;
2218 *end = '\0';
2219 switch (is_ctor_dtor (name))
2221 case 1:
2222 if (which_pass != PASS_LIB)
2223 add_to_list (&constructors, name);
2224 break;
2226 case 2:
2227 if (which_pass != PASS_LIB)
2228 add_to_list (&destructors, name);
2229 break;
2231 case 3:
2232 if (which_pass != PASS_LIB)
2233 fatal ("init function found in object %s", prog_name);
2234 #ifndef LD_INIT_SWITCH
2235 add_to_list (&constructors, name);
2236 #endif
2237 break;
2239 case 4:
2240 if (which_pass != PASS_LIB)
2241 fatal ("fini function found in object %s", prog_name);
2242 #ifndef LD_FINI_SWITCH
2243 add_to_list (&destructors, name);
2244 #endif
2245 break;
2247 case 5:
2248 if (which_pass != PASS_LIB)
2249 add_to_list (&frame_tables, name);
2250 break;
2252 default: /* not a constructor or destructor */
2253 continue;
2256 if (debug)
2257 fprintf (stderr, "\t%s\n", buf);
2260 if (debug)
2261 fprintf (stderr, "\n");
2263 if (fclose (inf) != 0)
2264 fatal_perror ("fclose");
2266 do_wait (nm_file_name);
2268 signal (SIGINT, int_handler);
2269 #ifdef SIGQUIT
2270 signal (SIGQUIT, quit_handler);
2271 #endif
2274 #if SUNOS4_SHARED_LIBRARIES
2276 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2277 that the output file depends upon and their initialization/finalization
2278 routines, if any. */
2280 #include <a.out.h>
2281 #include <fcntl.h>
2282 #include <link.h>
2283 #include <sys/mman.h>
2284 #include <sys/param.h>
2285 #include <unistd.h>
2286 #include <sys/dir.h>
2288 /* pointers to the object file */
2289 unsigned object; /* address of memory mapped file */
2290 unsigned objsize; /* size of memory mapped to file */
2291 char * code; /* pointer to code segment */
2292 char * data; /* pointer to data segment */
2293 struct nlist *symtab; /* pointer to symbol table */
2294 struct link_dynamic *ld;
2295 struct link_dynamic_2 *ld_2;
2296 struct head libraries;
2298 /* Map the file indicated by NAME into memory and store its address. */
2300 static void mapfile PROTO ((const char *));
2302 static void
2303 mapfile (name)
2304 const char *name;
2306 int fp;
2307 struct stat s;
2308 if ((fp = open (name, O_RDONLY)) == -1)
2309 fatal ("unable to open file '%s'", name);
2310 if (fstat (fp, &s) == -1)
2311 fatal ("unable to stat file '%s'", name);
2313 objsize = s.st_size;
2314 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2315 fp, 0);
2316 if (object == (unsigned)-1)
2317 fatal ("unable to mmap file '%s'", name);
2319 close (fp);
2322 /* Helpers for locatelib. */
2324 static const char *libname;
2326 static int libselect PROTO ((struct direct *));
2328 static int
2329 libselect (d)
2330 struct direct *d;
2332 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2335 /* If one file has an additional numeric extension past LIBNAME, then put
2336 that one first in the sort. If both files have additional numeric
2337 extensions, then put the one with the higher number first in the sort.
2339 We must verify that the extension is numeric, because Sun saves the
2340 original versions of patched libraries with a .FCS extension. Files with
2341 invalid extensions must go last in the sort, so that they will not be used. */
2342 static int libcompare PROTO ((struct direct **, struct direct **));
2344 static int
2345 libcompare (d1, d2)
2346 struct direct **d1, **d2;
2348 int i1, i2 = strlen (libname);
2349 char *e1 = (*d1)->d_name + i2;
2350 char *e2 = (*d2)->d_name + i2;
2352 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2353 && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2355 ++e1;
2356 ++e2;
2357 i1 = strtol (e1, &e1, 10);
2358 i2 = strtol (e2, &e2, 10);
2359 if (i1 != i2)
2360 return i1 - i2;
2363 if (*e1)
2365 /* It has a valid numeric extension, prefer this one. */
2366 if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2367 return 1;
2368 /* It has a invalid numeric extension, must prefer the other one. */
2369 else
2370 return -1;
2372 else if (*e2)
2374 /* It has a valid numeric extension, prefer this one. */
2375 if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2376 return -1;
2377 /* It has a invalid numeric extension, must prefer the other one. */
2378 else
2379 return 1;
2381 else
2382 return 0;
2385 /* Given the name NAME of a dynamic dependency, find its pathname and add
2386 it to the list of libraries. */
2387 static void locatelib PROTO ((const char *));
2389 static void
2390 locatelib (name)
2391 const char *name;
2393 static const char **l;
2394 static int cnt;
2395 char buf[MAXPATHLEN];
2396 char *p, *q;
2397 const char **pp;
2399 if (l == 0)
2401 char *ld_rules;
2402 char *ldr = 0;
2403 /* counting elements in array, need 1 extra for null */
2404 cnt = 1;
2405 ld_rules = (char *) (ld_2->ld_rules + code);
2406 if (ld_rules)
2408 cnt++;
2409 for (; *ld_rules != 0; ld_rules++)
2410 if (*ld_rules == ':')
2411 cnt++;
2412 ld_rules = (char *) (ld_2->ld_rules + code);
2413 ldr = xstrdup (ld_rules);
2415 p = getenv ("LD_LIBRARY_PATH");
2416 q = 0;
2417 if (p)
2419 cnt++;
2420 for (q = p ; *q != 0; q++)
2421 if (*q == ':')
2422 cnt++;
2423 q = xstrdup (p);
2425 l = (const char **) xmalloc ((cnt + 3) * sizeof (char *));
2426 pp = l;
2427 if (ldr)
2429 *pp++ = ldr;
2430 for (; *ldr != 0; ldr++)
2431 if (*ldr == ':')
2433 *ldr++ = 0;
2434 *pp++ = ldr;
2437 if (q)
2439 *pp++ = q;
2440 for (; *q != 0; q++)
2441 if (*q == ':')
2443 *q++ = 0;
2444 *pp++ = q;
2447 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2448 *pp++ = "/lib";
2449 *pp++ = "/usr/lib";
2450 *pp++ = "/usr/local/lib";
2451 *pp = 0;
2453 libname = name;
2454 for (pp = l; *pp != 0 ; pp++)
2456 struct direct **namelist;
2457 int entries;
2458 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2460 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2461 add_to_list (&libraries, buf);
2462 if (debug)
2463 fprintf (stderr, "%s\n", buf);
2464 break;
2467 if (*pp == 0)
2469 if (debug)
2470 notice ("not found\n");
2471 else
2472 fatal ("dynamic dependency %s not found", name);
2476 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2477 that it depends upon and any constructors or destructors they contain. */
2479 static void
2480 scan_libraries (prog_name)
2481 const char *prog_name;
2483 struct exec *header;
2484 char *base;
2485 struct link_object *lo;
2486 char buff[MAXPATHLEN];
2487 struct id *list;
2489 mapfile (prog_name);
2490 header = (struct exec *)object;
2491 if (N_BADMAG (*header))
2492 fatal ("bad magic number in file '%s'", prog_name);
2493 if (header->a_dynamic == 0)
2494 return;
2496 code = (char *) (N_TXTOFF (*header) + (long) header);
2497 data = (char *) (N_DATOFF (*header) + (long) header);
2498 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2500 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2502 /* shared object */
2503 ld = (struct link_dynamic *) (symtab->n_value + code);
2504 base = code;
2506 else
2508 /* executable */
2509 ld = (struct link_dynamic *) data;
2510 base = code-PAGSIZ;
2513 if (debug)
2514 notice ("dynamic dependencies.\n");
2516 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2517 for (lo = (struct link_object *) ld_2->ld_need; lo;
2518 lo = (struct link_object *) lo->lo_next)
2520 char *name;
2521 lo = (struct link_object *) ((long) lo + code);
2522 name = (char *) (code + lo->lo_name);
2523 if (lo->lo_library)
2525 if (debug)
2526 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2527 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2528 locatelib (buff);
2530 else
2532 if (debug)
2533 fprintf (stderr, "\t%s\n", name);
2534 add_to_list (&libraries, name);
2538 if (debug)
2539 fprintf (stderr, "\n");
2541 /* now iterate through the library list adding their symbols to
2542 the list. */
2543 for (list = libraries.first; list; list = list->next)
2544 scan_prog_file (list->name, PASS_LIB);
2547 #else /* SUNOS4_SHARED_LIBRARIES */
2548 #ifdef LDD_SUFFIX
2550 /* Use the List Dynamic Dependencies program to find shared libraries that
2551 the output file depends upon and their initialization/finalization
2552 routines, if any. */
2554 static void
2555 scan_libraries (prog_name)
2556 const char *prog_name;
2558 static struct head libraries; /* list of shared libraries found */
2559 struct id *list;
2560 void (*int_handler) PROTO ((int));
2561 void (*quit_handler) PROTO ((int));
2562 char *real_ldd_argv[4];
2563 const char **ldd_argv = (const char **) real_ldd_argv;
2564 int pid;
2565 int argc = 0;
2566 int pipe_fd[2];
2567 char buf[1024];
2568 FILE *inf;
2570 /* If we do not have an `ldd', complain. */
2571 if (ldd_file_name == 0)
2573 error ("cannot find `ldd'");
2574 return;
2577 ldd_argv[argc++] = ldd_file_name;
2578 ldd_argv[argc++] = prog_name;
2579 ldd_argv[argc++] = (char *) 0;
2581 if (pipe (pipe_fd) < 0)
2582 fatal_perror ("pipe");
2584 inf = fdopen (pipe_fd[0], "r");
2585 if (inf == (FILE *) 0)
2586 fatal_perror ("fdopen");
2588 /* Trace if needed. */
2589 if (vflag)
2591 const char **p_argv;
2592 const char *str;
2594 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2595 fprintf (stderr, " %s", str);
2597 fprintf (stderr, "\n");
2600 fflush (stdout);
2601 fflush (stderr);
2603 /* Spawn child ldd on pipe */
2604 pid = vfork ();
2605 if (pid == -1)
2606 fatal_perror (VFORK_STRING);
2608 if (pid == 0) /* child context */
2610 /* setup stdout */
2611 if (dup2 (pipe_fd[1], 1) < 0)
2612 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2614 if (close (pipe_fd[0]) < 0)
2615 fatal_perror ("close %d", pipe_fd[0]);
2617 if (close (pipe_fd[1]) < 0)
2618 fatal_perror ("close %d", pipe_fd[1]);
2620 execv (ldd_file_name, real_ldd_argv);
2621 fatal_perror ("execv %s", ldd_file_name);
2624 /* Parent context from here on. */
2625 int_handler = (void (*) PROTO ((int))) signal (SIGINT, SIG_IGN);
2626 #ifdef SIGQUIT
2627 quit_handler = (void (*) PROTO ((int))) signal (SIGQUIT, SIG_IGN);
2628 #endif
2630 if (close (pipe_fd[1]) < 0)
2631 fatal_perror ("close %d", pipe_fd[1]);
2633 if (debug)
2634 notice ("\nldd output with constructors/destructors.\n");
2636 /* Read each line of ldd output. */
2637 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2639 int ch, ch2;
2640 char *name, *end, *p = buf;
2642 /* Extract names of libraries and add to list. */
2643 PARSE_LDD_OUTPUT (p);
2644 if (p == 0)
2645 continue;
2647 name = p;
2648 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2649 fatal ("dynamic dependency %s not found", buf);
2651 /* Find the end of the symbol name. */
2652 for (end = p;
2653 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2654 end++)
2655 continue;
2656 *end = '\0';
2658 if (access (name, R_OK) == 0)
2659 add_to_list (&libraries, name);
2660 else
2661 fatal ("unable to open dynamic dependency '%s'", buf);
2663 if (debug)
2664 fprintf (stderr, "\t%s\n", buf);
2666 if (debug)
2667 fprintf (stderr, "\n");
2669 if (fclose (inf) != 0)
2670 fatal_perror ("fclose");
2672 do_wait (ldd_file_name);
2674 signal (SIGINT, int_handler);
2675 #ifdef SIGQUIT
2676 signal (SIGQUIT, quit_handler);
2677 #endif
2679 /* now iterate through the library list adding their symbols to
2680 the list. */
2681 for (list = libraries.first; list; list = list->next)
2682 scan_prog_file (list->name, PASS_LIB);
2685 #endif /* LDD_SUFFIX */
2686 #endif /* SUNOS4_SHARED_LIBRARIES */
2688 #endif /* OBJECT_FORMAT_NONE */
2692 * COFF specific stuff.
2695 #ifdef OBJECT_FORMAT_COFF
2697 #if defined(EXTENDED_COFF)
2698 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2699 # define GCC_SYMENT SYMR
2700 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2701 # define GCC_SYMINC(X) (1)
2702 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2703 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2704 #else
2705 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2706 # define GCC_SYMENT SYMENT
2707 # define GCC_OK_SYMBOL(X) \
2708 (((X).n_sclass == C_EXT) && \
2709 ((X).n_scnum > N_UNDEF) && \
2710 (aix64_flag \
2711 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2712 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2713 # define GCC_UNDEF_SYMBOL(X) \
2714 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2715 # define GCC_SYMINC(X) ((X).n_numaux+1)
2716 # define GCC_SYMZERO(X) 0
2717 # define GCC_CHECK_HDR(X) \
2718 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2719 || (HEADER (X).f_magic == 0757 && aix64_flag))
2720 #endif
2722 extern char *ldgetname ();
2724 /* COFF version to scan the name list of the loaded program for
2725 the symbols g++ uses for static constructors and destructors.
2727 The constructor table begins at __CTOR_LIST__ and contains a count
2728 of the number of pointers (or -1 if the constructors are built in a
2729 separate section by the linker), followed by the pointers to the
2730 constructor functions, terminated with a null pointer. The
2731 destructor table has the same format, and begins at __DTOR_LIST__. */
2733 static void
2734 scan_prog_file (prog_name, which_pass)
2735 const char *prog_name;
2736 enum pass which_pass;
2738 LDFILE *ldptr = NULL;
2739 int sym_index, sym_count;
2740 int is_shared = 0;
2741 #ifdef COLLECT_EXPORT_LIST
2742 /* Should we generate an import list for given prog_name? */
2743 int import_flag = (which_pass == PASS_OBJ ? 0 : use_import_list (prog_name));
2744 #endif
2746 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2747 return;
2749 #ifdef COLLECT_EXPORT_LIST
2750 /* We do not need scanning for some standard C libraries. */
2751 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2752 return;
2754 /* On AIX we have a loop, because there is not much difference
2755 between an object and an archive. This trick allows us to
2756 eliminate scan_libraries() function. */
2759 #endif
2760 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2761 non-const char * filename parameter, even though it will not
2762 modify that string. So we must cast away const-ness here,
2763 which will cause -Wcast-qual to burp. */
2764 if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2766 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2767 fatal ("%s: not a COFF file", prog_name);
2769 if (GCC_CHECK_HDR (ldptr))
2771 sym_count = GCC_SYMBOLS (ldptr);
2772 sym_index = GCC_SYMZERO (ldptr);
2774 #ifdef COLLECT_EXPORT_LIST
2775 /* Is current archive member a shared object? */
2776 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2777 #endif
2779 while (sym_index < sym_count)
2781 GCC_SYMENT symbol;
2783 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2784 break;
2785 sym_index += GCC_SYMINC (symbol);
2787 if (GCC_OK_SYMBOL (symbol))
2789 char *name;
2791 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2792 continue; /* should never happen */
2794 #ifdef XCOFF_DEBUGGING_INFO
2795 /* All AIX function names have a duplicate entry
2796 beginning with a dot. */
2797 if (*name == '.')
2798 ++name;
2799 #endif
2801 switch (is_ctor_dtor (name))
2803 case 1:
2804 if (! is_shared) add_to_list (&constructors, name);
2805 #ifdef COLLECT_EXPORT_LIST
2806 if (which_pass == PASS_OBJ)
2807 add_to_list (&exports, name);
2808 /* If this symbol was undefined and we are building
2809 an import list, we should add a symbol to this
2810 list. */
2811 else
2812 if (import_flag
2813 && is_in_list (name, undefined.first))
2814 add_to_list (&imports, name);
2815 #endif
2816 break;
2818 case 2:
2819 if (! is_shared) add_to_list (&destructors, name);
2820 #ifdef COLLECT_EXPORT_LIST
2821 if (which_pass == PASS_OBJ)
2822 add_to_list (&exports, name);
2823 /* If this symbol was undefined and we are building
2824 an import list, we should add a symbol to this
2825 list. */
2826 else
2827 if (import_flag
2828 && is_in_list (name, undefined.first))
2829 add_to_list (&imports, name);
2830 #endif
2831 break;
2833 #ifdef COLLECT_EXPORT_LIST
2834 case 3:
2835 if (is_shared)
2836 add_to_list (&constructors, name);
2837 break;
2839 case 4:
2840 if (is_shared)
2841 add_to_list (&destructors, name);
2842 break;
2843 #endif
2845 case 5:
2846 if (! is_shared)
2847 add_to_list (&frame_tables, name);
2848 break;
2850 default: /* not a constructor or destructor */
2851 #ifdef COLLECT_EXPORT_LIST
2852 /* If we are building a shared object on AIX we need
2853 to explicitly export all global symbols or add
2854 them to import list. */
2855 if (shared_obj)
2857 if (which_pass == PASS_OBJ && (! export_flag))
2858 add_to_list (&exports, name);
2859 else if (! is_shared && which_pass == PASS_FIRST
2860 && import_flag
2861 && is_in_list(name, undefined.first))
2862 add_to_list (&imports, name);
2864 #endif
2865 continue;
2868 #if !defined(EXTENDED_COFF)
2869 if (debug)
2870 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2871 symbol.n_scnum, symbol.n_sclass,
2872 (symbol.n_type ? "0" : ""), symbol.n_type,
2873 name);
2874 #else
2875 if (debug)
2876 fprintf (stderr,
2877 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2878 symbol.iss, (long) symbol.value, symbol.index, name);
2879 #endif
2881 #ifdef COLLECT_EXPORT_LIST
2882 /* If we are building a shared object we should collect
2883 information about undefined symbols for later
2884 import list generation. */
2885 else if (shared_obj && GCC_UNDEF_SYMBOL (symbol))
2887 char *name;
2889 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2890 continue; /* should never happen */
2892 /* All AIX function names have a duplicate entry
2893 beginning with a dot. */
2894 if (*name == '.')
2895 ++name;
2896 add_to_list (&undefined, name);
2898 #endif
2901 #ifdef COLLECT_EXPORT_LIST
2902 else
2904 /* If archive contains both 32-bit and 64-bit objects,
2905 we want to skip objects in other mode so mismatch normal. */
2906 if (debug)
2907 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2908 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2910 #endif
2912 else
2914 fatal ("%s: cannot open as COFF file", prog_name);
2916 #ifdef COLLECT_EXPORT_LIST
2917 /* On AIX loop continues while there are more members in archive. */
2919 while (ldclose (ldptr) == FAILURE);
2920 #else
2921 /* Otherwise we simply close ldptr. */
2922 (void) ldclose(ldptr);
2923 #endif
2927 #ifdef COLLECT_EXPORT_LIST
2929 /* This new function is used to decide whether we should
2930 generate import list for an object or to use it directly. */
2931 static int
2932 use_import_list (prog_name)
2933 const char *prog_name;
2935 char *p;
2937 /* If we do not build a shared object then import list should not be used. */
2938 if (! shared_obj) return 0;
2940 /* Currently we check only for libgcc, but this can be changed in future. */
2941 p = strstr (prog_name, "libgcc.a");
2942 if (p != 0 && (strlen (p) == sizeof ("libgcc.a") - 1))
2943 return 1;
2944 return 0;
2947 /* Given a library name without "lib" prefix, this function
2948 returns a full library name including a path. */
2949 static char *
2950 resolve_lib_name (name)
2951 const char *name;
2953 char *lib_buf;
2954 int i, j, l = 0;
2956 for (i = 0; libpaths[i]; i++)
2957 if (libpaths[i]->max_len > l)
2958 l = libpaths[i]->max_len;
2960 lib_buf = xmalloc (l + strlen(name) + 10);
2962 for (i = 0; libpaths[i]; i++)
2964 struct prefix_list *list = libpaths[i]->plist;
2965 for (; list; list = list->next)
2967 for (j = 0; libexts[j]; j++)
2969 /* The following lines are needed because path_prefix list
2970 may contain directories both with trailing '/' and
2971 without it. */
2972 const char *p = "";
2973 if (list->prefix[strlen(list->prefix)-1] != '/')
2974 p = "/";
2975 sprintf (lib_buf, "%s%slib%s.%s",
2976 list->prefix, p, name, libexts[j]);
2977 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2978 if (file_exists (lib_buf))
2980 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2981 return (lib_buf);
2986 if (debug)
2987 fprintf (stderr, "not found\n");
2988 else
2989 fatal ("Library lib%s not found", name);
2990 return (NULL);
2993 /* Array of standard AIX libraries which should not
2994 be scanned for ctors/dtors. */
2995 static const char *aix_std_libs[] = {
2996 "/unix",
2997 "/lib/libc.a",
2998 "/lib/libc_r.a",
2999 "/usr/lib/libc.a",
3000 "/usr/lib/libc_r.a",
3001 "/usr/lib/threads/libc.a",
3002 "/usr/ccs/lib/libc.a",
3003 "/usr/ccs/lib/libc_r.a",
3004 NULL
3007 /* This function checks the filename and returns 1
3008 if this name matches the location of a standard AIX library. */
3009 static int
3010 ignore_library (name)
3011 const char *name;
3013 const char **p = &aix_std_libs[0];
3014 while (*p++ != NULL)
3015 if (! strcmp (name, *p)) return 1;
3016 return 0;
3019 #endif
3021 #endif /* OBJECT_FORMAT_COFF */
3025 * OSF/rose specific stuff.
3028 #ifdef OBJECT_FORMAT_ROSE
3030 /* Union of the various load commands */
3032 typedef union load_union
3034 ldc_header_t hdr; /* common header */
3035 load_cmd_map_command_t map; /* map indexing other load cmds */
3036 interpreter_command_t iprtr; /* interpreter pathname */
3037 strings_command_t str; /* load commands strings section */
3038 region_command_t region; /* region load command */
3039 reloc_command_t reloc; /* relocation section */
3040 package_command_t pkg; /* package load command */
3041 symbols_command_t sym; /* symbol sections */
3042 entry_command_t ent; /* program start section */
3043 gen_info_command_t info; /* object information */
3044 func_table_command_t func; /* function constructors/destructors */
3045 } load_union_t;
3047 /* Structure to point to load command and data section in memory. */
3049 typedef struct load_all
3051 load_union_t *load; /* load command */
3052 char *section; /* pointer to section */
3053 } load_all_t;
3055 /* Structure to contain information about a file mapped into memory. */
3057 struct file_info
3059 char *start; /* start of map */
3060 char *name; /* filename */
3061 long size; /* size of the file */
3062 long rounded_size; /* size rounded to page boundary */
3063 int fd; /* file descriptor */
3064 int rw; /* != 0 if opened read/write */
3065 int use_mmap; /* != 0 if mmap'ed */
3068 extern int decode_mach_o_hdr ();
3069 extern int encode_mach_o_hdr ();
3071 static void add_func_table PROTO((mo_header_t *, load_all_t *,
3072 symbol_info_t *, int));
3073 static void print_header PROTO((mo_header_t *));
3074 static void print_load_command PROTO((load_union_t *, size_t, int));
3075 static void bad_header PROTO((int));
3076 static struct file_info *read_file PROTO((const char *, int, int));
3077 static void end_file PROTO((struct file_info *));
3079 /* OSF/rose specific version to scan the name list of the loaded
3080 program for the symbols g++ uses for static constructors and
3081 destructors.
3083 The constructor table begins at __CTOR_LIST__ and contains a count
3084 of the number of pointers (or -1 if the constructors are built in a
3085 separate section by the linker), followed by the pointers to the
3086 constructor functions, terminated with a null pointer. The
3087 destructor table has the same format, and begins at __DTOR_LIST__. */
3089 static void
3090 scan_prog_file (prog_name, which_pass)
3091 const char *prog_name;
3092 enum pass which_pass;
3094 char *obj;
3095 mo_header_t hdr;
3096 load_all_t *load_array;
3097 load_all_t *load_end;
3098 load_all_t *load_cmd;
3099 int symbol_load_cmds;
3100 off_t offset;
3101 int i;
3102 int num_syms;
3103 int status;
3104 char *str_sect;
3105 struct file_info *obj_file;
3106 int prog_fd;
3107 mo_lcid_t cmd_strings = -1;
3108 symbol_info_t *main_sym = 0;
3109 int rw = (which_pass != PASS_FIRST);
3111 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3112 if (prog_fd < 0)
3113 fatal_perror ("open %s", prog_name);
3115 obj_file = read_file (prog_name, prog_fd, rw);
3116 obj = obj_file->start;
3118 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3119 if (status != MO_HDR_CONV_SUCCESS)
3120 bad_header (status);
3123 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3124 since the hardware will automatically swap bytes for us on loading little endian
3125 integers. */
3127 #ifndef CROSS_COMPILE
3128 if (hdr.moh_magic != MOH_MAGIC_MSB
3129 || hdr.moh_header_version != MOH_HEADER_VERSION
3130 || hdr.moh_byte_order != OUR_BYTE_ORDER
3131 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3132 || hdr.moh_cpu_type != OUR_CPU_TYPE
3133 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3134 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3136 fatal ("incompatibilities between object file & expected values");
3138 #endif
3140 if (debug)
3141 print_header (&hdr);
3143 offset = hdr.moh_first_cmd_off;
3144 load_end = load_array
3145 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3147 /* Build array of load commands, calculating the offsets */
3148 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3150 load_union_t *load_hdr; /* load command header */
3152 load_cmd = load_end++;
3153 load_hdr = (load_union_t *) (obj + offset);
3155 /* If modifying the program file, copy the header. */
3156 if (rw)
3158 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3159 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
3160 load_hdr = ptr;
3162 /* null out old command map, because we will rewrite at the end. */
3163 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3165 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3166 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3170 load_cmd->load = load_hdr;
3171 if (load_hdr->hdr.ldci_section_off > 0)
3172 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3174 if (debug)
3175 print_load_command (load_hdr, offset, i);
3177 offset += load_hdr->hdr.ldci_cmd_size;
3180 /* If the last command is the load command map and is not undefined,
3181 decrement the count of load commands. */
3182 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3184 load_end--;
3185 hdr.moh_n_load_cmds--;
3188 /* Go through and process each symbol table section. */
3189 symbol_load_cmds = 0;
3190 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3192 load_union_t *load_hdr = load_cmd->load;
3194 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3196 symbol_load_cmds++;
3198 if (debug)
3200 const char *kind = "unknown";
3202 switch (load_hdr->sym.symc_kind)
3204 case SYMC_IMPORTS: kind = "imports"; break;
3205 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3206 case SYMC_STABS: kind = "stabs"; break;
3209 notice ("\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3210 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3213 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3214 continue;
3216 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3217 if (str_sect == (char *) 0)
3218 fatal ("string section missing");
3220 if (load_cmd->section == (char *) 0)
3221 fatal ("section pointer missing");
3223 num_syms = load_hdr->sym.symc_nentries;
3224 for (i = 0; i < num_syms; i++)
3226 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3227 char *name = sym->si_name.symbol_name + str_sect;
3229 if (name[0] != '_')
3230 continue;
3232 if (rw)
3234 char *n = name + strlen (name) - strlen (NAME__MAIN);
3236 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3237 continue;
3238 while (n != name)
3239 if (*--n != '_')
3240 continue;
3242 main_sym = sym;
3244 else
3246 switch (is_ctor_dtor (name))
3248 case 1:
3249 add_to_list (&constructors, name);
3250 break;
3252 case 2:
3253 add_to_list (&destructors, name);
3254 break;
3256 default: /* not a constructor or destructor */
3257 continue;
3261 if (debug)
3262 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3263 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3268 if (symbol_load_cmds == 0)
3269 fatal ("no symbol table found");
3271 /* Update the program file now, rewrite header and load commands. At present,
3272 we assume that there is enough space after the last load command to insert
3273 one more. Since the first section written out is page aligned, and the
3274 number of load commands is small, this is ok for the present. */
3276 if (rw)
3278 load_union_t *load_map;
3279 size_t size;
3281 if (cmd_strings == -1)
3282 fatal ("no cmd_strings found");
3284 /* Add __main to initializer list.
3285 If we are building a program instead of a shared library, do not
3286 do anything, since in the current version, you cannot do mallocs
3287 and such in the constructors. */
3289 if (main_sym != (symbol_info_t *) 0
3290 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3291 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3293 if (debug)
3294 notice ("\nUpdating header and load commands.\n\n");
3296 hdr.moh_n_load_cmds++;
3297 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3299 /* Create new load command map. */
3300 if (debug)
3301 notice ("load command map, %d cmds, new size %ld.\n",
3302 (int) hdr.moh_n_load_cmds, (long) size);
3304 load_map = (load_union_t *) xcalloc (1, size);
3305 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3306 load_map->map.ldc_header.ldci_cmd_size = size;
3307 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3308 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3309 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3311 offset = hdr.moh_first_cmd_off;
3312 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3314 load_map->map.lcm_map[i] = offset;
3315 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3316 hdr.moh_load_map_cmd_off = offset;
3318 offset += load_array[i].load->hdr.ldci_cmd_size;
3321 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3323 if (debug)
3324 print_header (&hdr);
3326 /* Write header */
3327 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3328 if (status != MO_HDR_CONV_SUCCESS)
3329 bad_header (status);
3331 if (debug)
3332 notice ("writing load commands.\n\n");
3334 /* Write load commands */
3335 offset = hdr.moh_first_cmd_off;
3336 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3338 load_union_t *load_hdr = load_array[i].load;
3339 size_t size = load_hdr->hdr.ldci_cmd_size;
3341 if (debug)
3342 print_load_command (load_hdr, offset, i);
3344 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3345 offset += size;
3349 end_file (obj_file);
3351 if (close (prog_fd))
3352 fatal_perror ("close %s", prog_name);
3354 if (debug)
3355 fprintf (stderr, "\n");
3359 /* Add a function table to the load commands to call a function
3360 on initiation or termination of the process. */
3362 static void
3363 add_func_table (hdr_p, load_array, sym, type)
3364 mo_header_t *hdr_p; /* pointer to global header */
3365 load_all_t *load_array; /* array of ptrs to load cmds */
3366 symbol_info_t *sym; /* pointer to symbol entry */
3367 int type; /* fntc_type value */
3369 /* Add a new load command. */
3370 int num_cmds = ++hdr_p->moh_n_load_cmds;
3371 int load_index = num_cmds - 1;
3372 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3373 load_union_t *ptr = xcalloc (1, size);
3374 load_all_t *load_cmd;
3375 int i;
3377 /* Set the unresolved address bit in the header to force the loader to be
3378 used, since kernel exec does not call the initialization functions. */
3379 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3381 load_cmd = &load_array[load_index];
3382 load_cmd->load = ptr;
3383 load_cmd->section = (char *) 0;
3385 /* Fill in func table load command. */
3386 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3387 ptr->func.ldc_header.ldci_cmd_size = size;
3388 ptr->func.ldc_header.ldci_section_off = 0;
3389 ptr->func.ldc_header.ldci_section_len = 0;
3390 ptr->func.fntc_type = type;
3391 ptr->func.fntc_nentries = 1;
3393 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3394 /* Is the symbol already expressed as (region, offset)? */
3395 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3397 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3398 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3401 /* If not, figure out which region it's in. */
3402 else
3404 mo_vm_addr_t addr = sym->si_value.abs_val;
3405 int found = 0;
3407 for (i = 0; i < load_index; i++)
3409 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3411 region_command_t *region_ptr = &load_array[i].load->region;
3413 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3414 && addr >= region_ptr->regc_addr.vm_addr
3415 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3417 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3418 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3419 found++;
3420 break;
3425 if (!found)
3426 fatal ("could not convert 0x%l.8x into a region", addr);
3429 if (debug)
3430 notice ("%s function, region %d, offset = %ld (0x%.8lx)\n",
3431 type == FNTC_INITIALIZATION ? "init" : "term",
3432 (int) ptr->func.fntc_entry_loc[i].adr_lcid,
3433 (long) ptr->func.fntc_entry_loc[i].adr_sctoff,
3434 (long) ptr->func.fntc_entry_loc[i].adr_sctoff);
3439 /* Print the global header for an OSF/rose object. */
3441 static void
3442 print_header (hdr_ptr)
3443 mo_header_t *hdr_ptr;
3445 fprintf (stderr, "\nglobal header:\n");
3446 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3447 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3448 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3449 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3450 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3451 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3452 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3453 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3454 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3455 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3456 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3457 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3458 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3459 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3460 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3462 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3463 fprintf (stderr, ", relocatable");
3465 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3466 fprintf (stderr, ", linkable");
3468 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3469 fprintf (stderr, ", execable");
3471 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3472 fprintf (stderr, ", executable");
3474 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3475 fprintf (stderr, ", unresolved");
3477 fprintf (stderr, "\n\n");
3478 return;
3482 /* Print a short summary of a load command. */
3484 static void
3485 print_load_command (load_hdr, offset, number)
3486 load_union_t *load_hdr;
3487 size_t offset;
3488 int number;
3490 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3491 const char *type_str = (char *) 0;
3493 switch (type)
3495 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3496 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3497 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3498 case LDC_STRINGS: type_str = "STRINGS"; break;
3499 case LDC_REGION: type_str = "REGION"; break;
3500 case LDC_RELOC: type_str = "RELOC"; break;
3501 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3502 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3503 case LDC_ENTRY: type_str = "ENTRY"; break;
3504 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3505 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3508 fprintf (stderr,
3509 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3510 number,
3511 (long) load_hdr->hdr.ldci_cmd_size,
3512 (long) offset,
3513 (long) load_hdr->hdr.ldci_section_off,
3514 (long) load_hdr->hdr.ldci_section_len);
3516 if (type_str == (char *) 0)
3517 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3519 else if (type != LDC_REGION)
3520 fprintf (stderr, ", ty: %s\n", type_str);
3522 else
3524 const char *region = "";
3525 switch (load_hdr->region.regc_usage_type)
3527 case REG_TEXT_T: region = ", .text"; break;
3528 case REG_DATA_T: region = ", .data"; break;
3529 case REG_BSS_T: region = ", .bss"; break;
3530 case REG_GLUE_T: region = ", .glue"; break;
3531 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3532 case REG_RDATA_T: region = ", .rdata"; break;
3533 case REG_SDATA_T: region = ", .sdata"; break;
3534 case REG_SBSS_T: region = ", .sbss"; break;
3535 #endif
3538 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3539 type_str,
3540 (long) load_hdr->region.regc_vm_addr,
3541 (long) load_hdr->region.regc_vm_size,
3542 region);
3545 return;
3549 /* Fatal error when {en,de}code_mach_o_header fails. */
3551 static void
3552 bad_header (status)
3553 int status;
3555 switch (status)
3557 case MO_ERROR_BAD_MAGIC: fatal ("bad magic number");
3558 case MO_ERROR_BAD_HDR_VERS: fatal ("bad header version");
3559 case MO_ERROR_BAD_RAW_HDR_VERS: fatal ("bad raw header version");
3560 case MO_ERROR_BUF2SML: fatal ("raw header buffer too small");
3561 case MO_ERROR_OLD_RAW_HDR_FILE: fatal ("old raw header file");
3562 case MO_ERROR_UNSUPPORTED_VERS: fatal ("unsupported version");
3563 default:
3564 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3569 /* Read a file into a memory buffer. */
3571 static struct file_info *
3572 read_file (name, fd, rw)
3573 const char *name; /* filename */
3574 int fd; /* file descriptor */
3575 int rw; /* read/write */
3577 struct stat stat_pkt;
3578 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3579 #ifdef USE_MMAP
3580 static int page_size;
3581 #endif
3583 if (fstat (fd, &stat_pkt) < 0)
3584 fatal_perror ("fstat %s", name);
3586 p->name = name;
3587 p->size = stat_pkt.st_size;
3588 p->rounded_size = stat_pkt.st_size;
3589 p->fd = fd;
3590 p->rw = rw;
3592 #ifdef USE_MMAP
3593 if (debug)
3594 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3596 if (page_size == 0)
3597 page_size = sysconf (_SC_PAGE_SIZE);
3599 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3600 p->start = mmap ((caddr_t) 0,
3601 (rw) ? p->rounded_size : p->size,
3602 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3603 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3605 0L);
3607 if (p->start != (char *) 0 && p->start != (char *) -1)
3608 p->use_mmap = 1;
3610 else
3611 #endif /* USE_MMAP */
3613 long len;
3615 if (debug)
3616 fprintf (stderr, "read %s\n", name);
3618 p->use_mmap = 0;
3619 p->start = xmalloc (p->size);
3620 if (lseek (fd, 0L, SEEK_SET) < 0)
3621 fatal_perror ("lseek %s 0", name);
3623 len = read (fd, p->start, p->size);
3624 if (len < 0)
3625 fatal_perror ("read %s", name);
3627 if (len != p->size)
3628 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3631 return p;
3634 /* Do anything necessary to write a file back from memory. */
3636 static void
3637 end_file (ptr)
3638 struct file_info *ptr; /* file information block */
3640 #ifdef USE_MMAP
3641 if (ptr->use_mmap)
3643 if (ptr->rw)
3645 if (debug)
3646 fprintf (stderr, "msync %s\n", ptr->name);
3648 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3649 fatal_perror ("msync %s", ptr->name);
3652 if (debug)
3653 fprintf (stderr, "munmap %s\n", ptr->name);
3655 if (munmap (ptr->start, ptr->size))
3656 fatal_perror ("munmap %s", ptr->name);
3658 else
3659 #endif /* USE_MMAP */
3661 if (ptr->rw)
3663 long len;
3665 if (debug)
3666 fprintf (stderr, "write %s\n", ptr->name);
3668 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3669 fatal_perror ("lseek %s 0", ptr->name);
3671 len = write (ptr->fd, ptr->start, ptr->size);
3672 if (len < 0)
3673 fatal_perror ("write %s", ptr->name);
3675 if (len != ptr->size)
3676 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3679 free (ptr->start);
3682 free (ptr);
3685 #endif /* OBJECT_FORMAT_ROSE */