x86: rework of match_template()'s suffix checking
[binutils-gdb.git] / ld / ldelf.c
blobbfa0d54753ad8a7de02b4bae999119588ef982c6
1 /* ELF emulation code for targets using elf.em.
2 Copyright (C) 1991-2022 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;
67 void
68 ldelf_after_parse (void)
70 if (bfd_link_pie (&link_info))
71 link_info.flags_1 |= (bfd_vma) DF_1_PIE;
73 if (bfd_link_executable (&link_info)
74 && link_info.nointerp)
76 if (link_info.dynamic_undefined_weak > 0)
77 einfo (_("%P: warning: -z dynamic-undefined-weak ignored\n"));
78 link_info.dynamic_undefined_weak = 0;
81 /* Disable DT_RELR if not building PIE nor shared library. */
82 if (!bfd_link_pic (&link_info))
83 link_info.enable_dt_relr = 0;
85 /* Add 3 spare tags for DT_RELR, DT_RELRSZ and DT_RELRENT. */
86 if (link_info.enable_dt_relr)
87 link_info.spare_dynamic_tags += 3;
89 after_parse_default ();
90 if (link_info.commonpagesize > link_info.maxpagesize)
92 if (!link_info.commonpagesize_is_set)
93 link_info.commonpagesize = link_info.maxpagesize;
94 else if (!link_info.maxpagesize_is_set)
95 link_info.maxpagesize = link_info.commonpagesize;
96 else
97 einfo (_("%F%P: common page size (0x%v) > maximum page size (0x%v)\n"),
98 link_info.commonpagesize, link_info.maxpagesize);
102 /* Handle the generation of DT_NEEDED tags. */
104 bool
105 ldelf_load_symbols (lang_input_statement_type *entry)
107 int link_class = 0;
109 /* Tell the ELF linker that we don't want the output file to have a
110 DT_NEEDED entry for this file, unless it is used to resolve
111 references in a regular object. */
112 if (entry->flags.add_DT_NEEDED_for_regular)
113 link_class = DYN_AS_NEEDED;
115 /* Tell the ELF linker that we don't want the output file to have a
116 DT_NEEDED entry for any dynamic library in DT_NEEDED tags from
117 this file at all. */
118 if (!entry->flags.add_DT_NEEDED_for_dynamic)
119 link_class |= DYN_NO_ADD_NEEDED;
121 if (entry->flags.just_syms
122 && (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) != 0)
123 einfo (_("%F%P: %pB: --just-symbols may not be used on DSO\n"),
124 entry->the_bfd);
126 if (link_class == 0
127 || (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) == 0)
128 return false;
130 bfd_elf_set_dyn_lib_class (entry->the_bfd,
131 (enum dynamic_lib_link_class) link_class);
133 /* Continue on with normal load_symbols processing. */
134 return false;
137 /* On Linux, it's possible to have different versions of the same
138 shared library linked against different versions of libc. The
139 dynamic linker somehow tags which libc version to use in
140 /etc/ld.so.cache, and, based on the libc that it sees in the
141 executable, chooses which version of the shared library to use.
143 We try to do a similar check here by checking whether this shared
144 library needs any other shared libraries which may conflict with
145 libraries we have already included in the link. If it does, we
146 skip it, and try to find another shared library farther on down the
147 link path.
149 This is called via lang_for_each_input_file.
150 GLOBAL_VERCHECK_NEEDED is the list of objects needed by the object
151 which we are checking. This sets GLOBAL_VERCHECK_FAILED if we find
152 a conflicting version. */
154 static void
155 ldelf_vercheck (lang_input_statement_type *s)
157 const char *soname;
158 struct bfd_link_needed_list *l;
160 if (global_vercheck_failed)
161 return;
162 if (s->the_bfd == NULL
163 || (bfd_get_file_flags (s->the_bfd) & DYNAMIC) == 0)
164 return;
166 soname = bfd_elf_get_dt_soname (s->the_bfd);
167 if (soname == NULL)
168 soname = lbasename (bfd_get_filename (s->the_bfd));
170 for (l = global_vercheck_needed; l != NULL; l = l->next)
172 const char *suffix;
174 if (filename_cmp (soname, l->name) == 0)
176 /* Probably can't happen, but it's an easy check. */
177 continue;
180 if (strchr (l->name, '/') != NULL)
181 continue;
183 suffix = strstr (l->name, ".so.");
184 if (suffix == NULL)
185 continue;
187 suffix += sizeof ".so." - 1;
189 if (filename_ncmp (soname, l->name, suffix - l->name) == 0)
191 /* Here we know that S is a dynamic object FOO.SO.VER1, and
192 the object we are considering needs a dynamic object
193 FOO.SO.VER2, and VER1 and VER2 are different. This
194 appears to be a version mismatch, so we tell the caller
195 to try a different version of this library. */
196 global_vercheck_failed = true;
197 return;
203 /* See if an input file matches a DT_NEEDED entry by running stat on
204 the file. */
206 static void
207 ldelf_stat_needed (lang_input_statement_type *s)
209 struct stat st;
210 const char *suffix;
211 const char *soname;
213 if (global_found != NULL)
214 return;
215 if (s->the_bfd == NULL)
216 return;
218 /* If this input file was an as-needed entry, and wasn't found to be
219 needed at the stage it was linked, then don't say we have loaded it. */
220 if ((bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
221 return;
223 if (bfd_stat (s->the_bfd, &st) != 0)
225 einfo (_("%P: %pB: bfd_stat failed: %E\n"), s->the_bfd);
226 return;
229 /* Some operating systems, e.g. Windows, do not provide a meaningful
230 st_ino; they always set it to zero. (Windows does provide a
231 meaningful st_dev.) Do not indicate a duplicate library in that
232 case. While there is no guarantee that a system that provides
233 meaningful inode numbers will never set st_ino to zero, this is
234 merely an optimization, so we do not need to worry about false
235 negatives. */
236 if (st.st_dev == global_stat.st_dev
237 && st.st_ino == global_stat.st_ino
238 && st.st_ino != 0)
240 global_found = s;
241 return;
244 /* We issue a warning if it looks like we are including two
245 different versions of the same shared library. For example,
246 there may be a problem if -lc picks up libc.so.6 but some other
247 shared library has a DT_NEEDED entry of libc.so.5. This is a
248 heuristic test, and it will only work if the name looks like
249 NAME.so.VERSION. FIXME: Depending on file names is error-prone.
250 If we really want to issue warnings about mixing version numbers
251 of shared libraries, we need to find a better way. */
253 if (strchr (global_needed->name, '/') != NULL)
254 return;
255 suffix = strstr (global_needed->name, ".so.");
256 if (suffix == NULL)
257 return;
258 suffix += sizeof ".so." - 1;
260 soname = bfd_elf_get_dt_soname (s->the_bfd);
261 if (soname == NULL)
262 soname = lbasename (s->filename);
264 if (filename_ncmp (soname, global_needed->name,
265 suffix - global_needed->name) == 0)
266 einfo (_("%P: warning: %s, needed by %pB, may conflict with %s\n"),
267 global_needed->name, global_needed->by, soname);
270 /* This function is called for each possible name for a dynamic object
271 named by a DT_NEEDED entry. The FORCE parameter indicates whether
272 to skip the check for a conflicting version. */
274 static bool
275 ldelf_try_needed (struct dt_needed *needed, int force, int is_linux)
277 bfd *abfd;
278 const char *name = needed->name;
279 const char *soname;
280 int link_class;
282 abfd = bfd_openr (name, bfd_get_target (link_info.output_bfd));
283 if (abfd == NULL)
285 if (verbose)
286 info_msg (_("attempt to open %s failed\n"), name);
287 return false;
290 track_dependency_files (name);
292 /* Linker needs to decompress sections. */
293 abfd->flags |= BFD_DECOMPRESS;
295 if (! bfd_check_format (abfd, bfd_object))
297 bfd_close (abfd);
298 return false;
300 if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
302 bfd_close (abfd);
303 return false;
306 /* For DT_NEEDED, they have to match. */
307 if (abfd->xvec != link_info.output_bfd->xvec)
309 bfd_close (abfd);
310 return false;
313 /* Check whether this object would include any conflicting library
314 versions. If FORCE is set, then we skip this check; we use this
315 the second time around, if we couldn't find any compatible
316 instance of the shared library. */
318 if (!force)
320 struct bfd_link_needed_list *needs;
322 if (! bfd_elf_get_bfd_needed_list (abfd, &needs))
323 einfo (_("%F%P: %pB: bfd_elf_get_bfd_needed_list failed: %E\n"), abfd);
325 if (needs != NULL)
327 global_vercheck_needed = needs;
328 global_vercheck_failed = false;
329 lang_for_each_input_file (ldelf_vercheck);
330 if (global_vercheck_failed)
332 bfd_close (abfd);
333 /* Return FALSE to force the caller to move on to try
334 another file on the search path. */
335 return false;
338 /* But wait! It gets much worse. On Linux, if a shared
339 library does not use libc at all, we are supposed to skip
340 it the first time around in case we encounter a shared
341 library later on with the same name which does use the
342 version of libc that we want. This is much too horrible
343 to use on any system other than Linux. */
344 if (is_linux)
346 struct bfd_link_needed_list *l;
348 for (l = needs; l != NULL; l = l->next)
349 if (startswith (l->name, "libc.so"))
350 break;
351 if (l == NULL)
353 bfd_close (abfd);
354 return false;
360 /* We've found a dynamic object matching the DT_NEEDED entry. */
362 /* We have already checked that there is no other input file of the
363 same name. We must now check again that we are not including the
364 same file twice. We need to do this because on many systems
365 libc.so is a symlink to, e.g., libc.so.1. The SONAME entry will
366 reference libc.so.1. If we have already included libc.so, we
367 don't want to include libc.so.1 if they are the same file, and we
368 can only check that using stat. */
370 if (bfd_stat (abfd, &global_stat) != 0)
371 einfo (_("%F%P: %pB: bfd_stat failed: %E\n"), abfd);
373 /* First strip off everything before the last '/'. */
374 soname = lbasename (bfd_get_filename (abfd));
376 if (verbose)
377 info_msg (_("found %s at %s\n"), soname, name);
379 global_found = NULL;
380 lang_for_each_input_file (ldelf_stat_needed);
381 if (global_found != NULL)
383 /* Return TRUE to indicate that we found the file, even though
384 we aren't going to do anything with it. */
385 return true;
388 /* Specify the soname to use. */
389 bfd_elf_set_dt_needed_name (abfd, soname);
391 /* Tell the ELF linker that we don't want the output file to have a
392 DT_NEEDED entry for this file, unless it is used to resolve
393 references in a regular object. */
394 link_class = DYN_DT_NEEDED;
396 /* Tell the ELF linker that we don't want the output file to have a
397 DT_NEEDED entry for this file at all if the entry is from a file
398 with DYN_NO_ADD_NEEDED. */
399 if (needed->by != NULL
400 && (bfd_elf_get_dyn_lib_class (needed->by) & DYN_NO_ADD_NEEDED) != 0)
401 link_class |= DYN_NO_NEEDED | DYN_NO_ADD_NEEDED;
403 bfd_elf_set_dyn_lib_class (abfd, (enum dynamic_lib_link_class) link_class);
405 *link_info.input_bfds_tail = abfd;
406 link_info.input_bfds_tail = &abfd->link.next;
408 /* Add this file into the symbol table. */
409 if (! bfd_link_add_symbols (abfd, &link_info))
410 einfo (_("%F%P: %pB: error adding symbols: %E\n"), abfd);
412 return true;
415 /* Search for a needed file in a path. */
417 static bool
418 ldelf_search_needed (const char *path, struct dt_needed *n, int force,
419 int is_linux, int elfsize)
421 const char *s;
422 const char *name = n->name;
423 size_t len;
424 struct dt_needed needed;
426 if (name[0] == '/')
427 return ldelf_try_needed (n, force, is_linux);
429 if (path == NULL || *path == '\0')
430 return false;
432 needed.by = n->by;
433 needed.name = n->name;
435 len = strlen (name);
436 while (1)
438 unsigned offset = 0;
439 char * var;
440 char *filename, *sset;
442 s = strchr (path, config.rpath_separator);
443 if (s == NULL)
444 s = path + strlen (path);
446 #if HAVE_DOS_BASED_FILE_SYSTEM
447 /* Assume a match on the second char is part of drive specifier. */
448 else if (config.rpath_separator == ':'
449 && s == path + 1
450 && ISALPHA (*path))
452 s = strchr (s + 1, config.rpath_separator);
453 if (s == NULL)
454 s = path + strlen (path);
456 #endif
457 filename = (char *) xmalloc (s - path + len + 2);
458 if (s == path)
459 sset = filename;
460 else
462 memcpy (filename, path, s - path);
463 filename[s - path] = '/';
464 sset = filename + (s - path) + 1;
466 strcpy (sset, name);
468 /* PR 20535: Support the same pseudo-environment variables that
469 are supported by ld.so. Namely, $ORIGIN, $LIB and $PLATFORM.
470 Since there can be more than one occurrence of these tokens in
471 the path we loop until no more are found. Since we might not
472 be able to substitute some of the tokens we maintain an offset
473 into the filename for where we should begin our scan. */
474 while ((var = strchr (filename + offset, '$')) != NULL)
476 /* The ld.so manual page does not say, but I am going to assume that
477 these tokens are terminated by a directory separator character
478 (/) or the end of the string. There is also an implication that
479 $ORIGIN should only be used at the start of a path, but that is
480 not enforced here.
482 The ld.so manual page also states that it allows ${ORIGIN},
483 ${LIB} and ${PLATFORM}, so these are supported as well.
485 FIXME: The code could be a lot cleverer about allocating space
486 for the processed string. */
487 char * end = strchr (var, '/');
488 const char *replacement = NULL;
489 char * v = var + 1;
490 char * freeme = NULL;
491 unsigned flen = strlen (filename);
493 if (end != NULL)
494 /* Temporarily terminate the filename at the end of the token. */
495 * end = 0;
497 if (*v == '{')
498 ++ v;
499 switch (*v++)
501 case 'O':
502 if (strcmp (v, "RIGIN") == 0 || strcmp (v, "RIGIN}") == 0)
504 /* ORIGIN - replace with the full path to the directory
505 containing the program or shared object. */
506 if (needed.by == NULL)
508 if (link_info.output_bfd == NULL)
510 break;
512 else
513 replacement = bfd_get_filename (link_info.output_bfd);
515 else
516 replacement = bfd_get_filename (needed.by);
518 if (replacement)
520 char * slash;
522 if (replacement[0] == '/')
523 freeme = xstrdup (replacement);
524 else
526 char * current_dir = getpwd ();
528 freeme = xmalloc (strlen (replacement)
529 + strlen (current_dir) + 2);
530 sprintf (freeme, "%s/%s", current_dir, replacement);
533 replacement = freeme;
534 if ((slash = strrchr (replacement, '/')) != NULL)
535 * slash = 0;
538 break;
540 case 'L':
541 if (strcmp (v, "IB") == 0 || strcmp (v, "IB}") == 0)
543 /* LIB - replace with "lib" in 32-bit environments
544 and "lib64" in 64-bit environments. */
546 switch (elfsize)
548 case 32: replacement = "lib"; break;
549 case 64: replacement = "lib64"; break;
550 default:
551 abort ();
554 break;
556 case 'P':
557 /* Supporting $PLATFORM in a cross-hosted environment is not
558 possible. Supporting it in a native environment involves
559 loading the <sys/auxv.h> header file which loads the
560 system <elf.h> header file, which conflicts with the
561 "include/elf/mips.h" header file. */
562 /* Fall through. */
563 default:
564 break;
567 if (replacement)
569 char * filename2 = xmalloc (flen + strlen (replacement));
571 if (end)
573 sprintf (filename2, "%.*s%s/%s",
574 (int)(var - filename), filename,
575 replacement, end + 1);
576 offset = (var - filename) + 1 + strlen (replacement);
578 else
580 sprintf (filename2, "%.*s%s",
581 (int)(var - filename), filename,
582 replacement);
583 offset = var - filename + strlen (replacement);
586 free (filename);
587 filename = filename2;
588 /* There is no need to restore the path separator (when
589 end != NULL) as we have replaced the entire string. */
591 else
593 if (verbose)
594 /* We only issue an "unrecognised" message in verbose mode
595 as the $<foo> token might be a legitimate component of
596 a path name in the target's file system. */
597 info_msg (_("unrecognised or unsupported token "
598 "'%s' in search path\n"), var);
599 if (end)
600 /* Restore the path separator. */
601 * end = '/';
603 /* PR 20784: Make sure that we resume the scan *after*
604 the token that we could not replace. */
605 offset = (var + 1) - filename;
608 free (freeme);
611 needed.name = filename;
613 if (ldelf_try_needed (&needed, force, is_linux))
614 return true;
616 free (filename);
618 if (*s == '\0')
619 break;
620 path = s + 1;
623 return false;
626 /* Prefix the sysroot to absolute paths in PATH, a string containing
627 paths separated by config.rpath_separator. If running on a DOS
628 file system, paths containing a drive spec won't have the sysroot
629 prefix added, unless the sysroot also specifies the same drive. */
631 static const char *
632 ldelf_add_sysroot (const char *path)
634 size_t len, extra;
635 const char *p;
636 char *ret, *q;
637 int dos_drive_sysroot = HAS_DRIVE_SPEC (ld_sysroot);
639 len = strlen (ld_sysroot);
640 for (extra = 0, p = path; ; )
642 int dos_drive = HAS_DRIVE_SPEC (p);
644 if (dos_drive)
645 p += 2;
646 if (IS_DIR_SEPARATOR (*p)
647 && (!dos_drive
648 || (dos_drive_sysroot
649 && ld_sysroot[0] == p[-2])))
651 if (dos_drive && dos_drive_sysroot)
652 extra += len - 2;
653 else
654 extra += len;
656 p = strchr (p, config.rpath_separator);
657 if (!p)
658 break;
659 ++p;
662 ret = xmalloc (strlen (path) + extra + 1);
664 for (q = ret, p = path; ; )
666 const char *end;
667 int dos_drive = HAS_DRIVE_SPEC (p);
669 if (dos_drive)
671 *q++ = *p++;
672 *q++ = *p++;
674 if (IS_DIR_SEPARATOR (*p)
675 && (!dos_drive
676 || (dos_drive_sysroot
677 && ld_sysroot[0] == p[-2])))
679 if (dos_drive && dos_drive_sysroot)
681 strcpy (q, ld_sysroot + 2);
682 q += len - 2;
684 else
686 strcpy (q, ld_sysroot);
687 q += len;
690 end = strchr (p, config.rpath_separator);
691 if (end)
693 size_t n = end - p + 1;
694 strncpy (q, p, n);
695 q += n;
696 p += n;
698 else
700 strcpy (q, p);
701 break;
705 return ret;
708 /* Read the system search path the FreeBSD way rather than the Linux way. */
709 #ifdef HAVE_ELF_HINTS_H
710 #include <elf-hints.h>
711 #else
712 #include "elf-hints-local.h"
713 #endif
715 static bool
716 ldelf_check_ld_elf_hints (const struct bfd_link_needed_list *l, int force,
717 int elfsize)
719 static bool initialized;
720 static const char *ld_elf_hints;
721 struct dt_needed needed;
723 if (!initialized)
725 FILE *f;
726 char *tmppath;
728 tmppath = concat (ld_sysroot, _PATH_ELF_HINTS, (const char *) NULL);
729 f = fopen (tmppath, FOPEN_RB);
730 free (tmppath);
731 if (f != NULL)
733 struct elfhints_hdr hdr;
735 if (fread (&hdr, 1, sizeof (hdr), f) == sizeof (hdr)
736 && hdr.magic == ELFHINTS_MAGIC
737 && hdr.version == 1)
739 if (fseek (f, hdr.strtab + hdr.dirlist, SEEK_SET) != -1)
741 char *b;
743 b = xmalloc (hdr.dirlistlen + 1);
744 if (fread (b, 1, hdr.dirlistlen + 1, f) ==
745 hdr.dirlistlen + 1)
746 ld_elf_hints = ldelf_add_sysroot (b);
748 free (b);
751 fclose (f);
754 initialized = true;
757 if (ld_elf_hints == NULL)
758 return false;
760 needed.by = l->by;
761 needed.name = l->name;
762 return ldelf_search_needed (ld_elf_hints, &needed, force, false, elfsize);
765 /* For a native linker, check the file /etc/ld.so.conf for directories
766 in which we may find shared libraries. /etc/ld.so.conf is really
767 only meaningful on Linux. */
769 struct ldelf_ld_so_conf
771 char *path;
772 size_t len, alloc;
775 static bool
776 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *, const char *);
778 static void
779 ldelf_parse_ld_so_conf_include (struct ldelf_ld_so_conf *info,
780 const char *filename,
781 const char *pattern)
783 char *newp = NULL;
784 #ifdef HAVE_GLOB
785 glob_t gl;
786 #endif
788 if (pattern[0] != '/')
790 char *p = strrchr (filename, '/');
791 size_t patlen = strlen (pattern) + 1;
793 newp = xmalloc (p - filename + 1 + patlen);
794 memcpy (newp, filename, p - filename + 1);
795 memcpy (newp + (p - filename + 1), pattern, patlen);
796 pattern = newp;
799 #ifdef HAVE_GLOB
800 if (glob (pattern, 0, NULL, &gl) == 0)
802 size_t i;
804 for (i = 0; i < gl.gl_pathc; ++i)
805 ldelf_parse_ld_so_conf (info, gl.gl_pathv[i]);
806 globfree (&gl);
808 #else
809 /* If we do not have glob, treat the pattern as a literal filename. */
810 ldelf_parse_ld_so_conf (info, pattern);
811 #endif
813 free (newp);
816 static bool
817 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *info, const char *filename)
819 FILE *f = fopen (filename, FOPEN_RT);
820 char *line;
821 size_t linelen;
823 if (f == NULL)
824 return false;
826 linelen = 256;
827 line = xmalloc (linelen);
830 char *p = line, *q;
832 /* Normally this would use getline(3), but we need to be portable. */
833 while ((q = fgets (p, linelen - (p - line), f)) != NULL
834 && strlen (q) == linelen - (p - line) - 1
835 && line[linelen - 2] != '\n')
837 line = xrealloc (line, 2 * linelen);
838 p = line + linelen - 1;
839 linelen += linelen;
842 if (q == NULL && p == line)
843 break;
845 p = strchr (line, '\n');
846 if (p)
847 *p = '\0';
849 /* Because the file format does not know any form of quoting we
850 can search forward for the next '#' character and if found
851 make it terminating the line. */
852 p = strchr (line, '#');
853 if (p)
854 *p = '\0';
856 /* Remove leading whitespace. NUL is no whitespace character. */
857 p = line;
858 while (*p == ' ' || *p == '\f' || *p == '\r' || *p == '\t' || *p == '\v')
859 ++p;
861 /* If the line is blank it is ignored. */
862 if (p[0] == '\0')
863 continue;
865 if (startswith (p, "include") && (p[7] == ' ' || p[7] == '\t'))
867 char *dir, c;
868 p += 8;
871 while (*p == ' ' || *p == '\t')
872 ++p;
874 if (*p == '\0')
875 break;
877 dir = p;
879 while (*p != ' ' && *p != '\t' && *p)
880 ++p;
882 c = *p;
883 *p++ = '\0';
884 if (dir[0] != '\0')
885 ldelf_parse_ld_so_conf_include (info, filename, dir);
887 while (c != '\0');
889 else
891 char *dir = p;
892 while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
893 && *p != '\r' && *p != '\v')
894 ++p;
896 while (p != dir && p[-1] == '/')
897 --p;
898 if (info->path == NULL)
900 info->alloc = p - dir + 1 + 256;
901 info->path = xmalloc (info->alloc);
902 info->len = 0;
904 else
906 if (info->len + 1 + (p - dir) >= info->alloc)
908 info->alloc += p - dir + 256;
909 info->path = xrealloc (info->path, info->alloc);
911 info->path[info->len++] = config.rpath_separator;
913 memcpy (info->path + info->len, dir, p - dir);
914 info->len += p - dir;
915 info->path[info->len] = '\0';
918 while (! feof (f));
919 free (line);
920 fclose (f);
921 return true;
924 static bool
925 ldelf_check_ld_so_conf (const struct bfd_link_needed_list *l, int force,
926 int elfsize, const char *prefix)
928 static bool initialized;
929 static const char *ld_so_conf;
930 struct dt_needed needed;
932 if (! initialized)
934 char *tmppath;
935 struct ldelf_ld_so_conf info;
937 info.path = NULL;
938 info.len = info.alloc = 0;
939 tmppath = concat (ld_sysroot, prefix, "/etc/ld.so.conf",
940 (const char *) NULL);
941 if (!ldelf_parse_ld_so_conf (&info, tmppath))
943 free (tmppath);
944 tmppath = concat (ld_sysroot, "/etc/ld.so.conf",
945 (const char *) NULL);
946 ldelf_parse_ld_so_conf (&info, tmppath);
948 free (tmppath);
950 if (info.path)
952 ld_so_conf = ldelf_add_sysroot (info.path);
953 free (info.path);
955 initialized = true;
958 if (ld_so_conf == NULL)
959 return false;
962 needed.by = l->by;
963 needed.name = l->name;
964 return ldelf_search_needed (ld_so_conf, &needed, force, true, elfsize);
967 /* See if an input file matches a DT_NEEDED entry by name. */
969 static void
970 ldelf_check_needed (lang_input_statement_type *s)
972 const char *soname;
974 /* Stop looking if we've found a loaded lib. */
975 if (global_found != NULL
976 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
977 & DYN_AS_NEEDED) == 0)
978 return;
980 if (s->filename == NULL || s->the_bfd == NULL)
981 return;
983 /* Don't look for a second non-loaded as-needed lib. */
984 if (global_found != NULL
985 && (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
986 return;
988 if (filename_cmp (s->filename, global_needed->name) == 0)
990 global_found = s;
991 return;
994 if (s->flags.search_dirs)
996 const char *f = strrchr (s->filename, '/');
997 if (f != NULL
998 && filename_cmp (f + 1, global_needed->name) == 0)
1000 global_found = s;
1001 return;
1005 soname = bfd_elf_get_dt_soname (s->the_bfd);
1006 if (soname != NULL
1007 && filename_cmp (soname, global_needed->name) == 0)
1009 global_found = s;
1010 return;
1014 static void
1015 ldelf_handle_dt_needed (struct elf_link_hash_table *htab,
1016 int use_libpath, int native, int is_linux,
1017 int is_freebsd, int elfsize, const char *prefix)
1019 struct bfd_link_needed_list *needed, *l;
1020 bfd *abfd;
1021 bfd **save_input_bfd_tail;
1023 /* Get the list of files which appear in DT_NEEDED entries in
1024 dynamic objects included in the link (often there will be none).
1025 For each such file, we want to track down the corresponding
1026 library, and include the symbol table in the link. This is what
1027 the runtime dynamic linker will do. Tracking the files down here
1028 permits one dynamic object to include another without requiring
1029 special action by the person doing the link. Note that the
1030 needed list can actually grow while we are stepping through this
1031 loop. */
1032 save_input_bfd_tail = link_info.input_bfds_tail;
1033 needed = bfd_elf_get_needed_list (link_info.output_bfd, &link_info);
1034 for (l = needed; l != NULL; l = l->next)
1036 struct bfd_link_needed_list *ll;
1037 struct dt_needed n, nn;
1038 int force;
1040 /* If the lib that needs this one was --as-needed and wasn't
1041 found to be needed, then this lib isn't needed either. */
1042 if (l->by != NULL
1043 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_AS_NEEDED) != 0)
1044 continue;
1046 /* Skip the lib if --no-copy-dt-needed-entries and when we are
1047 handling DT_NEEDED entries or --allow-shlib-undefined is in
1048 effect. */
1049 if (l->by != NULL
1050 && (htab->handling_dt_needed
1051 || link_info.unresolved_syms_in_shared_libs == RM_IGNORE)
1052 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_NO_ADD_NEEDED) != 0)
1053 continue;
1055 /* If we've already seen this file, skip it. */
1056 for (ll = needed; ll != l; ll = ll->next)
1057 if ((ll->by == NULL
1058 || (bfd_elf_get_dyn_lib_class (ll->by) & DYN_AS_NEEDED) == 0)
1059 && strcmp (ll->name, l->name) == 0)
1060 break;
1061 if (ll != l)
1062 continue;
1064 /* See if this file was included in the link explicitly. */
1065 global_needed = l;
1066 global_found = NULL;
1067 lang_for_each_input_file (ldelf_check_needed);
1068 if (global_found != NULL
1069 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
1070 & DYN_AS_NEEDED) == 0)
1071 continue;
1073 n.by = l->by;
1074 n.name = l->name;
1075 nn.by = l->by;
1076 if (verbose)
1077 info_msg (_("%s needed by %pB\n"), l->name, l->by);
1079 /* As-needed libs specified on the command line (or linker script)
1080 take priority over libs found in search dirs. */
1081 if (global_found != NULL)
1083 nn.name = global_found->filename;
1084 if (ldelf_try_needed (&nn, true, is_linux))
1085 continue;
1088 /* We need to find this file and include the symbol table. We
1089 want to search for the file in the same way that the dynamic
1090 linker will search. That means that we want to use
1091 rpath_link, rpath, then the environment variable
1092 LD_LIBRARY_PATH (native only), then the DT_RPATH/DT_RUNPATH
1093 entries (native only), then the linker script LIB_SEARCH_DIRS.
1094 We do not search using the -L arguments.
1096 We search twice. The first time, we skip objects which may
1097 introduce version mismatches. The second time, we force
1098 their use. See ldelf_vercheck comment. */
1099 for (force = 0; force < 2; force++)
1101 size_t len;
1102 search_dirs_type *search;
1103 const char *path;
1104 struct bfd_link_needed_list *rp;
1105 int found;
1107 if (ldelf_search_needed (command_line.rpath_link, &n, force,
1108 is_linux, elfsize))
1109 break;
1111 if (use_libpath)
1113 path = command_line.rpath;
1114 if (path)
1116 path = ldelf_add_sysroot (path);
1117 found = ldelf_search_needed (path, &n, force,
1118 is_linux, elfsize);
1119 free ((char *) path);
1120 if (found)
1121 break;
1124 if (native)
1126 if (command_line.rpath_link == NULL
1127 && command_line.rpath == NULL)
1129 path = (const char *) getenv ("LD_RUN_PATH");
1130 if (path
1131 && ldelf_search_needed (path, &n, force,
1132 is_linux, elfsize))
1133 break;
1135 path = (const char *) getenv ("LD_LIBRARY_PATH");
1136 if (path
1137 && ldelf_search_needed (path, &n, force,
1138 is_linux, elfsize))
1139 break;
1141 if (use_libpath)
1143 found = 0;
1144 rp = bfd_elf_get_runpath_list (link_info.output_bfd, &link_info);
1145 for (; !found && rp != NULL; rp = rp->next)
1147 path = ldelf_add_sysroot (rp->name);
1148 found = (rp->by == l->by
1149 && ldelf_search_needed (path, &n, force,
1150 is_linux, elfsize));
1151 free ((char *) path);
1153 if (found)
1154 break;
1156 if (is_freebsd
1157 && ldelf_check_ld_elf_hints (l, force, elfsize))
1158 break;
1160 if (is_linux
1161 && ldelf_check_ld_so_conf (l, force, elfsize, prefix))
1162 break;
1165 len = strlen (l->name);
1166 for (search = search_head; search != NULL; search = search->next)
1168 char *filename;
1170 if (search->cmdline)
1171 continue;
1172 filename = (char *) xmalloc (strlen (search->name) + len + 2);
1173 sprintf (filename, "%s/%s", search->name, l->name);
1174 nn.name = filename;
1175 if (ldelf_try_needed (&nn, force, is_linux))
1176 break;
1177 free (filename);
1179 if (search != NULL)
1180 break;
1183 if (force < 2)
1184 continue;
1186 einfo (_("%P: warning: %s, needed by %pB, not found "
1187 "(try using -rpath or -rpath-link)\n"),
1188 l->name, l->by);
1191 /* Don't add DT_NEEDED when loading shared objects from DT_NEEDED for
1192 plugin symbol resolution while handling DT_NEEDED entries. */
1193 if (!htab->handling_dt_needed)
1194 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1195 if (bfd_get_format (abfd) == bfd_object
1196 && ((abfd->flags) & DYNAMIC) != 0
1197 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
1198 && (elf_dyn_lib_class (abfd) & (DYN_AS_NEEDED | DYN_NO_NEEDED)) == 0
1199 && elf_dt_name (abfd) != NULL)
1201 if (bfd_elf_add_dt_needed_tag (abfd, &link_info) < 0)
1202 einfo (_("%F%P: failed to add DT_NEEDED dynamic tag\n"));
1205 link_info.input_bfds_tail = save_input_bfd_tail;
1206 *save_input_bfd_tail = NULL;
1209 /* This is called before calling plugin 'all symbols read' hook. */
1211 void
1212 ldelf_before_plugin_all_symbols_read (int use_libpath, int native,
1213 int is_linux, int is_freebsd,
1214 int elfsize, const char *prefix)
1216 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1218 if (!is_elf_hash_table (&htab->root))
1219 return;
1221 htab->handling_dt_needed = true;
1222 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1223 is_freebsd, elfsize, prefix);
1224 htab->handling_dt_needed = false;
1227 /* This is called after all the input files have been opened and all
1228 symbols have been loaded. */
1230 void
1231 ldelf_after_open (int use_libpath, int native, int is_linux, int is_freebsd,
1232 int elfsize, const char *prefix)
1234 struct elf_link_hash_table *htab;
1235 asection *s;
1236 bfd *abfd;
1238 after_open_default ();
1240 htab = elf_hash_table (&link_info);
1241 if (!is_elf_hash_table (&htab->root))
1242 return;
1244 if (command_line.out_implib_filename)
1246 unlink_if_ordinary (command_line.out_implib_filename);
1247 link_info.out_implib_bfd
1248 = bfd_openw (command_line.out_implib_filename,
1249 bfd_get_target (link_info.output_bfd));
1251 if (link_info.out_implib_bfd == NULL)
1253 einfo (_("%F%P: %s: can't open for writing: %E\n"),
1254 command_line.out_implib_filename);
1258 if (ldelf_emit_note_gnu_build_id != NULL
1259 || ldelf_emit_note_fdo_package_metadata != NULL)
1261 /* Find an ELF input. */
1262 for (abfd = link_info.input_bfds;
1263 abfd != (bfd *) NULL; abfd = abfd->link.next)
1264 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1265 && bfd_count_sections (abfd) != 0
1266 && !bfd_input_just_syms (abfd))
1267 break;
1269 /* PR 10555: If there are no ELF input files do not try to
1270 create a .note.gnu-build-id section. */
1271 if (abfd == NULL
1272 || (ldelf_emit_note_gnu_build_id != NULL
1273 && !ldelf_setup_build_id (abfd)))
1275 free ((char *) ldelf_emit_note_gnu_build_id);
1276 ldelf_emit_note_gnu_build_id = NULL;
1279 if (abfd == NULL
1280 || (ldelf_emit_note_fdo_package_metadata != NULL
1281 && !ldelf_setup_package_metadata (abfd)))
1283 free ((char *) ldelf_emit_note_fdo_package_metadata);
1284 ldelf_emit_note_fdo_package_metadata = NULL;
1288 get_elf_backend_data (link_info.output_bfd)->setup_gnu_properties (&link_info);
1290 /* Do not allow executable files to be used as inputs to the link. */
1291 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1293 /* Discard input .note.gnu.build-id sections. */
1294 s = bfd_get_section_by_name (abfd, ".note.gnu.build-id");
1295 while (s != NULL)
1297 if (s != elf_tdata (link_info.output_bfd)->o->build_id.sec)
1298 s->flags |= SEC_EXCLUDE;
1299 s = bfd_get_next_section_by_name (NULL, s);
1302 if (abfd->xvec->flavour == bfd_target_elf_flavour
1303 && !bfd_input_just_syms (abfd)
1304 && elf_tdata (abfd) != NULL
1305 /* FIXME: Maybe check for other non-supportable types as well ? */
1306 && (elf_tdata (abfd)->elf_header->e_type == ET_EXEC
1307 || (elf_tdata (abfd)->elf_header->e_type == ET_DYN
1308 && elf_tdata (abfd)->is_pie)))
1309 einfo (_("%F%P: cannot use executable file '%pB' as input to a link\n"),
1310 abfd);
1313 if (bfd_link_relocatable (&link_info))
1315 if (link_info.execstack == !link_info.noexecstack)
1317 /* PR ld/16744: If "-z [no]execstack" has been specified on the
1318 command line and we are perfoming a relocatable link then no
1319 PT_GNU_STACK segment will be created and so the
1320 linkinfo.[no]execstack values set in _handle_option() will have no
1321 effect. Instead we create a .note.GNU-stack section in much the
1322 same way as the assembler does with its --[no]execstack option. */
1323 flagword flags = SEC_READONLY | (link_info.execstack ? SEC_CODE : 0);
1324 (void) bfd_make_section_with_flags (link_info.input_bfds,
1325 ".note.GNU-stack", flags);
1327 return;
1330 if (!link_info.traditional_format)
1332 bfd *elfbfd = NULL;
1333 bool warn_eh_frame = false;
1334 int seen_type = 0;
1336 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1338 int type = 0;
1340 if (bfd_input_just_syms (abfd))
1341 continue;
1343 for (s = abfd->sections; s && type < COMPACT_EH_HDR; s = s->next)
1345 const char *name = bfd_section_name (s);
1347 if (bfd_is_abs_section (s->output_section))
1348 continue;
1349 if (startswith (name, ".eh_frame_entry"))
1350 type = COMPACT_EH_HDR;
1351 else if (strcmp (name, ".eh_frame") == 0 && s->size > 8)
1352 type = DWARF2_EH_HDR;
1355 if (type != 0)
1357 if (seen_type == 0)
1359 seen_type = type;
1361 else if (seen_type != type)
1363 einfo (_("%F%P: compact frame descriptions incompatible with"
1364 " DWARF2 .eh_frame from %pB\n"),
1365 type == DWARF2_EH_HDR ? abfd : elfbfd);
1366 break;
1369 if (!elfbfd
1370 && (type == COMPACT_EH_HDR
1371 || link_info.eh_frame_hdr_type != 0))
1373 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1374 elfbfd = abfd;
1376 warn_eh_frame = true;
1380 if (seen_type == COMPACT_EH_HDR)
1381 link_info.eh_frame_hdr_type = COMPACT_EH_HDR;
1383 if (elfbfd)
1385 const struct elf_backend_data *bed;
1387 bed = get_elf_backend_data (elfbfd);
1388 s = bfd_make_section_with_flags (elfbfd, ".eh_frame_hdr",
1389 bed->dynamic_sec_flags
1390 | SEC_READONLY);
1391 if (s != NULL
1392 && bfd_set_section_alignment (s, 2))
1394 htab->eh_info.hdr_sec = s;
1395 warn_eh_frame = false;
1398 if (warn_eh_frame)
1399 einfo (_("%P: warning: cannot create .eh_frame_hdr section,"
1400 " --eh-frame-hdr ignored\n"));
1403 if (link_info.eh_frame_hdr_type == COMPACT_EH_HDR)
1404 if (!bfd_elf_parse_eh_frame_entries (NULL, &link_info))
1405 einfo (_("%F%P: failed to parse EH frame entries\n"));
1407 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1408 is_freebsd, elfsize, prefix);
1411 static bfd_size_type
1412 id_note_section_size (bfd *abfd ATTRIBUTE_UNUSED)
1414 const char *style = ldelf_emit_note_gnu_build_id;
1415 bfd_size_type size;
1416 bfd_size_type build_id_size;
1418 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1419 size = (size + 3) & -(bfd_size_type) 4;
1421 build_id_size = compute_build_id_size (style);
1422 if (build_id_size)
1423 size += build_id_size;
1424 else
1425 size = 0;
1427 return size;
1430 static bool
1431 write_build_id (bfd *abfd)
1433 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1434 struct elf_obj_tdata *t = elf_tdata (abfd);
1435 const char *style;
1436 asection *asec;
1437 Elf_Internal_Shdr *i_shdr;
1438 unsigned char *contents, *id_bits;
1439 bfd_size_type size;
1440 file_ptr position;
1441 Elf_External_Note *e_note;
1443 style = t->o->build_id.style;
1444 asec = t->o->build_id.sec;
1445 if (bfd_is_abs_section (asec->output_section))
1447 einfo (_("%P: warning: .note.gnu.build-id section discarded,"
1448 " --build-id ignored\n"));
1449 return true;
1451 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1453 if (i_shdr->contents == NULL)
1455 if (asec->contents == NULL)
1456 asec->contents = (unsigned char *) xmalloc (asec->size);
1457 contents = asec->contents;
1459 else
1460 contents = i_shdr->contents + asec->output_offset;
1462 e_note = (Elf_External_Note *) contents;
1463 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1464 size = (size + 3) & -(bfd_size_type) 4;
1465 id_bits = contents + size;
1466 size = asec->size - size;
1468 /* Clear the build ID field. */
1469 memset (id_bits, 0, size);
1471 bfd_h_put_32 (abfd, sizeof "GNU", &e_note->namesz);
1472 bfd_h_put_32 (abfd, size, &e_note->descsz);
1473 bfd_h_put_32 (abfd, NT_GNU_BUILD_ID, &e_note->type);
1474 memcpy (e_note->name, "GNU", sizeof "GNU");
1476 generate_build_id (abfd, style, bed->s->checksum_contents, id_bits, size);
1478 position = i_shdr->sh_offset + asec->output_offset;
1479 size = asec->size;
1480 return (bfd_seek (abfd, position, SEEK_SET) == 0
1481 && bfd_bwrite (contents, size, abfd) == size);
1484 /* Make .note.gnu.build-id section, and set up elf_tdata->build_id. */
1486 bool
1487 ldelf_setup_build_id (bfd *ibfd)
1489 asection *s;
1490 bfd_size_type size;
1491 flagword flags;
1493 size = id_note_section_size (ibfd);
1494 if (size == 0)
1496 einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1497 return false;
1500 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1501 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1502 s = bfd_make_section_anyway_with_flags (ibfd, ".note.gnu.build-id",
1503 flags);
1504 if (s != NULL && bfd_set_section_alignment (s, 2))
1506 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1507 t->o->build_id.after_write_object_contents = &write_build_id;
1508 t->o->build_id.style = ldelf_emit_note_gnu_build_id;
1509 t->o->build_id.sec = s;
1510 elf_section_type (s) = SHT_NOTE;
1511 s->size = size;
1512 return true;
1515 einfo (_("%P: warning: cannot create .note.gnu.build-id section,"
1516 " --build-id ignored\n"));
1517 return false;
1520 static bool
1521 write_package_metadata (bfd *abfd)
1523 struct elf_obj_tdata *t = elf_tdata (abfd);
1524 const char *json;
1525 asection *asec;
1526 Elf_Internal_Shdr *i_shdr;
1527 unsigned char *contents, *json_bits;
1528 bfd_size_type size;
1529 file_ptr position;
1530 Elf_External_Note *e_note;
1532 json = t->o->package_metadata.json;
1533 asec = t->o->package_metadata.sec;
1534 if (bfd_is_abs_section (asec->output_section))
1536 einfo (_("%P: warning: .note.package section discarded,"
1537 " --package-metadata ignored\n"));
1538 return true;
1540 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1542 if (i_shdr->contents == NULL)
1544 if (asec->contents == NULL)
1545 asec->contents = (unsigned char *) xmalloc (asec->size);
1546 contents = asec->contents;
1548 else
1549 contents = i_shdr->contents + asec->output_offset;
1551 e_note = (Elf_External_Note *) contents;
1552 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1553 size = (size + 3) & -(bfd_size_type) 4;
1554 json_bits = contents + size;
1555 size = asec->size - size;
1557 /* Clear the package metadata field. */
1558 memset (json_bits, 0, size);
1560 bfd_h_put_32 (abfd, sizeof "FDO", &e_note->namesz);
1561 bfd_h_put_32 (abfd, size, &e_note->descsz);
1562 bfd_h_put_32 (abfd, FDO_PACKAGING_METADATA, &e_note->type);
1563 memcpy (e_note->name, "FDO", sizeof "FDO");
1564 memcpy (json_bits, json, strlen(json));
1566 position = i_shdr->sh_offset + asec->output_offset;
1567 size = asec->size;
1568 return (bfd_seek (abfd, position, SEEK_SET) == 0
1569 && bfd_bwrite (contents, size, abfd) == size);
1572 /* Make .note.package section.
1573 https://systemd.io/ELF_PACKAGE_METADATA/ */
1575 bool
1576 ldelf_setup_package_metadata (bfd *ibfd)
1578 asection *s;
1579 bfd_size_type size;
1580 size_t json_length;
1581 flagword flags;
1583 /* If the option wasn't specified, silently return. */
1584 if (!ldelf_emit_note_fdo_package_metadata)
1585 return false;
1587 /* The option was specified, but it's empty, log and return. */
1588 json_length = strlen (ldelf_emit_note_fdo_package_metadata);
1589 if (json_length == 0)
1591 einfo (_("%P: warning: --package-metadata is empty, ignoring\n"));
1592 return false;
1595 #ifdef HAVE_JANSSON
1596 json_error_t json_error;
1597 json_t *json = json_loads (ldelf_emit_note_fdo_package_metadata,
1598 0, &json_error);
1599 if (!json)
1601 einfo (_("%P: warning: --package-metadata=%s does not contain valid "
1602 "JSON, ignoring: %s\n"),
1603 ldelf_emit_note_fdo_package_metadata, json_error.text);
1604 return false;
1606 else
1607 json_decref (json);
1608 #endif
1610 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1611 size += json_length + 1;
1612 size = (size + 3) & -(bfd_size_type) 4;
1614 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1615 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1616 s = bfd_make_section_anyway_with_flags (ibfd, ".note.package",
1617 flags);
1618 if (s != NULL && bfd_set_section_alignment (s, 2))
1620 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1621 t->o->package_metadata.after_write_object_contents
1622 = &write_package_metadata;
1623 t->o->package_metadata.json = ldelf_emit_note_fdo_package_metadata;
1624 t->o->package_metadata.sec = s;
1625 elf_section_type (s) = SHT_NOTE;
1626 s->size = size;
1627 return true;
1630 einfo (_("%P: warning: cannot create .note.package section,"
1631 " --package-metadata ignored\n"));
1632 return false;
1635 /* Look through an expression for an assignment statement. */
1637 static void
1638 ldelf_find_exp_assignment (etree_type *exp)
1640 bool provide = false;
1642 switch (exp->type.node_class)
1644 case etree_provide:
1645 case etree_provided:
1646 provide = true;
1647 /* Fallthru */
1648 case etree_assign:
1649 /* We call record_link_assignment even if the symbol is defined.
1650 This is because if it is defined by a dynamic object, we
1651 actually want to use the value defined by the linker script,
1652 not the value from the dynamic object (because we are setting
1653 symbols like etext). If the symbol is defined by a regular
1654 object, then, as it happens, calling record_link_assignment
1655 will do no harm. */
1656 if (strcmp (exp->assign.dst, ".") != 0)
1658 if (!bfd_elf_record_link_assignment (link_info.output_bfd,
1659 &link_info,
1660 exp->assign.dst, provide,
1661 exp->assign.hidden))
1662 einfo (_("%F%P: failed to record assignment to %s: %E\n"),
1663 exp->assign.dst);
1665 ldelf_find_exp_assignment (exp->assign.src);
1666 break;
1668 case etree_binary:
1669 ldelf_find_exp_assignment (exp->binary.lhs);
1670 ldelf_find_exp_assignment (exp->binary.rhs);
1671 break;
1673 case etree_trinary:
1674 ldelf_find_exp_assignment (exp->trinary.cond);
1675 ldelf_find_exp_assignment (exp->trinary.lhs);
1676 ldelf_find_exp_assignment (exp->trinary.rhs);
1677 break;
1679 case etree_unary:
1680 ldelf_find_exp_assignment (exp->unary.child);
1681 break;
1683 default:
1684 break;
1688 /* This is called by the before_allocation routine via
1689 lang_for_each_statement. It locates any assignment statements, and
1690 tells the ELF backend about them, in case they are assignments to
1691 symbols which are referred to by dynamic objects. */
1693 static void
1694 ldelf_find_statement_assignment (lang_statement_union_type *s)
1696 if (s->header.type == lang_assignment_statement_enum)
1697 ldelf_find_exp_assignment (s->assignment_statement.exp);
1700 /* Used by before_allocation and handle_option. */
1702 void
1703 ldelf_append_to_separated_string (char **to, char *op_arg)
1705 if (*to == NULL)
1706 *to = xstrdup (op_arg);
1707 else
1709 size_t to_len = strlen (*to);
1710 size_t op_arg_len = strlen (op_arg);
1711 char *buf;
1712 char *cp = *to;
1714 /* First see whether OPTARG is already in the path. */
1717 if (strncmp (op_arg, cp, op_arg_len) == 0
1718 && (cp[op_arg_len] == 0
1719 || cp[op_arg_len] == config.rpath_separator))
1720 /* We found it. */
1721 break;
1723 /* Not yet found. */
1724 cp = strchr (cp, config.rpath_separator);
1725 if (cp != NULL)
1726 ++cp;
1728 while (cp != NULL);
1730 if (cp == NULL)
1732 buf = xmalloc (to_len + op_arg_len + 2);
1733 sprintf (buf, "%s%c%s", *to,
1734 config.rpath_separator, op_arg);
1735 free (*to);
1736 *to = buf;
1741 /* This is called after the sections have been attached to output
1742 sections, but before any sizes or addresses have been set. */
1744 void
1745 ldelf_before_allocation (char *audit, char *depaudit,
1746 const char *default_interpreter_name)
1748 const char *rpath;
1749 asection *sinterp;
1750 bfd *abfd;
1751 struct bfd_link_hash_entry *ehdr_start = NULL;
1752 unsigned char ehdr_start_save_type = 0;
1753 char ehdr_start_save_u[sizeof ehdr_start->u
1754 - sizeof ehdr_start->u.def.next] = "";
1756 if (is_elf_hash_table (link_info.hash))
1758 _bfd_elf_tls_setup (link_info.output_bfd, &link_info);
1760 /* Make __ehdr_start hidden if it has been referenced, to
1761 prevent the symbol from being dynamic. */
1762 if (!bfd_link_relocatable (&link_info))
1764 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1765 struct elf_link_hash_entry *h
1766 = elf_link_hash_lookup (htab, "__ehdr_start", false, false, true);
1768 /* Only adjust the export class if the symbol was referenced
1769 and not defined, otherwise leave it alone. */
1770 if (h != NULL
1771 && (h->root.type == bfd_link_hash_new
1772 || h->root.type == bfd_link_hash_undefined
1773 || h->root.type == bfd_link_hash_undefweak
1774 || h->root.type == bfd_link_hash_common))
1776 /* Don't leave the symbol undefined. Undefined hidden
1777 symbols typically won't have dynamic relocations, but
1778 we most likely will need dynamic relocations for
1779 __ehdr_start if we are building a PIE or shared
1780 library. */
1781 ehdr_start = &h->root;
1782 ehdr_start_save_type = ehdr_start->type;
1783 memcpy (ehdr_start_save_u,
1784 (char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1785 sizeof ehdr_start_save_u);
1786 ehdr_start->type = bfd_link_hash_defined;
1787 /* It will be converted to section-relative later. */
1788 ehdr_start->u.def.section = bfd_abs_section_ptr;
1789 ehdr_start->u.def.value = 0;
1793 /* If we are going to make any variable assignments, we need to
1794 let the ELF backend know about them in case the variables are
1795 referred to by dynamic objects. */
1796 lang_for_each_statement (ldelf_find_statement_assignment);
1799 /* Let the ELF backend work out the sizes of any sections required
1800 by dynamic linking. */
1801 rpath = command_line.rpath;
1802 if (rpath == NULL)
1803 rpath = (const char *) getenv ("LD_RUN_PATH");
1805 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1806 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1808 const char *audit_libs = elf_dt_audit (abfd);
1810 /* If the input bfd contains an audit entry, we need to add it as
1811 a dep audit entry. */
1812 if (audit_libs && *audit_libs != '\0')
1814 char *cp = xstrdup (audit_libs);
1817 int more = 0;
1818 char *cp2 = strchr (cp, config.rpath_separator);
1820 if (cp2)
1822 *cp2 = '\0';
1823 more = 1;
1826 if (cp != NULL && *cp != '\0')
1827 ldelf_append_to_separated_string (&depaudit, cp);
1829 cp = more ? ++cp2 : NULL;
1831 while (cp != NULL);
1835 if (! (bfd_elf_size_dynamic_sections
1836 (link_info.output_bfd, command_line.soname, rpath,
1837 command_line.filter_shlib, audit, depaudit,
1838 (const char * const *) command_line.auxiliary_filters,
1839 &link_info, &sinterp)))
1840 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1842 if (sinterp != NULL)
1844 /* Let the user override the dynamic linker we are using. */
1845 if (command_line.interpreter != NULL)
1846 default_interpreter_name = command_line.interpreter;
1847 if (default_interpreter_name != NULL)
1849 sinterp->contents = (bfd_byte *) default_interpreter_name;
1850 sinterp->size = strlen ((char *) sinterp->contents) + 1;
1854 /* Look for any sections named .gnu.warning. As a GNU extensions,
1855 we treat such sections as containing warning messages. We print
1856 out the warning message, and then zero out the section size so
1857 that it does not get copied into the output file. */
1860 LANG_FOR_EACH_INPUT_STATEMENT (is)
1862 asection *s;
1863 bfd_size_type sz;
1864 char *msg;
1866 if (is->flags.just_syms)
1867 continue;
1869 s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1870 if (s == NULL)
1871 continue;
1873 sz = s->size;
1874 msg = (char *) xmalloc ((size_t) (sz + 1));
1875 if (! bfd_get_section_contents (is->the_bfd, s, msg,
1876 (file_ptr) 0, sz))
1877 einfo (_("%F%P: %pB: can't read contents of section .gnu.warning: %E\n"),
1878 is->the_bfd);
1879 msg[sz] = '\0';
1880 (*link_info.callbacks->warning) (&link_info, msg,
1881 (const char *) NULL, is->the_bfd,
1882 (asection *) NULL, (bfd_vma) 0);
1883 free (msg);
1885 /* Clobber the section size, so that we don't waste space
1886 copying the warning into the output file. If we've already
1887 sized the output section, adjust its size. The adjustment
1888 is on rawsize because targets that size sections early will
1889 have called lang_reset_memory_regions after sizing. */
1890 if (s->output_section != NULL
1891 && s->output_section->rawsize >= s->size)
1892 s->output_section->rawsize -= s->size;
1894 s->size = 0;
1896 /* Also set SEC_EXCLUDE, so that local symbols defined in the
1897 warning section don't get copied to the output. */
1898 s->flags |= SEC_EXCLUDE | SEC_KEEP;
1902 before_allocation_default ();
1904 if (!bfd_elf_size_dynsym_hash_dynstr (link_info.output_bfd, &link_info))
1905 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1907 if (ehdr_start != NULL)
1909 /* If we twiddled __ehdr_start to defined earlier, put it back
1910 as it was. */
1911 ehdr_start->type = ehdr_start_save_type;
1912 memcpy ((char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1913 ehdr_start_save_u,
1914 sizeof ehdr_start_save_u);
1917 /* Try to open a dynamic archive. This is where we know that ELF
1918 dynamic libraries have an extension of .so (or .sl on oddball systems
1919 like hpux). */
1921 bool
1922 ldelf_open_dynamic_archive (const char *arch, search_dirs_type *search,
1923 lang_input_statement_type *entry)
1925 const char *filename;
1926 char *string;
1927 size_t len;
1928 bool opened = false;
1930 if (! entry->flags.maybe_archive)
1931 return false;
1933 filename = entry->filename;
1934 len = strlen (search->name) + strlen (filename);
1935 if (entry->flags.full_name_provided)
1937 len += sizeof "/";
1938 string = (char *) xmalloc (len);
1939 sprintf (string, "%s/%s", search->name, filename);
1941 else
1943 size_t xlen = 0;
1945 len += strlen (arch) + sizeof "/lib.so";
1946 #ifdef EXTRA_SHLIB_EXTENSION
1947 xlen = (strlen (EXTRA_SHLIB_EXTENSION) > 3
1948 ? strlen (EXTRA_SHLIB_EXTENSION) - 3
1949 : 0);
1950 #endif
1951 string = (char *) xmalloc (len + xlen);
1952 sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1953 #ifdef EXTRA_SHLIB_EXTENSION
1954 /* Try the .so extension first. If that fails build a new filename
1955 using EXTRA_SHLIB_EXTENSION. */
1956 opened = ldfile_try_open_bfd (string, entry);
1957 if (!opened)
1958 strcpy (string + len - 4, EXTRA_SHLIB_EXTENSION);
1959 #endif
1962 if (!opened && !ldfile_try_open_bfd (string, entry))
1964 free (string);
1965 return false;
1968 entry->filename = string;
1970 /* We have found a dynamic object to include in the link. The ELF
1971 backend linker will create a DT_NEEDED entry in the .dynamic
1972 section naming this file. If this file includes a DT_SONAME
1973 entry, it will be used. Otherwise, the ELF linker will just use
1974 the name of the file. For an archive found by searching, like
1975 this one, the DT_NEEDED entry should consist of just the name of
1976 the file, without the path information used to find it. Note
1977 that we only need to do this if we have a dynamic object; an
1978 archive will never be referenced by a DT_NEEDED entry.
1980 FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1981 very pretty. I haven't been able to think of anything that is
1982 pretty, though. */
1983 if (bfd_check_format (entry->the_bfd, bfd_object)
1984 && (entry->the_bfd->flags & DYNAMIC) != 0)
1986 ASSERT (entry->flags.maybe_archive && entry->flags.search_dirs);
1988 /* Rather than duplicating the logic above. Just use the
1989 filename we recorded earlier. */
1991 if (!entry->flags.full_name_provided)
1992 filename = lbasename (entry->filename);
1993 bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
1996 return true;
1999 /* A variant of lang_output_section_find used by place_orphan. */
2001 static lang_output_section_statement_type *
2002 output_rel_find (int isdyn, int rela)
2004 lang_output_section_statement_type *lookup;
2005 lang_output_section_statement_type *last = NULL;
2006 lang_output_section_statement_type *last_alloc = NULL;
2007 lang_output_section_statement_type *last_ro_alloc = NULL;
2008 lang_output_section_statement_type *last_rel = NULL;
2009 lang_output_section_statement_type *last_rel_alloc = NULL;
2011 for (lookup = (void *) lang_os_list.head;
2012 lookup != NULL;
2013 lookup = lookup->next)
2015 if (lookup->constraint >= 0
2016 && startswith (lookup->name, ".rel"))
2018 int lookrela = lookup->name[4] == 'a';
2020 /* .rel.dyn must come before all other reloc sections, to suit
2021 GNU ld.so. */
2022 if (isdyn)
2023 break;
2025 /* Don't place after .rel.plt as doing so results in wrong
2026 dynamic tags. */
2027 if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
2028 break;
2030 if (rela == lookrela || last_rel == NULL)
2031 last_rel = lookup;
2032 if ((rela == lookrela || last_rel_alloc == NULL)
2033 && lookup->bfd_section != NULL
2034 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2035 last_rel_alloc = lookup;
2038 last = lookup;
2039 if (lookup->bfd_section != NULL
2040 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2042 last_alloc = lookup;
2043 if ((lookup->bfd_section->flags & SEC_READONLY) != 0)
2044 last_ro_alloc = lookup;
2048 if (last_rel_alloc)
2049 return last_rel_alloc;
2051 if (last_rel)
2052 return last_rel;
2054 if (last_ro_alloc)
2055 return last_ro_alloc;
2057 if (last_alloc)
2058 return last_alloc;
2060 return last;
2063 /* Return whether IN is suitable to be part of OUT. */
2065 static bool
2066 elf_orphan_compatible (asection *in, asection *out)
2068 /* Non-zero sh_info implies a section with SHF_INFO_LINK with
2069 unknown semantics for the generic linker, or a SHT_REL/SHT_RELA
2070 section where sh_info specifies a symbol table. (We won't see
2071 SHT_GROUP, SHT_SYMTAB or SHT_DYNSYM sections here.) We clearly
2072 can't merge SHT_REL/SHT_RELA using differing symbol tables, and
2073 shouldn't merge sections with differing unknown semantics. */
2074 if (elf_section_data (out)->this_hdr.sh_info
2075 != elf_section_data (in)->this_hdr.sh_info)
2076 return false;
2077 /* We can't merge with a member of an output section group or merge
2078 two sections with differing SHF_EXCLUDE or other processor and OS
2079 specific flags when doing a relocatable link. */
2080 if (bfd_link_relocatable (&link_info)
2081 && (elf_next_in_group (out) != NULL
2082 || ((elf_section_flags (out) ^ elf_section_flags (in))
2083 & (SHF_MASKPROC | SHF_MASKOS)) != 0))
2084 return false;
2085 return _bfd_elf_match_sections_by_type (link_info.output_bfd, out,
2086 in->owner, in);
2089 /* Place an orphan section. We use this to put random SHF_ALLOC
2090 sections in the right segment. */
2092 lang_output_section_statement_type *
2093 ldelf_place_orphan (asection *s, const char *secname, int constraint)
2095 static struct orphan_save hold[] =
2097 { ".text",
2098 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2099 0, 0, 0, 0 },
2100 { ".rodata",
2101 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2102 0, 0, 0, 0 },
2103 { ".tdata",
2104 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_THREAD_LOCAL,
2105 0, 0, 0, 0 },
2106 { ".data",
2107 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2108 0, 0, 0, 0 },
2109 { ".bss",
2110 SEC_ALLOC,
2111 0, 0, 0, 0 },
2112 { 0,
2113 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2114 0, 0, 0, 0 },
2115 { ".interp",
2116 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2117 0, 0, 0, 0 },
2118 { ".sdata",
2119 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
2120 0, 0, 0, 0 },
2121 { ".comment",
2122 SEC_HAS_CONTENTS,
2123 0, 0, 0, 0 },
2125 enum orphan_save_index
2127 orphan_text = 0,
2128 orphan_rodata,
2129 orphan_tdata,
2130 orphan_data,
2131 orphan_bss,
2132 orphan_rel,
2133 orphan_interp,
2134 orphan_sdata,
2135 orphan_nonalloc
2137 static int orphan_init_done = 0;
2138 struct orphan_save *place;
2139 lang_output_section_statement_type *after;
2140 lang_output_section_statement_type *os;
2141 lang_output_section_statement_type *match_by_name = NULL;
2142 int isdyn = 0;
2143 int elfinput = s->owner->xvec->flavour == bfd_target_elf_flavour;
2144 int elfoutput = link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour;
2145 unsigned int sh_type = elfinput ? elf_section_type (s) : SHT_NULL;
2146 flagword flags;
2147 asection *nexts;
2149 if (!bfd_link_relocatable (&link_info)
2150 && link_info.combreloc
2151 && (s->flags & SEC_ALLOC))
2153 if (elfinput)
2154 switch (sh_type)
2156 case SHT_RELA:
2157 secname = ".rela.dyn";
2158 isdyn = 1;
2159 break;
2160 case SHT_REL:
2161 secname = ".rel.dyn";
2162 isdyn = 1;
2163 break;
2164 default:
2165 break;
2167 else if (startswith (secname, ".rel"))
2169 secname = secname[4] == 'a' ? ".rela.dyn" : ".rel.dyn";
2170 isdyn = 1;
2174 if (!bfd_link_relocatable (&link_info)
2175 && elfinput
2176 && elfoutput
2177 && (s->flags & SEC_ALLOC) != 0
2178 && (elf_tdata (s->owner)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0
2179 && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
2181 /* Find the output mbind section with the same type, attributes
2182 and sh_info field. */
2183 for (os = (void *) lang_os_list.head;
2184 os != NULL;
2185 os = os->next)
2186 if (os->bfd_section != NULL
2187 && !bfd_is_abs_section (os->bfd_section)
2188 && (elf_section_flags (os->bfd_section) & SHF_GNU_MBIND) != 0
2189 && ((s->flags & (SEC_ALLOC
2190 | SEC_LOAD
2191 | SEC_HAS_CONTENTS
2192 | SEC_READONLY
2193 | SEC_CODE))
2194 == (os->bfd_section->flags & (SEC_ALLOC
2195 | SEC_LOAD
2196 | SEC_HAS_CONTENTS
2197 | SEC_READONLY
2198 | SEC_CODE)))
2199 && (elf_section_data (os->bfd_section)->this_hdr.sh_info
2200 == elf_section_data (s)->this_hdr.sh_info))
2202 lang_add_section (&os->children, s, NULL, NULL, os);
2203 return os;
2206 /* Create the output mbind section with the ".mbind." prefix
2207 in section name. */
2208 if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2209 secname = ".mbind.bss";
2210 else if ((s->flags & SEC_READONLY) == 0)
2211 secname = ".mbind.data";
2212 else if ((s->flags & SEC_CODE) == 0)
2213 secname = ".mbind.rodata";
2214 else
2215 secname = ".mbind.text";
2216 elf_tdata (link_info.output_bfd)->has_gnu_osabi |= elf_gnu_osabi_mbind;
2219 /* Look through the script to see where to place this section. The
2220 script includes entries added by previous lang_insert_orphan
2221 calls, so this loop puts multiple compatible orphans of the same
2222 name into a single output section. */
2223 if (constraint == 0)
2224 for (os = lang_output_section_find (secname);
2225 os != NULL;
2226 os = next_matching_output_section_statement (os, 0))
2228 /* If we don't match an existing output section, tell
2229 lang_insert_orphan to create a new output section. */
2230 constraint = SPECIAL;
2232 /* Check to see if we already have an output section statement
2233 with this name, and its bfd section has compatible flags.
2234 If the section already exists but does not have any flags
2235 set, then it has been created by the linker, possibly as a
2236 result of a --section-start command line switch. */
2237 if (os->bfd_section != NULL
2238 && (os->bfd_section->flags == 0
2239 || (((s->flags ^ os->bfd_section->flags)
2240 & (SEC_LOAD | SEC_ALLOC)) == 0
2241 && (!elfinput
2242 || !elfoutput
2243 || elf_orphan_compatible (s, os->bfd_section)))))
2245 lang_add_section (&os->children, s, NULL, NULL, os);
2246 return os;
2249 /* Save unused output sections in case we can match them
2250 against orphans later. */
2251 if (os->bfd_section == NULL)
2252 match_by_name = os;
2255 /* If we didn't match an active output section, see if we matched an
2256 unused one and use that. */
2257 if (match_by_name)
2259 lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2260 return match_by_name;
2263 if (!orphan_init_done)
2265 struct orphan_save *ho;
2267 for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
2268 if (ho->name != NULL)
2270 ho->os = lang_output_section_find (ho->name);
2271 if (ho->os != NULL && ho->os->flags == 0)
2272 ho->os->flags = ho->flags;
2274 orphan_init_done = 1;
2277 /* If this is a final link, then always put .gnu.warning.SYMBOL
2278 sections into the .text section to get them out of the way. */
2279 if (bfd_link_executable (&link_info)
2280 && startswith (s->name, ".gnu.warning.")
2281 && hold[orphan_text].os != NULL)
2283 os = hold[orphan_text].os;
2284 lang_add_section (&os->children, s, NULL, NULL, os);
2285 return os;
2288 flags = s->flags;
2289 if (!bfd_link_relocatable (&link_info))
2291 nexts = s;
2292 while ((nexts = bfd_get_next_section_by_name (nexts->owner, nexts))
2293 != NULL)
2294 if (nexts->output_section == NULL
2295 && (nexts->flags & SEC_EXCLUDE) == 0
2296 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2297 && (nexts->owner->flags & DYNAMIC) == 0
2298 && !bfd_input_just_syms (nexts->owner)
2299 && _bfd_elf_match_sections_by_type (nexts->owner, nexts,
2300 s->owner, s))
2301 flags = (((flags ^ SEC_READONLY)
2302 | (nexts->flags ^ SEC_READONLY))
2303 ^ SEC_READONLY);
2306 /* Decide which segment the section should go in based on the
2307 section name and section flags. We put loadable .note sections
2308 right after the .interp section, so that the PT_NOTE segment is
2309 stored right after the program headers where the OS can read it
2310 in the first page. */
2312 place = NULL;
2313 if ((flags & (SEC_ALLOC | SEC_DEBUGGING)) == 0)
2314 place = &hold[orphan_nonalloc];
2315 else if ((flags & SEC_ALLOC) == 0)
2317 else if ((flags & SEC_LOAD) != 0
2318 && (elfinput
2319 ? sh_type == SHT_NOTE
2320 : startswith (secname, ".note")))
2321 place = &hold[orphan_interp];
2322 else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS | SEC_THREAD_LOCAL)) == 0)
2323 place = &hold[orphan_bss];
2324 else if ((flags & SEC_SMALL_DATA) != 0)
2325 place = &hold[orphan_sdata];
2326 else if ((flags & SEC_THREAD_LOCAL) != 0)
2327 place = &hold[orphan_tdata];
2328 else if ((flags & SEC_READONLY) == 0)
2329 place = &hold[orphan_data];
2330 else if ((flags & SEC_LOAD) != 0
2331 && (elfinput
2332 ? sh_type == SHT_RELA || sh_type == SHT_REL
2333 : startswith (secname, ".rel")))
2334 place = &hold[orphan_rel];
2335 else if ((flags & SEC_CODE) == 0)
2336 place = &hold[orphan_rodata];
2337 else
2338 place = &hold[orphan_text];
2340 after = NULL;
2341 if (place != NULL)
2343 if (place->os == NULL)
2345 if (place->name != NULL)
2346 place->os = lang_output_section_find (place->name);
2347 else
2349 int rela = elfinput ? sh_type == SHT_RELA : secname[4] == 'a';
2350 place->os = output_rel_find (isdyn, rela);
2353 after = place->os;
2354 if (after == NULL)
2355 after
2356 = lang_output_section_find_by_flags (s, flags, &place->os,
2357 _bfd_elf_match_sections_by_type);
2358 if (after == NULL)
2359 /* *ABS* is always the first output section statement. */
2360 after = (void *) lang_os_list.head;
2363 return lang_insert_orphan (s, secname, constraint, after, place, NULL, NULL);
2366 void
2367 ldelf_before_place_orphans (void)
2369 bfd *abfd;
2371 for (abfd = link_info.input_bfds;
2372 abfd != (bfd *) NULL; abfd = abfd->link.next)
2373 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2374 && bfd_count_sections (abfd) != 0
2375 && !bfd_input_just_syms (abfd))
2377 asection *isec;
2378 for (isec = abfd->sections; isec != NULL; isec = isec->next)
2380 /* Discard a section if any of its linked-to section has
2381 been discarded. */
2382 asection *linked_to_sec;
2383 for (linked_to_sec = elf_linked_to_section (isec);
2384 linked_to_sec != NULL && !linked_to_sec->linker_mark;
2385 linked_to_sec = elf_linked_to_section (linked_to_sec))
2387 if (discarded_section (linked_to_sec))
2389 isec->output_section = bfd_abs_section_ptr;
2390 isec->flags |= SEC_EXCLUDE;
2391 break;
2393 linked_to_sec->linker_mark = 1;
2395 for (linked_to_sec = elf_linked_to_section (isec);
2396 linked_to_sec != NULL && linked_to_sec->linker_mark;
2397 linked_to_sec = elf_linked_to_section (linked_to_sec))
2398 linked_to_sec->linker_mark = 0;
2403 void
2404 ldelf_set_output_arch (void)
2406 set_output_arch_default ();
2407 if (link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour)
2408 elf_link_info (link_info.output_bfd) = &link_info;