* optimize.c (initialize_inlined_parameters): Take FN to which the
[official-gcc.git] / gcc / collect2.c
blob18d7fb85a1ef458ae85e95f39d1732b8666daac8
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93-98, 1999 Free Software Foundation, Inc.
4 Contributed by Chris Smith (csmith@convex.com).
5 Heavily modified by Michael Meissner (meissner@cygnus.com),
6 Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
8 This file is part of GNU CC.
10 GNU CC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
13 any later version.
15 GNU CC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with GNU CC; see the file COPYING. If not, write to
22 the Free Software Foundation, 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA. */
26 /* Build tables of static constructors and destructors and run ld. */
28 #include "config.h"
29 #include "system.h"
30 #include <signal.h>
32 #ifdef vfork /* Autoconf may define this to fork for us. */
33 # define VFORK_STRING "fork"
34 #else
35 # define VFORK_STRING "vfork"
36 #endif
37 #ifdef HAVE_VFORK_H
38 #include <vfork.h>
39 #endif
40 #ifdef VMS
41 #define vfork() (decc$$alloc_vfork_blocks() >= 0 ? \
42 lib$get_current_invo_context(decc$$get_vfork_jmpbuf()) : -1)
43 #endif /* VMS */
45 #define COLLECT
47 #include "collect2.h"
48 #include "demangle.h"
49 #include "obstack.h"
50 #include "intl.h"
52 #ifndef DIR_SEPARATOR
53 # define DIR_SEPARATOR '/'
54 # define IS_DIR_SEPARATOR(ch) ((ch) == '/')
55 #else /* DIR_SEPARATOR */
56 # ifndef DIR_SEPARATOR_2
57 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)
58 # else /* DIR_SEPARATOR && DIR_SEPARATOR_2 */
59 # define IS_DIR_SEPARATOR(ch) \
60 (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))
61 # endif /* DIR_SEPARATOR && DIR_SEPARATOR_2 */
62 #endif /* DIR_SEPARATOR */
64 /* Obstack allocation and deallocation routines. */
65 #define obstack_chunk_alloc xmalloc
66 #define obstack_chunk_free free
68 /* On certain systems, we have code that works by scanning the object file
69 directly. But this code uses system-specific header files and library
70 functions, so turn it off in a cross-compiler. Likewise, the names of
71 the utilities are not correct for a cross-compiler; we have to hope that
72 cross-versions are in the proper directories. */
74 #ifdef CROSS_COMPILE
75 #undef SUNOS4_SHARED_LIBRARIES
76 #undef OBJECT_FORMAT_COFF
77 #undef OBJECT_FORMAT_ROSE
78 #undef MD_EXEC_PREFIX
79 #undef REAL_LD_FILE_NAME
80 #undef REAL_NM_FILE_NAME
81 #undef REAL_STRIP_FILE_NAME
82 #endif
84 /* If we cannot use a special method, use the ordinary one:
85 run nm to find what symbols are present.
86 In a cross-compiler, this means you need a cross nm,
87 but that is not quite as unpleasant as special headers. */
89 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
90 #define OBJECT_FORMAT_NONE
91 #endif
93 #ifdef OBJECT_FORMAT_COFF
95 #include <a.out.h>
96 #include <ar.h>
98 #ifdef UMAX
99 #include <sgs.h>
100 #endif
102 /* Many versions of ldfcn.h define these. */
103 #ifdef FREAD
104 #undef FREAD
105 #undef FWRITE
106 #endif
108 #include <ldfcn.h>
110 /* Some systems have an ISCOFF macro, but others do not. In some cases
111 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
112 that either do not have an ISCOFF macro in /usr/include or for those
113 where it is wrong. */
115 #ifndef MY_ISCOFF
116 #define MY_ISCOFF(X) ISCOFF (X)
117 #endif
119 #endif /* OBJECT_FORMAT_COFF */
121 #ifdef OBJECT_FORMAT_ROSE
123 #ifdef _OSF_SOURCE
124 #define USE_MMAP
125 #endif
127 #ifdef USE_MMAP
128 #include <sys/mman.h>
129 #endif
131 #include <unistd.h>
132 #include <mach_o_format.h>
133 #include <mach_o_header.h>
134 #include <mach_o_vals.h>
135 #include <mach_o_types.h>
137 #endif /* OBJECT_FORMAT_ROSE */
139 #ifdef OBJECT_FORMAT_NONE
141 /* Default flags to pass to nm. */
142 #ifndef NM_FLAGS
143 #define NM_FLAGS "-n"
144 #endif
146 #endif /* OBJECT_FORMAT_NONE */
148 /* Some systems use __main in a way incompatible with its use in gcc, in these
149 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
150 give the same symbol without quotes for an alternative entry point. You
151 must define both, or neither. */
152 #ifndef NAME__MAIN
153 #define NAME__MAIN "__main"
154 #define SYMBOL__MAIN __main
155 #endif
157 /* This must match tree.h. */
158 #define DEFAULT_INIT_PRIORITY 65535
160 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
161 #define SCAN_LIBRARIES
162 #endif
164 #ifdef USE_COLLECT2
165 int do_collecting = 1;
166 #else
167 int do_collecting = 0;
168 #endif
170 /* Linked lists of constructor and destructor names. */
172 struct id
174 struct id *next;
175 int sequence;
176 char name[1];
179 struct head
181 struct id *first;
182 struct id *last;
183 int number;
186 /* Enumeration giving which pass this is for scanning the program file. */
188 enum pass {
189 PASS_FIRST, /* without constructors */
190 PASS_OBJ, /* individual objects */
191 PASS_LIB, /* looking for shared libraries */
192 PASS_SECOND /* with constructors linked in */
195 extern char *version_string;
197 int vflag; /* true if -v */
198 static int rflag; /* true if -r */
199 static int strip_flag; /* true if -s */
200 #ifdef COLLECT_EXPORT_LIST
201 static int export_flag; /* true if -bE */
202 static int aix64_flag; /* true if -b64 */
203 #endif
205 int debug; /* true if -debug */
207 static int shared_obj; /* true if -shared */
209 static const char *c_file; /* <xxx>.c for constructor/destructor list. */
210 static const char *o_file; /* <xxx>.o for constructor/destructor list. */
211 #ifdef COLLECT_EXPORT_LIST
212 static const char *export_file; /* <xxx>.x for AIX export list. */
213 static const char *import_file; /* <xxx>.p for AIX import list. */
214 #endif
215 const char *ldout; /* File for ld errors. */
216 static const char *output_file; /* Output file for ld. */
217 static const char *nm_file_name; /* pathname of nm */
218 #ifdef LDD_SUFFIX
219 static const char *ldd_file_name; /* pathname of ldd (or equivalent) */
220 #endif
221 static const char *strip_file_name; /* pathname of strip */
222 const char *c_file_name; /* pathname of gcc */
223 static char *initname, *fininame; /* names of init and fini funcs */
225 static struct head constructors; /* list of constructors found */
226 static struct head destructors; /* list of destructors found */
227 #ifdef COLLECT_EXPORT_LIST
228 static struct head exports; /* list of exported symbols */
229 static struct head imports; /* list of imported symbols */
230 static struct head undefined; /* list of undefined symbols */
231 #endif
232 static struct head frame_tables; /* list of frame unwind info tables */
234 struct obstack temporary_obstack;
235 struct obstack permanent_obstack;
236 char * temporary_firstobj;
238 /* Holds the return value of pexecute. */
239 int pexecute_pid;
241 /* Defined in the automatically-generated underscore.c. */
242 extern int prepends_underscore;
244 #ifndef GET_ENV_PATH_LIST
245 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
246 #endif
248 /* Structure to hold all the directories in which to search for files to
249 execute. */
251 struct prefix_list
253 const char *prefix; /* String to prepend to the path. */
254 struct prefix_list *next; /* Next in linked list. */
257 struct path_prefix
259 struct prefix_list *plist; /* List of prefixes to try */
260 int max_len; /* Max length of a prefix in PLIST */
261 const char *name; /* Name of this list (used in config stuff) */
264 #ifdef COLLECT_EXPORT_LIST
265 /* Lists to keep libraries to be scanned for global constructors/destructors. */
266 static struct head libs; /* list of libraries */
267 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
268 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
269 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
270 &libpath_lib_dirs, NULL};
271 static const char *libexts[3] = {"a", "so", NULL}; /* possible library extentions */
272 #endif
274 static void handler PROTO((int));
275 static int is_ctor_dtor PROTO((const char *));
276 static char *find_a_file PROTO((struct path_prefix *, const char *));
277 static void add_prefix PROTO((struct path_prefix *, const char *));
278 static void prefix_from_env PROTO((const char *, struct path_prefix *));
279 static void prefix_from_string PROTO((const char *, struct path_prefix *));
280 static void do_wait PROTO((const char *));
281 static void fork_execute PROTO((const char *, char **));
282 static void maybe_unlink PROTO((const char *));
283 static void add_to_list PROTO((struct head *, const char *));
284 static int extract_init_priority PROTO((const char *));
285 static void sort_ids PROTO((struct head *));
286 static void write_list PROTO((FILE *, const char *, struct id *));
287 #ifdef COLLECT_EXPORT_LIST
288 static void dump_list PROTO((FILE *, const char *, struct id *));
289 #endif
290 #if 0
291 static void dump_prefix_list PROTO((FILE *, const char *, struct prefix_list *));
292 #endif
293 static void write_list_with_asm PROTO((FILE *, const char *, struct id *));
294 static void write_c_file PROTO((FILE *, const char *));
295 static void write_c_file_stat PROTO((FILE *, const char *));
296 #ifndef LD_INIT_SWITCH
297 static void write_c_file_glob PROTO((FILE *, const char *));
298 #endif
299 static void scan_prog_file PROTO((const char *, enum pass));
300 #ifdef SCAN_LIBRARIES
301 static void scan_libraries PROTO((const char *));
302 #endif
303 #ifdef COLLECT_EXPORT_LIST
304 static int is_in_list PROTO((const char *, struct id *));
305 static void write_aix_file PROTO((FILE *, struct id *));
306 static char *resolve_lib_name PROTO((const char *));
307 static int use_import_list PROTO((const char *));
308 static int ignore_library PROTO((const char *));
309 #endif
310 static char *extract_string PROTO((const char **));
312 #ifdef NO_DUP2
314 dup2 (oldfd, newfd)
315 int oldfd;
316 int newfd;
318 int fdtmp[256];
319 int fdx = 0;
320 int fd;
322 if (oldfd == newfd)
323 return oldfd;
324 close (newfd);
325 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
326 fdtmp[fdx++] = fd;
327 while (fdx > 0)
328 close (fdtmp[--fdx]);
330 return fd;
332 #endif
334 /* Delete tempfiles and exit function. */
336 void
337 collect_exit (status)
338 int status;
340 if (c_file != 0 && c_file[0])
341 maybe_unlink (c_file);
343 if (o_file != 0 && o_file[0])
344 maybe_unlink (o_file);
346 #ifdef COLLECT_EXPORT_LIST
347 if (export_file != 0 && export_file[0])
348 maybe_unlink (export_file);
350 if (import_file != 0 && import_file[0])
351 maybe_unlink (import_file);
352 #endif
354 if (ldout != 0 && ldout[0])
356 dump_file (ldout);
357 maybe_unlink (ldout);
360 if (status != 0 && output_file != 0 && output_file[0])
361 maybe_unlink (output_file);
363 exit (status);
367 /* Notify user of a non-error. */
368 void
369 notice VPROTO((const char *msgid, ...))
371 #ifndef ANSI_PROTOTYPES
372 const char *msgid;
373 #endif
374 va_list ap;
376 VA_START (ap, msgid);
378 #ifndef ANSI_PROTOTYPES
379 msgid = va_arg (ap, const char *);
380 #endif
382 vfprintf (stderr, _(msgid), ap);
383 va_end (ap);
386 /* Die when sys call fails. */
388 void
389 fatal_perror VPROTO((const char * msgid, ...))
391 #ifndef ANSI_PROTOTYPES
392 const char *msgid;
393 #endif
394 int e = errno;
395 va_list ap;
397 VA_START (ap, msgid);
399 #ifndef ANSI_PROTOTYPES
400 msgid = va_arg (ap, const char *);
401 #endif
403 fprintf (stderr, "collect2: ");
404 vfprintf (stderr, _(msgid), ap);
405 fprintf (stderr, ": %s\n", xstrerror (e));
406 va_end (ap);
408 collect_exit (FATAL_EXIT_CODE);
411 /* Just die. */
413 void
414 fatal VPROTO((const char * msgid, ...))
416 #ifndef ANSI_PROTOTYPES
417 const char *msgid;
418 #endif
419 va_list ap;
421 VA_START (ap, msgid);
423 #ifndef ANSI_PROTOTYPES
424 msgid = va_arg (ap, const char *);
425 #endif
427 fprintf (stderr, "collect2: ");
428 vfprintf (stderr, _(msgid), ap);
429 fprintf (stderr, "\n");
430 va_end (ap);
432 collect_exit (FATAL_EXIT_CODE);
435 /* Write error message. */
437 void
438 error VPROTO((const char * msgid, ...))
440 #ifndef ANSI_PROTOTYPES
441 const char * msgid;
442 #endif
443 va_list ap;
445 VA_START (ap, msgid);
447 #ifndef ANSI_PROTOTYPES
448 msgid = va_arg (ap, const char *);
449 #endif
451 fprintf (stderr, "collect2: ");
452 vfprintf (stderr, _(msgid), ap);
453 fprintf (stderr, "\n");
454 va_end(ap);
457 /* In case obstack is linked in, and abort is defined to fancy_abort,
458 provide a default entry. */
460 void
461 fancy_abort ()
463 fatal ("internal error");
466 static void
467 handler (signo)
468 int signo;
470 if (c_file != 0 && c_file[0])
471 maybe_unlink (c_file);
473 if (o_file != 0 && o_file[0])
474 maybe_unlink (o_file);
476 if (ldout != 0 && ldout[0])
477 maybe_unlink (ldout);
479 #ifdef COLLECT_EXPORT_LIST
480 if (export_file != 0 && export_file[0])
481 maybe_unlink (export_file);
483 if (import_file != 0 && import_file[0])
484 maybe_unlink (import_file);
485 #endif
487 signal (signo, SIG_DFL);
488 kill (getpid (), signo);
493 file_exists (name)
494 const char *name;
496 return access (name, R_OK) == 0;
499 /* Parse a reasonable subset of shell quoting syntax. */
501 static char *
502 extract_string (pp)
503 const char **pp;
505 const char *p = *pp;
506 int backquote = 0;
507 int inside = 0;
509 for (;;)
511 char c = *p;
512 if (c == '\0')
513 break;
514 ++p;
515 if (backquote)
516 obstack_1grow (&temporary_obstack, c);
517 else if (! inside && c == ' ')
518 break;
519 else if (! inside && c == '\\')
520 backquote = 1;
521 else if (c == '\'')
522 inside = !inside;
523 else
524 obstack_1grow (&temporary_obstack, c);
527 obstack_1grow (&temporary_obstack, '\0');
528 *pp = p;
529 return obstack_finish (&temporary_obstack);
532 void
533 dump_file (name)
534 const char *name;
536 FILE *stream = fopen (name, "r");
537 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
539 if (stream == 0)
540 return;
541 while (1)
543 int c;
544 while (c = getc (stream),
545 c != EOF && (ISALNUM (c) || c == '_' || c == '$' || c == '.'))
546 obstack_1grow (&temporary_obstack, c);
547 if (obstack_object_size (&temporary_obstack) > 0)
549 const char *word, *p;
550 char *result;
551 obstack_1grow (&temporary_obstack, '\0');
552 word = obstack_finish (&temporary_obstack);
554 if (*word == '.')
555 ++word, putc ('.', stderr);
556 p = word;
557 if (*p == '_' && prepends_underscore)
558 ++p;
560 if (no_demangle)
561 result = 0;
562 else
563 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
565 if (result)
567 int diff;
568 fputs (result, stderr);
570 diff = strlen (word) - strlen (result);
571 while (diff > 0)
572 --diff, putc (' ', stderr);
573 while (diff < 0 && c == ' ')
574 ++diff, c = getc (stream);
576 free (result);
578 else
579 fputs (word, stderr);
581 fflush (stderr);
582 obstack_free (&temporary_obstack, temporary_firstobj);
584 if (c == EOF)
585 break;
586 putc (c, stderr);
588 fclose (stream);
591 /* Decide whether the given symbol is:
592 a constructor (1), a destructor (2), or neither (0). */
594 static int
595 is_ctor_dtor (s)
596 const char *s;
598 struct names { const char *name; int len; int ret; int two_underscores; };
600 register struct names *p;
601 register int ch;
602 register const char *orig_s = s;
604 static struct names special[] = {
605 #ifdef NO_DOLLAR_IN_LABEL
606 #ifdef NO_DOT_IN_LABEL
607 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
608 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
609 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
610 #else
611 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
612 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
613 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
614 #endif
615 #else
616 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
617 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
618 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
619 #endif
620 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
621 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
622 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
623 cfront has its own linker procedure to collect them;
624 if collect2 gets them too, they get collected twice
625 when the cfront procedure is run and the compiler used
626 for linking happens to be GCC. */
627 { "sti__", sizeof ("sti__")-1, 1, 1 },
628 { "std__", sizeof ("std__")-1, 2, 1 },
629 #endif /* CFRONT_LOSSAGE */
630 { NULL, 0, 0, 0 }
633 while ((ch = *s) == '_')
634 ++s;
636 if (s == orig_s)
637 return 0;
639 for (p = &special[0]; p->len > 0; p++)
641 if (ch == p->name[0]
642 && (!p->two_underscores || ((s - orig_s) >= 2))
643 && strncmp(s, p->name, p->len) == 0)
645 return p->ret;
648 return 0;
651 /* By default, colon separates directories in a path. */
652 #ifndef PATH_SEPARATOR
653 #define PATH_SEPARATOR ':'
654 #endif
656 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
657 and one from the PATH variable. */
659 static struct path_prefix cpath, path;
661 #ifdef CROSS_COMPILE
662 /* This is the name of the target machine. We use it to form the name
663 of the files to execute. */
665 static const char *const target_machine = TARGET_MACHINE;
666 #endif
668 /* Search for NAME using prefix list PPREFIX. We only look for executable
669 files.
671 Return 0 if not found, otherwise return its name, allocated with malloc. */
673 static char *
674 find_a_file (pprefix, name)
675 struct path_prefix *pprefix;
676 const char *name;
678 char *temp;
679 struct prefix_list *pl;
680 int len = pprefix->max_len + strlen (name) + 1;
682 if (debug)
683 fprintf (stderr, "Looking for '%s'\n", name);
685 #ifdef EXECUTABLE_SUFFIX
686 len += strlen (EXECUTABLE_SUFFIX);
687 #endif
689 temp = xmalloc (len);
691 /* Determine the filename to execute (special case for absolute paths). */
693 if (*name == '/'
694 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
695 || (*name && name[1] == ':')
696 #endif
699 if (access (name, X_OK) == 0)
701 strcpy (temp, name);
703 if (debug)
704 fprintf (stderr, " - found: absolute path\n");
706 return temp;
709 #ifdef EXECUTABLE_SUFFIX
710 /* Some systems have a suffix for executable files.
711 So try appending that. */
712 strcpy (temp, name);
713 strcat (temp, EXECUTABLE_SUFFIX);
715 if (access (temp, X_OK) == 0)
716 return temp;
717 #endif
719 if (debug)
720 fprintf (stderr, " - failed to locate using absolute path\n");
722 else
723 for (pl = pprefix->plist; pl; pl = pl->next)
725 struct stat st;
727 strcpy (temp, pl->prefix);
728 strcat (temp, name);
730 if (stat (temp, &st) >= 0
731 && ! S_ISDIR (st.st_mode)
732 && access (temp, X_OK) == 0)
733 return temp;
735 #ifdef EXECUTABLE_SUFFIX
736 /* Some systems have a suffix for executable files.
737 So try appending that. */
738 strcat (temp, EXECUTABLE_SUFFIX);
740 if (stat (temp, &st) >= 0
741 && ! S_ISDIR (st.st_mode)
742 && access (temp, X_OK) == 0)
743 return temp;
744 #endif
747 if (debug && pprefix->plist == NULL)
748 fprintf (stderr, " - failed: no entries in prefix list\n");
750 free (temp);
751 return 0;
754 /* Add an entry for PREFIX to prefix list PPREFIX. */
756 static void
757 add_prefix (pprefix, prefix)
758 struct path_prefix *pprefix;
759 const char *prefix;
761 struct prefix_list *pl, **prev;
762 int len;
764 if (pprefix->plist)
766 for (pl = pprefix->plist; pl->next; pl = pl->next)
768 prev = &pl->next;
770 else
771 prev = &pprefix->plist;
773 /* Keep track of the longest prefix */
775 len = strlen (prefix);
776 if (len > pprefix->max_len)
777 pprefix->max_len = len;
779 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
780 pl->prefix = xstrdup (prefix);
782 if (*prev)
783 pl->next = *prev;
784 else
785 pl->next = (struct prefix_list *) 0;
786 *prev = pl;
789 /* Take the value of the environment variable ENV, break it into a path, and
790 add of the entries to PPREFIX. */
792 static void
793 prefix_from_env (env, pprefix)
794 const char *env;
795 struct path_prefix *pprefix;
797 const char *p;
798 GET_ENV_PATH_LIST (p, env);
800 if (p)
801 prefix_from_string (p, pprefix);
804 static void
805 prefix_from_string (p, pprefix)
806 const char *p;
807 struct path_prefix *pprefix;
809 const char *startp, *endp;
810 char *nstore = (char *) xmalloc (strlen (p) + 3);
812 if (debug)
813 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
815 startp = endp = p;
816 while (1)
818 if (*endp == PATH_SEPARATOR || *endp == 0)
820 strncpy (nstore, startp, endp-startp);
821 if (endp == startp)
823 strcpy (nstore, "./");
825 else if (! IS_DIR_SEPARATOR (endp[-1]))
827 nstore[endp-startp] = DIR_SEPARATOR;
828 nstore[endp-startp+1] = 0;
830 else
831 nstore[endp-startp] = 0;
833 if (debug)
834 fprintf (stderr, " - add prefix: %s\n", nstore);
836 add_prefix (pprefix, nstore);
837 if (*endp == 0)
838 break;
839 endp = startp = endp + 1;
841 else
842 endp++;
846 /* Main program. */
848 int main PROTO ((int, char *[]));
850 main (argc, argv)
851 int argc;
852 char *argv[];
854 const char *ld_suffix = "ld";
855 const char *full_ld_suffix = ld_suffix;
856 const char *real_ld_suffix = "real-ld";
857 const char *collect_ld_suffix = "collect-ld";
858 const char *nm_suffix = "nm";
859 const char *full_nm_suffix = nm_suffix;
860 const char *gnm_suffix = "gnm";
861 const char *full_gnm_suffix = gnm_suffix;
862 #ifdef LDD_SUFFIX
863 const char *ldd_suffix = LDD_SUFFIX;
864 const char *full_ldd_suffix = ldd_suffix;
865 #endif
866 const char *strip_suffix = "strip";
867 const char *full_strip_suffix = strip_suffix;
868 const char *gstrip_suffix = "gstrip";
869 const char *full_gstrip_suffix = gstrip_suffix;
870 const char *arg;
871 FILE *outf;
872 #ifdef COLLECT_EXPORT_LIST
873 FILE *exportf;
874 FILE *importf;
875 #endif
876 const char *ld_file_name;
877 const char *p;
878 char **c_argv;
879 const char **c_ptr;
880 char **ld1_argv;
881 const char **ld1;
882 char **ld2_argv;
883 const char **ld2;
884 char **object_lst;
885 const char **object;
886 int first_file;
887 int num_c_args = argc+9;
889 #if defined (COLLECT2_HOST_INITIALIZATION)
890 /* Perform system dependant initialization, if neccessary. */
891 COLLECT2_HOST_INITIALIZATION;
892 #endif
894 #ifdef HAVE_LC_MESSAGES
895 setlocale (LC_MESSAGES, "");
896 #endif
897 (void) bindtextdomain (PACKAGE, localedir);
898 (void) textdomain (PACKAGE);
900 /* Do not invoke xcalloc before this point, since locale needs to be
901 set first, in case a diagnostic is issued. */
903 ld1 = (const char **)(ld1_argv = (char **) xcalloc(sizeof (char *), argc+3));
904 ld2 = (const char **)(ld2_argv = (char **) xcalloc(sizeof (char *), argc+6));
905 object = (const char **)(object_lst = (char **) xcalloc(sizeof (char *), argc));
907 #ifdef DEBUG
908 debug = 1;
909 #endif
911 /* Parse command line early for instances of -debug. This allows
912 the debug flag to be set before functions like find_a_file()
913 are called. */
915 int i;
917 for (i = 1; argv[i] != NULL; i ++)
918 if (! strcmp (argv[i], "-debug"))
919 debug = 1;
920 vflag = debug;
923 #ifndef DEFAULT_A_OUT_NAME
924 output_file = "a.out";
925 #else
926 output_file = DEFAULT_A_OUT_NAME;
927 #endif
929 obstack_begin (&temporary_obstack, 0);
930 obstack_begin (&permanent_obstack, 0);
931 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
933 current_demangling_style = gnu_demangling;
934 p = getenv ("COLLECT_GCC_OPTIONS");
935 while (p && *p)
937 const char *q = extract_string (&p);
938 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
939 num_c_args++;
941 obstack_free (&temporary_obstack, temporary_firstobj);
943 /* -fno-exceptions -w */
944 num_c_args += 2;
946 c_ptr = (const char **)
947 (c_argv = (char **) xcalloc (sizeof (char *), num_c_args));
949 if (argc < 2)
950 fatal ("no arguments");
952 #ifdef SIGQUIT
953 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
954 signal (SIGQUIT, handler);
955 #endif
956 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
957 signal (SIGINT, handler);
958 #ifdef SIGALRM
959 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
960 signal (SIGALRM, handler);
961 #endif
962 #ifdef SIGHUP
963 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
964 signal (SIGHUP, handler);
965 #endif
966 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
967 signal (SIGSEGV, handler);
968 #ifdef SIGBUS
969 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
970 signal (SIGBUS, handler);
971 #endif
973 /* Extract COMPILER_PATH and PATH into our prefix list. */
974 prefix_from_env ("COMPILER_PATH", &cpath);
975 prefix_from_env ("PATH", &path);
977 #ifdef CROSS_COMPILE
978 /* If we look for a program in the compiler directories, we just use
979 the short name, since these directories are already system-specific.
980 But it we look for a program in the system directories, we need to
981 qualify the program name with the target machine. */
983 full_ld_suffix = concat(target_machine, "-", ld_suffix, NULL);
985 #if 0
986 full_gld_suffix = concat (target_machine, "-", gld_suffix, NULL);
987 #endif
989 full_nm_suffix = concat (target_machine, "-", nm_suffix, NULL);
991 full_gnm_suffix = concat (target_machine, "-", gnm_suffix, NULL);
993 #ifdef LDD_SUFFIX
994 full_ldd_suffix = concat (target_machine, "-", ldd_suffix, NULL);
995 #endif
997 full_strip_suffix = concat (target_machine, "-", strip_suffix, NULL);
999 full_gstrip_suffix = concat (target_machine, "-", gstrip_suffix, NULL);
1000 #endif /* CROSS_COMPILE */
1002 /* Try to discover a valid linker/nm/strip to use. */
1004 /* Maybe we know the right file to use (if not cross). */
1005 ld_file_name = 0;
1006 #ifdef DEFAULT_LINKER
1007 if (access (DEFAULT_LINKER, X_OK) == 0)
1008 ld_file_name = DEFAULT_LINKER;
1009 if (ld_file_name == 0)
1010 #endif
1011 #ifdef REAL_LD_FILE_NAME
1012 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1013 if (ld_file_name == 0)
1014 #endif
1015 /* Search the (target-specific) compiler dirs for ld'. */
1016 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1017 /* Likewise for `collect-ld'. */
1018 if (ld_file_name == 0)
1019 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1020 /* Search the compiler directories for `ld'. We have protection against
1021 recursive calls in find_a_file. */
1022 if (ld_file_name == 0)
1023 ld_file_name = find_a_file (&cpath, ld_suffix);
1024 /* Search the ordinary system bin directories
1025 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1026 if (ld_file_name == 0)
1027 ld_file_name = find_a_file (&path, full_ld_suffix);
1029 #ifdef REAL_NM_FILE_NAME
1030 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1031 if (nm_file_name == 0)
1032 #endif
1033 nm_file_name = find_a_file (&cpath, gnm_suffix);
1034 if (nm_file_name == 0)
1035 nm_file_name = find_a_file (&path, full_gnm_suffix);
1036 if (nm_file_name == 0)
1037 nm_file_name = find_a_file (&cpath, nm_suffix);
1038 if (nm_file_name == 0)
1039 nm_file_name = find_a_file (&path, full_nm_suffix);
1041 #ifdef LDD_SUFFIX
1042 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1043 if (ldd_file_name == 0)
1044 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1045 #endif
1047 #ifdef REAL_STRIP_FILE_NAME
1048 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1049 if (strip_file_name == 0)
1050 #endif
1051 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1052 if (strip_file_name == 0)
1053 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1054 if (strip_file_name == 0)
1055 strip_file_name = find_a_file (&cpath, strip_suffix);
1056 if (strip_file_name == 0)
1057 strip_file_name = find_a_file (&path, full_strip_suffix);
1059 /* Determine the full path name of the C compiler to use. */
1060 c_file_name = getenv ("COLLECT_GCC");
1061 if (c_file_name == 0)
1063 #ifdef CROSS_COMPILE
1064 c_file_name = concat (target_machine, "-gcc", NULL);
1065 #else
1066 c_file_name = "gcc";
1067 #endif
1070 p = find_a_file (&cpath, c_file_name);
1072 /* Here it should be safe to use the system search path since we should have
1073 already qualified the name of the compiler when it is needed. */
1074 if (p == 0)
1075 p = find_a_file (&path, c_file_name);
1077 if (p)
1078 c_file_name = p;
1080 *ld1++ = *ld2++ = ld_file_name;
1082 /* Make temp file names. */
1083 c_file = make_temp_file (".c");
1084 o_file = make_temp_file (".o");
1085 #ifdef COLLECT_EXPORT_LIST
1086 export_file = make_temp_file (".x");
1087 import_file = make_temp_file (".p");
1088 #endif
1089 ldout = make_temp_file (".ld");
1090 *c_ptr++ = c_file_name;
1091 *c_ptr++ = "-x";
1092 *c_ptr++ = "c";
1093 *c_ptr++ = "-c";
1094 *c_ptr++ = "-o";
1095 *c_ptr++ = o_file;
1097 #ifdef COLLECT_EXPORT_LIST
1098 /* Generate a list of directories from LIBPATH. */
1099 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1100 /* Add to this list also two standard directories where
1101 AIX loader always searches for libraries. */
1102 add_prefix (&libpath_lib_dirs, "/lib");
1103 add_prefix (&libpath_lib_dirs, "/usr/lib");
1104 #endif
1106 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1108 AIX support needs to know if -shared has been specified before
1109 parsing commandline arguments. */
1111 p = getenv ("COLLECT_GCC_OPTIONS");
1112 while (p && *p)
1114 const char *q = extract_string (&p);
1115 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1116 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1117 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1118 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1119 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1120 shared_obj = 1;
1122 obstack_free (&temporary_obstack, temporary_firstobj);
1123 *c_ptr++ = "-fno-exceptions";
1124 *c_ptr++ = "-w";
1126 /* !!! When GCC calls collect2,
1127 it does not know whether it is calling collect2 or ld.
1128 So collect2 cannot meaningfully understand any options
1129 except those ld understands.
1130 If you propose to make GCC pass some other option,
1131 just imagine what will happen if ld is really ld!!! */
1133 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1134 /* After the first file, put in the c++ rt0. */
1136 first_file = 1;
1137 while ((arg = *++argv) != (char *) 0)
1139 *ld1++ = *ld2++ = arg;
1141 if (arg[0] == '-')
1143 switch (arg[1])
1145 #ifdef COLLECT_EXPORT_LIST
1146 /* We want to disable automatic exports on AIX when user
1147 explicitly puts an export list in command line */
1148 case 'b':
1149 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1150 export_flag = 1;
1151 else if (arg[2] == '6' && arg[3] == '4')
1152 aix64_flag = 1;
1153 break;
1154 #endif
1156 case 'd':
1157 if (!strcmp (arg, "-debug"))
1159 /* Already parsed. */
1160 ld1--;
1161 ld2--;
1163 break;
1165 case 'l':
1166 if (first_file)
1168 /* place o_file BEFORE this argument! */
1169 first_file = 0;
1170 ld2--;
1171 *ld2++ = o_file;
1172 *ld2++ = arg;
1174 #ifdef COLLECT_EXPORT_LIST
1176 /* Resolving full library name. */
1177 const char *s = resolve_lib_name (arg+2);
1179 /* If we will use an import list for this library,
1180 we should exclude it from ld args. */
1181 if (use_import_list (s))
1183 ld1--;
1184 ld2--;
1187 /* Saving a full library name. */
1188 add_to_list (&libs, s);
1190 #endif
1191 break;
1193 #ifdef COLLECT_EXPORT_LIST
1194 /* Saving directories where to search for libraries. */
1195 case 'L':
1196 add_prefix (&cmdline_lib_dirs, arg+2);
1197 break;
1198 #endif
1200 case 'o':
1201 if (arg[2] == '\0')
1202 output_file = *ld1++ = *ld2++ = *++argv;
1203 else if (1
1204 #ifdef SWITCHES_NEED_SPACES
1205 && ! index (SWITCHES_NEED_SPACES, arg[1])
1206 #endif
1209 output_file = &arg[2];
1210 break;
1212 case 'r':
1213 if (arg[2] == '\0')
1214 rflag = 1;
1215 break;
1217 case 's':
1218 if (arg[2] == '\0' && do_collecting)
1220 /* We must strip after the nm run, otherwise C++ linking
1221 will not work. Thus we strip in the second ld run, or
1222 else with strip if there is no second ld run. */
1223 strip_flag = 1;
1224 ld1--;
1226 break;
1228 case 'v':
1229 if (arg[2] == '\0')
1230 vflag = 1;
1231 break;
1234 else if ((p = rindex (arg, '.')) != (char *) 0
1235 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1236 || strcmp (p, ".so") == 0))
1238 if (first_file)
1240 first_file = 0;
1241 if (p[1] == 'o')
1242 *ld2++ = o_file;
1243 else
1245 /* place o_file BEFORE this argument! */
1246 ld2--;
1247 *ld2++ = o_file;
1248 *ld2++ = arg;
1251 if (p[1] == 'o')
1252 *object++ = arg;
1253 #ifdef COLLECT_EXPORT_LIST
1254 /* libraries can be specified directly, i.e. without -l flag. */
1255 else
1257 /* If we will use an import list for this library,
1258 we should exclude it from ld args. */
1259 if (use_import_list (arg))
1261 ld1--;
1262 ld2--;
1265 /* Saving a full library name. */
1266 add_to_list (&libs, arg);
1268 #endif
1272 #ifdef COLLECT_EXPORT_LIST
1273 /* This is added only for debugging purposes. */
1274 if (debug)
1276 fprintf (stderr, "List of libraries:\n");
1277 dump_list (stderr, "\t", libs.first);
1280 /* The AIX linker will discard static constructors in object files if
1281 nothing else in the file is referenced, so look at them first. */
1283 char **export_object_lst = object_lst;
1285 while (export_object_lst < object)
1286 scan_prog_file (*export_object_lst++, PASS_OBJ);
1289 struct id *list = libs.first;
1291 for (; list; list = list->next)
1292 scan_prog_file (list->name, PASS_FIRST);
1295 if (exports.first)
1297 char *buf = xmalloc (strlen (export_file) + 5);
1299 sprintf (buf, "-bE:%s", export_file);
1300 *ld1++ = buf;
1301 *ld2++ = buf;
1303 exportf = fopen (export_file, "w");
1304 if (exportf == (FILE *) 0)
1305 fatal_perror ("fopen %s", export_file);
1306 write_aix_file (exportf, exports.first);
1307 if (fclose (exportf))
1308 fatal_perror ("fclose %s", export_file);
1311 if (imports.first)
1313 char *buf = xmalloc (strlen (import_file) + 5);
1315 sprintf (buf, "-bI:%s", import_file);
1316 *ld1++ = buf;
1317 *ld2++ = buf;
1319 importf = fopen (import_file, "w");
1320 if (importf == (FILE *) 0)
1321 fatal_perror ("%s", import_file);
1322 fputs ("#! .\n", importf);
1323 write_aix_file (importf, imports.first);
1324 if (fclose (importf))
1325 fatal_perror ("fclose %s", import_file);
1327 #endif
1329 *c_ptr++ = c_file;
1330 *c_ptr = *ld1 = *object = (char *) 0;
1332 if (vflag)
1334 notice ("collect2 version %s", version_string);
1335 #ifdef TARGET_VERSION
1336 TARGET_VERSION;
1337 #endif
1338 fprintf (stderr, "\n");
1341 if (debug)
1343 const char *ptr;
1344 fprintf (stderr, "ld_file_name = %s\n",
1345 (ld_file_name ? ld_file_name : "not found"));
1346 fprintf (stderr, "c_file_name = %s\n",
1347 (c_file_name ? c_file_name : "not found"));
1348 fprintf (stderr, "nm_file_name = %s\n",
1349 (nm_file_name ? nm_file_name : "not found"));
1350 #ifdef LDD_SUFFIX
1351 fprintf (stderr, "ldd_file_name = %s\n",
1352 (ldd_file_name ? ldd_file_name : "not found"));
1353 #endif
1354 fprintf (stderr, "strip_file_name = %s\n",
1355 (strip_file_name ? strip_file_name : "not found"));
1356 fprintf (stderr, "c_file = %s\n",
1357 (c_file ? c_file : "not found"));
1358 fprintf (stderr, "o_file = %s\n",
1359 (o_file ? o_file : "not found"));
1361 ptr = getenv ("COLLECT_GCC_OPTIONS");
1362 if (ptr)
1363 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1365 ptr = getenv ("COLLECT_GCC");
1366 if (ptr)
1367 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1369 ptr = getenv ("COMPILER_PATH");
1370 if (ptr)
1371 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1373 ptr = getenv ("LIBRARY_PATH");
1374 if (ptr)
1375 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1377 fprintf (stderr, "\n");
1380 /* Load the program, searching all libraries and attempting to provide
1381 undefined symbols from repository information. */
1383 /* On AIX we do this later. */
1384 #ifndef COLLECT_EXPORT_LIST
1385 do_tlink (ld1_argv, object_lst);
1386 #endif
1388 /* If -r or they will be run via some other method, do not build the
1389 constructor or destructor list, just return now. */
1390 if (rflag
1391 #ifndef COLLECT_EXPORT_LIST
1392 || ! do_collecting
1393 #endif
1396 #ifdef COLLECT_EXPORT_LIST
1397 /* Do the link we avoided above if we are exiting. */
1398 do_tlink (ld1_argv, object_lst);
1400 /* But make sure we delete the export file we may have created. */
1401 if (export_file != 0 && export_file[0])
1402 maybe_unlink (export_file);
1403 if (import_file != 0 && import_file[0])
1404 maybe_unlink (import_file);
1405 #endif
1406 maybe_unlink (c_file);
1407 maybe_unlink (o_file);
1408 return 0;
1411 /* Examine the namelist with nm and search it for static constructors
1412 and destructors to call.
1413 Write the constructor and destructor tables to a .s file and reload. */
1415 /* On AIX we already scanned for global constructors/destructors. */
1416 #ifndef COLLECT_EXPORT_LIST
1417 scan_prog_file (output_file, PASS_FIRST);
1418 #endif
1420 #ifdef SCAN_LIBRARIES
1421 scan_libraries (output_file);
1422 #endif
1424 if (debug)
1426 notice ("%d constructor(s) found\n", constructors.number);
1427 notice ("%d destructor(s) found\n", destructors.number);
1428 notice ("%d frame table(s) found\n", frame_tables.number);
1431 if (constructors.number == 0 && destructors.number == 0
1432 && frame_tables.number == 0
1433 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1434 /* If we will be running these functions ourselves, we want to emit
1435 stubs into the shared library so that we do not have to relink
1436 dependent programs when we add static objects. */
1437 && ! shared_obj
1438 #endif
1441 #ifdef COLLECT_EXPORT_LIST
1442 /* Do tlink without additional code generation */
1443 do_tlink (ld1_argv, object_lst);
1444 #endif
1445 /* Strip now if it was requested on the command line. */
1446 if (strip_flag)
1448 char **real_strip_argv = (char **) xcalloc (sizeof (char *), 3);
1449 const char ** strip_argv = (const char **) real_strip_argv;
1451 strip_argv[0] = strip_file_name;
1452 strip_argv[1] = output_file;
1453 strip_argv[2] = (char *) 0;
1454 fork_execute ("strip", real_strip_argv);
1457 #ifdef COLLECT_EXPORT_LIST
1458 maybe_unlink (export_file);
1459 maybe_unlink (import_file);
1460 #endif
1461 maybe_unlink (c_file);
1462 maybe_unlink (o_file);
1463 return 0;
1466 /* Sort ctor and dtor lists by priority. */
1467 sort_ids (&constructors);
1468 sort_ids (&destructors);
1470 maybe_unlink(output_file);
1471 outf = fopen (c_file, "w");
1472 if (outf == (FILE *) 0)
1473 fatal_perror ("fopen %s", c_file);
1475 write_c_file (outf, c_file);
1477 if (fclose (outf))
1478 fatal_perror ("fclose %s", c_file);
1480 /* Tell the linker that we have initializer and finalizer functions. */
1481 #ifdef LD_INIT_SWITCH
1482 *ld2++ = LD_INIT_SWITCH;
1483 *ld2++ = initname;
1484 *ld2++ = LD_FINI_SWITCH;
1485 *ld2++ = fininame;
1486 #endif
1488 #ifdef COLLECT_EXPORT_LIST
1489 if (shared_obj)
1491 /* If we did not add export flag to link arguments before, add it to
1492 second link phase now. No new exports should have been added. */
1493 if (! exports.first)
1495 char *buf = xmalloc (strlen (export_file) + 5);
1497 sprintf (buf, "-bE:%s", export_file);
1498 *ld2++ = buf;
1501 add_to_list (&exports, initname);
1502 add_to_list (&exports, fininame);
1503 add_to_list (&exports, "_GLOBAL__DI");
1504 add_to_list (&exports, "_GLOBAL__DD");
1505 exportf = fopen (export_file, "w");
1506 if (exportf == (FILE *) 0)
1507 fatal_perror ("fopen %s", export_file);
1508 write_aix_file (exportf, exports.first);
1509 if (fclose (exportf))
1510 fatal_perror ("fclose %s", export_file);
1512 #endif
1514 /* End of arguments to second link phase. */
1515 *ld2 = (char*) 0;
1517 if (debug)
1519 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1520 output_file, c_file);
1521 write_c_file (stderr, "stderr");
1522 fprintf (stderr, "========== end of c_file\n\n");
1523 #ifdef COLLECT_EXPORT_LIST
1524 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1525 write_aix_file (stderr, exports.first);
1526 fprintf (stderr, "========== end of export_file\n\n");
1527 #endif
1530 /* Assemble the constructor and destructor tables.
1531 Link the tables in with the rest of the program. */
1533 fork_execute ("gcc", c_argv);
1534 #ifdef COLLECT_EXPORT_LIST
1535 /* On AIX we must call tlink because of possible templates resolution */
1536 do_tlink (ld2_argv, object_lst);
1537 #else
1538 /* Otherwise, simply call ld because tlink is already done */
1539 fork_execute ("ld", ld2_argv);
1541 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1542 constructors/destructors in shared libraries. */
1543 scan_prog_file (output_file, PASS_SECOND);
1544 #endif
1546 maybe_unlink (c_file);
1547 maybe_unlink (o_file);
1549 #ifdef COLLECT_EXPORT_LIST
1550 maybe_unlink (export_file);
1551 maybe_unlink (import_file);
1552 #endif
1554 return 0;
1558 /* Wait for a process to finish, and exit if a non-zero status is found. */
1561 collect_wait (prog)
1562 const char *prog;
1564 int status;
1566 pwait (pexecute_pid, &status, 0);
1567 if (status)
1569 if (WIFSIGNALED (status))
1571 int sig = WTERMSIG (status);
1572 error ("%s terminated with signal %d [%s]%s",
1573 prog, sig, strsignal(sig),
1574 status & 0200 ? "" : ", core dumped");
1575 collect_exit (FATAL_EXIT_CODE);
1578 if (WIFEXITED (status))
1579 return WEXITSTATUS (status);
1581 return 0;
1584 static void
1585 do_wait (prog)
1586 const char *prog;
1588 int ret = collect_wait (prog);
1589 if (ret != 0)
1591 error ("%s returned %d exit status", prog, ret);
1592 collect_exit (ret);
1597 /* Execute a program, and wait for the reply. */
1599 void
1600 collect_execute (prog, argv, redir)
1601 const char *prog;
1602 char **argv;
1603 const char *redir;
1605 char *errmsg_fmt;
1606 char *errmsg_arg;
1607 int redir_handle = -1;
1608 int stdout_save = -1;
1609 int stderr_save = -1;
1611 if (vflag || debug)
1613 char **p_argv;
1614 const char *str;
1616 if (argv[0])
1617 fprintf (stderr, "%s", argv[0]);
1618 else
1619 notice ("[cannot find %s]", prog);
1621 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1622 fprintf (stderr, " %s", str);
1624 fprintf (stderr, "\n");
1627 fflush (stdout);
1628 fflush (stderr);
1630 /* If we cannot find a program we need, complain error. Do this here
1631 since we might not end up needing something that we could not find. */
1633 if (argv[0] == 0)
1634 fatal ("cannot find `%s'", prog);
1636 if (redir)
1638 /* Open response file. */
1639 redir_handle = open (redir, O_WRONLY | O_TRUNC | O_CREAT);
1641 /* Duplicate the stdout and stderr file handles
1642 so they can be restored later. */
1643 stdout_save = dup (STDOUT_FILENO);
1644 if (stdout_save == -1)
1645 fatal_perror ("redirecting stdout: %s", redir);
1646 stderr_save = dup (STDERR_FILENO);
1647 if (stderr_save == -1)
1648 fatal_perror ("redirecting stdout: %s", redir);
1650 /* Redirect stdout & stderr to our response file. */
1651 dup2 (redir_handle, STDOUT_FILENO);
1652 dup2 (redir_handle, STDERR_FILENO);
1655 pexecute_pid = pexecute (argv[0], argv, argv[0], NULL,
1656 &errmsg_fmt, &errmsg_arg,
1657 (PEXECUTE_FIRST | PEXECUTE_LAST | PEXECUTE_SEARCH));
1659 if (redir)
1661 /* Restore stdout and stderr to their previous settings. */
1662 dup2 (stdout_save, STDOUT_FILENO);
1663 dup2 (stderr_save, STDERR_FILENO);
1665 /* Close reponse file. */
1666 close (redir_handle);
1669 if (pexecute_pid == -1)
1670 fatal_perror (errmsg_fmt, errmsg_arg);
1673 static void
1674 fork_execute (prog, argv)
1675 const char *prog;
1676 char **argv;
1678 collect_execute (prog, argv, NULL);
1679 do_wait (prog);
1682 /* Unlink a file unless we are debugging. */
1684 static void
1685 maybe_unlink (file)
1686 const char *file;
1688 if (!debug)
1689 unlink (file);
1690 else
1691 notice ("[Leaving %s]\n", file);
1695 static long sequence_number = 0;
1697 /* Add a name to a linked list. */
1699 static void
1700 add_to_list (head_ptr, name)
1701 struct head *head_ptr;
1702 const char *name;
1704 struct id *newid
1705 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1706 struct id *p;
1707 strcpy (newid->name, name);
1709 if (head_ptr->first)
1710 head_ptr->last->next = newid;
1711 else
1712 head_ptr->first = newid;
1714 /* Check for duplicate symbols. */
1715 for (p = head_ptr->first;
1716 strcmp (name, p->name) != 0;
1717 p = p->next)
1719 if (p != newid)
1721 head_ptr->last->next = 0;
1722 free (newid);
1723 return;
1726 newid->sequence = ++sequence_number;
1727 head_ptr->last = newid;
1728 head_ptr->number++;
1731 /* Grab the init priority number from an init function name that
1732 looks like "_GLOBAL_.I.12345.foo". */
1734 static int
1735 extract_init_priority (name)
1736 const char *name;
1738 int pos = 0, pri;
1740 while (name[pos] == '_')
1741 ++pos;
1742 pos += 10; /* strlen ("GLOBAL__X_") */
1744 /* Extract init_p number from ctor/dtor name. */
1745 pri = atoi (name + pos);
1746 return pri ? pri : DEFAULT_INIT_PRIORITY;
1749 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1750 ctors will be run from right to left, dtors from left to right. */
1752 static void
1753 sort_ids (head_ptr)
1754 struct head *head_ptr;
1756 /* id holds the current element to insert. id_next holds the next
1757 element to insert. id_ptr iterates through the already sorted elements
1758 looking for the place to insert id. */
1759 struct id *id, *id_next, **id_ptr;
1761 id = head_ptr->first;
1763 /* We don't have any sorted elements yet. */
1764 head_ptr->first = NULL;
1766 for (; id; id = id_next)
1768 id_next = id->next;
1769 id->sequence = extract_init_priority (id->name);
1771 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1772 if (*id_ptr == NULL
1773 /* If the sequence numbers are the same, we put the id from the
1774 file later on the command line later in the list. */
1775 || id->sequence > (*id_ptr)->sequence
1776 /* Hack: do lexical compare, too.
1777 || (id->sequence == (*id_ptr)->sequence
1778 && strcmp (id->name, (*id_ptr)->name) > 0) */
1781 id->next = *id_ptr;
1782 *id_ptr = id;
1783 break;
1787 /* Now set the sequence numbers properly so write_c_file works. */
1788 for (id = head_ptr->first; id; id = id->next)
1789 id->sequence = ++sequence_number;
1792 /* Write: `prefix', the names on list LIST, `suffix'. */
1794 static void
1795 write_list (stream, prefix, list)
1796 FILE *stream;
1797 const char *prefix;
1798 struct id *list;
1800 while (list)
1802 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1803 list = list->next;
1807 #ifdef COLLECT_EXPORT_LIST
1808 /* This function is really used only on AIX, but may be useful. */
1809 static int
1810 is_in_list (prefix, list)
1811 const char *prefix;
1812 struct id *list;
1814 while (list)
1816 if (!strcmp (prefix, list->name)) return 1;
1817 list = list->next;
1819 return 0;
1821 #endif
1823 /* Added for debugging purpose. */
1824 #ifdef COLLECT_EXPORT_LIST
1825 static void
1826 dump_list (stream, prefix, list)
1827 FILE *stream;
1828 const char *prefix;
1829 struct id *list;
1831 while (list)
1833 fprintf (stream, "%s%s,\n", prefix, list->name);
1834 list = list->next;
1837 #endif
1839 #if 0
1840 static void
1841 dump_prefix_list (stream, prefix, list)
1842 FILE *stream;
1843 const char *prefix;
1844 struct prefix_list *list;
1846 while (list)
1848 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1849 list = list->next;
1852 #endif
1854 static void
1855 write_list_with_asm (stream, prefix, list)
1856 FILE *stream;
1857 const char *prefix;
1858 struct id *list;
1860 while (list)
1862 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1863 prefix, list->sequence, list->name);
1864 list = list->next;
1868 /* Write out the constructor and destructor tables statically (for a shared
1869 object), along with the functions to execute them. */
1871 static void
1872 write_c_file_stat (stream, name)
1873 FILE *stream;
1874 const char *name ATTRIBUTE_UNUSED;
1876 const char *p, *q;
1877 char *prefix, *r;
1878 int frames = (frame_tables.number > 0);
1880 /* Figure out name of output_file, stripping off .so version. */
1881 p = rindex (output_file, '/');
1882 if (p == 0)
1883 p = output_file;
1884 else
1885 p++;
1886 q = p;
1887 while (q)
1889 q = index (q,'.');
1890 if (q == 0)
1892 q = p + strlen (p);
1893 break;
1895 else
1897 if (strncmp (q, ".so", 3) == 0)
1899 q += 3;
1900 break;
1902 else
1903 q++;
1906 /* q points to null at end of the string (or . of the .so version) */
1907 prefix = xmalloc (q - p + 1);
1908 strncpy (prefix, p, q - p);
1909 prefix[q - p] = 0;
1910 for (r = prefix; *r; r++)
1911 if (!ISALNUM ((unsigned char)*r))
1912 *r = '_';
1913 if (debug)
1914 notice ("\nwrite_c_file - output name is %s, prefix is %s\n",
1915 output_file, prefix);
1917 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1918 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1919 sprintf (initname, INIT_NAME_FORMAT, prefix);
1921 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1922 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1923 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1925 free (prefix);
1927 /* Write the tables as C code */
1929 fprintf (stream, "static int count;\n");
1930 fprintf (stream, "typedef void entry_pt();\n");
1931 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
1933 if (frames)
1935 write_list_with_asm (stream, "extern void *", frame_tables.first);
1937 fprintf (stream, "\tstatic void *frame_table[] = {\n");
1938 write_list (stream, "\t\t&", frame_tables.first);
1939 fprintf (stream, "\t0\n};\n");
1941 /* This must match what's in frame.h. */
1942 fprintf (stream, "struct object {\n");
1943 fprintf (stream, " void *pc_begin;\n");
1944 fprintf (stream, " void *pc_end;\n");
1945 fprintf (stream, " void *fde_begin;\n");
1946 fprintf (stream, " void *fde_array;\n");
1947 fprintf (stream, " __SIZE_TYPE__ count;\n");
1948 fprintf (stream, " struct object *next;\n");
1949 fprintf (stream, "};\n");
1951 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
1952 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
1954 fprintf (stream, "static void reg_frame () {\n");
1955 fprintf (stream, "\tstatic struct object ob;\n");
1956 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
1957 fprintf (stream, "\t}\n");
1959 fprintf (stream, "static void dereg_frame () {\n");
1960 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
1961 fprintf (stream, "\t}\n");
1964 fprintf (stream, "void %s() {\n", initname);
1965 if (constructors.number > 0 || frames)
1967 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
1968 write_list (stream, "\t\t", constructors.first);
1969 if (frames)
1970 fprintf (stream, "\treg_frame,\n");
1971 fprintf (stream, "\t};\n");
1972 fprintf (stream, "\tentry_pt **p;\n");
1973 fprintf (stream, "\tif (count++ != 0) return;\n");
1974 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
1975 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
1977 else
1978 fprintf (stream, "\t++count;\n");
1979 fprintf (stream, "}\n");
1980 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
1981 fprintf (stream, "void %s() {\n", fininame);
1982 if (destructors.number > 0 || frames)
1984 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
1985 write_list (stream, "\t\t", destructors.first);
1986 if (frames)
1987 fprintf (stream, "\tdereg_frame,\n");
1988 fprintf (stream, "\t};\n");
1989 fprintf (stream, "\tentry_pt **p;\n");
1990 fprintf (stream, "\tif (--count != 0) return;\n");
1991 fprintf (stream, "\tp = dtors;\n");
1992 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
1993 destructors.number + frames);
1995 fprintf (stream, "}\n");
1997 if (shared_obj)
1999 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
2000 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
2004 /* Write the constructor/destructor tables. */
2006 #ifndef LD_INIT_SWITCH
2007 static void
2008 write_c_file_glob (stream, name)
2009 FILE *stream;
2010 const char *name ATTRIBUTE_UNUSED;
2012 /* Write the tables as C code */
2014 int frames = (frame_tables.number > 0);
2016 fprintf (stream, "typedef void entry_pt();\n\n");
2018 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2020 if (frames)
2022 write_list_with_asm (stream, "extern void *", frame_tables.first);
2024 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2025 write_list (stream, "\t\t&", frame_tables.first);
2026 fprintf (stream, "\t0\n};\n");
2028 /* This must match what's in frame.h. */
2029 fprintf (stream, "struct object {\n");
2030 fprintf (stream, " void *pc_begin;\n");
2031 fprintf (stream, " void *pc_end;\n");
2032 fprintf (stream, " void *fde_begin;\n");
2033 fprintf (stream, " void *fde_array;\n");
2034 fprintf (stream, " __SIZE_TYPE__ count;\n");
2035 fprintf (stream, " struct object *next;\n");
2036 fprintf (stream, "};\n");
2038 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2039 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2041 fprintf (stream, "static void reg_frame () {\n");
2042 fprintf (stream, "\tstatic struct object ob;\n");
2043 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2044 fprintf (stream, "\t}\n");
2046 fprintf (stream, "static void dereg_frame () {\n");
2047 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2048 fprintf (stream, "\t}\n");
2051 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2052 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2053 write_list (stream, "\t", constructors.first);
2054 if (frames)
2055 fprintf (stream, "\treg_frame,\n");
2056 fprintf (stream, "\t0\n};\n\n");
2058 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2060 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2061 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2062 write_list (stream, "\t", destructors.first);
2063 if (frames)
2064 fprintf (stream, "\tdereg_frame,\n");
2065 fprintf (stream, "\t0\n};\n\n");
2067 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2068 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2070 #endif /* ! LD_INIT_SWITCH */
2072 static void
2073 write_c_file (stream, name)
2074 FILE *stream;
2075 const char *name;
2077 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2078 #ifndef LD_INIT_SWITCH
2079 if (! shared_obj)
2080 write_c_file_glob (stream, name);
2081 else
2082 #endif
2083 write_c_file_stat (stream, name);
2084 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2087 #ifdef COLLECT_EXPORT_LIST
2088 static void
2089 write_aix_file (stream, list)
2090 FILE *stream;
2091 struct id *list;
2093 for (; list; list = list->next)
2095 fputs (list->name, stream);
2096 putc ('\n', stream);
2099 #endif
2101 #ifdef OBJECT_FORMAT_NONE
2103 /* Generic version to scan the name list of the loaded program for
2104 the symbols g++ uses for static constructors and destructors.
2106 The constructor table begins at __CTOR_LIST__ and contains a count
2107 of the number of pointers (or -1 if the constructors are built in a
2108 separate section by the linker), followed by the pointers to the
2109 constructor functions, terminated with a null pointer. The
2110 destructor table has the same format, and begins at __DTOR_LIST__. */
2112 static void
2113 scan_prog_file (prog_name, which_pass)
2114 const char *prog_name;
2115 enum pass which_pass;
2117 void (*int_handler) PROTO ((int));
2118 void (*quit_handler) PROTO ((int));
2119 char *real_nm_argv[4];
2120 const char **nm_argv = (const char **) real_nm_argv;
2121 int pid;
2122 int argc = 0;
2123 int pipe_fd[2];
2124 char *p, buf[1024];
2125 FILE *inf;
2127 if (which_pass == PASS_SECOND)
2128 return;
2130 /* If we do not have an `nm', complain. */
2131 if (nm_file_name == 0)
2132 fatal ("cannot find `nm'");
2134 nm_argv[argc++] = nm_file_name;
2135 if (NM_FLAGS[0] != '\0')
2136 nm_argv[argc++] = NM_FLAGS;
2138 nm_argv[argc++] = prog_name;
2139 nm_argv[argc++] = (char *) 0;
2141 if (pipe (pipe_fd) < 0)
2142 fatal_perror ("pipe");
2144 inf = fdopen (pipe_fd[0], "r");
2145 if (inf == (FILE *) 0)
2146 fatal_perror ("fdopen");
2148 /* Trace if needed. */
2149 if (vflag)
2151 const char **p_argv;
2152 const char *str;
2154 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2155 fprintf (stderr, " %s", str);
2157 fprintf (stderr, "\n");
2160 fflush (stdout);
2161 fflush (stderr);
2163 /* Spawn child nm on pipe */
2164 pid = vfork ();
2165 if (pid == -1)
2166 fatal_perror (VFORK_STRING);
2168 if (pid == 0) /* child context */
2170 /* setup stdout */
2171 if (dup2 (pipe_fd[1], 1) < 0)
2172 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2174 if (close (pipe_fd[0]) < 0)
2175 fatal_perror ("close %d", pipe_fd[0]);
2177 if (close (pipe_fd[1]) < 0)
2178 fatal_perror ("close %d", pipe_fd[1]);
2180 execv (nm_file_name, real_nm_argv);
2181 fatal_perror ("execvp %s", nm_file_name);
2184 /* Parent context from here on. */
2185 int_handler = (void (*) PROTO ((int))) signal (SIGINT, SIG_IGN);
2186 #ifdef SIGQUIT
2187 quit_handler = (void (*) PROTO ((int))) signal (SIGQUIT, SIG_IGN);
2188 #endif
2190 if (close (pipe_fd[1]) < 0)
2191 fatal_perror ("close %d", pipe_fd[1]);
2193 if (debug)
2194 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2196 /* Read each line of nm output. */
2197 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2199 int ch, ch2;
2200 char *name, *end;
2202 /* If it contains a constructor or destructor name, add the name
2203 to the appropriate list. */
2205 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2206 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2207 break;
2209 if (ch != '_')
2210 continue;
2212 name = p;
2213 /* Find the end of the symbol name.
2214 Do not include `|', because Encore nm can tack that on the end. */
2215 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2216 end++)
2217 continue;
2220 *end = '\0';
2221 switch (is_ctor_dtor (name))
2223 case 1:
2224 if (which_pass != PASS_LIB)
2225 add_to_list (&constructors, name);
2226 break;
2228 case 2:
2229 if (which_pass != PASS_LIB)
2230 add_to_list (&destructors, name);
2231 break;
2233 case 3:
2234 if (which_pass != PASS_LIB)
2235 fatal ("init function found in object %s", prog_name);
2236 #ifndef LD_INIT_SWITCH
2237 add_to_list (&constructors, name);
2238 #endif
2239 break;
2241 case 4:
2242 if (which_pass != PASS_LIB)
2243 fatal ("fini function found in object %s", prog_name);
2244 #ifndef LD_FINI_SWITCH
2245 add_to_list (&destructors, name);
2246 #endif
2247 break;
2249 case 5:
2250 if (which_pass != PASS_LIB)
2251 add_to_list (&frame_tables, name);
2252 break;
2254 default: /* not a constructor or destructor */
2255 continue;
2258 if (debug)
2259 fprintf (stderr, "\t%s\n", buf);
2262 if (debug)
2263 fprintf (stderr, "\n");
2265 if (fclose (inf) != 0)
2266 fatal_perror ("fclose");
2268 do_wait (nm_file_name);
2270 signal (SIGINT, int_handler);
2271 #ifdef SIGQUIT
2272 signal (SIGQUIT, quit_handler);
2273 #endif
2276 #if SUNOS4_SHARED_LIBRARIES
2278 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2279 that the output file depends upon and their initialization/finalization
2280 routines, if any. */
2282 #include <a.out.h>
2283 #include <fcntl.h>
2284 #include <link.h>
2285 #include <sys/mman.h>
2286 #include <sys/param.h>
2287 #include <unistd.h>
2288 #include <sys/dir.h>
2290 /* pointers to the object file */
2291 unsigned object; /* address of memory mapped file */
2292 unsigned objsize; /* size of memory mapped to file */
2293 char * code; /* pointer to code segment */
2294 char * data; /* pointer to data segment */
2295 struct nlist *symtab; /* pointer to symbol table */
2296 struct link_dynamic *ld;
2297 struct link_dynamic_2 *ld_2;
2298 struct head libraries;
2300 /* Map the file indicated by NAME into memory and store its address. */
2302 static void mapfile PROTO ((const char *));
2304 static void
2305 mapfile (name)
2306 const char *name;
2308 int fp;
2309 struct stat s;
2310 if ((fp = open (name, O_RDONLY)) == -1)
2311 fatal ("unable to open file '%s'", name);
2312 if (fstat (fp, &s) == -1)
2313 fatal ("unable to stat file '%s'", name);
2315 objsize = s.st_size;
2316 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2317 fp, 0);
2318 if (object == (unsigned)-1)
2319 fatal ("unable to mmap file '%s'", name);
2321 close (fp);
2324 /* Helpers for locatelib. */
2326 static const char *libname;
2328 static int libselect PROTO ((struct direct *));
2330 static int
2331 libselect (d)
2332 struct direct *d;
2334 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2337 /* If one file has an additional numeric extension past LIBNAME, then put
2338 that one first in the sort. If both files have additional numeric
2339 extensions, then put the one with the higher number first in the sort.
2341 We must verify that the extension is numeric, because Sun saves the
2342 original versions of patched libraries with a .FCS extension. Files with
2343 invalid extensions must go last in the sort, so that they will not be used. */
2344 static int libcompare PROTO ((struct direct **, struct direct **));
2346 static int
2347 libcompare (d1, d2)
2348 struct direct **d1, **d2;
2350 int i1, i2 = strlen (libname);
2351 char *e1 = (*d1)->d_name + i2;
2352 char *e2 = (*d2)->d_name + i2;
2354 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2355 && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2357 ++e1;
2358 ++e2;
2359 i1 = strtol (e1, &e1, 10);
2360 i2 = strtol (e2, &e2, 10);
2361 if (i1 != i2)
2362 return i1 - i2;
2365 if (*e1)
2367 /* It has a valid numeric extension, prefer this one. */
2368 if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2369 return 1;
2370 /* It has a invalid numeric extension, must prefer the other one. */
2371 else
2372 return -1;
2374 else if (*e2)
2376 /* It has a valid numeric extension, prefer this one. */
2377 if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2378 return -1;
2379 /* It has a invalid numeric extension, must prefer the other one. */
2380 else
2381 return 1;
2383 else
2384 return 0;
2387 /* Given the name NAME of a dynamic dependency, find its pathname and add
2388 it to the list of libraries. */
2389 static void locatelib PROTO ((const char *));
2391 static void
2392 locatelib (name)
2393 const char *name;
2395 static const char **l;
2396 static int cnt;
2397 char buf[MAXPATHLEN];
2398 char *p, *q;
2399 const char **pp;
2401 if (l == 0)
2403 char *ld_rules;
2404 char *ldr = 0;
2405 /* counting elements in array, need 1 extra for null */
2406 cnt = 1;
2407 ld_rules = (char *) (ld_2->ld_rules + code);
2408 if (ld_rules)
2410 cnt++;
2411 for (; *ld_rules != 0; ld_rules++)
2412 if (*ld_rules == ':')
2413 cnt++;
2414 ld_rules = (char *) (ld_2->ld_rules + code);
2415 ldr = xstrdup (ld_rules);
2417 p = getenv ("LD_LIBRARY_PATH");
2418 q = 0;
2419 if (p)
2421 cnt++;
2422 for (q = p ; *q != 0; q++)
2423 if (*q == ':')
2424 cnt++;
2425 q = xstrdup (p);
2427 l = (const char **) xmalloc ((cnt + 3) * sizeof (char *));
2428 pp = l;
2429 if (ldr)
2431 *pp++ = ldr;
2432 for (; *ldr != 0; ldr++)
2433 if (*ldr == ':')
2435 *ldr++ = 0;
2436 *pp++ = ldr;
2439 if (q)
2441 *pp++ = q;
2442 for (; *q != 0; q++)
2443 if (*q == ':')
2445 *q++ = 0;
2446 *pp++ = q;
2449 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2450 *pp++ = "/lib";
2451 *pp++ = "/usr/lib";
2452 *pp++ = "/usr/local/lib";
2453 *pp = 0;
2455 libname = name;
2456 for (pp = l; *pp != 0 ; pp++)
2458 struct direct **namelist;
2459 int entries;
2460 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2462 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2463 add_to_list (&libraries, buf);
2464 if (debug)
2465 fprintf (stderr, "%s\n", buf);
2466 break;
2469 if (*pp == 0)
2471 if (debug)
2472 notice ("not found\n");
2473 else
2474 fatal ("dynamic dependency %s not found", name);
2478 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2479 that it depends upon and any constructors or destructors they contain. */
2481 static void
2482 scan_libraries (prog_name)
2483 const char *prog_name;
2485 struct exec *header;
2486 char *base;
2487 struct link_object *lo;
2488 char buff[MAXPATHLEN];
2489 struct id *list;
2491 mapfile (prog_name);
2492 header = (struct exec *)object;
2493 if (N_BADMAG (*header))
2494 fatal ("bad magic number in file '%s'", prog_name);
2495 if (header->a_dynamic == 0)
2496 return;
2498 code = (char *) (N_TXTOFF (*header) + (long) header);
2499 data = (char *) (N_DATOFF (*header) + (long) header);
2500 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2502 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2504 /* shared object */
2505 ld = (struct link_dynamic *) (symtab->n_value + code);
2506 base = code;
2508 else
2510 /* executable */
2511 ld = (struct link_dynamic *) data;
2512 base = code-PAGSIZ;
2515 if (debug)
2516 notice ("dynamic dependencies.\n");
2518 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2519 for (lo = (struct link_object *) ld_2->ld_need; lo;
2520 lo = (struct link_object *) lo->lo_next)
2522 char *name;
2523 lo = (struct link_object *) ((long) lo + code);
2524 name = (char *) (code + lo->lo_name);
2525 if (lo->lo_library)
2527 if (debug)
2528 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2529 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2530 locatelib (buff);
2532 else
2534 if (debug)
2535 fprintf (stderr, "\t%s\n", name);
2536 add_to_list (&libraries, name);
2540 if (debug)
2541 fprintf (stderr, "\n");
2543 /* now iterate through the library list adding their symbols to
2544 the list. */
2545 for (list = libraries.first; list; list = list->next)
2546 scan_prog_file (list->name, PASS_LIB);
2549 #else /* SUNOS4_SHARED_LIBRARIES */
2550 #ifdef LDD_SUFFIX
2552 /* Use the List Dynamic Dependencies program to find shared libraries that
2553 the output file depends upon and their initialization/finalization
2554 routines, if any. */
2556 static void
2557 scan_libraries (prog_name)
2558 const char *prog_name;
2560 static struct head libraries; /* list of shared libraries found */
2561 struct id *list;
2562 void (*int_handler) PROTO ((int));
2563 void (*quit_handler) PROTO ((int));
2564 char *real_ldd_argv[4];
2565 const char **ldd_argv = (const char **) real_ldd_argv;
2566 int pid;
2567 int argc = 0;
2568 int pipe_fd[2];
2569 char buf[1024];
2570 FILE *inf;
2572 /* If we do not have an `ldd', complain. */
2573 if (ldd_file_name == 0)
2575 error ("cannot find `ldd'");
2576 return;
2579 ldd_argv[argc++] = ldd_file_name;
2580 ldd_argv[argc++] = prog_name;
2581 ldd_argv[argc++] = (char *) 0;
2583 if (pipe (pipe_fd) < 0)
2584 fatal_perror ("pipe");
2586 inf = fdopen (pipe_fd[0], "r");
2587 if (inf == (FILE *) 0)
2588 fatal_perror ("fdopen");
2590 /* Trace if needed. */
2591 if (vflag)
2593 const char **p_argv;
2594 const char *str;
2596 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2597 fprintf (stderr, " %s", str);
2599 fprintf (stderr, "\n");
2602 fflush (stdout);
2603 fflush (stderr);
2605 /* Spawn child ldd on pipe */
2606 pid = vfork ();
2607 if (pid == -1)
2608 fatal_perror (VFORK_STRING);
2610 if (pid == 0) /* child context */
2612 /* setup stdout */
2613 if (dup2 (pipe_fd[1], 1) < 0)
2614 fatal_perror ("dup2 %d 1", pipe_fd[1]);
2616 if (close (pipe_fd[0]) < 0)
2617 fatal_perror ("close %d", pipe_fd[0]);
2619 if (close (pipe_fd[1]) < 0)
2620 fatal_perror ("close %d", pipe_fd[1]);
2622 execv (ldd_file_name, real_ldd_argv);
2623 fatal_perror ("execv %s", ldd_file_name);
2626 /* Parent context from here on. */
2627 int_handler = (void (*) PROTO ((int))) signal (SIGINT, SIG_IGN);
2628 #ifdef SIGQUIT
2629 quit_handler = (void (*) PROTO ((int))) signal (SIGQUIT, SIG_IGN);
2630 #endif
2632 if (close (pipe_fd[1]) < 0)
2633 fatal_perror ("close %d", pipe_fd[1]);
2635 if (debug)
2636 notice ("\nldd output with constructors/destructors.\n");
2638 /* Read each line of ldd output. */
2639 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2641 int ch, ch2;
2642 char *name, *end, *p = buf;
2644 /* Extract names of libraries and add to list. */
2645 PARSE_LDD_OUTPUT (p);
2646 if (p == 0)
2647 continue;
2649 name = p;
2650 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2651 fatal ("dynamic dependency %s not found", buf);
2653 /* Find the end of the symbol name. */
2654 for (end = p;
2655 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2656 end++)
2657 continue;
2658 *end = '\0';
2660 if (access (name, R_OK) == 0)
2661 add_to_list (&libraries, name);
2662 else
2663 fatal ("unable to open dynamic dependency '%s'", buf);
2665 if (debug)
2666 fprintf (stderr, "\t%s\n", buf);
2668 if (debug)
2669 fprintf (stderr, "\n");
2671 if (fclose (inf) != 0)
2672 fatal_perror ("fclose");
2674 do_wait (ldd_file_name);
2676 signal (SIGINT, int_handler);
2677 #ifdef SIGQUIT
2678 signal (SIGQUIT, quit_handler);
2679 #endif
2681 /* now iterate through the library list adding their symbols to
2682 the list. */
2683 for (list = libraries.first; list; list = list->next)
2684 scan_prog_file (list->name, PASS_LIB);
2687 #endif /* LDD_SUFFIX */
2688 #endif /* SUNOS4_SHARED_LIBRARIES */
2690 #endif /* OBJECT_FORMAT_NONE */
2694 * COFF specific stuff.
2697 #ifdef OBJECT_FORMAT_COFF
2699 #if defined(EXTENDED_COFF)
2700 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2701 # define GCC_SYMENT SYMR
2702 # define GCC_OK_SYMBOL(X) ((X).st == stProc || (X).st == stGlobal)
2703 # define GCC_SYMINC(X) (1)
2704 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2705 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2706 #else
2707 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2708 # define GCC_SYMENT SYMENT
2709 # define GCC_OK_SYMBOL(X) \
2710 (((X).n_sclass == C_EXT) && \
2711 ((X).n_scnum > N_UNDEF) && \
2712 (aix64_flag \
2713 || (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) \
2714 || ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT))))
2715 # define GCC_UNDEF_SYMBOL(X) \
2716 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2717 # define GCC_SYMINC(X) ((X).n_numaux+1)
2718 # define GCC_SYMZERO(X) 0
2719 # define GCC_CHECK_HDR(X) \
2720 ((HEADER (X).f_magic == U802TOCMAGIC && ! aix64_flag) \
2721 || (HEADER (X).f_magic == 0757 && aix64_flag))
2722 #endif
2724 extern char *ldgetname ();
2726 /* COFF version to scan the name list of the loaded program for
2727 the symbols g++ uses for static constructors and destructors.
2729 The constructor table begins at __CTOR_LIST__ and contains a count
2730 of the number of pointers (or -1 if the constructors are built in a
2731 separate section by the linker), followed by the pointers to the
2732 constructor functions, terminated with a null pointer. The
2733 destructor table has the same format, and begins at __DTOR_LIST__. */
2735 static void
2736 scan_prog_file (prog_name, which_pass)
2737 const char *prog_name;
2738 enum pass which_pass;
2740 LDFILE *ldptr = NULL;
2741 int sym_index, sym_count;
2742 int is_shared = 0;
2743 #ifdef COLLECT_EXPORT_LIST
2744 /* Should we generate an import list for given prog_name? */
2745 int import_flag = (which_pass == PASS_OBJ ? 0 : use_import_list (prog_name));
2746 #endif
2748 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2749 return;
2751 #ifdef COLLECT_EXPORT_LIST
2752 /* We do not need scanning for some standard C libraries. */
2753 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2754 return;
2756 /* On AIX we have a loop, because there is not much difference
2757 between an object and an archive. This trick allows us to
2758 eliminate scan_libraries() function. */
2761 #endif
2762 /* Some platforms (e.g. OSF4) declare ldopen as taking a
2763 non-const char * filename parameter, even though it will not
2764 modify that string. So we must cast away const-ness here,
2765 which will cause -Wcast-qual to burp. */
2766 if ((ldptr = ldopen ((char *)prog_name, ldptr)) != NULL)
2768 if (! MY_ISCOFF (HEADER (ldptr).f_magic))
2769 fatal ("%s: not a COFF file", prog_name);
2771 if (GCC_CHECK_HDR (ldptr))
2773 sym_count = GCC_SYMBOLS (ldptr);
2774 sym_index = GCC_SYMZERO (ldptr);
2776 #ifdef COLLECT_EXPORT_LIST
2777 /* Is current archive member a shared object? */
2778 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2779 #endif
2781 while (sym_index < sym_count)
2783 GCC_SYMENT symbol;
2785 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2786 break;
2787 sym_index += GCC_SYMINC (symbol);
2789 if (GCC_OK_SYMBOL (symbol))
2791 char *name;
2793 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2794 continue; /* should never happen */
2796 #ifdef XCOFF_DEBUGGING_INFO
2797 /* All AIX function names have a duplicate entry
2798 beginning with a dot. */
2799 if (*name == '.')
2800 ++name;
2801 #endif
2803 switch (is_ctor_dtor (name))
2805 case 1:
2806 if (! is_shared) add_to_list (&constructors, name);
2807 #ifdef COLLECT_EXPORT_LIST
2808 if (which_pass == PASS_OBJ)
2809 add_to_list (&exports, name);
2810 /* If this symbol was undefined and we are building
2811 an import list, we should add a symbol to this
2812 list. */
2813 else
2814 if (import_flag
2815 && is_in_list (name, undefined.first))
2816 add_to_list (&imports, name);
2817 #endif
2818 break;
2820 case 2:
2821 if (! is_shared) add_to_list (&destructors, name);
2822 #ifdef COLLECT_EXPORT_LIST
2823 if (which_pass == PASS_OBJ)
2824 add_to_list (&exports, name);
2825 /* If this symbol was undefined and we are building
2826 an import list, we should add a symbol to this
2827 list. */
2828 else
2829 if (import_flag
2830 && is_in_list (name, undefined.first))
2831 add_to_list (&imports, name);
2832 #endif
2833 break;
2835 #ifdef COLLECT_EXPORT_LIST
2836 case 3:
2837 if (is_shared)
2838 add_to_list (&constructors, name);
2839 break;
2841 case 4:
2842 if (is_shared)
2843 add_to_list (&destructors, name);
2844 break;
2845 #endif
2847 case 5:
2848 if (! is_shared)
2849 add_to_list (&frame_tables, name);
2850 break;
2852 default: /* not a constructor or destructor */
2853 #ifdef COLLECT_EXPORT_LIST
2854 /* If we are building a shared object on AIX we need
2855 to explicitly export all global symbols or add
2856 them to import list. */
2857 if (shared_obj)
2859 if (which_pass == PASS_OBJ && (! export_flag))
2860 add_to_list (&exports, name);
2861 else if (! is_shared && which_pass == PASS_FIRST
2862 && import_flag
2863 && is_in_list(name, undefined.first))
2864 add_to_list (&imports, name);
2866 #endif
2867 continue;
2870 #if !defined(EXTENDED_COFF)
2871 if (debug)
2872 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2873 symbol.n_scnum, symbol.n_sclass,
2874 (symbol.n_type ? "0" : ""), symbol.n_type,
2875 name);
2876 #else
2877 if (debug)
2878 fprintf (stderr,
2879 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2880 symbol.iss, (long) symbol.value, symbol.index, name);
2881 #endif
2883 #ifdef COLLECT_EXPORT_LIST
2884 /* If we are building a shared object we should collect
2885 information about undefined symbols for later
2886 import list generation. */
2887 else if (shared_obj && GCC_UNDEF_SYMBOL (symbol))
2889 char *name;
2891 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2892 continue; /* should never happen */
2894 /* All AIX function names have a duplicate entry
2895 beginning with a dot. */
2896 if (*name == '.')
2897 ++name;
2898 add_to_list (&undefined, name);
2900 #endif
2903 #ifdef COLLECT_EXPORT_LIST
2904 else
2906 /* If archive contains both 32-bit and 64-bit objects,
2907 we want to skip objects in other mode so mismatch normal. */
2908 if (debug)
2909 fprintf (stderr, "%s : magic=%o aix64=%d mismatch\n",
2910 prog_name, HEADER (ldptr).f_magic, aix64_flag);
2912 #endif
2914 else
2916 fatal ("%s: cannot open as COFF file", prog_name);
2918 #ifdef COLLECT_EXPORT_LIST
2919 /* On AIX loop continues while there are more members in archive. */
2921 while (ldclose (ldptr) == FAILURE);
2922 #else
2923 /* Otherwise we simply close ldptr. */
2924 (void) ldclose(ldptr);
2925 #endif
2929 #ifdef COLLECT_EXPORT_LIST
2931 /* This new function is used to decide whether we should
2932 generate import list for an object or to use it directly. */
2933 static int
2934 use_import_list (prog_name)
2935 const char *prog_name;
2937 char *p;
2939 /* If we do not build a shared object then import list should not be used. */
2940 if (! shared_obj) return 0;
2942 /* Currently we check only for libgcc, but this can be changed in future. */
2943 p = strstr (prog_name, "libgcc.a");
2944 if (p != 0 && (strlen (p) == sizeof ("libgcc.a") - 1))
2945 return 1;
2946 return 0;
2949 /* Given a library name without "lib" prefix, this function
2950 returns a full library name including a path. */
2951 static char *
2952 resolve_lib_name (name)
2953 const char *name;
2955 char *lib_buf;
2956 int i, j, l = 0;
2958 for (i = 0; libpaths[i]; i++)
2959 if (libpaths[i]->max_len > l)
2960 l = libpaths[i]->max_len;
2962 lib_buf = xmalloc (l + strlen(name) + 10);
2964 for (i = 0; libpaths[i]; i++)
2966 struct prefix_list *list = libpaths[i]->plist;
2967 for (; list; list = list->next)
2969 for (j = 0; libexts[j]; j++)
2971 /* The following lines are needed because path_prefix list
2972 may contain directories both with trailing '/' and
2973 without it. */
2974 const char *p = "";
2975 if (list->prefix[strlen(list->prefix)-1] != '/')
2976 p = "/";
2977 sprintf (lib_buf, "%s%slib%s.%s",
2978 list->prefix, p, name, libexts[j]);
2979 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
2980 if (file_exists (lib_buf))
2982 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
2983 return (lib_buf);
2988 if (debug)
2989 fprintf (stderr, "not found\n");
2990 else
2991 fatal ("Library lib%s not found", name);
2992 return (NULL);
2995 /* Array of standard AIX libraries which should not
2996 be scanned for ctors/dtors. */
2997 static const char *aix_std_libs[] = {
2998 "/unix",
2999 "/lib/libc.a",
3000 "/lib/libc_r.a",
3001 "/usr/lib/libc.a",
3002 "/usr/lib/libc_r.a",
3003 "/usr/lib/threads/libc.a",
3004 "/usr/ccs/lib/libc.a",
3005 "/usr/ccs/lib/libc_r.a",
3006 NULL
3009 /* This function checks the filename and returns 1
3010 if this name matches the location of a standard AIX library. */
3011 static int
3012 ignore_library (name)
3013 const char *name;
3015 const char **p = &aix_std_libs[0];
3016 while (*p++ != NULL)
3017 if (! strcmp (name, *p)) return 1;
3018 return 0;
3021 #endif
3023 #endif /* OBJECT_FORMAT_COFF */
3027 * OSF/rose specific stuff.
3030 #ifdef OBJECT_FORMAT_ROSE
3032 /* Union of the various load commands */
3034 typedef union load_union
3036 ldc_header_t hdr; /* common header */
3037 load_cmd_map_command_t map; /* map indexing other load cmds */
3038 interpreter_command_t iprtr; /* interpreter pathname */
3039 strings_command_t str; /* load commands strings section */
3040 region_command_t region; /* region load command */
3041 reloc_command_t reloc; /* relocation section */
3042 package_command_t pkg; /* package load command */
3043 symbols_command_t sym; /* symbol sections */
3044 entry_command_t ent; /* program start section */
3045 gen_info_command_t info; /* object information */
3046 func_table_command_t func; /* function constructors/destructors */
3047 } load_union_t;
3049 /* Structure to point to load command and data section in memory. */
3051 typedef struct load_all
3053 load_union_t *load; /* load command */
3054 char *section; /* pointer to section */
3055 } load_all_t;
3057 /* Structure to contain information about a file mapped into memory. */
3059 struct file_info
3061 char *start; /* start of map */
3062 char *name; /* filename */
3063 long size; /* size of the file */
3064 long rounded_size; /* size rounded to page boundary */
3065 int fd; /* file descriptor */
3066 int rw; /* != 0 if opened read/write */
3067 int use_mmap; /* != 0 if mmap'ed */
3070 extern int decode_mach_o_hdr ();
3071 extern int encode_mach_o_hdr ();
3073 static void add_func_table PROTO((mo_header_t *, load_all_t *,
3074 symbol_info_t *, int));
3075 static void print_header PROTO((mo_header_t *));
3076 static void print_load_command PROTO((load_union_t *, size_t, int));
3077 static void bad_header PROTO((int));
3078 static struct file_info *read_file PROTO((const char *, int, int));
3079 static void end_file PROTO((struct file_info *));
3081 /* OSF/rose specific version to scan the name list of the loaded
3082 program for the symbols g++ uses for static constructors and
3083 destructors.
3085 The constructor table begins at __CTOR_LIST__ and contains a count
3086 of the number of pointers (or -1 if the constructors are built in a
3087 separate section by the linker), followed by the pointers to the
3088 constructor functions, terminated with a null pointer. The
3089 destructor table has the same format, and begins at __DTOR_LIST__. */
3091 static void
3092 scan_prog_file (prog_name, which_pass)
3093 const char *prog_name;
3094 enum pass which_pass;
3096 char *obj;
3097 mo_header_t hdr;
3098 load_all_t *load_array;
3099 load_all_t *load_end;
3100 load_all_t *load_cmd;
3101 int symbol_load_cmds;
3102 off_t offset;
3103 int i;
3104 int num_syms;
3105 int status;
3106 char *str_sect;
3107 struct file_info *obj_file;
3108 int prog_fd;
3109 mo_lcid_t cmd_strings = -1;
3110 symbol_info_t *main_sym = 0;
3111 int rw = (which_pass != PASS_FIRST);
3113 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3114 if (prog_fd < 0)
3115 fatal_perror ("open %s", prog_name);
3117 obj_file = read_file (prog_name, prog_fd, rw);
3118 obj = obj_file->start;
3120 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3121 if (status != MO_HDR_CONV_SUCCESS)
3122 bad_header (status);
3125 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3126 since the hardware will automatically swap bytes for us on loading little endian
3127 integers. */
3129 #ifndef CROSS_COMPILE
3130 if (hdr.moh_magic != MOH_MAGIC_MSB
3131 || hdr.moh_header_version != MOH_HEADER_VERSION
3132 || hdr.moh_byte_order != OUR_BYTE_ORDER
3133 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3134 || hdr.moh_cpu_type != OUR_CPU_TYPE
3135 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3136 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3138 fatal ("incompatibilities between object file & expected values");
3140 #endif
3142 if (debug)
3143 print_header (&hdr);
3145 offset = hdr.moh_first_cmd_off;
3146 load_end = load_array
3147 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3149 /* Build array of load commands, calculating the offsets */
3150 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3152 load_union_t *load_hdr; /* load command header */
3154 load_cmd = load_end++;
3155 load_hdr = (load_union_t *) (obj + offset);
3157 /* If modifying the program file, copy the header. */
3158 if (rw)
3160 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3161 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
3162 load_hdr = ptr;
3164 /* null out old command map, because we will rewrite at the end. */
3165 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3167 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3168 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3172 load_cmd->load = load_hdr;
3173 if (load_hdr->hdr.ldci_section_off > 0)
3174 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3176 if (debug)
3177 print_load_command (load_hdr, offset, i);
3179 offset += load_hdr->hdr.ldci_cmd_size;
3182 /* If the last command is the load command map and is not undefined,
3183 decrement the count of load commands. */
3184 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3186 load_end--;
3187 hdr.moh_n_load_cmds--;
3190 /* Go through and process each symbol table section. */
3191 symbol_load_cmds = 0;
3192 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3194 load_union_t *load_hdr = load_cmd->load;
3196 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3198 symbol_load_cmds++;
3200 if (debug)
3202 const char *kind = "unknown";
3204 switch (load_hdr->sym.symc_kind)
3206 case SYMC_IMPORTS: kind = "imports"; break;
3207 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3208 case SYMC_STABS: kind = "stabs"; break;
3211 notice ("\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3212 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3215 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3216 continue;
3218 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3219 if (str_sect == (char *) 0)
3220 fatal ("string section missing");
3222 if (load_cmd->section == (char *) 0)
3223 fatal ("section pointer missing");
3225 num_syms = load_hdr->sym.symc_nentries;
3226 for (i = 0; i < num_syms; i++)
3228 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3229 char *name = sym->si_name.symbol_name + str_sect;
3231 if (name[0] != '_')
3232 continue;
3234 if (rw)
3236 char *n = name + strlen (name) - strlen (NAME__MAIN);
3238 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3239 continue;
3240 while (n != name)
3241 if (*--n != '_')
3242 continue;
3244 main_sym = sym;
3246 else
3248 switch (is_ctor_dtor (name))
3250 case 1:
3251 add_to_list (&constructors, name);
3252 break;
3254 case 2:
3255 add_to_list (&destructors, name);
3256 break;
3258 default: /* not a constructor or destructor */
3259 continue;
3263 if (debug)
3264 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3265 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3270 if (symbol_load_cmds == 0)
3271 fatal ("no symbol table found");
3273 /* Update the program file now, rewrite header and load commands. At present,
3274 we assume that there is enough space after the last load command to insert
3275 one more. Since the first section written out is page aligned, and the
3276 number of load commands is small, this is ok for the present. */
3278 if (rw)
3280 load_union_t *load_map;
3281 size_t size;
3283 if (cmd_strings == -1)
3284 fatal ("no cmd_strings found");
3286 /* Add __main to initializer list.
3287 If we are building a program instead of a shared library, do not
3288 do anything, since in the current version, you cannot do mallocs
3289 and such in the constructors. */
3291 if (main_sym != (symbol_info_t *) 0
3292 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3293 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3295 if (debug)
3296 notice ("\nUpdating header and load commands.\n\n");
3298 hdr.moh_n_load_cmds++;
3299 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3301 /* Create new load command map. */
3302 if (debug)
3303 notice ("load command map, %d cmds, new size %ld.\n",
3304 (int) hdr.moh_n_load_cmds, (long) size);
3306 load_map = (load_union_t *) xcalloc (1, size);
3307 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3308 load_map->map.ldc_header.ldci_cmd_size = size;
3309 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3310 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3311 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3313 offset = hdr.moh_first_cmd_off;
3314 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3316 load_map->map.lcm_map[i] = offset;
3317 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3318 hdr.moh_load_map_cmd_off = offset;
3320 offset += load_array[i].load->hdr.ldci_cmd_size;
3323 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3325 if (debug)
3326 print_header (&hdr);
3328 /* Write header */
3329 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3330 if (status != MO_HDR_CONV_SUCCESS)
3331 bad_header (status);
3333 if (debug)
3334 notice ("writing load commands.\n\n");
3336 /* Write load commands */
3337 offset = hdr.moh_first_cmd_off;
3338 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3340 load_union_t *load_hdr = load_array[i].load;
3341 size_t size = load_hdr->hdr.ldci_cmd_size;
3343 if (debug)
3344 print_load_command (load_hdr, offset, i);
3346 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3347 offset += size;
3351 end_file (obj_file);
3353 if (close (prog_fd))
3354 fatal_perror ("close %s", prog_name);
3356 if (debug)
3357 fprintf (stderr, "\n");
3361 /* Add a function table to the load commands to call a function
3362 on initiation or termination of the process. */
3364 static void
3365 add_func_table (hdr_p, load_array, sym, type)
3366 mo_header_t *hdr_p; /* pointer to global header */
3367 load_all_t *load_array; /* array of ptrs to load cmds */
3368 symbol_info_t *sym; /* pointer to symbol entry */
3369 int type; /* fntc_type value */
3371 /* Add a new load command. */
3372 int num_cmds = ++hdr_p->moh_n_load_cmds;
3373 int load_index = num_cmds - 1;
3374 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3375 load_union_t *ptr = xcalloc (1, size);
3376 load_all_t *load_cmd;
3377 int i;
3379 /* Set the unresolved address bit in the header to force the loader to be
3380 used, since kernel exec does not call the initialization functions. */
3381 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3383 load_cmd = &load_array[load_index];
3384 load_cmd->load = ptr;
3385 load_cmd->section = (char *) 0;
3387 /* Fill in func table load command. */
3388 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3389 ptr->func.ldc_header.ldci_cmd_size = size;
3390 ptr->func.ldc_header.ldci_section_off = 0;
3391 ptr->func.ldc_header.ldci_section_len = 0;
3392 ptr->func.fntc_type = type;
3393 ptr->func.fntc_nentries = 1;
3395 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3396 /* Is the symbol already expressed as (region, offset)? */
3397 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3399 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3400 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3403 /* If not, figure out which region it's in. */
3404 else
3406 mo_vm_addr_t addr = sym->si_value.abs_val;
3407 int found = 0;
3409 for (i = 0; i < load_index; i++)
3411 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3413 region_command_t *region_ptr = &load_array[i].load->region;
3415 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3416 && addr >= region_ptr->regc_addr.vm_addr
3417 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3419 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3420 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3421 found++;
3422 break;
3427 if (!found)
3428 fatal ("could not convert 0x%l.8x into a region", addr);
3431 if (debug)
3432 notice ("%s function, region %d, offset = %ld (0x%.8lx)\n",
3433 type == FNTC_INITIALIZATION ? "init" : "term",
3434 (int) ptr->func.fntc_entry_loc[i].adr_lcid,
3435 (long) ptr->func.fntc_entry_loc[i].adr_sctoff,
3436 (long) ptr->func.fntc_entry_loc[i].adr_sctoff);
3441 /* Print the global header for an OSF/rose object. */
3443 static void
3444 print_header (hdr_ptr)
3445 mo_header_t *hdr_ptr;
3447 fprintf (stderr, "\nglobal header:\n");
3448 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3449 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3450 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3451 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3452 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3453 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3454 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3455 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3456 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3457 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3458 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3459 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3460 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3461 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3462 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3464 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3465 fprintf (stderr, ", relocatable");
3467 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3468 fprintf (stderr, ", linkable");
3470 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3471 fprintf (stderr, ", execable");
3473 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3474 fprintf (stderr, ", executable");
3476 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3477 fprintf (stderr, ", unresolved");
3479 fprintf (stderr, "\n\n");
3480 return;
3484 /* Print a short summary of a load command. */
3486 static void
3487 print_load_command (load_hdr, offset, number)
3488 load_union_t *load_hdr;
3489 size_t offset;
3490 int number;
3492 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3493 const char *type_str = (char *) 0;
3495 switch (type)
3497 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3498 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3499 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3500 case LDC_STRINGS: type_str = "STRINGS"; break;
3501 case LDC_REGION: type_str = "REGION"; break;
3502 case LDC_RELOC: type_str = "RELOC"; break;
3503 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3504 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3505 case LDC_ENTRY: type_str = "ENTRY"; break;
3506 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3507 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3510 fprintf (stderr,
3511 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3512 number,
3513 (long) load_hdr->hdr.ldci_cmd_size,
3514 (long) offset,
3515 (long) load_hdr->hdr.ldci_section_off,
3516 (long) load_hdr->hdr.ldci_section_len);
3518 if (type_str == (char *) 0)
3519 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3521 else if (type != LDC_REGION)
3522 fprintf (stderr, ", ty: %s\n", type_str);
3524 else
3526 const char *region = "";
3527 switch (load_hdr->region.regc_usage_type)
3529 case REG_TEXT_T: region = ", .text"; break;
3530 case REG_DATA_T: region = ", .data"; break;
3531 case REG_BSS_T: region = ", .bss"; break;
3532 case REG_GLUE_T: region = ", .glue"; break;
3533 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3534 case REG_RDATA_T: region = ", .rdata"; break;
3535 case REG_SDATA_T: region = ", .sdata"; break;
3536 case REG_SBSS_T: region = ", .sbss"; break;
3537 #endif
3540 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3541 type_str,
3542 (long) load_hdr->region.regc_vm_addr,
3543 (long) load_hdr->region.regc_vm_size,
3544 region);
3547 return;
3551 /* Fatal error when {en,de}code_mach_o_header fails. */
3553 static void
3554 bad_header (status)
3555 int status;
3557 switch (status)
3559 case MO_ERROR_BAD_MAGIC: fatal ("bad magic number");
3560 case MO_ERROR_BAD_HDR_VERS: fatal ("bad header version");
3561 case MO_ERROR_BAD_RAW_HDR_VERS: fatal ("bad raw header version");
3562 case MO_ERROR_BUF2SML: fatal ("raw header buffer too small");
3563 case MO_ERROR_OLD_RAW_HDR_FILE: fatal ("old raw header file");
3564 case MO_ERROR_UNSUPPORTED_VERS: fatal ("unsupported version");
3565 default:
3566 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3571 /* Read a file into a memory buffer. */
3573 static struct file_info *
3574 read_file (name, fd, rw)
3575 const char *name; /* filename */
3576 int fd; /* file descriptor */
3577 int rw; /* read/write */
3579 struct stat stat_pkt;
3580 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3581 #ifdef USE_MMAP
3582 static int page_size;
3583 #endif
3585 if (fstat (fd, &stat_pkt) < 0)
3586 fatal_perror ("fstat %s", name);
3588 p->name = name;
3589 p->size = stat_pkt.st_size;
3590 p->rounded_size = stat_pkt.st_size;
3591 p->fd = fd;
3592 p->rw = rw;
3594 #ifdef USE_MMAP
3595 if (debug)
3596 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3598 if (page_size == 0)
3599 page_size = sysconf (_SC_PAGE_SIZE);
3601 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3602 p->start = mmap ((caddr_t) 0,
3603 (rw) ? p->rounded_size : p->size,
3604 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3605 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3607 0L);
3609 if (p->start != (char *) 0 && p->start != (char *) -1)
3610 p->use_mmap = 1;
3612 else
3613 #endif /* USE_MMAP */
3615 long len;
3617 if (debug)
3618 fprintf (stderr, "read %s\n", name);
3620 p->use_mmap = 0;
3621 p->start = xmalloc (p->size);
3622 if (lseek (fd, 0L, SEEK_SET) < 0)
3623 fatal_perror ("lseek %s 0", name);
3625 len = read (fd, p->start, p->size);
3626 if (len < 0)
3627 fatal_perror ("read %s", name);
3629 if (len != p->size)
3630 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3633 return p;
3636 /* Do anything necessary to write a file back from memory. */
3638 static void
3639 end_file (ptr)
3640 struct file_info *ptr; /* file information block */
3642 #ifdef USE_MMAP
3643 if (ptr->use_mmap)
3645 if (ptr->rw)
3647 if (debug)
3648 fprintf (stderr, "msync %s\n", ptr->name);
3650 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3651 fatal_perror ("msync %s", ptr->name);
3654 if (debug)
3655 fprintf (stderr, "munmap %s\n", ptr->name);
3657 if (munmap (ptr->start, ptr->size))
3658 fatal_perror ("munmap %s", ptr->name);
3660 else
3661 #endif /* USE_MMAP */
3663 if (ptr->rw)
3665 long len;
3667 if (debug)
3668 fprintf (stderr, "write %s\n", ptr->name);
3670 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3671 fatal_perror ("lseek %s 0", ptr->name);
3673 len = write (ptr->fd, ptr->start, ptr->size);
3674 if (len < 0)
3675 fatal_perror ("write %s", ptr->name);
3677 if (len != ptr->size)
3678 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3681 free (ptr->start);
3684 free (ptr);
3687 #endif /* OBJECT_FORMAT_ROSE */