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