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