oops - fixed typo in previous delta
[official-gcc.git] / gcc / collect2.c
blobf69d56a78d6130095d72d3ed5ebd3452a12b3f58
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93-99, 2000 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 #ifndef LIBRARY_PATH_ENV
46 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
47 #endif
49 #define COLLECT
51 #include "collect2.h"
52 #include "demangle.h"
53 #include "obstack.h"
54 #include "intl.h"
55 #include "version.h"
57 /* Obstack allocation and deallocation routines. */
58 #define obstack_chunk_alloc xmalloc
59 #define obstack_chunk_free free
61 /* On certain systems, we have code that works by scanning the object file
62 directly. But this code uses system-specific header files and library
63 functions, so turn it off in a cross-compiler. Likewise, the names of
64 the utilities are not correct for a cross-compiler; we have to hope that
65 cross-versions are in the proper directories. */
67 #ifdef CROSS_COMPILE
68 #undef SUNOS4_SHARED_LIBRARIES
69 #undef OBJECT_FORMAT_COFF
70 #undef OBJECT_FORMAT_ROSE
71 #undef MD_EXEC_PREFIX
72 #undef REAL_LD_FILE_NAME
73 #undef REAL_NM_FILE_NAME
74 #undef REAL_STRIP_FILE_NAME
75 #endif
77 /* If we cannot use a special method, use the ordinary one:
78 run nm to find what symbols are present.
79 In a cross-compiler, this means you need a cross nm,
80 but that is not quite as unpleasant as special headers. */
82 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
83 #define OBJECT_FORMAT_NONE
84 #endif
86 #ifdef OBJECT_FORMAT_COFF
88 #include <a.out.h>
89 #include <ar.h>
91 #ifdef UMAX
92 #include <sgs.h>
93 #endif
95 /* Many versions of ldfcn.h define these. */
96 #ifdef FREAD
97 #undef FREAD
98 #undef FWRITE
99 #endif
101 #include <ldfcn.h>
103 /* Some systems have an ISCOFF macro, but others do not. In some cases
104 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
105 that either do not have an ISCOFF macro in /usr/include or for those
106 where it is wrong. */
108 #ifndef MY_ISCOFF
109 #define MY_ISCOFF(X) ISCOFF (X)
110 #endif
112 #endif /* OBJECT_FORMAT_COFF */
114 #ifdef OBJECT_FORMAT_ROSE
116 #ifdef _OSF_SOURCE
117 #define USE_MMAP
118 #endif
120 #ifdef USE_MMAP
121 #include <sys/mman.h>
122 #endif
124 #include <unistd.h>
125 #include <mach_o_format.h>
126 #include <mach_o_header.h>
127 #include <mach_o_vals.h>
128 #include <mach_o_types.h>
130 #endif /* OBJECT_FORMAT_ROSE */
132 #ifdef OBJECT_FORMAT_NONE
134 /* Default flags to pass to nm. */
135 #ifndef NM_FLAGS
136 #define NM_FLAGS "-n"
137 #endif
139 #endif /* OBJECT_FORMAT_NONE */
141 /* Some systems use __main in a way incompatible with its use in gcc, in these
142 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
143 give the same symbol without quotes for an alternative entry point. You
144 must define both, or neither. */
145 #ifndef NAME__MAIN
146 #define NAME__MAIN "__main"
147 #define SYMBOL__MAIN __main
148 #endif
150 /* This must match tree.h. */
151 #define DEFAULT_INIT_PRIORITY 65535
153 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
154 #define SCAN_LIBRARIES
155 #endif
157 #ifdef USE_COLLECT2
158 int do_collecting = 1;
159 #else
160 int do_collecting = 0;
161 #endif
163 /* Linked lists of constructor and destructor names. */
165 struct id
167 struct id *next;
168 int sequence;
169 char name[1];
172 struct head
174 struct id *first;
175 struct id *last;
176 int number;
179 /* Enumeration giving which pass this is for scanning the program file. */
181 enum pass {
182 PASS_FIRST, /* without constructors */
183 PASS_OBJ, /* individual objects */
184 PASS_LIB, /* looking for shared libraries */
185 PASS_SECOND /* with constructors linked in */
188 int vflag; /* true if -v */
189 static int rflag; /* true if -r */
190 static int strip_flag; /* true if -s */
191 #ifdef COLLECT_EXPORT_LIST
192 static int export_flag; /* true if -bE */
193 static int aix64_flag; /* true if -b64 */
194 #endif
196 int debug; /* true if -debug */
198 static int shared_obj; /* true if -shared */
200 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
201 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
202 #ifdef COLLECT_EXPORT_LIST
203 static const char *export_file; /* <xxx>.x for AIX export list. */
204 static const char *import_file; /* <xxx>.p for AIX import list. */
205 #endif
206 const char *ldout; /* File for ld errors. */
207 static const char *output_file; /* Output file for ld. */
208 static const char *nm_file_name; /* pathname of nm */
209 #ifdef LDD_SUFFIX
210 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
211 #endif
212 static const char *strip_file_name; /* pathname of strip */
213 const char *c_file_name; /* pathname of gcc */
214 static char *initname, *fininame; /* names of init and fini funcs */
216 static struct head constructors; /* list of constructors found */
217 static struct head destructors; /* list of destructors found */
218 #ifdef COLLECT_EXPORT_LIST
219 static struct head exports; /* list of exported symbols */
220 static struct head imports; /* list of imported symbols */
221 static struct head undefined; /* list of undefined symbols */
222 #endif
223 static struct head frame_tables; /* list of frame unwind info tables */
225 struct obstack temporary_obstack;
226 struct obstack permanent_obstack;
227 char * temporary_firstobj;
229 /* Holds the return value of pexecute. */
230 int pexecute_pid;
232 /* Defined in the automatically-generated underscore.c. */
233 extern int prepends_underscore;
235 #ifndef GET_ENV_PATH_LIST
236 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
237 #endif
239 /* Structure to hold all the directories in which to search for files to
240 execute. */
242 struct prefix_list
244 const char *prefix; /* String to prepend to the path. */
245 struct prefix_list *next; /* Next in linked list. */
248 struct path_prefix
250 struct prefix_list *plist; /* List of prefixes to try */
251 int max_len; /* Max length of a prefix in PLIST */
252 const char *name; /* Name of this list (used in config stuff) */
255 #ifdef COLLECT_EXPORT_LIST
256 /* Lists to keep libraries to be scanned for global constructors/destructors. */
257 static struct head libs; /* list of libraries */
258 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
259 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
260 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
261 &libpath_lib_dirs, NULL};
262 static const char *libexts[3] = {"a", "so", NULL}; /* possible library extentions */
263 #endif
265 static void handler PARAMS ((int));
266 static int is_ctor_dtor PARAMS ((const char *));
267 static char *find_a_file PARAMS ((struct path_prefix *, const char *));
268 static void add_prefix PARAMS ((struct path_prefix *, const char *));
269 static void prefix_from_env PARAMS ((const char *, struct path_prefix *));
270 static void prefix_from_string PARAMS ((const char *, struct path_prefix *));
271 static void do_wait PARAMS ((const char *));
272 static void fork_execute PARAMS ((const char *, char **));
273 static void maybe_unlink PARAMS ((const char *));
274 static void add_to_list PARAMS ((struct head *, const char *));
275 static int extract_init_priority PARAMS ((const char *));
276 static void sort_ids PARAMS ((struct head *));
277 static void write_list PARAMS ((FILE *, const char *, struct id *));
278 #ifdef COLLECT_EXPORT_LIST
279 static void dump_list PARAMS ((FILE *, const char *, struct id *));
280 #endif
281 #if 0
282 static void dump_prefix_list PARAMS ((FILE *, const char *, struct prefix_list *));
283 #endif
284 static void write_list_with_asm PARAMS ((FILE *, const char *, struct id *));
285 static void write_c_file PARAMS ((FILE *, const char *));
286 static void write_c_file_stat PARAMS ((FILE *, const char *));
287 #ifndef LD_INIT_SWITCH
288 static void write_c_file_glob PARAMS ((FILE *, const char *));
289 #endif
290 static void scan_prog_file PARAMS ((const char *, enum pass));
291 #ifdef SCAN_LIBRARIES
292 static void scan_libraries PARAMS ((const char *));
293 #endif
294 #ifdef COLLECT_EXPORT_LIST
295 static int is_in_list PARAMS ((const char *, struct id *));
296 static void write_aix_file PARAMS ((FILE *, struct id *));
297 static char *resolve_lib_name PARAMS ((const char *));
298 static int use_import_list PARAMS ((const char *));
299 static int ignore_library PARAMS ((const char *));
300 #endif
301 static char *extract_string PARAMS ((const char **));
303 #ifdef NO_DUP2
305 dup2 (oldfd, newfd)
306 int oldfd;
307 int newfd;
309 int fdtmp[256];
310 int fdx = 0;
311 int fd;
313 if (oldfd == newfd)
314 return oldfd;
315 close (newfd);
316 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
317 fdtmp[fdx++] = fd;
318 while (fdx > 0)
319 close (fdtmp[--fdx]);
321 return fd;
323 #endif
325 /* Delete tempfiles and exit function. */
327 void
328 collect_exit (status)
329 int status;
331 if (c_file != 0 && c_file[0])
332 maybe_unlink (c_file);
334 if (o_file != 0 && o_file[0])
335 maybe_unlink (o_file);
337 #ifdef COLLECT_EXPORT_LIST
338 if (export_file != 0 && export_file[0])
339 maybe_unlink (export_file);
341 if (import_file != 0 && import_file[0])
342 maybe_unlink (import_file);
343 #endif
345 if (ldout != 0 && ldout[0])
347 dump_file (ldout);
348 maybe_unlink (ldout);
351 if (status != 0 && output_file != 0 && output_file[0])
352 maybe_unlink (output_file);
354 exit (status);
358 /* Notify user of a non-error. */
359 void
360 notice VPARAMS ((const char *msgid, ...))
362 #ifndef ANSI_PROTOTYPES
363 const char *msgid;
364 #endif
365 va_list ap;
367 VA_START (ap, msgid);
369 #ifndef ANSI_PROTOTYPES
370 msgid = va_arg (ap, const char *);
371 #endif
373 vfprintf (stderr, _(msgid), ap);
374 va_end (ap);
377 /* Die when sys call fails. */
379 void
380 fatal_perror VPARAMS ((const char * msgid, ...))
382 #ifndef ANSI_PROTOTYPES
383 const char *msgid;
384 #endif
385 int e = errno;
386 va_list ap;
388 VA_START (ap, msgid);
390 #ifndef ANSI_PROTOTYPES
391 msgid = va_arg (ap, const char *);
392 #endif
394 fprintf (stderr, "collect2: ");
395 vfprintf (stderr, _(msgid), ap);
396 fprintf (stderr, ": %s\n", xstrerror (e));
397 va_end (ap);
399 collect_exit (FATAL_EXIT_CODE);
402 /* Just die. */
404 void
405 fatal VPARAMS ((const char * msgid, ...))
407 #ifndef ANSI_PROTOTYPES
408 const char *msgid;
409 #endif
410 va_list ap;
412 VA_START (ap, msgid);
414 #ifndef ANSI_PROTOTYPES
415 msgid = va_arg (ap, const char *);
416 #endif
418 fprintf (stderr, "collect2: ");
419 vfprintf (stderr, _(msgid), ap);
420 fprintf (stderr, "\n");
421 va_end (ap);
423 collect_exit (FATAL_EXIT_CODE);
426 /* Write error message. */
428 void
429 error VPARAMS ((const char * msgid, ...))
431 #ifndef ANSI_PROTOTYPES
432 const char * msgid;
433 #endif
434 va_list ap;
436 VA_START (ap, msgid);
438 #ifndef ANSI_PROTOTYPES
439 msgid = va_arg (ap, const char *);
440 #endif
442 fprintf (stderr, "collect2: ");
443 vfprintf (stderr, _(msgid), ap);
444 fprintf (stderr, "\n");
445 va_end(ap);
448 /* In case obstack is linked in, and abort is defined to fancy_abort,
449 provide a default entry. */
451 void
452 fancy_abort ()
454 fatal ("internal error");
457 static void
458 handler (signo)
459 int signo;
461 if (c_file != 0 && c_file[0])
462 maybe_unlink (c_file);
464 if (o_file != 0 && o_file[0])
465 maybe_unlink (o_file);
467 if (ldout != 0 && ldout[0])
468 maybe_unlink (ldout);
470 #ifdef COLLECT_EXPORT_LIST
471 if (export_file != 0 && export_file[0])
472 maybe_unlink (export_file);
474 if (import_file != 0 && import_file[0])
475 maybe_unlink (import_file);
476 #endif
478 signal (signo, SIG_DFL);
479 kill (getpid (), signo);
484 file_exists (name)
485 const char *name;
487 return access (name, R_OK) == 0;
490 /* Parse a reasonable subset of shell quoting syntax. */
492 static char *
493 extract_string (pp)
494 const char **pp;
496 const char *p = *pp;
497 int backquote = 0;
498 int inside = 0;
500 for (;;)
502 char c = *p;
503 if (c == '\0')
504 break;
505 ++p;
506 if (backquote)
507 obstack_1grow (&temporary_obstack, c);
508 else if (! inside && c == ' ')
509 break;
510 else if (! inside && c == '\\')
511 backquote = 1;
512 else if (c == '\'')
513 inside = !inside;
514 else
515 obstack_1grow (&temporary_obstack, c);
518 obstack_1grow (&temporary_obstack, '\0');
519 *pp = p;
520 return obstack_finish (&temporary_obstack);
523 void
524 dump_file (name)
525 const char *name;
527 FILE *stream = fopen (name, "r");
528 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
530 if (stream == 0)
531 return;
532 while (1)
534 int c;
535 while (c = getc (stream),
536 c != EOF && (ISALNUM (c) || c == '_' || c == '$' || c == '.'))
537 obstack_1grow (&temporary_obstack, c);
538 if (obstack_object_size (&temporary_obstack) > 0)
540 const char *word, *p;
541 char *result;
542 obstack_1grow (&temporary_obstack, '\0');
543 word = obstack_finish (&temporary_obstack);
545 if (*word == '.')
546 ++word, putc ('.', stderr);
547 p = word;
548 if (*p == '_' && prepends_underscore)
549 ++p;
551 if (no_demangle)
552 result = 0;
553 else
554 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
556 if (result)
558 int diff;
559 fputs (result, stderr);
561 diff = strlen (word) - strlen (result);
562 while (diff > 0)
563 --diff, putc (' ', stderr);
564 while (diff < 0 && c == ' ')
565 ++diff, c = getc (stream);
567 free (result);
569 else
570 fputs (word, stderr);
572 fflush (stderr);
573 obstack_free (&temporary_obstack, temporary_firstobj);
575 if (c == EOF)
576 break;
577 putc (c, stderr);
579 fclose (stream);
582 /* Decide whether the given symbol is: a constructor (1), a destructor
583 (2), a routine in a shared object that calls all the constructors
584 (3) or destructors (4), a DWARF exception-handling table (5), or
585 nothing special (0). */
587 static int
588 is_ctor_dtor (s)
589 const char *s;
591 struct names { const char *name; int len; int ret; int two_underscores; };
593 register struct names *p;
594 register int ch;
595 register const char *orig_s = s;
597 static struct names special[] = {
598 #ifdef NO_DOLLAR_IN_LABEL
599 #ifdef NO_DOT_IN_LABEL
600 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
601 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
602 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
603 #else
604 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
605 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
606 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
607 #endif
608 #else
609 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
610 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
611 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
612 #endif
613 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
614 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
615 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
616 cfront has its own linker procedure to collect them;
617 if collect2 gets them too, they get collected twice
618 when the cfront procedure is run and the compiler used
619 for linking happens to be GCC. */
620 { "sti__", sizeof ("sti__")-1, 1, 1 },
621 { "std__", sizeof ("std__")-1, 2, 1 },
622 #endif /* CFRONT_LOSSAGE */
623 { NULL, 0, 0, 0 }
626 while ((ch = *s) == '_')
627 ++s;
629 if (s == orig_s)
630 return 0;
632 for (p = &special[0]; p->len > 0; p++)
634 if (ch == p->name[0]
635 && (!p->two_underscores || ((s - orig_s) >= 2))
636 && strncmp(s, p->name, p->len) == 0)
638 return p->ret;
641 return 0;
644 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
645 and one from the PATH variable. */
647 static struct path_prefix cpath, path;
649 #ifdef CROSS_COMPILE
650 /* This is the name of the target machine. We use it to form the name
651 of the files to execute. */
653 static const char *const target_machine = TARGET_MACHINE;
654 #endif
656 /* Search for NAME using prefix list PPREFIX. We only look for executable
657 files.
659 Return 0 if not found, otherwise return its name, allocated with malloc. */
661 static char *
662 find_a_file (pprefix, name)
663 struct path_prefix *pprefix;
664 const char *name;
666 char *temp;
667 struct prefix_list *pl;
668 int len = pprefix->max_len + strlen (name) + 1;
670 if (debug)
671 fprintf (stderr, "Looking for '%s'\n", name);
673 #ifdef EXECUTABLE_SUFFIX
674 len += strlen (EXECUTABLE_SUFFIX);
675 #endif
677 temp = xmalloc (len);
679 /* Determine the filename to execute (special case for absolute paths). */
681 if (*name == '/'
682 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
683 || (*name && name[1] == ':')
684 #endif
687 if (access (name, X_OK) == 0)
689 strcpy (temp, name);
691 if (debug)
692 fprintf (stderr, " - found: absolute path\n");
694 return temp;
697 #ifdef EXECUTABLE_SUFFIX
698 /* Some systems have a suffix for executable files.
699 So try appending that. */
700 strcpy (temp, name);
701 strcat (temp, EXECUTABLE_SUFFIX);
703 if (access (temp, X_OK) == 0)
704 return temp;
705 #endif
707 if (debug)
708 fprintf (stderr, " - failed to locate using absolute path\n");
710 else
711 for (pl = pprefix->plist; pl; pl = pl->next)
713 struct stat st;
715 strcpy (temp, pl->prefix);
716 strcat (temp, name);
718 if (stat (temp, &st) >= 0
719 && ! S_ISDIR (st.st_mode)
720 && access (temp, X_OK) == 0)
721 return temp;
723 #ifdef EXECUTABLE_SUFFIX
724 /* Some systems have a suffix for executable files.
725 So try appending that. */
726 strcat (temp, EXECUTABLE_SUFFIX);
728 if (stat (temp, &st) >= 0
729 && ! S_ISDIR (st.st_mode)
730 && access (temp, X_OK) == 0)
731 return temp;
732 #endif
735 if (debug && pprefix->plist == NULL)
736 fprintf (stderr, " - failed: no entries in prefix list\n");
738 free (temp);
739 return 0;
742 /* Add an entry for PREFIX to prefix list PPREFIX. */
744 static void
745 add_prefix (pprefix, prefix)
746 struct path_prefix *pprefix;
747 const char *prefix;
749 struct prefix_list *pl, **prev;
750 int len;
752 if (pprefix->plist)
754 for (pl = pprefix->plist; pl->next; pl = pl->next)
756 prev = &pl->next;
758 else
759 prev = &pprefix->plist;
761 /* Keep track of the longest prefix */
763 len = strlen (prefix);
764 if (len > pprefix->max_len)
765 pprefix->max_len = len;
767 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
768 pl->prefix = xstrdup (prefix);
770 if (*prev)
771 pl->next = *prev;
772 else
773 pl->next = (struct prefix_list *) 0;
774 *prev = pl;
777 /* Take the value of the environment variable ENV, break it into a path, and
778 add of the entries to PPREFIX. */
780 static void
781 prefix_from_env (env, pprefix)
782 const char *env;
783 struct path_prefix *pprefix;
785 const char *p;
786 GET_ENV_PATH_LIST (p, env);
788 if (p)
789 prefix_from_string (p, pprefix);
792 static void
793 prefix_from_string (p, pprefix)
794 const char *p;
795 struct path_prefix *pprefix;
797 const char *startp, *endp;
798 char *nstore = (char *) xmalloc (strlen (p) + 3);
800 if (debug)
801 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
803 startp = endp = p;
804 while (1)
806 if (*endp == PATH_SEPARATOR || *endp == 0)
808 strncpy (nstore, startp, endp-startp);
809 if (endp == startp)
811 strcpy (nstore, "./");
813 else if (! IS_DIR_SEPARATOR (endp[-1]))
815 nstore[endp-startp] = DIR_SEPARATOR;
816 nstore[endp-startp+1] = 0;
818 else
819 nstore[endp-startp] = 0;
821 if (debug)
822 fprintf (stderr, " - add prefix: %s\n", nstore);
824 add_prefix (pprefix, nstore);
825 if (*endp == 0)
826 break;
827 endp = startp = endp + 1;
829 else
830 endp++;
834 /* Main program. */
836 int main PARAMS ((int, char *[]));
838 main (argc, argv)
839 int argc;
840 char *argv[];
842 const char *ld_suffix = "ld";
843 const char *full_ld_suffix = ld_suffix;
844 const char *real_ld_suffix = "real-ld";
845 const char *collect_ld_suffix = "collect-ld";
846 const char *nm_suffix = "nm";
847 const char *full_nm_suffix = nm_suffix;
848 const char *gnm_suffix = "gnm";
849 const char *full_gnm_suffix = gnm_suffix;
850 #ifdef LDD_SUFFIX
851 const char *ldd_suffix = LDD_SUFFIX;
852 const char *full_ldd_suffix = ldd_suffix;
853 #endif
854 const char *strip_suffix = "strip";
855 const char *full_strip_suffix = strip_suffix;
856 const char *gstrip_suffix = "gstrip";
857 const char *full_gstrip_suffix = gstrip_suffix;
858 const char *arg;
859 FILE *outf;
860 #ifdef COLLECT_EXPORT_LIST
861 FILE *exportf;
862 FILE *importf;
863 #endif
864 const char *ld_file_name;
865 const char *p;
866 char **c_argv;
867 const char **c_ptr;
868 char **ld1_argv;
869 const char **ld1;
870 char **ld2_argv;
871 const char **ld2;
872 char **object_lst;
873 const char **object;
874 int first_file;
875 int num_c_args = argc+9;
877 #if defined (COLLECT2_HOST_INITIALIZATION)
878 /* Perform system dependant initialization, if neccessary. */
879 COLLECT2_HOST_INITIALIZATION;
880 #endif
882 #ifdef HAVE_LC_MESSAGES
883 setlocale (LC_MESSAGES, "");
884 #endif
885 (void) bindtextdomain (PACKAGE, localedir);
886 (void) textdomain (PACKAGE);
888 /* Do not invoke xcalloc before this point, since locale needs to be
889 set first, in case a diagnostic is issued. */
891 ld1 = (const char **)(ld1_argv = (char **) xcalloc(sizeof (char *), argc+3));
892 ld2 = (const char **)(ld2_argv = (char **) xcalloc(sizeof (char *), argc+10));
893 object = (const char **)(object_lst = (char **) xcalloc(sizeof (char *), argc));
895 #ifdef DEBUG
896 debug = 1;
897 #endif
899 /* Parse command line early for instances of -debug. This allows
900 the debug flag to be set before functions like find_a_file()
901 are called. */
903 int i;
905 for (i = 1; argv[i] != NULL; i ++)
906 if (! strcmp (argv[i], "-debug"))
907 debug = 1;
908 vflag = debug;
911 #ifndef DEFAULT_A_OUT_NAME
912 output_file = "a.out";
913 #else
914 output_file = DEFAULT_A_OUT_NAME;
915 #endif
917 obstack_begin (&temporary_obstack, 0);
918 obstack_begin (&permanent_obstack, 0);
919 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
921 current_demangling_style = gnu_demangling;
922 p = getenv ("COLLECT_GCC_OPTIONS");
923 while (p && *p)
925 const char *q = extract_string (&p);
926 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
927 num_c_args++;
929 obstack_free (&temporary_obstack, temporary_firstobj);
931 /* -fno-exceptions -w */
932 num_c_args += 2;
934 c_ptr = (const char **)
935 (c_argv = (char **) xcalloc (sizeof (char *), num_c_args));
937 if (argc < 2)
938 fatal ("no arguments");
940 #ifdef SIGQUIT
941 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
942 signal (SIGQUIT, handler);
943 #endif
944 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
945 signal (SIGINT, handler);
946 #ifdef SIGALRM
947 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
948 signal (SIGALRM, handler);
949 #endif
950 #ifdef SIGHUP
951 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
952 signal (SIGHUP, handler);
953 #endif
954 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
955 signal (SIGSEGV, handler);
956 #ifdef SIGBUS
957 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
958 signal (SIGBUS, handler);
959 #endif
961 /* Extract COMPILER_PATH and PATH into our prefix list. */
962 prefix_from_env ("COMPILER_PATH", &cpath);
963 prefix_from_env ("PATH", &path);
965 #ifdef CROSS_COMPILE
966 /* If we look for a program in the compiler directories, we just use
967 the short name, since these directories are already system-specific.
968 But it we look for a program in the system directories, we need to
969 qualify the program name with the target machine. */
971 full_ld_suffix = concat(target_machine, "-", ld_suffix, NULL);
973 #if 0
974 full_gld_suffix = concat (target_machine, "-", gld_suffix, NULL);
975 #endif
977 full_nm_suffix = concat (target_machine, "-", nm_suffix, NULL);
979 full_gnm_suffix = concat (target_machine, "-", gnm_suffix, NULL);
981 #ifdef LDD_SUFFIX
982 full_ldd_suffix = concat (target_machine, "-", ldd_suffix, NULL);
983 #endif
985 full_strip_suffix = concat (target_machine, "-", strip_suffix, NULL);
987 full_gstrip_suffix = concat (target_machine, "-", gstrip_suffix, NULL);
988 #endif /* CROSS_COMPILE */
990 /* Try to discover a valid linker/nm/strip to use. */
992 /* Maybe we know the right file to use (if not cross). */
993 ld_file_name = 0;
994 #ifdef DEFAULT_LINKER
995 if (access (DEFAULT_LINKER, X_OK) == 0)
996 ld_file_name = DEFAULT_LINKER;
997 if (ld_file_name == 0)
998 #endif
999 #ifdef REAL_LD_FILE_NAME
1000 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1001 if (ld_file_name == 0)
1002 #endif
1003 /* Search the (target-specific) compiler dirs for ld'. */
1004 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1005 /* Likewise for `collect-ld'. */
1006 if (ld_file_name == 0)
1007 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1008 /* Search the compiler directories for `ld'. We have protection against
1009 recursive calls in find_a_file. */
1010 if (ld_file_name == 0)
1011 ld_file_name = find_a_file (&cpath, ld_suffix);
1012 /* Search the ordinary system bin directories
1013 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1014 if (ld_file_name == 0)
1015 ld_file_name = find_a_file (&path, full_ld_suffix);
1017 #ifdef REAL_NM_FILE_NAME
1018 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1019 if (nm_file_name == 0)
1020 #endif
1021 nm_file_name = find_a_file (&cpath, gnm_suffix);
1022 if (nm_file_name == 0)
1023 nm_file_name = find_a_file (&path, full_gnm_suffix);
1024 if (nm_file_name == 0)
1025 nm_file_name = find_a_file (&cpath, nm_suffix);
1026 if (nm_file_name == 0)
1027 nm_file_name = find_a_file (&path, full_nm_suffix);
1029 #ifdef LDD_SUFFIX
1030 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1031 if (ldd_file_name == 0)
1032 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1033 #endif
1035 #ifdef REAL_STRIP_FILE_NAME
1036 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1037 if (strip_file_name == 0)
1038 #endif
1039 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1040 if (strip_file_name == 0)
1041 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1042 if (strip_file_name == 0)
1043 strip_file_name = find_a_file (&cpath, strip_suffix);
1044 if (strip_file_name == 0)
1045 strip_file_name = find_a_file (&path, full_strip_suffix);
1047 /* Determine the full path name of the C compiler to use. */
1048 c_file_name = getenv ("COLLECT_GCC");
1049 if (c_file_name == 0)
1051 #ifdef CROSS_COMPILE
1052 c_file_name = concat (target_machine, "-gcc", NULL);
1053 #else
1054 c_file_name = "gcc";
1055 #endif
1058 p = find_a_file (&cpath, c_file_name);
1060 /* Here it should be safe to use the system search path since we should have
1061 already qualified the name of the compiler when it is needed. */
1062 if (p == 0)
1063 p = find_a_file (&path, c_file_name);
1065 if (p)
1066 c_file_name = p;
1068 *ld1++ = *ld2++ = ld_file_name;
1070 /* Make temp file names. */
1071 c_file = make_temp_file (".c");
1072 o_file = make_temp_file (".o");
1073 #ifdef COLLECT_EXPORT_LIST
1074 export_file = make_temp_file (".x");
1075 import_file = make_temp_file (".p");
1076 #endif
1077 ldout = make_temp_file (".ld");
1078 *c_ptr++ = c_file_name;
1079 *c_ptr++ = "-x";
1080 *c_ptr++ = "c";
1081 *c_ptr++ = "-c";
1082 *c_ptr++ = "-o";
1083 *c_ptr++ = o_file;
1085 #ifdef COLLECT_EXPORT_LIST
1086 /* Generate a list of directories from LIBPATH. */
1087 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1088 /* Add to this list also two standard directories where
1089 AIX loader always searches for libraries. */
1090 add_prefix (&libpath_lib_dirs, "/lib");
1091 add_prefix (&libpath_lib_dirs, "/usr/lib");
1092 #endif
1094 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1096 AIX support needs to know if -shared has been specified before
1097 parsing commandline arguments. */
1099 p = getenv ("COLLECT_GCC_OPTIONS");
1100 while (p && *p)
1102 const char *q = extract_string (&p);
1103 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1104 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1105 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1106 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1107 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1108 shared_obj = 1;
1110 obstack_free (&temporary_obstack, temporary_firstobj);
1111 *c_ptr++ = "-fno-exceptions";
1112 *c_ptr++ = "-w";
1114 /* !!! When GCC calls collect2,
1115 it does not know whether it is calling collect2 or ld.
1116 So collect2 cannot meaningfully understand any options
1117 except those ld understands.
1118 If you propose to make GCC pass some other option,
1119 just imagine what will happen if ld is really ld!!! */
1121 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1122 /* After the first file, put in the c++ rt0. */
1124 first_file = 1;
1125 while ((arg = *++argv) != (char *) 0)
1127 *ld1++ = *ld2++ = arg;
1129 if (arg[0] == '-')
1131 switch (arg[1])
1133 #ifdef COLLECT_EXPORT_LIST
1134 /* We want to disable automatic exports on AIX when user
1135 explicitly puts an export list in command line */
1136 case 'b':
1137 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1138 export_flag = 1;
1139 else if (arg[2] == '6' && arg[3] == '4')
1140 aix64_flag = 1;
1141 break;
1142 #endif
1144 case 'd':
1145 if (!strcmp (arg, "-debug"))
1147 /* Already parsed. */
1148 ld1--;
1149 ld2--;
1151 break;
1153 case 'l':
1154 if (first_file)
1156 /* place o_file BEFORE this argument! */
1157 first_file = 0;
1158 ld2--;
1159 *ld2++ = o_file;
1160 *ld2++ = arg;
1162 #ifdef COLLECT_EXPORT_LIST
1164 /* Resolving full library name. */
1165 const char *s = resolve_lib_name (arg+2);
1167 /* If we will use an import list for this library,
1168 we should exclude it from ld args. */
1169 if (use_import_list (s))
1171 ld1--;
1172 ld2--;
1175 /* Saving a full library name. */
1176 add_to_list (&libs, s);
1178 #endif
1179 break;
1181 #ifdef COLLECT_EXPORT_LIST
1182 /* Saving directories where to search for libraries. */
1183 case 'L':
1184 add_prefix (&cmdline_lib_dirs, arg+2);
1185 break;
1186 #endif
1188 case 'o':
1189 if (arg[2] == '\0')
1190 output_file = *ld1++ = *ld2++ = *++argv;
1191 else if (1
1192 #ifdef SWITCHES_NEED_SPACES
1193 && ! index (SWITCHES_NEED_SPACES, arg[1])
1194 #endif
1197 output_file = &arg[2];
1198 break;
1200 case 'r':
1201 if (arg[2] == '\0')
1202 rflag = 1;
1203 break;
1205 case 's':
1206 if (arg[2] == '\0' && do_collecting)
1208 /* We must strip after the nm run, otherwise C++ linking
1209 will not work. Thus we strip in the second ld run, or
1210 else with strip if there is no second ld run. */
1211 strip_flag = 1;
1212 ld1--;
1214 break;
1216 case 'v':
1217 if (arg[2] == '\0')
1218 vflag = 1;
1219 break;
1222 else if ((p = rindex (arg, '.')) != (char *) 0
1223 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1224 || strcmp (p, ".so") == 0))
1226 if (first_file)
1228 first_file = 0;
1229 if (p[1] == 'o')
1230 *ld2++ = o_file;
1231 else
1233 /* place o_file BEFORE this argument! */
1234 ld2--;
1235 *ld2++ = o_file;
1236 *ld2++ = arg;
1239 if (p[1] == 'o')
1240 *object++ = arg;
1241 #ifdef COLLECT_EXPORT_LIST
1242 /* libraries can be specified directly, i.e. without -l flag. */
1243 else
1245 /* If we will use an import list for this library,
1246 we should exclude it from ld args. */
1247 if (use_import_list (arg))
1249 ld1--;
1250 ld2--;
1253 /* Saving a full library name. */
1254 add_to_list (&libs, arg);
1256 #endif
1260 #ifdef COLLECT_EXPORT_LIST
1261 /* This is added only for debugging purposes. */
1262 if (debug)
1264 fprintf (stderr, "List of libraries:\n");
1265 dump_list (stderr, "\t", libs.first);
1268 /* The AIX linker will discard static constructors in object files if
1269 nothing else in the file is referenced, so look at them first. */
1271 const char **export_object_lst = (const char **)object_lst;
1273 while (export_object_lst < object)
1274 scan_prog_file (*export_object_lst++, PASS_OBJ);
1277 struct id *list = libs.first;
1279 for (; list; list = list->next)
1280 scan_prog_file (list->name, PASS_FIRST);
1283 if (frame_tables.number > 0 && shared_obj)
1285 /* If there are any frames, then we will need
1286 the frame table handling functions. */
1287 add_to_list (&imports, "__register_frame_info_table");
1288 add_to_list (&imports, "__deregister_frame_info");
1291 if (exports.first)
1293 char *buf = xmalloc (strlen (export_file) + 5);
1295 sprintf (buf, "-bE:%s", export_file);
1296 *ld1++ = buf;
1297 *ld2++ = buf;
1299 exportf = fopen (export_file, "w");
1300 if (exportf == (FILE *) 0)
1301 fatal_perror ("fopen %s", export_file);
1302 write_aix_file (exportf, exports.first);
1303 if (fclose (exportf))
1304 fatal_perror ("fclose %s", export_file);
1307 if (imports.first)
1309 char *buf = xmalloc (strlen (import_file) + 5);
1311 sprintf (buf, "-bI:%s", import_file);
1312 *ld1++ = buf;
1313 *ld2++ = buf;
1315 importf = fopen (import_file, "w");
1316 if (importf == (FILE *) 0)
1317 fatal_perror ("%s", import_file);
1318 fputs ("#! .\n", importf);
1319 write_aix_file (importf, imports.first);
1320 if (fclose (importf))
1321 fatal_perror ("fclose %s", import_file);
1323 #endif
1325 *c_ptr++ = c_file;
1326 *c_ptr = *ld1 = *object = (char *) 0;
1328 if (vflag)
1330 notice ("collect2 version %s", version_string);
1331 #ifdef TARGET_VERSION
1332 TARGET_VERSION;
1333 #endif
1334 fprintf (stderr, "\n");
1337 if (debug)
1339 const char *ptr;
1340 fprintf (stderr, "ld_file_name = %s\n",
1341 (ld_file_name ? ld_file_name : "not found"));
1342 fprintf (stderr, "c_file_name = %s\n",
1343 (c_file_name ? c_file_name : "not found"));
1344 fprintf (stderr, "nm_file_name = %s\n",
1345 (nm_file_name ? nm_file_name : "not found"));
1346 #ifdef LDD_SUFFIX
1347 fprintf (stderr, "ldd_file_name = %s\n",
1348 (ldd_file_name ? ldd_file_name : "not found"));
1349 #endif
1350 fprintf (stderr, "strip_file_name = %s\n",
1351 (strip_file_name ? strip_file_name : "not found"));
1352 fprintf (stderr, "c_file = %s\n",
1353 (c_file ? c_file : "not found"));
1354 fprintf (stderr, "o_file = %s\n",
1355 (o_file ? o_file : "not found"));
1357 ptr = getenv ("COLLECT_GCC_OPTIONS");
1358 if (ptr)
1359 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1361 ptr = getenv ("COLLECT_GCC");
1362 if (ptr)
1363 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1365 ptr = getenv ("COMPILER_PATH");
1366 if (ptr)
1367 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1369 ptr = getenv (LIBRARY_PATH_ENV);
1370 if (ptr)
1371 fprintf (stderr, "%-20s= %s\n", LIBRARY_PATH_ENV, ptr);
1373 fprintf (stderr, "\n");
1376 /* Load the program, searching all libraries and attempting to provide
1377 undefined symbols from repository information. */
1379 /* On AIX we do this later. */
1380 #ifndef COLLECT_EXPORT_LIST
1381 do_tlink (ld1_argv, object_lst);
1382 #endif
1384 /* If -r or they will be run via some other method, do not build the
1385 constructor or destructor list, just return now. */
1386 if (rflag
1387 #ifndef COLLECT_EXPORT_LIST
1388 || ! do_collecting
1389 #endif
1392 #ifdef COLLECT_EXPORT_LIST
1393 /* Do the link we avoided above if we are exiting. */
1394 do_tlink (ld1_argv, object_lst);
1396 /* But make sure we delete the export file we may have created. */
1397 if (export_file != 0 && export_file[0])
1398 maybe_unlink (export_file);
1399 if (import_file != 0 && import_file[0])
1400 maybe_unlink (import_file);
1401 #endif
1402 maybe_unlink (c_file);
1403 maybe_unlink (o_file);
1404 return 0;
1407 /* Examine the namelist with nm and search it for static constructors
1408 and destructors to call.
1409 Write the constructor and destructor tables to a .s file and reload. */
1411 /* On AIX we already scanned for global constructors/destructors. */
1412 #ifndef COLLECT_EXPORT_LIST
1413 scan_prog_file (output_file, PASS_FIRST);
1414 #endif
1416 #ifdef SCAN_LIBRARIES
1417 scan_libraries (output_file);
1418 #endif
1420 if (debug)
1422 notice ("%d constructor(s) found\n", constructors.number);
1423 notice ("%d destructor(s) found\n", destructors.number);
1424 notice ("%d frame table(s) found\n", frame_tables.number);
1427 if (constructors.number == 0 && destructors.number == 0
1428 && frame_tables.number == 0
1429 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1430 /* If we will be running these functions ourselves, we want to emit
1431 stubs into the shared library so that we do not have to relink
1432 dependent programs when we add static objects. */
1433 && ! shared_obj
1434 #endif
1437 #ifdef COLLECT_EXPORT_LIST
1438 /* Do tlink without additional code generation */
1439 do_tlink (ld1_argv, object_lst);
1440 #endif
1441 /* Strip now if it was requested on the command line. */
1442 if (strip_flag)
1444 char **real_strip_argv = (char **) xcalloc (sizeof (char *), 3);
1445 const char ** strip_argv = (const char **) real_strip_argv;
1447 strip_argv[0] = strip_file_name;
1448 strip_argv[1] = output_file;
1449 strip_argv[2] = (char *) 0;
1450 fork_execute ("strip", real_strip_argv);
1453 #ifdef COLLECT_EXPORT_LIST
1454 maybe_unlink (export_file);
1455 maybe_unlink (import_file);
1456 #endif
1457 maybe_unlink (c_file);
1458 maybe_unlink (o_file);
1459 return 0;
1462 /* Sort ctor and dtor lists by priority. */
1463 sort_ids (&constructors);
1464 sort_ids (&destructors);
1466 maybe_unlink(output_file);
1467 outf = fopen (c_file, "w");
1468 if (outf == (FILE *) 0)
1469 fatal_perror ("fopen %s", c_file);
1471 write_c_file (outf, c_file);
1473 if (fclose (outf))
1474 fatal_perror ("fclose %s", c_file);
1476 /* Tell the linker that we have initializer and finalizer functions. */
1477 #ifdef LD_INIT_SWITCH
1478 #ifdef COLLECT_EXPORT_LIST
1480 /* option name + functions + colons + NULL */
1481 char *buf = xmalloc (strlen (LD_INIT_SWITCH)
1482 + strlen(initname) + strlen(fininame) + 3);
1483 sprintf (buf, "%s:%s:%s", LD_INIT_SWITCH, initname, fininame);
1484 *ld2++ = buf;
1486 #else
1487 *ld2++ = LD_INIT_SWITCH;
1488 *ld2++ = initname;
1489 *ld2++ = LD_FINI_SWITCH;
1490 *ld2++ = fininame;
1491 #endif
1492 #endif
1494 #ifdef COLLECT_EXPORT_LIST
1495 if (shared_obj)
1497 /* If we did not add export flag to link arguments before, add it to
1498 second link phase now. No new exports should have been added. */
1499 if (! exports.first)
1501 char *buf = xmalloc (strlen (export_file) + 5);
1503 sprintf (buf, "-bE:%s", export_file);
1504 *ld2++ = buf;
1507 add_to_list (&exports, initname);
1508 add_to_list (&exports, fininame);
1509 add_to_list (&exports, "_GLOBAL__DI");
1510 add_to_list (&exports, "_GLOBAL__DD");
1511 exportf = fopen (export_file, "w");
1512 if (exportf == (FILE *) 0)
1513 fatal_perror ("fopen %s", export_file);
1514 write_aix_file (exportf, exports.first);
1515 if (fclose (exportf))
1516 fatal_perror ("fclose %s", export_file);
1518 #endif
1520 /* End of arguments to second link phase. */
1521 *ld2 = (char*) 0;
1523 if (debug)
1525 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1526 output_file, c_file);
1527 write_c_file (stderr, "stderr");
1528 fprintf (stderr, "========== end of c_file\n\n");
1529 #ifdef COLLECT_EXPORT_LIST
1530 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1531 write_aix_file (stderr, exports.first);
1532 fprintf (stderr, "========== end of export_file\n\n");
1533 #endif
1536 /* Assemble the constructor and destructor tables.
1537 Link the tables in with the rest of the program. */
1539 fork_execute ("gcc", c_argv);
1540 #ifdef COLLECT_EXPORT_LIST
1541 /* On AIX we must call tlink because of possible templates resolution */
1542 do_tlink (ld2_argv, object_lst);
1543 #else
1544 /* Otherwise, simply call ld because tlink is already done */
1545 fork_execute ("ld", ld2_argv);
1547 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1548 constructors/destructors in shared libraries. */
1549 scan_prog_file (output_file, PASS_SECOND);
1550 #endif
1552 maybe_unlink (c_file);
1553 maybe_unlink (o_file);
1555 #ifdef COLLECT_EXPORT_LIST
1556 maybe_unlink (export_file);
1557 maybe_unlink (import_file);
1558 #endif
1560 return 0;
1564 /* Wait for a process to finish, and exit if a non-zero status is found. */
1567 collect_wait (prog)
1568 const char *prog;
1570 int status;
1572 pwait (pexecute_pid, &status, 0);
1573 if (status)
1575 if (WIFSIGNALED (status))
1577 int sig = WTERMSIG (status);
1578 error ("%s terminated with signal %d [%s]%s",
1579 prog, sig, strsignal(sig),
1580 status & 0200 ? "" : ", core dumped");
1581 collect_exit (FATAL_EXIT_CODE);
1584 if (WIFEXITED (status))
1585 return WEXITSTATUS (status);
1587 return 0;
1590 static void
1591 do_wait (prog)
1592 const char *prog;
1594 int ret = collect_wait (prog);
1595 if (ret != 0)
1597 error ("%s returned %d exit status", prog, ret);
1598 collect_exit (ret);
1603 /* Execute a program, and wait for the reply. */
1605 void
1606 collect_execute (prog, argv, redir)
1607 const char *prog;
1608 char **argv;
1609 const char *redir;
1611 char *errmsg_fmt;
1612 char *errmsg_arg;
1613 int redir_handle = -1;
1614 int stdout_save = -1;
1615 int stderr_save = -1;
1617 if (vflag || debug)
1619 char **p_argv;
1620 const char *str;
1622 if (argv[0])
1623 fprintf (stderr, "%s", argv[0]);
1624 else
1625 notice ("[cannot find %s]", prog);
1627 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1628 fprintf (stderr, " %s", str);
1630 fprintf (stderr, "\n");
1633 fflush (stdout);
1634 fflush (stderr);
1636 /* If we cannot find a program we need, complain error. Do this here
1637 since we might not end up needing something that we could not find. */
1639 if (argv[0] == 0)
1640 fatal ("cannot find `%s'", prog);
1642 if (redir)
1644 /* Open response file. */
1645 redir_handle = open (redir, O_WRONLY | O_TRUNC | O_CREAT);
1647 /* Duplicate the stdout and stderr file handles
1648 so they can be restored later. */
1649 stdout_save = dup (STDOUT_FILENO);
1650 if (stdout_save == -1)
1651 fatal_perror ("redirecting stdout: %s", redir);
1652 stderr_save = dup (STDERR_FILENO);
1653 if (stderr_save == -1)
1654 fatal_perror ("redirecting stdout: %s", redir);
1656 /* Redirect stdout & stderr to our response file. */
1657 dup2 (redir_handle, STDOUT_FILENO);
1658 dup2 (redir_handle, STDERR_FILENO);
1661 pexecute_pid = pexecute (argv[0], argv, argv[0], NULL,
1662 &errmsg_fmt, &errmsg_arg,
1663 (PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH));
1665 if (redir)
1667 /* Restore stdout and stderr to their previous settings. */
1668 dup2 (stdout_save, STDOUT_FILENO);
1669 dup2 (stderr_save, STDERR_FILENO);
1671 /* Close reponse file. */
1672 close (redir_handle);
1675 if (pexecute_pid == -1)
1676 fatal_perror (errmsg_fmt, errmsg_arg);
1679 static void
1680 fork_execute (prog, argv)
1681 const char *prog;
1682 char **argv;
1684 collect_execute (prog, argv, NULL);
1685 do_wait (prog);
1688 /* Unlink a file unless we are debugging. */
1690 static void
1691 maybe_unlink (file)
1692 const char *file;
1694 if (!debug)
1695 unlink (file);
1696 else
1697 notice ("[Leaving %s]\n", file);
1701 static long sequence_number = 0;
1703 /* Add a name to a linked list. */
1705 static void
1706 add_to_list (head_ptr, name)
1707 struct head *head_ptr;
1708 const char *name;
1710 struct id *newid
1711 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1712 struct id *p;
1713 strcpy (newid->name, name);
1715 if (head_ptr->first)
1716 head_ptr->last->next = newid;
1717 else
1718 head_ptr->first = newid;
1720 /* Check for duplicate symbols. */
1721 for (p = head_ptr->first;
1722 strcmp (name, p->name) != 0;
1723 p = p->next)
1725 if (p != newid)
1727 head_ptr->last->next = 0;
1728 free (newid);
1729 return;
1732 newid->sequence = ++sequence_number;
1733 head_ptr->last = newid;
1734 head_ptr->number++;
1737 /* Grab the init priority number from an init function name that
1738 looks like "_GLOBAL_.I.12345.foo". */
1740 static int
1741 extract_init_priority (name)
1742 const char *name;
1744 int pos = 0, pri;
1746 while (name[pos] == '_')
1747 ++pos;
1748 pos += 10; /* strlen ("GLOBAL__X_") */
1750 /* Extract init_p number from ctor/dtor name. */
1751 pri = atoi (name + pos);
1752 return pri ? pri : DEFAULT_INIT_PRIORITY;
1755 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1756 ctors will be run from right to left, dtors from left to right. */
1758 static void
1759 sort_ids (head_ptr)
1760 struct head *head_ptr;
1762 /* id holds the current element to insert. id_next holds the next
1763 element to insert. id_ptr iterates through the already sorted elements
1764 looking for the place to insert id. */
1765 struct id *id, *id_next, **id_ptr;
1767 id = head_ptr->first;
1769 /* We don't have any sorted elements yet. */
1770 head_ptr->first = NULL;
1772 for (; id; id = id_next)
1774 id_next = id->next;
1775 id->sequence = extract_init_priority (id->name);
1777 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1778 if (*id_ptr == NULL
1779 /* If the sequence numbers are the same, we put the id from the
1780 file later on the command line later in the list. */
1781 || id->sequence > (*id_ptr)->sequence
1782 /* Hack: do lexical compare, too.
1783 || (id->sequence == (*id_ptr)->sequence
1784 && strcmp (id->name, (*id_ptr)->name) > 0) */
1787 id->next = *id_ptr;
1788 *id_ptr = id;
1789 break;
1793 /* Now set the sequence numbers properly so write_c_file works. */
1794 for (id = head_ptr->first; id; id = id->next)
1795 id->sequence = ++sequence_number;
1798 /* Write: `prefix', the names on list LIST, `suffix'. */
1800 static void
1801 write_list (stream, prefix, list)
1802 FILE *stream;
1803 const char *prefix;
1804 struct id *list;
1806 while (list)
1808 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1809 list = list->next;
1813 #ifdef COLLECT_EXPORT_LIST
1814 /* This function is really used only on AIX, but may be useful. */
1815 static int
1816 is_in_list (prefix, list)
1817 const char *prefix;
1818 struct id *list;
1820 while (list)
1822 if (!strcmp (prefix, list->name)) return 1;
1823 list = list->next;
1825 return 0;
1827 #endif
1829 /* Added for debugging purpose. */
1830 #ifdef COLLECT_EXPORT_LIST
1831 static void
1832 dump_list (stream, prefix, list)
1833 FILE *stream;
1834 const char *prefix;
1835 struct id *list;
1837 while (list)
1839 fprintf (stream, "%s%s,\n", prefix, list->name);
1840 list = list->next;
1843 #endif
1845 #if 0
1846 static void
1847 dump_prefix_list (stream, prefix, list)
1848 FILE *stream;
1849 const char *prefix;
1850 struct prefix_list *list;
1852 while (list)
1854 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1855 list = list->next;
1858 #endif
1860 static void
1861 write_list_with_asm (stream, prefix, list)
1862 FILE *stream;
1863 const char *prefix;
1864 struct id *list;
1866 while (list)
1868 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1869 prefix, list->sequence, list->name);
1870 list = list->next;
1874 /* Write out the constructor and destructor tables statically (for a shared
1875 object), along with the functions to execute them. */
1877 static void
1878 write_c_file_stat (stream, name)
1879 FILE *stream;
1880 const char *name ATTRIBUTE_UNUSED;
1882 const char *p, *q;
1883 char *prefix, *r;
1884 int frames = (frame_tables.number > 0);
1886 /* Figure out name of output_file, stripping off .so version. */
1887 p = rindex (output_file, '/');
1888 if (p == 0)
1889 p = output_file;
1890 else
1891 p++;
1892 q = p;
1893 while (q)
1895 q = index (q,'.');
1896 if (q == 0)
1898 q = p + strlen (p);
1899 break;
1901 else
1903 if (strncmp (q, ".so", 3) == 0)
1905 q += 3;
1906 break;
1908 else
1909 q++;
1912 /* q points to null at end of the string (or . of the .so version) */
1913 prefix = xmalloc (q - p + 1);
1914 strncpy (prefix, p, q - p);
1915 prefix[q - p] = 0;
1916 for (r = prefix; *r; r++)
1917 if (!ISALNUM ((unsigned char)*r))
1918 *r = '_';
1919 if (debug)
1920 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1921 output_file, prefix);
1923 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1924 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1925 sprintf (initname, INIT_NAME_FORMAT, prefix);
1927 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1928 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1929 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1931 free (prefix);
1933 /* Write the tables as C code */
1935 fprintf (stream, "static int count;\n");
1936 fprintf (stream, "typedef void entry_pt();\n");
1937 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1939 if (frames)
1941 write_list_with_asm (stream, "extern void *", frame_tables.first);
1943 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1944 write_list (stream, "\t\t&", frame_tables.first);
1945 fprintf (stream, "\t0\n};\n");
1947 /* This must match what's in frame.h. */
1948 fprintf (stream, "struct object {\n");
1949 fprintf (stream, " void *pc_begin;\n");
1950 fprintf (stream, " void *pc_end;\n");
1951 fprintf (stream, " void *fde_begin;\n");
1952 fprintf (stream, " void *fde_array;\n");
1953 fprintf (stream, " __SIZE_TYPE__ count;\n");
1954 fprintf (stream, " struct object *next;\n");
1955 fprintf (stream, "};\n");
1957 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1958 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1960 fprintf (stream, "static void reg_frame () {\n");
1961 fprintf (stream, "\tstatic struct object ob;\n");
1962 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1963 fprintf (stream, "\t}\n");
1965 fprintf (stream, "static void dereg_frame () {\n");
1966 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1967 fprintf (stream, "\t}\n");
1970 fprintf (stream, "void %s() {\n", initname);
1971 if (constructors.number > 0 || frames)
1973 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1974 write_list (stream, "\t\t", constructors.first);
1975 if (frames)
1976 fprintf (stream, "\treg_frame,\n");
1977 fprintf (stream, "\t};\n");
1978 fprintf (stream, "\tentry_pt **p;\n");
1979 fprintf (stream, "\tif (count++ != 0) return;\n");
1980 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1981 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1983 else
1984 fprintf (stream, "\t++count;\n");
1985 fprintf (stream, "}\n");
1986 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1987 fprintf (stream, "void %s() {\n", fininame);
1988 if (destructors.number > 0 || frames)
1990 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1991 write_list (stream, "\t\t", destructors.first);
1992 if (frames)
1993 fprintf (stream, "\tdereg_frame,\n");
1994 fprintf (stream, "\t};\n");
1995 fprintf (stream, "\tentry_pt **p;\n");
1996 fprintf (stream, "\tif (--count != 0) return;\n");
1997 fprintf (stream, "\tp = dtors;\n");
1998 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1999 destructors.number + frames);
2001 fprintf (stream, "}\n");
2003 if (shared_obj)
2005 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
2006 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
2010 /* Write the constructor/destructor tables. */
2012 #ifndef LD_INIT_SWITCH
2013 static void
2014 write_c_file_glob (stream, name)
2015 FILE *stream;
2016 const char *name ATTRIBUTE_UNUSED;
2018 /* Write the tables as C code */
2020 int frames = (frame_tables.number > 0);
2022 fprintf (stream, "typedef void entry_pt();\n\n");
2024 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2026 if (frames)
2028 write_list_with_asm (stream, "extern void *", frame_tables.first);
2030 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2031 write_list (stream, "\t\t&", frame_tables.first);
2032 fprintf (stream, "\t0\n};\n");
2034 /* This must match what's in frame.h. */
2035 fprintf (stream, "struct object {\n");
2036 fprintf (stream, " void *pc_begin;\n");
2037 fprintf (stream, " void *pc_end;\n");
2038 fprintf (stream, " void *fde_begin;\n");
2039 fprintf (stream, " void *fde_array;\n");
2040 fprintf (stream, " __SIZE_TYPE__ count;\n");
2041 fprintf (stream, " struct object *next;\n");
2042 fprintf (stream, "};\n");
2044 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2045 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2047 fprintf (stream, "static void reg_frame () {\n");
2048 fprintf (stream, "\tstatic struct object ob;\n");
2049 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2050 fprintf (stream, "\t}\n");
2052 fprintf (stream, "static void dereg_frame () {\n");
2053 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2054 fprintf (stream, "\t}\n");
2057 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2058 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2059 write_list (stream, "\t", constructors.first);
2060 if (frames)
2061 fprintf (stream, "\treg_frame,\n");
2062 fprintf (stream, "\t0\n};\n\n");
2064 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2066 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2067 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2068 write_list (stream, "\t", destructors.first);
2069 if (frames)
2070 fprintf (stream, "\tdereg_frame,\n");
2071 fprintf (stream, "\t0\n};\n\n");
2073 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2074 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2076 #endif /* ! LD_INIT_SWITCH */
2078 static void
2079 write_c_file (stream, name)
2080 FILE *stream;
2081 const char *name;
2083 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2084 #ifndef LD_INIT_SWITCH
2085 if (! shared_obj)
2086 write_c_file_glob (stream, name);
2087 else
2088 #endif
2089 write_c_file_stat (stream, name);
2090 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2093 #ifdef COLLECT_EXPORT_LIST
2094 static void
2095 write_aix_file (stream, list)
2096 FILE *stream;
2097 struct id *list;
2099 for (; list; list = list->next)
2101 fputs (list->name, stream);
2102 putc ('\n', stream);
2105 #endif
2107 #ifdef OBJECT_FORMAT_NONE
2109 /* Generic version to scan the name list of the loaded program for
2110 the symbols g++ uses for static constructors and destructors.
2112 The constructor table begins at __CTOR_LIST__ and contains a count
2113 of the number of pointers (or -1 if the constructors are built in a
2114 separate section by the linker), followed by the pointers to the
2115 constructor functions, terminated with a null pointer. The
2116 destructor table has the same format, and begins at __DTOR_LIST__. */
2118 static void
2119 scan_prog_file (prog_name, which_pass)
2120 const char *prog_name;
2121 enum pass which_pass;
2123 void (*int_handler) PARAMS ((int));
2124 void (*quit_handler) PARAMS ((int));
2125 char *real_nm_argv[4];
2126 const char **nm_argv = (const char **) real_nm_argv;
2127 int pid;
2128 int argc = 0;
2129 int pipe_fd[2];
2130 char *p, buf[1024];
2131 FILE *inf;
2133 if (which_pass == PASS_SECOND)
2134 return;
2136 /* If we do not have an `nm', complain. */
2137 if (nm_file_name == 0)
2138 fatal ("cannot find `nm'");
2140 nm_argv[argc++] = nm_file_name;
2141 if (NM_FLAGS[0] != '\0')
2142 nm_argv[argc++] = NM_FLAGS;
2144 nm_argv[argc++] = prog_name;
2145 nm_argv[argc++] = (char *) 0;
2147 if (pipe (pipe_fd) < 0)
2148 fatal_perror ("pipe");
2150 inf = fdopen (pipe_fd[0], "r");
2151 if (inf == (FILE *) 0)
2152 fatal_perror ("fdopen");
2154 /* Trace if needed. */
2155 if (vflag)
2157 const char **p_argv;
2158 const char *str;
2160 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2161 fprintf (stderr, " %s", str);
2163 fprintf (stderr, "\n");
2166 fflush (stdout);
2167 fflush (stderr);
2169 /* Spawn child nm on pipe */
2170 pid = vfork ();
2171 if (pid == -1)
2172 fatal_perror (VFORK_STRING);
2174 if (pid == 0) /* child context */
2176 /* setup stdout */
2177 if (dup2 (pipe_fd[1], 1) < 0)
2178 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2180 if (close (pipe_fd[0]) < 0)
2181 fatal_perror ("close %d", pipe_fd[0]);
2183 if (close (pipe_fd[1]) < 0)
2184 fatal_perror ("close %d", pipe_fd[1]);
2186 execv (nm_file_name, real_nm_argv);
2187 fatal_perror ("execvp %s", nm_file_name);
2190 /* Parent context from here on. */
2191 int_handler = (void (*) PARAMS ((int))) signal (SIGINT, SIG_IGN);
2192 #ifdef SIGQUIT
2193 quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2194 #endif
2196 if (close (pipe_fd[1]) < 0)
2197 fatal_perror ("close %d", pipe_fd[1]);
2199 if (debug)
2200 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2202 /* Read each line of nm output. */
2203 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2205 int ch, ch2;
2206 char *name, *end;
2208 /* If it contains a constructor or destructor name, add the name
2209 to the appropriate list. */
2211 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2212 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2213 break;
2215 if (ch != '_')
2216 continue;
2218 name = p;
2219 /* Find the end of the symbol name.
2220 Do not include `|', because Encore nm can tack that on the end. */
2221 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2222 end++)
2223 continue;
2226 *end = '\0';
2227 switch (is_ctor_dtor (name))
2229 case 1:
2230 if (which_pass != PASS_LIB)
2231 add_to_list (&constructors, name);
2232 break;
2234 case 2:
2235 if (which_pass != PASS_LIB)
2236 add_to_list (&destructors, name);
2237 break;
2239 case 3:
2240 if (which_pass != PASS_LIB)
2241 fatal ("init function found in object %s", prog_name);
2242 #ifndef LD_INIT_SWITCH
2243 add_to_list (&constructors, name);
2244 #endif
2245 break;
2247 case 4:
2248 if (which_pass != PASS_LIB)
2249 fatal ("fini function found in object %s", prog_name);
2250 #ifndef LD_FINI_SWITCH
2251 add_to_list (&destructors, name);
2252 #endif
2253 break;
2255 case 5:
2256 if (which_pass != PASS_LIB)
2257 add_to_list (&frame_tables, name);
2258 break;
2260 default: /* not a constructor or destructor */
2261 continue;
2264 if (debug)
2265 fprintf (stderr, "\t%s\n", buf);
2268 if (debug)
2269 fprintf (stderr, "\n");
2271 if (fclose (inf) != 0)
2272 fatal_perror ("fclose");
2274 do_wait (nm_file_name);
2276 signal (SIGINT, int_handler);
2277 #ifdef SIGQUIT
2278 signal (SIGQUIT, quit_handler);
2279 #endif
2282 #if SUNOS4_SHARED_LIBRARIES
2284 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2285 that the output file depends upon and their initialization/finalization
2286 routines, if any. */
2288 #include <a.out.h>
2289 #include <fcntl.h>
2290 #include <link.h>
2291 #include <sys/mman.h>
2292 #include <sys/param.h>
2293 #include <unistd.h>
2294 #include <sys/dir.h>
2296 /* pointers to the object file */
2297 unsigned object; /* address of memory mapped file */
2298 unsigned objsize; /* size of memory mapped to file */
2299 char * code; /* pointer to code segment */
2300 char * data; /* pointer to data segment */
2301 struct nlist *symtab; /* pointer to symbol table */
2302 struct link_dynamic *ld;
2303 struct link_dynamic_2 *ld_2;
2304 struct head libraries;
2306 /* Map the file indicated by NAME into memory and store its address. */
2308 static void mapfile PARAMS ((const char *));
2310 static void
2311 mapfile (name)
2312 const char *name;
2314 int fp;
2315 struct stat s;
2316 if ((fp = open (name, O_RDONLY)) == -1)
2317 fatal ("unable to open file '%s'", name);
2318 if (fstat (fp, &s) == -1)
2319 fatal ("unable to stat file '%s'", name);
2321 objsize = s.st_size;
2322 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2323 fp, 0);
2324 if (object == (unsigned)-1)
2325 fatal ("unable to mmap file '%s'", name);
2327 close (fp);
2330 /* Helpers for locatelib. */
2332 static const char *libname;
2334 static int libselect PARAMS ((struct direct *));
2336 static int
2337 libselect (d)
2338 struct direct *d;
2340 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2343 /* If one file has an additional numeric extension past LIBNAME, then put
2344 that one first in the sort. If both files have additional numeric
2345 extensions, then put the one with the higher number first in the sort.
2347 We must verify that the extension is numeric, because Sun saves the
2348 original versions of patched libraries with a .FCS extension. Files with
2349 invalid extensions must go last in the sort, so that they will not be used. */
2350 static int libcompare PARAMS ((struct direct **, struct direct **));
2352 static int
2353 libcompare (d1, d2)
2354 struct direct **d1, **d2;
2356 int i1, i2 = strlen (libname);
2357 char *e1 = (*d1)->d_name + i2;
2358 char *e2 = (*d2)->d_name + i2;
2360 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2361 && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2363 ++e1;
2364 ++e2;
2365 i1 = strtol (e1, &e1, 10);
2366 i2 = strtol (e2, &e2, 10);
2367 if (i1 != i2)
2368 return i1 - i2;
2371 if (*e1)
2373 /* It has a valid numeric extension, prefer this one. */
2374 if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2375 return 1;
2376 /* It has a invalid numeric extension, must prefer the other one. */
2377 else
2378 return -1;
2380 else if (*e2)
2382 /* It has a valid numeric extension, prefer this one. */
2383 if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2384 return -1;
2385 /* It has a invalid numeric extension, must prefer the other one. */
2386 else
2387 return 1;
2389 else
2390 return 0;
2393 /* Given the name NAME of a dynamic dependency, find its pathname and add
2394 it to the list of libraries. */
2395 static void locatelib PARAMS ((const char *));
2397 static void
2398 locatelib (name)
2399 const char *name;
2401 static const char **l;
2402 static int cnt;
2403 char buf[MAXPATHLEN];
2404 char *p, *q;
2405 const char **pp;
2407 if (l == 0)
2409 char *ld_rules;
2410 char *ldr = 0;
2411 /* counting elements in array, need 1 extra for null */
2412 cnt = 1;
2413 ld_rules = (char *) (ld_2->ld_rules + code);
2414 if (ld_rules)
2416 cnt++;
2417 for (; *ld_rules != 0; ld_rules++)
2418 if (*ld_rules == ':')
2419 cnt++;
2420 ld_rules = (char *) (ld_2->ld_rules + code);
2421 ldr = xstrdup (ld_rules);
2423 p = getenv ("LD_LIBRARY_PATH");
2424 q = 0;
2425 if (p)
2427 cnt++;
2428 for (q = p ; *q != 0; q++)
2429 if (*q == ':')
2430 cnt++;
2431 q = xstrdup (p);
2433 l = (const char **) xmalloc ((cnt + 3) * sizeof (char *));
2434 pp = l;
2435 if (ldr)
2437 *pp++ = ldr;
2438 for (; *ldr != 0; ldr++)
2439 if (*ldr == ':')
2441 *ldr++ = 0;
2442 *pp++ = ldr;
2445 if (q)
2447 *pp++ = q;
2448 for (; *q != 0; q++)
2449 if (*q == ':')
2451 *q++ = 0;
2452 *pp++ = q;
2455 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2456 *pp++ = "/lib";
2457 *pp++ = "/usr/lib";
2458 *pp++ = "/usr/local/lib";
2459 *pp = 0;
2461 libname = name;
2462 for (pp = l; *pp != 0 ; pp++)
2464 struct direct **namelist;
2465 int entries;
2466 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2468 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2469 add_to_list (&libraries, buf);
2470 if (debug)
2471 fprintf (stderr, "%s\n", buf);
2472 break;
2475 if (*pp == 0)
2477 if (debug)
2478 notice ("not found\n");
2479 else
2480 fatal ("dynamic dependency %s not found", name);
2484 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2485 that it depends upon and any constructors or destructors they contain. */
2487 static void
2488 scan_libraries (prog_name)
2489 const char *prog_name;
2491 struct exec *header;
2492 char *base;
2493 struct link_object *lo;
2494 char buff[MAXPATHLEN];
2495 struct id *list;
2497 mapfile (prog_name);
2498 header = (struct exec *)object;
2499 if (N_BADMAG (*header))
2500 fatal ("bad magic number in file '%s'", prog_name);
2501 if (header->a_dynamic == 0)
2502 return;
2504 code = (char *) (N_TXTOFF (*header) + (long) header);
2505 data = (char *) (N_DATOFF (*header) + (long) header);
2506 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2508 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2510 /* shared object */
2511 ld = (struct link_dynamic *) (symtab->n_value + code);
2512 base = code;
2514 else
2516 /* executable */
2517 ld = (struct link_dynamic *) data;
2518 base = code-PAGSIZ;
2521 if (debug)
2522 notice ("dynamic dependencies.\n");
2524 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2525 for (lo = (struct link_object *) ld_2->ld_need; lo;
2526 lo = (struct link_object *) lo->lo_next)
2528 char *name;
2529 lo = (struct link_object *) ((long) lo + code);
2530 name = (char *) (code + lo->lo_name);
2531 if (lo->lo_library)
2533 if (debug)
2534 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2535 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2536 locatelib (buff);
2538 else
2540 if (debug)
2541 fprintf (stderr, "\t%s\n", name);
2542 add_to_list (&libraries, name);
2546 if (debug)
2547 fprintf (stderr, "\n");
2549 /* now iterate through the library list adding their symbols to
2550 the list. */
2551 for (list = libraries.first; list; list = list->next)
2552 scan_prog_file (list->name, PASS_LIB);
2555 #else /* SUNOS4_SHARED_LIBRARIES */
2556 #ifdef LDD_SUFFIX
2558 /* Use the List Dynamic Dependencies program to find shared libraries that
2559 the output file depends upon and their initialization/finalization
2560 routines, if any. */
2562 static void
2563 scan_libraries (prog_name)
2564 const char *prog_name;
2566 static struct head libraries; /* list of shared libraries found */
2567 struct id *list;
2568 void (*int_handler) PARAMS ((int));
2569 void (*quit_handler) PARAMS ((int));
2570 char *real_ldd_argv[4];
2571 const char **ldd_argv = (const char **) real_ldd_argv;
2572 int pid;
2573 int argc = 0;
2574 int pipe_fd[2];
2575 char buf[1024];
2576 FILE *inf;
2578 /* If we do not have an `ldd', complain. */
2579 if (ldd_file_name == 0)
2581 error ("cannot find `ldd'");
2582 return;
2585 ldd_argv[argc++] = ldd_file_name;
2586 ldd_argv[argc++] = prog_name;
2587 ldd_argv[argc++] = (char *) 0;
2589 if (pipe (pipe_fd) < 0)
2590 fatal_perror ("pipe");
2592 inf = fdopen (pipe_fd[0], "r");
2593 if (inf == (FILE *) 0)
2594 fatal_perror ("fdopen");
2596 /* Trace if needed. */
2597 if (vflag)
2599 const char **p_argv;
2600 const char *str;
2602 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2603 fprintf (stderr, " %s", str);
2605 fprintf (stderr, "\n");
2608 fflush (stdout);
2609 fflush (stderr);
2611 /* Spawn child ldd on pipe */
2612 pid = vfork ();
2613 if (pid == -1)
2614 fatal_perror (VFORK_STRING);
2616 if (pid == 0) /* child context */
2618 /* setup stdout */
2619 if (dup2 (pipe_fd[1], 1) < 0)
2620 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2622 if (close (pipe_fd[0]) < 0)
2623 fatal_perror ("close %d", pipe_fd[0]);
2625 if (close (pipe_fd[1]) < 0)
2626 fatal_perror ("close %d", pipe_fd[1]);
2628 execv (ldd_file_name, real_ldd_argv);
2629 fatal_perror ("execv %s", ldd_file_name);
2632 /* Parent context from here on. */
2633 int_handler = (void (*) PARAMS ((int))) signal (SIGINT, SIG_IGN);
2634 #ifdef SIGQUIT
2635 quit_handler = (void (*) PARAMS ((int))) signal (SIGQUIT, SIG_IGN);
2636 #endif
2638 if (close (pipe_fd[1]) < 0)
2639 fatal_perror ("close %d", pipe_fd[1]);
2641 if (debug)
2642 notice ("\nldd output with constructors/destructors.\n");
2644 /* Read each line of ldd output. */
2645 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2647 int ch, ch2;
2648 char *name, *end, *p = buf;
2650 /* Extract names of libraries and add to list. */
2651 PARSE_LDD_OUTPUT (p);
2652 if (p == 0)
2653 continue;
2655 name = p;
2656 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2657 fatal ("dynamic dependency %s not found", buf);
2659 /* Find the end of the symbol name. */
2660 for (end = p;
2661 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2662 end++)
2663 continue;
2664 *end = '\0';
2666 if (access (name, R_OK) == 0)
2667 add_to_list (&libraries, name);
2668 else
2669 fatal ("unable to open dynamic dependency '%s'", buf);
2671 if (debug)
2672 fprintf (stderr, "\t%s\n", buf);
2674 if (debug)
2675 fprintf (stderr, "\n");
2677 if (fclose (inf) != 0)
2678 fatal_perror ("fclose");
2680 do_wait (ldd_file_name);
2682 signal (SIGINT, int_handler);
2683 #ifdef SIGQUIT
2684 signal (SIGQUIT, quit_handler);
2685 #endif
2687 /* now iterate through the library list adding their symbols to
2688 the list. */
2689 for (list = libraries.first; list; list = list->next)
2690 scan_prog_file (list->name, PASS_LIB);
2693 #endif /* LDD_SUFFIX */
2694 #endif /* SUNOS4_SHARED_LIBRARIES */
2696 #endif /* OBJECT_FORMAT_NONE */
2700 * COFF specific stuff.
2703 #ifdef OBJECT_FORMAT_COFF
2705 #if defined(EXTENDED_COFF)
2706 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2707 # define GCC_SYMENT SYMR
2708 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2709 # define GCC_SYMINC(X) (1)
2710 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2711 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2712 #else
2713 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2714 # define GCC_SYMENT SYMENT
2715 # define GCC_OK_SYMBOL(X) \
2716 (((X).n_sclass == C_EXT) && \
2717 ((X).n_scnum > N_UNDEF) && \
2718 (aix64_flag \
2719 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2720 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2721 # define GCC_UNDEF_SYMBOL(X) \
2722 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2723 # define GCC_SYMINC(X) ((X).n_numaux+1)
2724 # define GCC_SYMZERO(X) 0
2725 # define GCC_CHECK_HDR(X) \
2726 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2727 || (HEADER (X).f_magic == 0757 && aix64_flag))
2728 #endif
2730 extern char *ldgetname ();
2732 /* COFF version to scan the name list of the loaded program for
2733 the symbols g++ uses for static constructors and destructors.
2735 The constructor table begins at __CTOR_LIST__ and contains a count
2736 of the number of pointers (or -1 if the constructors are built in a
2737 separate section by the linker), followed by the pointers to the
2738 constructor functions, terminated with a null pointer. The
2739 destructor table has the same format, and begins at __DTOR_LIST__. */
2741 static void
2742 scan_prog_file (prog_name, which_pass)
2743 const char *prog_name;
2744 enum pass which_pass;
2746 LDFILE *ldptr = NULL;
2747 int sym_index, sym_count;
2748 int is_shared = 0;
2749 #ifdef COLLECT_EXPORT_LIST
2750 /* Should we generate an import list for given prog_name? */
2751 int import_flag = (which_pass == PASS_OBJ ? 0 : use_import_list (prog_name));
2752 #endif
2754 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2755 return;
2757 #ifdef COLLECT_EXPORT_LIST
2758 /* We do not need scanning for some standard C libraries. */
2759 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2760 return;
2762 /* On AIX we have a loop, because there is not much difference
2763 between an object and an archive. This trick allows us to
2764 eliminate scan_libraries() function. */
2767 #endif
2768 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2769 non-const char * filename parameter, even though it will not
2770 modify that string. So we must cast away const-ness here,
2771 which will cause -Wcast-qual to burp. */
2772 if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2774 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2775 fatal ("%s: not a COFF file", prog_name);
2777 if (GCC_CHECK_HDR (ldptr))
2779 sym_count = GCC_SYMBOLS (ldptr);
2780 sym_index = GCC_SYMZERO (ldptr);
2782 #ifdef COLLECT_EXPORT_LIST
2783 /* Is current archive member a shared object? */
2784 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2785 #endif
2787 while (sym_index < sym_count)
2789 GCC_SYMENT symbol;
2791 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2792 break;
2793 sym_index += GCC_SYMINC (symbol);
2795 if (GCC_OK_SYMBOL (symbol))
2797 char *name;
2799 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2800 continue; /* should never happen */
2802 #ifdef XCOFF_DEBUGGING_INFO
2803 /* All AIX function names have a duplicate entry
2804 beginning with a dot. */
2805 if (*name == '.')
2806 ++name;
2807 #endif
2809 switch (is_ctor_dtor (name))
2811 case 1:
2812 if (! is_shared)
2813 add_to_list (&constructors, name);
2814 #ifdef COLLECT_EXPORT_LIST
2815 if (which_pass == PASS_OBJ)
2816 add_to_list (&exports, name);
2817 /* If this symbol was undefined and we are building
2818 an import list, we should add a symbol to this
2819 list. */
2820 else
2821 if (import_flag
2822 && is_in_list (name, undefined.first))
2823 add_to_list (&imports, name);
2824 #endif
2825 break;
2827 case 2:
2828 if (! is_shared)
2829 add_to_list (&destructors, name);
2830 #ifdef COLLECT_EXPORT_LIST
2831 if (which_pass == PASS_OBJ)
2832 add_to_list (&exports, name);
2833 /* If this symbol was undefined and we are building
2834 an import list, we should add a symbol to this
2835 list. */
2836 else
2837 if (import_flag
2838 && is_in_list (name, undefined.first))
2839 add_to_list (&imports, name);
2840 #endif
2841 break;
2843 #ifdef COLLECT_EXPORT_LIST
2844 case 3:
2845 #ifndef LD_INIT_SWITCH
2846 if (is_shared)
2847 add_to_list (&constructors, name);
2848 #endif
2849 break;
2851 case 4:
2852 #ifndef LD_INIT_SWITCH
2853 if (is_shared)
2854 add_to_list (&destructors, name);
2855 #endif
2856 break;
2857 #endif
2859 case 5:
2860 if (! is_shared)
2861 add_to_list (&frame_tables, name);
2862 #ifdef COLLECT_EXPORT_LIST
2863 if (which_pass == PASS_OBJ)
2864 add_to_list (&exports, name);
2865 /* If we are building an import list, we
2866 should add the symbol to the list.
2867 We'd like to do it only if the symbol
2868 is not defined, but we can't tell
2869 that here (it is only known whether a symbol
2870 is referenced and not defined, but who
2871 would reference an EH table entry?). */
2872 else
2873 if (import_flag)
2874 add_to_list (&imports, name);
2875 #endif
2876 break;
2878 default: /* not a constructor or destructor */
2879 #ifdef COLLECT_EXPORT_LIST
2880 /* If we are building a shared object on AIX we need
2881 to explicitly export all global symbols or add
2882 them to import list. */
2883 if (shared_obj)
2885 if (which_pass == PASS_OBJ && (! export_flag))
2886 add_to_list (&exports, name);
2887 else if (! is_shared
2888 && which_pass == PASS_FIRST
2889 && import_flag
2890 && is_in_list(name, undefined.first))
2891 add_to_list (&imports, name);
2893 #endif
2894 continue;
2897 if (debug)
2898 #if !defined(EXTENDED_COFF)
2899 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2900 symbol.n_scnum, symbol.n_sclass,
2901 (symbol.n_type ? "0" : ""), symbol.n_type,
2902 name);
2903 #else
2904 fprintf (stderr,
2905 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2906 symbol.iss, (long) symbol.value, symbol.index, name);
2907 #endif
2909 #ifdef COLLECT_EXPORT_LIST
2910 /* If we are building a shared object we should collect
2911 information about undefined symbols for later
2912 import list generation. */
2913 else if (shared_obj && GCC_UNDEF_SYMBOL (symbol))
2915 char *name;
2917 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2918 continue; /* should never happen */
2920 /* All AIX function names have a duplicate entry
2921 beginning with a dot. */
2922 if (*name == '.')
2923 ++name;
2924 add_to_list (&undefined, name);
2926 #endif
2929 #ifdef COLLECT_EXPORT_LIST
2930 else
2932 /* If archive contains both 32-bit and 64-bit objects,
2933 we want to skip objects in other mode so mismatch normal. */
2934 if (debug)
2935 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2936 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2938 #endif
2940 else
2942 fatal ("%s: cannot open as COFF file", prog_name);
2944 #ifdef COLLECT_EXPORT_LIST
2945 /* On AIX loop continues while there are more members in archive. */
2947 while (ldclose (ldptr) == FAILURE);
2948 #else
2949 /* Otherwise we simply close ldptr. */
2950 (void) ldclose(ldptr);
2951 #endif
2955 #ifdef COLLECT_EXPORT_LIST
2957 /* This new function is used to decide whether we should
2958 generate import list for an object or to use it directly. */
2959 static int
2960 use_import_list (prog_name)
2961 const char *prog_name;
2963 char *p;
2965 /* If we do not build a shared object then import list should not be used. */
2966 if (! shared_obj) return 0;
2968 /* Currently we check only for libgcc, but this can be changed in future. */
2969 p = strstr (prog_name, "libgcc.a");
2970 if (p != 0 && (strlen (p) == sizeof ("libgcc.a") - 1))
2971 return 1;
2972 return 0;
2975 /* Given a library name without "lib" prefix, this function
2976 returns a full library name including a path. */
2977 static char *
2978 resolve_lib_name (name)
2979 const char *name;
2981 char *lib_buf;
2982 int i, j, l = 0;
2984 for (i = 0; libpaths[i]; i++)
2985 if (libpaths[i]->max_len > l)
2986 l = libpaths[i]->max_len;
2988 lib_buf = xmalloc (l + strlen(name) + 10);
2990 for (i = 0; libpaths[i]; i++)
2992 struct prefix_list *list = libpaths[i]->plist;
2993 for (; list; list = list->next)
2995 for (j = 0; libexts[j]; j++)
2997 /* The following lines are needed because path_prefix list
2998 may contain directories both with trailing '/' and
2999 without it. */
3000 const char *p = "";
3001 if (list->prefix[strlen(list->prefix)-1] != '/')
3002 p = "/";
3003 sprintf (lib_buf, "%s%slib%s.%s",
3004 list->prefix, p, name, libexts[j]);
3005 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
3006 if (file_exists (lib_buf))
3008 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
3009 return (lib_buf);
3014 if (debug)
3015 fprintf (stderr, "not found\n");
3016 else
3017 fatal ("Library lib%s not found", name);
3018 return (NULL);
3021 /* Array of standard AIX libraries which should not
3022 be scanned for ctors/dtors. */
3023 static const char *aix_std_libs[] = {
3024 "/unix",
3025 "/lib/libc.a",
3026 "/lib/libc_r.a",
3027 "/usr/lib/libc.a",
3028 "/usr/lib/libc_r.a",
3029 "/usr/lib/threads/libc.a",
3030 "/usr/ccs/lib/libc.a",
3031 "/usr/ccs/lib/libc_r.a",
3032 NULL
3035 /* This function checks the filename and returns 1
3036 if this name matches the location of a standard AIX library. */
3037 static int
3038 ignore_library (name)
3039 const char *name;
3041 const char **p = &aix_std_libs[0];
3042 while (*p++ != NULL)
3043 if (! strcmp (name, *p)) return 1;
3044 return 0;
3047 #endif
3049 #endif /* OBJECT_FORMAT_COFF */
3053 * OSF/rose specific stuff.
3056 #ifdef OBJECT_FORMAT_ROSE
3058 /* Union of the various load commands */
3060 typedef union load_union
3062 ldc_header_t hdr; /* common header */
3063 load_cmd_map_command_t map; /* map indexing other load cmds */
3064 interpreter_command_t iprtr; /* interpreter pathname */
3065 strings_command_t str; /* load commands strings section */
3066 region_command_t region; /* region load command */
3067 reloc_command_t reloc; /* relocation section */
3068 package_command_t pkg; /* package load command */
3069 symbols_command_t sym; /* symbol sections */
3070 entry_command_t ent; /* program start section */
3071 gen_info_command_t info; /* object information */
3072 func_table_command_t func; /* function constructors/destructors */
3073 } load_union_t;
3075 /* Structure to point to load command and data section in memory. */
3077 typedef struct load_all
3079 load_union_t *load; /* load command */
3080 char *section; /* pointer to section */
3081 } load_all_t;
3083 /* Structure to contain information about a file mapped into memory. */
3085 struct file_info
3087 char *start; /* start of map */
3088 char *name; /* filename */
3089 long size; /* size of the file */
3090 long rounded_size; /* size rounded to page boundary */
3091 int fd; /* file descriptor */
3092 int rw; /* != 0 if opened read/write */
3093 int use_mmap; /* != 0 if mmap'ed */
3096 extern int decode_mach_o_hdr ();
3097 extern int encode_mach_o_hdr ();
3099 static void add_func_table PARAMS ((mo_header_t *, load_all_t *,
3100 symbol_info_t *, int));
3101 static void print_header PARAMS ((mo_header_t *));
3102 static void print_load_command PARAMS ((load_union_t *, size_t, int));
3103 static void bad_header PARAMS ((int));
3104 static struct file_info *read_file PARAMS ((const char *, int, int));
3105 static void end_file PARAMS ((struct file_info *));
3107 /* OSF/rose specific version to scan the name list of the loaded
3108 program for the symbols g++ uses for static constructors and
3109 destructors.
3111 The constructor table begins at __CTOR_LIST__ and contains a count
3112 of the number of pointers (or -1 if the constructors are built in a
3113 separate section by the linker), followed by the pointers to the
3114 constructor functions, terminated with a null pointer. The
3115 destructor table has the same format, and begins at __DTOR_LIST__. */
3117 static void
3118 scan_prog_file (prog_name, which_pass)
3119 const char *prog_name;
3120 enum pass which_pass;
3122 char *obj;
3123 mo_header_t hdr;
3124 load_all_t *load_array;
3125 load_all_t *load_end;
3126 load_all_t *load_cmd;
3127 int symbol_load_cmds;
3128 off_t offset;
3129 int i;
3130 int num_syms;
3131 int status;
3132 char *str_sect;
3133 struct file_info *obj_file;
3134 int prog_fd;
3135 mo_lcid_t cmd_strings = -1;
3136 symbol_info_t *main_sym = 0;
3137 int rw = (which_pass != PASS_FIRST);
3139 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3140 if (prog_fd < 0)
3141 fatal_perror ("open %s", prog_name);
3143 obj_file = read_file (prog_name, prog_fd, rw);
3144 obj = obj_file->start;
3146 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3147 if (status != MO_HDR_CONV_SUCCESS)
3148 bad_header (status);
3151 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3152 since the hardware will automatically swap bytes for us on loading little endian
3153 integers. */
3155 #ifndef CROSS_COMPILE
3156 if (hdr.moh_magic != MOH_MAGIC_MSB
3157 || hdr.moh_header_version != MOH_HEADER_VERSION
3158 || hdr.moh_byte_order != OUR_BYTE_ORDER
3159 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3160 || hdr.moh_cpu_type != OUR_CPU_TYPE
3161 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3162 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3164 fatal ("incompatibilities between object file & expected values");
3166 #endif
3168 if (debug)
3169 print_header (&hdr);
3171 offset = hdr.moh_first_cmd_off;
3172 load_end = load_array
3173 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3175 /* Build array of load commands, calculating the offsets */
3176 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3178 load_union_t *load_hdr; /* load command header */
3180 load_cmd = load_end++;
3181 load_hdr = (load_union_t *) (obj + offset);
3183 /* If modifying the program file, copy the header. */
3184 if (rw)
3186 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3187 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
3188 load_hdr = ptr;
3190 /* null out old command map, because we will rewrite at the end. */
3191 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3193 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3194 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3198 load_cmd->load = load_hdr;
3199 if (load_hdr->hdr.ldci_section_off > 0)
3200 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3202 if (debug)
3203 print_load_command (load_hdr, offset, i);
3205 offset += load_hdr->hdr.ldci_cmd_size;
3208 /* If the last command is the load command map and is not undefined,
3209 decrement the count of load commands. */
3210 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3212 load_end--;
3213 hdr.moh_n_load_cmds--;
3216 /* Go through and process each symbol table section. */
3217 symbol_load_cmds = 0;
3218 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3220 load_union_t *load_hdr = load_cmd->load;
3222 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3224 symbol_load_cmds++;
3226 if (debug)
3228 const char *kind = "unknown";
3230 switch (load_hdr->sym.symc_kind)
3232 case SYMC_IMPORTS: kind = "imports"; break;
3233 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3234 case SYMC_STABS: kind = "stabs"; break;
3237 notice ("\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3238 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3241 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3242 continue;
3244 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3245 if (str_sect == (char *) 0)
3246 fatal ("string section missing");
3248 if (load_cmd->section == (char *) 0)
3249 fatal ("section pointer missing");
3251 num_syms = load_hdr->sym.symc_nentries;
3252 for (i = 0; i < num_syms; i++)
3254 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3255 char *name = sym->si_name.symbol_name + str_sect;
3257 if (name[0] != '_')
3258 continue;
3260 if (rw)
3262 char *n = name + strlen (name) - strlen (NAME__MAIN);
3264 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3265 continue;
3266 while (n != name)
3267 if (*--n != '_')
3268 continue;
3270 main_sym = sym;
3272 else
3274 switch (is_ctor_dtor (name))
3276 case 1:
3277 add_to_list (&constructors, name);
3278 break;
3280 case 2:
3281 add_to_list (&destructors, name);
3282 break;
3284 default: /* not a constructor or destructor */
3285 continue;
3289 if (debug)
3290 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3291 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3296 if (symbol_load_cmds == 0)
3297 fatal ("no symbol table found");
3299 /* Update the program file now, rewrite header and load commands. At present,
3300 we assume that there is enough space after the last load command to insert
3301 one more. Since the first section written out is page aligned, and the
3302 number of load commands is small, this is ok for the present. */
3304 if (rw)
3306 load_union_t *load_map;
3307 size_t size;
3309 if (cmd_strings == -1)
3310 fatal ("no cmd_strings found");
3312 /* Add __main to initializer list.
3313 If we are building a program instead of a shared library, do not
3314 do anything, since in the current version, you cannot do mallocs
3315 and such in the constructors. */
3317 if (main_sym != (symbol_info_t *) 0
3318 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3319 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3321 if (debug)
3322 notice ("\nUpdating header and load commands.\n\n");
3324 hdr.moh_n_load_cmds++;
3325 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3327 /* Create new load command map. */
3328 if (debug)
3329 notice ("load command map, %d cmds, new size %ld.\n",
3330 (int) hdr.moh_n_load_cmds, (long) size);
3332 load_map = (load_union_t *) xcalloc (1, size);
3333 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3334 load_map->map.ldc_header.ldci_cmd_size = size;
3335 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3336 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3337 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3339 offset = hdr.moh_first_cmd_off;
3340 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3342 load_map->map.lcm_map[i] = offset;
3343 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3344 hdr.moh_load_map_cmd_off = offset;
3346 offset += load_array[i].load->hdr.ldci_cmd_size;
3349 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3351 if (debug)
3352 print_header (&hdr);
3354 /* Write header */
3355 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3356 if (status != MO_HDR_CONV_SUCCESS)
3357 bad_header (status);
3359 if (debug)
3360 notice ("writing load commands.\n\n");
3362 /* Write load commands */
3363 offset = hdr.moh_first_cmd_off;
3364 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3366 load_union_t *load_hdr = load_array[i].load;
3367 size_t size = load_hdr->hdr.ldci_cmd_size;
3369 if (debug)
3370 print_load_command (load_hdr, offset, i);
3372 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3373 offset += size;
3377 end_file (obj_file);
3379 if (close (prog_fd))
3380 fatal_perror ("close %s", prog_name);
3382 if (debug)
3383 fprintf (stderr, "\n");
3387 /* Add a function table to the load commands to call a function
3388 on initiation or termination of the process. */
3390 static void
3391 add_func_table (hdr_p, load_array, sym, type)
3392 mo_header_t *hdr_p; /* pointer to global header */
3393 load_all_t *load_array; /* array of ptrs to load cmds */
3394 symbol_info_t *sym; /* pointer to symbol entry */
3395 int type; /* fntc_type value */
3397 /* Add a new load command. */
3398 int num_cmds = ++hdr_p->moh_n_load_cmds;
3399 int load_index = num_cmds - 1;
3400 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3401 load_union_t *ptr = xcalloc (1, size);
3402 load_all_t *load_cmd;
3403 int i;
3405 /* Set the unresolved address bit in the header to force the loader to be
3406 used, since kernel exec does not call the initialization functions. */
3407 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3409 load_cmd = &load_array[load_index];
3410 load_cmd->load = ptr;
3411 load_cmd->section = (char *) 0;
3413 /* Fill in func table load command. */
3414 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3415 ptr->func.ldc_header.ldci_cmd_size = size;
3416 ptr->func.ldc_header.ldci_section_off = 0;
3417 ptr->func.ldc_header.ldci_section_len = 0;
3418 ptr->func.fntc_type = type;
3419 ptr->func.fntc_nentries = 1;
3421 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3422 /* Is the symbol already expressed as (region, offset)? */
3423 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3425 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3426 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3429 /* If not, figure out which region it's in. */
3430 else
3432 mo_vm_addr_t addr = sym->si_value.abs_val;
3433 int found = 0;
3435 for (i = 0; i < load_index; i++)
3437 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3439 region_command_t *region_ptr = &load_array[i].load->region;
3441 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3442 && addr >= region_ptr->regc_addr.vm_addr
3443 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3445 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3446 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3447 found++;
3448 break;
3453 if (!found)
3454 fatal ("could not convert 0x%l.8x into a region", addr);
3457 if (debug)
3458 notice ("%s function, region %d, offset = %ld (0x%.8lx)\n",
3459 type == FNTC_INITIALIZATION ? "init" : "term",
3460 (int) ptr->func.fntc_entry_loc[i].adr_lcid,
3461 (long) ptr->func.fntc_entry_loc[i].adr_sctoff,
3462 (long) ptr->func.fntc_entry_loc[i].adr_sctoff);
3467 /* Print the global header for an OSF/rose object. */
3469 static void
3470 print_header (hdr_ptr)
3471 mo_header_t *hdr_ptr;
3473 fprintf (stderr, "\nglobal header:\n");
3474 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3475 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3476 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3477 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3478 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3479 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3480 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3481 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3482 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3483 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3484 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3485 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3486 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3487 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3488 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3490 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3491 fprintf (stderr, ", relocatable");
3493 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3494 fprintf (stderr, ", linkable");
3496 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3497 fprintf (stderr, ", execable");
3499 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3500 fprintf (stderr, ", executable");
3502 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3503 fprintf (stderr, ", unresolved");
3505 fprintf (stderr, "\n\n");
3506 return;
3510 /* Print a short summary of a load command. */
3512 static void
3513 print_load_command (load_hdr, offset, number)
3514 load_union_t *load_hdr;
3515 size_t offset;
3516 int number;
3518 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3519 const char *type_str = (char *) 0;
3521 switch (type)
3523 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3524 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3525 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3526 case LDC_STRINGS: type_str = "STRINGS"; break;
3527 case LDC_REGION: type_str = "REGION"; break;
3528 case LDC_RELOC: type_str = "RELOC"; break;
3529 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3530 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3531 case LDC_ENTRY: type_str = "ENTRY"; break;
3532 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3533 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3536 fprintf (stderr,
3537 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3538 number,
3539 (long) load_hdr->hdr.ldci_cmd_size,
3540 (long) offset,
3541 (long) load_hdr->hdr.ldci_section_off,
3542 (long) load_hdr->hdr.ldci_section_len);
3544 if (type_str == (char *) 0)
3545 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3547 else if (type != LDC_REGION)
3548 fprintf (stderr, ", ty: %s\n", type_str);
3550 else
3552 const char *region = "";
3553 switch (load_hdr->region.regc_usage_type)
3555 case REG_TEXT_T: region = ", .text"; break;
3556 case REG_DATA_T: region = ", .data"; break;
3557 case REG_BSS_T: region = ", .bss"; break;
3558 case REG_GLUE_T: region = ", .glue"; break;
3559 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3560 case REG_RDATA_T: region = ", .rdata"; break;
3561 case REG_SDATA_T: region = ", .sdata"; break;
3562 case REG_SBSS_T: region = ", .sbss"; break;
3563 #endif
3566 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3567 type_str,
3568 (long) load_hdr->region.regc_vm_addr,
3569 (long) load_hdr->region.regc_vm_size,
3570 region);
3573 return;
3577 /* Fatal error when {en,de}code_mach_o_header fails. */
3579 static void
3580 bad_header (status)
3581 int status;
3583 switch (status)
3585 case MO_ERROR_BAD_MAGIC: fatal ("bad magic number");
3586 case MO_ERROR_BAD_HDR_VERS: fatal ("bad header version");
3587 case MO_ERROR_BAD_RAW_HDR_VERS: fatal ("bad raw header version");
3588 case MO_ERROR_BUF2SML: fatal ("raw header buffer too small");
3589 case MO_ERROR_OLD_RAW_HDR_FILE: fatal ("old raw header file");
3590 case MO_ERROR_UNSUPPORTED_VERS: fatal ("unsupported version");
3591 default:
3592 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3597 /* Read a file into a memory buffer. */
3599 static struct file_info *
3600 read_file (name, fd, rw)
3601 const char *name; /* filename */
3602 int fd; /* file descriptor */
3603 int rw; /* read/write */
3605 struct stat stat_pkt;
3606 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3607 #ifdef USE_MMAP
3608 static int page_size;
3609 #endif
3611 if (fstat (fd, &stat_pkt) < 0)
3612 fatal_perror ("fstat %s", name);
3614 p->name = name;
3615 p->size = stat_pkt.st_size;
3616 p->rounded_size = stat_pkt.st_size;
3617 p->fd = fd;
3618 p->rw = rw;
3620 #ifdef USE_MMAP
3621 if (debug)
3622 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3624 if (page_size == 0)
3625 page_size = sysconf (_SC_PAGE_SIZE);
3627 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3628 p->start = mmap ((caddr_t) 0,
3629 (rw) ? p->rounded_size : p->size,
3630 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3631 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3633 0L);
3635 if (p->start != (char *) 0 && p->start != (char *) -1)
3636 p->use_mmap = 1;
3638 else
3639 #endif /* USE_MMAP */
3641 long len;
3643 if (debug)
3644 fprintf (stderr, "read %s\n", name);
3646 p->use_mmap = 0;
3647 p->start = xmalloc (p->size);
3648 if (lseek (fd, 0L, SEEK_SET) < 0)
3649 fatal_perror ("lseek %s 0", name);
3651 len = read (fd, p->start, p->size);
3652 if (len < 0)
3653 fatal_perror ("read %s", name);
3655 if (len != p->size)
3656 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3659 return p;
3662 /* Do anything necessary to write a file back from memory. */
3664 static void
3665 end_file (ptr)
3666 struct file_info *ptr; /* file information block */
3668 #ifdef USE_MMAP
3669 if (ptr->use_mmap)
3671 if (ptr->rw)
3673 if (debug)
3674 fprintf (stderr, "msync %s\n", ptr->name);
3676 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3677 fatal_perror ("msync %s", ptr->name);
3680 if (debug)
3681 fprintf (stderr, "munmap %s\n", ptr->name);
3683 if (munmap (ptr->start, ptr->size))
3684 fatal_perror ("munmap %s", ptr->name);
3686 else
3687 #endif /* USE_MMAP */
3689 if (ptr->rw)
3691 long len;
3693 if (debug)
3694 fprintf (stderr, "write %s\n", ptr->name);
3696 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3697 fatal_perror ("lseek %s 0", ptr->name);
3699 len = write (ptr->fd, ptr->start, ptr->size);
3700 if (len < 0)
3701 fatal_perror ("write %s", ptr->name);
3703 if (len != ptr->size)
3704 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3707 free (ptr->start);
3710 free (ptr);
3713 #endif /* OBJECT_FORMAT_ROSE */