ld/
[external/binutils.git] / ld / ldmain.c
1 /* Main program of GNU linker.
2    Copyright 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3    2002, 2003, 2004
4    Free Software Foundation, Inc.
5    Written by Steve Chamberlain steve@cygnus.com
6
7    This file is part of GLD, the Gnu Linker.
8
9    GLD is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2, or (at your option)
12    any later version.
13
14    GLD is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with GLD; see the file COPYING.  If not, write to the Free
21    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22    02111-1307, USA.  */
23
24 #include "bfd.h"
25 #include "sysdep.h"
26 #include <stdio.h>
27 #include "safe-ctype.h"
28 #include "libiberty.h"
29 #include "progress.h"
30 #include "bfdlink.h"
31 #include "filenames.h"
32
33 #include "ld.h"
34 #include "ldmain.h"
35 #include "ldmisc.h"
36 #include "ldwrite.h"
37 #include "ldexp.h"
38 #include "ldlang.h"
39 #include <ldgram.h>
40 #include "ldlex.h"
41 #include "ldfile.h"
42 #include "ldemul.h"
43 #include "ldctor.h"
44
45 /* Somewhere above, sys/stat.h got included.  */
46 #if !defined(S_ISDIR) && defined(S_IFDIR)
47 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
48 #endif
49
50 #include <string.h>
51
52 #ifdef HAVE_SBRK
53 #ifdef NEED_DECLARATION_SBRK
54 extern void *sbrk ();
55 #endif
56 #endif
57
58 #ifndef TARGET_SYSTEM_ROOT
59 #define TARGET_SYSTEM_ROOT ""
60 #endif
61
62 /* EXPORTS */
63
64 char *default_target;
65 const char *output_filename = "a.out";
66
67 /* Name this program was invoked by.  */
68 char *program_name;
69
70 /* The prefix for system library directories.  */
71 char *ld_sysroot;
72
73 /* The canonical representation of ld_sysroot.  */
74 char * ld_canon_sysroot;
75 int ld_canon_sysroot_len;
76
77 /* The file that we're creating.  */
78 bfd *output_bfd = 0;
79
80 /* Set by -G argument, for MIPS ECOFF target.  */
81 int g_switch_value = 8;
82
83 /* Nonzero means print names of input files as processed.  */
84 bfd_boolean trace_files;
85
86 /* Nonzero means same, but note open failures, too.  */
87 bfd_boolean trace_file_tries;
88
89 /* Nonzero means version number was printed, so exit successfully
90    instead of complaining if no input files are given.  */
91 bfd_boolean version_printed;
92
93 /* Nonzero means link in every member of an archive.  */
94 bfd_boolean whole_archive;
95
96 /* Nonzero means create DT_NEEDED entries only if a dynamic library
97    actually satisfies some reference in a regular object.  */
98 bfd_boolean as_needed;
99
100 /* Nonzero means never create DT_NEEDED entries for dynamic libraries
101    in DT_NEEDED tags.  */
102 bfd_boolean add_needed = TRUE;
103
104 /* TRUE if we should demangle symbol names.  */
105 bfd_boolean demangling;
106
107 args_type command_line;
108
109 ld_config_type config;
110
111 sort_type sort_section;
112
113 static char *get_emulation
114   (int, char **);
115 static void set_scripts_dir
116   (void);
117 static bfd_boolean add_archive_element
118   (struct bfd_link_info *, bfd *, const char *);
119 static bfd_boolean multiple_definition
120   (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma,
121    bfd *, asection *, bfd_vma);
122 static bfd_boolean multiple_common
123   (struct bfd_link_info *, const char *, bfd *, enum bfd_link_hash_type,
124    bfd_vma, bfd *, enum bfd_link_hash_type, bfd_vma);
125 static bfd_boolean add_to_set
126   (struct bfd_link_info *, struct bfd_link_hash_entry *,
127    bfd_reloc_code_real_type, bfd *, asection *, bfd_vma);
128 static bfd_boolean constructor_callback
129   (struct bfd_link_info *, bfd_boolean, const char *, bfd *,
130    asection *, bfd_vma);
131 static bfd_boolean warning_callback
132   (struct bfd_link_info *, const char *, const char *, bfd *,
133    asection *, bfd_vma);
134 static void warning_find_reloc
135   (bfd *, asection *, void *);
136 static bfd_boolean undefined_symbol
137   (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma,
138    bfd_boolean);
139 static bfd_boolean reloc_overflow
140   (struct bfd_link_info *, const char *, const char *, bfd_vma,
141    bfd *, asection *, bfd_vma);
142 static bfd_boolean reloc_dangerous
143   (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma);
144 static bfd_boolean unattached_reloc
145   (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma);
146 static bfd_boolean notice
147   (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma);
148
149 static struct bfd_link_callbacks link_callbacks =
150 {
151   add_archive_element,
152   multiple_definition,
153   multiple_common,
154   add_to_set,
155   constructor_callback,
156   warning_callback,
157   undefined_symbol,
158   reloc_overflow,
159   reloc_dangerous,
160   unattached_reloc,
161   notice
162 };
163
164 struct bfd_link_info link_info;
165 \f
166 static void
167 remove_output (void)
168 {
169   if (output_filename)
170     {
171       if (output_bfd)
172         bfd_cache_close (output_bfd);
173       if (delete_output_file_on_failure)
174         unlink (output_filename);
175     }
176 }
177
178 int
179 main (int argc, char **argv)
180 {
181   char *emulation;
182   long start_time = get_run_time ();
183
184 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
185   setlocale (LC_MESSAGES, "");
186 #endif
187 #if defined (HAVE_SETLOCALE)
188   setlocale (LC_CTYPE, "");
189 #endif
190   bindtextdomain (PACKAGE, LOCALEDIR);
191   textdomain (PACKAGE);
192
193   program_name = argv[0];
194   xmalloc_set_program_name (program_name);
195
196   START_PROGRESS (program_name, 0);
197
198   bfd_init ();
199
200   bfd_set_error_program_name (program_name);
201
202   xatexit (remove_output);
203
204 #ifdef TARGET_SYSTEM_ROOT_RELOCATABLE
205   ld_sysroot = make_relative_prefix (program_name, BINDIR,
206                                      TARGET_SYSTEM_ROOT);
207
208   if (ld_sysroot)
209     {
210       struct stat s;
211       int res = stat (ld_sysroot, &s) == 0 && S_ISDIR (s.st_mode);
212
213       if (!res)
214         {
215           free (ld_sysroot);
216           ld_sysroot = NULL;
217         }
218     }
219
220   if (! ld_sysroot)
221     {
222       ld_sysroot = make_relative_prefix (program_name, TOOLBINDIR,
223                                          TARGET_SYSTEM_ROOT);
224
225       if (ld_sysroot)
226         {
227           struct stat s;
228           int res = stat (ld_sysroot, &s) == 0 && S_ISDIR (s.st_mode);
229
230           if (!res)
231             {
232               free (ld_sysroot);
233               ld_sysroot = NULL;
234             }
235         }
236     }
237
238   if (! ld_sysroot)
239 #endif
240     ld_sysroot = TARGET_SYSTEM_ROOT;
241
242   if (ld_sysroot && *ld_sysroot)
243     ld_canon_sysroot = lrealpath (ld_sysroot);
244
245   if (ld_canon_sysroot)
246     ld_canon_sysroot_len = strlen (ld_canon_sysroot);
247   else
248     ld_canon_sysroot_len = -1;
249
250   /* Set the default BFD target based on the configured target.  Doing
251      this permits the linker to be configured for a particular target,
252      and linked against a shared BFD library which was configured for
253      a different target.  The macro TARGET is defined by Makefile.  */
254   if (! bfd_set_default_target (TARGET))
255     {
256       einfo (_("%X%P: can't set BFD default target to `%s': %E\n"), TARGET);
257       xexit (1);
258     }
259
260 #if YYDEBUG
261   {
262     extern int yydebug;
263     yydebug = 1;
264   }
265 #endif
266
267   /* Initialize the data about options.  */
268   trace_files = trace_file_tries = version_printed = FALSE;
269   whole_archive = FALSE;
270   config.build_constructors = TRUE;
271   config.dynamic_link = FALSE;
272   config.has_shared = FALSE;
273   config.split_by_reloc = (unsigned) -1;
274   config.split_by_file = (bfd_size_type) -1;
275   config.hash_table_size = 0;
276   command_line.force_common_definition = FALSE;
277   command_line.inhibit_common_definition = FALSE;
278   command_line.interpreter = NULL;
279   command_line.rpath = NULL;
280   command_line.warn_mismatch = TRUE;
281   command_line.check_section_addresses = TRUE;
282   command_line.accept_unknown_input_arch = FALSE;
283   command_line.reduce_memory_overheads = FALSE;
284
285   sort_section = none;
286
287   /* We initialize DEMANGLING based on the environment variable
288      COLLECT_NO_DEMANGLE.  The gcc collect2 program will demangle the
289      output of the linker, unless COLLECT_NO_DEMANGLE is set in the
290      environment.  Acting the same way here lets us provide the same
291      interface by default.  */
292   demangling = getenv ("COLLECT_NO_DEMANGLE") == NULL;
293
294   link_info.relocatable = FALSE;
295   link_info.emitrelocations = FALSE;
296   link_info.task_link = FALSE;
297   link_info.shared = FALSE;
298   link_info.pie = FALSE;
299   link_info.executable = FALSE;
300   link_info.symbolic = FALSE;
301   link_info.export_dynamic = FALSE;
302   link_info.static_link = FALSE;
303   link_info.traditional_format = FALSE;
304   link_info.optimize = FALSE;
305   link_info.unresolved_syms_in_objects = RM_NOT_YET_SET;
306   link_info.unresolved_syms_in_shared_libs = RM_NOT_YET_SET;
307   link_info.allow_multiple_definition = FALSE;
308   link_info.allow_undefined_version = TRUE;
309   link_info.keep_memory = TRUE;
310   link_info.notice_all = FALSE;
311   link_info.nocopyreloc = FALSE;
312   link_info.new_dtags = FALSE;
313   link_info.combreloc = TRUE;
314   link_info.eh_frame_hdr = FALSE;
315   link_info.relro = FALSE;
316   link_info.strip_discarded = TRUE;
317   link_info.strip = strip_none;
318   link_info.discard = discard_sec_merge;
319   link_info.common_skip_ar_aymbols = bfd_link_common_skip_none;
320   link_info.callbacks = &link_callbacks;
321   link_info.hash = NULL;
322   link_info.keep_hash = NULL;
323   link_info.notice_hash = NULL;
324   link_info.wrap_hash = NULL;
325   link_info.input_bfds = NULL;
326   link_info.create_object_symbols_section = NULL;
327   link_info.gc_sym_list = NULL;
328   link_info.base_file = NULL;
329   /* SVR4 linkers seem to set DT_INIT and DT_FINI based on magic _init
330      and _fini symbols.  We are compatible.  */
331   link_info.init_function = "_init";
332   link_info.fini_function = "_fini";
333   link_info.pei386_auto_import = -1;
334   link_info.pei386_runtime_pseudo_reloc = FALSE;
335   link_info.spare_dynamic_tags = 5;
336   link_info.flags = 0;
337   link_info.flags_1 = 0;
338   link_info.need_relax_finalize = FALSE;
339
340   ldfile_add_arch ("");
341
342   config.make_executable = TRUE;
343   force_make_executable = FALSE;
344   config.magic_demand_paged = TRUE;
345   config.text_read_only = TRUE;
346
347   emulation = get_emulation (argc, argv);
348   ldemul_choose_mode (emulation);
349   default_target = ldemul_choose_target (argc, argv);
350   lang_init ();
351   ldemul_before_parse ();
352   lang_has_input_file = FALSE;
353   parse_args (argc, argv);
354
355   if (config.hash_table_size != 0)
356     bfd_hash_set_default_size (config.hash_table_size);
357
358   ldemul_set_symbols ();
359
360   if (link_info.relocatable)
361     {
362       if (command_line.gc_sections)
363         einfo ("%P%F: --gc-sections and -r may not be used together\n");
364       else if (command_line.relax)
365         einfo (_("%P%F: --relax and -r may not be used together\n"));
366       if (link_info.shared)
367         einfo (_("%P%F: -r and -shared may not be used together\n"));
368     }
369
370   if (! link_info.shared)
371     {
372       if (command_line.filter_shlib)
373         einfo (_("%P%F: -F may not be used without -shared\n"));
374       if (command_line.auxiliary_filters)
375         einfo (_("%P%F: -f may not be used without -shared\n"));
376     }
377
378   if (! link_info.shared || link_info.pie)
379     link_info.executable = TRUE;
380
381   /* Treat ld -r -s as ld -r -S -x (i.e., strip all local symbols).  I
382      don't see how else this can be handled, since in this case we
383      must preserve all externally visible symbols.  */
384   if (link_info.relocatable && link_info.strip == strip_all)
385     {
386       link_info.strip = strip_debugger;
387       if (link_info.discard == discard_sec_merge)
388         link_info.discard = discard_all;
389     }
390
391   /* This essentially adds another -L directory so this must be done after
392      the -L's in argv have been processed.  */
393   set_scripts_dir ();
394
395   /* If we have not already opened and parsed a linker script
396      read the emulation's appropriate default script.  */
397   if (saved_script_handle == NULL)
398     {
399       int isfile;
400       char *s = ldemul_get_script (&isfile);
401
402       if (isfile)
403         ldfile_open_command_file (s);
404       else
405         {
406           lex_string = s;
407           lex_redirect (s);
408         }
409       parser_input = input_script;
410       yyparse ();
411       lex_string = NULL;
412     }
413
414   if (trace_file_tries)
415     {
416       if (saved_script_handle)
417         info_msg (_("using external linker script:"));
418       else
419         info_msg (_("using internal linker script:"));
420       info_msg ("\n==================================================\n");
421
422       if (saved_script_handle)
423         {
424           static const int ld_bufsz = 8193;
425           size_t n;
426           char *buf = xmalloc (ld_bufsz);
427
428           rewind (saved_script_handle);
429           while ((n = fread (buf, 1, ld_bufsz - 1, saved_script_handle)) > 0)
430             {
431               buf[n] = 0;
432               info_msg (buf);
433             }
434           rewind (saved_script_handle);
435           free (buf);
436         }
437       else
438         {
439           int isfile;
440
441           info_msg (ldemul_get_script (&isfile));
442         }
443
444       info_msg ("\n==================================================\n");
445     }
446
447   lang_final ();
448
449   if (!lang_has_input_file)
450     {
451       if (version_printed)
452         xexit (0);
453       einfo (_("%P%F: no input files\n"));
454     }
455
456   if (trace_files)
457     info_msg (_("%P: mode %s\n"), emulation);
458
459   ldemul_after_parse ();
460
461   if (config.map_filename)
462     {
463       if (strcmp (config.map_filename, "-") == 0)
464         {
465           config.map_file = stdout;
466         }
467       else
468         {
469           config.map_file = fopen (config.map_filename, FOPEN_WT);
470           if (config.map_file == (FILE *) NULL)
471             {
472               bfd_set_error (bfd_error_system_call);
473               einfo (_("%P%F: cannot open map file %s: %E\n"),
474                      config.map_filename);
475             }
476         }
477     }
478
479   lang_process ();
480
481   /* Print error messages for any missing symbols, for any warning
482      symbols, and possibly multiple definitions.  */
483   if (link_info.relocatable)
484     output_bfd->flags &= ~EXEC_P;
485   else
486     output_bfd->flags |= EXEC_P;
487
488   ldwrite ();
489
490   if (config.map_file != NULL)
491     lang_map ();
492   if (command_line.cref)
493     output_cref (config.map_file != NULL ? config.map_file : stdout);
494   if (nocrossref_list != NULL)
495     check_nocrossrefs ();
496
497   /* Even if we're producing relocatable output, some non-fatal errors should
498      be reported in the exit status.  (What non-fatal errors, if any, do we
499      want to ignore for relocatable output?)  */
500   if (!config.make_executable && !force_make_executable)
501     {
502       if (trace_files)
503         einfo (_("%P: link errors found, deleting executable `%s'\n"),
504                output_filename);
505
506       /* The file will be removed by remove_output.  */
507       xexit (1);
508     }
509   else
510     {
511       if (! bfd_close (output_bfd))
512         einfo (_("%F%B: final close failed: %E\n"), output_bfd);
513
514       /* If the --force-exe-suffix is enabled, and we're making an
515          executable file and it doesn't end in .exe, copy it to one
516          which does.  */
517       if (! link_info.relocatable && command_line.force_exe_suffix)
518         {
519           int len = strlen (output_filename);
520
521           if (len < 4
522               || (strcasecmp (output_filename + len - 4, ".exe") != 0
523                   && strcasecmp (output_filename + len - 4, ".dll") != 0))
524             {
525               FILE *src;
526               FILE *dst;
527               const int bsize = 4096;
528               char *buf = xmalloc (bsize);
529               int l;
530               char *dst_name = xmalloc (len + 5);
531
532               strcpy (dst_name, output_filename);
533               strcat (dst_name, ".exe");
534               src = fopen (output_filename, FOPEN_RB);
535               dst = fopen (dst_name, FOPEN_WB);
536
537               if (!src)
538                 einfo (_("%X%P: unable to open for source of copy `%s'\n"),
539                        output_filename);
540               if (!dst)
541                 einfo (_("%X%P: unable to open for destination of copy `%s'\n"),
542                        dst_name);
543               while ((l = fread (buf, 1, bsize, src)) > 0)
544                 {
545                   int done = fwrite (buf, 1, l, dst);
546
547                   if (done != l)
548                     einfo (_("%P: Error writing file `%s'\n"), dst_name);
549                 }
550
551               fclose (src);
552               if (fclose (dst) == EOF)
553                 einfo (_("%P: Error closing file `%s'\n"), dst_name);
554               free (dst_name);
555               free (buf);
556             }
557         }
558     }
559
560   END_PROGRESS (program_name);
561
562   if (config.stats)
563     {
564 #ifdef HAVE_SBRK
565       char *lim = sbrk (0);
566 #endif
567       long run_time = get_run_time () - start_time;
568
569       fprintf (stderr, _("%s: total time in link: %ld.%06ld\n"),
570                program_name, run_time / 1000000, run_time % 1000000);
571 #ifdef HAVE_SBRK
572       fprintf (stderr, _("%s: data size %ld\n"), program_name,
573                (long) (lim - (char *) &environ));
574 #endif
575     }
576
577   /* Prevent remove_output from doing anything, after a successful link.  */
578   output_filename = NULL;
579
580   xexit (0);
581   return 0;
582 }
583
584 /* We need to find any explicitly given emulation in order to initialize the
585    state that's needed by the lex&yacc argument parser (parse_args).  */
586
587 static char *
588 get_emulation (int argc, char **argv)
589 {
590   char *emulation;
591   int i;
592
593   emulation = getenv (EMULATION_ENVIRON);
594   if (emulation == NULL)
595     emulation = DEFAULT_EMULATION;
596
597   for (i = 1; i < argc; i++)
598     {
599       if (!strncmp (argv[i], "-m", 2))
600         {
601           if (argv[i][2] == '\0')
602             {
603               /* -m EMUL */
604               if (i < argc - 1)
605                 {
606                   emulation = argv[i + 1];
607                   i++;
608                 }
609               else
610                 einfo (_("%P%F: missing argument to -m\n"));
611             }
612           else if (strcmp (argv[i], "-mips1") == 0
613                    || strcmp (argv[i], "-mips2") == 0
614                    || strcmp (argv[i], "-mips3") == 0
615                    || strcmp (argv[i], "-mips4") == 0
616                    || strcmp (argv[i], "-mips5") == 0
617                    || strcmp (argv[i], "-mips32") == 0
618                    || strcmp (argv[i], "-mips32r2") == 0
619                    || strcmp (argv[i], "-mips64") == 0
620                    || strcmp (argv[i], "-mips64r2") == 0)
621             {
622               /* FIXME: The arguments -mips1, -mips2, -mips3, etc. are
623                  passed to the linker by some MIPS compilers.  They
624                  generally tell the linker to use a slightly different
625                  library path.  Perhaps someday these should be
626                  implemented as emulations; until then, we just ignore
627                  the arguments and hope that nobody ever creates
628                  emulations named ips1, ips2 or ips3.  */
629             }
630           else if (strcmp (argv[i], "-m486") == 0)
631             {
632               /* FIXME: The argument -m486 is passed to the linker on
633                  some Linux systems.  Hope that nobody creates an
634                  emulation named 486.  */
635             }
636           else
637             {
638               /* -mEMUL */
639               emulation = &argv[i][2];
640             }
641         }
642     }
643
644   return emulation;
645 }
646
647 /* If directory DIR contains an "ldscripts" subdirectory,
648    add DIR to the library search path and return TRUE,
649    else return FALSE.  */
650
651 static bfd_boolean
652 check_for_scripts_dir (char *dir)
653 {
654   size_t dirlen;
655   char *buf;
656   struct stat s;
657   bfd_boolean res;
658
659   dirlen = strlen (dir);
660   /* sizeof counts the terminating NUL.  */
661   buf = xmalloc (dirlen + sizeof ("/ldscripts"));
662   sprintf (buf, "%s/ldscripts", dir);
663
664   res = stat (buf, &s) == 0 && S_ISDIR (s.st_mode);
665   free (buf);
666   if (res)
667     ldfile_add_library_path (dir, FALSE);
668   return res;
669 }
670
671 /* Set the default directory for finding script files.
672    Libraries will be searched for here too, but that's ok.
673    We look for the "ldscripts" directory in:
674
675    SCRIPTDIR (passed from Makefile)
676              (adjusted according to the current location of the binary)
677    SCRIPTDIR (passed from Makefile)
678    the dir where this program is (for using it from the build tree)
679    the dir where this program is/../lib
680              (for installing the tool suite elsewhere).  */
681
682 static void
683 set_scripts_dir (void)
684 {
685   char *end, *dir;
686   size_t dirlen;
687   bfd_boolean found;
688
689   dir = make_relative_prefix (program_name, BINDIR, SCRIPTDIR);
690   if (dir)
691     {
692       found = check_for_scripts_dir (dir);
693       free (dir);
694       if (found)
695         return;
696     }
697
698   dir = make_relative_prefix (program_name, TOOLBINDIR, SCRIPTDIR);
699   if (dir)
700     {
701       found = check_for_scripts_dir (dir);
702       free (dir);
703       if (found)
704         return;
705     }
706
707   if (check_for_scripts_dir (SCRIPTDIR))
708     /* We've been installed normally.  */
709     return;
710
711   /* Look for "ldscripts" in the dir where our binary is.  */
712   end = strrchr (program_name, '/');
713 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
714   {
715     /* We could have \foo\bar, or /foo\bar.  */
716     char *bslash = strrchr (program_name, '\\');
717
718     if (end == NULL || (bslash != NULL && bslash > end))
719       end = bslash;
720   }
721 #endif
722
723   if (end == NULL)
724     /* Don't look for ldscripts in the current directory.  There is
725        too much potential for confusion.  */
726     return;
727
728   dirlen = end - program_name;
729   /* Make a copy of program_name in dir.
730      Leave room for later "/../lib".  */
731   dir = xmalloc (dirlen + 8);
732   strncpy (dir, program_name, dirlen);
733   dir[dirlen] = '\0';
734
735   if (check_for_scripts_dir (dir))
736     {
737       free (dir);
738       return;
739     }
740
741   /* Look for "ldscripts" in <the dir where our binary is>/../lib.  */
742   strcpy (dir + dirlen, "/../lib");
743   check_for_scripts_dir (dir);
744   free (dir);
745 }
746
747 void
748 add_ysym (const char *name)
749 {
750   if (link_info.notice_hash == NULL)
751     {
752       link_info.notice_hash = xmalloc (sizeof (struct bfd_hash_table));
753       if (! bfd_hash_table_init_n (link_info.notice_hash,
754                                    bfd_hash_newfunc,
755                                    61))
756         einfo (_("%P%F: bfd_hash_table_init failed: %E\n"));
757     }
758
759   if (bfd_hash_lookup (link_info.notice_hash, name, TRUE, TRUE) == NULL)
760     einfo (_("%P%F: bfd_hash_lookup failed: %E\n"));
761 }
762
763 /* Record a symbol to be wrapped, from the --wrap option.  */
764
765 void
766 add_wrap (const char *name)
767 {
768   if (link_info.wrap_hash == NULL)
769     {
770       link_info.wrap_hash = xmalloc (sizeof (struct bfd_hash_table));
771       if (! bfd_hash_table_init_n (link_info.wrap_hash,
772                                    bfd_hash_newfunc,
773                                    61))
774         einfo (_("%P%F: bfd_hash_table_init failed: %E\n"));
775     }
776
777   if (bfd_hash_lookup (link_info.wrap_hash, name, TRUE, TRUE) == NULL)
778     einfo (_("%P%F: bfd_hash_lookup failed: %E\n"));
779 }
780
781 /* Handle the -retain-symbols-file option.  */
782
783 void
784 add_keepsyms_file (const char *filename)
785 {
786   FILE *file;
787   char *buf;
788   size_t bufsize;
789   int c;
790
791   if (link_info.strip == strip_some)
792     einfo (_("%X%P: error: duplicate retain-symbols-file\n"));
793
794   file = fopen (filename, "r");
795   if (file == NULL)
796     {
797       bfd_set_error (bfd_error_system_call);
798       einfo ("%X%P: %s: %E\n", filename);
799       return;
800     }
801
802   link_info.keep_hash = xmalloc (sizeof (struct bfd_hash_table));
803   if (! bfd_hash_table_init (link_info.keep_hash, bfd_hash_newfunc))
804     einfo (_("%P%F: bfd_hash_table_init failed: %E\n"));
805
806   bufsize = 100;
807   buf = xmalloc (bufsize);
808
809   c = getc (file);
810   while (c != EOF)
811     {
812       while (ISSPACE (c))
813         c = getc (file);
814
815       if (c != EOF)
816         {
817           size_t len = 0;
818
819           while (! ISSPACE (c) && c != EOF)
820             {
821               buf[len] = c;
822               ++len;
823               if (len >= bufsize)
824                 {
825                   bufsize *= 2;
826                   buf = xrealloc (buf, bufsize);
827                 }
828               c = getc (file);
829             }
830
831           buf[len] = '\0';
832
833           if (bfd_hash_lookup (link_info.keep_hash, buf, TRUE, TRUE) == NULL)
834             einfo (_("%P%F: bfd_hash_lookup for insertion failed: %E\n"));
835         }
836     }
837
838   if (link_info.strip != strip_none)
839     einfo (_("%P: `-retain-symbols-file' overrides `-s' and `-S'\n"));
840
841   free (buf);
842   link_info.strip = strip_some;
843 }
844 \f
845 /* Callbacks from the BFD linker routines.  */
846
847 /* This is called when BFD has decided to include an archive member in
848    a link.  */
849
850 static bfd_boolean
851 add_archive_element (struct bfd_link_info *info ATTRIBUTE_UNUSED,
852                      bfd *abfd,
853                      const char *name)
854 {
855   lang_input_statement_type *input;
856
857   input = xmalloc (sizeof (lang_input_statement_type));
858   input->filename = abfd->filename;
859   input->local_sym_name = abfd->filename;
860   input->the_bfd = abfd;
861   input->asymbols = NULL;
862   input->next = NULL;
863   input->just_syms_flag = FALSE;
864   input->loaded = FALSE;
865   input->search_dirs_flag = FALSE;
866
867   /* FIXME: The following fields are not set: header.next,
868      header.type, closed, passive_position, symbol_count,
869      next_real_file, is_archive, target, real.  This bit of code is
870      from the old decode_library_subfile function.  I don't know
871      whether any of those fields matters.  */
872
873   ldlang_add_file (input);
874
875   if (config.map_file != NULL)
876     {
877       static bfd_boolean header_printed;
878       struct bfd_link_hash_entry *h;
879       bfd *from;
880       int len;
881
882       h = bfd_link_hash_lookup (link_info.hash, name, FALSE, FALSE, TRUE);
883
884       if (h == NULL)
885         from = NULL;
886       else
887         {
888           switch (h->type)
889             {
890             default:
891               from = NULL;
892               break;
893
894             case bfd_link_hash_defined:
895             case bfd_link_hash_defweak:
896               from = h->u.def.section->owner;
897               break;
898
899             case bfd_link_hash_undefined:
900             case bfd_link_hash_undefweak:
901               from = h->u.undef.abfd;
902               break;
903
904             case bfd_link_hash_common:
905               from = h->u.c.p->section->owner;
906               break;
907             }
908         }
909
910       if (! header_printed)
911         {
912           char buf[100];
913
914           sprintf (buf, _("Archive member included because of file (symbol)\n\n"));
915           minfo ("%s", buf);
916           header_printed = TRUE;
917         }
918
919       if (bfd_my_archive (abfd) == NULL)
920         {
921           minfo ("%s", bfd_get_filename (abfd));
922           len = strlen (bfd_get_filename (abfd));
923         }
924       else
925         {
926           minfo ("%s(%s)", bfd_get_filename (bfd_my_archive (abfd)),
927                  bfd_get_filename (abfd));
928           len = (strlen (bfd_get_filename (bfd_my_archive (abfd)))
929                  + strlen (bfd_get_filename (abfd))
930                  + 2);
931         }
932
933       if (len >= 29)
934         {
935           print_nl ();
936           len = 0;
937         }
938       while (len < 30)
939         {
940           print_space ();
941           ++len;
942         }
943
944       if (from != NULL)
945         minfo ("%B ", from);
946       if (h != NULL)
947         minfo ("(%T)\n", h->root.string);
948       else
949         minfo ("(%s)\n", name);
950     }
951
952   if (trace_files || trace_file_tries)
953     info_msg ("%I\n", input);
954
955   return TRUE;
956 }
957
958 /* This is called when BFD has discovered a symbol which is defined
959    multiple times.  */
960
961 static bfd_boolean
962 multiple_definition (struct bfd_link_info *info ATTRIBUTE_UNUSED,
963                      const char *name,
964                      bfd *obfd,
965                      asection *osec,
966                      bfd_vma oval,
967                      bfd *nbfd,
968                      asection *nsec,
969                      bfd_vma nval)
970 {
971   /* If either section has the output_section field set to
972      bfd_abs_section_ptr, it means that the section is being
973      discarded, and this is not really a multiple definition at all.
974      FIXME: It would be cleaner to somehow ignore symbols defined in
975      sections which are being discarded.  */
976   if ((osec->output_section != NULL
977        && ! bfd_is_abs_section (osec)
978        && bfd_is_abs_section (osec->output_section))
979       || (nsec->output_section != NULL
980           && ! bfd_is_abs_section (nsec)
981           && bfd_is_abs_section (nsec->output_section)))
982     return TRUE;
983
984   einfo (_("%X%C: multiple definition of `%T'\n"),
985          nbfd, nsec, nval, name);
986   if (obfd != NULL)
987     einfo (_("%D: first defined here\n"), obfd, osec, oval);
988
989   if (command_line.relax)
990     {
991       einfo (_("%P: Disabling relaxation: it will not work with multiple definitions\n"));
992       command_line.relax = 0;
993     }
994
995   return TRUE;
996 }
997
998 /* This is called when there is a definition of a common symbol, or
999    when a common symbol is found for a symbol that is already defined,
1000    or when two common symbols are found.  We only do something if
1001    -warn-common was used.  */
1002
1003 static bfd_boolean
1004 multiple_common (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1005                  const char *name,
1006                  bfd *obfd,
1007                  enum bfd_link_hash_type otype,
1008                  bfd_vma osize,
1009                  bfd *nbfd,
1010                  enum bfd_link_hash_type ntype,
1011                  bfd_vma nsize)
1012 {
1013   if (! config.warn_common)
1014     return TRUE;
1015
1016   if (ntype == bfd_link_hash_defined
1017       || ntype == bfd_link_hash_defweak
1018       || ntype == bfd_link_hash_indirect)
1019     {
1020       ASSERT (otype == bfd_link_hash_common);
1021       einfo (_("%B: warning: definition of `%T' overriding common\n"),
1022              nbfd, name);
1023       if (obfd != NULL)
1024         einfo (_("%B: warning: common is here\n"), obfd);
1025     }
1026   else if (otype == bfd_link_hash_defined
1027            || otype == bfd_link_hash_defweak
1028            || otype == bfd_link_hash_indirect)
1029     {
1030       ASSERT (ntype == bfd_link_hash_common);
1031       einfo (_("%B: warning: common of `%T' overridden by definition\n"),
1032              nbfd, name);
1033       if (obfd != NULL)
1034         einfo (_("%B: warning: defined here\n"), obfd);
1035     }
1036   else
1037     {
1038       ASSERT (otype == bfd_link_hash_common && ntype == bfd_link_hash_common);
1039       if (osize > nsize)
1040         {
1041           einfo (_("%B: warning: common of `%T' overridden by larger common\n"),
1042                  nbfd, name);
1043           if (obfd != NULL)
1044             einfo (_("%B: warning: larger common is here\n"), obfd);
1045         }
1046       else if (nsize > osize)
1047         {
1048           einfo (_("%B: warning: common of `%T' overriding smaller common\n"),
1049                  nbfd, name);
1050           if (obfd != NULL)
1051             einfo (_("%B: warning: smaller common is here\n"), obfd);
1052         }
1053       else
1054         {
1055           einfo (_("%B: warning: multiple common of `%T'\n"), nbfd, name);
1056           if (obfd != NULL)
1057             einfo (_("%B: warning: previous common is here\n"), obfd);
1058         }
1059     }
1060
1061   return TRUE;
1062 }
1063
1064 /* This is called when BFD has discovered a set element.  H is the
1065    entry in the linker hash table for the set.  SECTION and VALUE
1066    represent a value which should be added to the set.  */
1067
1068 static bfd_boolean
1069 add_to_set (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1070             struct bfd_link_hash_entry *h,
1071             bfd_reloc_code_real_type reloc,
1072             bfd *abfd,
1073             asection *section,
1074             bfd_vma value)
1075 {
1076   if (config.warn_constructors)
1077     einfo (_("%P: warning: global constructor %s used\n"),
1078            h->root.string);
1079
1080   if (! config.build_constructors)
1081     return TRUE;
1082
1083   ldctor_add_set_entry (h, reloc, NULL, section, value);
1084
1085   if (h->type == bfd_link_hash_new)
1086     {
1087       h->type = bfd_link_hash_undefined;
1088       h->u.undef.abfd = abfd;
1089       /* We don't call bfd_link_add_undef to add this to the list of
1090          undefined symbols because we are going to define it
1091          ourselves.  */
1092     }
1093
1094   return TRUE;
1095 }
1096
1097 /* This is called when BFD has discovered a constructor.  This is only
1098    called for some object file formats--those which do not handle
1099    constructors in some more clever fashion.  This is similar to
1100    adding an element to a set, but less general.  */
1101
1102 static bfd_boolean
1103 constructor_callback (struct bfd_link_info *info,
1104                       bfd_boolean constructor,
1105                       const char *name,
1106                       bfd *abfd,
1107                       asection *section,
1108                       bfd_vma value)
1109 {
1110   char *s;
1111   struct bfd_link_hash_entry *h;
1112   char set_name[1 + sizeof "__CTOR_LIST__"];
1113
1114   if (config.warn_constructors)
1115     einfo (_("%P: warning: global constructor %s used\n"), name);
1116
1117   if (! config.build_constructors)
1118     return TRUE;
1119
1120   /* Ensure that BFD_RELOC_CTOR exists now, so that we can give a
1121      useful error message.  */
1122   if (bfd_reloc_type_lookup (output_bfd, BFD_RELOC_CTOR) == NULL
1123       && (link_info.relocatable
1124           || bfd_reloc_type_lookup (abfd, BFD_RELOC_CTOR) == NULL))
1125     einfo (_("%P%F: BFD backend error: BFD_RELOC_CTOR unsupported\n"));
1126
1127   s = set_name;
1128   if (bfd_get_symbol_leading_char (abfd) != '\0')
1129     *s++ = bfd_get_symbol_leading_char (abfd);
1130   if (constructor)
1131     strcpy (s, "__CTOR_LIST__");
1132   else
1133     strcpy (s, "__DTOR_LIST__");
1134
1135   h = bfd_link_hash_lookup (info->hash, set_name, TRUE, TRUE, TRUE);
1136   if (h == (struct bfd_link_hash_entry *) NULL)
1137     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
1138   if (h->type == bfd_link_hash_new)
1139     {
1140       h->type = bfd_link_hash_undefined;
1141       h->u.undef.abfd = abfd;
1142       /* We don't call bfd_link_add_undef to add this to the list of
1143          undefined symbols because we are going to define it
1144          ourselves.  */
1145     }
1146
1147   ldctor_add_set_entry (h, BFD_RELOC_CTOR, name, section, value);
1148   return TRUE;
1149 }
1150
1151 /* A structure used by warning_callback to pass information through
1152    bfd_map_over_sections.  */
1153
1154 struct warning_callback_info
1155 {
1156   bfd_boolean found;
1157   const char *warning;
1158   const char *symbol;
1159   asymbol **asymbols;
1160 };
1161
1162 /* This is called when there is a reference to a warning symbol.  */
1163
1164 static bfd_boolean
1165 warning_callback (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1166                   const char *warning,
1167                   const char *symbol,
1168                   bfd *abfd,
1169                   asection *section,
1170                   bfd_vma address)
1171 {
1172   /* This is a hack to support warn_multiple_gp.  FIXME: This should
1173      have a cleaner interface, but what?  */
1174   if (! config.warn_multiple_gp
1175       && strcmp (warning, "using multiple gp values") == 0)
1176     return TRUE;
1177
1178   if (section != NULL)
1179     einfo ("%C: %s\n", abfd, section, address, warning);
1180   else if (abfd == NULL)
1181     einfo ("%P: %s\n", warning);
1182   else if (symbol == NULL)
1183     einfo ("%B: %s\n", abfd, warning);
1184   else
1185     {
1186       lang_input_statement_type *entry;
1187       asymbol **asymbols;
1188       struct warning_callback_info info;
1189
1190       /* Look through the relocs to see if we can find a plausible
1191          address.  */
1192       entry = (lang_input_statement_type *) abfd->usrdata;
1193       if (entry != NULL && entry->asymbols != NULL)
1194         asymbols = entry->asymbols;
1195       else
1196         {
1197           long symsize;
1198           long symbol_count;
1199
1200           symsize = bfd_get_symtab_upper_bound (abfd);
1201           if (symsize < 0)
1202             einfo (_("%B%F: could not read symbols: %E\n"), abfd);
1203           asymbols = xmalloc (symsize);
1204           symbol_count = bfd_canonicalize_symtab (abfd, asymbols);
1205           if (symbol_count < 0)
1206             einfo (_("%B%F: could not read symbols: %E\n"), abfd);
1207           if (entry != NULL)
1208             {
1209               entry->asymbols = asymbols;
1210               entry->symbol_count = symbol_count;
1211             }
1212         }
1213
1214       info.found = FALSE;
1215       info.warning = warning;
1216       info.symbol = symbol;
1217       info.asymbols = asymbols;
1218       bfd_map_over_sections (abfd, warning_find_reloc, &info);
1219
1220       if (! info.found)
1221         einfo ("%B: %s\n", abfd, warning);
1222
1223       if (entry == NULL)
1224         free (asymbols);
1225     }
1226
1227   return TRUE;
1228 }
1229
1230 /* This is called by warning_callback for each section.  It checks the
1231    relocs of the section to see if it can find a reference to the
1232    symbol which triggered the warning.  If it can, it uses the reloc
1233    to give an error message with a file and line number.  */
1234
1235 static void
1236 warning_find_reloc (bfd *abfd, asection *sec, void *iarg)
1237 {
1238   struct warning_callback_info *info = iarg;
1239   long relsize;
1240   arelent **relpp;
1241   long relcount;
1242   arelent **p, **pend;
1243
1244   if (info->found)
1245     return;
1246
1247   relsize = bfd_get_reloc_upper_bound (abfd, sec);
1248   if (relsize < 0)
1249     einfo (_("%B%F: could not read relocs: %E\n"), abfd);
1250   if (relsize == 0)
1251     return;
1252
1253   relpp = xmalloc (relsize);
1254   relcount = bfd_canonicalize_reloc (abfd, sec, relpp, info->asymbols);
1255   if (relcount < 0)
1256     einfo (_("%B%F: could not read relocs: %E\n"), abfd);
1257
1258   p = relpp;
1259   pend = p + relcount;
1260   for (; p < pend && *p != NULL; p++)
1261     {
1262       arelent *q = *p;
1263
1264       if (q->sym_ptr_ptr != NULL
1265           && *q->sym_ptr_ptr != NULL
1266           && strcmp (bfd_asymbol_name (*q->sym_ptr_ptr), info->symbol) == 0)
1267         {
1268           /* We found a reloc for the symbol we are looking for.  */
1269           einfo ("%C: %s\n", abfd, sec, q->address, info->warning);
1270           info->found = TRUE;
1271           break;
1272         }
1273     }
1274
1275   free (relpp);
1276 }
1277
1278 /* This is called when an undefined symbol is found.  */
1279
1280 static bfd_boolean
1281 undefined_symbol (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1282                   const char *name,
1283                   bfd *abfd,
1284                   asection *section,
1285                   bfd_vma address,
1286                   bfd_boolean error)
1287 {
1288   static char *error_name;
1289   static unsigned int error_count;
1290
1291 #define MAX_ERRORS_IN_A_ROW 5
1292
1293   if (config.warn_once)
1294     {
1295       static struct bfd_hash_table *hash;
1296
1297       /* Only warn once about a particular undefined symbol.  */
1298       if (hash == NULL)
1299         {
1300           hash = xmalloc (sizeof (struct bfd_hash_table));
1301           if (! bfd_hash_table_init (hash, bfd_hash_newfunc))
1302             einfo (_("%F%P: bfd_hash_table_init failed: %E\n"));
1303         }
1304
1305       if (bfd_hash_lookup (hash, name, FALSE, FALSE) != NULL)
1306         return TRUE;
1307
1308       if (bfd_hash_lookup (hash, name, TRUE, TRUE) == NULL)
1309         einfo (_("%F%P: bfd_hash_lookup failed: %E\n"));
1310     }
1311
1312   /* We never print more than a reasonable number of errors in a row
1313      for a single symbol.  */
1314   if (error_name != NULL
1315       && strcmp (name, error_name) == 0)
1316     ++error_count;
1317   else
1318     {
1319       error_count = 0;
1320       if (error_name != NULL)
1321         free (error_name);
1322       error_name = xstrdup (name);
1323     }
1324
1325   if (section != NULL)
1326     {
1327       if (error_count < MAX_ERRORS_IN_A_ROW)
1328         {
1329           if (error)
1330             einfo (_("%X%C: undefined reference to `%T'\n"),
1331                    abfd, section, address, name);
1332           else
1333             einfo (_("%C: warning: undefined reference to `%T'\n"),
1334                    abfd, section, address, name);
1335         }
1336       else if (error_count == MAX_ERRORS_IN_A_ROW)
1337         {
1338           if (error)
1339             einfo (_("%X%D: more undefined references to `%T' follow\n"),
1340                    abfd, section, address, name);
1341           else
1342             einfo (_("%D: warning: more undefined references to `%T' follow\n"),
1343                    abfd, section, address, name);
1344         }
1345       else if (error)
1346         einfo ("%X");
1347     }
1348   else
1349     {
1350       if (error_count < MAX_ERRORS_IN_A_ROW)
1351         {
1352           if (error)
1353             einfo (_("%X%B: undefined reference to `%T'\n"),
1354                    abfd, name);
1355           else
1356             einfo (_("%B: warning: undefined reference to `%T'\n"),
1357                    abfd, name);
1358         }
1359       else if (error_count == MAX_ERRORS_IN_A_ROW)
1360         {
1361           if (error)
1362             einfo (_("%X%B: more undefined references to `%T' follow\n"),
1363                    abfd, name);
1364           else
1365             einfo (_("%B: warning: more undefined references to `%T' follow\n"),
1366                    abfd, name);
1367         }
1368       else if (error)
1369         einfo ("%X");
1370     }
1371
1372   return TRUE;
1373 }
1374
1375 /* Counter to limit the number of relocation overflow error messages
1376    to print.  Errors are printed as it is decremented.  When it's
1377    called and the counter is zero, a final message is printed
1378    indicating more relocations were omitted.  When it gets to -1, no
1379    such errors are printed.  If it's initially set to a value less
1380    than -1, all such errors will be printed (--verbose does this).  */
1381
1382 int overflow_cutoff_limit = 10;
1383
1384 /* This is called when a reloc overflows.  */
1385
1386 static bfd_boolean
1387 reloc_overflow (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1388                 const char *name,
1389                 const char *reloc_name,
1390                 bfd_vma addend,
1391                 bfd *abfd,
1392                 asection *section,
1393                 bfd_vma address)
1394 {
1395   if (overflow_cutoff_limit == -1)
1396     return TRUE;
1397
1398   if (abfd == NULL)
1399     einfo (_("%P%X: generated"));
1400   else
1401     einfo ("%X%C:", abfd, section, address);
1402
1403   if (overflow_cutoff_limit >= 0
1404       && overflow_cutoff_limit-- == 0)
1405     {
1406       einfo (_(" additional relocation overflows omitted from the output\n"));
1407       return TRUE;
1408     }
1409
1410   einfo (_(" relocation truncated to fit: %s %T"), reloc_name, name);
1411   if (addend != 0)
1412     einfo ("+%v", addend);
1413   einfo ("\n");
1414   return TRUE;
1415 }
1416
1417 /* This is called when a dangerous relocation is made.  */
1418
1419 static bfd_boolean
1420 reloc_dangerous (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1421                  const char *message,
1422                  bfd *abfd,
1423                  asection *section,
1424                  bfd_vma address)
1425 {
1426   if (abfd == NULL)
1427     einfo (_("%P%X: generated"));
1428   else
1429     einfo ("%X%C:", abfd, section, address);
1430   einfo (_("dangerous relocation: %s\n"), message);
1431   return TRUE;
1432 }
1433
1434 /* This is called when a reloc is being generated attached to a symbol
1435    that is not being output.  */
1436
1437 static bfd_boolean
1438 unattached_reloc (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1439                   const char *name,
1440                   bfd *abfd,
1441                   asection *section,
1442                   bfd_vma address)
1443 {
1444   if (abfd == NULL)
1445     einfo (_("%P%X: generated"));
1446   else
1447     einfo ("%X%C:", abfd, section, address);
1448   einfo (_(" reloc refers to symbol `%T' which is not being output\n"), name);
1449   return TRUE;
1450 }
1451
1452 /* This is called if link_info.notice_all is set, or when a symbol in
1453    link_info.notice_hash is found.  Symbols are put in notice_hash
1454    using the -y option.  */
1455
1456 static bfd_boolean
1457 notice (struct bfd_link_info *info,
1458         const char *name,
1459         bfd *abfd,
1460         asection *section,
1461         bfd_vma value)
1462 {
1463   if (! info->notice_all
1464       || (info->notice_hash != NULL
1465           && bfd_hash_lookup (info->notice_hash, name, FALSE, FALSE) != NULL))
1466     {
1467       if (bfd_is_und_section (section))
1468         einfo ("%B: reference to %s\n", abfd, name);
1469       else
1470         einfo ("%B: definition of %s\n", abfd, name);
1471     }
1472
1473   if (command_line.cref || nocrossref_list != NULL)
1474     add_cref (name, abfd, section, value);
1475
1476   return TRUE;
1477 }