Add translations for various sub-directories
[binutils-gdb.git] / ld / ldelf.c
blobdbc3d77d47b0c54c694fe6c410a76b443b621639
1 /* ELF emulation code for targets using elf.em.
2 Copyright (C) 1991-2025 Free Software Foundation, Inc.
4 This file is part of the GNU Binutils.
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.
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.
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. */
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
46 struct dt_needed
48 bfd *by;
49 const char *name;
52 /* Style of .note.gnu.build-id section. */
53 const char *ldelf_emit_note_gnu_build_id;
55 /* Content of .note.package section. */
56 const char *ldelf_emit_note_fdo_package_metadata;
58 /* These variables are required to pass information back and forth
59 between after_open and check_needed and stat_needed and vercheck. */
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;
68 void
69 ldelf_after_parse (void)
71 if (bfd_link_pie (&link_info))
72 link_info.flags_1 |= (bfd_vma) DF_1_PIE;
74 if (bfd_link_executable (&link_info)
75 && link_info.nointerp)
77 if (link_info.dynamic_undefined_weak > 0)
78 queue_unknown_cmdline_warning ("-z dynamic-undefined-weak");
79 link_info.dynamic_undefined_weak = 0;
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;
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;
90 after_parse_default ();
91 if (link_info.commonpagesize > link_info.maxpagesize)
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 einfo (_("%F%P: common page size (0x%v) > maximum page size (0x%v)\n"),
99 link_info.commonpagesize, link_info.maxpagesize);
103 /* Handle the generation of DT_NEEDED tags. */
105 bool
106 ldelf_load_symbols (lang_input_statement_type *entry)
108 int link_class = 0;
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;
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;
122 if (entry->flags.just_syms
123 && (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) != 0)
124 einfo (_("%F%P: %pB: --just-symbols may not be used on DSO\n"),
125 entry->the_bfd);
127 if (link_class == 0
128 || (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) == 0)
129 return false;
131 bfd_elf_set_dyn_lib_class (entry->the_bfd,
132 (enum dynamic_lib_link_class) link_class);
134 /* Continue on with normal load_symbols processing. */
135 return false;
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.
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.
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. */
155 static void
156 ldelf_vercheck (lang_input_statement_type *s)
158 const char *soname;
159 struct bfd_link_needed_list *l;
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;
167 soname = bfd_elf_get_dt_soname (s->the_bfd);
168 if (soname == NULL)
169 soname = lbasename (bfd_get_filename (s->the_bfd));
171 for (l = global_vercheck_needed; l != NULL; l = l->next)
173 const char *suffix;
175 if (filename_cmp (soname, l->name) == 0)
177 /* Probably can't happen, but it's an easy check. */
178 continue;
181 if (strchr (l->name, '/') != NULL)
182 continue;
184 suffix = strstr (l->name, ".so.");
185 if (suffix == NULL)
186 continue;
188 suffix += sizeof ".so." - 1;
190 if (filename_ncmp (soname, l->name, suffix - l->name) == 0)
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;
204 /* See if an input file matches a DT_NEEDED entry by running stat on
205 the file. */
207 static void
208 ldelf_stat_needed (lang_input_statement_type *s)
210 struct stat st;
211 const char *suffix;
212 const char *soname;
214 if (global_found != NULL)
215 return;
216 if (s->the_bfd == NULL)
217 return;
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;
224 if (bfd_stat (s->the_bfd, &st) != 0)
226 einfo (_("%P: %pB: bfd_stat failed: %E\n"), s->the_bfd);
227 return;
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)
241 global_found = s;
242 return;
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. */
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;
261 soname = bfd_elf_get_dt_soname (s->the_bfd);
262 if (soname == NULL)
263 soname = lbasename (s->filename);
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);
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. */
275 static bool
276 ldelf_try_needed (struct dt_needed *needed, int force, int is_linux)
278 bfd *abfd;
279 const char *name = needed->name;
280 const char *soname;
281 int link_class;
283 abfd = bfd_openr (name, bfd_get_target (link_info.output_bfd));
284 if (abfd == NULL)
286 if (verbose)
287 info_msg (_("attempt to open %s failed\n"), name);
288 return false;
291 track_dependency_files (name);
293 /* Linker needs to decompress sections. */
294 abfd->flags |= BFD_DECOMPRESS;
296 if (! bfd_check_format (abfd, bfd_object))
298 bfd_close (abfd);
299 return false;
301 if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
303 bfd_close (abfd);
304 return false;
307 /* For DT_NEEDED, they have to match. */
308 if (abfd->xvec != link_info.output_bfd->xvec)
310 bfd_close (abfd);
311 return false;
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. */
319 if (!force)
321 struct bfd_link_needed_list *needs;
323 if (! bfd_elf_get_bfd_needed_list (abfd, &needs))
324 einfo (_("%F%P: %pB: bfd_elf_get_bfd_needed_list failed: %E\n"), abfd);
326 if (needs != NULL)
328 global_vercheck_needed = needs;
329 global_vercheck_failed = false;
330 lang_for_each_input_file (ldelf_vercheck);
331 if (global_vercheck_failed)
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;
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)
347 struct bfd_link_needed_list *l;
349 for (l = needs; l != NULL; l = l->next)
350 if (startswith (l->name, "libc.so"))
351 break;
352 if (l == NULL)
354 bfd_close (abfd);
355 return false;
361 /* We've found a dynamic object matching the DT_NEEDED entry. */
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. */
371 if (bfd_stat (abfd, &global_stat) != 0)
372 einfo (_("%F%P: %pB: bfd_stat failed: %E\n"), abfd);
374 /* First strip off everything before the last '/'. */
375 soname = lbasename (bfd_get_filename (abfd));
377 if (verbose)
378 info_msg (_("found %s at %s\n"), soname, name);
380 global_found = NULL;
381 lang_for_each_input_file (ldelf_stat_needed);
382 if (global_found != NULL)
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;
389 /* Specify the soname to use. */
390 bfd_elf_set_dt_needed_name (abfd, soname);
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;
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;
404 bfd_elf_set_dyn_lib_class (abfd, (enum dynamic_lib_link_class) link_class);
406 *link_info.input_bfds_tail = abfd;
407 link_info.input_bfds_tail = &abfd->link.next;
409 /* Add this file into the symbol table. */
410 if (! bfd_link_add_symbols (abfd, &link_info))
411 einfo (_("%F%P: %pB: error adding symbols: %E\n"), abfd);
413 return true;
416 /* Search for a needed file in a path. */
418 static bool
419 ldelf_search_needed (const char *path, struct dt_needed *n, int force,
420 int is_linux, int elfsize)
422 const char *s;
423 const char *name = n->name;
424 size_t len;
425 struct dt_needed needed;
427 if (name[0] == '/')
428 return ldelf_try_needed (n, force, is_linux);
430 if (path == NULL || *path == '\0')
431 return false;
433 needed.by = n->by;
434 needed.name = n->name;
436 len = strlen (name);
437 while (1)
439 unsigned offset = 0;
440 char * var;
441 char *filename, *sset;
443 s = strchr (path, config.rpath_separator);
444 if (s == NULL)
445 s = path + strlen (path);
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))
453 s = strchr (s + 1, config.rpath_separator);
454 if (s == NULL)
455 s = path + strlen (path);
457 #endif
458 filename = (char *) xmalloc (s - path + len + 2);
459 if (s == path)
460 sset = filename;
461 else
463 memcpy (filename, path, s - path);
464 filename[s - path] = '/';
465 sset = filename + (s - path) + 1;
467 strcpy (sset, name);
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)
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.
483 The ld.so manual page also states that it allows ${ORIGIN},
484 ${LIB} and ${PLATFORM}, so these are supported as well.
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);
494 if (end != NULL)
495 /* Temporarily terminate the filename at the end of the token. */
496 * end = 0;
498 if (*v == '{')
499 ++ v;
500 switch (*v++)
502 case 'O':
503 if (strcmp (v, "RIGIN") == 0 || strcmp (v, "RIGIN}") == 0)
505 /* ORIGIN - replace with the full path to the directory
506 containing the program or shared object. */
507 if (needed.by == NULL)
509 if (link_info.output_bfd == NULL)
511 break;
513 else
514 replacement = bfd_get_filename (link_info.output_bfd);
516 else
517 replacement = bfd_get_filename (needed.by);
519 if (replacement)
521 char * slash;
523 if (replacement[0] == '/')
524 freeme = xstrdup (replacement);
525 else
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);
537 replacement = freeme;
538 if ((slash = strrchr (replacement, '/')) != NULL)
539 * slash = 0;
542 break;
544 case 'L':
545 if (strcmp (v, "IB") == 0 || strcmp (v, "IB}") == 0)
547 /* LIB - replace with "lib" in 32-bit environments
548 and "lib64" in 64-bit environments. */
550 switch (elfsize)
552 case 32: replacement = "lib"; break;
553 case 64: replacement = "lib64"; break;
554 default:
555 abort ();
558 break;
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;
571 if (replacement)
573 char * filename2 = xmalloc (flen + strlen (replacement));
575 if (end)
577 sprintf (filename2, "%.*s%s/%s",
578 (int)(var - filename), filename,
579 replacement, end + 1);
580 offset = (var - filename) + 1 + strlen (replacement);
582 else
584 sprintf (filename2, "%.*s%s",
585 (int)(var - filename), filename,
586 replacement);
587 offset = var - filename + strlen (replacement);
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. */
595 else
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 = '/';
607 /* PR 20784: Make sure that we resume the scan *after*
608 the token that we could not replace. */
609 offset = (var + 1) - filename;
612 free (freeme);
615 needed.name = filename;
617 if (ldelf_try_needed (&needed, force, is_linux))
619 free (filename);
620 return true;
623 free (filename);
625 if (*s == '\0')
626 break;
627 path = s + 1;
630 return false;
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. */
638 static const char *
639 ldelf_add_sysroot (const char *path)
641 size_t len, extra;
642 const char *p;
643 char *ret, *q;
644 int dos_drive_sysroot = HAS_DRIVE_SPEC (ld_sysroot);
646 len = strlen (ld_sysroot);
647 for (extra = 0, p = path; ; )
649 int dos_drive = HAS_DRIVE_SPEC (p);
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])))
658 if (dos_drive && dos_drive_sysroot)
659 extra += len - 2;
660 else
661 extra += len;
663 p = strchr (p, config.rpath_separator);
664 if (!p)
665 break;
666 ++p;
669 ret = xmalloc (strlen (path) + extra + 1);
671 for (q = ret, p = path; ; )
673 const char *end;
674 int dos_drive = HAS_DRIVE_SPEC (p);
676 if (dos_drive)
678 *q++ = *p++;
679 *q++ = *p++;
681 if (IS_DIR_SEPARATOR (*p)
682 && (!dos_drive
683 || (dos_drive_sysroot
684 && ld_sysroot[0] == p[-2])))
686 if (dos_drive && dos_drive_sysroot)
688 strcpy (q, ld_sysroot + 2);
689 q += len - 2;
691 else
693 strcpy (q, ld_sysroot);
694 q += len;
697 end = strchr (p, config.rpath_separator);
698 if (end)
700 size_t n = end - p + 1;
701 strncpy (q, p, n);
702 q += n;
703 p += n;
705 else
707 strcpy (q, p);
708 break;
712 return ret;
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
722 static bool
723 ldelf_check_ld_elf_hints (const struct bfd_link_needed_list *l, int force,
724 int elfsize)
726 static bool initialized;
727 static const char *ld_elf_hints;
728 struct dt_needed needed;
730 if (!initialized)
732 FILE *f;
733 char *tmppath;
735 tmppath = concat (ld_sysroot, _PATH_ELF_HINTS, (const char *) NULL);
736 f = fopen (tmppath, FOPEN_RB);
737 free (tmppath);
738 if (f != NULL)
740 struct elfhints_hdr hdr;
742 if (fread (&hdr, 1, sizeof (hdr), f) == sizeof (hdr)
743 && hdr.magic == ELFHINTS_MAGIC
744 && hdr.version == 1)
746 if (fseek (f, hdr.strtab + hdr.dirlist, SEEK_SET) != -1)
748 char *b;
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);
755 free (b);
758 fclose (f);
761 initialized = true;
764 if (ld_elf_hints == NULL)
765 return false;
767 needed.by = l->by;
768 needed.name = l->name;
769 return ldelf_search_needed (ld_elf_hints, &needed, force, false, elfsize);
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. */
776 struct ldelf_ld_so_conf
778 char *path;
779 size_t len, alloc;
782 static bool
783 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *, const char *);
785 static void
786 ldelf_parse_ld_so_conf_include (struct ldelf_ld_so_conf *info,
787 const char *filename,
788 const char *pattern)
790 char *newp = NULL;
791 #ifdef HAVE_GLOB
792 glob_t gl;
793 #endif
795 if (pattern[0] != '/')
797 char *p = strrchr (filename, '/');
798 size_t patlen = strlen (pattern) + 1;
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;
806 #ifdef HAVE_GLOB
807 if (glob (pattern, 0, NULL, &gl) == 0)
809 size_t i;
811 for (i = 0; i < gl.gl_pathc; ++i)
812 ldelf_parse_ld_so_conf (info, gl.gl_pathv[i]);
813 globfree (&gl);
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
820 free (newp);
823 static bool
824 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *info, const char *filename)
826 FILE *f = fopen (filename, FOPEN_RT);
827 char *line;
828 size_t linelen;
830 if (f == NULL)
831 return false;
833 linelen = 256;
834 line = xmalloc (linelen);
837 char *p = line, *q;
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')
844 line = xrealloc (line, 2 * linelen);
845 p = line + linelen - 1;
846 linelen += linelen;
849 if (q == NULL && p == line)
850 break;
852 p = strchr (line, '\n');
853 if (p)
854 *p = '\0';
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';
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;
868 /* If the line is blank it is ignored. */
869 if (p[0] == '\0')
870 continue;
872 if (startswith (p, "include") && (p[7] == ' ' || p[7] == '\t'))
874 char *dir, c;
875 p += 8;
878 while (*p == ' ' || *p == '\t')
879 ++p;
881 if (*p == '\0')
882 break;
884 dir = p;
886 while (*p != ' ' && *p != '\t' && *p)
887 ++p;
889 c = *p;
890 *p++ = '\0';
891 if (dir[0] != '\0')
892 ldelf_parse_ld_so_conf_include (info, filename, dir);
894 while (c != '\0');
896 else
898 char *dir = p;
899 while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
900 && *p != '\r' && *p != '\v')
901 ++p;
903 while (p != dir && p[-1] == '/')
904 --p;
905 if (info->path == NULL)
907 info->alloc = p - dir + 1 + 256;
908 info->path = xmalloc (info->alloc);
909 info->len = 0;
911 else
913 if (info->len + 1 + (p - dir) >= info->alloc)
915 info->alloc += p - dir + 256;
916 info->path = xrealloc (info->path, info->alloc);
918 info->path[info->len++] = config.rpath_separator;
920 memcpy (info->path + info->len, dir, p - dir);
921 info->len += p - dir;
922 info->path[info->len] = '\0';
925 while (! feof (f));
926 free (line);
927 fclose (f);
928 return true;
931 static bool
932 ldelf_check_ld_so_conf (const struct bfd_link_needed_list *l, int force,
933 int elfsize, const char *prefix)
935 static bool initialized;
936 static const char *ld_so_conf;
937 struct dt_needed needed;
939 if (! initialized)
941 char *tmppath;
942 struct ldelf_ld_so_conf info;
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))
950 free (tmppath);
951 tmppath = concat (ld_sysroot, "/etc/ld.so.conf",
952 (const char *) NULL);
953 ldelf_parse_ld_so_conf (&info, tmppath);
955 free (tmppath);
957 if (info.path)
959 ld_so_conf = ldelf_add_sysroot (info.path);
960 free (info.path);
962 initialized = true;
965 if (ld_so_conf == NULL)
966 return false;
969 needed.by = l->by;
970 needed.name = l->name;
971 return ldelf_search_needed (ld_so_conf, &needed, force, true, elfsize);
974 /* See if an input file matches a DT_NEEDED entry by name. */
976 static void
977 ldelf_check_needed (lang_input_statement_type *s)
979 const char *soname;
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;
987 if (s->filename == NULL || s->the_bfd == NULL)
988 return;
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;
995 if (filename_cmp (s->filename, global_needed->name) == 0)
997 global_found = s;
998 return;
1001 if (s->flags.search_dirs)
1003 const char *f = strrchr (s->filename, '/');
1004 if (f != NULL
1005 && filename_cmp (f + 1, global_needed->name) == 0)
1007 global_found = s;
1008 return;
1012 soname = bfd_elf_get_dt_soname (s->the_bfd);
1013 if (soname != NULL
1014 && filename_cmp (soname, global_needed->name) == 0)
1016 global_found = s;
1017 return;
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)
1026 struct bfd_link_needed_list *needed, *l;
1027 bfd *abfd;
1028 bfd **save_input_bfd_tail;
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)
1043 struct bfd_link_needed_list *ll;
1044 struct dt_needed n, nn;
1045 int force;
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;
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;
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;
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;
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);
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)
1090 nn.name = global_found->filename;
1091 if (ldelf_try_needed (&nn, true, is_linux))
1092 continue;
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.
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++)
1108 size_t len;
1109 search_dirs_type *search;
1110 const char *path;
1111 struct bfd_link_needed_list *rp;
1112 int found;
1114 if (ldelf_search_needed (command_line.rpath_link, &n, force,
1115 is_linux, elfsize))
1116 break;
1118 if (use_libpath)
1120 path = command_line.rpath;
1121 if (path)
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;
1131 if (native)
1133 if (command_line.rpath_link == NULL
1134 && command_line.rpath == NULL)
1136 path = (const char *) getenv ("LD_RUN_PATH");
1137 if (path
1138 && ldelf_search_needed (path, &n, force,
1139 is_linux, elfsize))
1140 break;
1142 path = (const char *) getenv ("LD_LIBRARY_PATH");
1143 if (path
1144 && ldelf_search_needed (path, &n, force,
1145 is_linux, elfsize))
1146 break;
1148 if (use_libpath)
1150 found = 0;
1151 rp = bfd_elf_get_runpath_list (link_info.output_bfd, &link_info);
1152 for (; !found && rp != NULL; rp = rp->next)
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);
1160 if (found)
1161 break;
1163 if (is_freebsd
1164 && ldelf_check_ld_elf_hints (l, force, elfsize))
1165 break;
1167 if (is_linux
1168 && ldelf_check_ld_so_conf (l, force, elfsize, prefix))
1169 break;
1172 len = strlen (l->name);
1173 for (search = search_head; search != NULL; search = search->next)
1175 char *filename;
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);
1186 if (search != NULL)
1187 break;
1190 if (force < 2)
1191 continue;
1193 einfo (_("%P: warning: %s, needed by %pB, not found "
1194 "(try using -rpath or -rpath-link)\n"),
1195 l->name, l->by);
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)
1208 if (bfd_elf_add_dt_needed_tag (abfd, &link_info) < 0)
1209 einfo (_("%F%P: failed to add DT_NEEDED dynamic tag\n"));
1212 link_info.input_bfds_tail = save_input_bfd_tail;
1213 *save_input_bfd_tail = NULL;
1216 /* This is called before calling plugin 'all symbols read' hook. */
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)
1223 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1225 if (!link_info.lto_plugin_active
1226 || !is_elf_hash_table (&htab->root))
1227 return;
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;
1235 /* This is called after all the input files have been opened and all
1236 symbols have been loaded. */
1238 void
1239 ldelf_after_open (int use_libpath, int native, int is_linux, int is_freebsd,
1240 int elfsize, const char *prefix)
1242 struct elf_link_hash_table *htab;
1243 asection *s;
1244 bfd *abfd;
1246 after_open_default ();
1248 htab = elf_hash_table (&link_info);
1249 if (!is_elf_hash_table (&htab->root))
1250 return;
1252 if (command_line.out_implib_filename)
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));
1259 if (link_info.out_implib_bfd == NULL)
1261 einfo (_("%F%P: %s: can't open for writing: %E\n"),
1262 command_line.out_implib_filename);
1266 if (ldelf_emit_note_gnu_build_id != NULL
1267 || ldelf_emit_note_fdo_package_metadata != NULL)
1269 /* Find an ELF input. */
1270 for (abfd = link_info.input_bfds;
1271 abfd != (bfd *) NULL; abfd = abfd->link.next)
1272 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1273 && bfd_count_sections (abfd) != 0
1274 && !bfd_input_just_syms (abfd))
1275 break;
1277 /* PR 10555: If there are no ELF input files do not try to
1278 create a .note.gnu-build-id section. */
1279 if (abfd == NULL
1280 || (ldelf_emit_note_gnu_build_id != NULL
1281 && !ldelf_setup_build_id (abfd)))
1283 free ((char *) ldelf_emit_note_gnu_build_id);
1284 ldelf_emit_note_gnu_build_id = NULL;
1287 if (abfd == NULL
1288 || (ldelf_emit_note_fdo_package_metadata != NULL
1289 && !ldelf_setup_package_metadata (abfd)))
1291 free ((char *) ldelf_emit_note_fdo_package_metadata);
1292 ldelf_emit_note_fdo_package_metadata = NULL;
1296 get_elf_backend_data (link_info.output_bfd)->setup_gnu_properties (&link_info);
1298 /* Do not allow executable files to be used as inputs to the link. */
1299 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1301 /* Discard input .note.gnu.build-id sections. */
1302 s = bfd_get_section_by_name (abfd, ".note.gnu.build-id");
1303 while (s != NULL)
1305 if (s != elf_tdata (link_info.output_bfd)->o->build_id.sec)
1306 s->flags |= SEC_EXCLUDE;
1307 s = bfd_get_next_section_by_name (NULL, s);
1310 if (abfd->xvec->flavour == bfd_target_elf_flavour
1311 && !bfd_input_just_syms (abfd)
1312 && elf_tdata (abfd) != NULL
1313 /* FIXME: Maybe check for other non-supportable types as well ? */
1314 && (elf_tdata (abfd)->elf_header->e_type == ET_EXEC
1315 || (elf_tdata (abfd)->elf_header->e_type == ET_DYN
1316 && elf_tdata (abfd)->is_pie)))
1317 einfo (_("%F%P: cannot use executable file '%pB' as input to a link\n"),
1318 abfd);
1321 if (bfd_link_relocatable (&link_info))
1323 if (link_info.execstack == !link_info.noexecstack)
1325 /* PR ld/16744: If "-z [no]execstack" has been specified on the
1326 command line and we are perfoming a relocatable link then no
1327 PT_GNU_STACK segment will be created and so the
1328 linkinfo.[no]execstack values set in _handle_option() will have no
1329 effect. Instead we create a .note.GNU-stack section in much the
1330 same way as the assembler does with its --[no]execstack option. */
1331 flagword flags = SEC_READONLY | (link_info.execstack ? SEC_CODE : 0);
1332 (void) bfd_make_section_with_flags (link_info.input_bfds,
1333 ".note.GNU-stack", flags);
1335 return;
1338 if (!link_info.traditional_format)
1340 bfd *elfbfd = NULL;
1341 bool warn_eh_frame = false;
1342 int seen_type = 0;
1344 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1346 int type = 0;
1348 if (bfd_input_just_syms (abfd))
1349 continue;
1351 for (s = abfd->sections; s && type < COMPACT_EH_HDR; s = s->next)
1353 const char *name = bfd_section_name (s);
1355 if (bfd_is_abs_section (s->output_section))
1356 continue;
1357 if (startswith (name, ".eh_frame_entry"))
1358 type = COMPACT_EH_HDR;
1359 else if (strcmp (name, ".eh_frame") == 0 && s->size > 8)
1360 type = DWARF2_EH_HDR;
1363 if (type != 0)
1365 if (seen_type == 0)
1367 seen_type = type;
1369 else if (seen_type != type)
1371 einfo (_("%F%P: compact frame descriptions incompatible with"
1372 " DWARF2 .eh_frame from %pB\n"),
1373 type == DWARF2_EH_HDR ? abfd : elfbfd);
1374 break;
1377 if (!elfbfd
1378 && (type == COMPACT_EH_HDR
1379 || link_info.eh_frame_hdr_type != 0))
1381 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1382 elfbfd = abfd;
1384 warn_eh_frame = true;
1388 if (seen_type == COMPACT_EH_HDR)
1389 link_info.eh_frame_hdr_type = COMPACT_EH_HDR;
1391 if (elfbfd)
1393 const struct elf_backend_data *bed;
1395 bed = get_elf_backend_data (elfbfd);
1396 s = bfd_make_section_with_flags (elfbfd, ".eh_frame_hdr",
1397 bed->dynamic_sec_flags
1398 | SEC_READONLY);
1399 if (s != NULL
1400 && bfd_set_section_alignment (s, 2))
1402 htab->eh_info.hdr_sec = s;
1403 warn_eh_frame = false;
1406 if (warn_eh_frame)
1407 einfo (_("%P: warning: cannot create .eh_frame_hdr section,"
1408 " --eh-frame-hdr ignored\n"));
1411 if (link_info.eh_frame_hdr_type == COMPACT_EH_HDR)
1412 if (!bfd_elf_parse_eh_frame_entries (NULL, &link_info))
1413 einfo (_("%F%P: failed to parse EH frame entries\n"));
1415 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1416 is_freebsd, elfsize, prefix);
1419 static bfd_size_type
1420 id_note_section_size (bfd *abfd ATTRIBUTE_UNUSED)
1422 const char *style = ldelf_emit_note_gnu_build_id;
1423 bfd_size_type size;
1424 bfd_size_type build_id_size;
1426 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1427 size = (size + 3) & -(bfd_size_type) 4;
1429 build_id_size = compute_build_id_size (style);
1430 if (build_id_size)
1431 size += build_id_size;
1432 else
1433 size = 0;
1435 return size;
1438 static bool
1439 write_build_id (bfd *abfd)
1441 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1442 struct elf_obj_tdata *t = elf_tdata (abfd);
1443 const char *style;
1444 asection *asec;
1445 Elf_Internal_Shdr *i_shdr;
1446 unsigned char *contents, *id_bits;
1447 bfd_size_type size;
1448 file_ptr position;
1449 Elf_External_Note *e_note;
1451 style = t->o->build_id.style;
1452 asec = t->o->build_id.sec;
1453 if (bfd_is_abs_section (asec->output_section))
1455 einfo (_("%P: warning: .note.gnu.build-id section discarded,"
1456 " --build-id ignored\n"));
1457 return true;
1459 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1461 if (i_shdr->contents != NULL)
1462 contents = i_shdr->contents + asec->output_offset;
1463 else if (asec->contents != NULL)
1464 contents = asec->contents;
1465 else
1466 contents = xmalloc (asec->size);
1468 e_note = (Elf_External_Note *) contents;
1469 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1470 size = (size + 3) & -(bfd_size_type) 4;
1471 id_bits = contents + size;
1472 size = asec->size - size;
1474 /* Clear the build ID field. */
1475 memset (id_bits, 0, size);
1477 bfd_h_put_32 (abfd, sizeof "GNU", &e_note->namesz);
1478 bfd_h_put_32 (abfd, size, &e_note->descsz);
1479 bfd_h_put_32 (abfd, NT_GNU_BUILD_ID, &e_note->type);
1480 memcpy (e_note->name, "GNU", sizeof "GNU");
1482 generate_build_id (abfd, style, bed->s->checksum_contents, id_bits, size);
1484 position = i_shdr->sh_offset + asec->output_offset;
1485 size = asec->size;
1486 bool ret = (bfd_seek (abfd, position, SEEK_SET) == 0
1487 && bfd_write (contents, size, abfd) == size);
1488 if (i_shdr->contents == NULL && asec->contents == NULL)
1489 free (contents);
1490 return ret;
1493 /* Make .note.gnu.build-id section, and set up elf_tdata->build_id. */
1495 bool
1496 ldelf_setup_build_id (bfd *ibfd)
1498 asection *s;
1499 bfd_size_type size;
1500 flagword flags;
1502 size = id_note_section_size (ibfd);
1503 if (size == 0)
1505 einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1506 return false;
1509 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1510 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1511 s = bfd_make_section_anyway_with_flags (ibfd, ".note.gnu.build-id",
1512 flags);
1513 if (s != NULL && bfd_set_section_alignment (s, 2))
1515 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1516 t->o->build_id.after_write_object_contents = &write_build_id;
1517 t->o->build_id.style = ldelf_emit_note_gnu_build_id;
1518 t->o->build_id.sec = s;
1519 elf_section_type (s) = SHT_NOTE;
1520 s->size = size;
1521 return true;
1524 einfo (_("%P: warning: cannot create .note.gnu.build-id section,"
1525 " --build-id ignored\n"));
1526 return false;
1529 static bool
1530 write_package_metadata (bfd *abfd)
1532 struct elf_obj_tdata *t = elf_tdata (abfd);
1533 const char *json;
1534 asection *asec;
1535 Elf_Internal_Shdr *i_shdr;
1536 unsigned char *contents, *json_bits;
1537 bfd_size_type size;
1538 file_ptr position;
1539 Elf_External_Note *e_note;
1541 json = t->o->package_metadata.json;
1542 asec = t->o->package_metadata.sec;
1543 if (bfd_is_abs_section (asec->output_section))
1545 einfo (_("%P: warning: .note.package section discarded,"
1546 " --package-metadata ignored\n"));
1547 return true;
1549 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1551 if (i_shdr->contents != NULL)
1552 contents = i_shdr->contents + asec->output_offset;
1553 else if (asec->contents != NULL)
1554 contents = asec->contents;
1555 else
1556 contents = xmalloc (asec->size);
1558 e_note = (Elf_External_Note *) contents;
1559 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1560 size = (size + 3) & -(bfd_size_type) 4;
1561 json_bits = contents + size;
1562 size = asec->size - size;
1564 /* Clear the package metadata field. */
1565 memset (json_bits, 0, size);
1567 bfd_h_put_32 (abfd, sizeof "FDO", &e_note->namesz);
1568 bfd_h_put_32 (abfd, size, &e_note->descsz);
1569 bfd_h_put_32 (abfd, FDO_PACKAGING_METADATA, &e_note->type);
1570 memcpy (e_note->name, "FDO", sizeof "FDO");
1571 memcpy (json_bits, json, strlen(json));
1573 position = i_shdr->sh_offset + asec->output_offset;
1574 size = asec->size;
1575 bool ret = (bfd_seek (abfd, position, SEEK_SET) == 0
1576 && bfd_write (contents, size, abfd) == size);
1577 if (i_shdr->contents == NULL && asec->contents == NULL)
1578 free (contents);
1579 return ret;
1582 /* Make .note.package section.
1583 https://systemd.io/ELF_PACKAGE_METADATA/ */
1585 bool
1586 ldelf_setup_package_metadata (bfd *ibfd)
1588 asection *s;
1589 bfd_size_type size;
1590 size_t json_length;
1591 flagword flags;
1593 /* If the option wasn't specified, silently return. */
1594 if (!ldelf_emit_note_fdo_package_metadata)
1595 return false;
1597 /* The option was specified, but it's empty, log and return. */
1598 json_length = strlen (ldelf_emit_note_fdo_package_metadata);
1599 if (json_length == 0)
1601 einfo (_("%P: warning: --package-metadata is empty, ignoring\n"));
1602 return false;
1605 #ifdef HAVE_JANSSON
1606 json_error_t json_error;
1607 json_t *json = json_loads (ldelf_emit_note_fdo_package_metadata,
1608 0, &json_error);
1609 if (!json)
1611 einfo (_("%P: warning: --package-metadata=%s does not contain valid "
1612 "JSON, ignoring: %s\n"),
1613 ldelf_emit_note_fdo_package_metadata, json_error.text);
1614 return false;
1616 else
1617 json_decref (json);
1618 #endif
1620 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1621 size += json_length + 1;
1622 size = (size + 3) & -(bfd_size_type) 4;
1624 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1625 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1626 s = bfd_make_section_anyway_with_flags (ibfd, ".note.package",
1627 flags);
1628 if (s != NULL && bfd_set_section_alignment (s, 2))
1630 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1631 t->o->package_metadata.after_write_object_contents
1632 = &write_package_metadata;
1633 t->o->package_metadata.json = ldelf_emit_note_fdo_package_metadata;
1634 t->o->package_metadata.sec = s;
1635 elf_section_type (s) = SHT_NOTE;
1636 s->size = size;
1637 return true;
1640 einfo (_("%P: warning: cannot create .note.package section,"
1641 " --package-metadata ignored\n"));
1642 return false;
1645 /* Look through an expression for an assignment statement. */
1647 static void
1648 ldelf_find_exp_assignment (etree_type *exp)
1650 bool provide = false;
1652 switch (exp->type.node_class)
1654 case etree_provide:
1655 case etree_provided:
1656 provide = true;
1657 /* Fallthru */
1658 case etree_assign:
1659 /* We call record_link_assignment even if the symbol is defined.
1660 This is because if it is defined by a dynamic object, we
1661 actually want to use the value defined by the linker script,
1662 not the value from the dynamic object (because we are setting
1663 symbols like etext). If the symbol is defined by a regular
1664 object, then, as it happens, calling record_link_assignment
1665 will do no harm. */
1666 if (strcmp (exp->assign.dst, ".") != 0)
1668 if (!bfd_elf_record_link_assignment (link_info.output_bfd,
1669 &link_info,
1670 exp->assign.dst, provide,
1671 exp->assign.hidden))
1672 einfo (_("%F%P: failed to record assignment to %s: %E\n"),
1673 exp->assign.dst);
1675 ldelf_find_exp_assignment (exp->assign.src);
1676 break;
1678 case etree_binary:
1679 ldelf_find_exp_assignment (exp->binary.lhs);
1680 ldelf_find_exp_assignment (exp->binary.rhs);
1681 break;
1683 case etree_trinary:
1684 ldelf_find_exp_assignment (exp->trinary.cond);
1685 ldelf_find_exp_assignment (exp->trinary.lhs);
1686 ldelf_find_exp_assignment (exp->trinary.rhs);
1687 break;
1689 case etree_unary:
1690 ldelf_find_exp_assignment (exp->unary.child);
1691 break;
1693 default:
1694 break;
1698 /* This is called by the before_allocation routine via
1699 lang_for_each_statement. It locates any assignment statements, and
1700 tells the ELF backend about them, in case they are assignments to
1701 symbols which are referred to by dynamic objects. */
1703 static void
1704 ldelf_find_statement_assignment (lang_statement_union_type *s)
1706 if (s->header.type == lang_assignment_statement_enum)
1707 ldelf_find_exp_assignment (s->assignment_statement.exp);
1710 /* Used by before_allocation and handle_option. */
1712 void
1713 ldelf_append_to_separated_string (char **to, char *op_arg)
1715 if (*to == NULL)
1716 *to = xstrdup (op_arg);
1717 else
1719 size_t to_len = strlen (*to);
1720 size_t op_arg_len = strlen (op_arg);
1721 char *buf;
1722 char *cp = *to;
1724 /* First see whether OPTARG is already in the path. */
1727 if (strncmp (op_arg, cp, op_arg_len) == 0
1728 && (cp[op_arg_len] == 0
1729 || cp[op_arg_len] == config.rpath_separator))
1730 /* We found it. */
1731 break;
1733 /* Not yet found. */
1734 cp = strchr (cp, config.rpath_separator);
1735 if (cp != NULL)
1736 ++cp;
1738 while (cp != NULL);
1740 if (cp == NULL)
1742 buf = xmalloc (to_len + op_arg_len + 2);
1743 sprintf (buf, "%s%c%s", *to,
1744 config.rpath_separator, op_arg);
1745 free (*to);
1746 *to = buf;
1751 /* This is called after the sections have been attached to output
1752 sections, but before any sizes or addresses have been set. */
1754 void
1755 ldelf_before_allocation (char **audit, char **depaudit,
1756 const char *default_interpreter_name)
1758 const char *rpath;
1759 asection *sinterp;
1760 bfd *abfd;
1761 struct bfd_link_hash_entry *ehdr_start = NULL;
1762 unsigned char ehdr_start_save_type = 0;
1763 char ehdr_start_save_u[sizeof ehdr_start->u
1764 - sizeof ehdr_start->u.def.next] = "";
1766 if (is_elf_hash_table (link_info.hash))
1768 _bfd_elf_tls_setup (link_info.output_bfd, &link_info);
1770 /* Make __ehdr_start hidden if it has been referenced, to
1771 prevent the symbol from being dynamic. */
1772 if (!bfd_link_relocatable (&link_info))
1774 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1775 struct elf_link_hash_entry *h
1776 = elf_link_hash_lookup (htab, "__ehdr_start", false, false, true);
1778 /* Only adjust the export class if the symbol was referenced
1779 and not defined, otherwise leave it alone. */
1780 if (h != NULL
1781 && (h->root.type == bfd_link_hash_new
1782 || h->root.type == bfd_link_hash_undefined
1783 || h->root.type == bfd_link_hash_undefweak
1784 || h->root.type == bfd_link_hash_common))
1786 /* Don't leave the symbol undefined. Undefined hidden
1787 symbols typically won't have dynamic relocations, but
1788 we most likely will need dynamic relocations for
1789 __ehdr_start if we are building a PIE or shared
1790 library. */
1791 ehdr_start = &h->root;
1792 ehdr_start_save_type = ehdr_start->type;
1793 memcpy (ehdr_start_save_u,
1794 (char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1795 sizeof ehdr_start_save_u);
1796 ehdr_start->type = bfd_link_hash_defined;
1797 /* It will be converted to section-relative later. */
1798 ehdr_start->u.def.section = bfd_abs_section_ptr;
1799 ehdr_start->u.def.value = 0;
1803 /* If we are going to make any variable assignments, we need to
1804 let the ELF backend know about them in case the variables are
1805 referred to by dynamic objects. */
1806 lang_for_each_statement (ldelf_find_statement_assignment);
1809 /* Let the ELF backend work out the sizes of any sections required
1810 by dynamic linking. */
1811 rpath = command_line.rpath;
1812 if (rpath == NULL)
1813 rpath = (const char *) getenv ("LD_RUN_PATH");
1815 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1816 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1818 const char *audit_libs = elf_dt_audit (abfd);
1820 /* If the input bfd contains an audit entry, we need to add it as
1821 a dep audit entry. */
1822 if (audit_libs && *audit_libs != '\0')
1824 char *copy_audit_libs = xstrdup (audit_libs);
1825 char *cp = copy_audit_libs;
1828 char *cp2 = strchr (cp, config.rpath_separator);
1830 if (cp2)
1831 *cp2++ = '\0';
1833 if (*cp != '\0')
1834 ldelf_append_to_separated_string (depaudit, cp);
1836 cp = cp2;
1838 while (cp != NULL);
1839 free (copy_audit_libs);
1843 if (! (bfd_elf_size_dynamic_sections
1844 (link_info.output_bfd, command_line.soname, rpath,
1845 command_line.filter_shlib, *audit, *depaudit,
1846 (const char * const *) command_line.auxiliary_filters,
1847 &link_info, &sinterp)))
1848 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1850 if (sinterp != NULL)
1852 /* Let the user override the dynamic linker we are using. */
1853 if (command_line.interpreter != NULL)
1854 default_interpreter_name = command_line.interpreter;
1855 if (default_interpreter_name != NULL)
1857 sinterp->contents = (bfd_byte *) default_interpreter_name;
1858 sinterp->alloced = 1;
1859 sinterp->size = strlen ((char *) sinterp->contents) + 1;
1863 /* Look for any sections named .gnu.warning. As a GNU extensions,
1864 we treat such sections as containing warning messages. We print
1865 out the warning message, and then zero out the section size so
1866 that it does not get copied into the output file. */
1869 LANG_FOR_EACH_INPUT_STATEMENT (is)
1871 asection *s;
1872 bfd_size_type sz;
1873 char *msg;
1875 if (is->flags.just_syms)
1876 continue;
1878 s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1879 if (s == NULL)
1880 continue;
1882 sz = s->size;
1883 msg = (char *) xmalloc ((size_t) (sz + 1));
1884 if (! bfd_get_section_contents (is->the_bfd, s, msg,
1885 (file_ptr) 0, sz))
1886 einfo (_("%F%P: %pB: can't read contents of section .gnu.warning: %E\n"),
1887 is->the_bfd);
1888 msg[sz] = '\0';
1889 (*link_info.callbacks->warning) (&link_info, msg,
1890 (const char *) NULL, is->the_bfd,
1891 (asection *) NULL, (bfd_vma) 0);
1892 free (msg);
1894 /* Clobber the section size, so that we don't waste space
1895 copying the warning into the output file. If we've already
1896 sized the output section, adjust its size. The adjustment
1897 is on rawsize because targets that size sections early will
1898 have called lang_reset_memory_regions after sizing. */
1899 if (s->output_section != NULL
1900 && s->output_section->rawsize >= s->size)
1901 s->output_section->rawsize -= s->size;
1903 s->size = 0;
1905 /* Also set SEC_EXCLUDE, so that local symbols defined in the
1906 warning section don't get copied to the output. */
1907 s->flags |= SEC_EXCLUDE | SEC_KEEP;
1911 before_allocation_default ();
1913 if (!bfd_elf_size_dynsym_hash_dynstr (link_info.output_bfd, &link_info))
1914 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1916 if (ehdr_start != NULL)
1918 /* If we twiddled __ehdr_start to defined earlier, put it back
1919 as it was. */
1920 ehdr_start->type = ehdr_start_save_type;
1921 memcpy ((char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1922 ehdr_start_save_u,
1923 sizeof ehdr_start_save_u);
1926 /* Try to open a dynamic archive. This is where we know that ELF
1927 dynamic libraries have an extension of .so (or .sl on oddball systems
1928 like hpux). */
1930 bool
1931 ldelf_open_dynamic_archive (const char *arch, search_dirs_type *search,
1932 lang_input_statement_type *entry)
1934 const char *filename;
1935 char *string;
1936 size_t len;
1937 bool opened = false;
1939 if (! entry->flags.maybe_archive)
1940 return false;
1942 filename = entry->filename;
1943 len = strlen (search->name) + strlen (filename);
1944 if (entry->flags.full_name_provided)
1946 len += sizeof "/";
1947 string = (char *) xmalloc (len);
1948 sprintf (string, "%s/%s", search->name, filename);
1950 else
1952 size_t xlen = 0;
1954 len += strlen (arch) + sizeof "/lib.so";
1955 #ifdef EXTRA_SHLIB_EXTENSION
1956 xlen = (strlen (EXTRA_SHLIB_EXTENSION) > 3
1957 ? strlen (EXTRA_SHLIB_EXTENSION) - 3
1958 : 0);
1959 #endif
1960 string = (char *) xmalloc (len + xlen);
1961 sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1962 #ifdef EXTRA_SHLIB_EXTENSION
1963 /* Try the .so extension first. If that fails build a new filename
1964 using EXTRA_SHLIB_EXTENSION. */
1965 opened = ldfile_try_open_bfd (string, entry);
1966 if (!opened)
1967 strcpy (string + len - 4, EXTRA_SHLIB_EXTENSION);
1968 #endif
1971 if (!opened && !ldfile_try_open_bfd (string, entry))
1973 free (string);
1974 return false;
1977 entry->filename = string;
1979 /* We have found a dynamic object to include in the link. The ELF
1980 backend linker will create a DT_NEEDED entry in the .dynamic
1981 section naming this file. If this file includes a DT_SONAME
1982 entry, it will be used. Otherwise, the ELF linker will just use
1983 the name of the file. For an archive found by searching, like
1984 this one, the DT_NEEDED entry should consist of just the name of
1985 the file, without the path information used to find it. Note
1986 that we only need to do this if we have a dynamic object; an
1987 archive will never be referenced by a DT_NEEDED entry.
1989 FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1990 very pretty. I haven't been able to think of anything that is
1991 pretty, though. */
1992 if (bfd_check_format (entry->the_bfd, bfd_object)
1993 && (entry->the_bfd->flags & DYNAMIC) != 0)
1995 ASSERT (entry->flags.maybe_archive && entry->flags.search_dirs);
1997 /* Rather than duplicating the logic above. Just use the
1998 filename we recorded earlier. */
2000 if (!entry->flags.full_name_provided)
2001 filename = lbasename (entry->filename);
2002 bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
2005 return true;
2008 /* A variant of lang_output_section_find used by place_orphan. */
2010 static lang_output_section_statement_type *
2011 output_rel_find (int isdyn, int rela)
2013 lang_output_section_statement_type *lookup;
2014 lang_output_section_statement_type *last = NULL;
2015 lang_output_section_statement_type *last_alloc = NULL;
2016 lang_output_section_statement_type *last_ro_alloc = NULL;
2017 lang_output_section_statement_type *last_rel = NULL;
2018 lang_output_section_statement_type *last_rel_alloc = NULL;
2020 for (lookup = (void *) lang_os_list.head;
2021 lookup != NULL;
2022 lookup = lookup->next)
2024 if (lookup->constraint >= 0
2025 && startswith (lookup->name, ".rel"))
2027 int lookrela = lookup->name[4] == 'a';
2029 /* .rel.dyn must come before all other reloc sections, to suit
2030 GNU ld.so. */
2031 if (isdyn)
2032 break;
2034 /* Don't place after .rel.plt as doing so results in wrong
2035 dynamic tags. */
2036 if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
2037 break;
2039 if (rela == lookrela || last_rel == NULL)
2040 last_rel = lookup;
2041 if ((rela == lookrela || last_rel_alloc == NULL)
2042 && lookup->bfd_section != NULL
2043 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2044 last_rel_alloc = lookup;
2047 last = lookup;
2048 if (lookup->bfd_section != NULL
2049 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2051 last_alloc = lookup;
2052 if ((lookup->bfd_section->flags & SEC_READONLY) != 0)
2053 last_ro_alloc = lookup;
2057 if (last_rel_alloc)
2058 return last_rel_alloc;
2060 if (last_rel)
2061 return last_rel;
2063 if (last_ro_alloc)
2064 return last_ro_alloc;
2066 if (last_alloc)
2067 return last_alloc;
2069 return last;
2072 /* Return whether IN is suitable to be part of OUT. */
2074 static bool
2075 elf_orphan_compatible (asection *in, asection *out)
2077 /* Non-zero sh_info implies a section with SHF_INFO_LINK with
2078 unknown semantics for the generic linker, or a SHT_REL/SHT_RELA
2079 section where sh_info specifies a symbol table. (We won't see
2080 SHT_GROUP, SHT_SYMTAB or SHT_DYNSYM sections here.) We clearly
2081 can't merge SHT_REL/SHT_RELA using differing symbol tables, and
2082 shouldn't merge sections with differing unknown semantics. */
2083 if (elf_section_data (out)->this_hdr.sh_info
2084 != elf_section_data (in)->this_hdr.sh_info)
2085 return false;
2086 /* We can't merge with a member of an output section group or merge
2087 two sections with differing SHF_EXCLUDE or other processor and OS
2088 specific flags or with different SHF_LINK_ORDER when doing a
2089 relocatable link. */
2090 if (bfd_link_relocatable (&link_info)
2091 && (elf_next_in_group (out) != NULL
2092 || ((elf_section_flags (in) & SHF_LINK_ORDER) != 0
2093 && (elf_section_flags (out) & SHF_LINK_ORDER) != 0
2094 && (elf_linked_to_section (in)->output_section
2095 != elf_linked_to_section (out)->output_section))
2096 || ((elf_section_flags (out) ^ elf_section_flags (in))
2097 & (SHF_MASKPROC | SHF_MASKOS)) != 0))
2098 return false;
2099 return _bfd_elf_match_sections_by_type (link_info.output_bfd, out,
2100 in->owner, in);
2103 /* Place an orphan section. We use this to put random SHF_ALLOC
2104 sections in the right segment. */
2106 lang_output_section_statement_type *
2107 ldelf_place_orphan (asection *s, const char *secname, int constraint)
2109 static struct orphan_save orig_hold[] =
2111 { ".text",
2112 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2113 0, 0, 0, 0 },
2114 { ".rodata",
2115 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2116 0, 0, 0, 0 },
2117 { ".tdata",
2118 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_THREAD_LOCAL,
2119 0, 0, 0, 0 },
2120 { ".data",
2121 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2122 0, 0, 0, 0 },
2123 { ".bss",
2124 SEC_ALLOC,
2125 0, 0, 0, 0 },
2126 { NULL,
2127 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2128 0, 0, 0, 0 },
2129 { ".interp",
2130 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2131 0, 0, 0, 0 },
2132 { ".sdata",
2133 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
2134 0, 0, 0, 0 },
2135 { ".comment",
2136 SEC_HAS_CONTENTS,
2137 0, 0, 0, 0 },
2139 static struct orphan_save hold[ARRAY_SIZE (orig_hold)];
2140 enum orphan_save_index
2142 orphan_text = 0,
2143 orphan_rodata,
2144 orphan_tdata,
2145 orphan_data,
2146 orphan_bss,
2147 orphan_rel,
2148 orphan_interp,
2149 orphan_sdata,
2150 orphan_nonalloc
2152 struct orphan_save *place;
2153 lang_output_section_statement_type *after;
2154 lang_output_section_statement_type *os;
2155 lang_output_section_statement_type *match_by_name = NULL;
2156 int isdyn = 0;
2157 int elfinput = s->owner->xvec->flavour == bfd_target_elf_flavour;
2158 int elfoutput = link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour;
2159 unsigned int sh_type = elfinput ? elf_section_type (s) : SHT_NULL;
2160 flagword flags;
2161 asection *nexts;
2163 if (!bfd_link_relocatable (&link_info)
2164 && link_info.combreloc
2165 && (s->flags & SEC_ALLOC))
2167 if (elfinput)
2168 switch (sh_type)
2170 case SHT_RELA:
2171 secname = ".rela.dyn";
2172 isdyn = 1;
2173 break;
2174 case SHT_REL:
2175 secname = ".rel.dyn";
2176 isdyn = 1;
2177 break;
2178 default:
2179 break;
2181 else if (startswith (secname, ".rel"))
2183 secname = secname[4] == 'a' ? ".rela.dyn" : ".rel.dyn";
2184 isdyn = 1;
2188 if (!bfd_link_relocatable (&link_info)
2189 && elfinput
2190 && elfoutput
2191 && (s->flags & SEC_ALLOC) != 0
2192 && (elf_tdata (s->owner)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0
2193 && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
2195 /* Find the output mbind section with the same type, attributes
2196 and sh_info field. */
2197 for (os = (void *) lang_os_list.head;
2198 os != NULL;
2199 os = os->next)
2200 if (os->bfd_section != NULL
2201 && !bfd_is_abs_section (os->bfd_section)
2202 && (elf_section_flags (os->bfd_section) & SHF_GNU_MBIND) != 0
2203 && ((s->flags & (SEC_ALLOC
2204 | SEC_LOAD
2205 | SEC_HAS_CONTENTS
2206 | SEC_READONLY
2207 | SEC_CODE))
2208 == (os->bfd_section->flags & (SEC_ALLOC
2209 | SEC_LOAD
2210 | SEC_HAS_CONTENTS
2211 | SEC_READONLY
2212 | SEC_CODE)))
2213 && (elf_section_data (os->bfd_section)->this_hdr.sh_info
2214 == elf_section_data (s)->this_hdr.sh_info))
2216 lang_add_section (&os->children, s, NULL, NULL, os);
2217 return os;
2220 /* Create the output mbind section with the ".mbind." prefix
2221 in section name. */
2222 if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2223 secname = ".mbind.bss";
2224 else if ((s->flags & SEC_READONLY) == 0)
2225 secname = ".mbind.data";
2226 else if ((s->flags & SEC_CODE) == 0)
2227 secname = ".mbind.rodata";
2228 else
2229 secname = ".mbind.text";
2230 elf_tdata (link_info.output_bfd)->has_gnu_osabi |= elf_gnu_osabi_mbind;
2233 /* Look through the script to see where to place this section. The
2234 script includes entries added by previous lang_insert_orphan
2235 calls, so this loop puts multiple compatible orphans of the same
2236 name into a single output section. */
2237 if (constraint == 0)
2238 for (os = lang_output_section_find (secname);
2239 os != NULL;
2240 os = next_matching_output_section_statement (os, 0))
2242 /* If we don't match an existing output section, tell
2243 lang_insert_orphan to create a new output section. */
2244 constraint = SPECIAL;
2246 /* Check to see if we already have an output section statement
2247 with this name, and its bfd section has compatible flags.
2248 If the section already exists but does not have any flags
2249 set, then it has been created by the linker, possibly as a
2250 result of a --section-start command line switch. */
2251 if (os->bfd_section != NULL
2252 && !bfd_is_abs_section (os->bfd_section)
2253 && (os->bfd_section->flags == 0
2254 || (((s->flags ^ os->bfd_section->flags)
2255 & (SEC_LOAD | SEC_ALLOC)) == 0
2256 && (!elfinput
2257 || !elfoutput
2258 || elf_orphan_compatible (s, os->bfd_section)))))
2260 lang_add_section (&os->children, s, NULL, NULL, os);
2261 return os;
2264 /* Save unused output sections in case we can match them
2265 against orphans later. */
2266 if (os->bfd_section == NULL)
2267 match_by_name = os;
2270 /* If we didn't match an active output section, see if we matched an
2271 unused one and use that. */
2272 if (match_by_name)
2274 lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2275 return match_by_name;
2278 if (!orphan_init_done)
2280 struct orphan_save *ho, *horig;
2282 for (ho = hold, horig = orig_hold;
2283 ho < hold + ARRAY_SIZE (hold);
2284 ++ho, ++horig)
2286 *ho = *horig;
2287 if (ho->name != NULL)
2289 ho->os = lang_output_section_find (ho->name);
2290 if (ho->os != NULL && ho->os->flags == 0)
2291 ho->os->flags = ho->flags;
2294 orphan_init_done = true;
2297 /* If this is a final link, then always put .gnu.warning.SYMBOL
2298 sections into the .text section to get them out of the way. */
2299 if (bfd_link_executable (&link_info)
2300 && startswith (s->name, ".gnu.warning.")
2301 && hold[orphan_text].os != NULL)
2303 os = hold[orphan_text].os;
2304 lang_add_section (&os->children, s, NULL, NULL, os);
2305 return os;
2308 flags = s->flags;
2309 if (!bfd_link_relocatable (&link_info))
2311 nexts = s;
2312 while ((nexts = bfd_get_next_section_by_name (nexts->owner, nexts))
2313 != NULL)
2314 if (nexts->output_section == NULL
2315 && (nexts->flags & SEC_EXCLUDE) == 0
2316 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2317 && (nexts->owner->flags & DYNAMIC) == 0
2318 && !bfd_input_just_syms (nexts->owner)
2319 && _bfd_elf_match_sections_by_type (nexts->owner, nexts,
2320 s->owner, s))
2321 flags = (((flags ^ SEC_READONLY)
2322 | (nexts->flags ^ SEC_READONLY))
2323 ^ SEC_READONLY);
2326 /* Decide which segment the section should go in based on the
2327 section name and section flags. We put loadable .note sections
2328 right after the .interp section, so that the PT_NOTE segment is
2329 stored right after the program headers where the OS can read it
2330 in the first page. */
2332 place = NULL;
2333 if ((flags & (SEC_ALLOC | SEC_DEBUGGING)) == 0)
2334 place = &hold[orphan_nonalloc];
2335 else if ((flags & SEC_ALLOC) == 0)
2337 else if ((flags & SEC_LOAD) != 0
2338 && (elfinput
2339 ? sh_type == SHT_NOTE
2340 : startswith (secname, ".note")))
2342 /* PR 32219: Check that the .interp section
2343 exists before attaching orphans to it. */
2344 if (lang_output_section_find (hold[orphan_interp].name))
2345 place = &hold[orphan_interp];
2346 /* Next best place: after .rodata. */
2347 else if (lang_output_section_find (hold[orphan_rodata].name))
2348 place = &hold[orphan_rodata];
2349 /* Last attempt: the .text section. */
2350 else
2351 place = &hold[orphan_text];
2353 else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS | SEC_THREAD_LOCAL)) == 0)
2354 place = &hold[orphan_bss];
2355 else if ((flags & SEC_SMALL_DATA) != 0)
2356 place = &hold[orphan_sdata];
2357 else if ((flags & SEC_THREAD_LOCAL) != 0)
2358 place = &hold[orphan_tdata];
2359 else if ((flags & SEC_READONLY) == 0)
2360 place = &hold[orphan_data];
2361 else if ((flags & SEC_LOAD) != 0
2362 && (elfinput
2363 ? sh_type == SHT_RELA || sh_type == SHT_REL
2364 : startswith (secname, ".rel")))
2365 place = &hold[orphan_rel];
2366 else if ((flags & SEC_CODE) == 0)
2367 place = &hold[orphan_rodata];
2368 else
2369 place = &hold[orphan_text];
2371 after = NULL;
2372 if (place != NULL)
2374 if (place->os == NULL)
2376 if (place->name != NULL)
2377 place->os = lang_output_section_find (place->name);
2378 else
2380 int rela = elfinput ? sh_type == SHT_RELA : secname[4] == 'a';
2381 place->os = output_rel_find (isdyn, rela);
2384 after = place->os;
2385 if (after == NULL)
2386 after
2387 = lang_output_section_find_by_flags (s, flags, &place->os,
2388 _bfd_elf_match_sections_by_type);
2389 if (after == NULL)
2390 /* *ABS* is always the first output section statement. */
2391 after = (void *) lang_os_list.head;
2394 return lang_insert_orphan (s, secname, constraint, after, place, NULL, NULL);
2397 void
2398 ldelf_before_place_orphans (void)
2400 bfd *abfd;
2402 for (abfd = link_info.input_bfds;
2403 abfd != (bfd *) NULL; abfd = abfd->link.next)
2404 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2405 && bfd_count_sections (abfd) != 0
2406 && !bfd_input_just_syms (abfd))
2408 asection *isec;
2409 for (isec = abfd->sections; isec != NULL; isec = isec->next)
2411 /* Discard a section if any of its linked-to section has
2412 been discarded. */
2413 asection *linked_to_sec;
2414 for (linked_to_sec = elf_linked_to_section (isec);
2415 linked_to_sec != NULL && !linked_to_sec->linker_mark;
2416 linked_to_sec = elf_linked_to_section (linked_to_sec))
2418 if (discarded_section (linked_to_sec))
2420 isec->output_section = bfd_abs_section_ptr;
2421 isec->flags |= SEC_EXCLUDE;
2422 break;
2424 linked_to_sec->linker_mark = 1;
2426 for (linked_to_sec = elf_linked_to_section (isec);
2427 linked_to_sec != NULL && linked_to_sec->linker_mark;
2428 linked_to_sec = elf_linked_to_section (linked_to_sec))
2429 linked_to_sec->linker_mark = 0;
2434 void
2435 ldelf_set_output_arch (void)
2437 set_output_arch_default ();
2438 if (link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour)
2439 elf_link_info (link_info.output_bfd) = &link_info;
2442 void
2443 ldelf_finish (void)
2445 /* Support the object-only output. */
2446 if (config.emit_gnu_object_only)
2447 orphan_init_done = false;
2449 finish_default ();