H
[official-gcc.git] / gcc / collect2.c
blobbf494c04562a8164736200a5a19ce8da9b7317b8
1 /* Collect static initialization info into data structures that can be
2 traversed by C++ initialization and finalization routines.
3 Copyright (C) 1992, 93-97, 1998 Free Software Foundation, Inc.
4 Contributed by Chris Smith (csmith@convex.com).
5 Heavily modified by Michael Meissner (meissner@cygnus.com),
6 Per Bothner (bothner@cygnus.com), and John Gilmore (gnu@cygnus.com).
8 This file is part of GNU CC.
10 GNU CC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2, or (at your option)
13 any later version.
15 GNU CC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with GNU CC; see the file COPYING. If not, write to
22 the Free Software Foundation, 59 Temple Place - Suite 330,
23 Boston, MA 02111-1307, USA. */
26 /* Build tables of static constructors and destructors and run ld. */
28 #include "config.h"
29 #include "system.h"
30 #include <signal.h>
31 #include <sys/stat.h>
33 #define COLLECT
35 #include "demangle.h"
36 #include "obstack.h"
37 #include "gansidecl.h"
38 #ifdef __CYGWIN32__
39 #include <process.h>
40 #endif
42 /* Obstack allocation and deallocation routines. */
43 #define obstack_chunk_alloc xmalloc
44 #define obstack_chunk_free free
46 #ifdef USG
47 #define vfork fork
48 #endif
50 #ifndef WIFSIGNALED
51 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
52 #endif
53 #ifndef WTERMSIG
54 #define WTERMSIG(S) ((S) & 0x7f)
55 #endif
56 #ifndef WIFEXITED
57 #define WIFEXITED(S) (((S) & 0xff) == 0)
58 #endif
59 #ifndef WEXITSTATUS
60 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
61 #endif
63 extern char *make_temp_file PROTO ((char *));
65 /* On certain systems, we have code that works by scanning the object file
66 directly. But this code uses system-specific header files and library
67 functions, so turn it off in a cross-compiler. Likewise, the names of
68 the utilities are not correct for a cross-compiler; we have to hope that
69 cross-versions are in the proper directories. */
71 #ifdef CROSS_COMPILE
72 #undef SUNOS4_SHARED_LIBRARIES
73 #undef OBJECT_FORMAT_COFF
74 #undef OBJECT_FORMAT_ROSE
75 #undef MD_EXEC_PREFIX
76 #undef REAL_LD_FILE_NAME
77 #undef REAL_NM_FILE_NAME
78 #undef REAL_STRIP_FILE_NAME
79 #endif
81 /* If we cannot use a special method, use the ordinary one:
82 run nm to find what symbols are present.
83 In a cross-compiler, this means you need a cross nm,
84 but that is not quite as unpleasant as special headers. */
86 #if !defined (OBJECT_FORMAT_COFF) && !defined (OBJECT_FORMAT_ROSE)
87 #define OBJECT_FORMAT_NONE
88 #endif
90 #ifdef OBJECT_FORMAT_COFF
92 #include <a.out.h>
93 #include <ar.h>
95 #ifdef UMAX
96 #include <sgs.h>
97 #endif
99 /* Many versions of ldfcn.h define these. */
100 #ifdef FREAD
101 #undef FREAD
102 #undef FWRITE
103 #endif
105 #include <ldfcn.h>
107 /* Some systems have an ISCOFF macro, but others do not. In some cases
108 the macro may be wrong. MY_ISCOFF is defined in tm.h files for machines
109 that either do not have an ISCOFF macro in /usr/include or for those
110 where it is wrong. */
112 #ifndef MY_ISCOFF
113 #define MY_ISCOFF(X) ISCOFF (X)
114 #endif
116 #endif /* OBJECT_FORMAT_COFF */
118 #ifdef OBJECT_FORMAT_ROSE
120 #ifdef _OSF_SOURCE
121 #define USE_MMAP
122 #endif
124 #ifdef USE_MMAP
125 #include <sys/mman.h>
126 #endif
128 #include <unistd.h>
129 #include <mach_o_format.h>
130 #include <mach_o_header.h>
131 #include <mach_o_vals.h>
132 #include <mach_o_types.h>
134 #endif /* OBJECT_FORMAT_ROSE */
136 #ifdef OBJECT_FORMAT_NONE
138 /* Default flags to pass to nm. */
139 #ifndef NM_FLAGS
140 #define NM_FLAGS "-n"
141 #endif
143 #endif /* OBJECT_FORMAT_NONE */
145 /* Some systems use __main in a way incompatible with its use in gcc, in these
146 cases use the macros NAME__MAIN to give a quoted symbol and SYMBOL__MAIN to
147 give the same symbol without quotes for an alternative entry point. You
148 must define both, or neither. */
149 #ifndef NAME__MAIN
150 #define NAME__MAIN "__main"
151 #define SYMBOL__MAIN __main
152 #endif
154 /* This must match tree.h. */
155 #define DEFAULT_INIT_PRIORITY 65535
157 #if defined (LDD_SUFFIX) || SUNOS4_SHARED_LIBRARIES
158 #define SCAN_LIBRARIES
159 #endif
161 #ifdef USE_COLLECT2
162 int do_collecting = 1;
163 #else
164 int do_collecting = 0;
165 #endif
167 /* Linked lists of constructor and destructor names. */
169 struct id
171 struct id *next;
172 int sequence;
173 char name[1];
176 struct head
178 struct id *first;
179 struct id *last;
180 int number;
183 /* Enumeration giving which pass this is for scanning the program file. */
185 enum pass {
186 PASS_FIRST, /* without constructors */
187 PASS_OBJ, /* individual objects */
188 PASS_LIB, /* looking for shared libraries */
189 PASS_SECOND /* with constructors linked in */
192 extern char *version_string;
194 int vflag; /* true if -v */
195 static int rflag; /* true if -r */
196 static int strip_flag; /* true if -s */
197 #ifdef COLLECT_EXPORT_LIST
198 static int export_flag; /* true if -bE */
199 #endif
201 int debug; /* true if -debug */
203 static int shared_obj; /* true if -shared */
205 static char *c_file; /* <xxx>.c for constructor/destructor list. */
206 static char *o_file; /* <xxx>.o for constructor/destructor list. */
207 #ifdef COLLECT_EXPORT_LIST
208 static char *export_file; /* <xxx>.x for AIX export list. */
209 static char *import_file; /* <xxx>.p for AIX import list. */
210 #endif
211 char *ldout; /* File for ld errors. */
212 static char *output_file; /* Output file for ld. */
213 static char *nm_file_name; /* pathname of nm */
214 #ifdef LDD_SUFFIX
215 static char *ldd_file_name; /* pathname of ldd (or equivalent) */
216 #endif
217 static char *strip_file_name; /* pathname of strip */
218 char *c_file_name; /* pathname of gcc */
219 static char *initname, *fininame; /* names of init and fini funcs */
221 static struct head constructors; /* list of constructors found */
222 static struct head destructors; /* list of destructors found */
223 #ifdef COLLECT_EXPORT_LIST
224 static struct head exports; /* list of exported symbols */
225 static struct head imports; /* list of imported symbols */
226 static struct head undefined; /* list of undefined symbols */
227 #endif
228 static struct head frame_tables; /* list of frame unwind info tables */
230 struct obstack temporary_obstack;
231 struct obstack permanent_obstack;
232 char * temporary_firstobj;
234 /* Defined in the automatically-generated underscore.c. */
235 extern int prepends_underscore;
237 extern FILE *fdopen ();
239 #ifndef GET_ENV_PATH_LIST
240 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
241 #endif
243 /* Structure to hold all the directories in which to search for files to
244 execute. */
246 struct prefix_list
248 char *prefix; /* String to prepend to the path. */
249 struct prefix_list *next; /* Next in linked list. */
252 struct path_prefix
254 struct prefix_list *plist; /* List of prefixes to try */
255 int max_len; /* Max length of a prefix in PLIST */
256 char *name; /* Name of this list (used in config stuff) */
259 #ifdef COLLECT_EXPORT_LIST
260 /* Lists to keep libraries to be scanned for global constructors/destructors. */
261 static struct head libs; /* list of libraries */
262 static struct path_prefix cmdline_lib_dirs; /* directories specified with -L */
263 static struct path_prefix libpath_lib_dirs; /* directories in LIBPATH */
264 static struct path_prefix *libpaths[3] = {&cmdline_lib_dirs,
265 &libpath_lib_dirs, NULL};
266 static char *libexts[3] = {"a", "so", NULL}; /* possible library extentions */
267 #endif
269 void error PVPROTO((const char *, ...)) ATTRIBUTE_PRINTF_1;
270 void fatal PVPROTO((const char *, ...))
271 ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
272 void fatal_perror PVPROTO((const char *, ...))
273 ATTRIBUTE_PRINTF_1 ATTRIBUTE_NORETURN;
274 static char *my_strerror PROTO((int));
275 static const char *my_strsignal PROTO((int));
276 static void handler PROTO((int));
277 static int is_ctor_dtor PROTO((char *));
278 static char *find_a_file PROTO((struct path_prefix *, char *));
279 static void add_prefix PROTO((struct path_prefix *, char *));
280 static void prefix_from_env PROTO((char *, struct path_prefix *));
281 static void prefix_from_string PROTO((char *, struct path_prefix *));
282 static void do_wait PROTO((char *));
283 static void fork_execute PROTO((char *, char **));
284 static void maybe_unlink PROTO((char *));
285 static void add_to_list PROTO((struct head *, char *));
286 static int extract_init_priority PROTO((char *));
287 static void sort_ids PROTO((struct head *));
288 static void write_list PROTO((FILE *, char *, struct id *));
289 #ifdef COLLECT_EXPORT_LIST
290 static void dump_list PROTO((FILE *, char *, struct id *));
291 #endif
292 #if 0
293 static void dump_prefix_list PROTO((FILE *, char *, struct prefix_list *));
294 #endif
295 static void write_list_with_asm PROTO((FILE *, char *, struct id *));
296 static void write_c_file PROTO((FILE *, char *));
297 static void scan_prog_file PROTO((char *, enum pass));
298 #ifdef SCAN_LIBRARIES
299 static void scan_libraries PROTO((char *));
300 #endif
301 #ifdef COLLECT_EXPORT_LIST
302 static int is_in_list PROTO((char *, struct id *));
303 static void write_export_file PROTO((FILE *));
304 static void write_import_file PROTO((FILE *));
305 static char *resolve_lib_name PROTO((char *));
306 static int use_import_list PROTO((char *));
307 static int ignore_library PROTO((char *));
308 #endif
310 char *xcalloc ();
311 char *xmalloc ();
314 #ifdef NO_DUP2
316 dup2 (oldfd, newfd)
317 int oldfd;
318 int newfd;
320 int fdtmp[256];
321 int fdx = 0;
322 int fd;
324 if (oldfd == newfd)
325 return oldfd;
326 close (newfd);
327 while ((fd = dup (oldfd)) != newfd && fd >= 0) /* good enough for low fd's */
328 fdtmp[fdx++] = fd;
329 while (fdx > 0)
330 close (fdtmp[--fdx]);
332 return fd;
334 #endif
336 static char *
337 my_strerror (e)
338 int e;
341 #ifdef HAVE_STRERROR
342 return strerror (e);
344 #else
346 static char buffer[30];
347 if (!e)
348 return "";
350 if (e > 0 && e < sys_nerr)
351 return sys_errlist[e];
353 sprintf (buffer, "Unknown error %d", e);
354 return buffer;
355 #endif
358 static const char *
359 my_strsignal (s)
360 int s;
362 #ifdef HAVE_STRSIGNAL
363 return strsignal (s);
364 #else
365 if (s >= 0 && s < NSIG)
367 # ifdef NO_SYS_SIGLIST
368 static char buffer[30];
370 sprintf (buffer, "Unknown signal %d", s);
371 return buffer;
372 # else
373 return sys_siglist[s];
374 # endif
376 else
377 return NULL;
378 #endif /* HAVE_STRSIGNAL */
381 /* Delete tempfiles and exit function. */
383 void
384 collect_exit (status)
385 int status;
387 if (c_file != 0 && c_file[0])
388 maybe_unlink (c_file);
390 if (o_file != 0 && o_file[0])
391 maybe_unlink (o_file);
393 #ifdef COLLECT_EXPORT_LIST
394 if (export_file != 0 && export_file[0])
395 maybe_unlink (export_file);
397 if (import_file != 0 && import_file[0])
398 maybe_unlink (import_file);
399 #endif
401 if (ldout != 0 && ldout[0])
403 dump_file (ldout);
404 maybe_unlink (ldout);
407 if (status != 0 && output_file != 0 && output_file[0])
408 maybe_unlink (output_file);
410 exit (status);
414 /* Die when sys call fails. */
416 void
417 fatal_perror VPROTO((const char * string, ...))
419 #ifndef __STDC__
420 const char *string;
421 #endif
422 int e = errno;
423 va_list ap;
425 VA_START (ap, string);
427 #ifndef __STDC__
428 string = va_arg (ap, const char *);
429 #endif
431 fprintf (stderr, "collect2: ");
432 vfprintf (stderr, string, ap);
433 fprintf (stderr, ": %s\n", my_strerror (e));
434 va_end (ap);
436 collect_exit (FATAL_EXIT_CODE);
439 /* Just die. */
441 void
442 fatal VPROTO((const char * string, ...))
444 #ifndef __STDC__
445 const char *string;
446 #endif
447 va_list ap;
449 VA_START (ap, string);
451 #ifndef __STDC__
452 string = va_arg (ap, const char *);
453 #endif
455 fprintf (stderr, "collect2: ");
456 vfprintf (stderr, string, ap);
457 fprintf (stderr, "\n");
458 va_end (ap);
460 collect_exit (FATAL_EXIT_CODE);
463 /* Write error message. */
465 void
466 error VPROTO((const char * string, ...))
468 #ifndef __STDC__
469 const char * string;
470 #endif
471 va_list ap;
473 VA_START (ap, string);
475 #ifndef __STDC__
476 string = va_arg (ap, const char *);
477 #endif
479 fprintf (stderr, "collect2: ");
480 vfprintf (stderr, string, ap);
481 fprintf (stderr, "\n");
482 va_end(ap);
485 /* In case obstack is linked in, and abort is defined to fancy_abort,
486 provide a default entry. */
488 void
489 fancy_abort ()
491 fatal ("internal error");
495 static void
496 handler (signo)
497 int signo;
499 if (c_file != 0 && c_file[0])
500 maybe_unlink (c_file);
502 if (o_file != 0 && o_file[0])
503 maybe_unlink (o_file);
505 if (ldout != 0 && ldout[0])
506 maybe_unlink (ldout);
508 #ifdef COLLECT_EXPORT_LIST
509 if (export_file != 0 && export_file[0])
510 maybe_unlink (export_file);
512 if (import_file != 0 && import_file[0])
513 maybe_unlink (import_file);
514 #endif
516 signal (signo, SIG_DFL);
517 kill (getpid (), signo);
521 char *
522 xcalloc (size1, size2)
523 int size1, size2;
525 char *ptr = (char *) calloc (size1, size2);
526 if (ptr)
527 return ptr;
529 fatal ("out of memory");
530 return (char *) 0;
533 char *
534 xmalloc (size)
535 unsigned size;
537 char *ptr = (char *) malloc (size);
538 if (ptr)
539 return ptr;
541 fatal ("out of memory");
542 return (char *) 0;
545 char *
546 xrealloc (ptr, size)
547 char *ptr;
548 unsigned size;
550 register char *value = (char *) realloc (ptr, size);
551 if (value == 0)
552 fatal ("virtual memory exhausted");
553 return value;
557 file_exists (name)
558 char *name;
560 return access (name, R_OK) == 0;
563 /* Make a copy of a string INPUT with size SIZE. */
565 char *
566 savestring (input, size)
567 char *input;
568 int size;
570 char *output = (char *) xmalloc (size + 1);
571 bcopy (input, output, size);
572 output[size] = 0;
573 return output;
576 /* Parse a reasonable subset of shell quoting syntax. */
578 static char *
579 extract_string (pp)
580 char **pp;
582 char *p = *pp;
583 int backquote = 0;
584 int inside = 0;
586 for (;;)
588 char c = *p;
589 if (c == '\0')
590 break;
591 ++p;
592 if (backquote)
593 obstack_1grow (&temporary_obstack, c);
594 else if (! inside && c == ' ')
595 break;
596 else if (! inside && c == '\\')
597 backquote = 1;
598 else if (c == '\'')
599 inside = !inside;
600 else
601 obstack_1grow (&temporary_obstack, c);
604 obstack_1grow (&temporary_obstack, '\0');
605 *pp = p;
606 return obstack_finish (&temporary_obstack);
609 void
610 dump_file (name)
611 char *name;
613 FILE *stream = fopen (name, "r");
614 int no_demangle = !! getenv ("COLLECT_NO_DEMANGLE");
616 if (stream == 0)
617 return;
618 while (1)
620 int c;
621 while (c = getc (stream),
622 c != EOF && (ISALNUM (c) || c == '_' || c == '$' || c == '.'))
623 obstack_1grow (&temporary_obstack, c);
624 if (obstack_object_size (&temporary_obstack) > 0)
626 char *word, *p, *result;
627 obstack_1grow (&temporary_obstack, '\0');
628 word = obstack_finish (&temporary_obstack);
630 if (*word == '.')
631 ++word, putc ('.', stderr);
632 p = word;
633 if (*p == '_' && prepends_underscore)
634 ++p;
636 if (no_demangle)
637 result = 0;
638 else
639 result = cplus_demangle (p, DMGL_PARAMS | DMGL_ANSI);
641 if (result)
643 int diff;
644 fputs (result, stderr);
646 diff = strlen (word) - strlen (result);
647 while (diff > 0)
648 --diff, putc (' ', stderr);
649 while (diff < 0 && c == ' ')
650 ++diff, c = getc (stream);
652 free (result);
654 else
655 fputs (word, stderr);
657 fflush (stderr);
658 obstack_free (&temporary_obstack, temporary_firstobj);
660 if (c == EOF)
661 break;
662 putc (c, stderr);
664 fclose (stream);
667 /* Decide whether the given symbol is:
668 a constructor (1), a destructor (2), or neither (0). */
670 static int
671 is_ctor_dtor (s)
672 char *s;
674 struct names { char *name; int len; int ret; int two_underscores; };
676 register struct names *p;
677 register int ch;
678 register char *orig_s = s;
680 static struct names special[] = {
681 #ifdef NO_DOLLAR_IN_LABEL
682 #ifdef NO_DOT_IN_LABEL
683 { "GLOBAL__I_", sizeof ("GLOBAL__I_")-1, 1, 0 },
684 { "GLOBAL__D_", sizeof ("GLOBAL__D_")-1, 2, 0 },
685 { "GLOBAL__F_", sizeof ("GLOBAL__F_")-1, 5, 0 },
686 #else
687 { "GLOBAL_.I.", sizeof ("GLOBAL_.I.")-1, 1, 0 },
688 { "GLOBAL_.D.", sizeof ("GLOBAL_.D.")-1, 2, 0 },
689 { "GLOBAL_.F.", sizeof ("GLOBAL_.F.")-1, 5, 0 },
690 #endif
691 #else
692 { "GLOBAL_$I$", sizeof ("GLOBAL_$I$")-1, 1, 0 },
693 { "GLOBAL_$D$", sizeof ("GLOBAL_$D$")-1, 2, 0 },
694 { "GLOBAL_$F$", sizeof ("GLOBAL_$F$")-1, 5, 0 },
695 #endif
696 { "GLOBAL__FI_", sizeof ("GLOBAL__FI_")-1, 3, 0 },
697 { "GLOBAL__FD_", sizeof ("GLOBAL__FD_")-1, 4, 0 },
698 #ifdef CFRONT_LOSSAGE /* Do not collect cfront initialization functions.
699 cfront has its own linker procedure to collect them;
700 if collect2 gets them too, they get collected twice
701 when the cfront procedure is run and the compiler used
702 for linking happens to be GCC. */
703 { "sti__", sizeof ("sti__")-1, 1, 1 },
704 { "std__", sizeof ("std__")-1, 2, 1 },
705 #endif /* CFRONT_LOSSAGE */
706 { NULL, 0, 0, 0 }
709 while ((ch = *s) == '_')
710 ++s;
712 if (s == orig_s)
713 return 0;
715 for (p = &special[0]; p->len > 0; p++)
717 if (ch == p->name[0]
718 && (!p->two_underscores || ((s - orig_s) >= 2))
719 && strncmp(s, p->name, p->len) == 0)
721 return p->ret;
724 return 0;
727 /* Routine to add variables to the environment. */
729 #ifndef HAVE_PUTENV
732 putenv (str)
733 char *str;
735 #ifndef VMS /* nor about VMS */
737 extern char **environ;
738 char **old_environ = environ;
739 char **envp;
740 int num_envs = 0;
741 int name_len = 1;
742 char *p = str;
743 int ch;
745 while ((ch = *p++) != '\0' && ch != '=')
746 name_len++;
748 if (!ch)
749 abort ();
751 /* Search for replacing an existing environment variable, and
752 count the number of total environment variables. */
753 for (envp = old_environ; *envp; envp++)
755 num_envs++;
756 if (!strncmp (str, *envp, name_len))
758 *envp = str;
759 return 0;
763 /* Add a new environment variable */
764 environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
765 *environ = str;
766 bcopy ((char *) old_environ, (char *) (environ + 1),
767 sizeof (char *) * (num_envs+1));
769 return 0;
770 #endif /* VMS */
773 #endif /* HAVE_PUTENV */
775 /* By default, colon separates directories in a path. */
776 #ifndef PATH_SEPARATOR
777 #define PATH_SEPARATOR ':'
778 #endif
780 /* We maintain two prefix lists: one from COMPILER_PATH environment variable
781 and one from the PATH variable. */
783 static struct path_prefix cpath, path;
785 #ifdef CROSS_COMPILE
786 /* This is the name of the target machine. We use it to form the name
787 of the files to execute. */
789 static char *target_machine = TARGET_MACHINE;
790 #endif
792 /* Search for NAME using prefix list PPREFIX. We only look for executable
793 files.
795 Return 0 if not found, otherwise return its name, allocated with malloc. */
797 static char *
798 find_a_file (pprefix, name)
799 struct path_prefix *pprefix;
800 char *name;
802 char *temp;
803 struct prefix_list *pl;
804 int len = pprefix->max_len + strlen (name) + 1;
806 if (debug)
807 fprintf (stderr, "Looking for '%s'\n", name);
809 #ifdef EXECUTABLE_SUFFIX
810 len += strlen (EXECUTABLE_SUFFIX);
811 #endif
813 temp = xmalloc (len);
815 /* Determine the filename to execute (special case for absolute paths). */
817 if (*name == '/'
818 #ifdef DIR_SEPARATOR
819 || (DIR_SEPARATOR == '\\' && name[1] == ':'
820 && (name[2] == DIR_SEPARATOR || name[2] == '/'))
821 #endif
824 if (access (name, X_OK) == 0)
826 strcpy (temp, name);
828 if (debug)
829 fprintf (stderr, " - found: absolute path\n");
831 return temp;
834 if (debug)
835 fprintf (stderr, " - failed to locate using absolute path\n");
837 else
838 for (pl = pprefix->plist; pl; pl = pl->next)
840 strcpy (temp, pl->prefix);
841 strcat (temp, name);
843 if (access (temp, X_OK) == 0)
844 return temp;
846 #ifdef EXECUTABLE_SUFFIX
847 /* Some systems have a suffix for executable files.
848 So try appending that. */
849 strcat (temp, EXECUTABLE_SUFFIX);
851 if (access (temp, X_OK) == 0)
852 return temp;
853 #endif
856 if (debug && pprefix->plist == NULL)
857 fprintf (stderr, " - failed: no entries in prefix list\n");
859 free (temp);
860 return 0;
863 /* Add an entry for PREFIX to prefix list PPREFIX. */
865 static void
866 add_prefix (pprefix, prefix)
867 struct path_prefix *pprefix;
868 char *prefix;
870 struct prefix_list *pl, **prev;
871 int len;
873 if (pprefix->plist)
875 for (pl = pprefix->plist; pl->next; pl = pl->next)
877 prev = &pl->next;
879 else
880 prev = &pprefix->plist;
882 /* Keep track of the longest prefix */
884 len = strlen (prefix);
885 if (len > pprefix->max_len)
886 pprefix->max_len = len;
888 pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
889 pl->prefix = savestring (prefix, len);
891 if (*prev)
892 pl->next = *prev;
893 else
894 pl->next = (struct prefix_list *) 0;
895 *prev = pl;
898 /* Take the value of the environment variable ENV, break it into a path, and
899 add of the entries to PPREFIX. */
901 static void
902 prefix_from_env (env, pprefix)
903 char *env;
904 struct path_prefix *pprefix;
906 char *p;
907 GET_ENV_PATH_LIST (p, env);
909 if (p)
910 prefix_from_string (p, pprefix);
913 static void
914 prefix_from_string (p, pprefix)
915 char *p;
916 struct path_prefix *pprefix;
918 char *startp, *endp;
919 char *nstore = (char *) xmalloc (strlen (p) + 3);
921 if (debug)
922 fprintf (stderr, "Convert string '%s' into prefixes, separator = '%c'\n", p, PATH_SEPARATOR);
924 startp = endp = p;
925 while (1)
927 if (*endp == PATH_SEPARATOR || *endp == 0)
929 strncpy (nstore, startp, endp-startp);
930 if (endp == startp)
932 strcpy (nstore, "./");
934 else if (endp[-1] != '/')
936 nstore[endp-startp] = '/';
937 nstore[endp-startp+1] = 0;
939 else
940 nstore[endp-startp] = 0;
942 if (debug)
943 fprintf (stderr, " - add prefix: %s\n", nstore);
945 add_prefix (pprefix, nstore);
946 if (*endp == 0)
947 break;
948 endp = startp = endp + 1;
950 else
951 endp++;
955 /* Main program. */
958 main (argc, argv)
959 int argc;
960 char *argv[];
962 char *ld_suffix = "ld";
963 char *full_ld_suffix = ld_suffix;
964 char *real_ld_suffix = "real-ld";
965 char *collect_ld_suffix = "collect-ld";
966 char *nm_suffix = "nm";
967 char *full_nm_suffix = nm_suffix;
968 char *gnm_suffix = "gnm";
969 char *full_gnm_suffix = gnm_suffix;
970 #ifdef LDD_SUFFIX
971 char *ldd_suffix = LDD_SUFFIX;
972 char *full_ldd_suffix = ldd_suffix;
973 #endif
974 char *strip_suffix = "strip";
975 char *full_strip_suffix = strip_suffix;
976 char *gstrip_suffix = "gstrip";
977 char *full_gstrip_suffix = gstrip_suffix;
978 char *arg;
979 FILE *outf;
980 #ifdef COLLECT_EXPORT_LIST
981 FILE *exportf;
982 FILE *importf;
983 #endif
984 char *ld_file_name;
985 char *p;
986 char **c_argv;
987 char **c_ptr;
988 char **ld1_argv = (char **) xcalloc (sizeof (char *), argc+3);
989 char **ld1 = ld1_argv;
990 char **ld2_argv = (char **) xcalloc (sizeof (char *), argc+6);
991 char **ld2 = ld2_argv;
992 char **object_lst = (char **) xcalloc (sizeof (char *), argc);
993 char **object = object_lst;
994 int first_file;
995 int num_c_args = argc+9;
997 #ifdef DEBUG
998 debug = 1;
999 #endif
1001 /* Parse command line early for instances of -debug. This allows
1002 the debug flag to be set before functions like find_a_file()
1003 are called. */
1005 int i;
1007 for (i = 1; argv[i] != NULL; i ++)
1008 if (! strcmp (argv[i], "-debug"))
1009 debug = 1;
1010 vflag = debug;
1013 #ifndef DEFAULT_A_OUT_NAME
1014 output_file = "a.out";
1015 #else
1016 output_file = DEFAULT_A_OUT_NAME;
1017 #endif
1019 obstack_begin (&temporary_obstack, 0);
1020 obstack_begin (&permanent_obstack, 0);
1021 temporary_firstobj = (char *) obstack_alloc (&temporary_obstack, 0);
1023 current_demangling_style = gnu_demangling;
1024 p = getenv ("COLLECT_GCC_OPTIONS");
1025 while (p && *p)
1027 char *q = extract_string (&p);
1028 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1029 num_c_args++;
1031 obstack_free (&temporary_obstack, temporary_firstobj);
1032 ++num_c_args;
1034 c_ptr = c_argv = (char **) xcalloc (sizeof (char *), num_c_args);
1036 if (argc < 2)
1037 fatal ("no arguments");
1039 #ifdef SIGQUIT
1040 if (signal (SIGQUIT, SIG_IGN) != SIG_IGN)
1041 signal (SIGQUIT, handler);
1042 #endif
1043 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1044 signal (SIGINT, handler);
1045 #ifdef SIGALRM
1046 if (signal (SIGALRM, SIG_IGN) != SIG_IGN)
1047 signal (SIGALRM, handler);
1048 #endif
1049 #ifdef SIGHUP
1050 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1051 signal (SIGHUP, handler);
1052 #endif
1053 if (signal (SIGSEGV, SIG_IGN) != SIG_IGN)
1054 signal (SIGSEGV, handler);
1055 #ifdef SIGBUS
1056 if (signal (SIGBUS, SIG_IGN) != SIG_IGN)
1057 signal (SIGBUS, handler);
1058 #endif
1060 /* Extract COMPILER_PATH and PATH into our prefix list. */
1061 prefix_from_env ("COMPILER_PATH", &cpath);
1062 prefix_from_env ("PATH", &path);
1064 #ifdef CROSS_COMPILE
1065 /* If we look for a program in the compiler directories, we just use
1066 the short name, since these directories are already system-specific.
1067 But it we look for a program in the system directories, we need to
1068 qualify the program name with the target machine. */
1070 full_ld_suffix
1071 = xcalloc (strlen (ld_suffix) + strlen (target_machine) + 2, 1);
1072 strcpy (full_ld_suffix, target_machine);
1073 strcat (full_ld_suffix, "-");
1074 strcat (full_ld_suffix, ld_suffix);
1076 #if 0
1077 full_gld_suffix
1078 = xcalloc (strlen (gld_suffix) + strlen (target_machine) + 2, 1);
1079 strcpy (full_gld_suffix, target_machine);
1080 strcat (full_gld_suffix, "-");
1081 strcat (full_gld_suffix, gld_suffix);
1082 #endif
1084 full_nm_suffix
1085 = xcalloc (strlen (nm_suffix) + strlen (target_machine) + 2, 1);
1086 strcpy (full_nm_suffix, target_machine);
1087 strcat (full_nm_suffix, "-");
1088 strcat (full_nm_suffix, nm_suffix);
1090 full_gnm_suffix
1091 = xcalloc (strlen (gnm_suffix) + strlen (target_machine) + 2, 1);
1092 strcpy (full_gnm_suffix, target_machine);
1093 strcat (full_gnm_suffix, "-");
1094 strcat (full_gnm_suffix, gnm_suffix);
1096 #ifdef LDD_SUFFIX
1097 full_ldd_suffix
1098 = xcalloc (strlen (ldd_suffix) + strlen (target_machine) + 2, 1);
1099 strcpy (full_ldd_suffix, target_machine);
1100 strcat (full_ldd_suffix, "-");
1101 strcat (full_ldd_suffix, ldd_suffix);
1102 #endif
1104 full_strip_suffix
1105 = xcalloc (strlen (strip_suffix) + strlen (target_machine) + 2, 1);
1106 strcpy (full_strip_suffix, target_machine);
1107 strcat (full_strip_suffix, "-");
1108 strcat (full_strip_suffix, strip_suffix);
1110 full_gstrip_suffix
1111 = xcalloc (strlen (gstrip_suffix) + strlen (target_machine) + 2, 1);
1112 strcpy (full_gstrip_suffix, target_machine);
1113 strcat (full_gstrip_suffix, "-");
1114 strcat (full_gstrip_suffix, gstrip_suffix);
1115 #endif /* CROSS_COMPILE */
1117 /* Try to discover a valid linker/nm/strip to use. */
1119 /* Maybe we know the right file to use (if not cross). */
1120 ld_file_name = 0;
1121 #ifdef DEFAULT_LINKER
1122 if (access (DEFAULT_LINKER, X_OK) == 0)
1123 ld_file_name = DEFAULT_LINKER;
1124 if (ld_file_name == 0)
1125 #endif
1126 #ifdef REAL_LD_FILE_NAME
1127 ld_file_name = find_a_file (&path, REAL_LD_FILE_NAME);
1128 if (ld_file_name == 0)
1129 #endif
1130 /* Search the (target-specific) compiler dirs for ld'. */
1131 ld_file_name = find_a_file (&cpath, real_ld_suffix);
1132 /* Likewise for `collect-ld'. */
1133 if (ld_file_name == 0)
1134 ld_file_name = find_a_file (&cpath, collect_ld_suffix);
1135 /* Search the compiler directories for `ld'. We have protection against
1136 recursive calls in find_a_file. */
1137 if (ld_file_name == 0)
1138 ld_file_name = find_a_file (&cpath, ld_suffix);
1139 /* Search the ordinary system bin directories
1140 for `ld' (if native linking) or `TARGET-ld' (if cross). */
1141 if (ld_file_name == 0)
1142 ld_file_name = find_a_file (&path, full_ld_suffix);
1144 #ifdef REAL_NM_FILE_NAME
1145 nm_file_name = find_a_file (&path, REAL_NM_FILE_NAME);
1146 if (nm_file_name == 0)
1147 #endif
1148 nm_file_name = find_a_file (&cpath, gnm_suffix);
1149 if (nm_file_name == 0)
1150 nm_file_name = find_a_file (&path, full_gnm_suffix);
1151 if (nm_file_name == 0)
1152 nm_file_name = find_a_file (&cpath, nm_suffix);
1153 if (nm_file_name == 0)
1154 nm_file_name = find_a_file (&path, full_nm_suffix);
1156 #ifdef LDD_SUFFIX
1157 ldd_file_name = find_a_file (&cpath, ldd_suffix);
1158 if (ldd_file_name == 0)
1159 ldd_file_name = find_a_file (&path, full_ldd_suffix);
1160 #endif
1162 #ifdef REAL_STRIP_FILE_NAME
1163 strip_file_name = find_a_file (&path, REAL_STRIP_FILE_NAME);
1164 if (strip_file_name == 0)
1165 #endif
1166 strip_file_name = find_a_file (&cpath, gstrip_suffix);
1167 if (strip_file_name == 0)
1168 strip_file_name = find_a_file (&path, full_gstrip_suffix);
1169 if (strip_file_name == 0)
1170 strip_file_name = find_a_file (&cpath, strip_suffix);
1171 if (strip_file_name == 0)
1172 strip_file_name = find_a_file (&path, full_strip_suffix);
1174 /* Determine the full path name of the C compiler to use. */
1175 c_file_name = getenv ("COLLECT_GCC");
1176 if (c_file_name == 0)
1178 #ifdef CROSS_COMPILE
1179 c_file_name = xcalloc (sizeof ("gcc-") + strlen (target_machine) + 1, 1);
1180 strcpy (c_file_name, target_machine);
1181 strcat (c_file_name, "-gcc");
1182 #else
1183 c_file_name = "gcc";
1184 #endif
1187 p = find_a_file (&cpath, c_file_name);
1189 /* Here it should be safe to use the system search path since we should have
1190 already qualified the name of the compiler when it is needed. */
1191 if (p == 0)
1192 p = find_a_file (&path, c_file_name);
1194 if (p)
1195 c_file_name = p;
1197 *ld1++ = *ld2++ = ld_file_name;
1199 /* Make temp file names. */
1200 c_file = make_temp_file (".c");
1201 o_file = make_temp_file (".o");
1202 #ifdef COLLECT_EXPORT_LIST
1203 export_file = make_temp_file (".x");
1204 import_file = make_temp_file (".p");
1205 #endif
1206 ldout = make_temp_file (".ld");
1207 *c_ptr++ = c_file_name;
1208 *c_ptr++ = "-x";
1209 *c_ptr++ = "c";
1210 *c_ptr++ = "-c";
1211 *c_ptr++ = "-o";
1212 *c_ptr++ = o_file;
1214 #ifdef COLLECT_EXPORT_LIST
1215 /* Generate a list of directories from LIBPATH. */
1216 prefix_from_env ("LIBPATH", &libpath_lib_dirs);
1217 /* Add to this list also two standard directories where
1218 AIX loader always searches for libraries. */
1219 add_prefix (&libpath_lib_dirs, "/lib");
1220 add_prefix (&libpath_lib_dirs, "/usr/lib");
1221 #endif
1223 /* Get any options that the upper GCC wants to pass to the sub-GCC.
1225 AIX support needs to know if -shared has been specified before
1226 parsing commandline arguments. */
1228 p = getenv ("COLLECT_GCC_OPTIONS");
1229 while (p && *p)
1231 char *q = extract_string (&p);
1232 if (*q == '-' && (q[1] == 'm' || q[1] == 'f'))
1233 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1234 if (strcmp (q, "-EL") == 0 || strcmp (q, "-EB") == 0)
1235 *c_ptr++ = obstack_copy0 (&permanent_obstack, q, strlen (q));
1236 if (strncmp (q, "-shared", sizeof ("-shared") - 1) == 0)
1237 shared_obj = 1;
1239 obstack_free (&temporary_obstack, temporary_firstobj);
1240 *c_ptr++ = "-fno-exceptions";
1242 /* !!! When GCC calls collect2,
1243 it does not know whether it is calling collect2 or ld.
1244 So collect2 cannot meaningfully understand any options
1245 except those ld understands.
1246 If you propose to make GCC pass some other option,
1247 just imagine what will happen if ld is really ld!!! */
1249 /* Parse arguments. Remember output file spec, pass the rest to ld. */
1250 /* After the first file, put in the c++ rt0. */
1252 first_file = 1;
1253 while ((arg = *++argv) != (char *) 0)
1255 *ld1++ = *ld2++ = arg;
1257 if (arg[0] == '-')
1259 switch (arg[1])
1261 #ifdef COLLECT_EXPORT_LIST
1262 /* We want to disable automatic exports on AIX when user
1263 explicitly puts an export list in command line */
1264 case 'b':
1265 if (arg[2] == 'E' || strncmp (&arg[2], "export", 6) == 0)
1266 export_flag = 1;
1267 break;
1268 #endif
1270 case 'd':
1271 if (!strcmp (arg, "-debug"))
1273 /* Already parsed. */
1274 ld1--;
1275 ld2--;
1277 break;
1279 case 'l':
1280 if (first_file)
1282 /* place o_file BEFORE this argument! */
1283 first_file = 0;
1284 ld2--;
1285 *ld2++ = o_file;
1286 *ld2++ = arg;
1288 #ifdef COLLECT_EXPORT_LIST
1290 /* Resolving full library name. */
1291 char *s = resolve_lib_name (arg+2);
1293 /* If we will use an import list for this library,
1294 we should exclude it from ld args. */
1295 if (use_import_list (s))
1297 ld1--;
1298 ld2--;
1301 /* Saving a full library name. */
1302 add_to_list (&libs, s);
1304 #endif
1305 break;
1307 #ifdef COLLECT_EXPORT_LIST
1308 /* Saving directories where to search for libraries. */
1309 case 'L':
1310 add_prefix (&cmdline_lib_dirs, arg+2);
1311 break;
1312 #endif
1314 case 'o':
1315 if (arg[2] == '\0')
1316 output_file = *ld1++ = *ld2++ = *++argv;
1317 else
1318 output_file = &arg[2];
1319 break;
1321 case 'r':
1322 if (arg[2] == '\0')
1323 rflag = 1;
1324 break;
1326 case 's':
1327 if (arg[2] == '\0' && do_collecting)
1329 /* We must strip after the nm run, otherwise C++ linking
1330 will not work. Thus we strip in the second ld run, or
1331 else with strip if there is no second ld run. */
1332 strip_flag = 1;
1333 ld1--;
1335 break;
1337 case 'v':
1338 if (arg[2] == '\0')
1339 vflag = 1;
1340 break;
1343 else if ((p = rindex (arg, '.')) != (char *) 0
1344 && (strcmp (p, ".o") == 0 || strcmp (p, ".a") == 0
1345 || strcmp (p, ".so") == 0))
1347 if (first_file)
1349 first_file = 0;
1350 if (p[1] == 'o')
1351 *ld2++ = o_file;
1352 else
1354 /* place o_file BEFORE this argument! */
1355 ld2--;
1356 *ld2++ = o_file;
1357 *ld2++ = arg;
1360 if (p[1] == 'o')
1361 *object++ = arg;
1362 #ifdef COLLECT_EXPORT_LIST
1363 /* libraries can be specified directly, i.e. without -l flag. */
1364 else
1366 /* If we will use an import list for this library,
1367 we should exclude it from ld args. */
1368 if (use_import_list (arg))
1370 ld1--;
1371 ld2--;
1374 /* Saving a full library name. */
1375 add_to_list (&libs, arg);
1377 #endif
1381 #ifdef COLLECT_EXPORT_LIST
1382 /* This is added only for debugging purposes. */
1383 if (debug)
1385 fprintf (stderr, "List of libraries:\n");
1386 dump_list (stderr, "\t", libs.first);
1389 /* The AIX linker will discard static constructors in object files if
1390 nothing else in the file is referenced, so look at them first. */
1392 char **export_object_lst = object_lst;
1393 while (export_object_lst < object)
1394 scan_prog_file (*export_object_lst++, PASS_OBJ);
1397 struct id *list = libs.first;
1398 for (; list; list = list->next)
1399 scan_prog_file (list->name, PASS_FIRST);
1402 char *buf1 = alloca (strlen (export_file) + 5);
1403 char *buf2 = alloca (strlen (import_file) + 5);
1404 sprintf (buf1, "-bE:%s", export_file);
1405 sprintf (buf2, "-bI:%s", import_file);
1406 *ld1++ = buf1;
1407 *ld2++ = buf1;
1408 *ld1++ = buf2;
1409 *ld2++ = buf2;
1410 exportf = fopen (export_file, "w");
1411 if (exportf == (FILE *) 0)
1412 fatal_perror ("%s", export_file);
1413 write_export_file (exportf);
1414 if (fclose (exportf))
1415 fatal_perror ("closing %s", export_file);
1416 importf = fopen (import_file, "w");
1417 if (importf == (FILE *) 0)
1418 fatal_perror ("%s", import_file);
1419 write_import_file (importf);
1420 if (fclose (importf))
1421 fatal_perror ("closing %s", import_file);
1423 #endif
1425 *c_ptr++ = c_file;
1426 *object = *c_ptr = *ld1 = (char *) 0;
1428 if (vflag)
1430 fprintf (stderr, "collect2 version %s", version_string);
1431 #ifdef TARGET_VERSION
1432 TARGET_VERSION;
1433 #endif
1434 fprintf (stderr, "\n");
1437 if (debug)
1439 char *ptr;
1440 fprintf (stderr, "ld_file_name = %s\n",
1441 (ld_file_name ? ld_file_name : "not found"));
1442 fprintf (stderr, "c_file_name = %s\n",
1443 (c_file_name ? c_file_name : "not found"));
1444 fprintf (stderr, "nm_file_name = %s\n",
1445 (nm_file_name ? nm_file_name : "not found"));
1446 #ifdef LDD_SUFFIX
1447 fprintf (stderr, "ldd_file_name = %s\n",
1448 (ldd_file_name ? ldd_file_name : "not found"));
1449 #endif
1450 fprintf (stderr, "strip_file_name = %s\n",
1451 (strip_file_name ? strip_file_name : "not found"));
1452 fprintf (stderr, "c_file = %s\n",
1453 (c_file ? c_file : "not found"));
1454 fprintf (stderr, "o_file = %s\n",
1455 (o_file ? o_file : "not found"));
1457 ptr = getenv ("COLLECT_GCC_OPTIONS");
1458 if (ptr)
1459 fprintf (stderr, "COLLECT_GCC_OPTIONS = %s\n", ptr);
1461 ptr = getenv ("COLLECT_GCC");
1462 if (ptr)
1463 fprintf (stderr, "COLLECT_GCC = %s\n", ptr);
1465 ptr = getenv ("COMPILER_PATH");
1466 if (ptr)
1467 fprintf (stderr, "COMPILER_PATH = %s\n", ptr);
1469 ptr = getenv ("LIBRARY_PATH");
1470 if (ptr)
1471 fprintf (stderr, "LIBRARY_PATH = %s\n", ptr);
1473 fprintf (stderr, "\n");
1476 /* Load the program, searching all libraries and attempting to provide
1477 undefined symbols from repository information. */
1479 /* On AIX we do this later. */
1480 #ifndef COLLECT_EXPORT_LIST
1481 do_tlink (ld1_argv, object_lst);
1482 #endif
1484 /* If -r or they will be run via some other method, do not build the
1485 constructor or destructor list, just return now. */
1486 if (rflag
1487 #ifndef COLLECT_EXPORT_LIST
1488 || ! do_collecting
1489 #endif
1492 #ifdef COLLECT_EXPORT_LIST
1493 /* But make sure we delete the export file we may have created. */
1494 if (export_file != 0 && export_file[0])
1495 maybe_unlink (export_file);
1496 if (import_file != 0 && import_file[0])
1497 maybe_unlink (import_file);
1498 #endif
1499 maybe_unlink (c_file);
1500 maybe_unlink (o_file);
1501 return 0;
1504 /* Examine the namelist with nm and search it for static constructors
1505 and destructors to call.
1506 Write the constructor and destructor tables to a .s file and reload. */
1508 /* On AIX we already done scanning for global constructors/destructors. */
1509 #ifndef COLLECT_EXPORT_LIST
1510 scan_prog_file (output_file, PASS_FIRST);
1511 #endif
1513 #ifdef SCAN_LIBRARIES
1514 scan_libraries (output_file);
1515 #endif
1517 if (debug)
1519 fprintf (stderr, "%d constructor(s) found\n", constructors.number);
1520 fprintf (stderr, "%d destructor(s) found\n", destructors.number);
1523 if (constructors.number == 0 && destructors.number == 0
1524 && frame_tables.number == 0
1525 #if defined (SCAN_LIBRARIES) || defined (COLLECT_EXPORT_LIST)
1526 /* If we will be running these functions ourselves, we want to emit
1527 stubs into the shared library so that we do not have to relink
1528 dependent programs when we add static objects. */
1529 && ! shared_obj
1530 #endif
1533 #ifdef COLLECT_EXPORT_LIST
1534 /* Doing tlink without additional code generation */
1535 do_tlink (ld1_argv, object_lst);
1536 #endif
1537 /* Strip now if it was requested on the command line. */
1538 if (strip_flag)
1540 char **strip_argv = (char **) xcalloc (sizeof (char *), 3);
1541 strip_argv[0] = strip_file_name;
1542 strip_argv[1] = output_file;
1543 strip_argv[2] = (char *) 0;
1544 fork_execute ("strip", strip_argv);
1547 #ifdef COLLECT_EXPORT_LIST
1548 maybe_unlink (export_file);
1549 maybe_unlink (import_file);
1550 #endif
1551 maybe_unlink (c_file);
1552 maybe_unlink (o_file);
1553 return 0;
1556 /* Sort ctor and dtor lists by priority. */
1557 sort_ids (&constructors);
1558 sort_ids (&destructors);
1560 maybe_unlink(output_file);
1561 outf = fopen (c_file, "w");
1562 if (outf == (FILE *) 0)
1563 fatal_perror ("%s", c_file);
1565 write_c_file (outf, c_file);
1567 if (fclose (outf))
1568 fatal_perror ("closing %s", c_file);
1570 /* Tell the linker that we have initializer and finalizer functions. */
1571 #ifdef LD_INIT_SWITCH
1572 *ld2++ = LD_INIT_SWITCH;
1573 *ld2++ = initname;
1574 *ld2++ = LD_FINI_SWITCH;
1575 *ld2++ = fininame;
1576 #endif
1577 *ld2 = (char*) 0;
1579 #ifdef COLLECT_EXPORT_LIST
1580 if (shared_obj)
1582 add_to_list (&exports, initname);
1583 add_to_list (&exports, fininame);
1584 add_to_list (&exports, "_GLOBAL__DI");
1585 add_to_list (&exports, "_GLOBAL__DD");
1586 exportf = fopen (export_file, "w");
1587 if (exportf == (FILE *) 0)
1588 fatal_perror ("%s", export_file);
1589 write_export_file (exportf);
1590 if (fclose (exportf))
1591 fatal_perror ("closing %s", export_file);
1593 #endif
1595 if (debug)
1597 fprintf (stderr, "\n========== output_file = %s, c_file = %s\n",
1598 output_file, c_file);
1599 write_c_file (stderr, "stderr");
1600 fprintf (stderr, "========== end of c_file\n\n");
1601 #ifdef COLLECT_EXPORT_LIST
1602 fprintf (stderr, "\n========== export_file = %s\n", export_file);
1603 write_export_file (stderr);
1604 fprintf (stderr, "========== end of export_file\n\n");
1605 #endif
1608 /* Assemble the constructor and destructor tables.
1609 Link the tables in with the rest of the program. */
1611 fork_execute ("gcc", c_argv);
1612 #ifdef COLLECT_EXPORT_LIST
1613 /* On AIX we must call tlink because of possible templates resolution */
1614 do_tlink (ld2_argv, object_lst);
1615 #else
1616 /* Otherwise, simply call ld because tlink is already done */
1617 fork_execute ("ld", ld2_argv);
1619 /* Let scan_prog_file do any final mods (OSF/rose needs this for
1620 constructors/destructors in shared libraries. */
1621 scan_prog_file (output_file, PASS_SECOND);
1622 #endif
1624 maybe_unlink (c_file);
1625 maybe_unlink (o_file);
1627 #ifdef COLLECT_EXPORT_LIST
1628 maybe_unlink (export_file);
1629 maybe_unlink (import_file);
1630 #endif
1632 return 0;
1636 /* Wait for a process to finish, and exit if a non-zero status is found. */
1639 collect_wait (prog)
1640 char *prog;
1642 int status;
1644 wait (&status);
1645 if (status)
1647 if (WIFSIGNALED (status))
1649 int sig = WTERMSIG (status);
1650 error ("%s terminated with signal %d [%s]%s",
1651 prog,
1652 sig,
1653 my_strsignal(sig),
1654 (status & 0200) ? ", core dumped" : "");
1656 collect_exit (FATAL_EXIT_CODE);
1659 if (WIFEXITED (status))
1660 return WEXITSTATUS (status);
1662 return 0;
1665 static void
1666 do_wait (prog)
1667 char *prog;
1669 int ret = collect_wait (prog);
1670 if (ret != 0)
1672 error ("%s returned %d exit status", prog, ret);
1673 collect_exit (ret);
1678 /* Fork and execute a program, and wait for the reply. */
1680 void
1681 collect_execute (prog, argv, redir)
1682 char *prog;
1683 char **argv;
1684 char *redir;
1686 int pid;
1688 if (vflag || debug)
1690 char **p_argv;
1691 char *str;
1693 if (argv[0])
1694 fprintf (stderr, "%s", argv[0]);
1695 else
1696 fprintf (stderr, "[cannot find %s]", prog);
1698 for (p_argv = &argv[1]; (str = *p_argv) != (char *) 0; p_argv++)
1699 fprintf (stderr, " %s", str);
1701 fprintf (stderr, "\n");
1704 fflush (stdout);
1705 fflush (stderr);
1707 /* If we cannot find a program we need, complain error. Do this here
1708 since we might not end up needing something that we could not find. */
1710 if (argv[0] == 0)
1711 fatal ("cannot find `%s'", prog);
1713 #ifndef __CYGWIN32__
1714 pid = vfork ();
1715 if (pid == -1)
1717 #ifdef vfork
1718 fatal_perror ("fork");
1719 #else
1720 fatal_perror ("vfork");
1721 #endif
1724 if (pid == 0) /* child context */
1726 if (redir)
1728 unlink (redir);
1729 if (freopen (redir, "a", stdout) == NULL)
1730 fatal_perror ("redirecting stdout: %s", redir);
1731 if (freopen (redir, "a", stderr) == NULL)
1732 fatal_perror ("redirecting stderr: %s", redir);
1735 execvp (argv[0], argv);
1736 fatal_perror ("executing %s", prog);
1738 #else
1739 pid = _spawnvp (_P_NOWAIT, argv[0], argv);
1740 if (pid == -1)
1741 fatal ("spawnvp failed");
1742 #endif
1745 static void
1746 fork_execute (prog, argv)
1747 char *prog;
1748 char **argv;
1750 collect_execute (prog, argv, NULL);
1751 do_wait (prog);
1754 /* Unlink a file unless we are debugging. */
1756 static void
1757 maybe_unlink (file)
1758 char *file;
1760 if (!debug)
1761 unlink (file);
1762 else
1763 fprintf (stderr, "[Leaving %s]\n", file);
1767 static long sequence_number = 0;
1769 /* Add a name to a linked list. */
1771 static void
1772 add_to_list (head_ptr, name)
1773 struct head *head_ptr;
1774 char *name;
1776 struct id *newid
1777 = (struct id *) xcalloc (sizeof (struct id) + strlen (name), 1);
1778 struct id *p;
1779 strcpy (newid->name, name);
1781 if (head_ptr->first)
1782 head_ptr->last->next = newid;
1783 else
1784 head_ptr->first = newid;
1786 /* Check for duplicate symbols. */
1787 for (p = head_ptr->first;
1788 strcmp (name, p->name) != 0;
1789 p = p->next)
1791 if (p != newid)
1793 head_ptr->last->next = 0;
1794 free (newid);
1795 return;
1798 newid->sequence = ++sequence_number;
1799 head_ptr->last = newid;
1800 head_ptr->number++;
1803 /* Grab the init priority number from an init function name that
1804 looks like "_GLOBAL_.I.12345.foo". */
1806 static int
1807 extract_init_priority (name)
1808 char *name;
1810 int pos = 0, pri;
1812 while (name[pos] == '_')
1813 ++pos;
1814 pos += 10; /* strlen ("GLOBAL__X_") */
1816 /* Extract init_p number from ctor/dtor name. */
1817 pri = atoi (name + pos);
1818 return pri ? pri : DEFAULT_INIT_PRIORITY;
1821 /* Insertion sort the ids from ctor/dtor list HEAD_PTR in descending order.
1822 ctors will be run from right to left, dtors from left to right. */
1824 static void
1825 sort_ids (head_ptr)
1826 struct head *head_ptr;
1828 /* id holds the current element to insert. id_next holds the next
1829 element to insert. id_ptr iterates through the already sorted elements
1830 looking for the place to insert id. */
1831 struct id *id, *id_next, **id_ptr;
1833 id = head_ptr->first;
1835 /* We don't have any sorted elements yet. */
1836 head_ptr->first = NULL;
1838 for (; id; id = id_next)
1840 id_next = id->next;
1841 id->sequence = extract_init_priority (id->name);
1843 for (id_ptr = &(head_ptr->first); ; id_ptr = &((*id_ptr)->next))
1844 if (*id_ptr == NULL
1845 /* If the sequence numbers are the same, we put the id from the
1846 file later on the command line later in the list. */
1847 || id->sequence > (*id_ptr)->sequence
1848 /* Hack: do lexical compare, too.
1849 || (id->sequence == (*id_ptr)->sequence
1850 && strcmp (id->name, (*id_ptr)->name) > 0) */
1853 id->next = *id_ptr;
1854 *id_ptr = id;
1855 break;
1859 /* Now set the sequence numbers properly so write_c_file works. */
1860 for (id = head_ptr->first; id; id = id->next)
1861 id->sequence = ++sequence_number;
1864 /* Write: `prefix', the names on list LIST, `suffix'. */
1866 static void
1867 write_list (stream, prefix, list)
1868 FILE *stream;
1869 char *prefix;
1870 struct id *list;
1872 while (list)
1874 fprintf (stream, "%sx%d,\n", prefix, list->sequence);
1875 list = list->next;
1879 #ifdef COLLECT_EXPORT_LIST
1880 /* This function is really used only on AIX, but may be useful. */
1881 static int
1882 is_in_list (prefix, list)
1883 char *prefix;
1884 struct id *list;
1886 while (list)
1888 if (!strcmp (prefix, list->name)) return 1;
1889 list = list->next;
1891 return 0;
1893 #endif
1895 /* Added for debugging purpose. */
1896 #ifdef COLLECT_EXPORT_LIST
1897 static void
1898 dump_list (stream, prefix, list)
1899 FILE *stream;
1900 char *prefix;
1901 struct id *list;
1903 while (list)
1905 fprintf (stream, "%s%s,\n", prefix, list->name);
1906 list = list->next;
1909 #endif
1911 #if 0
1912 static void
1913 dump_prefix_list (stream, prefix, list)
1914 FILE *stream;
1915 char *prefix;
1916 struct prefix_list *list;
1918 while (list)
1920 fprintf (stream, "%s%s,\n", prefix, list->prefix);
1921 list = list->next;
1924 #endif
1926 static void
1927 write_list_with_asm (stream, prefix, list)
1928 FILE *stream;
1929 char *prefix;
1930 struct id *list;
1932 while (list)
1934 fprintf (stream, "%sx%d __asm__ (\"%s\");\n",
1935 prefix, list->sequence, list->name);
1936 list = list->next;
1940 /* Write out the constructor and destructor tables statically (for a shared
1941 object), along with the functions to execute them. */
1943 static void
1944 write_c_file_stat (stream, name)
1945 FILE *stream;
1946 char *name;
1948 char *prefix, *p, *q;
1949 int frames = (frame_tables.number > 0);
1951 /* Figure out name of output_file, stripping off .so version. */
1952 p = rindex (output_file, '/');
1953 if (p == 0)
1954 p = (char *) output_file;
1955 else
1956 p++;
1957 q = p;
1958 while (q)
1960 q = index (q,'.');
1961 if (q == 0)
1963 q = p + strlen (p);
1964 break;
1966 else
1968 if (strncmp (q, ".so", 3) == 0)
1970 q += 3;
1971 break;
1973 else
1974 q++;
1977 /* q points to null at end of the string (or . of the .so version) */
1978 prefix = xmalloc (q - p + 1);
1979 strncpy (prefix, p, q - p);
1980 prefix[q - p] = 0;
1981 for (q = prefix; *q; q++)
1982 if (!ISALNUM ((unsigned char)*q))
1983 *q = '_';
1984 if (debug)
1985 fprintf (stderr, "\nwrite_c_file - output name is %s, prefix is %s\n",
1986 output_file, prefix);
1988 #define INIT_NAME_FORMAT "_GLOBAL__FI_%s"
1989 initname = xmalloc (strlen (prefix) + sizeof (INIT_NAME_FORMAT) - 2);
1990 sprintf (initname, INIT_NAME_FORMAT, prefix);
1992 #define FINI_NAME_FORMAT "_GLOBAL__FD_%s"
1993 fininame = xmalloc (strlen (prefix) + sizeof (FINI_NAME_FORMAT) - 2);
1994 sprintf (fininame, FINI_NAME_FORMAT, prefix);
1996 free (prefix);
1998 /* Write the tables as C code */
2000 fprintf (stream, "static int count;\n");
2001 fprintf (stream, "typedef void entry_pt();\n");
2002 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2004 if (frames)
2006 write_list_with_asm (stream, "extern void *", frame_tables.first);
2008 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2009 write_list (stream, "\t\t&", frame_tables.first);
2010 fprintf (stream, "\t0\n};\n");
2012 /* This must match what's in frame.h. */
2013 fprintf (stream, "struct object {\n");
2014 fprintf (stream, " void *pc_begin;\n");
2015 fprintf (stream, " void *pc_end;\n");
2016 fprintf (stream, " void *fde_begin;\n");
2017 fprintf (stream, " void *fde_array;\n");
2018 fprintf (stream, " __SIZE_TYPE__ count;\n");
2019 fprintf (stream, " struct object *next;\n");
2020 fprintf (stream, "};\n");
2022 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2023 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2025 fprintf (stream, "static void reg_frame () {\n");
2026 fprintf (stream, "\tstatic struct object ob;\n");
2027 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2028 fprintf (stream, "\t}\n");
2030 fprintf (stream, "static void dereg_frame () {\n");
2031 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2032 fprintf (stream, "\t}\n");
2035 fprintf (stream, "void %s() {\n", initname);
2036 if (constructors.number > 0 || frames)
2038 fprintf (stream, "\tstatic entry_pt *ctors[] = {\n");
2039 write_list (stream, "\t\t", constructors.first);
2040 if (frames)
2041 fprintf (stream, "\treg_frame,\n");
2042 fprintf (stream, "\t};\n");
2043 fprintf (stream, "\tentry_pt **p;\n");
2044 fprintf (stream, "\tif (count++ != 0) return;\n");
2045 fprintf (stream, "\tp = ctors + %d;\n", constructors.number + frames);
2046 fprintf (stream, "\twhile (p > ctors) (*--p)();\n");
2048 else
2049 fprintf (stream, "\t++count;\n");
2050 fprintf (stream, "}\n");
2051 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2052 fprintf (stream, "void %s() {\n", fininame);
2053 if (destructors.number > 0 || frames)
2055 fprintf (stream, "\tstatic entry_pt *dtors[] = {\n");
2056 write_list (stream, "\t\t", destructors.first);
2057 if (frames)
2058 fprintf (stream, "\tdereg_frame,\n");
2059 fprintf (stream, "\t};\n");
2060 fprintf (stream, "\tentry_pt **p;\n");
2061 fprintf (stream, "\tif (--count != 0) return;\n");
2062 fprintf (stream, "\tp = dtors;\n");
2063 fprintf (stream, "\twhile (p < dtors + %d) (*p++)();\n",
2064 destructors.number + frames);
2066 fprintf (stream, "}\n");
2068 if (shared_obj)
2070 fprintf (stream, "void _GLOBAL__DI() {\n\t%s();\n}\n", initname);
2071 fprintf (stream, "void _GLOBAL__DD() {\n\t%s();\n}\n", fininame);
2075 /* Write the constructor/destructor tables. */
2077 #ifndef LD_INIT_SWITCH
2078 static void
2079 write_c_file_glob (stream, name)
2080 FILE *stream;
2081 char *name;
2083 /* Write the tables as C code */
2085 int frames = (frame_tables.number > 0);
2087 fprintf (stream, "typedef void entry_pt();\n\n");
2089 write_list_with_asm (stream, "extern entry_pt ", constructors.first);
2091 if (frames)
2093 write_list_with_asm (stream, "extern void *", frame_tables.first);
2095 fprintf (stream, "\tstatic void *frame_table[] = {\n");
2096 write_list (stream, "\t\t&", frame_tables.first);
2097 fprintf (stream, "\t0\n};\n");
2099 /* This must match what's in frame.h. */
2100 fprintf (stream, "struct object {\n");
2101 fprintf (stream, " void *pc_begin;\n");
2102 fprintf (stream, " void *pc_end;\n");
2103 fprintf (stream, " void *fde_begin;\n");
2104 fprintf (stream, " void *fde_array;\n");
2105 fprintf (stream, " __SIZE_TYPE__ count;\n");
2106 fprintf (stream, " struct object *next;\n");
2107 fprintf (stream, "};\n");
2109 fprintf (stream, "extern void __register_frame_info_table (void *, struct object *);\n");
2110 fprintf (stream, "extern void *__deregister_frame_info (void *);\n");
2112 fprintf (stream, "static void reg_frame () {\n");
2113 fprintf (stream, "\tstatic struct object ob;\n");
2114 fprintf (stream, "\t__register_frame_info_table (frame_table, &ob);\n");
2115 fprintf (stream, "\t}\n");
2117 fprintf (stream, "static void dereg_frame () {\n");
2118 fprintf (stream, "\t__deregister_frame_info (frame_table);\n");
2119 fprintf (stream, "\t}\n");
2122 fprintf (stream, "\nentry_pt * __CTOR_LIST__[] = {\n");
2123 fprintf (stream, "\t(entry_pt *) %d,\n", constructors.number + frames);
2124 write_list (stream, "\t", constructors.first);
2125 if (frames)
2126 fprintf (stream, "\treg_frame,\n");
2127 fprintf (stream, "\t0\n};\n\n");
2129 write_list_with_asm (stream, "extern entry_pt ", destructors.first);
2131 fprintf (stream, "\nentry_pt * __DTOR_LIST__[] = {\n");
2132 fprintf (stream, "\t(entry_pt *) %d,\n", destructors.number + frames);
2133 write_list (stream, "\t", destructors.first);
2134 if (frames)
2135 fprintf (stream, "\tdereg_frame,\n");
2136 fprintf (stream, "\t0\n};\n\n");
2138 fprintf (stream, "extern entry_pt %s;\n", NAME__MAIN);
2139 fprintf (stream, "entry_pt *__main_reference = %s;\n\n", NAME__MAIN);
2141 #endif /* ! LD_INIT_SWITCH */
2143 static void
2144 write_c_file (stream, name)
2145 FILE *stream;
2146 char *name;
2148 fprintf (stream, "#ifdef __cplusplus\nextern \"C\" {\n#endif\n");
2149 #ifndef LD_INIT_SWITCH
2150 if (! shared_obj)
2151 write_c_file_glob (stream, name);
2152 else
2153 #endif
2154 write_c_file_stat (stream, name);
2155 fprintf (stream, "#ifdef __cplusplus\n}\n#endif\n");
2158 #ifdef COLLECT_EXPORT_LIST
2159 static void
2160 write_export_file (stream)
2161 FILE *stream;
2163 struct id *list = exports.first;
2164 for (; list; list = list->next)
2165 fprintf (stream, "%s\n", list->name);
2168 static void
2169 write_import_file (stream)
2170 FILE *stream;
2172 struct id *list = imports.first;
2173 fprintf (stream, "%s\n", "#! .");
2174 for (; list; list = list->next)
2175 fprintf (stream, "%s\n", list->name);
2177 #endif
2179 #ifdef OBJECT_FORMAT_NONE
2181 /* Generic version to scan the name list of the loaded program for
2182 the symbols g++ uses for static constructors and destructors.
2184 The constructor table begins at __CTOR_LIST__ and contains a count
2185 of the number of pointers (or -1 if the constructors are built in a
2186 separate section by the linker), followed by the pointers to the
2187 constructor functions, terminated with a null pointer. The
2188 destructor table has the same format, and begins at __DTOR_LIST__. */
2190 static void
2191 scan_prog_file (prog_name, which_pass)
2192 char *prog_name;
2193 enum pass which_pass;
2195 void (*int_handler) ();
2196 void (*quit_handler) ();
2197 char *nm_argv[4];
2198 int pid;
2199 int argc = 0;
2200 int pipe_fd[2];
2201 char *p, buf[1024];
2202 FILE *inf;
2204 if (which_pass == PASS_SECOND)
2205 return;
2207 /* If we do not have an `nm', complain. */
2208 if (nm_file_name == 0)
2209 fatal ("cannot find `nm'");
2211 nm_argv[argc++] = nm_file_name;
2212 if (NM_FLAGS[0] != '\0')
2213 nm_argv[argc++] = NM_FLAGS;
2215 nm_argv[argc++] = prog_name;
2216 nm_argv[argc++] = (char *) 0;
2218 if (pipe (pipe_fd) < 0)
2219 fatal_perror ("pipe");
2221 inf = fdopen (pipe_fd[0], "r");
2222 if (inf == (FILE *) 0)
2223 fatal_perror ("fdopen");
2225 /* Trace if needed. */
2226 if (vflag)
2228 char **p_argv;
2229 char *str;
2231 for (p_argv = &nm_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2232 fprintf (stderr, " %s", str);
2234 fprintf (stderr, "\n");
2237 fflush (stdout);
2238 fflush (stderr);
2240 /* Spawn child nm on pipe */
2241 pid = vfork ();
2242 if (pid == -1)
2244 #ifdef vfork
2245 fatal_perror ("fork");
2246 #else
2247 fatal_perror ("vfork");
2248 #endif
2251 if (pid == 0) /* child context */
2253 /* setup stdout */
2254 if (dup2 (pipe_fd[1], 1) < 0)
2255 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2257 if (close (pipe_fd[0]) < 0)
2258 fatal_perror ("close (%d)", pipe_fd[0]);
2260 if (close (pipe_fd[1]) < 0)
2261 fatal_perror ("close (%d)", pipe_fd[1]);
2263 execv (nm_file_name, nm_argv);
2264 fatal_perror ("executing %s", nm_file_name);
2267 /* Parent context from here on. */
2268 int_handler = (void (*) ())signal (SIGINT, SIG_IGN);
2269 #ifdef SIGQUIT
2270 quit_handler = (void (*) ())signal (SIGQUIT, SIG_IGN);
2271 #endif
2273 if (close (pipe_fd[1]) < 0)
2274 fatal_perror ("close (%d)", pipe_fd[1]);
2276 if (debug)
2277 fprintf (stderr, "\nnm output with constructors/destructors.\n");
2279 /* Read each line of nm output. */
2280 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2282 int ch, ch2;
2283 char *name, *end;
2285 /* If it contains a constructor or destructor name, add the name
2286 to the appropriate list. */
2288 for (p = buf; (ch = *p) != '\0' && ch != '\n' && ch != '_'; p++)
2289 if (ch == ' ' && p[1] == 'U' && p[2] == ' ')
2290 break;
2292 if (ch != '_')
2293 continue;
2295 name = p;
2296 /* Find the end of the symbol name.
2297 Do not include `|', because Encore nm can tack that on the end. */
2298 for (end = p; (ch2 = *end) != '\0' && !ISSPACE (ch2) && ch2 != '|';
2299 end++)
2300 continue;
2303 *end = '\0';
2304 switch (is_ctor_dtor (name))
2306 case 1:
2307 if (which_pass != PASS_LIB)
2308 add_to_list (&constructors, name);
2309 break;
2311 case 2:
2312 if (which_pass != PASS_LIB)
2313 add_to_list (&destructors, name);
2314 break;
2316 case 3:
2317 if (which_pass != PASS_LIB)
2318 fatal ("init function found in object %s", prog_name);
2319 #ifndef LD_INIT_SWITCH
2320 add_to_list (&constructors, name);
2321 #endif
2322 break;
2324 case 4:
2325 if (which_pass != PASS_LIB)
2326 fatal ("fini function found in object %s", prog_name);
2327 #ifndef LD_FINI_SWITCH
2328 add_to_list (&destructors, name);
2329 #endif
2330 break;
2332 case 5:
2333 if (which_pass != PASS_LIB)
2334 add_to_list (&frame_tables, name);
2336 default: /* not a constructor or destructor */
2337 continue;
2340 if (debug)
2341 fprintf (stderr, "\t%s\n", buf);
2344 if (debug)
2345 fprintf (stderr, "\n");
2347 if (fclose (inf) != 0)
2348 fatal_perror ("fclose of pipe");
2350 do_wait (nm_file_name);
2352 signal (SIGINT, int_handler);
2353 #ifdef SIGQUIT
2354 signal (SIGQUIT, quit_handler);
2355 #endif
2358 #if SUNOS4_SHARED_LIBRARIES
2360 /* Routines to scan the SunOS 4 _DYNAMIC structure to find shared libraries
2361 that the output file depends upon and their initialization/finalization
2362 routines, if any. */
2364 #include <a.out.h>
2365 #include <fcntl.h>
2366 #include <link.h>
2367 #include <sys/mman.h>
2368 #include <sys/param.h>
2369 #include <unistd.h>
2370 #include <sys/dir.h>
2372 /* pointers to the object file */
2373 unsigned object; /* address of memory mapped file */
2374 unsigned objsize; /* size of memory mapped to file */
2375 char * code; /* pointer to code segment */
2376 char * data; /* pointer to data segment */
2377 struct nlist *symtab; /* pointer to symbol table */
2378 struct link_dynamic *ld;
2379 struct link_dynamic_2 *ld_2;
2380 struct head libraries;
2382 /* Map the file indicated by NAME into memory and store its address. */
2384 static void
2385 mapfile (name)
2386 char *name;
2388 int fp;
2389 struct stat s;
2390 if ((fp = open (name, O_RDONLY)) == -1)
2391 fatal ("unable to open file '%s'", name);
2392 if (fstat (fp, &s) == -1)
2393 fatal ("unable to stat file '%s'", name);
2395 objsize = s.st_size;
2396 object = (unsigned) mmap (0, objsize, PROT_READ|PROT_WRITE, MAP_PRIVATE,
2397 fp, 0);
2398 if (object == -1)
2399 fatal ("unable to mmap file '%s'", name);
2401 close (fp);
2404 /* Helpers for locatelib. */
2406 static char *libname;
2408 static int
2409 libselect (d)
2410 struct direct *d;
2412 return (strncmp (libname, d->d_name, strlen (libname)) == 0);
2415 /* If one file has an additional numeric extension past LIBNAME, then put
2416 that one first in the sort. If both files have additional numeric
2417 extensions, then put the one with the higher number first in the sort.
2419 We must verify that the extension is numeric, because Sun saves the
2420 original versions of patched libraries with a .FCS extension. Files with
2421 invalid extensions must go last in the sort, so that they will not be used. */
2423 static int
2424 libcompare (d1, d2)
2425 struct direct **d1, **d2;
2427 int i1, i2 = strlen (libname);
2428 char *e1 = (*d1)->d_name + i2;
2429 char *e2 = (*d2)->d_name + i2;
2431 while (*e1 && *e2 && *e1 == '.' && *e2 == '.'
2432 && e1[1] && ISDIGIT (e1[1]) && e2[1] && ISDIGIT (e2[1]))
2434 ++e1;
2435 ++e2;
2436 i1 = strtol (e1, &e1, 10);
2437 i2 = strtol (e2, &e2, 10);
2438 if (i1 != i2)
2439 return i1 - i2;
2442 if (*e1)
2444 /* It has a valid numeric extension, prefer this one. */
2445 if (*e1 == '.' && e1[1] && ISDIGIT (e1[1]))
2446 return 1;
2447 /* It has a invalid numeric extension, must prefer the other one. */
2448 else
2449 return -1;
2451 else if (*e2)
2453 /* It has a valid numeric extension, prefer this one. */
2454 if (*e2 == '.' && e2[1] && ISDIGIT (e2[1]))
2455 return -1;
2456 /* It has a invalid numeric extension, must prefer the other one. */
2457 else
2458 return 1;
2460 else
2461 return 0;
2464 /* Given the name NAME of a dynamic dependency, find its pathname and add
2465 it to the list of libraries. */
2467 static void
2468 locatelib (name)
2469 char *name;
2471 static char **l;
2472 static int cnt;
2473 char buf[MAXPATHLEN];
2474 char *p, *q;
2475 char **pp;
2477 if (l == 0)
2479 char *ld_rules;
2480 char *ldr = 0;
2481 /* counting elements in array, need 1 extra for null */
2482 cnt = 1;
2483 ld_rules = (char *) (ld_2->ld_rules + code);
2484 if (ld_rules)
2486 cnt++;
2487 for (; *ld_rules != 0; ld_rules++)
2488 if (*ld_rules == ':')
2489 cnt++;
2490 ld_rules = (char *) (ld_2->ld_rules + code);
2491 ldr = (char *) malloc (strlen (ld_rules) + 1);
2492 strcpy (ldr, ld_rules);
2494 p = getenv ("LD_LIBRARY_PATH");
2495 q = 0;
2496 if (p)
2498 cnt++;
2499 for (q = p ; *q != 0; q++)
2500 if (*q == ':')
2501 cnt++;
2502 q = (char *) malloc (strlen (p) + 1);
2503 strcpy (q, p);
2505 l = (char **) malloc ((cnt + 3) * sizeof (char *));
2506 pp = l;
2507 if (ldr)
2509 *pp++ = ldr;
2510 for (; *ldr != 0; ldr++)
2511 if (*ldr == ':')
2513 *ldr++ = 0;
2514 *pp++ = ldr;
2517 if (q)
2519 *pp++ = q;
2520 for (; *q != 0; q++)
2521 if (*q == ':')
2523 *q++ = 0;
2524 *pp++ = q;
2527 /* built in directories are /lib, /usr/lib, and /usr/local/lib */
2528 *pp++ = "/lib";
2529 *pp++ = "/usr/lib";
2530 *pp++ = "/usr/local/lib";
2531 *pp = 0;
2533 libname = name;
2534 for (pp = l; *pp != 0 ; pp++)
2536 struct direct **namelist;
2537 int entries;
2538 if ((entries = scandir (*pp, &namelist, libselect, libcompare)) > 0)
2540 sprintf (buf, "%s/%s", *pp, namelist[entries - 1]->d_name);
2541 add_to_list (&libraries, buf);
2542 if (debug)
2543 fprintf (stderr, "%s\n", buf);
2544 break;
2547 if (*pp == 0)
2549 if (debug)
2550 fprintf (stderr, "not found\n");
2551 else
2552 fatal ("dynamic dependency %s not found", name);
2556 /* Scan the _DYNAMIC structure of the output file to find shared libraries
2557 that it depends upon and any constructors or destructors they contain. */
2559 static void
2560 scan_libraries (prog_name)
2561 char *prog_name;
2563 struct exec *header;
2564 char *base;
2565 struct link_object *lo;
2566 char buff[MAXPATHLEN];
2567 struct id *list;
2569 mapfile (prog_name);
2570 header = (struct exec *)object;
2571 if (N_BADMAG (*header))
2572 fatal ("bad magic number in file '%s'", prog_name);
2573 if (header->a_dynamic == 0)
2574 return;
2576 code = (char *) (N_TXTOFF (*header) + (long) header);
2577 data = (char *) (N_DATOFF (*header) + (long) header);
2578 symtab = (struct nlist *) (N_SYMOFF (*header) + (long) header);
2580 if (header->a_magic == ZMAGIC && header->a_entry == 0x20)
2582 /* shared object */
2583 ld = (struct link_dynamic *) (symtab->n_value + code);
2584 base = code;
2586 else
2588 /* executable */
2589 ld = (struct link_dynamic *) data;
2590 base = code-PAGSIZ;
2593 if (debug)
2594 fprintf (stderr, "dynamic dependencies.\n");
2596 ld_2 = (struct link_dynamic_2 *) ((long) ld->ld_un.ld_2 + (long)base);
2597 for (lo = (struct link_object *) ld_2->ld_need; lo;
2598 lo = (struct link_object *) lo->lo_next)
2600 char *name;
2601 lo = (struct link_object *) ((long) lo + code);
2602 name = (char *) (code + lo->lo_name);
2603 if (lo->lo_library)
2605 if (debug)
2606 fprintf (stderr, "\t-l%s.%d => ", name, lo->lo_major);
2607 sprintf (buff, "lib%s.so.%d.%d", name, lo->lo_major, lo->lo_minor);
2608 locatelib (buff);
2610 else
2612 if (debug)
2613 fprintf (stderr, "\t%s\n", name);
2614 add_to_list (&libraries, name);
2618 if (debug)
2619 fprintf (stderr, "\n");
2621 /* now iterate through the library list adding their symbols to
2622 the list. */
2623 for (list = libraries.first; list; list = list->next)
2624 scan_prog_file (list->name, PASS_LIB);
2627 #else /* SUNOS4_SHARED_LIBRARIES */
2628 #ifdef LDD_SUFFIX
2630 /* Use the List Dynamic Dependencies program to find shared libraries that
2631 the output file depends upon and their initialization/finalization
2632 routines, if any. */
2634 static void
2635 scan_libraries (prog_name)
2636 char *prog_name;
2638 static struct head libraries; /* list of shared libraries found */
2639 struct id *list;
2640 void (*int_handler) ();
2641 void (*quit_handler) ();
2642 char *ldd_argv[4];
2643 int pid;
2644 int argc = 0;
2645 int pipe_fd[2];
2646 char buf[1024];
2647 FILE *inf;
2649 /* If we do not have an `ldd', complain. */
2650 if (ldd_file_name == 0)
2652 error ("cannot find `ldd'");
2653 return;
2656 ldd_argv[argc++] = ldd_file_name;
2657 ldd_argv[argc++] = prog_name;
2658 ldd_argv[argc++] = (char *) 0;
2660 if (pipe (pipe_fd) < 0)
2661 fatal_perror ("pipe");
2663 inf = fdopen (pipe_fd[0], "r");
2664 if (inf == (FILE *) 0)
2665 fatal_perror ("fdopen");
2667 /* Trace if needed. */
2668 if (vflag)
2670 char **p_argv;
2671 char *str;
2673 for (p_argv = &ldd_argv[0]; (str = *p_argv) != (char *) 0; p_argv++)
2674 fprintf (stderr, " %s", str);
2676 fprintf (stderr, "\n");
2679 fflush (stdout);
2680 fflush (stderr);
2682 /* Spawn child ldd on pipe */
2683 pid = vfork ();
2684 if (pid == -1)
2686 #ifdef vfork
2687 fatal_perror ("fork");
2688 #else
2689 fatal_perror ("vfork");
2690 #endif
2693 if (pid == 0) /* child context */
2695 /* setup stdout */
2696 if (dup2 (pipe_fd[1], 1) < 0)
2697 fatal_perror ("dup2 (%d, 1)", pipe_fd[1]);
2699 if (close (pipe_fd[0]) < 0)
2700 fatal_perror ("close (%d)", pipe_fd[0]);
2702 if (close (pipe_fd[1]) < 0)
2703 fatal_perror ("close (%d)", pipe_fd[1]);
2705 execv (ldd_file_name, ldd_argv);
2706 fatal_perror ("executing %s", ldd_file_name);
2709 /* Parent context from here on. */
2710 int_handler = (void (*) ()) signal (SIGINT, SIG_IGN);
2711 #ifdef SIGQUIT
2712 quit_handler = (void (*) ()) signal (SIGQUIT, SIG_IGN);
2713 #endif
2715 if (close (pipe_fd[1]) < 0)
2716 fatal_perror ("close (%d)", pipe_fd[1]);
2718 if (debug)
2719 fprintf (stderr, "\nldd output with constructors/destructors.\n");
2721 /* Read each line of ldd output. */
2722 while (fgets (buf, sizeof buf, inf) != (char *) 0)
2724 int ch, ch2;
2725 char *name, *end, *p = buf;
2727 /* Extract names of libraries and add to list. */
2728 PARSE_LDD_OUTPUT (p);
2729 if (p == 0)
2730 continue;
2732 name = p;
2733 if (strncmp (name, "not found", sizeof ("not found") - 1) == 0)
2734 fatal ("dynamic dependency %s not found", buf);
2736 /* Find the end of the symbol name. */
2737 for (end = p;
2738 (ch2 = *end) != '\0' && ch2 != '\n' && !ISSPACE (ch2) && ch2 != '|';
2739 end++)
2740 continue;
2741 *end = '\0';
2743 if (access (name, R_OK) == 0)
2744 add_to_list (&libraries, name);
2745 else
2746 fatal ("unable to open dynamic dependency '%s'", buf);
2748 if (debug)
2749 fprintf (stderr, "\t%s\n", buf);
2751 if (debug)
2752 fprintf (stderr, "\n");
2754 if (fclose (inf) != 0)
2755 fatal_perror ("fclose of pipe");
2757 do_wait (ldd_file_name);
2759 signal (SIGINT, int_handler);
2760 #ifdef SIGQUIT
2761 signal (SIGQUIT, quit_handler);
2762 #endif
2764 /* now iterate through the library list adding their symbols to
2765 the list. */
2766 for (list = libraries.first; list; list = list->next)
2767 scan_prog_file (list->name, PASS_LIB);
2770 #endif /* LDD_SUFFIX */
2771 #endif /* SUNOS4_SHARED_LIBRARIES */
2773 #endif /* OBJECT_FORMAT_NONE */
2777 * COFF specific stuff.
2780 #ifdef OBJECT_FORMAT_COFF
2782 #if defined(EXTENDED_COFF)
2783 # define GCC_SYMBOLS(X) (SYMHEADER(X).isymMax + SYMHEADER(X).iextMax)
2784 # define GCC_SYMENT SYMR
2785 # define GCC_OK_SYMBOL(X) ((X).st == stProc && (X).sc == scText)
2786 # define GCC_SYMINC(X) (1)
2787 # define GCC_SYMZERO(X) (SYMHEADER(X).isymMax)
2788 # define GCC_CHECK_HDR(X) (PSYMTAB(X) != 0)
2789 #else
2790 # define GCC_SYMBOLS(X) (HEADER(ldptr).f_nsyms)
2791 # define GCC_SYMENT SYMENT
2792 # define GCC_OK_SYMBOL(X) \
2793 (((X).n_sclass == C_EXT) && \
2794 ((X).n_scnum > N_UNDEF) && \
2795 (((X).n_type & N_TMASK) == (DT_NON << N_BTSHFT) || \
2796 ((X).n_type & N_TMASK) == (DT_FCN << N_BTSHFT)))
2797 # define GCC_UNDEF_SYMBOL(X) \
2798 (((X).n_sclass == C_EXT) && ((X).n_scnum == N_UNDEF))
2799 # define GCC_SYMINC(X) ((X).n_numaux+1)
2800 # define GCC_SYMZERO(X) 0
2801 # define GCC_CHECK_HDR(X) (1)
2802 #endif
2804 extern char *ldgetname ();
2806 /* COFF version to scan the name list of the loaded program for
2807 the symbols g++ uses for static constructors and destructors.
2809 The constructor table begins at __CTOR_LIST__ and contains a count
2810 of the number of pointers (or -1 if the constructors are built in a
2811 separate section by the linker), followed by the pointers to the
2812 constructor functions, terminated with a null pointer. The
2813 destructor table has the same format, and begins at __DTOR_LIST__. */
2815 static void
2816 scan_prog_file (prog_name, which_pass)
2817 char *prog_name;
2818 enum pass which_pass;
2820 LDFILE *ldptr = NULL;
2821 int sym_index, sym_count;
2822 int is_shared = 0;
2823 #ifdef COLLECT_EXPORT_LIST
2824 /* Should we generate an import list for given prog_name? */
2825 int import_flag = (which_pass == PASS_OBJ ? 0 : use_import_list (prog_name));
2826 #endif
2828 if (which_pass != PASS_FIRST && which_pass != PASS_OBJ)
2829 return;
2831 #ifdef COLLECT_EXPORT_LIST
2832 /* We do not need scanning for some standard C libraries. */
2833 if (which_pass == PASS_FIRST && ignore_library (prog_name))
2834 return;
2836 /* On AIX we have a loop, because there is not much difference
2837 between an object and an archive. This trick allows us to
2838 eliminate scan_libraries() function. */
2841 #endif
2842 if ((ldptr = ldopen (prog_name, ldptr)) != NULL)
2845 if (!MY_ISCOFF (HEADER (ldptr).f_magic))
2846 fatal ("%s: not a COFF file", prog_name);
2848 #ifdef COLLECT_EXPORT_LIST
2849 /* Is current archive member a shared object? */
2850 is_shared = HEADER (ldptr).f_flags & F_SHROBJ;
2851 #endif
2852 if (GCC_CHECK_HDR (ldptr))
2854 sym_count = GCC_SYMBOLS (ldptr);
2855 sym_index = GCC_SYMZERO (ldptr);
2856 while (sym_index < sym_count)
2858 GCC_SYMENT symbol;
2860 if (ldtbread (ldptr, sym_index, &symbol) <= 0)
2861 break;
2862 sym_index += GCC_SYMINC (symbol);
2864 if (GCC_OK_SYMBOL (symbol))
2866 char *name;
2868 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2869 continue; /* should never happen */
2871 #ifdef XCOFF_DEBUGGING_INFO
2872 /* All AIX function names have a duplicate entry
2873 beginning with a dot. */
2874 if (*name == '.')
2875 ++name;
2876 #endif
2878 switch (is_ctor_dtor (name))
2880 case 1:
2881 if (! is_shared) add_to_list (&constructors, name);
2882 #ifdef COLLECT_EXPORT_LIST
2883 if (which_pass == PASS_OBJ)
2884 add_to_list (&exports, name);
2885 /* If this symbol was undefined and we are building
2886 an import list, we should add a symbol to this
2887 list. */
2888 else
2889 if (import_flag
2890 && is_in_list (name, undefined.first))
2891 add_to_list (&imports, name);
2892 #endif
2893 break;
2895 case 2:
2896 if (! is_shared) add_to_list (&destructors, name);
2897 #ifdef COLLECT_EXPORT_LIST
2898 if (which_pass == PASS_OBJ)
2899 add_to_list (&exports, name);
2900 /* If this symbol was undefined and we are building
2901 an import list, we should add a symbol to this
2902 list. */
2903 else
2904 if (import_flag
2905 && is_in_list (name, undefined.first))
2906 add_to_list (&imports, name);
2907 #endif
2908 break;
2910 #ifdef COLLECT_EXPORT_LIST
2911 case 3:
2912 if (is_shared)
2913 add_to_list (&constructors, name);
2914 break;
2916 case 4:
2917 if (is_shared)
2918 add_to_list (&destructors, name);
2919 break;
2920 #endif
2922 default: /* not a constructor or destructor */
2923 #ifdef COLLECT_EXPORT_LIST
2924 /* If we are building a shared object on AIX we need
2925 to explicitly export all global symbols or add
2926 them to import list. */
2927 if (shared_obj)
2929 if (which_pass == PASS_OBJ && (! export_flag))
2930 add_to_list (&exports, name);
2931 else if (! is_shared && which_pass == PASS_FIRST
2932 && import_flag
2933 && is_in_list(name, undefined.first))
2934 add_to_list (&imports, name);
2936 #endif
2937 continue;
2940 #if !defined(EXTENDED_COFF)
2941 if (debug)
2942 fprintf (stderr, "\tsec=%d class=%d type=%s%o %s\n",
2943 symbol.n_scnum, symbol.n_sclass,
2944 (symbol.n_type ? "0" : ""), symbol.n_type,
2945 name);
2946 #else
2947 if (debug)
2948 fprintf (stderr,
2949 "\tiss = %5d, value = %5ld, index = %5d, name = %s\n",
2950 symbol.iss, (long) symbol.value, symbol.index, name);
2951 #endif
2953 #ifdef COLLECT_EXPORT_LIST
2954 /* If we are building a shared object we should collect
2955 information about undefined symbols for later
2956 import list generation. */
2957 else if (shared_obj && GCC_UNDEF_SYMBOL (symbol))
2959 char *name;
2961 if ((name = ldgetname (ldptr, &symbol)) == NULL)
2962 continue; /* should never happen */
2964 /* All AIX function names have a duplicate entry
2965 beginning with a dot. */
2966 if (*name == '.')
2967 ++name;
2968 add_to_list (&undefined, name);
2970 #endif
2974 else
2976 fatal ("%s: cannot open as COFF file", prog_name);
2978 #ifdef COLLECT_EXPORT_LIST
2979 /* On AIX loop continues while there are more members in archive. */
2981 while (ldclose (ldptr) == FAILURE);
2982 #else
2983 /* Otherwise we simply close ldptr. */
2984 (void) ldclose(ldptr);
2985 #endif
2989 #ifdef COLLECT_EXPORT_LIST
2991 /* This new function is used to decide whether we should
2992 generate import list for an object or to use it directly. */
2993 static int
2994 use_import_list (prog_name)
2995 char *prog_name;
2997 char *p;
2999 /* If we do not build a shared object then import list should not be used. */
3000 if (! shared_obj) return 0;
3002 /* Currently we check only for libgcc, but this can be changed in future. */
3003 p = strstr (prog_name, "libgcc.a");
3004 if (p != 0 && (strlen (p) == sizeof ("libgcc.a") - 1))
3005 return 1;
3006 return 0;
3009 /* Given a library name without "lib" prefix, this function
3010 returns a full library name including a path. */
3011 static char *
3012 resolve_lib_name (name)
3013 char *name;
3015 char *lib_buf;
3016 int i, j, l = 0;
3018 for (i = 0; libpaths[i]; i++)
3019 if (libpaths[i]->max_len > l)
3020 l = libpaths[i]->max_len;
3022 lib_buf = xmalloc (l + strlen(name) + 10);
3024 for (i = 0; libpaths[i]; i++)
3026 struct prefix_list *list = libpaths[i]->plist;
3027 for (; list; list = list->next)
3029 for (j = 0; libexts[j]; j++)
3031 /* The following lines are needed because path_prefix list
3032 may contain directories both with trailing '/' and
3033 without it. */
3034 char *p = "";
3035 if (list->prefix[strlen(list->prefix)-1] != '/')
3036 p = "/";
3037 sprintf (lib_buf, "%s%slib%s.%s",
3038 list->prefix, p, name, libexts[j]);
3039 if (debug) fprintf (stderr, "searching for: %s\n", lib_buf);
3040 if (file_exists (lib_buf))
3042 if (debug) fprintf (stderr, "found: %s\n", lib_buf);
3043 return (lib_buf);
3048 if (debug)
3049 fprintf (stderr, "not found\n");
3050 else
3051 fatal ("Library lib%s not found", name);
3052 return (NULL);
3055 /* Array of standard AIX libraries which should not
3056 be scanned for ctors/dtors. */
3057 static char* aix_std_libs[] = {
3058 "/unix",
3059 "/lib/libc.a",
3060 "/lib/libc_r.a",
3061 "/usr/lib/libc.a",
3062 "/usr/lib/libc_r.a",
3063 "/usr/lib/threads/libc.a",
3064 "/usr/ccs/lib/libc.a",
3065 "/usr/ccs/lib/libc_r.a",
3066 NULL
3069 /* This function checks the filename and returns 1
3070 if this name matches the location of a standard AIX library. */
3071 static int
3072 ignore_library (name)
3073 char *name;
3075 char **p = &aix_std_libs[0];
3076 while (*p++ != NULL)
3077 if (! strcmp (name, *p)) return 1;
3078 return 0;
3081 #endif
3083 #endif /* OBJECT_FORMAT_COFF */
3087 * OSF/rose specific stuff.
3090 #ifdef OBJECT_FORMAT_ROSE
3092 /* Union of the various load commands */
3094 typedef union load_union
3096 ldc_header_t hdr; /* common header */
3097 load_cmd_map_command_t map; /* map indexing other load cmds */
3098 interpreter_command_t iprtr; /* interpreter pathname */
3099 strings_command_t str; /* load commands strings section */
3100 region_command_t region; /* region load command */
3101 reloc_command_t reloc; /* relocation section */
3102 package_command_t pkg; /* package load command */
3103 symbols_command_t sym; /* symbol sections */
3104 entry_command_t ent; /* program start section */
3105 gen_info_command_t info; /* object information */
3106 func_table_command_t func; /* function constructors/destructors */
3107 } load_union_t;
3109 /* Structure to point to load command and data section in memory. */
3111 typedef struct load_all
3113 load_union_t *load; /* load command */
3114 char *section; /* pointer to section */
3115 } load_all_t;
3117 /* Structure to contain information about a file mapped into memory. */
3119 struct file_info
3121 char *start; /* start of map */
3122 char *name; /* filename */
3123 long size; /* size of the file */
3124 long rounded_size; /* size rounded to page boundary */
3125 int fd; /* file descriptor */
3126 int rw; /* != 0 if opened read/write */
3127 int use_mmap; /* != 0 if mmap'ed */
3130 extern int decode_mach_o_hdr ();
3131 extern int encode_mach_o_hdr ();
3133 static void add_func_table PROTO((mo_header_t *, load_all_t *,
3134 symbol_info_t *, int));
3135 static void print_header PROTO((mo_header_t *));
3136 static void print_load_command PROTO((load_union_t *, size_t, int));
3137 static void bad_header PROTO((int));
3138 static struct file_info *read_file PROTO((char *, int, int));
3139 static void end_file PROTO((struct file_info *));
3141 /* OSF/rose specific version to scan the name list of the loaded
3142 program for the symbols g++ uses for static constructors and
3143 destructors.
3145 The constructor table begins at __CTOR_LIST__ and contains a count
3146 of the number of pointers (or -1 if the constructors are built in a
3147 separate section by the linker), followed by the pointers to the
3148 constructor functions, terminated with a null pointer. The
3149 destructor table has the same format, and begins at __DTOR_LIST__. */
3151 static void
3152 scan_prog_file (prog_name, which_pass)
3153 char *prog_name;
3154 enum pass which_pass;
3156 char *obj;
3157 mo_header_t hdr;
3158 load_all_t *load_array;
3159 load_all_t *load_end;
3160 load_all_t *load_cmd;
3161 int symbol_load_cmds;
3162 off_t offset;
3163 int i;
3164 int num_syms;
3165 int status;
3166 char *str_sect;
3167 struct file_info *obj_file;
3168 int prog_fd;
3169 mo_lcid_t cmd_strings = -1;
3170 symbol_info_t *main_sym = 0;
3171 int rw = (which_pass != PASS_FIRST);
3173 prog_fd = open (prog_name, (rw) ? O_RDWR : O_RDONLY);
3174 if (prog_fd < 0)
3175 fatal_perror ("cannot read %s", prog_name);
3177 obj_file = read_file (prog_name, prog_fd, rw);
3178 obj = obj_file->start;
3180 status = decode_mach_o_hdr (obj, MO_SIZEOF_RAW_HDR, MOH_HEADER_VERSION, &hdr);
3181 if (status != MO_HDR_CONV_SUCCESS)
3182 bad_header (status);
3185 /* Do some basic sanity checks. Note we explicitly use the big endian magic number,
3186 since the hardware will automatically swap bytes for us on loading little endian
3187 integers. */
3189 #ifndef CROSS_COMPILE
3190 if (hdr.moh_magic != MOH_MAGIC_MSB
3191 || hdr.moh_header_version != MOH_HEADER_VERSION
3192 || hdr.moh_byte_order != OUR_BYTE_ORDER
3193 || hdr.moh_data_rep_id != OUR_DATA_REP_ID
3194 || hdr.moh_cpu_type != OUR_CPU_TYPE
3195 || hdr.moh_cpu_subtype != OUR_CPU_SUBTYPE
3196 || hdr.moh_vendor_type != OUR_VENDOR_TYPE)
3198 fatal ("incompatibilities between object file & expected values");
3200 #endif
3202 if (debug)
3203 print_header (&hdr);
3205 offset = hdr.moh_first_cmd_off;
3206 load_end = load_array
3207 = (load_all_t *) xcalloc (sizeof (load_all_t), hdr.moh_n_load_cmds + 2);
3209 /* Build array of load commands, calculating the offsets */
3210 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3212 load_union_t *load_hdr; /* load command header */
3214 load_cmd = load_end++;
3215 load_hdr = (load_union_t *) (obj + offset);
3217 /* If modifying the program file, copy the header. */
3218 if (rw)
3220 load_union_t *ptr = (load_union_t *) xmalloc (load_hdr->hdr.ldci_cmd_size);
3221 bcopy ((char *)load_hdr, (char *)ptr, load_hdr->hdr.ldci_cmd_size);
3222 load_hdr = ptr;
3224 /* null out old command map, because we will rewrite at the end. */
3225 if (ptr->hdr.ldci_cmd_type == LDC_CMD_MAP)
3227 cmd_strings = ptr->map.lcm_ld_cmd_strings;
3228 ptr->hdr.ldci_cmd_type = LDC_UNDEFINED;
3232 load_cmd->load = load_hdr;
3233 if (load_hdr->hdr.ldci_section_off > 0)
3234 load_cmd->section = obj + load_hdr->hdr.ldci_section_off;
3236 if (debug)
3237 print_load_command (load_hdr, offset, i);
3239 offset += load_hdr->hdr.ldci_cmd_size;
3242 /* If the last command is the load command map and is not undefined,
3243 decrement the count of load commands. */
3244 if (rw && load_end[-1].load->hdr.ldci_cmd_type == LDC_UNDEFINED)
3246 load_end--;
3247 hdr.moh_n_load_cmds--;
3250 /* Go through and process each symbol table section. */
3251 symbol_load_cmds = 0;
3252 for (load_cmd = load_array; load_cmd < load_end; load_cmd++)
3254 load_union_t *load_hdr = load_cmd->load;
3256 if (load_hdr->hdr.ldci_cmd_type == LDC_SYMBOLS)
3258 symbol_load_cmds++;
3260 if (debug)
3262 char *kind = "unknown";
3264 switch (load_hdr->sym.symc_kind)
3266 case SYMC_IMPORTS: kind = "imports"; break;
3267 case SYMC_DEFINED_SYMBOLS: kind = "defined"; break;
3268 case SYMC_STABS: kind = "stabs"; break;
3271 fprintf (stderr, "\nProcessing symbol table #%d, offset = 0x%.8lx, kind = %s\n",
3272 symbol_load_cmds, load_hdr->hdr.ldci_section_off, kind);
3275 if (load_hdr->sym.symc_kind != SYMC_DEFINED_SYMBOLS)
3276 continue;
3278 str_sect = load_array[load_hdr->sym.symc_strings_section].section;
3279 if (str_sect == (char *) 0)
3280 fatal ("string section missing");
3282 if (load_cmd->section == (char *) 0)
3283 fatal ("section pointer missing");
3285 num_syms = load_hdr->sym.symc_nentries;
3286 for (i = 0; i < num_syms; i++)
3288 symbol_info_t *sym = ((symbol_info_t *) load_cmd->section) + i;
3289 char *name = sym->si_name.symbol_name + str_sect;
3291 if (name[0] != '_')
3292 continue;
3294 if (rw)
3296 char *n = name + strlen (name) - strlen (NAME__MAIN);
3298 if ((n - name) < 0 || strcmp (n, NAME__MAIN))
3299 continue;
3300 while (n != name)
3301 if (*--n != '_')
3302 continue;
3304 main_sym = sym;
3306 else
3308 switch (is_ctor_dtor (name))
3310 case 1:
3311 add_to_list (&constructors, name);
3312 break;
3314 case 2:
3315 add_to_list (&destructors, name);
3316 break;
3318 default: /* not a constructor or destructor */
3319 continue;
3323 if (debug)
3324 fprintf (stderr, "\ttype = 0x%.4x, sc = 0x%.2x, flags = 0x%.8x, name = %.30s\n",
3325 sym->si_type, sym->si_sc_type, sym->si_flags, name);
3330 if (symbol_load_cmds == 0)
3331 fatal ("no symbol table found");
3333 /* Update the program file now, rewrite header and load commands. At present,
3334 we assume that there is enough space after the last load command to insert
3335 one more. Since the first section written out is page aligned, and the
3336 number of load commands is small, this is ok for the present. */
3338 if (rw)
3340 load_union_t *load_map;
3341 size_t size;
3343 if (cmd_strings == -1)
3344 fatal ("no cmd_strings found");
3346 /* Add __main to initializer list.
3347 If we are building a program instead of a shared library, do not
3348 do anything, since in the current version, you cannot do mallocs
3349 and such in the constructors. */
3351 if (main_sym != (symbol_info_t *) 0
3352 && ((hdr.moh_flags & MOH_EXECABLE_F) == 0))
3353 add_func_table (&hdr, load_array, main_sym, FNTC_INITIALIZATION);
3355 if (debug)
3356 fprintf (stderr, "\nUpdating header and load commands.\n\n");
3358 hdr.moh_n_load_cmds++;
3359 size = sizeof (load_cmd_map_command_t) + (sizeof (mo_offset_t) * (hdr.moh_n_load_cmds - 1));
3361 /* Create new load command map. */
3362 if (debug)
3363 fprintf (stderr, "load command map, %d cmds, new size %ld.\n",
3364 (int)hdr.moh_n_load_cmds, (long)size);
3366 load_map = (load_union_t *) xcalloc (1, size);
3367 load_map->map.ldc_header.ldci_cmd_type = LDC_CMD_MAP;
3368 load_map->map.ldc_header.ldci_cmd_size = size;
3369 load_map->map.lcm_ld_cmd_strings = cmd_strings;
3370 load_map->map.lcm_nentries = hdr.moh_n_load_cmds;
3371 load_array[hdr.moh_n_load_cmds-1].load = load_map;
3373 offset = hdr.moh_first_cmd_off;
3374 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3376 load_map->map.lcm_map[i] = offset;
3377 if (load_array[i].load->hdr.ldci_cmd_type == LDC_CMD_MAP)
3378 hdr.moh_load_map_cmd_off = offset;
3380 offset += load_array[i].load->hdr.ldci_cmd_size;
3383 hdr.moh_sizeofcmds = offset - MO_SIZEOF_RAW_HDR;
3385 if (debug)
3386 print_header (&hdr);
3388 /* Write header */
3389 status = encode_mach_o_hdr (&hdr, obj, MO_SIZEOF_RAW_HDR);
3390 if (status != MO_HDR_CONV_SUCCESS)
3391 bad_header (status);
3393 if (debug)
3394 fprintf (stderr, "writing load commands.\n\n");
3396 /* Write load commands */
3397 offset = hdr.moh_first_cmd_off;
3398 for (i = 0; i < hdr.moh_n_load_cmds; i++)
3400 load_union_t *load_hdr = load_array[i].load;
3401 size_t size = load_hdr->hdr.ldci_cmd_size;
3403 if (debug)
3404 print_load_command (load_hdr, offset, i);
3406 bcopy ((char *) load_hdr, (char *) (obj + offset), size);
3407 offset += size;
3411 end_file (obj_file);
3413 if (close (prog_fd))
3414 fatal_perror ("closing %s", prog_name);
3416 if (debug)
3417 fprintf (stderr, "\n");
3421 /* Add a function table to the load commands to call a function
3422 on initiation or termination of the process. */
3424 static void
3425 add_func_table (hdr_p, load_array, sym, type)
3426 mo_header_t *hdr_p; /* pointer to global header */
3427 load_all_t *load_array; /* array of ptrs to load cmds */
3428 symbol_info_t *sym; /* pointer to symbol entry */
3429 int type; /* fntc_type value */
3431 /* Add a new load command. */
3432 int num_cmds = ++hdr_p->moh_n_load_cmds;
3433 int load_index = num_cmds - 1;
3434 size_t size = sizeof (func_table_command_t) + sizeof (mo_addr_t);
3435 load_union_t *ptr = xcalloc (1, size);
3436 load_all_t *load_cmd;
3437 int i;
3439 /* Set the unresolved address bit in the header to force the loader to be
3440 used, since kernel exec does not call the initialization functions. */
3441 hdr_p->moh_flags |= MOH_UNRESOLVED_F;
3443 load_cmd = &load_array[load_index];
3444 load_cmd->load = ptr;
3445 load_cmd->section = (char *) 0;
3447 /* Fill in func table load command. */
3448 ptr->func.ldc_header.ldci_cmd_type = LDC_FUNC_TABLE;
3449 ptr->func.ldc_header.ldci_cmd_size = size;
3450 ptr->func.ldc_header.ldci_section_off = 0;
3451 ptr->func.ldc_header.ldci_section_len = 0;
3452 ptr->func.fntc_type = type;
3453 ptr->func.fntc_nentries = 1;
3455 /* copy address, turn it from abs. address to (region,offset) if necessary. */
3456 /* Is the symbol already expressed as (region, offset)? */
3457 if ((sym->si_flags & SI_ABSOLUTE_VALUE_F) == 0)
3459 ptr->func.fntc_entry_loc[i].adr_lcid = sym->si_value.def_val.adr_lcid;
3460 ptr->func.fntc_entry_loc[i].adr_sctoff = sym->si_value.def_val.adr_sctoff;
3463 /* If not, figure out which region it's in. */
3464 else
3466 mo_vm_addr_t addr = sym->si_value.abs_val;
3467 int found = 0;
3469 for (i = 0; i < load_index; i++)
3471 if (load_array[i].load->hdr.ldci_cmd_type == LDC_REGION)
3473 region_command_t *region_ptr = &load_array[i].load->region;
3475 if ((region_ptr->regc_flags & REG_ABS_ADDR_F) != 0
3476 && addr >= region_ptr->regc_addr.vm_addr
3477 && addr <= region_ptr->regc_addr.vm_addr + region_ptr->regc_vm_size)
3479 ptr->func.fntc_entry_loc[0].adr_lcid = i;
3480 ptr->func.fntc_entry_loc[0].adr_sctoff = addr - region_ptr->regc_addr.vm_addr;
3481 found++;
3482 break;
3487 if (!found)
3488 fatal ("could not convert 0x%l.8x into a region", addr);
3491 if (debug)
3492 fprintf (stderr,
3493 "%s function, region %d, offset = %ld (0x%.8lx)\n",
3494 (type == FNTC_INITIALIZATION) ? "init" : "term",
3495 (int)ptr->func.fntc_entry_loc[i].adr_lcid,
3496 (long)ptr->func.fntc_entry_loc[i].adr_sctoff,
3497 (long)ptr->func.fntc_entry_loc[i].adr_sctoff);
3502 /* Print the global header for an OSF/rose object. */
3504 static void
3505 print_header (hdr_ptr)
3506 mo_header_t *hdr_ptr;
3508 fprintf (stderr, "\nglobal header:\n");
3509 fprintf (stderr, "\tmoh_magic = 0x%.8lx\n", hdr_ptr->moh_magic);
3510 fprintf (stderr, "\tmoh_major_version = %d\n", (int)hdr_ptr->moh_major_version);
3511 fprintf (stderr, "\tmoh_minor_version = %d\n", (int)hdr_ptr->moh_minor_version);
3512 fprintf (stderr, "\tmoh_header_version = %d\n", (int)hdr_ptr->moh_header_version);
3513 fprintf (stderr, "\tmoh_max_page_size = %d\n", (int)hdr_ptr->moh_max_page_size);
3514 fprintf (stderr, "\tmoh_byte_order = %d\n", (int)hdr_ptr->moh_byte_order);
3515 fprintf (stderr, "\tmoh_data_rep_id = %d\n", (int)hdr_ptr->moh_data_rep_id);
3516 fprintf (stderr, "\tmoh_cpu_type = %d\n", (int)hdr_ptr->moh_cpu_type);
3517 fprintf (stderr, "\tmoh_cpu_subtype = %d\n", (int)hdr_ptr->moh_cpu_subtype);
3518 fprintf (stderr, "\tmoh_vendor_type = %d\n", (int)hdr_ptr->moh_vendor_type);
3519 fprintf (stderr, "\tmoh_load_map_cmd_off = %d\n", (int)hdr_ptr->moh_load_map_cmd_off);
3520 fprintf (stderr, "\tmoh_first_cmd_off = %d\n", (int)hdr_ptr->moh_first_cmd_off);
3521 fprintf (stderr, "\tmoh_sizeofcmds = %d\n", (int)hdr_ptr->moh_sizeofcmds);
3522 fprintf (stderr, "\tmon_n_load_cmds = %d\n", (int)hdr_ptr->moh_n_load_cmds);
3523 fprintf (stderr, "\tmoh_flags = 0x%.8lx", (long)hdr_ptr->moh_flags);
3525 if (hdr_ptr->moh_flags & MOH_RELOCATABLE_F)
3526 fprintf (stderr, ", relocatable");
3528 if (hdr_ptr->moh_flags & MOH_LINKABLE_F)
3529 fprintf (stderr, ", linkable");
3531 if (hdr_ptr->moh_flags & MOH_EXECABLE_F)
3532 fprintf (stderr, ", execable");
3534 if (hdr_ptr->moh_flags & MOH_EXECUTABLE_F)
3535 fprintf (stderr, ", executable");
3537 if (hdr_ptr->moh_flags & MOH_UNRESOLVED_F)
3538 fprintf (stderr, ", unresolved");
3540 fprintf (stderr, "\n\n");
3541 return;
3545 /* Print a short summary of a load command. */
3547 static void
3548 print_load_command (load_hdr, offset, number)
3549 load_union_t *load_hdr;
3550 size_t offset;
3551 int number;
3553 mo_long_t type = load_hdr->hdr.ldci_cmd_type;
3554 char *type_str = (char *) 0;
3556 switch (type)
3558 case LDC_UNDEFINED: type_str = "UNDEFINED"; break;
3559 case LDC_CMD_MAP: type_str = "CMD_MAP"; break;
3560 case LDC_INTERPRETER: type_str = "INTERPRETER"; break;
3561 case LDC_STRINGS: type_str = "STRINGS"; break;
3562 case LDC_REGION: type_str = "REGION"; break;
3563 case LDC_RELOC: type_str = "RELOC"; break;
3564 case LDC_PACKAGE: type_str = "PACKAGE"; break;
3565 case LDC_SYMBOLS: type_str = "SYMBOLS"; break;
3566 case LDC_ENTRY: type_str = "ENTRY"; break;
3567 case LDC_FUNC_TABLE: type_str = "FUNC_TABLE"; break;
3568 case LDC_GEN_INFO: type_str = "GEN_INFO"; break;
3571 fprintf (stderr,
3572 "cmd %2d, sz: 0x%.2lx, coff: 0x%.3lx, doff: 0x%.6lx, dlen: 0x%.6lx",
3573 number,
3574 (long) load_hdr->hdr.ldci_cmd_size,
3575 (long) offset,
3576 (long) load_hdr->hdr.ldci_section_off,
3577 (long) load_hdr->hdr.ldci_section_len);
3579 if (type_str == (char *) 0)
3580 fprintf (stderr, ", ty: unknown (%ld)\n", (long) type);
3582 else if (type != LDC_REGION)
3583 fprintf (stderr, ", ty: %s\n", type_str);
3585 else
3587 char *region = "";
3588 switch (load_hdr->region.regc_usage_type)
3590 case REG_TEXT_T: region = ", .text"; break;
3591 case REG_DATA_T: region = ", .data"; break;
3592 case REG_BSS_T: region = ", .bss"; break;
3593 case REG_GLUE_T: region = ", .glue"; break;
3594 #if defined (REG_RDATA_T) && defined (REG_SDATA_T) && defined (REG_SBSS_T) /*mips*/
3595 case REG_RDATA_T: region = ", .rdata"; break;
3596 case REG_SDATA_T: region = ", .sdata"; break;
3597 case REG_SBSS_T: region = ", .sbss"; break;
3598 #endif
3601 fprintf (stderr, ", ty: %s, vaddr: 0x%.8lx, vlen: 0x%.6lx%s\n",
3602 type_str,
3603 (long) load_hdr->region.regc_vm_addr,
3604 (long) load_hdr->region.regc_vm_size,
3605 region);
3608 return;
3612 /* Fatal error when {en,de}code_mach_o_header fails. */
3614 static void
3615 bad_header (status)
3616 int status;
3618 char *msg = (char *) 0;
3620 switch (status)
3622 case MO_ERROR_BAD_MAGIC: msg = "bad magic number"; break;
3623 case MO_ERROR_BAD_HDR_VERS: msg = "bad header version"; break;
3624 case MO_ERROR_BAD_RAW_HDR_VERS: msg = "bad raw header version"; break;
3625 case MO_ERROR_BUF2SML: msg = "raw header buffer too small"; break;
3626 case MO_ERROR_OLD_RAW_HDR_FILE: msg = "old raw header file"; break;
3627 case MO_ERROR_UNSUPPORTED_VERS: msg = "unsupported version"; break;
3630 if (msg == (char *) 0)
3631 fatal ("unknown {de,en}code_mach_o_hdr return value %d", status);
3632 else
3633 fatal ("%s", msg);
3637 /* Read a file into a memory buffer. */
3639 static struct file_info *
3640 read_file (name, fd, rw)
3641 char *name; /* filename */
3642 int fd; /* file descriptor */
3643 int rw; /* read/write */
3645 struct stat stat_pkt;
3646 struct file_info *p = (struct file_info *) xcalloc (sizeof (struct file_info), 1);
3647 #ifdef USE_MMAP
3648 static int page_size;
3649 #endif
3651 if (fstat (fd, &stat_pkt) < 0)
3652 fatal_perror ("fstat %s", name);
3654 p->name = name;
3655 p->size = stat_pkt.st_size;
3656 p->rounded_size = stat_pkt.st_size;
3657 p->fd = fd;
3658 p->rw = rw;
3660 #ifdef USE_MMAP
3661 if (debug)
3662 fprintf (stderr, "mmap %s, %s\n", name, (rw) ? "read/write" : "read-only");
3664 if (page_size == 0)
3665 page_size = sysconf (_SC_PAGE_SIZE);
3667 p->rounded_size = ((p->size + page_size - 1) / page_size) * page_size;
3668 p->start = mmap ((caddr_t) 0,
3669 (rw) ? p->rounded_size : p->size,
3670 (rw) ? (PROT_READ | PROT_WRITE) : PROT_READ,
3671 MAP_FILE | MAP_VARIABLE | MAP_SHARED,
3673 0L);
3675 if (p->start != (char *) 0 && p->start != (char *) -1)
3676 p->use_mmap = 1;
3678 else
3679 #endif /* USE_MMAP */
3681 long len;
3683 if (debug)
3684 fprintf (stderr, "read %s\n", name);
3686 p->use_mmap = 0;
3687 p->start = xmalloc (p->size);
3688 if (lseek (fd, 0L, SEEK_SET) < 0)
3689 fatal_perror ("lseek to 0 on %s", name);
3691 len = read (fd, p->start, p->size);
3692 if (len < 0)
3693 fatal_perror ("read %s", name);
3695 if (len != p->size)
3696 fatal ("read %ld bytes, expected %ld, from %s", len, p->size, name);
3699 return p;
3702 /* Do anything necessary to write a file back from memory. */
3704 static void
3705 end_file (ptr)
3706 struct file_info *ptr; /* file information block */
3708 #ifdef USE_MMAP
3709 if (ptr->use_mmap)
3711 if (ptr->rw)
3713 if (debug)
3714 fprintf (stderr, "msync %s\n", ptr->name);
3716 if (msync (ptr->start, ptr->rounded_size, MS_ASYNC))
3717 fatal_perror ("msync %s", ptr->name);
3720 if (debug)
3721 fprintf (stderr, "munmap %s\n", ptr->name);
3723 if (munmap (ptr->start, ptr->size))
3724 fatal_perror ("munmap %s", ptr->name);
3726 else
3727 #endif /* USE_MMAP */
3729 if (ptr->rw)
3731 long len;
3733 if (debug)
3734 fprintf (stderr, "write %s\n", ptr->name);
3736 if (lseek (ptr->fd, 0L, SEEK_SET) < 0)
3737 fatal_perror ("lseek to 0 on %s", ptr->name);
3739 len = write (ptr->fd, ptr->start, ptr->size);
3740 if (len < 0)
3741 fatal_perror ("write %s", ptr->name);
3743 if (len != ptr->size)
3744 fatal ("wrote %ld bytes, expected %ld, to %s", len, ptr->size, ptr->name);
3747 free (ptr->start);
3750 free (ptr);
3753 #endif /* OBJECT_FORMAT_ROSE */