]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - ld/ldmain.c
gas: introduce .errif and .warnif
[thirdparty/binutils-gdb.git] / ld / ldmain.c
... / ...
CommitLineData
1/* Main program of GNU linker.
2 Copyright (C) 1991-2025 Free Software Foundation, Inc.
3 Written by Steve Chamberlain steve@cygnus.com
4
5 This file is part of the GNU Binutils.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20 MA 02110-1301, USA. */
21
22#include "sysdep.h"
23#include "bfd.h"
24#include "bfdver.h"
25#include "safe-ctype.h"
26#include "libiberty.h"
27#include "bfdlink.h"
28#include "ctf-api.h"
29#include "filenames.h"
30#include "elf/common.h"
31
32#include "ld.h"
33#include "ldmain.h"
34#include "ldmisc.h"
35#include "ldwrite.h"
36#include "ldexp.h"
37#include "ldlang.h"
38#include <ldgram.h>
39#include "ldlex.h"
40#include "ldfile.h"
41#include "ldemul.h"
42#include "ldctor.h"
43#if BFD_SUPPORTS_PLUGINS
44#include "plugin.h"
45#include "plugin-api.h"
46#endif /* BFD_SUPPORTS_PLUGINS */
47
48/* Somewhere above, sys/stat.h got included. */
49#if !defined(S_ISDIR) && defined(S_IFDIR)
50#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
51#endif
52
53#include <string.h>
54
55#if defined (HAVE_GETRUSAGE)
56#include <sys/resource.h>
57#endif
58
59#ifndef TARGET_SYSTEM_ROOT
60#define TARGET_SYSTEM_ROOT ""
61#endif
62
63/* EXPORTS */
64
65FILE *saved_script_handle = NULL;
66FILE *previous_script_handle = NULL;
67bool force_make_executable = false;
68
69char *default_target;
70const char *output_filename = "a.out";
71
72/* Name this program was invoked by. */
73char *program_name;
74
75/* The prefix for system library directories. */
76const char *ld_sysroot;
77
78/* The canonical representation of ld_sysroot. */
79char *ld_canon_sysroot;
80int ld_canon_sysroot_len;
81
82/* Set by -G argument, for targets like MIPS ELF. */
83int g_switch_value = 8;
84
85/* Nonzero means print names of input files as processed. */
86unsigned int trace_files;
87
88/* Nonzero means report actions taken by the linker, and describe the linker script in use. */
89bool verbose;
90
91/* Nonzero means version number was printed, so exit successfully
92 instead of complaining if no input files are given. */
93bool version_printed;
94
95/* TRUE if we should demangle symbol names. */
96bool demangling;
97
98bool in_section_ordering;
99
100args_type command_line;
101
102ld_config_type config;
103
104sort_type sort_section;
105
106static const char *get_sysroot
107 (int, char **);
108static char *get_emulation
109 (int, char **);
110static bool add_archive_element
111 (struct bfd_link_info *, bfd *, const char *, bfd **);
112static void multiple_definition
113 (struct bfd_link_info *, struct bfd_link_hash_entry *,
114 bfd *, asection *, bfd_vma);
115static void multiple_common
116 (struct bfd_link_info *, struct bfd_link_hash_entry *,
117 bfd *, enum bfd_link_hash_type, bfd_vma);
118static void add_to_set
119 (struct bfd_link_info *, struct bfd_link_hash_entry *,
120 bfd_reloc_code_real_type, bfd *, asection *, bfd_vma);
121static void constructor_callback
122 (struct bfd_link_info *, bool, const char *, bfd *,
123 asection *, bfd_vma);
124static void warning_callback
125 (struct bfd_link_info *, const char *, const char *, bfd *,
126 asection *, bfd_vma);
127static void warning_find_reloc
128 (bfd *, asection *, void *);
129static void undefined_symbol
130 (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma,
131 bool);
132static void reloc_overflow
133 (struct bfd_link_info *, struct bfd_link_hash_entry *, const char *,
134 const char *, bfd_vma, bfd *, asection *, bfd_vma);
135static void reloc_dangerous
136 (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma);
137static void unattached_reloc
138 (struct bfd_link_info *, const char *, bfd *, asection *, bfd_vma);
139static bool notice
140 (struct bfd_link_info *, struct bfd_link_hash_entry *,
141 struct bfd_link_hash_entry *, bfd *, asection *, bfd_vma, flagword);
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 fatal,
157 einfo,
158 info_msg,
159 minfo,
160 ldlang_override_segment_assignment,
161 ldlang_ctf_acquire_strings,
162 NULL,
163 ldlang_ctf_new_dynsym,
164 ldlang_write_ctf_late
165};
166
167static bfd_assert_handler_type default_bfd_assert_handler;
168static bfd_error_handler_type default_bfd_error_handler;
169
170struct bfd_link_info link_info;
171\f
172struct dependency_file
173{
174 struct dependency_file *next;
175 char *name;
176};
177
178static struct dependency_file *dependency_files, *dependency_files_tail;
179
180void
181track_dependency_files (const char *filename)
182{
183 struct dependency_file *dep
184 = (struct dependency_file *) xmalloc (sizeof (*dep));
185 dep->name = xstrdup (filename);
186 dep->next = NULL;
187 if (dependency_files == NULL)
188 dependency_files = dep;
189 else
190 dependency_files_tail->next = dep;
191 dependency_files_tail = dep;
192}
193
194static void
195write_dependency_file (void)
196{
197 FILE *out;
198 struct dependency_file *dep;
199
200 out = fopen (config.dependency_file, FOPEN_WT);
201 if (out == NULL)
202 {
203 bfd_set_error (bfd_error_system_call);
204 fatal (_("%P: cannot open dependency file %s: %E\n"),
205 config.dependency_file);
206 }
207
208 fprintf (out, "%s:", output_filename);
209
210 for (dep = dependency_files; dep != NULL; dep = dep->next)
211 fprintf (out, " \\\n %s", dep->name);
212
213 fprintf (out, "\n");
214 for (dep = dependency_files; dep != NULL; dep = dep->next)
215 fprintf (out, "\n%s:\n", dep->name);
216
217 fclose (out);
218}
219\f
220static void
221ld_cleanup (void)
222{
223 bfd *ibfd, *inext;
224 if (link_info.output_bfd)
225 bfd_close_all_done (link_info.output_bfd);
226 for (ibfd = link_info.input_bfds; ibfd; ibfd = inext)
227 {
228 inext = ibfd->link.next;
229 bfd_close_all_done (ibfd);
230 }
231#if BFD_SUPPORTS_PLUGINS
232 /* Note - we do not call ld_plugin_start (PHASE_PLUGINS) here as this
233 function is only called when the linker is exiting - ie after any
234 stats may have been reported, and potentially in the middle of a
235 phase where we have already started recording plugin stats. */
236 plugin_call_cleanup ();
237#endif
238 if (output_filename && delete_output_file_on_failure)
239 unlink_if_ordinary (output_filename);
240}
241
242/* Hook to notice BFD assertions. */
243
244static void
245ld_bfd_assert_handler (const char *fmt, const char *bfdver,
246 const char *file, int line)
247{
248 config.make_executable = false;
249 (*default_bfd_assert_handler) (fmt, bfdver, file, line);
250}
251
252/* Hook the bfd error/warning handler for --fatal-warnings. */
253
254static void
255ld_bfd_error_handler (const char *fmt, va_list ap)
256{
257 if (config.fatal_warnings)
258 config.make_executable = false;
259 (*default_bfd_error_handler) (fmt, ap);
260}
261
262static void
263display_external_script (void)
264{
265 if (saved_script_handle == NULL)
266 return;
267
268 static const int ld_bufsz = 8193;
269 size_t n;
270 char *buf = (char *) xmalloc (ld_bufsz);
271
272 rewind (saved_script_handle);
273 while ((n = fread (buf, 1, ld_bufsz - 1, saved_script_handle)) > 0)
274 {
275 buf[n] = 0;
276 info_msg ("%s", buf);
277 }
278 rewind (saved_script_handle);
279 free (buf);
280}
281
282struct ld_phase_data
283{
284 const char * name;
285
286 unsigned long start;
287 unsigned long duration;
288
289 bool started;
290 bool broken;
291
292#if defined (HAVE_GETRUSAGE)
293 struct rusage begin;
294 struct rusage use;
295#endif
296};
297
298static struct ld_phase_data phase_data [NUM_PHASES] =
299{
300 [PHASE_ALL] = { .name = "ALL" },
301 [PHASE_CTF] = { .name = "ctf processing" },
302 [PHASE_MERGE] = { .name = "string merge" },
303 [PHASE_PARSE] = { .name = "parsing" },
304 [PHASE_PLUGINS] = { .name = "plugins" },
305 [PHASE_PROCESS] = { .name = "processing files" },
306 [PHASE_WRITE] = { .name = "write" },
307};
308
309void
310ld_start_phase (ld_phase phase)
311{
312 struct ld_phase_data * pd = phase_data + phase;
313
314 /* We record data even if config.stats_file is NULL. This allows
315 us to record data about phases that start before the command line
316 arguments have been parsed. ie PHASE_ALL and PHASE_PARSE. */
317
318 /* Do not overwrite the fields if we have already started recording. */
319 if (pd->started)
320 {
321 /* Since we do not queue phase starts and stops, if a phase is started
322 multiple times there is a likelyhood that it will be stopped multiple
323 times as well. This is problematic as we will only record the data
324 for the first time the phase stops and ignore all of the other stops.
325
326 So let the user know. Ideally real users will never actually see
327 this message, and instead only developers who are adding new phase
328 tracking code will ever encounter it. */
329 einfo ("%P: --stats: phase %s started twice - data may be unreliable\n",
330 pd->name);
331 return;
332 }
333
334 /* It is OK if other phases are also active at this point.
335 It just means that the phases overlap or that one phase is a sub-task
336 of another. Since we record resources on a per-phase basis, this
337 should not matter. */
338
339 pd->started = true;
340 pd->start = get_run_time ();
341
342#if defined (HAVE_GETRUSAGE)
343 /* Record the resource usage at the start of the phase. */
344 struct rusage usage;
345
346 if (getrusage (RUSAGE_SELF, & usage) != 0)
347 /* FIXME: Complain ? */
348 return;
349
350 memcpy (& pd->begin, & usage, sizeof usage);
351#endif
352}
353
354void
355ld_stop_phase (ld_phase phase)
356{
357 struct ld_phase_data * pd = phase_data + phase;
358
359 if (!pd->started)
360 {
361 /* We set the broken flag to indicate that the data
362 recorded for this phase is inconsistent. */
363 pd->broken = true;
364 return;
365 }
366
367 pd->duration += get_run_time () - pd->start;
368 pd->started = false;
369
370#if defined (HAVE_GETRUSAGE)
371 struct rusage usage;
372
373 if (getrusage (RUSAGE_SELF, & usage) != 0)
374 /* FIXME: Complain ? */
375 return;
376
377 if (phase == PHASE_ALL)
378 memcpy (& pd->use, & usage, sizeof usage);
379 else
380 {
381 struct timeval t;
382
383 /* For sub-phases we record the increase in specific fields. */
384 /* FIXME: Most rusage{} fields appear to be irrelevent to when considering
385 linker resource usage. Currently we record maxrss and user and system
386 cpu times. Are there any other fields that might be useful ? */
387
388#ifndef timeradd /* Macros copied from <sys/time.h>. */
389#define timeradd(a, b, result) \
390 do \
391 { \
392 (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
393 (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
394 if ((result)->tv_usec >= 1000000) \
395 { \
396 ++(result)->tv_sec; \
397 (result)->tv_usec -= 1000000; \
398 } \
399 } \
400 while (0)
401#endif
402
403#ifndef timersub
404#define timersub(a, b, result) \
405 do \
406 { \
407 (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
408 (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
409 if ((result)->tv_usec < 0) \
410 { \
411 --(result)->tv_sec; \
412 (result)->tv_usec += 1000000; \
413 } \
414 } \
415 while (0)
416#endif
417
418 timersub (& usage.ru_utime, & pd->begin.ru_utime, & t);
419 timeradd (& pd->use.ru_utime, &t, & pd->use.ru_utime);
420
421 timersub (& usage.ru_stime, & pd->begin.ru_stime, & t);
422 timeradd (& pd->use.ru_stime, &t, & pd->use.ru_stime);
423
424 if (pd->begin.ru_maxrss < usage.ru_maxrss)
425 pd->use.ru_maxrss += usage.ru_maxrss - pd->begin.ru_maxrss;
426 }
427#endif
428}
429
430static void
431report_phases (FILE * file, time_t * start, char ** argv)
432{
433 unsigned long i;
434
435 if (file == NULL)
436 return;
437
438 /* We might be writing to stdout, so make sure
439 that we do not have any pending error output. */
440 fflush (stderr);
441
442 /* We do not translate "Stats" as we provide this as a key
443 word that can be searched for by grep and the like. */
444#define STATS_PREFIX "Stats: "
445
446 fprintf (file, STATS_PREFIX "linker version: %s\n", BFD_VERSION_STRING);
447
448 /* No \n at the end of the string as ctime() provides its own. */
449 fprintf (file, STATS_PREFIX "linker started: %s", ctime (start));
450
451 /* We include the linker command line arguments since
452 they can be hard to track down by other means. */
453 if (argv != NULL)
454 {
455 fprintf (file, STATS_PREFIX "args: ");
456 for (i = 0; argv[i] != NULL; i++)
457 fprintf (file, "%s ", argv[i]);
458 fprintf (file, "\n\n"); /* Blank line to separate the args from the stats. */
459 }
460
461 /* All of this song and dance with the column_info struct and printf
462 formatting is so that we can have a nicely formated table with regular
463 column spacing, whilst allowing for the column headers to be translated,
464 and coping nicely with extra long strings or numbers. */
465 struct column_info
466 {
467 const char * header;
468 const char * sub_header;
469 int width;
470 int pad;
471 } columns[] =
472#define COLUMNS_FIELD(HEADER,SUBHEADER) \
473 { .header = N_( HEADER ), .sub_header = N_( SUBHEADER ) },
474 {
475 COLUMNS_FIELD ("phase", "name")
476 COLUMNS_FIELD ("cpu time", "(microsec)")
477#if defined (HAVE_GETRUSAGE)
478 /* Note: keep these columns in sync with the
479 information recorded in ld_stop_phase(). */
480 COLUMNS_FIELD ("memory", "(KiB)")
481 COLUMNS_FIELD ("user time", "(seconds)")
482 COLUMNS_FIELD ("system time", "(seconds)")
483#endif
484 };
485
486#ifndef max
487#define max(A,B) ((A) < (B) ? (B) : (A))
488#endif
489
490 size_t maxwidth = 1;
491 for (i = 0; i < NUM_PHASES; i++)
492 maxwidth = max (maxwidth, strlen (phase_data[i].name));
493
494 fprintf (file, "%s", STATS_PREFIX);
495
496 for (i = 0; i < ARRAY_SIZE (columns); i++)
497 {
498 int padding;
499
500 if (i == 0)
501 columns[i].width = fprintf (file, "%-*s", (int) maxwidth, columns[i].header);
502 else
503 columns[i].width = fprintf (file, "%s", columns[i].header);
504 padding = columns[i].width % 8;
505 if (padding < 4)
506 padding = 4;
507 columns[i].pad = fprintf (file, "%*c", padding, ' ');
508 }
509
510 fprintf (file, "\n");
511
512 int bias = 0;
513#define COLUMN_ENTRY(VAL, FORMAT, N) \
514 do \
515 { \
516 int l; \
517 \
518 if (N == 0) \
519 l = fprintf (file, "%-*" FORMAT, columns[N].width, VAL); \
520 else \
521 l = fprintf (file, "%*" FORMAT, columns[N].width - bias, VAL); \
522 bias = 0; \
523 if (l < columns[N].width) \
524 l = columns[N].pad; \
525 else if (l < columns[N].width + columns[N].pad) \
526 l = columns[N].pad - (l - columns[N].width); \
527 else \
528 { \
529 bias = l - (columns[N].width + columns[N].pad); \
530 l = 0; \
531 } \
532 if (l) \
533 fprintf (file, "%*c", l, ' '); \
534 } \
535 while (0)
536
537 fprintf (file, "%s", STATS_PREFIX);
538
539 for (i = 0; i < ARRAY_SIZE (columns); i++)
540 COLUMN_ENTRY (columns[i].sub_header, "s", i);
541
542 fprintf (file, "\n");
543
544 for (i = 0; i < NUM_PHASES; i++)
545 {
546 struct ld_phase_data * pd = phase_data + i;
547 /* This should not be needed... */
548 const char * name = pd->name ? pd->name : "<unnamed>";
549
550 if (pd->broken)
551 {
552 fprintf (file, "%s %s: %s",
553 STATS_PREFIX, name, _("WARNING: Data is unreliable!\n"));
554 continue;
555 }
556
557 fprintf (file, "%s", STATS_PREFIX);
558
559 /* Care must be taken to keep the lines below in sync with
560 entries in the columns_info array.
561 FIXME: There ought to be a better way to do this... */
562 COLUMN_ENTRY (name, "s", 0);
563 COLUMN_ENTRY (pd->duration, "ld", 1);
564#if defined (HAVE_GETRUSAGE)
565 COLUMN_ENTRY (pd->use.ru_maxrss, "ld", 2);
566 COLUMN_ENTRY ((int64_t) pd->use.ru_utime.tv_sec, PRId64, 3);
567 COLUMN_ENTRY ((int64_t) pd->use.ru_stime.tv_sec, PRId64, 4);
568#endif
569 fprintf (file, "\n");
570 }
571
572 fflush (file);
573}
574
575int
576main (int argc, char **argv)
577{
578 char *emulation;
579 long start_time = get_run_time ();
580 time_t start_seconds = time (NULL);
581
582#ifdef HAVE_LC_MESSAGES
583 setlocale (LC_MESSAGES, "");
584#endif
585 setlocale (LC_CTYPE, "");
586 bindtextdomain (PACKAGE, LOCALEDIR);
587 textdomain (PACKAGE);
588
589 program_name = argv[0];
590 xmalloc_set_program_name (program_name);
591
592 /* Check the LD_STATS environment variable before parsing the command line
593 so that the --stats option, if used, can override the environment variable. */
594 char * stats_filename;
595 if ((stats_filename = getenv ("LD_STATS")) != NULL)
596 {
597 if (ISPRINT (stats_filename[0]))
598 config.stats_filename = stats_filename;
599 else
600 config.stats_filename = "-";
601 config.stats = true;
602 }
603
604 ld_start_phase (PHASE_ALL);
605 ld_start_phase (PHASE_PARSE);
606
607 expandargv (&argc, &argv);
608 char ** saved_argv = dupargv (argv);
609
610 if (bfd_init () != BFD_INIT_MAGIC)
611 fatal (_("%P: fatal error: libbfd ABI mismatch\n"));
612
613 bfd_set_error_program_name (program_name);
614
615 /* We want to notice and fail on those nasty BFD assertions which are
616 likely to signal incorrect output being generated but otherwise may
617 leave no trace. */
618 default_bfd_assert_handler = bfd_set_assert_handler (ld_bfd_assert_handler);
619
620 /* Also hook the bfd error/warning handler for --fatal-warnings. */
621 default_bfd_error_handler = bfd_set_error_handler (ld_bfd_error_handler);
622
623 xatexit (ld_cleanup);
624
625 /* Remove temporary object-only files. */
626 xatexit (cmdline_remove_object_only_files);
627
628 /* Set up the sysroot directory. */
629 ld_sysroot = get_sysroot (argc, argv);
630 if (*ld_sysroot)
631 ld_canon_sysroot = lrealpath (ld_sysroot);
632 if (ld_canon_sysroot)
633 {
634 ld_canon_sysroot_len = strlen (ld_canon_sysroot);
635
636 /* is_sysrooted_pathname() relies on no trailing dirsep. */
637 if (ld_canon_sysroot_len > 0
638 && IS_DIR_SEPARATOR (ld_canon_sysroot [ld_canon_sysroot_len - 1]))
639 ld_canon_sysroot [--ld_canon_sysroot_len] = '\0';
640 }
641 else
642 ld_canon_sysroot_len = -1;
643
644 /* Set the default BFD target based on the configured target. Doing
645 this permits the linker to be configured for a particular target,
646 and linked against a shared BFD library which was configured for
647 a different target. The macro TARGET is defined by Makefile. */
648 if (!bfd_set_default_target (TARGET))
649 {
650 einfo (_("%X%P: can't set BFD default target to `%s': %E\n"), TARGET);
651 xexit (1);
652 }
653
654#if YYDEBUG
655 {
656 extern int yydebug;
657 yydebug = 1;
658 }
659#endif
660
661 config.build_constructors = true;
662 config.rpath_separator = ':';
663 config.split_by_reloc = (unsigned) -1;
664 config.split_by_file = (bfd_size_type) -1;
665 config.make_executable = true;
666 config.magic_demand_paged = true;
667 config.text_read_only = true;
668 config.print_map_discarded = true;
669 link_info.disable_target_specific_optimizations = -1;
670
671 command_line.warn_mismatch = true;
672 command_line.warn_search_mismatch = true;
673 command_line.check_section_addresses = -1;
674
675 /* We initialize DEMANGLING based on the environment variable
676 COLLECT_NO_DEMANGLE. The gcc collect2 program will demangle the
677 output of the linker, unless COLLECT_NO_DEMANGLE is set in the
678 environment. Acting the same way here lets us provide the same
679 interface by default. */
680 demangling = getenv ("COLLECT_NO_DEMANGLE") == NULL;
681
682 link_info.allow_undefined_version = true;
683 link_info.keep_memory = true;
684 link_info.max_cache_size = (bfd_size_type) -1;
685 link_info.combreloc = true;
686 link_info.strip_discarded = true;
687 link_info.prohibit_multiple_definition_absolute = false;
688 link_info.textrel_check = DEFAULT_LD_TEXTREL_CHECK;
689 link_info.emit_hash = DEFAULT_EMIT_SYSV_HASH;
690 link_info.emit_gnu_hash = DEFAULT_EMIT_GNU_HASH;
691 link_info.callbacks = &link_callbacks;
692 link_info.input_bfds_tail = &link_info.input_bfds;
693 /* SVR4 linkers seem to set DT_INIT and DT_FINI based on magic _init
694 and _fini symbols. We are compatible. */
695 link_info.init_function = "_init";
696 link_info.fini_function = "_fini";
697 link_info.relax_pass = 1;
698 link_info.extern_protected_data = -1;
699 link_info.dynamic_undefined_weak = -1;
700 link_info.indirect_extern_access = -1;
701 link_info.pei386_auto_import = -1;
702 link_info.spare_dynamic_tags = 5;
703 link_info.path_separator = ':';
704#ifdef DEFAULT_FLAG_COMPRESS_DEBUG
705 config.compress_debug = DEFAULT_COMPRESSED_DEBUG_ALGORITHM;
706#endif
707#ifdef DEFAULT_NEW_DTAGS
708 link_info.new_dtags = DEFAULT_NEW_DTAGS;
709#endif
710 link_info.start_stop_gc = false;
711 link_info.start_stop_visibility = STV_PROTECTED;
712
713 ldfile_add_arch ("");
714 emulation = get_emulation (argc, argv);
715 ldemul_choose_mode (emulation);
716 default_target = ldemul_choose_target (argc, argv);
717 lang_init (false);
718 ldexp_init (false);
719 ldemul_before_parse ();
720 lang_has_input_file = false;
721 parse_args (argc, argv);
722
723 if (config.hash_table_size != 0)
724 bfd_hash_set_default_size (config.hash_table_size);
725
726 ld_stop_phase (PHASE_PARSE);
727
728#if BFD_SUPPORTS_PLUGINS
729 ld_start_phase (PHASE_PLUGINS);
730 /* Now all the plugin arguments have been gathered, we can load them. */
731 plugin_load_plugins ();
732 ld_stop_phase (PHASE_PLUGINS);
733#endif /* BFD_SUPPORTS_PLUGINS */
734
735 ld_start_phase (PHASE_PARSE);
736
737 ldemul_set_symbols ();
738
739 /* If we have not already opened and parsed a linker script,
740 try the default script from command line first. */
741 if (saved_script_handle == NULL
742 && command_line.default_script != NULL)
743 {
744 ldfile_open_script_file (command_line.default_script);
745 parser_input = input_script;
746 yyparse ();
747 }
748
749 /* If we have not already opened and parsed a linker script
750 read the emulation's appropriate default script. */
751 if (saved_script_handle == NULL)
752 {
753 int isfile;
754 char *s = ldemul_get_script (&isfile);
755
756 if (isfile)
757 ldfile_open_default_command_file (s);
758 else
759 {
760 lex_string = s;
761 lex_redirect (s, _("built in linker script"), 1);
762 }
763 parser_input = input_script;
764 yyparse ();
765 lex_string = NULL;
766 }
767
768 if (verbose)
769 {
770 if (saved_script_handle)
771 info_msg (_("using external linker script: %s"), processed_scripts->name);
772 else
773 info_msg (_("using internal linker script:"));
774 info_msg ("\n==================================================\n");
775
776 if (saved_script_handle)
777 display_external_script ();
778 else
779 {
780 int isfile;
781
782 info_msg (ldemul_get_script (&isfile));
783 }
784
785 info_msg ("\n==================================================\n");
786 }
787
788 if (command_line.section_ordering_file)
789 {
790 FILE *hold_script_handle;
791
792 hold_script_handle = saved_script_handle;
793 ldfile_open_command_file (command_line.section_ordering_file);
794 if (verbose)
795 display_external_script ();
796 saved_script_handle = hold_script_handle;
797 in_section_ordering = true;
798 parser_input = input_section_ordering_script;
799 yyparse ();
800 in_section_ordering = false;
801
802 }
803
804 if (command_line.force_group_allocation
805 || !bfd_link_relocatable (&link_info))
806 link_info.resolve_section_groups = true;
807 else
808 link_info.resolve_section_groups = false;
809
810 if (command_line.print_output_format)
811 info_msg ("%s\n", lang_get_output_target ());
812
813 lang_final ();
814
815 /* If the only command line argument has been -v or --version or --verbose
816 then ignore any input files provided by linker scripts and exit now.
817 We do not want to create an output file when the linker is just invoked
818 to provide version information. */
819 if (argc == 2 && version_printed)
820 xexit (0);
821
822 if (link_info.inhibit_common_definition && !bfd_link_dll (&link_info))
823 fatal (_("%P: --no-define-common may not be used without -shared\n"));
824
825 if (!lang_has_input_file)
826 {
827 if (version_printed || command_line.print_output_format)
828 xexit (0);
829 output_unknown_cmdline_warnings ();
830 fatal (_("%P: no input files\n"));
831 }
832
833 if (verbose)
834 info_msg (_("%P: mode %s\n"), emulation);
835
836 ldemul_after_parse ();
837
838 output_unknown_cmdline_warnings ();
839
840 if (config.map_filename)
841 {
842 if (strcmp (config.map_filename, "-") == 0)
843 {
844 config.map_file = stdout;
845 }
846 else
847 {
848 config.map_file = fopen (config.map_filename, FOPEN_WT);
849 if (config.map_file == (FILE *) NULL)
850 {
851 bfd_set_error (bfd_error_system_call);
852 einfo (_("%P: cannot open map file %s: %E\n"),
853 config.map_filename);
854 }
855 }
856 link_info.has_map_file = true;
857 }
858
859 if (config.stats_filename != NULL)
860 {
861 if (config.map_filename != NULL
862 && strcmp (config.stats_filename, config.map_filename) == 0)
863 config.stats_file = NULL;
864 else if (strcmp (config.stats_filename, "-") == 0)
865 config.stats_file = stdout;
866 else
867 {
868 if (config.stats_filename[0] == '+')
869 config.stats_file = fopen (config.stats_filename + 1, "a");
870 else
871 config.stats_file = fopen (config.stats_filename, "w");
872
873 if (config.stats_file == NULL)
874 einfo ("%P: Warning: failed to open resource record file: %s\n",
875 config.stats_filename);
876 }
877 }
878
879 ld_stop_phase (PHASE_PARSE);
880
881 ld_start_phase (PHASE_PROCESS);
882 lang_process ();
883 ld_stop_phase (PHASE_PROCESS);
884
885 /* Print error messages for any missing symbols, for any warning
886 symbols, and possibly multiple definitions. */
887 if (bfd_link_relocatable (&link_info))
888 link_info.output_bfd->flags &= ~EXEC_P;
889 else
890 link_info.output_bfd->flags |= EXEC_P;
891
892 flagword flags = 0;
893 switch (config.compress_debug)
894 {
895 case COMPRESS_DEBUG_GNU_ZLIB:
896 flags = BFD_COMPRESS;
897 break;
898 case COMPRESS_DEBUG_GABI_ZLIB:
899 flags = BFD_COMPRESS | BFD_COMPRESS_GABI;
900 break;
901 case COMPRESS_DEBUG_ZSTD:
902 flags = BFD_COMPRESS | BFD_COMPRESS_GABI | BFD_COMPRESS_ZSTD;
903 break;
904 default:
905 break;
906 }
907 link_info.output_bfd->flags
908 |= flags & bfd_applicable_file_flags (link_info.output_bfd);
909
910
911 ld_start_phase (PHASE_WRITE);
912 ldwrite ();
913 ld_stop_phase (PHASE_WRITE);
914
915
916 if (config.map_file != NULL)
917 lang_map ();
918 if (command_line.cref)
919 output_cref (config.map_file != NULL ? config.map_file : stdout);
920 if (nocrossref_list != NULL)
921 check_nocrossrefs ();
922 if (command_line.print_memory_usage)
923 lang_print_memory_usage ();
924#if 0
925 {
926 struct bfd_link_hash_entry *h;
927
928 h = bfd_link_hash_lookup (link_info.hash, "__image_base__", 0,0,1);
929 fprintf (stderr, "lookup = %p val %lx\n", h, h ? h->u.def.value : 1);
930 }
931#endif
932 ldexp_finish (false);
933 lang_finish ();
934
935 if (config.dependency_file != NULL)
936 write_dependency_file ();
937
938 /* Even if we're producing relocatable output, some non-fatal errors should
939 be reported in the exit status. (What non-fatal errors, if any, do we
940 want to ignore for relocatable output?) */
941 if (!config.make_executable && !force_make_executable)
942 {
943 if (verbose)
944 einfo (_("%P: link errors found, deleting executable `%s'\n"),
945 output_filename);
946
947 /* The file will be removed by ld_cleanup. */
948 xexit (1);
949 }
950 else
951 {
952 bfd *obfd = link_info.output_bfd;
953 link_info.output_bfd = NULL;
954 if (!bfd_close (obfd))
955 fatal (_("%P: %s: final close failed: %E\n"), output_filename);
956
957 link_info.output_bfd = NULL;
958
959 /* If the --force-exe-suffix is enabled, and we're making an
960 executable file and it doesn't end in .exe, copy it to one
961 which does. */
962 if (!bfd_link_relocatable (&link_info)
963 && command_line.force_exe_suffix)
964 {
965 int len = strlen (output_filename);
966
967 if (len < 4
968 || (strcasecmp (output_filename + len - 4, ".exe") != 0
969 && strcasecmp (output_filename + len - 4, ".dll") != 0))
970 {
971 FILE *src;
972 FILE *dst;
973 const int bsize = 4096;
974 char *buf = (char *) xmalloc (bsize);
975 int l;
976 char *dst_name = (char *) xmalloc (len + 5);
977
978 strcpy (dst_name, output_filename);
979 strcat (dst_name, ".exe");
980 src = fopen (output_filename, FOPEN_RB);
981 dst = fopen (dst_name, FOPEN_WB);
982
983 if (!src)
984 fatal (_("%P: unable to open for source of copy `%s'\n"),
985 output_filename);
986 if (!dst)
987 fatal (_("%P: unable to open for destination of copy `%s'\n"),
988 dst_name);
989 while ((l = fread (buf, 1, bsize, src)) > 0)
990 {
991 int done = fwrite (buf, 1, l, dst);
992
993 if (done != l)
994 einfo (_("%P: error writing file `%s'\n"), dst_name);
995 }
996
997 fclose (src);
998 if (fclose (dst) == EOF)
999 einfo (_("%P: error closing file `%s'\n"), dst_name);
1000 free (dst_name);
1001 free (buf);
1002 }
1003 }
1004 }
1005
1006 if (config.emit_gnu_object_only)
1007 cmdline_emit_object_only_section ();
1008
1009 ld_stop_phase (PHASE_ALL);
1010
1011 if (config.stats)
1012 {
1013 report_phases (config.map_file, & start_seconds, saved_argv);
1014
1015 if (config.stats_filename)
1016 {
1017 report_phases (config.stats_file, & start_seconds, saved_argv);
1018
1019 if (config.stats_file != stdout && config.stats_file != stderr)
1020 {
1021 fclose (config.stats_file);
1022 config.stats_file = NULL;
1023 }
1024 }
1025 else /* This is for backwards compatibility. */
1026 {
1027 long run_time = get_run_time () - start_time;
1028
1029 fflush (stdout);
1030 fprintf (stderr, _("%s: total time in link: %ld.%06ld\n"),
1031 program_name, run_time / 1000000, run_time % 1000000);
1032 fflush (stderr);
1033 }
1034 }
1035
1036 /* Prevent ld_cleanup from deleting the output file. */
1037 output_filename = NULL;
1038
1039 freeargv (saved_argv);
1040
1041 xexit (0);
1042 return 0;
1043}
1044
1045/* If the configured sysroot is relocatable, try relocating it based on
1046 default prefix FROM. Return the relocated directory if it exists,
1047 otherwise return null. */
1048
1049static char *
1050get_relative_sysroot (const char *from ATTRIBUTE_UNUSED)
1051{
1052#ifdef TARGET_SYSTEM_ROOT_RELOCATABLE
1053 char *path;
1054 struct stat s;
1055
1056 path = make_relative_prefix (program_name, from, TARGET_SYSTEM_ROOT);
1057 if (path)
1058 {
1059 if (stat (path, &s) == 0 && S_ISDIR (s.st_mode))
1060 return path;
1061 free (path);
1062 }
1063#endif
1064 return 0;
1065}
1066
1067/* Return the sysroot directory. Return "" if no sysroot is being used. */
1068
1069static const char *
1070get_sysroot (int argc, char **argv)
1071{
1072 int i;
1073 const char *path = NULL;
1074
1075 for (i = 1; i < argc; i++)
1076 if (startswith (argv[i], "--sysroot="))
1077 path = argv[i] + strlen ("--sysroot=");
1078
1079 if (!path)
1080 path = get_relative_sysroot (BINDIR);
1081
1082 if (!path)
1083 path = get_relative_sysroot (TOOLBINDIR);
1084
1085 if (!path)
1086 path = TARGET_SYSTEM_ROOT;
1087
1088 if (IS_DIR_SEPARATOR (*path) && path[1] == 0)
1089 path = "";
1090
1091 return path;
1092}
1093
1094/* We need to find any explicitly given emulation in order to initialize the
1095 state that's needed by the lex&yacc argument parser (parse_args). */
1096
1097static char *
1098get_emulation (int argc, char **argv)
1099{
1100 char *emulation;
1101 int i;
1102
1103 emulation = getenv (EMULATION_ENVIRON);
1104 if (emulation == NULL)
1105 emulation = DEFAULT_EMULATION;
1106
1107 for (i = 1; i < argc; i++)
1108 {
1109 if (startswith (argv[i], "-m"))
1110 {
1111 if (argv[i][2] == '\0')
1112 {
1113 /* -m EMUL */
1114 if (i < argc - 1)
1115 {
1116 emulation = argv[i + 1];
1117 i++;
1118 }
1119 else
1120 fatal (_("%P: missing argument to -m\n"));
1121 }
1122 else if (strcmp (argv[i], "-mips1") == 0
1123 || strcmp (argv[i], "-mips2") == 0
1124 || strcmp (argv[i], "-mips3") == 0
1125 || strcmp (argv[i], "-mips4") == 0
1126 || strcmp (argv[i], "-mips5") == 0
1127 || strcmp (argv[i], "-mips32") == 0
1128 || strcmp (argv[i], "-mips32r2") == 0
1129 || strcmp (argv[i], "-mips32r3") == 0
1130 || strcmp (argv[i], "-mips32r5") == 0
1131 || strcmp (argv[i], "-mips32r6") == 0
1132 || strcmp (argv[i], "-mips64") == 0
1133 || strcmp (argv[i], "-mips64r2") == 0
1134 || strcmp (argv[i], "-mips64r3") == 0
1135 || strcmp (argv[i], "-mips64r5") == 0
1136 || strcmp (argv[i], "-mips64r6") == 0)
1137 {
1138 /* FIXME: The arguments -mips1, -mips2, -mips3, etc. are
1139 passed to the linker by some MIPS compilers. They
1140 generally tell the linker to use a slightly different
1141 library path. Perhaps someday these should be
1142 implemented as emulations; until then, we just ignore
1143 the arguments and hope that nobody ever creates
1144 emulations named ips1, ips2 or ips3. */
1145 }
1146 else if (strcmp (argv[i], "-m486") == 0)
1147 {
1148 /* FIXME: The argument -m486 is passed to the linker on
1149 some Linux systems. Hope that nobody creates an
1150 emulation named 486. */
1151 }
1152 else
1153 {
1154 /* -mEMUL */
1155 emulation = &argv[i][2];
1156 }
1157 }
1158 }
1159
1160 return emulation;
1161}
1162
1163void
1164add_ysym (const char *name)
1165{
1166 if (link_info.notice_hash == NULL)
1167 {
1168 link_info.notice_hash
1169 = (struct bfd_hash_table *) xmalloc (sizeof (struct bfd_hash_table));
1170 if (!bfd_hash_table_init_n (link_info.notice_hash,
1171 bfd_hash_newfunc,
1172 sizeof (struct bfd_hash_entry),
1173 61))
1174 fatal (_("%P: bfd_hash_table_init failed: %E\n"));
1175 }
1176
1177 if (bfd_hash_lookup (link_info.notice_hash, name, true, true) == NULL)
1178 fatal (_("%P: bfd_hash_lookup failed: %E\n"));
1179}
1180
1181void
1182add_ignoresym (struct bfd_link_info *info, const char *name)
1183{
1184 if (info->ignore_hash == NULL)
1185 {
1186 info->ignore_hash = xmalloc (sizeof (struct bfd_hash_table));
1187 if (!bfd_hash_table_init_n (info->ignore_hash,
1188 bfd_hash_newfunc,
1189 sizeof (struct bfd_hash_entry),
1190 61))
1191 fatal (_("%P: bfd_hash_table_init failed: %E\n"));
1192 }
1193
1194 if (bfd_hash_lookup (info->ignore_hash, name, true, true) == NULL)
1195 fatal (_("%P: bfd_hash_lookup failed: %E\n"));
1196}
1197
1198/* Record a symbol to be wrapped, from the --wrap option. */
1199
1200void
1201add_wrap (const char *name)
1202{
1203 if (link_info.wrap_hash == NULL)
1204 {
1205 link_info.wrap_hash
1206 = (struct bfd_hash_table *) xmalloc (sizeof (struct bfd_hash_table));
1207 if (!bfd_hash_table_init_n (link_info.wrap_hash,
1208 bfd_hash_newfunc,
1209 sizeof (struct bfd_hash_entry),
1210 61))
1211 fatal (_("%P: bfd_hash_table_init failed: %E\n"));
1212 }
1213
1214 if (bfd_hash_lookup (link_info.wrap_hash, name, true, true) == NULL)
1215 fatal (_("%P: bfd_hash_lookup failed: %E\n"));
1216}
1217
1218/* Handle the -retain-symbols-file option. */
1219
1220void
1221add_keepsyms_file (const char *filename)
1222{
1223 FILE *file;
1224 char *buf;
1225 size_t bufsize;
1226 int c;
1227
1228 if (link_info.strip == strip_some)
1229 einfo (_("%X%P: error: duplicate retain-symbols-file\n"));
1230
1231 file = fopen (filename, "r");
1232 if (file == NULL)
1233 {
1234 bfd_set_error (bfd_error_system_call);
1235 einfo ("%X%P: %s: %E\n", filename);
1236 return;
1237 }
1238
1239 link_info.keep_hash = (struct bfd_hash_table *)
1240 xmalloc (sizeof (struct bfd_hash_table));
1241 if (!bfd_hash_table_init (link_info.keep_hash, bfd_hash_newfunc,
1242 sizeof (struct bfd_hash_entry)))
1243 fatal (_("%P: bfd_hash_table_init failed: %E\n"));
1244
1245 bufsize = 100;
1246 buf = (char *) xmalloc (bufsize);
1247
1248 c = getc (file);
1249 while (c != EOF)
1250 {
1251 while (ISSPACE (c))
1252 c = getc (file);
1253
1254 if (c != EOF)
1255 {
1256 size_t len = 0;
1257
1258 while (!ISSPACE (c) && c != EOF)
1259 {
1260 buf[len] = c;
1261 ++len;
1262 if (len >= bufsize)
1263 {
1264 bufsize *= 2;
1265 buf = (char *) xrealloc (buf, bufsize);
1266 }
1267 c = getc (file);
1268 }
1269
1270 buf[len] = '\0';
1271
1272 if (bfd_hash_lookup (link_info.keep_hash, buf, true, true) == NULL)
1273 fatal (_("%P: bfd_hash_lookup for insertion failed: %E\n"));
1274 }
1275 }
1276
1277 if (link_info.strip != strip_none)
1278 einfo (_("%P: `-retain-symbols-file' overrides `-s' and `-S'\n"));
1279
1280 free (buf);
1281 link_info.strip = strip_some;
1282 fclose (file);
1283}
1284\f
1285/* Callbacks from the BFD linker routines. */
1286
1287/* This is called when BFD has decided to include an archive member in
1288 a link. */
1289
1290static bool
1291add_archive_element (struct bfd_link_info *info,
1292 bfd *abfd,
1293 const char *name,
1294 bfd **subsbfd ATTRIBUTE_UNUSED)
1295{
1296 lang_input_statement_type *input;
1297 lang_input_statement_type *parent;
1298 lang_input_statement_type orig_input;
1299
1300 input = (lang_input_statement_type *)
1301 xcalloc (1, sizeof (lang_input_statement_type));
1302 input->header.type = lang_input_statement_enum;
1303 input->filename = bfd_get_filename (abfd);
1304 input->local_sym_name = bfd_get_filename (abfd);
1305 input->the_bfd = abfd;
1306
1307 /* Save the original data for trace files/tries below, as plugins
1308 (if enabled) may possibly alter it to point to a replacement
1309 BFD, but we still want to output the original BFD filename. */
1310 orig_input = *input;
1311#if BFD_SUPPORTS_PLUGINS
1312 /* Don't claim a fat IR object if no IR object should be claimed. */
1313 if (link_info.lto_plugin_active
1314 && (!no_more_claiming
1315 || bfd_get_lto_type (abfd) != lto_fat_ir_object))
1316 {
1317 ld_start_phase (PHASE_PLUGINS);
1318 /* We must offer this archive member to the plugins to claim. */
1319 plugin_maybe_claim (input);
1320 ld_stop_phase (PHASE_PLUGINS);
1321
1322 if (input->flags.claimed)
1323 {
1324 if (no_more_claiming)
1325 {
1326 /* Don't claim new IR symbols after all IR symbols have
1327 been claimed. */
1328 if (verbose)
1329 info_msg ("%pI: no new IR symbols to claim\n",
1330 &orig_input);
1331 input->flags.claimed = 0;
1332 return false;
1333 }
1334 input->flags.claim_archive = true;
1335 *subsbfd = input->the_bfd;
1336 }
1337 }
1338 else
1339 cmdline_check_object_only_section (input->the_bfd, false);
1340#endif /* BFD_SUPPORTS_PLUGINS */
1341
1342 if (link_info.input_bfds_tail == &input->the_bfd->link.next
1343 || input->the_bfd->link.next != NULL)
1344 {
1345 /* We have already loaded this element, and are attempting to
1346 load it again. This can happen when the archive map doesn't
1347 match actual symbols defined by the element. */
1348 free (input);
1349 bfd_set_error (bfd_error_malformed_archive);
1350 return false;
1351 }
1352
1353 /* Set the file_chain pointer of archives to the last element loaded
1354 from the archive. See ldlang.c:find_rescan_insertion. */
1355 parent = bfd_usrdata (abfd->my_archive);
1356 if (parent != NULL && !parent->flags.reload)
1357 parent->next = input;
1358
1359 ldlang_add_file (input);
1360
1361 if (config.map_file != NULL)
1362 {
1363 static bool header_printed;
1364 struct bfd_link_hash_entry *h;
1365 bfd *from;
1366 int len;
1367
1368 h = bfd_link_hash_lookup (info->hash, name, false, false, true);
1369 if (h == NULL
1370 && info->pei386_auto_import
1371 && startswith (name, "__imp_"))
1372 h = bfd_link_hash_lookup (info->hash, name + 6, false, false, true);
1373
1374 if (h == NULL)
1375 from = NULL;
1376 else
1377 {
1378 switch (h->type)
1379 {
1380 default:
1381 from = NULL;
1382 break;
1383
1384 case bfd_link_hash_defined:
1385 case bfd_link_hash_defweak:
1386 from = h->u.def.section->owner;
1387 break;
1388
1389 case bfd_link_hash_undefined:
1390 case bfd_link_hash_undefweak:
1391 from = h->u.undef.abfd;
1392 break;
1393
1394 case bfd_link_hash_common:
1395 from = h->u.c.p->section->owner;
1396 break;
1397 }
1398 }
1399
1400 if (!header_printed)
1401 {
1402 minfo (_("Archive member included to satisfy reference by file (symbol)\n\n"));
1403 header_printed = true;
1404 }
1405
1406 if (abfd->my_archive == NULL
1407 || bfd_is_thin_archive (abfd->my_archive))
1408 {
1409 minfo ("%s", bfd_get_filename (abfd));
1410 len = strlen (bfd_get_filename (abfd));
1411 }
1412 else
1413 {
1414 minfo ("%s(%s)", bfd_get_filename (abfd->my_archive),
1415 bfd_get_filename (abfd));
1416 len = (strlen (bfd_get_filename (abfd->my_archive))
1417 + strlen (bfd_get_filename (abfd))
1418 + 2);
1419 }
1420
1421 if (len >= 29)
1422 {
1423 print_nl ();
1424 len = 0;
1425 }
1426 print_spaces (30 - len);
1427
1428 if (from != NULL)
1429 minfo ("%pB ", from);
1430 if (h != NULL)
1431 minfo ("(%pT)\n", h->root.string);
1432 else
1433 minfo ("(%s)\n", name);
1434 }
1435
1436 if (verbose
1437 || trace_files > 1
1438 || (trace_files && bfd_is_thin_archive (orig_input.the_bfd->my_archive)))
1439 info_msg ("%pI\n", &orig_input);
1440 return true;
1441}
1442
1443/* This is called when BFD has discovered a symbol which is defined
1444 multiple times. */
1445
1446static void
1447multiple_definition (struct bfd_link_info *info,
1448 struct bfd_link_hash_entry *h,
1449 bfd *nbfd,
1450 asection *nsec,
1451 bfd_vma nval)
1452{
1453 const char *name;
1454 bfd *obfd;
1455 asection *osec;
1456 bfd_vma oval;
1457
1458 if (info->allow_multiple_definition)
1459 return;
1460
1461 switch (h->type)
1462 {
1463 case bfd_link_hash_defined:
1464 osec = h->u.def.section;
1465 oval = h->u.def.value;
1466 obfd = h->u.def.section->owner;
1467 break;
1468 case bfd_link_hash_indirect:
1469 osec = bfd_ind_section_ptr;
1470 oval = 0;
1471 obfd = NULL;
1472 break;
1473 default:
1474 abort ();
1475 }
1476
1477 /* Ignore a redefinition of an absolute symbol to the
1478 same value; it's harmless. */
1479 if (h->type == bfd_link_hash_defined
1480 && bfd_is_abs_section (osec)
1481 && bfd_is_abs_section (nsec)
1482 && nval == oval)
1483 return;
1484
1485 /* If either section has the output_section field set to
1486 bfd_abs_section_ptr, it means that the section is being
1487 discarded, and this is not really a multiple definition at all.
1488 FIXME: It would be cleaner to somehow ignore symbols defined in
1489 sections which are being discarded. */
1490 if (!info->prohibit_multiple_definition_absolute
1491 && ((osec->output_section != NULL
1492 && ! bfd_is_abs_section (osec)
1493 && bfd_is_abs_section (osec->output_section))
1494 || (nsec->output_section != NULL
1495 && !bfd_is_abs_section (nsec)
1496 && bfd_is_abs_section (nsec->output_section))))
1497 return;
1498
1499 name = h->root.string;
1500 if (nbfd == NULL)
1501 {
1502 nbfd = obfd;
1503 nsec = osec;
1504 nval = oval;
1505 obfd = NULL;
1506 }
1507 if (info->warn_multiple_definition)
1508 einfo (_("%P: %C: warning: multiple definition of `%pT'"),
1509 nbfd, nsec, nval, name);
1510 else
1511 einfo (_("%X%P: %C: multiple definition of `%pT'"),
1512 nbfd, nsec, nval, name);
1513 if (obfd != NULL)
1514 einfo (_("; %D: first defined here"), obfd, osec, oval);
1515 einfo ("\n");
1516
1517 if (RELAXATION_ENABLED_BY_USER)
1518 {
1519 einfo (_("%P: disabling relaxation; it will not work with multiple definitions\n"));
1520 DISABLE_RELAXATION;
1521 }
1522}
1523
1524/* This is called when there is a definition of a common symbol, or
1525 when a common symbol is found for a symbol that is already defined,
1526 or when two common symbols are found. We only do something if
1527 -warn-common was used. */
1528
1529static void
1530multiple_common (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1531 struct bfd_link_hash_entry *h,
1532 bfd *nbfd,
1533 enum bfd_link_hash_type ntype,
1534 bfd_vma nsize)
1535{
1536 const char *name;
1537 bfd *obfd;
1538 enum bfd_link_hash_type otype;
1539 bfd_vma osize;
1540
1541 if (!config.warn_common)
1542 return;
1543
1544 name = h->root.string;
1545 otype = h->type;
1546 if (otype == bfd_link_hash_common)
1547 {
1548 obfd = h->u.c.p->section->owner;
1549 osize = h->u.c.size;
1550 }
1551 else if (otype == bfd_link_hash_defined
1552 || otype == bfd_link_hash_defweak)
1553 {
1554 obfd = h->u.def.section->owner;
1555 osize = 0;
1556 }
1557 else
1558 {
1559 /* FIXME: It would nice if we could report the BFD which defined
1560 an indirect symbol, but we don't have anywhere to store the
1561 information. */
1562 obfd = NULL;
1563 osize = 0;
1564 }
1565
1566 if (ntype == bfd_link_hash_defined
1567 || ntype == bfd_link_hash_defweak
1568 || ntype == bfd_link_hash_indirect)
1569 {
1570 ASSERT (otype == bfd_link_hash_common);
1571 if (obfd != NULL)
1572 einfo (_("%P: %pB: warning: definition of `%pT' overriding common"
1573 " from %pB\n"),
1574 nbfd, name, obfd);
1575 else
1576 einfo (_("%P: %pB: warning: definition of `%pT' overriding common\n"),
1577 nbfd, name);
1578 }
1579 else if (otype == bfd_link_hash_defined
1580 || otype == bfd_link_hash_defweak
1581 || otype == bfd_link_hash_indirect)
1582 {
1583 ASSERT (ntype == bfd_link_hash_common);
1584 if (obfd != NULL)
1585 einfo (_("%P: %pB: warning: common of `%pT' overridden by definition"
1586 " from %pB\n"),
1587 nbfd, name, obfd);
1588 else
1589 einfo (_("%P: %pB: warning: common of `%pT' overridden by definition\n"),
1590 nbfd, name);
1591 }
1592 else
1593 {
1594 ASSERT (otype == bfd_link_hash_common && ntype == bfd_link_hash_common);
1595 if (osize > nsize)
1596 {
1597 if (obfd != NULL)
1598 einfo (_("%P: %pB: warning: common of `%pT' overridden"
1599 " by larger common from %pB\n"),
1600 nbfd, name, obfd);
1601 else
1602 einfo (_("%P: %pB: warning: common of `%pT' overridden"
1603 " by larger common\n"),
1604 nbfd, name);
1605 }
1606 else if (nsize > osize)
1607 {
1608 if (obfd != NULL)
1609 einfo (_("%P: %pB: warning: common of `%pT' overriding"
1610 " smaller common from %pB\n"),
1611 nbfd, name, obfd);
1612 else
1613 einfo (_("%P: %pB: warning: common of `%pT' overriding"
1614 " smaller common\n"),
1615 nbfd, name);
1616 }
1617 else
1618 {
1619 if (obfd != NULL)
1620 einfo (_("%P: %pB and %pB: warning: multiple common of `%pT'\n"),
1621 nbfd, obfd, name);
1622 else
1623 einfo (_("%P: %pB: warning: multiple common of `%pT'\n"),
1624 nbfd, name);
1625 }
1626 }
1627}
1628
1629/* This is called when BFD has discovered a set element. H is the
1630 entry in the linker hash table for the set. SECTION and VALUE
1631 represent a value which should be added to the set. */
1632
1633static void
1634add_to_set (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1635 struct bfd_link_hash_entry *h,
1636 bfd_reloc_code_real_type reloc,
1637 bfd *abfd,
1638 asection *section,
1639 bfd_vma value)
1640{
1641 if (config.warn_constructors)
1642 einfo (_("%P: warning: global constructor %s used\n"),
1643 h->root.string);
1644
1645 if (!config.build_constructors)
1646 return;
1647
1648 ldctor_add_set_entry (h, reloc, NULL, section, value);
1649
1650 if (h->type == bfd_link_hash_new)
1651 {
1652 h->type = bfd_link_hash_undefined;
1653 h->u.undef.abfd = abfd;
1654 /* We don't call bfd_link_add_undef to add this to the list of
1655 undefined symbols because we are going to define it
1656 ourselves. */
1657 }
1658}
1659
1660/* This is called when BFD has discovered a constructor. This is only
1661 called for some object file formats--those which do not handle
1662 constructors in some more clever fashion. This is similar to
1663 adding an element to a set, but less general. */
1664
1665static void
1666constructor_callback (struct bfd_link_info *info,
1667 bool constructor,
1668 const char *name,
1669 bfd *abfd,
1670 asection *section,
1671 bfd_vma value)
1672{
1673 char *s;
1674 struct bfd_link_hash_entry *h;
1675 char set_name[1 + sizeof "__CTOR_LIST__"];
1676
1677 if (config.warn_constructors)
1678 einfo (_("%P: warning: global constructor %s used\n"), name);
1679
1680 if (!config.build_constructors)
1681 return;
1682
1683 /* Ensure that BFD_RELOC_CTOR exists now, so that we can give a
1684 useful error message. */
1685 if (bfd_reloc_type_lookup (info->output_bfd, BFD_RELOC_CTOR) == NULL
1686 && (bfd_link_relocatable (info)
1687 || bfd_reloc_type_lookup (abfd, BFD_RELOC_CTOR) == NULL))
1688 fatal (_("%P: BFD backend error: BFD_RELOC_CTOR unsupported\n"));
1689
1690 s = set_name;
1691 if (bfd_get_symbol_leading_char (abfd) != '\0')
1692 *s++ = bfd_get_symbol_leading_char (abfd);
1693 if (constructor)
1694 strcpy (s, "__CTOR_LIST__");
1695 else
1696 strcpy (s, "__DTOR_LIST__");
1697
1698 h = bfd_link_hash_lookup (info->hash, set_name, true, true, true);
1699 if (h == (struct bfd_link_hash_entry *) NULL)
1700 fatal (_("%P: bfd_link_hash_lookup failed: %E\n"));
1701 if (h->type == bfd_link_hash_new)
1702 {
1703 h->type = bfd_link_hash_undefined;
1704 h->u.undef.abfd = abfd;
1705 /* We don't call bfd_link_add_undef to add this to the list of
1706 undefined symbols because we are going to define it
1707 ourselves. */
1708 }
1709
1710 ldctor_add_set_entry (h, BFD_RELOC_CTOR, name, section, value);
1711}
1712
1713/* A structure used by warning_callback to pass information through
1714 bfd_map_over_sections. */
1715
1716struct warning_callback_info
1717{
1718 bool found;
1719 const char *warning;
1720 const char *symbol;
1721 asymbol **asymbols;
1722};
1723
1724/* Look through the relocs to see if we can find a plausible address
1725 for SYMBOL in ABFD. Return TRUE if found. Otherwise return FALSE. */
1726
1727static bool
1728symbol_warning (const char *warning, const char *symbol, bfd *abfd)
1729{
1730 struct warning_callback_info cinfo;
1731
1732 if (!bfd_generic_link_read_symbols (abfd))
1733 fatal (_("%P: %pB: could not read symbols: %E\n"), abfd);
1734
1735 cinfo.found = false;
1736 cinfo.warning = warning;
1737 cinfo.symbol = symbol;
1738 cinfo.asymbols = bfd_get_outsymbols (abfd);
1739 bfd_map_over_sections (abfd, warning_find_reloc, &cinfo);
1740 return cinfo.found;
1741}
1742
1743/* This is called when there is a reference to a warning symbol. */
1744
1745static void
1746warning_callback (struct bfd_link_info *info ATTRIBUTE_UNUSED,
1747 const char *warning,
1748 const char *symbol,
1749 bfd *abfd,
1750 asection *section,
1751 bfd_vma address)
1752{
1753 /* This is a hack to support warn_multiple_gp. FIXME: This should
1754 have a cleaner interface, but what? */
1755 if (!config.warn_multiple_gp
1756 && strcmp (warning, "using multiple gp values") == 0)
1757 return;
1758
1759 if (section != NULL)
1760 einfo ("%P: %C: %s%s\n", abfd, section, address, _("warning: "), warning);
1761 else if (abfd == NULL)
1762 einfo ("%P: %s%s\n", _("warning: "), warning);
1763 else if (symbol == NULL)
1764 einfo ("%P: %pB: %s%s\n", abfd, _("warning: "), warning);
1765 else if (!symbol_warning (warning, symbol, abfd))
1766 {
1767 bfd *b;
1768 /* Search all input files for a reference to SYMBOL. */
1769 for (b = info->input_bfds; b; b = b->link.next)
1770 if (b != abfd && symbol_warning (warning, symbol, b))
1771 return;
1772 einfo ("%P: %pB: %s%s\n", abfd, _("warning: "), warning);
1773 }
1774}
1775
1776/* This is called by warning_callback for each section. It checks the
1777 relocs of the section to see if it can find a reference to the
1778 symbol which triggered the warning. If it can, it uses the reloc
1779 to give an error message with a file and line number. */
1780
1781static void
1782warning_find_reloc (bfd *abfd, asection *sec, void *iarg)
1783{
1784 struct warning_callback_info *info = (struct warning_callback_info *) iarg;
1785 long relsize;
1786 arelent **relpp;
1787 long relcount;
1788 arelent **p, **pend;
1789
1790 if (info->found)
1791 return;
1792
1793 relsize = bfd_get_reloc_upper_bound (abfd, sec);
1794 if (relsize < 0)
1795 fatal (_("%P: %pB: could not read relocs: %E\n"), abfd);
1796 if (relsize == 0)
1797 return;
1798
1799 relpp = (arelent **) xmalloc (relsize);
1800 relcount = bfd_canonicalize_reloc (abfd, sec, relpp, info->asymbols);
1801 if (relcount < 0)
1802 fatal (_("%P: %pB: could not read relocs: %E\n"), abfd);
1803
1804 p = relpp;
1805 pend = p + relcount;
1806 for (; p < pend && *p != NULL; p++)
1807 {
1808 arelent *q = *p;
1809
1810 if (q->sym_ptr_ptr != NULL
1811 && *q->sym_ptr_ptr != NULL
1812 && strcmp (bfd_asymbol_name (*q->sym_ptr_ptr), info->symbol) == 0)
1813 {
1814 /* We found a reloc for the symbol we are looking for. */
1815 einfo ("%P: %H: %s%s\n", abfd, sec, q->address, _("warning: "),
1816 info->warning);
1817 info->found = true;
1818 break;
1819 }
1820 }
1821
1822 free (relpp);
1823}
1824
1825#if SUPPORT_ERROR_HANDLING_SCRIPT
1826char * error_handling_script = NULL;
1827#endif
1828
1829/* This is called when an undefined symbol is found. */
1830
1831static void
1832undefined_symbol (struct bfd_link_info *info,
1833 const char *name,
1834 bfd *abfd,
1835 asection *section,
1836 bfd_vma address,
1837 bool error)
1838{
1839 static char *error_name;
1840 static unsigned int error_count;
1841
1842#define MAX_ERRORS_IN_A_ROW 5
1843
1844 if (info->ignore_hash != NULL
1845 && bfd_hash_lookup (info->ignore_hash, name, false, false) != NULL)
1846 return;
1847
1848 if (config.warn_once)
1849 {
1850 /* Only warn once about a particular undefined symbol. */
1851 add_ignoresym (info, name);
1852 }
1853
1854 /* We never print more than a reasonable number of errors in a row
1855 for a single symbol. */
1856 if (error_name != NULL
1857 && strcmp (name, error_name) == 0)
1858 ++error_count;
1859 else
1860 {
1861 error_count = 0;
1862 free (error_name);
1863 error_name = xstrdup (name);
1864 }
1865
1866#if SUPPORT_ERROR_HANDLING_SCRIPT
1867 if (error_handling_script != NULL
1868 && error_count < MAX_ERRORS_IN_A_ROW)
1869 {
1870 char * argv[4];
1871 const char * res;
1872 int status, err;
1873
1874 argv[0] = error_handling_script;
1875 argv[1] = "undefined-symbol";
1876 argv[2] = (char *) name;
1877 argv[3] = NULL;
1878
1879 if (verbose)
1880 einfo (_("%P: About to run error handling script '%s' with arguments: '%s' '%s'\n"),
1881 argv[0], argv[1], argv[2]);
1882
1883 res = pex_one (PEX_SEARCH, error_handling_script, argv,
1884 N_("error handling script"),
1885 NULL /* Send stdout to random, temp file. */,
1886 NULL /* Write to stderr. */,
1887 &status, &err);
1888 if (res != NULL)
1889 {
1890 einfo (_("%P: Failed to run error handling script '%s', reason: "),
1891 error_handling_script);
1892 /* FIXME: We assume here that errrno == err. */
1893 perror (res);
1894 }
1895 /* We ignore the return status of the script and
1896 carry on to issue the normal error message. */
1897 }
1898#endif /* SUPPORT_ERROR_HANDLING_SCRIPT */
1899
1900 if (section != NULL)
1901 {
1902 if (error_count < MAX_ERRORS_IN_A_ROW)
1903 {
1904 if (error)
1905 einfo (_("%X%P: %H: undefined reference to `%pT'\n"),
1906 abfd, section, address, name);
1907 else
1908 einfo (_("%P: %H: warning: undefined reference to `%pT'\n"),
1909 abfd, section, address, name);
1910 }
1911 else if (error_count == MAX_ERRORS_IN_A_ROW)
1912 {
1913 if (error)
1914 einfo (_("%X%P: %D: more undefined references to `%pT' follow\n"),
1915 abfd, section, address, name);
1916 else
1917 einfo (_("%P: %D: warning: more undefined references to `%pT' follow\n"),
1918 abfd, section, address, name);
1919 }
1920 else if (error)
1921 einfo ("%X");
1922 }
1923 else
1924 {
1925 if (error_count < MAX_ERRORS_IN_A_ROW)
1926 {
1927 if (error)
1928 einfo (_("%X%P: %pB: undefined reference to `%pT'\n"),
1929 abfd, name);
1930 else
1931 einfo (_("%P: %pB: warning: undefined reference to `%pT'\n"),
1932 abfd, name);
1933 }
1934 else if (error_count == MAX_ERRORS_IN_A_ROW)
1935 {
1936 if (error)
1937 einfo (_("%X%P: %pB: more undefined references to `%pT' follow\n"),
1938 abfd, name);
1939 else
1940 einfo (_("%P: %pB: warning: more undefined references to `%pT' follow\n"),
1941 abfd, name);
1942 }
1943 else if (error)
1944 einfo ("%X");
1945 }
1946}
1947
1948/* Counter to limit the number of relocation overflow error messages
1949 to print. Errors are printed as it is decremented. When it's
1950 called and the counter is zero, a final message is printed
1951 indicating more relocations were omitted. When it gets to -1, no
1952 such errors are printed. If it's initially set to a value less
1953 than -1, all such errors will be printed (--verbose does this). */
1954
1955int overflow_cutoff_limit = 10;
1956
1957/* This is called when a reloc overflows. */
1958
1959static void
1960reloc_overflow (struct bfd_link_info *info,
1961 struct bfd_link_hash_entry *entry,
1962 const char *name,
1963 const char *reloc_name,
1964 bfd_vma addend,
1965 bfd *abfd,
1966 asection *section,
1967 bfd_vma address)
1968{
1969 if (overflow_cutoff_limit == -1)
1970 return;
1971
1972 einfo ("%X%H:", abfd, section, address);
1973
1974 if (overflow_cutoff_limit >= 0
1975 && overflow_cutoff_limit-- == 0)
1976 {
1977 einfo (_(" additional relocation overflows omitted from the output\n"));
1978 return;
1979 }
1980
1981 if (entry)
1982 {
1983 while (entry->type == bfd_link_hash_indirect
1984 || entry->type == bfd_link_hash_warning)
1985 entry = entry->u.i.link;
1986 switch (entry->type)
1987 {
1988 case bfd_link_hash_undefined:
1989 case bfd_link_hash_undefweak:
1990 einfo (_(" relocation truncated to fit: "
1991 "%s against undefined symbol `%pT'"),
1992 reloc_name, entry->root.string);
1993 break;
1994 case bfd_link_hash_defined:
1995 case bfd_link_hash_defweak:
1996 einfo (_(" relocation truncated to fit: "
1997 "%s against symbol `%pT' defined in %pA section in %pB"),
1998 reloc_name, entry->root.string,
1999 entry->u.def.section,
2000 entry->u.def.section == bfd_abs_section_ptr
2001 ? info->output_bfd : entry->u.def.section->owner);
2002 break;
2003 default:
2004 abort ();
2005 break;
2006 }
2007 }
2008 else
2009 einfo (_(" relocation truncated to fit: %s against `%pT'"),
2010 reloc_name, name);
2011 if (addend != 0)
2012 einfo ("+%v", addend);
2013 einfo ("\n");
2014}
2015
2016/* This is called when a dangerous relocation is made. */
2017
2018static void
2019reloc_dangerous (struct bfd_link_info *info ATTRIBUTE_UNUSED,
2020 const char *message,
2021 bfd *abfd,
2022 asection *section,
2023 bfd_vma address)
2024{
2025 einfo (_("%X%H: dangerous relocation: %s\n"),
2026 abfd, section, address, message);
2027}
2028
2029/* This is called when a reloc is being generated attached to a symbol
2030 that is not being output. */
2031
2032static void
2033unattached_reloc (struct bfd_link_info *info ATTRIBUTE_UNUSED,
2034 const char *name,
2035 bfd *abfd,
2036 asection *section,
2037 bfd_vma address)
2038{
2039 einfo (_("%X%H: reloc refers to symbol `%pT' which is not being output\n"),
2040 abfd, section, address, name);
2041}
2042
2043/* This is called if link_info.notice_all is set, or when a symbol in
2044 link_info.notice_hash is found. Symbols are put in notice_hash
2045 using the -y option, while notice_all is set if the --cref option
2046 has been supplied, or if there are any NOCROSSREFS sections in the
2047 linker script; and if plugins are active, since they need to monitor
2048 all references from non-IR files. */
2049
2050static bool
2051notice (struct bfd_link_info *info,
2052 struct bfd_link_hash_entry *h,
2053 struct bfd_link_hash_entry *inh ATTRIBUTE_UNUSED,
2054 bfd *abfd,
2055 asection *section,
2056 bfd_vma value,
2057 flagword flags ATTRIBUTE_UNUSED)
2058{
2059 const char *name;
2060
2061 if (h == NULL)
2062 {
2063 if (command_line.cref || nocrossref_list != NULL)
2064 return handle_asneeded_cref (abfd, (enum notice_asneeded_action) value);
2065 return true;
2066 }
2067
2068 name = h->root.string;
2069 if (info->notice_hash != NULL
2070 && bfd_hash_lookup (info->notice_hash, name, false, false) != NULL)
2071 {
2072 if (bfd_is_und_section (section))
2073 einfo (_("%P: %pB: reference to %s\n"), abfd, name);
2074 else
2075 einfo (_("%P: %pB: definition of %s\n"), abfd, name);
2076 }
2077
2078 if (command_line.cref || nocrossref_list != NULL)
2079 add_cref (name, abfd, section, value);
2080
2081 return true;
2082}