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