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