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