ldelf.c revision 1.1.1.5 1 /* ELF emulation code for targets using elf.em.
2 Copyright (C) 1991-2026 Free Software Foundation, Inc.
3
4 This file is part of the GNU Binutils.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19 MA 02110-1301, USA. */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "libiberty.h"
24 #include "filenames.h"
25 #include "safe-ctype.h"
26 #include "bfdlink.h"
27 #include "ctf-api.h"
28 #include "ld.h"
29 #include "ldmain.h"
30 #include "ldmisc.h"
31 #include "ldexp.h"
32 #include "ldlang.h"
33 #include "ldfile.h"
34 #include "ldemul.h"
35 #include "ldbuildid.h"
36 #include <ldgram.h>
37 #include "elf-bfd.h"
38 #ifdef HAVE_GLOB
39 #include <glob.h>
40 #endif
41 #include "ldelf.h"
42 #ifdef HAVE_JANSSON
43 #include <jansson.h>
44 #endif
45
46 struct dt_needed
47 {
48 bfd *by;
49 const char *name;
50 };
51
52 /* Style of .note.gnu.build-id section. */
53 const char *ldelf_emit_note_gnu_build_id;
54
55 /* Content of .note.package section. */
56 const char *ldelf_emit_note_fdo_package_metadata;
57
58 /* These variables are required to pass information back and forth
59 between after_open and check_needed and stat_needed and vercheck. */
60
61 static struct bfd_link_needed_list *global_needed;
62 static lang_input_statement_type *global_found;
63 static struct stat global_stat;
64 static struct bfd_link_needed_list *global_vercheck_needed;
65 static bool global_vercheck_failed;
66 static bool orphan_init_done;
67
68 void
69 ldelf_after_parse (void)
70 {
71 if (bfd_link_pie (&link_info))
72 link_info.flags_1 |= (bfd_vma) DF_1_PIE;
73
74 if (bfd_link_executable (&link_info)
75 && link_info.nointerp)
76 {
77 if (link_info.dynamic_undefined_weak > 0)
78 queue_unknown_cmdline_warning ("-z dynamic-undefined-weak");
79 link_info.dynamic_undefined_weak = 0;
80 }
81
82 /* Disable DT_RELR if not building PIE nor shared library. */
83 if (!bfd_link_pic (&link_info))
84 link_info.enable_dt_relr = 0;
85
86 /* Add 3 spare tags for DT_RELR, DT_RELRSZ and DT_RELRENT. */
87 if (link_info.enable_dt_relr)
88 link_info.spare_dynamic_tags += 3;
89
90 after_parse_default ();
91 if (link_info.commonpagesize > link_info.maxpagesize)
92 {
93 if (!link_info.commonpagesize_is_set)
94 link_info.commonpagesize = link_info.maxpagesize;
95 else if (!link_info.maxpagesize_is_set)
96 link_info.maxpagesize = link_info.commonpagesize;
97 else
98 fatal (_("%P: common page size (0x%v) > maximum page size (0x%v)\n"),
99 link_info.commonpagesize, link_info.maxpagesize);
100 }
101 }
102
103 /* Handle the generation of DT_NEEDED tags. */
104
105 bool
106 ldelf_load_symbols (lang_input_statement_type *entry)
107 {
108 int link_class = 0;
109
110 /* Tell the ELF linker that we don't want the output file to have a
111 DT_NEEDED entry for this file, unless it is used to resolve
112 references in a regular object. */
113 if (entry->flags.add_DT_NEEDED_for_regular)
114 link_class = DYN_AS_NEEDED;
115
116 /* Tell the ELF linker that we don't want the output file to have a
117 DT_NEEDED entry for any dynamic library in DT_NEEDED tags from
118 this file at all. */
119 if (!entry->flags.add_DT_NEEDED_for_dynamic)
120 link_class |= DYN_NO_ADD_NEEDED;
121
122 if (entry->flags.just_syms
123 && (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) != 0)
124 fatal (_("%P: %pB: --just-symbols may not be used on DSO\n"),
125 entry->the_bfd);
126
127 if (link_class == 0
128 || (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) == 0)
129 return false;
130
131 bfd_elf_set_dyn_lib_class (entry->the_bfd,
132 (enum dynamic_lib_link_class) link_class);
133
134 /* Continue on with normal load_symbols processing. */
135 return false;
136 }
137
138 /* On Linux, it's possible to have different versions of the same
139 shared library linked against different versions of libc. The
140 dynamic linker somehow tags which libc version to use in
141 /etc/ld.so.cache, and, based on the libc that it sees in the
142 executable, chooses which version of the shared library to use.
143
144 We try to do a similar check here by checking whether this shared
145 library needs any other shared libraries which may conflict with
146 libraries we have already included in the link. If it does, we
147 skip it, and try to find another shared library farther on down the
148 link path.
149
150 This is called via lang_for_each_input_file.
151 GLOBAL_VERCHECK_NEEDED is the list of objects needed by the object
152 which we are checking. This sets GLOBAL_VERCHECK_FAILED if we find
153 a conflicting version. */
154
155 static void
156 ldelf_vercheck (lang_input_statement_type *s)
157 {
158 const char *soname;
159 struct bfd_link_needed_list *l;
160
161 if (global_vercheck_failed)
162 return;
163 if (s->the_bfd == NULL
164 || (bfd_get_file_flags (s->the_bfd) & DYNAMIC) == 0)
165 return;
166
167 soname = bfd_elf_get_dt_soname (s->the_bfd);
168 if (soname == NULL)
169 soname = lbasename (bfd_get_filename (s->the_bfd));
170
171 for (l = global_vercheck_needed; l != NULL; l = l->next)
172 {
173 const char *suffix;
174
175 if (filename_cmp (soname, l->name) == 0)
176 {
177 /* Probably can't happen, but it's an easy check. */
178 continue;
179 }
180
181 if (strchr (l->name, '/') != NULL)
182 continue;
183
184 suffix = strstr (l->name, ".so.");
185 if (suffix == NULL)
186 continue;
187
188 suffix += sizeof ".so." - 1;
189
190 if (filename_ncmp (soname, l->name, suffix - l->name) == 0)
191 {
192 /* Here we know that S is a dynamic object FOO.SO.VER1, and
193 the object we are considering needs a dynamic object
194 FOO.SO.VER2, and VER1 and VER2 are different. This
195 appears to be a version mismatch, so we tell the caller
196 to try a different version of this library. */
197 global_vercheck_failed = true;
198 return;
199 }
200 }
201 }
202
203
204 /* See if an input file matches a DT_NEEDED entry by running stat on
205 the file. */
206
207 static void
208 ldelf_stat_needed (lang_input_statement_type *s)
209 {
210 struct stat st;
211 const char *suffix;
212 const char *soname;
213
214 if (global_found != NULL)
215 return;
216 if (s->the_bfd == NULL)
217 return;
218
219 /* If this input file was an as-needed entry, and wasn't found to be
220 needed at the stage it was linked, then don't say we have loaded it. */
221 if ((bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
222 return;
223
224 if (bfd_stat (s->the_bfd, &st) != 0)
225 {
226 einfo (_("%P: %pB: bfd_stat failed: %E\n"), s->the_bfd);
227 return;
228 }
229
230 /* Some operating systems, e.g. Windows, do not provide a meaningful
231 st_ino; they always set it to zero. (Windows does provide a
232 meaningful st_dev.) Do not indicate a duplicate library in that
233 case. While there is no guarantee that a system that provides
234 meaningful inode numbers will never set st_ino to zero, this is
235 merely an optimization, so we do not need to worry about false
236 negatives. */
237 if (st.st_dev == global_stat.st_dev
238 && st.st_ino == global_stat.st_ino
239 && st.st_ino != 0)
240 {
241 global_found = s;
242 return;
243 }
244
245 /* We issue a warning if it looks like we are including two
246 different versions of the same shared library. For example,
247 there may be a problem if -lc picks up libc.so.6 but some other
248 shared library has a DT_NEEDED entry of libc.so.5. This is a
249 heuristic test, and it will only work if the name looks like
250 NAME.so.VERSION. FIXME: Depending on file names is error-prone.
251 If we really want to issue warnings about mixing version numbers
252 of shared libraries, we need to find a better way. */
253
254 if (strchr (global_needed->name, '/') != NULL)
255 return;
256 suffix = strstr (global_needed->name, ".so.");
257 if (suffix == NULL)
258 return;
259 suffix += sizeof ".so." - 1;
260
261 soname = bfd_elf_get_dt_soname (s->the_bfd);
262 if (soname == NULL)
263 soname = lbasename (s->filename);
264
265 if (filename_ncmp (soname, global_needed->name,
266 suffix - global_needed->name) == 0)
267 einfo (_("%P: warning: %s, needed by %pB, may conflict with %s\n"),
268 global_needed->name, global_needed->by, soname);
269 }
270
271 /* This function is called for each possible name for a dynamic object
272 named by a DT_NEEDED entry. The FORCE parameter indicates whether
273 to skip the check for a conflicting version. */
274
275 static bool
276 ldelf_try_needed (struct dt_needed *needed, int force, int is_linux)
277 {
278 bfd *abfd;
279 const char *name = needed->name;
280 const char *soname;
281 int link_class;
282
283 abfd = bfd_openr (name, bfd_get_target (link_info.output_bfd));
284 if (abfd == NULL)
285 {
286 if (verbose)
287 info_msg (_("attempt to open %s failed\n"), name);
288 return false;
289 }
290
291 track_dependency_files (name);
292
293 /* Linker needs to decompress sections. */
294 abfd->flags |= BFD_DECOMPRESS;
295
296 if (! bfd_check_format (abfd, bfd_object))
297 {
298 bfd_close (abfd);
299 return false;
300 }
301 if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
302 {
303 bfd_close (abfd);
304 return false;
305 }
306
307 /* For DT_NEEDED, they have to match. */
308 if (abfd->xvec != link_info.output_bfd->xvec)
309 {
310 bfd_close (abfd);
311 return false;
312 }
313
314 /* Check whether this object would include any conflicting library
315 versions. If FORCE is set, then we skip this check; we use this
316 the second time around, if we couldn't find any compatible
317 instance of the shared library. */
318
319 if (!force)
320 {
321 struct bfd_link_needed_list *needs;
322
323 if (! bfd_elf_get_bfd_needed_list (abfd, &needs))
324 fatal (_("%P: %pB: bfd_elf_get_bfd_needed_list failed: %E\n"), abfd);
325
326 if (needs != NULL)
327 {
328 global_vercheck_needed = needs;
329 global_vercheck_failed = false;
330 lang_for_each_input_file (ldelf_vercheck);
331 if (global_vercheck_failed)
332 {
333 bfd_close (abfd);
334 /* Return FALSE to force the caller to move on to try
335 another file on the search path. */
336 return false;
337 }
338
339 /* But wait! It gets much worse. On Linux, if a shared
340 library does not use libc at all, we are supposed to skip
341 it the first time around in case we encounter a shared
342 library later on with the same name which does use the
343 version of libc that we want. This is much too horrible
344 to use on any system other than Linux. */
345 if (is_linux)
346 {
347 struct bfd_link_needed_list *l;
348
349 for (l = needs; l != NULL; l = l->next)
350 if (startswith (l->name, "libc.so"))
351 break;
352 if (l == NULL)
353 {
354 bfd_close (abfd);
355 return false;
356 }
357 }
358 }
359 }
360
361 /* We've found a dynamic object matching the DT_NEEDED entry. */
362
363 /* We have already checked that there is no other input file of the
364 same name. We must now check again that we are not including the
365 same file twice. We need to do this because on many systems
366 libc.so is a symlink to, e.g., libc.so.1. The SONAME entry will
367 reference libc.so.1. If we have already included libc.so, we
368 don't want to include libc.so.1 if they are the same file, and we
369 can only check that using stat. */
370
371 if (bfd_stat (abfd, &global_stat) != 0)
372 fatal (_("%P: %pB: bfd_stat failed: %E\n"), abfd);
373
374 /* First strip off everything before the last '/'. */
375 soname = lbasename (bfd_get_filename (abfd));
376
377 if (verbose)
378 info_msg (_("found %s at %s\n"), soname, name);
379
380 global_found = NULL;
381 lang_for_each_input_file (ldelf_stat_needed);
382 if (global_found != NULL)
383 {
384 /* Return TRUE to indicate that we found the file, even though
385 we aren't going to do anything with it. */
386 return true;
387 }
388
389 /* Specify the soname to use. */
390 bfd_elf_set_dt_needed_name (abfd, soname);
391
392 /* Tell the ELF linker that we don't want the output file to have a
393 DT_NEEDED entry for this file, unless it is used to resolve
394 references in a regular object. */
395 link_class = DYN_DT_NEEDED;
396
397 /* Tell the ELF linker that we don't want the output file to have a
398 DT_NEEDED entry for this file at all if the entry is from a file
399 with DYN_NO_ADD_NEEDED. */
400 if (needed->by != NULL
401 && (bfd_elf_get_dyn_lib_class (needed->by) & DYN_NO_ADD_NEEDED) != 0)
402 link_class |= DYN_NO_NEEDED | DYN_NO_ADD_NEEDED;
403
404 bfd_elf_set_dyn_lib_class (abfd, (enum dynamic_lib_link_class) link_class);
405
406 *link_info.input_bfds_tail = abfd;
407 link_info.input_bfds_tail = &abfd->link.next;
408
409 /* Add this file into the symbol table. */
410 if (! bfd_link_add_symbols (abfd, &link_info))
411 fatal (_("%P: %pB: error adding symbols: %E\n"), abfd);
412
413 return true;
414 }
415
416 /* Search for a needed file in a path. */
417
418 static bool
419 ldelf_search_needed (const char *path, struct dt_needed *n, int force,
420 int is_linux, int elfsize)
421 {
422 const char *s;
423 const char *name = n->name;
424 size_t len;
425 struct dt_needed needed;
426
427 if (name[0] == '/')
428 return ldelf_try_needed (n, force, is_linux);
429
430 if (path == NULL || *path == '\0')
431 return false;
432
433 needed.by = n->by;
434 needed.name = n->name;
435
436 len = strlen (name);
437 while (1)
438 {
439 unsigned offset = 0;
440 char * var;
441 char *filename, *sset;
442
443 s = strchr (path, config.rpath_separator);
444 if (s == NULL)
445 s = path + strlen (path);
446
447 #if HAVE_DOS_BASED_FILE_SYSTEM
448 /* Assume a match on the second char is part of drive specifier. */
449 else if (config.rpath_separator == ':'
450 && s == path + 1
451 && ISALPHA (*path))
452 {
453 s = strchr (s + 1, config.rpath_separator);
454 if (s == NULL)
455 s = path + strlen (path);
456 }
457 #endif
458 filename = (char *) xmalloc (s - path + len + 2);
459 if (s == path)
460 sset = filename;
461 else
462 {
463 memcpy (filename, path, s - path);
464 filename[s - path] = '/';
465 sset = filename + (s - path) + 1;
466 }
467 strcpy (sset, name);
468
469 /* PR 20535: Support the same pseudo-environment variables that
470 are supported by ld.so. Namely, $ORIGIN, $LIB and $PLATFORM.
471 Since there can be more than one occurrence of these tokens in
472 the path we loop until no more are found. Since we might not
473 be able to substitute some of the tokens we maintain an offset
474 into the filename for where we should begin our scan. */
475 while ((var = strchr (filename + offset, '$')) != NULL)
476 {
477 /* The ld.so manual page does not say, but I am going to assume that
478 these tokens are terminated by a directory separator character
479 (/) or the end of the string. There is also an implication that
480 $ORIGIN should only be used at the start of a path, but that is
481 not enforced here.
482
483 The ld.so manual page also states that it allows ${ORIGIN},
484 ${LIB} and ${PLATFORM}, so these are supported as well.
485
486 FIXME: The code could be a lot cleverer about allocating space
487 for the processed string. */
488 char * end = strchr (var, '/');
489 const char *replacement = NULL;
490 char * v = var + 1;
491 char * freeme = NULL;
492 unsigned flen = strlen (filename);
493
494 if (end != NULL)
495 /* Temporarily terminate the filename at the end of the token. */
496 * end = 0;
497
498 if (*v == '{')
499 ++ v;
500 switch (*v++)
501 {
502 case 'O':
503 if (strcmp (v, "RIGIN") == 0 || strcmp (v, "RIGIN}") == 0)
504 {
505 /* ORIGIN - replace with the full path to the directory
506 containing the program or shared object. */
507 if (needed.by == NULL)
508 {
509 if (link_info.output_bfd == NULL)
510 {
511 break;
512 }
513 else
514 replacement = bfd_get_filename (link_info.output_bfd);
515 }
516 else
517 replacement = bfd_get_filename (needed.by);
518
519 if (replacement)
520 {
521 char * slash;
522
523 if (replacement[0] == '/')
524 freeme = xstrdup (replacement);
525 else
526 {
527 char * current_dir = getpwd ();
528 size_t cdir_len = strlen (current_dir);
529 size_t rep_len = strlen (replacement);
530 freeme = xmalloc (cdir_len + rep_len + 2);
531 memcpy (freeme, current_dir, cdir_len);
532 freeme[cdir_len] = '/';
533 memcpy (freeme + cdir_len + 1,
534 replacement, rep_len + 1);
535 }
536
537 replacement = freeme;
538 if ((slash = strrchr (replacement, '/')) != NULL)
539 * slash = 0;
540 }
541 }
542 break;
543
544 case 'L':
545 if (strcmp (v, "IB") == 0 || strcmp (v, "IB}") == 0)
546 {
547 /* LIB - replace with "lib" in 32-bit environments
548 and "lib64" in 64-bit environments. */
549
550 switch (elfsize)
551 {
552 case 32: replacement = "lib"; break;
553 case 64: replacement = "lib64"; break;
554 default:
555 abort ();
556 }
557 }
558 break;
559
560 case 'P':
561 /* Supporting $PLATFORM in a cross-hosted environment is not
562 possible. Supporting it in a native environment involves
563 loading the <sys/auxv.h> header file which loads the
564 system <elf.h> header file, which conflicts with the
565 "include/elf/mips.h" header file. */
566 /* Fall through. */
567 default:
568 break;
569 }
570
571 if (replacement)
572 {
573 char * filename2 = xmalloc (flen + strlen (replacement));
574
575 if (end)
576 {
577 sprintf (filename2, "%.*s%s/%s",
578 (int)(var - filename), filename,
579 replacement, end + 1);
580 offset = (var - filename) + 1 + strlen (replacement);
581 }
582 else
583 {
584 sprintf (filename2, "%.*s%s",
585 (int)(var - filename), filename,
586 replacement);
587 offset = var - filename + strlen (replacement);
588 }
589
590 free (filename);
591 filename = filename2;
592 /* There is no need to restore the path separator (when
593 end != NULL) as we have replaced the entire string. */
594 }
595 else
596 {
597 if (verbose)
598 /* We only issue an "unrecognised" message in verbose mode
599 as the $<foo> token might be a legitimate component of
600 a path name in the target's file system. */
601 info_msg (_("unrecognised or unsupported token "
602 "'%s' in search path\n"), var);
603 if (end)
604 /* Restore the path separator. */
605 * end = '/';
606
607 /* PR 20784: Make sure that we resume the scan *after*
608 the token that we could not replace. */
609 offset = (var + 1) - filename;
610 }
611
612 free (freeme);
613 }
614
615 needed.name = filename;
616
617 if (ldelf_try_needed (&needed, force, is_linux))
618 {
619 free (filename);
620 return true;
621 }
622
623 free (filename);
624
625 if (*s == '\0')
626 break;
627 path = s + 1;
628 }
629
630 return false;
631 }
632
633 /* Prefix the sysroot to absolute paths in PATH, a string containing
634 paths separated by config.rpath_separator. If running on a DOS
635 file system, paths containing a drive spec won't have the sysroot
636 prefix added, unless the sysroot also specifies the same drive. */
637
638 static const char *
639 ldelf_add_sysroot (const char *path)
640 {
641 size_t len, extra;
642 const char *p;
643 char *ret, *q;
644 int dos_drive_sysroot = HAS_DRIVE_SPEC (ld_sysroot);
645
646 len = strlen (ld_sysroot);
647 for (extra = 0, p = path; ; )
648 {
649 int dos_drive = HAS_DRIVE_SPEC (p);
650
651 if (dos_drive)
652 p += 2;
653 if (IS_DIR_SEPARATOR (*p)
654 && (!dos_drive
655 || (dos_drive_sysroot
656 && ld_sysroot[0] == p[-2])))
657 {
658 if (dos_drive && dos_drive_sysroot)
659 extra += len - 2;
660 else
661 extra += len;
662 }
663 p = strchr (p, config.rpath_separator);
664 if (!p)
665 break;
666 ++p;
667 }
668
669 ret = xmalloc (strlen (path) + extra + 1);
670
671 for (q = ret, p = path; ; )
672 {
673 const char *end;
674 int dos_drive = HAS_DRIVE_SPEC (p);
675
676 if (dos_drive)
677 {
678 *q++ = *p++;
679 *q++ = *p++;
680 }
681 if (IS_DIR_SEPARATOR (*p)
682 && (!dos_drive
683 || (dos_drive_sysroot
684 && ld_sysroot[0] == p[-2])))
685 {
686 if (dos_drive && dos_drive_sysroot)
687 {
688 strcpy (q, ld_sysroot + 2);
689 q += len - 2;
690 }
691 else
692 {
693 strcpy (q, ld_sysroot);
694 q += len;
695 }
696 }
697 end = strchr (p, config.rpath_separator);
698 if (end)
699 {
700 size_t n = end - p + 1;
701 strncpy (q, p, n);
702 q += n;
703 p += n;
704 }
705 else
706 {
707 strcpy (q, p);
708 break;
709 }
710 }
711
712 return ret;
713 }
714
715 /* Read the system search path the FreeBSD way rather than the Linux way. */
716 #ifdef HAVE_ELF_HINTS_H
717 #include <elf-hints.h>
718 #else
719 #include "elf-hints-local.h"
720 #endif
721
722 static bool
723 ldelf_check_ld_elf_hints (const struct bfd_link_needed_list *l, int force,
724 int elfsize)
725 {
726 static bool initialized;
727 static const char *ld_elf_hints;
728 struct dt_needed needed;
729
730 if (!initialized)
731 {
732 FILE *f;
733 char *tmppath;
734
735 tmppath = concat (ld_sysroot, _PATH_ELF_HINTS, (const char *) NULL);
736 f = fopen (tmppath, FOPEN_RB);
737 free (tmppath);
738 if (f != NULL)
739 {
740 struct elfhints_hdr hdr;
741
742 if (fread (&hdr, 1, sizeof (hdr), f) == sizeof (hdr)
743 && hdr.magic == ELFHINTS_MAGIC
744 && hdr.version == 1)
745 {
746 if (fseek (f, hdr.strtab + hdr.dirlist, SEEK_SET) != -1)
747 {
748 char *b;
749
750 b = xmalloc (hdr.dirlistlen + 1);
751 if (fread (b, 1, hdr.dirlistlen + 1, f) ==
752 hdr.dirlistlen + 1)
753 ld_elf_hints = ldelf_add_sysroot (b);
754
755 free (b);
756 }
757 }
758 fclose (f);
759 }
760
761 initialized = true;
762 }
763
764 if (ld_elf_hints == NULL)
765 return false;
766
767 needed.by = l->by;
768 needed.name = l->name;
769 return ldelf_search_needed (ld_elf_hints, &needed, force, false, elfsize);
770 }
771
772 /* For a native linker, check the file /etc/ld.so.conf for directories
773 in which we may find shared libraries. /etc/ld.so.conf is really
774 only meaningful on Linux. */
775
776 struct ldelf_ld_so_conf
777 {
778 char *path;
779 size_t len, alloc;
780 };
781
782 static bool
783 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *, const char *);
784
785 static void
786 ldelf_parse_ld_so_conf_include (struct ldelf_ld_so_conf *info,
787 const char *filename,
788 const char *pattern)
789 {
790 char *newp = NULL;
791 #ifdef HAVE_GLOB
792 glob_t gl;
793 #endif
794
795 if (pattern[0] != '/')
796 {
797 char *p = strrchr (filename, '/');
798 size_t patlen = strlen (pattern) + 1;
799
800 newp = xmalloc (p - filename + 1 + patlen);
801 memcpy (newp, filename, p - filename + 1);
802 memcpy (newp + (p - filename + 1), pattern, patlen);
803 pattern = newp;
804 }
805
806 #ifdef HAVE_GLOB
807 if (glob (pattern, 0, NULL, &gl) == 0)
808 {
809 size_t i;
810
811 for (i = 0; i < gl.gl_pathc; ++i)
812 ldelf_parse_ld_so_conf (info, gl.gl_pathv[i]);
813 globfree (&gl);
814 }
815 #else
816 /* If we do not have glob, treat the pattern as a literal filename. */
817 ldelf_parse_ld_so_conf (info, pattern);
818 #endif
819
820 free (newp);
821 }
822
823 static bool
824 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *info, const char *filename)
825 {
826 FILE *f = fopen (filename, FOPEN_RT);
827 char *line;
828 size_t linelen;
829
830 if (f == NULL)
831 return false;
832
833 linelen = 256;
834 line = xmalloc (linelen);
835 do
836 {
837 char *p = line, *q;
838
839 /* Normally this would use getline(3), but we need to be portable. */
840 while ((q = fgets (p, linelen - (p - line), f)) != NULL
841 && strlen (q) == linelen - (p - line) - 1
842 && line[linelen - 2] != '\n')
843 {
844 line = xrealloc (line, 2 * linelen);
845 p = line + linelen - 1;
846 linelen += linelen;
847 }
848
849 if (q == NULL && p == line)
850 break;
851
852 p = strchr (line, '\n');
853 if (p)
854 *p = '\0';
855
856 /* Because the file format does not know any form of quoting we
857 can search forward for the next '#' character and if found
858 make it terminating the line. */
859 p = strchr (line, '#');
860 if (p)
861 *p = '\0';
862
863 /* Remove leading whitespace. NUL is no whitespace character. */
864 p = line;
865 while (*p == ' ' || *p == '\f' || *p == '\r' || *p == '\t' || *p == '\v')
866 ++p;
867
868 /* If the line is blank it is ignored. */
869 if (p[0] == '\0')
870 continue;
871
872 if (startswith (p, "include") && (p[7] == ' ' || p[7] == '\t'))
873 {
874 char *dir, c;
875 p += 8;
876 do
877 {
878 while (*p == ' ' || *p == '\t')
879 ++p;
880
881 if (*p == '\0')
882 break;
883
884 dir = p;
885
886 while (*p != ' ' && *p != '\t' && *p)
887 ++p;
888
889 c = *p;
890 *p++ = '\0';
891 if (dir[0] != '\0')
892 ldelf_parse_ld_so_conf_include (info, filename, dir);
893 }
894 while (c != '\0');
895 }
896 else
897 {
898 char *dir = p;
899 while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
900 && *p != '\r' && *p != '\v')
901 ++p;
902
903 while (p != dir && p[-1] == '/')
904 --p;
905 if (info->path == NULL)
906 {
907 info->alloc = p - dir + 1 + 256;
908 info->path = xmalloc (info->alloc);
909 info->len = 0;
910 }
911 else
912 {
913 if (info->len + 1 + (p - dir) >= info->alloc)
914 {
915 info->alloc += p - dir + 256;
916 info->path = xrealloc (info->path, info->alloc);
917 }
918 info->path[info->len++] = config.rpath_separator;
919 }
920 memcpy (info->path + info->len, dir, p - dir);
921 info->len += p - dir;
922 info->path[info->len] = '\0';
923 }
924 }
925 while (! feof (f));
926 free (line);
927 fclose (f);
928 return true;
929 }
930
931 static bool
932 ldelf_check_ld_so_conf (const struct bfd_link_needed_list *l, int force,
933 int elfsize, const char *prefix)
934 {
935 static bool initialized;
936 static const char *ld_so_conf;
937 struct dt_needed needed;
938
939 if (! initialized)
940 {
941 char *tmppath;
942 struct ldelf_ld_so_conf info;
943
944 info.path = NULL;
945 info.len = info.alloc = 0;
946 tmppath = concat (ld_sysroot, prefix, "/etc/ld.so.conf",
947 (const char *) NULL);
948 if (!ldelf_parse_ld_so_conf (&info, tmppath))
949 {
950 free (tmppath);
951 tmppath = concat (ld_sysroot, "/etc/ld.so.conf",
952 (const char *) NULL);
953 ldelf_parse_ld_so_conf (&info, tmppath);
954 }
955 free (tmppath);
956
957 if (info.path)
958 {
959 ld_so_conf = ldelf_add_sysroot (info.path);
960 free (info.path);
961 }
962 initialized = true;
963 }
964
965 if (ld_so_conf == NULL)
966 return false;
967
968
969 needed.by = l->by;
970 needed.name = l->name;
971 return ldelf_search_needed (ld_so_conf, &needed, force, true, elfsize);
972 }
973
974 /* See if an input file matches a DT_NEEDED entry by name. */
975
976 static void
977 ldelf_check_needed (lang_input_statement_type *s)
978 {
979 const char *soname;
980
981 /* Stop looking if we've found a loaded lib. */
982 if (global_found != NULL
983 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
984 & DYN_AS_NEEDED) == 0)
985 return;
986
987 if (s->filename == NULL || s->the_bfd == NULL)
988 return;
989
990 /* Don't look for a second non-loaded as-needed lib. */
991 if (global_found != NULL
992 && (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
993 return;
994
995 if (filename_cmp (s->filename, global_needed->name) == 0)
996 {
997 global_found = s;
998 return;
999 }
1000
1001 if (s->flags.search_dirs)
1002 {
1003 const char *f = strrchr (s->filename, '/');
1004 if (f != NULL
1005 && filename_cmp (f + 1, global_needed->name) == 0)
1006 {
1007 global_found = s;
1008 return;
1009 }
1010 }
1011
1012 soname = bfd_elf_get_dt_soname (s->the_bfd);
1013 if (soname != NULL
1014 && filename_cmp (soname, global_needed->name) == 0)
1015 {
1016 global_found = s;
1017 return;
1018 }
1019 }
1020
1021 static void
1022 ldelf_handle_dt_needed (struct elf_link_hash_table *htab,
1023 int use_libpath, int native, int is_linux,
1024 int is_freebsd, int elfsize, const char *prefix)
1025 {
1026 struct bfd_link_needed_list *needed, *l;
1027 bfd *abfd;
1028 bfd **save_input_bfd_tail;
1029
1030 /* Get the list of files which appear in DT_NEEDED entries in
1031 dynamic objects included in the link (often there will be none).
1032 For each such file, we want to track down the corresponding
1033 library, and include the symbol table in the link. This is what
1034 the runtime dynamic linker will do. Tracking the files down here
1035 permits one dynamic object to include another without requiring
1036 special action by the person doing the link. Note that the
1037 needed list can actually grow while we are stepping through this
1038 loop. */
1039 save_input_bfd_tail = link_info.input_bfds_tail;
1040 needed = bfd_elf_get_needed_list (link_info.output_bfd, &link_info);
1041 for (l = needed; l != NULL; l = l->next)
1042 {
1043 struct bfd_link_needed_list *ll;
1044 struct dt_needed n, nn;
1045 int force;
1046
1047 /* If the lib that needs this one was --as-needed and wasn't
1048 found to be needed, then this lib isn't needed either. */
1049 if (l->by != NULL
1050 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_AS_NEEDED) != 0)
1051 continue;
1052
1053 /* Skip the lib if --no-copy-dt-needed-entries and when we are
1054 handling DT_NEEDED entries or --allow-shlib-undefined is in
1055 effect. */
1056 if (l->by != NULL
1057 && (htab->handling_dt_needed
1058 || link_info.unresolved_syms_in_shared_libs == RM_IGNORE)
1059 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_NO_ADD_NEEDED) != 0)
1060 continue;
1061
1062 /* If we've already seen this file, skip it. */
1063 for (ll = needed; ll != l; ll = ll->next)
1064 if ((ll->by == NULL
1065 || (bfd_elf_get_dyn_lib_class (ll->by) & DYN_AS_NEEDED) == 0)
1066 && strcmp (ll->name, l->name) == 0)
1067 break;
1068 if (ll != l)
1069 continue;
1070
1071 /* See if this file was included in the link explicitly. */
1072 global_needed = l;
1073 global_found = NULL;
1074 lang_for_each_input_file (ldelf_check_needed);
1075 if (global_found != NULL
1076 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
1077 & DYN_AS_NEEDED) == 0)
1078 continue;
1079
1080 n.by = l->by;
1081 n.name = l->name;
1082 nn.by = l->by;
1083 if (verbose)
1084 info_msg (_("%s needed by %pB\n"), l->name, l->by);
1085
1086 /* As-needed libs specified on the command line (or linker script)
1087 take priority over libs found in search dirs. */
1088 if (global_found != NULL)
1089 {
1090 nn.name = global_found->filename;
1091 if (ldelf_try_needed (&nn, true, is_linux))
1092 continue;
1093 }
1094
1095 /* We need to find this file and include the symbol table. We
1096 want to search for the file in the same way that the dynamic
1097 linker will search. That means that we want to use
1098 rpath_link, rpath, then the environment variable
1099 LD_LIBRARY_PATH (native only), then the DT_RPATH/DT_RUNPATH
1100 entries (native only), then the linker script LIB_SEARCH_DIRS.
1101 We do not search using the -L arguments.
1102
1103 We search twice. The first time, we skip objects which may
1104 introduce version mismatches. The second time, we force
1105 their use. See ldelf_vercheck comment. */
1106 for (force = 0; force < 2; force++)
1107 {
1108 size_t len;
1109 search_dirs_type *search;
1110 const char *path;
1111 struct bfd_link_needed_list *rp;
1112 int found;
1113
1114 if (ldelf_search_needed (command_line.rpath_link, &n, force,
1115 is_linux, elfsize))
1116 break;
1117
1118 if (use_libpath)
1119 {
1120 path = command_line.rpath;
1121 if (path)
1122 {
1123 path = ldelf_add_sysroot (path);
1124 found = ldelf_search_needed (path, &n, force,
1125 is_linux, elfsize);
1126 free ((char *) path);
1127 if (found)
1128 break;
1129 }
1130 }
1131 if (native)
1132 {
1133 if (command_line.rpath_link == NULL
1134 && command_line.rpath == NULL)
1135 {
1136 path = (const char *) getenv ("LD_RUN_PATH");
1137 if (path
1138 && ldelf_search_needed (path, &n, force,
1139 is_linux, elfsize))
1140 break;
1141 }
1142 path = (const char *) getenv ("LD_LIBRARY_PATH");
1143 if (path
1144 && ldelf_search_needed (path, &n, force,
1145 is_linux, elfsize))
1146 break;
1147 }
1148 if (use_libpath)
1149 {
1150 found = 0;
1151 rp = bfd_elf_get_runpath_list (link_info.output_bfd, &link_info);
1152 for (; !found && rp != NULL; rp = rp->next)
1153 {
1154 path = ldelf_add_sysroot (rp->name);
1155 found = (rp->by == l->by
1156 && ldelf_search_needed (path, &n, force,
1157 is_linux, elfsize));
1158 free ((char *) path);
1159 }
1160 if (found)
1161 break;
1162
1163 if (is_freebsd
1164 && ldelf_check_ld_elf_hints (l, force, elfsize))
1165 break;
1166
1167 if (is_linux
1168 && ldelf_check_ld_so_conf (l, force, elfsize, prefix))
1169 break;
1170 }
1171
1172 len = strlen (l->name);
1173 for (search = search_head; search != NULL; search = search->next)
1174 {
1175 char *filename;
1176
1177 if (search->cmdline)
1178 continue;
1179 filename = (char *) xmalloc (strlen (search->name) + len + 2);
1180 sprintf (filename, "%s/%s", search->name, l->name);
1181 nn.name = filename;
1182 if (ldelf_try_needed (&nn, force, is_linux))
1183 break;
1184 free (filename);
1185 }
1186 if (search != NULL)
1187 break;
1188 }
1189
1190 if (force < 2)
1191 continue;
1192
1193 einfo (_("%P: warning: %s, needed by %pB, not found "
1194 "(try using -rpath or -rpath-link)\n"),
1195 l->name, l->by);
1196 }
1197
1198 /* Don't add DT_NEEDED when loading shared objects from DT_NEEDED for
1199 plugin symbol resolution while handling DT_NEEDED entries. */
1200 if (!htab->handling_dt_needed)
1201 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1202 if (bfd_get_format (abfd) == bfd_object
1203 && ((abfd->flags) & DYNAMIC) != 0
1204 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
1205 && (elf_dyn_lib_class (abfd) & (DYN_AS_NEEDED | DYN_NO_NEEDED)) == 0
1206 && elf_dt_name (abfd) != NULL)
1207 {
1208 if (bfd_elf_add_dt_needed_tag (abfd, &link_info) < 0)
1209 fatal (_("%P: failed to add DT_NEEDED dynamic tag\n"));
1210 }
1211
1212 link_info.input_bfds_tail = save_input_bfd_tail;
1213 *save_input_bfd_tail = NULL;
1214 }
1215
1216 /* This is called before calling plugin 'all symbols read' hook. */
1217
1218 void
1219 ldelf_before_plugin_all_symbols_read (int use_libpath, int native,
1220 int is_linux, int is_freebsd,
1221 int elfsize, const char *prefix)
1222 {
1223 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1224
1225 if (!link_info.lto_plugin_active
1226 || !is_elf_hash_table (&htab->root))
1227 return;
1228
1229 htab->handling_dt_needed = true;
1230 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1231 is_freebsd, elfsize, prefix);
1232 htab->handling_dt_needed = false;
1233 }
1234
1235 /* This is called after all the input files have been opened and all
1236 symbols have been loaded. */
1237
1238 void
1239 ldelf_after_open (int use_libpath, int native, int is_linux, int is_freebsd,
1240 int elfsize, const char *prefix)
1241 {
1242 struct elf_link_hash_table *htab;
1243 asection *s;
1244 bfd *abfd;
1245
1246 after_open_default ();
1247
1248 htab = elf_hash_table (&link_info);
1249 if (!is_elf_hash_table (&htab->root))
1250 return;
1251
1252 if (command_line.out_implib_filename)
1253 {
1254 unlink_if_ordinary (command_line.out_implib_filename);
1255 link_info.out_implib_bfd
1256 = bfd_openw (command_line.out_implib_filename,
1257 bfd_get_target (link_info.output_bfd));
1258
1259 if (link_info.out_implib_bfd == NULL)
1260 fatal (_("%P: %s: can't open for writing: %E\n"),
1261 command_line.out_implib_filename);
1262 }
1263
1264 if (ldelf_emit_note_gnu_build_id != NULL
1265 || ldelf_emit_note_fdo_package_metadata != NULL)
1266 {
1267 /* Find an ELF input. */
1268 for (abfd = link_info.input_bfds;
1269 abfd != (bfd *) NULL; abfd = abfd->link.next)
1270 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1271 && bfd_count_sections (abfd) != 0
1272 && !bfd_input_just_syms (abfd))
1273 break;
1274
1275 /* PR 10555: If there are no ELF input files do not try to
1276 create a .note.gnu-build-id section. */
1277 if (abfd == NULL
1278 || (ldelf_emit_note_gnu_build_id != NULL
1279 && !ldelf_setup_build_id (abfd)))
1280 {
1281 free ((char *) ldelf_emit_note_gnu_build_id);
1282 ldelf_emit_note_gnu_build_id = NULL;
1283 }
1284
1285 if (abfd == NULL
1286 || (ldelf_emit_note_fdo_package_metadata != NULL
1287 && !ldelf_setup_package_metadata (abfd)))
1288 {
1289 free ((char *) ldelf_emit_note_fdo_package_metadata);
1290 ldelf_emit_note_fdo_package_metadata = NULL;
1291 }
1292 }
1293
1294 get_elf_backend_data (link_info.output_bfd)->setup_object_attributes (&link_info);
1295 get_elf_backend_data (link_info.output_bfd)->setup_gnu_properties (&link_info);
1296
1297 /* Do not allow executable files to be used as inputs to the link. */
1298 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1299 {
1300 /* Discard input .note.gnu.build-id sections. */
1301 s = bfd_get_section_by_name (abfd, ".note.gnu.build-id");
1302 while (s != NULL)
1303 {
1304 if (s != elf_tdata (link_info.output_bfd)->o->build_id.sec)
1305 s->flags |= SEC_EXCLUDE;
1306 s = bfd_get_next_section_by_name (NULL, s);
1307 }
1308
1309 if (abfd->xvec->flavour == bfd_target_elf_flavour
1310 && !bfd_input_just_syms (abfd)
1311 && elf_tdata (abfd) != NULL
1312 /* FIXME: Maybe check for other non-supportable types as well ? */
1313 && (elf_tdata (abfd)->elf_header->e_type == ET_EXEC
1314 || (elf_tdata (abfd)->elf_header->e_type == ET_DYN
1315 && elf_tdata (abfd)->is_pie)))
1316 fatal (_("%P: cannot use executable file '%pB' as input to a link\n"),
1317 abfd);
1318 }
1319
1320 if (bfd_link_relocatable (&link_info))
1321 {
1322 if (link_info.execstack == !link_info.noexecstack)
1323 {
1324 /* PR ld/16744: If "-z [no]execstack" has been specified on the
1325 command line and we are perfoming a relocatable link then no
1326 PT_GNU_STACK segment will be created and so the
1327 linkinfo.[no]execstack values set in _handle_option() will have no
1328 effect. Instead we create a .note.GNU-stack section in much the
1329 same way as the assembler does with its --[no]execstack option. */
1330 flagword flags = SEC_READONLY | (link_info.execstack ? SEC_CODE : 0);
1331 (void) bfd_make_section_with_flags (link_info.input_bfds,
1332 ".note.GNU-stack", flags);
1333 }
1334 return;
1335 }
1336
1337 if (!link_info.traditional_format)
1338 {
1339 bfd *elfbfd = NULL;
1340 bool warn_eh_frame = false;
1341 int seen_type = 0;
1342
1343 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1344 {
1345 int type = 0;
1346
1347 if (bfd_input_just_syms (abfd))
1348 continue;
1349
1350 for (s = abfd->sections; s && type < COMPACT_EH_HDR; s = s->next)
1351 {
1352 const char *name = bfd_section_name (s);
1353
1354 if (bfd_is_abs_section (s->output_section))
1355 continue;
1356 if (startswith (name, ".eh_frame_entry"))
1357 type = COMPACT_EH_HDR;
1358 else if (strcmp (name, ".eh_frame") == 0 && s->size > 8)
1359 type = DWARF2_EH_HDR;
1360 }
1361
1362 if (type != 0)
1363 {
1364 if (seen_type == 0)
1365 {
1366 seen_type = type;
1367 }
1368 else if (seen_type != type)
1369 {
1370 fatal (_("%P: compact frame descriptions incompatible with"
1371 " DWARF2 .eh_frame from %pB\n"),
1372 type == DWARF2_EH_HDR ? abfd : elfbfd);
1373 break;
1374 }
1375
1376 if (!elfbfd
1377 && (type == COMPACT_EH_HDR
1378 || link_info.eh_frame_hdr_type != 0))
1379 {
1380 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1381 elfbfd = abfd;
1382
1383 warn_eh_frame = true;
1384 }
1385 }
1386
1387 if (seen_type == COMPACT_EH_HDR)
1388 link_info.eh_frame_hdr_type = COMPACT_EH_HDR;
1389 }
1390 if (elfbfd)
1391 {
1392 elf_backend_data *bed = get_elf_backend_data (elfbfd);
1393 s = bfd_make_section_with_flags (elfbfd, ".eh_frame_hdr",
1394 bed->dynamic_sec_flags
1395 | SEC_READONLY);
1396 if (s != NULL
1397 && bfd_set_section_alignment (s, 2))
1398 {
1399 htab->eh_info.hdr_sec = s;
1400 warn_eh_frame = false;
1401 }
1402 }
1403 if (warn_eh_frame)
1404 einfo (_("%P: warning: cannot create .eh_frame_hdr section,"
1405 " --eh-frame-hdr ignored\n"));
1406 }
1407
1408 if (link_info.eh_frame_hdr_type == COMPACT_EH_HDR)
1409 if (!bfd_elf_parse_eh_frame_entries (NULL, &link_info))
1410 fatal (_("%P: failed to parse EH frame entries\n"));
1411
1412 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1413 is_freebsd, elfsize, prefix);
1414 }
1415
1416 static bfd_size_type
1417 id_note_section_size (bfd *abfd ATTRIBUTE_UNUSED)
1418 {
1419 const char *style = ldelf_emit_note_gnu_build_id;
1420 bfd_size_type size;
1421 bfd_size_type build_id_size;
1422
1423 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1424 size = (size + 3) & -(bfd_size_type) 4;
1425
1426 build_id_size = compute_build_id_size (style);
1427 if (build_id_size)
1428 size += build_id_size;
1429 else
1430 size = 0;
1431
1432 return size;
1433 }
1434
1435 static bool
1436 write_build_id (bfd *abfd)
1437 {
1438 elf_backend_data *bed = get_elf_backend_data (abfd);
1439 struct elf_obj_tdata *t = elf_tdata (abfd);
1440 const char *style;
1441 asection *asec;
1442 Elf_Internal_Shdr *i_shdr;
1443 unsigned char *contents, *id_bits;
1444 bfd_size_type size;
1445 file_ptr position;
1446 Elf_External_Note *e_note;
1447
1448 style = t->o->build_id.style;
1449 asec = t->o->build_id.sec;
1450 if (bfd_is_abs_section (asec->output_section))
1451 {
1452 einfo (_("%P: warning: .note.gnu.build-id section discarded,"
1453 " --build-id ignored\n"));
1454 return true;
1455 }
1456 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1457
1458 if (i_shdr->contents != NULL)
1459 contents = i_shdr->contents + asec->output_offset;
1460 else if (asec->contents != NULL)
1461 contents = asec->contents;
1462 else
1463 contents = xmalloc (asec->size);
1464
1465 e_note = (Elf_External_Note *) contents;
1466 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1467 size = (size + 3) & -(bfd_size_type) 4;
1468 id_bits = contents + size;
1469 size = asec->size - size;
1470
1471 /* Clear the build ID field. */
1472 memset (id_bits, 0, size);
1473
1474 bfd_h_put_32 (abfd, sizeof "GNU", &e_note->namesz);
1475 bfd_h_put_32 (abfd, size, &e_note->descsz);
1476 bfd_h_put_32 (abfd, NT_GNU_BUILD_ID, &e_note->type);
1477 memcpy (e_note->name, "GNU", sizeof "GNU");
1478
1479 generate_build_id (abfd, style, bed->s->checksum_contents, id_bits, size);
1480
1481 position = i_shdr->sh_offset + asec->output_offset;
1482 size = asec->size;
1483 bool ret = (bfd_seek (abfd, position, SEEK_SET) == 0
1484 && bfd_write (contents, size, abfd) == size);
1485 if (i_shdr->contents == NULL && asec->contents == NULL)
1486 free (contents);
1487 return ret;
1488 }
1489
1490 /* Make .note.gnu.build-id section, and set up elf_tdata->build_id. */
1491
1492 bool
1493 ldelf_setup_build_id (bfd *ibfd)
1494 {
1495 asection *s;
1496 bfd_size_type size;
1497 flagword flags;
1498
1499 size = id_note_section_size (ibfd);
1500 if (size == 0)
1501 {
1502 einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1503 return false;
1504 }
1505
1506 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1507 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1508 s = bfd_make_section_anyway_with_flags (ibfd, ".note.gnu.build-id",
1509 flags);
1510 if (s != NULL && bfd_set_section_alignment (s, 2))
1511 {
1512 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1513 t->o->build_id.after_write_object_contents = &write_build_id;
1514 t->o->build_id.style = ldelf_emit_note_gnu_build_id;
1515 t->o->build_id.sec = s;
1516 elf_section_type (s) = SHT_NOTE;
1517 s->size = size;
1518 return true;
1519 }
1520
1521 einfo (_("%P: warning: cannot create .note.gnu.build-id section,"
1522 " --build-id ignored\n"));
1523 return false;
1524 }
1525
1526 static bool
1527 write_package_metadata (bfd *abfd)
1528 {
1529 struct elf_obj_tdata *t = elf_tdata (abfd);
1530 const char *json;
1531 asection *asec;
1532 Elf_Internal_Shdr *i_shdr;
1533 unsigned char *contents, *json_bits;
1534 bfd_size_type size;
1535 file_ptr position;
1536 Elf_External_Note *e_note;
1537
1538 json = t->o->package_metadata.json;
1539 asec = t->o->package_metadata.sec;
1540 if (bfd_is_abs_section (asec->output_section))
1541 {
1542 einfo (_("%P: warning: .note.package section discarded,"
1543 " --package-metadata ignored\n"));
1544 return true;
1545 }
1546 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1547
1548 if (i_shdr->contents != NULL)
1549 contents = i_shdr->contents + asec->output_offset;
1550 else if (asec->contents != NULL)
1551 contents = asec->contents;
1552 else
1553 contents = xmalloc (asec->size);
1554
1555 e_note = (Elf_External_Note *) contents;
1556 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1557 size = (size + 3) & -(bfd_size_type) 4;
1558 json_bits = contents + size;
1559 size = asec->size - size;
1560
1561 /* Clear the package metadata field. */
1562 memset (json_bits, 0, size);
1563
1564 bfd_h_put_32 (abfd, sizeof "FDO", &e_note->namesz);
1565 bfd_h_put_32 (abfd, size, &e_note->descsz);
1566 bfd_h_put_32 (abfd, FDO_PACKAGING_METADATA, &e_note->type);
1567 memcpy (e_note->name, "FDO", sizeof "FDO");
1568 memcpy (json_bits, json, strlen(json));
1569
1570 position = i_shdr->sh_offset + asec->output_offset;
1571 size = asec->size;
1572 bool ret = (bfd_seek (abfd, position, SEEK_SET) == 0
1573 && bfd_write (contents, size, abfd) == size);
1574 if (i_shdr->contents == NULL && asec->contents == NULL)
1575 free (contents);
1576 return ret;
1577 }
1578
1579 /* Make .note.package section.
1580 https://systemd.io/ELF_PACKAGE_METADATA/ */
1581
1582 bool
1583 ldelf_setup_package_metadata (bfd *ibfd)
1584 {
1585 asection *s;
1586 bfd_size_type size;
1587 size_t json_length;
1588 flagword flags;
1589
1590 /* If the option wasn't specified, silently return. */
1591 if (!ldelf_emit_note_fdo_package_metadata)
1592 return false;
1593
1594 /* The option was specified, but it's empty, log and return. */
1595 json_length = strlen (ldelf_emit_note_fdo_package_metadata);
1596 if (json_length == 0)
1597 {
1598 einfo (_("%P: warning: --package-metadata is empty, ignoring\n"));
1599 return false;
1600 }
1601
1602 #ifdef HAVE_JANSSON
1603 json_error_t json_error;
1604 json_t *json = json_loads (ldelf_emit_note_fdo_package_metadata,
1605 0, &json_error);
1606 if (!json)
1607 {
1608 einfo (_("%P: warning: --package-metadata=%s does not contain valid "
1609 "JSON, ignoring: %s\n"),
1610 ldelf_emit_note_fdo_package_metadata, json_error.text);
1611 return false;
1612 }
1613 else
1614 json_decref (json);
1615 #endif
1616
1617 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1618 size += json_length + 1;
1619 size = (size + 3) & -(bfd_size_type) 4;
1620
1621 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1622 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1623 s = bfd_make_section_anyway_with_flags (ibfd, ".note.package",
1624 flags);
1625 if (s != NULL && bfd_set_section_alignment (s, 2))
1626 {
1627 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1628 t->o->package_metadata.after_write_object_contents
1629 = &write_package_metadata;
1630 t->o->package_metadata.json = ldelf_emit_note_fdo_package_metadata;
1631 t->o->package_metadata.sec = s;
1632 elf_section_type (s) = SHT_NOTE;
1633 s->size = size;
1634 return true;
1635 }
1636
1637 einfo (_("%P: warning: cannot create .note.package section,"
1638 " --package-metadata ignored\n"));
1639 return false;
1640 }
1641
1642 /* Look through an expression for an assignment statement. */
1643
1644 static void
1645 ldelf_find_exp_assignment (etree_type *exp)
1646 {
1647 bool provide = false;
1648
1649 switch (exp->type.node_class)
1650 {
1651 case etree_provide:
1652 case etree_provided:
1653 provide = true;
1654 /* Fallthru */
1655 case etree_assign:
1656 /* We call record_link_assignment even if the symbol is defined.
1657 This is because if it is defined by a dynamic object, we
1658 actually want to use the value defined by the linker script,
1659 not the value from the dynamic object (because we are setting
1660 symbols like etext). If the symbol is defined by a regular
1661 object, then, as it happens, calling record_link_assignment
1662 will do no harm. */
1663 if (strcmp (exp->assign.dst, ".") != 0)
1664 {
1665 if (!bfd_elf_record_link_assignment (link_info.output_bfd,
1666 &link_info,
1667 exp->assign.dst, provide,
1668 exp->assign.hidden))
1669 fatal (_("%P: failed to record assignment to %s: %E\n"),
1670 exp->assign.dst);
1671 }
1672 ldelf_find_exp_assignment (exp->assign.src);
1673 break;
1674
1675 case etree_binary:
1676 ldelf_find_exp_assignment (exp->binary.lhs);
1677 ldelf_find_exp_assignment (exp->binary.rhs);
1678 break;
1679
1680 case etree_trinary:
1681 ldelf_find_exp_assignment (exp->trinary.cond);
1682 ldelf_find_exp_assignment (exp->trinary.lhs);
1683 ldelf_find_exp_assignment (exp->trinary.rhs);
1684 break;
1685
1686 case etree_unary:
1687 ldelf_find_exp_assignment (exp->unary.child);
1688 break;
1689
1690 default:
1691 break;
1692 }
1693 }
1694
1695 /* This is called by the before_allocation routine via
1696 lang_for_each_statement. It locates any assignment statements, and
1697 tells the ELF backend about them, in case they are assignments to
1698 symbols which are referred to by dynamic objects. */
1699
1700 static void
1701 ldelf_find_statement_assignment (lang_statement_union_type *s)
1702 {
1703 if (s->header.type == lang_assignment_statement_enum)
1704 ldelf_find_exp_assignment (s->assignment_statement.exp);
1705 }
1706
1707 /* Used by before_allocation and handle_option. */
1708
1709 void
1710 ldelf_append_to_separated_string (char **to, char *op_arg)
1711 {
1712 if (*to == NULL)
1713 *to = xstrdup (op_arg);
1714 else
1715 {
1716 size_t to_len = strlen (*to);
1717 size_t op_arg_len = strlen (op_arg);
1718 char *buf;
1719 char *cp = *to;
1720
1721 /* First see whether OPTARG is already in the path. */
1722 do
1723 {
1724 if (strncmp (op_arg, cp, op_arg_len) == 0
1725 && (cp[op_arg_len] == 0
1726 || cp[op_arg_len] == config.rpath_separator))
1727 /* We found it. */
1728 break;
1729
1730 /* Not yet found. */
1731 cp = strchr (cp, config.rpath_separator);
1732 if (cp != NULL)
1733 ++cp;
1734 }
1735 while (cp != NULL);
1736
1737 if (cp == NULL)
1738 {
1739 buf = xmalloc (to_len + op_arg_len + 2);
1740 sprintf (buf, "%s%c%s", *to,
1741 config.rpath_separator, op_arg);
1742 free (*to);
1743 *to = buf;
1744 }
1745 }
1746 }
1747
1748 /* This is called after the sections have been attached to output
1749 sections, but before any sizes or addresses have been set. */
1750
1751 void
1752 ldelf_before_allocation (char **audit, char **depaudit,
1753 const char *default_interpreter_name)
1754 {
1755 const char *rpath;
1756 asection *sinterp;
1757 bfd *abfd;
1758 struct bfd_link_hash_entry *ehdr_start = NULL;
1759 unsigned char ehdr_start_save_type = 0;
1760 char ehdr_start_save_u[sizeof ehdr_start->u
1761 - sizeof ehdr_start->u.def.next] = "";
1762
1763 if (is_elf_hash_table (link_info.hash))
1764 {
1765 bfd_elf_tls_setup (link_info.output_bfd, &link_info);
1766
1767 /* Make __ehdr_start hidden if it has been referenced, to
1768 prevent the symbol from being dynamic. */
1769 if (!bfd_link_relocatable (&link_info))
1770 {
1771 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1772 struct elf_link_hash_entry *h = htab->hehdr_start;
1773
1774 /* Only adjust the export class if the symbol was referenced
1775 and not defined, otherwise leave it alone. */
1776 if (h != NULL
1777 && (h->root.type == bfd_link_hash_new
1778 || h->root.type == bfd_link_hash_undefined
1779 || h->root.type == bfd_link_hash_undefweak
1780 || h->root.type == bfd_link_hash_common))
1781 {
1782 /* Don't leave the symbol undefined. Undefined hidden
1783 symbols typically won't have dynamic relocations, but
1784 we most likely will need dynamic relocations for
1785 __ehdr_start if we are building a PIE or shared
1786 library. */
1787 ehdr_start = &h->root;
1788 ehdr_start_save_type = ehdr_start->type;
1789 memcpy (ehdr_start_save_u,
1790 (char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1791 sizeof ehdr_start_save_u);
1792 ehdr_start->type = bfd_link_hash_defined;
1793 /* It will be converted to section-relative later. */
1794 ehdr_start->u.def.section = bfd_abs_section_ptr;
1795 ehdr_start->u.def.value = 0;
1796 }
1797 }
1798
1799 /* If we are going to make any variable assignments, we need to
1800 let the ELF backend know about them in case the variables are
1801 referred to by dynamic objects. */
1802 lang_for_each_statement (ldelf_find_statement_assignment);
1803 }
1804
1805 /* Let the ELF backend work out the sizes of any sections required
1806 by dynamic linking. */
1807 rpath = command_line.rpath;
1808 if (rpath == NULL)
1809 rpath = (const char *) getenv ("LD_RUN_PATH");
1810
1811 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1812 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1813 {
1814 const char *audit_libs = elf_dt_audit (abfd);
1815
1816 /* If the input bfd contains an audit entry, we need to add it as
1817 a dep audit entry. */
1818 if (audit_libs && *audit_libs != '\0')
1819 {
1820 char *copy_audit_libs = xstrdup (audit_libs);
1821 char *cp = copy_audit_libs;
1822 do
1823 {
1824 char *cp2 = strchr (cp, config.rpath_separator);
1825
1826 if (cp2)
1827 *cp2++ = '\0';
1828
1829 if (*cp != '\0')
1830 ldelf_append_to_separated_string (depaudit, cp);
1831
1832 cp = cp2;
1833 }
1834 while (cp != NULL);
1835 free (copy_audit_libs);
1836 }
1837 }
1838
1839 if (! (bfd_elf_size_dynamic_sections
1840 (link_info.output_bfd, command_line.soname, rpath,
1841 command_line.filter_shlib, *audit, *depaudit,
1842 (const char * const *) command_line.auxiliary_filters,
1843 &link_info, &sinterp)))
1844 fatal (_("%P: failed to set dynamic section sizes: %E\n"));
1845
1846 if (sinterp != NULL)
1847 {
1848 /* Let the user override the dynamic linker we are using. */
1849 if (command_line.interpreter != NULL)
1850 default_interpreter_name = command_line.interpreter;
1851 if (default_interpreter_name != NULL)
1852 {
1853 sinterp->contents = (bfd_byte *) default_interpreter_name;
1854 sinterp->alloced = 1;
1855 sinterp->size = strlen ((char *) sinterp->contents) + 1;
1856 }
1857 }
1858
1859 /* Look for any sections named .gnu.warning. As a GNU extensions,
1860 we treat such sections as containing warning messages. We print
1861 out the warning message, and then zero out the section size so
1862 that it does not get copied into the output file. */
1863
1864 {
1865 LANG_FOR_EACH_INPUT_STATEMENT (is)
1866 {
1867 asection *s;
1868 bfd_size_type sz;
1869 char *msg;
1870
1871 if (is->flags.just_syms)
1872 continue;
1873
1874 s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1875 if (s == NULL)
1876 continue;
1877
1878 sz = s->size;
1879 msg = (char *) xmalloc ((size_t) (sz + 1));
1880 if (! bfd_get_section_contents (is->the_bfd, s, msg,
1881 (file_ptr) 0, sz))
1882 fatal (_("%P: %pB: can't read contents of section %pA: %E\n"),
1883 is->the_bfd, s);
1884 msg[sz] = '\0';
1885 (*link_info.callbacks->warning) (&link_info, msg,
1886 (const char *) NULL, is->the_bfd,
1887 (asection *) NULL, (bfd_vma) 0);
1888 free (msg);
1889
1890 /* Clobber the section size, so that we don't waste space
1891 copying the warning into the output file. If we've already
1892 sized the output section, adjust its size. The adjustment
1893 is on rawsize because targets that size sections early will
1894 have called lang_reset_memory_regions after sizing. */
1895 if (s->output_section != NULL
1896 && s->output_section->rawsize >= s->size)
1897 s->output_section->rawsize -= s->size;
1898
1899 s->size = 0;
1900
1901 /* Also set SEC_EXCLUDE, so that local symbols defined in the
1902 warning section don't get copied to the output. */
1903 s->flags |= SEC_EXCLUDE | SEC_KEEP;
1904 }
1905 }
1906
1907 before_allocation_default ();
1908
1909 if (!bfd_elf_size_dynsym_hash_dynstr (link_info.output_bfd, &link_info))
1910 fatal (_("%P: failed to set dynamic section sizes: %E\n"));
1911
1912 if (ehdr_start != NULL)
1913 {
1914 /* If we twiddled __ehdr_start to defined earlier, put it back
1915 as it was. */
1916 ehdr_start->type = ehdr_start_save_type;
1917 memcpy ((char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1918 ehdr_start_save_u,
1919 sizeof ehdr_start_save_u);
1920 }
1921 }
1922 /* Try to open a dynamic archive. This is where we know that ELF
1923 dynamic libraries have an extension of .so (or .sl on oddball systems
1924 like hpux). */
1925
1926 bool
1927 ldelf_open_dynamic_archive (const char *arch, search_dirs_type *search,
1928 lang_input_statement_type *entry)
1929 {
1930 const char *filename;
1931 char *string;
1932 size_t len;
1933 bool opened = false;
1934
1935 if (! entry->flags.maybe_archive)
1936 return false;
1937
1938 filename = entry->filename;
1939 len = strlen (search->name) + strlen (filename);
1940 if (entry->flags.full_name_provided)
1941 {
1942 len += sizeof "/";
1943 string = (char *) xmalloc (len);
1944 sprintf (string, "%s/%s", search->name, filename);
1945 }
1946 else
1947 {
1948 size_t xlen = 0;
1949
1950 len += strlen (arch) + sizeof "/lib.so";
1951 #ifdef EXTRA_SHLIB_EXTENSION
1952 xlen = (strlen (EXTRA_SHLIB_EXTENSION) > 3
1953 ? strlen (EXTRA_SHLIB_EXTENSION) - 3
1954 : 0);
1955 #endif
1956 string = (char *) xmalloc (len + xlen);
1957 sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1958 #ifdef EXTRA_SHLIB_EXTENSION
1959 /* Try the .so extension first. If that fails build a new filename
1960 using EXTRA_SHLIB_EXTENSION. */
1961 opened = ldfile_try_open_bfd (string, entry);
1962 if (!opened)
1963 strcpy (string + len - 4, EXTRA_SHLIB_EXTENSION);
1964 #endif
1965 }
1966
1967 if (!opened && !ldfile_try_open_bfd (string, entry))
1968 {
1969 free (string);
1970 return false;
1971 }
1972
1973 entry->filename = string;
1974
1975 /* We have found a dynamic object to include in the link. The ELF
1976 backend linker will create a DT_NEEDED entry in the .dynamic
1977 section naming this file. If this file includes a DT_SONAME
1978 entry, it will be used. Otherwise, the ELF linker will just use
1979 the name of the file. For an archive found by searching, like
1980 this one, the DT_NEEDED entry should consist of just the name of
1981 the file, without the path information used to find it. Note
1982 that we only need to do this if we have a dynamic object; an
1983 archive will never be referenced by a DT_NEEDED entry.
1984
1985 FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1986 very pretty. I haven't been able to think of anything that is
1987 pretty, though. */
1988 if (bfd_check_format (entry->the_bfd, bfd_object)
1989 && (entry->the_bfd->flags & DYNAMIC) != 0)
1990 {
1991 ASSERT (entry->flags.maybe_archive && entry->flags.search_dirs);
1992
1993 /* Rather than duplicating the logic above. Just use the
1994 filename we recorded earlier. */
1995
1996 if (!entry->flags.full_name_provided)
1997 filename = lbasename (entry->filename);
1998 bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
1999 }
2000
2001 return true;
2002 }
2003
2004 /* A variant of lang_output_section_find used by place_orphan. */
2005
2006 static lang_output_section_statement_type *
2007 output_rel_find (int isdyn, int rela)
2008 {
2009 lang_output_section_statement_type *lookup;
2010 lang_output_section_statement_type *last = NULL;
2011 lang_output_section_statement_type *last_alloc = NULL;
2012 lang_output_section_statement_type *last_ro_alloc = NULL;
2013 lang_output_section_statement_type *last_rel = NULL;
2014 lang_output_section_statement_type *last_rel_alloc = NULL;
2015
2016 for (lookup = (void *) lang_os_list.head;
2017 lookup != NULL;
2018 lookup = lookup->next)
2019 {
2020 if (lookup->constraint >= 0
2021 && startswith (lookup->name, ".rel"))
2022 {
2023 int lookrela = lookup->name[4] == 'a';
2024
2025 /* .rel.dyn must come before all other reloc sections, to suit
2026 GNU ld.so. */
2027 if (isdyn)
2028 break;
2029
2030 /* Don't place after .rel.plt as doing so results in wrong
2031 dynamic tags. */
2032 if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
2033 break;
2034
2035 if (rela == lookrela || last_rel == NULL)
2036 last_rel = lookup;
2037 if ((rela == lookrela || last_rel_alloc == NULL)
2038 && lookup->bfd_section != NULL
2039 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2040 last_rel_alloc = lookup;
2041 }
2042
2043 last = lookup;
2044 if (lookup->bfd_section != NULL
2045 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2046 {
2047 last_alloc = lookup;
2048 if ((lookup->bfd_section->flags & SEC_READONLY) != 0)
2049 last_ro_alloc = lookup;
2050 }
2051 }
2052
2053 if (last_rel_alloc)
2054 return last_rel_alloc;
2055
2056 if (last_rel)
2057 return last_rel;
2058
2059 if (last_ro_alloc)
2060 return last_ro_alloc;
2061
2062 if (last_alloc)
2063 return last_alloc;
2064
2065 return last;
2066 }
2067
2068 /* Return whether IN is suitable to be part of OUT. */
2069
2070 static bool
2071 elf_orphan_compatible (asection *in, asection *out)
2072 {
2073 /* Non-zero sh_info implies a section with SHF_INFO_LINK with
2074 unknown semantics for the generic linker, or a SHT_REL/SHT_RELA
2075 section where sh_info specifies a symbol table. (We won't see
2076 SHT_GROUP, SHT_SYMTAB or SHT_DYNSYM sections here.) We clearly
2077 can't merge SHT_REL/SHT_RELA using differing symbol tables, and
2078 shouldn't merge sections with differing unknown semantics. */
2079 if (elf_section_data (out)->this_hdr.sh_info
2080 != elf_section_data (in)->this_hdr.sh_info)
2081 return false;
2082 /* We can't merge with a member of an output section group or merge
2083 two sections with differing SHF_EXCLUDE or other processor and OS
2084 specific flags or with different SHF_LINK_ORDER when doing a
2085 relocatable link. */
2086 if (bfd_link_relocatable (&link_info)
2087 && (elf_next_in_group (out) != NULL
2088 || ((elf_section_flags (in) & SHF_LINK_ORDER) != 0
2089 && (elf_section_flags (out) & SHF_LINK_ORDER) != 0
2090 && elf_linked_to_section (in) != NULL
2091 && (elf_linked_to_section (in)->output_section
2092 != elf_linked_to_section (out)->output_section))
2093 || ((elf_section_flags (out) ^ elf_section_flags (in))
2094 & (SHF_MASKPROC | SHF_MASKOS)) != 0))
2095 return false;
2096 return bfd_elf_match_sections_by_type (link_info.output_bfd, out,
2097 in->owner, in);
2098 }
2099
2100 /* Place an orphan section. We use this to put random SHF_ALLOC
2101 sections in the right segment. */
2102
2103 lang_output_section_statement_type *
2104 ldelf_place_orphan (asection *s, const char *secname, int constraint)
2105 {
2106 static struct orphan_save orig_hold[] =
2107 {
2108 { ".text",
2109 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2110 0, 0, 0, 0 },
2111 { ".rodata",
2112 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2113 0, 0, 0, 0 },
2114 { ".tdata",
2115 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_THREAD_LOCAL,
2116 0, 0, 0, 0 },
2117 { ".data",
2118 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2119 0, 0, 0, 0 },
2120 { ".bss",
2121 SEC_ALLOC,
2122 0, 0, 0, 0 },
2123 { NULL,
2124 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2125 0, 0, 0, 0 },
2126 { ".interp",
2127 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2128 0, 0, 0, 0 },
2129 { ".sdata",
2130 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
2131 0, 0, 0, 0 },
2132 { ".comment",
2133 SEC_HAS_CONTENTS,
2134 0, 0, 0, 0 },
2135 };
2136 static struct orphan_save hold[ARRAY_SIZE (orig_hold)];
2137 enum orphan_save_index
2138 {
2139 orphan_text = 0,
2140 orphan_rodata,
2141 orphan_tdata,
2142 orphan_data,
2143 orphan_bss,
2144 orphan_rel,
2145 orphan_interp,
2146 orphan_sdata,
2147 orphan_nonalloc
2148 };
2149 struct orphan_save *place;
2150 lang_output_section_statement_type *after;
2151 lang_output_section_statement_type *os;
2152 lang_output_section_statement_type *match_by_name = NULL;
2153 int isdyn = 0;
2154 int elfinput = s->owner->xvec->flavour == bfd_target_elf_flavour;
2155 int elfoutput = link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour;
2156 unsigned int sh_type = elfinput ? elf_section_type (s) : SHT_NULL;
2157 flagword flags;
2158 asection *nexts;
2159
2160 if (!bfd_link_relocatable (&link_info)
2161 && link_info.combreloc
2162 && (s->flags & SEC_ALLOC))
2163 {
2164 if (elfinput)
2165 switch (sh_type)
2166 {
2167 case SHT_RELA:
2168 secname = ".rela.dyn";
2169 isdyn = 1;
2170 break;
2171 case SHT_REL:
2172 secname = ".rel.dyn";
2173 isdyn = 1;
2174 break;
2175 default:
2176 break;
2177 }
2178 else if (startswith (secname, ".rel"))
2179 {
2180 secname = secname[4] == 'a' ? ".rela.dyn" : ".rel.dyn";
2181 isdyn = 1;
2182 }
2183 }
2184
2185 if (!bfd_link_relocatable (&link_info)
2186 && elfinput
2187 && elfoutput
2188 && (s->flags & SEC_ALLOC) != 0
2189 && (elf_tdata (s->owner)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0
2190 && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
2191 {
2192 /* Find the output mbind section with the same type, attributes
2193 and sh_info field. */
2194 for (os = (void *) lang_os_list.head;
2195 os != NULL;
2196 os = os->next)
2197 if (os->bfd_section != NULL
2198 && !bfd_is_abs_section (os->bfd_section)
2199 && (elf_section_flags (os->bfd_section) & SHF_GNU_MBIND) != 0
2200 && ((s->flags & (SEC_ALLOC
2201 | SEC_LOAD
2202 | SEC_HAS_CONTENTS
2203 | SEC_READONLY
2204 | SEC_CODE))
2205 == (os->bfd_section->flags & (SEC_ALLOC
2206 | SEC_LOAD
2207 | SEC_HAS_CONTENTS
2208 | SEC_READONLY
2209 | SEC_CODE)))
2210 && (elf_section_data (os->bfd_section)->this_hdr.sh_info
2211 == elf_section_data (s)->this_hdr.sh_info))
2212 {
2213 lang_add_section (&os->children, s, NULL, NULL, os);
2214 return os;
2215 }
2216
2217 /* Create the output mbind section with the ".mbind." prefix
2218 in section name. */
2219 if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2220 secname = ".mbind.bss";
2221 else if ((s->flags & SEC_READONLY) == 0)
2222 secname = ".mbind.data";
2223 else if ((s->flags & SEC_CODE) == 0)
2224 secname = ".mbind.rodata";
2225 else
2226 secname = ".mbind.text";
2227 elf_tdata (link_info.output_bfd)->has_gnu_osabi |= elf_gnu_osabi_mbind;
2228 }
2229
2230 /* Look through the script to see where to place this section. The
2231 script includes entries added by previous lang_insert_orphan
2232 calls, so this loop puts multiple compatible orphans of the same
2233 name into a single output section. */
2234 if (constraint == 0)
2235 for (os = lang_output_section_find (secname);
2236 os != NULL;
2237 os = next_matching_output_section_statement (os, 0))
2238 {
2239 /* If we don't match an existing output section, tell
2240 lang_insert_orphan to create a new output section. */
2241 constraint = SPECIAL;
2242
2243 /* Check to see if we already have an output section statement
2244 with this name, and its bfd section has compatible flags.
2245 If the section already exists but does not have any flags
2246 set, then it has been created by the linker, possibly as a
2247 result of a --section-start command line switch. */
2248 if (os->bfd_section != NULL
2249 && !bfd_is_abs_section (os->bfd_section)
2250 && (os->bfd_section->flags == 0
2251 || (((s->flags ^ os->bfd_section->flags)
2252 & (SEC_LOAD | SEC_ALLOC)) == 0
2253 && (!elfinput
2254 || !elfoutput
2255 || elf_orphan_compatible (s, os->bfd_section)))))
2256 {
2257 lang_add_section (&os->children, s, NULL, NULL, os);
2258 return os;
2259 }
2260
2261 /* Save unused output sections in case we can match them
2262 against orphans later. */
2263 if (os->bfd_section == NULL)
2264 match_by_name = os;
2265 }
2266
2267 /* If we didn't match an active output section, see if we matched an
2268 unused one and use that. */
2269 if (match_by_name)
2270 {
2271 lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2272 return match_by_name;
2273 }
2274
2275 if (!orphan_init_done)
2276 {
2277 struct orphan_save *ho, *horig;
2278
2279 for (ho = hold, horig = orig_hold;
2280 ho < hold + ARRAY_SIZE (hold);
2281 ++ho, ++horig)
2282 {
2283 *ho = *horig;
2284 if (ho->name != NULL)
2285 {
2286 ho->os = lang_output_section_find (ho->name);
2287 if (ho->os != NULL && ho->os->flags == 0)
2288 ho->os->flags = ho->flags;
2289 }
2290 }
2291 orphan_init_done = true;
2292 }
2293
2294 /* If this is a final link, then always put .gnu.warning.SYMBOL
2295 sections into the .text section to get them out of the way. */
2296 if (bfd_link_executable (&link_info)
2297 && startswith (s->name, ".gnu.warning.")
2298 && hold[orphan_text].os != NULL)
2299 {
2300 os = hold[orphan_text].os;
2301 lang_add_section (&os->children, s, NULL, NULL, os);
2302 return os;
2303 }
2304
2305 flags = s->flags;
2306 if (!bfd_link_relocatable (&link_info))
2307 {
2308 nexts = s;
2309 while ((nexts = bfd_get_next_section_by_name (nexts->owner, nexts))
2310 != NULL)
2311 if (nexts->output_section == NULL
2312 && (nexts->flags & SEC_EXCLUDE) == 0
2313 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2314 && (nexts->owner->flags & DYNAMIC) == 0
2315 && !bfd_input_just_syms (nexts->owner)
2316 && bfd_elf_match_sections_by_type (nexts->owner, nexts,
2317 s->owner, s))
2318 flags = (((flags ^ SEC_READONLY)
2319 | (nexts->flags ^ SEC_READONLY))
2320 ^ SEC_READONLY);
2321 }
2322
2323 /* Decide which segment the section should go in based on the
2324 section name and section flags. We put loadable .note sections
2325 right after the .interp section, so that the PT_NOTE segment is
2326 stored right after the program headers where the OS can read it
2327 in the first page. */
2328
2329 place = NULL;
2330 if ((flags & (SEC_ALLOC | SEC_DEBUGGING)) == 0)
2331 place = &hold[orphan_nonalloc];
2332 else if ((flags & SEC_ALLOC) == 0)
2333 ;
2334 else if ((flags & SEC_LOAD) != 0
2335 && (elfinput
2336 ? sh_type == SHT_NOTE
2337 : startswith (secname, ".note")))
2338 {
2339 /* PR 32219: Check that the .interp section
2340 exists before attaching orphans to it. */
2341 if (lang_output_section_find (hold[orphan_interp].name))
2342 place = &hold[orphan_interp];
2343 /* Next best place: after .rodata. */
2344 else if (lang_output_section_find (hold[orphan_rodata].name))
2345 place = &hold[orphan_rodata];
2346 /* Last attempt: the .text section. */
2347 else
2348 place = &hold[orphan_text];
2349 }
2350 else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS | SEC_THREAD_LOCAL)) == 0)
2351 place = &hold[orphan_bss];
2352 else if ((flags & SEC_SMALL_DATA) != 0)
2353 place = &hold[orphan_sdata];
2354 else if ((flags & SEC_THREAD_LOCAL) != 0)
2355 place = &hold[orphan_tdata];
2356 else if ((flags & SEC_READONLY) == 0)
2357 place = &hold[orphan_data];
2358 else if ((flags & SEC_LOAD) != 0
2359 && (elfinput
2360 ? sh_type == SHT_RELA || sh_type == SHT_REL
2361 : startswith (secname, ".rel")))
2362 place = &hold[orphan_rel];
2363 else if ((flags & SEC_CODE) == 0)
2364 place = &hold[orphan_rodata];
2365 else
2366 place = &hold[orphan_text];
2367
2368 after = NULL;
2369 if (place != NULL)
2370 {
2371 if (place->os == NULL)
2372 {
2373 if (place->name != NULL)
2374 place->os = lang_output_section_find (place->name);
2375 else
2376 {
2377 int rela = elfinput ? sh_type == SHT_RELA : secname[4] == 'a';
2378 place->os = output_rel_find (isdyn, rela);
2379 }
2380 }
2381 after = place->os;
2382 if (after == NULL)
2383 after
2384 = lang_output_section_find_by_flags (s, flags, &place->os,
2385 bfd_elf_match_sections_by_type);
2386 if (after == NULL)
2387 /* *ABS* is always the first output section statement. */
2388 after = (void *) lang_os_list.head;
2389 }
2390
2391 return lang_insert_orphan (s, secname, constraint, after, place, NULL, NULL);
2392 }
2393
2394 void
2395 ldelf_before_place_orphans (void)
2396 {
2397 bfd *abfd;
2398
2399 for (abfd = link_info.input_bfds;
2400 abfd != (bfd *) NULL; abfd = abfd->link.next)
2401 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2402 && bfd_count_sections (abfd) != 0
2403 && !bfd_input_just_syms (abfd))
2404 {
2405 asection *isec;
2406 for (isec = abfd->sections; isec != NULL; isec = isec->next)
2407 {
2408 /* Discard a section if any of its linked-to section has
2409 been discarded. */
2410 asection *linked_to_sec;
2411 for (linked_to_sec = elf_linked_to_section (isec);
2412 linked_to_sec != NULL && !linked_to_sec->linker_mark;
2413 linked_to_sec = elf_linked_to_section (linked_to_sec))
2414 {
2415 if (discarded_section (linked_to_sec))
2416 {
2417 isec->output_section = bfd_abs_section_ptr;
2418 isec->flags |= SEC_EXCLUDE;
2419 break;
2420 }
2421 linked_to_sec->linker_mark = 1;
2422 }
2423 for (linked_to_sec = elf_linked_to_section (isec);
2424 linked_to_sec != NULL && linked_to_sec->linker_mark;
2425 linked_to_sec = elf_linked_to_section (linked_to_sec))
2426 linked_to_sec->linker_mark = 0;
2427 }
2428 }
2429 }
2430
2431 void
2432 ldelf_set_output_arch (void)
2433 {
2434 set_output_arch_default ();
2435 if (link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour)
2436 elf_link_info (link_info.output_bfd) = &link_info;
2437 }
2438
2439 void
2440 ldelf_finish (void)
2441 {
2442 /* Support the object-only output. */
2443 if (config.emit_gnu_object_only)
2444 orphan_init_done = false;
2445
2446 finish_default ();
2447 }
2448