Fix: Segmentation fault caused by npd in objdump
[binutils-gdb.git] / ld / ldelf.c
blobd74354a96222b050d49445fdd03e7d7f82b9e682
1 /* ELF emulation code for targets using elf.em.
2 Copyright (C) 1991-2023 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 ();
527 size_t cdir_len = strlen (current_dir);
528 size_t rep_len = strlen (replacement);
529 freeme = xmalloc (cdir_len + rep_len + 2);
530 memcpy (freeme, current_dir, cdir_len);
531 freeme[cdir_len] = '/';
532 memcpy (freeme + cdir_len + 1,
533 replacement, rep_len + 1);
536 replacement = freeme;
537 if ((slash = strrchr (replacement, '/')) != NULL)
538 * slash = 0;
541 break;
543 case 'L':
544 if (strcmp (v, "IB") == 0 || strcmp (v, "IB}") == 0)
546 /* LIB - replace with "lib" in 32-bit environments
547 and "lib64" in 64-bit environments. */
549 switch (elfsize)
551 case 32: replacement = "lib"; break;
552 case 64: replacement = "lib64"; break;
553 default:
554 abort ();
557 break;
559 case 'P':
560 /* Supporting $PLATFORM in a cross-hosted environment is not
561 possible. Supporting it in a native environment involves
562 loading the <sys/auxv.h> header file which loads the
563 system <elf.h> header file, which conflicts with the
564 "include/elf/mips.h" header file. */
565 /* Fall through. */
566 default:
567 break;
570 if (replacement)
572 char * filename2 = xmalloc (flen + strlen (replacement));
574 if (end)
576 sprintf (filename2, "%.*s%s/%s",
577 (int)(var - filename), filename,
578 replacement, end + 1);
579 offset = (var - filename) + 1 + strlen (replacement);
581 else
583 sprintf (filename2, "%.*s%s",
584 (int)(var - filename), filename,
585 replacement);
586 offset = var - filename + strlen (replacement);
589 free (filename);
590 filename = filename2;
591 /* There is no need to restore the path separator (when
592 end != NULL) as we have replaced the entire string. */
594 else
596 if (verbose)
597 /* We only issue an "unrecognised" message in verbose mode
598 as the $<foo> token might be a legitimate component of
599 a path name in the target's file system. */
600 info_msg (_("unrecognised or unsupported token "
601 "'%s' in search path\n"), var);
602 if (end)
603 /* Restore the path separator. */
604 * end = '/';
606 /* PR 20784: Make sure that we resume the scan *after*
607 the token that we could not replace. */
608 offset = (var + 1) - filename;
611 free (freeme);
614 needed.name = filename;
616 if (ldelf_try_needed (&needed, force, is_linux))
617 return true;
619 free (filename);
621 if (*s == '\0')
622 break;
623 path = s + 1;
626 return false;
629 /* Prefix the sysroot to absolute paths in PATH, a string containing
630 paths separated by config.rpath_separator. If running on a DOS
631 file system, paths containing a drive spec won't have the sysroot
632 prefix added, unless the sysroot also specifies the same drive. */
634 static const char *
635 ldelf_add_sysroot (const char *path)
637 size_t len, extra;
638 const char *p;
639 char *ret, *q;
640 int dos_drive_sysroot = HAS_DRIVE_SPEC (ld_sysroot);
642 len = strlen (ld_sysroot);
643 for (extra = 0, p = path; ; )
645 int dos_drive = HAS_DRIVE_SPEC (p);
647 if (dos_drive)
648 p += 2;
649 if (IS_DIR_SEPARATOR (*p)
650 && (!dos_drive
651 || (dos_drive_sysroot
652 && ld_sysroot[0] == p[-2])))
654 if (dos_drive && dos_drive_sysroot)
655 extra += len - 2;
656 else
657 extra += len;
659 p = strchr (p, config.rpath_separator);
660 if (!p)
661 break;
662 ++p;
665 ret = xmalloc (strlen (path) + extra + 1);
667 for (q = ret, p = path; ; )
669 const char *end;
670 int dos_drive = HAS_DRIVE_SPEC (p);
672 if (dos_drive)
674 *q++ = *p++;
675 *q++ = *p++;
677 if (IS_DIR_SEPARATOR (*p)
678 && (!dos_drive
679 || (dos_drive_sysroot
680 && ld_sysroot[0] == p[-2])))
682 if (dos_drive && dos_drive_sysroot)
684 strcpy (q, ld_sysroot + 2);
685 q += len - 2;
687 else
689 strcpy (q, ld_sysroot);
690 q += len;
693 end = strchr (p, config.rpath_separator);
694 if (end)
696 size_t n = end - p + 1;
697 strncpy (q, p, n);
698 q += n;
699 p += n;
701 else
703 strcpy (q, p);
704 break;
708 return ret;
711 /* Read the system search path the FreeBSD way rather than the Linux way. */
712 #ifdef HAVE_ELF_HINTS_H
713 #include <elf-hints.h>
714 #else
715 #include "elf-hints-local.h"
716 #endif
718 static bool
719 ldelf_check_ld_elf_hints (const struct bfd_link_needed_list *l, int force,
720 int elfsize)
722 static bool initialized;
723 static const char *ld_elf_hints;
724 struct dt_needed needed;
726 if (!initialized)
728 FILE *f;
729 char *tmppath;
731 tmppath = concat (ld_sysroot, _PATH_ELF_HINTS, (const char *) NULL);
732 f = fopen (tmppath, FOPEN_RB);
733 free (tmppath);
734 if (f != NULL)
736 struct elfhints_hdr hdr;
738 if (fread (&hdr, 1, sizeof (hdr), f) == sizeof (hdr)
739 && hdr.magic == ELFHINTS_MAGIC
740 && hdr.version == 1)
742 if (fseek (f, hdr.strtab + hdr.dirlist, SEEK_SET) != -1)
744 char *b;
746 b = xmalloc (hdr.dirlistlen + 1);
747 if (fread (b, 1, hdr.dirlistlen + 1, f) ==
748 hdr.dirlistlen + 1)
749 ld_elf_hints = ldelf_add_sysroot (b);
751 free (b);
754 fclose (f);
757 initialized = true;
760 if (ld_elf_hints == NULL)
761 return false;
763 needed.by = l->by;
764 needed.name = l->name;
765 return ldelf_search_needed (ld_elf_hints, &needed, force, false, elfsize);
768 /* For a native linker, check the file /etc/ld.so.conf for directories
769 in which we may find shared libraries. /etc/ld.so.conf is really
770 only meaningful on Linux. */
772 struct ldelf_ld_so_conf
774 char *path;
775 size_t len, alloc;
778 static bool
779 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *, const char *);
781 static void
782 ldelf_parse_ld_so_conf_include (struct ldelf_ld_so_conf *info,
783 const char *filename,
784 const char *pattern)
786 char *newp = NULL;
787 #ifdef HAVE_GLOB
788 glob_t gl;
789 #endif
791 if (pattern[0] != '/')
793 char *p = strrchr (filename, '/');
794 size_t patlen = strlen (pattern) + 1;
796 newp = xmalloc (p - filename + 1 + patlen);
797 memcpy (newp, filename, p - filename + 1);
798 memcpy (newp + (p - filename + 1), pattern, patlen);
799 pattern = newp;
802 #ifdef HAVE_GLOB
803 if (glob (pattern, 0, NULL, &gl) == 0)
805 size_t i;
807 for (i = 0; i < gl.gl_pathc; ++i)
808 ldelf_parse_ld_so_conf (info, gl.gl_pathv[i]);
809 globfree (&gl);
811 #else
812 /* If we do not have glob, treat the pattern as a literal filename. */
813 ldelf_parse_ld_so_conf (info, pattern);
814 #endif
816 free (newp);
819 static bool
820 ldelf_parse_ld_so_conf (struct ldelf_ld_so_conf *info, const char *filename)
822 FILE *f = fopen (filename, FOPEN_RT);
823 char *line;
824 size_t linelen;
826 if (f == NULL)
827 return false;
829 linelen = 256;
830 line = xmalloc (linelen);
833 char *p = line, *q;
835 /* Normally this would use getline(3), but we need to be portable. */
836 while ((q = fgets (p, linelen - (p - line), f)) != NULL
837 && strlen (q) == linelen - (p - line) - 1
838 && line[linelen - 2] != '\n')
840 line = xrealloc (line, 2 * linelen);
841 p = line + linelen - 1;
842 linelen += linelen;
845 if (q == NULL && p == line)
846 break;
848 p = strchr (line, '\n');
849 if (p)
850 *p = '\0';
852 /* Because the file format does not know any form of quoting we
853 can search forward for the next '#' character and if found
854 make it terminating the line. */
855 p = strchr (line, '#');
856 if (p)
857 *p = '\0';
859 /* Remove leading whitespace. NUL is no whitespace character. */
860 p = line;
861 while (*p == ' ' || *p == '\f' || *p == '\r' || *p == '\t' || *p == '\v')
862 ++p;
864 /* If the line is blank it is ignored. */
865 if (p[0] == '\0')
866 continue;
868 if (startswith (p, "include") && (p[7] == ' ' || p[7] == '\t'))
870 char *dir, c;
871 p += 8;
874 while (*p == ' ' || *p == '\t')
875 ++p;
877 if (*p == '\0')
878 break;
880 dir = p;
882 while (*p != ' ' && *p != '\t' && *p)
883 ++p;
885 c = *p;
886 *p++ = '\0';
887 if (dir[0] != '\0')
888 ldelf_parse_ld_so_conf_include (info, filename, dir);
890 while (c != '\0');
892 else
894 char *dir = p;
895 while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
896 && *p != '\r' && *p != '\v')
897 ++p;
899 while (p != dir && p[-1] == '/')
900 --p;
901 if (info->path == NULL)
903 info->alloc = p - dir + 1 + 256;
904 info->path = xmalloc (info->alloc);
905 info->len = 0;
907 else
909 if (info->len + 1 + (p - dir) >= info->alloc)
911 info->alloc += p - dir + 256;
912 info->path = xrealloc (info->path, info->alloc);
914 info->path[info->len++] = config.rpath_separator;
916 memcpy (info->path + info->len, dir, p - dir);
917 info->len += p - dir;
918 info->path[info->len] = '\0';
921 while (! feof (f));
922 free (line);
923 fclose (f);
924 return true;
927 static bool
928 ldelf_check_ld_so_conf (const struct bfd_link_needed_list *l, int force,
929 int elfsize, const char *prefix)
931 static bool initialized;
932 static const char *ld_so_conf;
933 struct dt_needed needed;
935 if (! initialized)
937 char *tmppath;
938 struct ldelf_ld_so_conf info;
940 info.path = NULL;
941 info.len = info.alloc = 0;
942 tmppath = concat (ld_sysroot, prefix, "/etc/ld.so.conf",
943 (const char *) NULL);
944 if (!ldelf_parse_ld_so_conf (&info, tmppath))
946 free (tmppath);
947 tmppath = concat (ld_sysroot, "/etc/ld.so.conf",
948 (const char *) NULL);
949 ldelf_parse_ld_so_conf (&info, tmppath);
951 free (tmppath);
953 if (info.path)
955 ld_so_conf = ldelf_add_sysroot (info.path);
956 free (info.path);
958 initialized = true;
961 if (ld_so_conf == NULL)
962 return false;
965 needed.by = l->by;
966 needed.name = l->name;
967 return ldelf_search_needed (ld_so_conf, &needed, force, true, elfsize);
970 /* See if an input file matches a DT_NEEDED entry by name. */
972 static void
973 ldelf_check_needed (lang_input_statement_type *s)
975 const char *soname;
977 /* Stop looking if we've found a loaded lib. */
978 if (global_found != NULL
979 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
980 & DYN_AS_NEEDED) == 0)
981 return;
983 if (s->filename == NULL || s->the_bfd == NULL)
984 return;
986 /* Don't look for a second non-loaded as-needed lib. */
987 if (global_found != NULL
988 && (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
989 return;
991 if (filename_cmp (s->filename, global_needed->name) == 0)
993 global_found = s;
994 return;
997 if (s->flags.search_dirs)
999 const char *f = strrchr (s->filename, '/');
1000 if (f != NULL
1001 && filename_cmp (f + 1, global_needed->name) == 0)
1003 global_found = s;
1004 return;
1008 soname = bfd_elf_get_dt_soname (s->the_bfd);
1009 if (soname != NULL
1010 && filename_cmp (soname, global_needed->name) == 0)
1012 global_found = s;
1013 return;
1017 static void
1018 ldelf_handle_dt_needed (struct elf_link_hash_table *htab,
1019 int use_libpath, int native, int is_linux,
1020 int is_freebsd, int elfsize, const char *prefix)
1022 struct bfd_link_needed_list *needed, *l;
1023 bfd *abfd;
1024 bfd **save_input_bfd_tail;
1026 /* Get the list of files which appear in DT_NEEDED entries in
1027 dynamic objects included in the link (often there will be none).
1028 For each such file, we want to track down the corresponding
1029 library, and include the symbol table in the link. This is what
1030 the runtime dynamic linker will do. Tracking the files down here
1031 permits one dynamic object to include another without requiring
1032 special action by the person doing the link. Note that the
1033 needed list can actually grow while we are stepping through this
1034 loop. */
1035 save_input_bfd_tail = link_info.input_bfds_tail;
1036 needed = bfd_elf_get_needed_list (link_info.output_bfd, &link_info);
1037 for (l = needed; l != NULL; l = l->next)
1039 struct bfd_link_needed_list *ll;
1040 struct dt_needed n, nn;
1041 int force;
1043 /* If the lib that needs this one was --as-needed and wasn't
1044 found to be needed, then this lib isn't needed either. */
1045 if (l->by != NULL
1046 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_AS_NEEDED) != 0)
1047 continue;
1049 /* Skip the lib if --no-copy-dt-needed-entries and when we are
1050 handling DT_NEEDED entries or --allow-shlib-undefined is in
1051 effect. */
1052 if (l->by != NULL
1053 && (htab->handling_dt_needed
1054 || link_info.unresolved_syms_in_shared_libs == RM_IGNORE)
1055 && (bfd_elf_get_dyn_lib_class (l->by) & DYN_NO_ADD_NEEDED) != 0)
1056 continue;
1058 /* If we've already seen this file, skip it. */
1059 for (ll = needed; ll != l; ll = ll->next)
1060 if ((ll->by == NULL
1061 || (bfd_elf_get_dyn_lib_class (ll->by) & DYN_AS_NEEDED) == 0)
1062 && strcmp (ll->name, l->name) == 0)
1063 break;
1064 if (ll != l)
1065 continue;
1067 /* See if this file was included in the link explicitly. */
1068 global_needed = l;
1069 global_found = NULL;
1070 lang_for_each_input_file (ldelf_check_needed);
1071 if (global_found != NULL
1072 && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
1073 & DYN_AS_NEEDED) == 0)
1074 continue;
1076 n.by = l->by;
1077 n.name = l->name;
1078 nn.by = l->by;
1079 if (verbose)
1080 info_msg (_("%s needed by %pB\n"), l->name, l->by);
1082 /* As-needed libs specified on the command line (or linker script)
1083 take priority over libs found in search dirs. */
1084 if (global_found != NULL)
1086 nn.name = global_found->filename;
1087 if (ldelf_try_needed (&nn, true, is_linux))
1088 continue;
1091 /* We need to find this file and include the symbol table. We
1092 want to search for the file in the same way that the dynamic
1093 linker will search. That means that we want to use
1094 rpath_link, rpath, then the environment variable
1095 LD_LIBRARY_PATH (native only), then the DT_RPATH/DT_RUNPATH
1096 entries (native only), then the linker script LIB_SEARCH_DIRS.
1097 We do not search using the -L arguments.
1099 We search twice. The first time, we skip objects which may
1100 introduce version mismatches. The second time, we force
1101 their use. See ldelf_vercheck comment. */
1102 for (force = 0; force < 2; force++)
1104 size_t len;
1105 search_dirs_type *search;
1106 const char *path;
1107 struct bfd_link_needed_list *rp;
1108 int found;
1110 if (ldelf_search_needed (command_line.rpath_link, &n, force,
1111 is_linux, elfsize))
1112 break;
1114 if (use_libpath)
1116 path = command_line.rpath;
1117 if (path)
1119 path = ldelf_add_sysroot (path);
1120 found = ldelf_search_needed (path, &n, force,
1121 is_linux, elfsize);
1122 free ((char *) path);
1123 if (found)
1124 break;
1127 if (native)
1129 if (command_line.rpath_link == NULL
1130 && command_line.rpath == NULL)
1132 path = (const char *) getenv ("LD_RUN_PATH");
1133 if (path
1134 && ldelf_search_needed (path, &n, force,
1135 is_linux, elfsize))
1136 break;
1138 path = (const char *) getenv ("LD_LIBRARY_PATH");
1139 if (path
1140 && ldelf_search_needed (path, &n, force,
1141 is_linux, elfsize))
1142 break;
1144 if (use_libpath)
1146 found = 0;
1147 rp = bfd_elf_get_runpath_list (link_info.output_bfd, &link_info);
1148 for (; !found && rp != NULL; rp = rp->next)
1150 path = ldelf_add_sysroot (rp->name);
1151 found = (rp->by == l->by
1152 && ldelf_search_needed (path, &n, force,
1153 is_linux, elfsize));
1154 free ((char *) path);
1156 if (found)
1157 break;
1159 if (is_freebsd
1160 && ldelf_check_ld_elf_hints (l, force, elfsize))
1161 break;
1163 if (is_linux
1164 && ldelf_check_ld_so_conf (l, force, elfsize, prefix))
1165 break;
1168 len = strlen (l->name);
1169 for (search = search_head; search != NULL; search = search->next)
1171 char *filename;
1173 if (search->cmdline)
1174 continue;
1175 filename = (char *) xmalloc (strlen (search->name) + len + 2);
1176 sprintf (filename, "%s/%s", search->name, l->name);
1177 nn.name = filename;
1178 if (ldelf_try_needed (&nn, force, is_linux))
1179 break;
1180 free (filename);
1182 if (search != NULL)
1183 break;
1186 if (force < 2)
1187 continue;
1189 einfo (_("%P: warning: %s, needed by %pB, not found "
1190 "(try using -rpath or -rpath-link)\n"),
1191 l->name, l->by);
1194 /* Don't add DT_NEEDED when loading shared objects from DT_NEEDED for
1195 plugin symbol resolution while handling DT_NEEDED entries. */
1196 if (!htab->handling_dt_needed)
1197 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1198 if (bfd_get_format (abfd) == bfd_object
1199 && ((abfd->flags) & DYNAMIC) != 0
1200 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
1201 && (elf_dyn_lib_class (abfd) & (DYN_AS_NEEDED | DYN_NO_NEEDED)) == 0
1202 && elf_dt_name (abfd) != NULL)
1204 if (bfd_elf_add_dt_needed_tag (abfd, &link_info) < 0)
1205 einfo (_("%F%P: failed to add DT_NEEDED dynamic tag\n"));
1208 link_info.input_bfds_tail = save_input_bfd_tail;
1209 *save_input_bfd_tail = NULL;
1212 /* This is called before calling plugin 'all symbols read' hook. */
1214 void
1215 ldelf_before_plugin_all_symbols_read (int use_libpath, int native,
1216 int is_linux, int is_freebsd,
1217 int elfsize, const char *prefix)
1219 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1221 if (!link_info.lto_plugin_active
1222 || !is_elf_hash_table (&htab->root))
1223 return;
1225 htab->handling_dt_needed = true;
1226 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1227 is_freebsd, elfsize, prefix);
1228 htab->handling_dt_needed = false;
1231 /* This is called after all the input files have been opened and all
1232 symbols have been loaded. */
1234 void
1235 ldelf_after_open (int use_libpath, int native, int is_linux, int is_freebsd,
1236 int elfsize, const char *prefix)
1238 struct elf_link_hash_table *htab;
1239 asection *s;
1240 bfd *abfd;
1242 after_open_default ();
1244 htab = elf_hash_table (&link_info);
1245 if (!is_elf_hash_table (&htab->root))
1246 return;
1248 if (command_line.out_implib_filename)
1250 unlink_if_ordinary (command_line.out_implib_filename);
1251 link_info.out_implib_bfd
1252 = bfd_openw (command_line.out_implib_filename,
1253 bfd_get_target (link_info.output_bfd));
1255 if (link_info.out_implib_bfd == NULL)
1257 einfo (_("%F%P: %s: can't open for writing: %E\n"),
1258 command_line.out_implib_filename);
1262 if (ldelf_emit_note_gnu_build_id != NULL
1263 || ldelf_emit_note_fdo_package_metadata != NULL)
1265 /* Find an ELF input. */
1266 for (abfd = link_info.input_bfds;
1267 abfd != (bfd *) NULL; abfd = abfd->link.next)
1268 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
1269 && bfd_count_sections (abfd) != 0
1270 && !bfd_input_just_syms (abfd))
1271 break;
1273 /* PR 10555: If there are no ELF input files do not try to
1274 create a .note.gnu-build-id section. */
1275 if (abfd == NULL
1276 || (ldelf_emit_note_gnu_build_id != NULL
1277 && !ldelf_setup_build_id (abfd)))
1279 free ((char *) ldelf_emit_note_gnu_build_id);
1280 ldelf_emit_note_gnu_build_id = NULL;
1283 if (abfd == NULL
1284 || (ldelf_emit_note_fdo_package_metadata != NULL
1285 && !ldelf_setup_package_metadata (abfd)))
1287 free ((char *) ldelf_emit_note_fdo_package_metadata);
1288 ldelf_emit_note_fdo_package_metadata = NULL;
1292 get_elf_backend_data (link_info.output_bfd)->setup_gnu_properties (&link_info);
1294 /* Do not allow executable files to be used as inputs to the link. */
1295 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1297 /* Discard input .note.gnu.build-id sections. */
1298 s = bfd_get_section_by_name (abfd, ".note.gnu.build-id");
1299 while (s != NULL)
1301 if (s != elf_tdata (link_info.output_bfd)->o->build_id.sec)
1302 s->flags |= SEC_EXCLUDE;
1303 s = bfd_get_next_section_by_name (NULL, s);
1306 if (abfd->xvec->flavour == bfd_target_elf_flavour
1307 && !bfd_input_just_syms (abfd)
1308 && elf_tdata (abfd) != NULL
1309 /* FIXME: Maybe check for other non-supportable types as well ? */
1310 && (elf_tdata (abfd)->elf_header->e_type == ET_EXEC
1311 || (elf_tdata (abfd)->elf_header->e_type == ET_DYN
1312 && elf_tdata (abfd)->is_pie)))
1313 einfo (_("%F%P: cannot use executable file '%pB' as input to a link\n"),
1314 abfd);
1317 if (bfd_link_relocatable (&link_info))
1319 if (link_info.execstack == !link_info.noexecstack)
1321 /* PR ld/16744: If "-z [no]execstack" has been specified on the
1322 command line and we are perfoming a relocatable link then no
1323 PT_GNU_STACK segment will be created and so the
1324 linkinfo.[no]execstack values set in _handle_option() will have no
1325 effect. Instead we create a .note.GNU-stack section in much the
1326 same way as the assembler does with its --[no]execstack option. */
1327 flagword flags = SEC_READONLY | (link_info.execstack ? SEC_CODE : 0);
1328 (void) bfd_make_section_with_flags (link_info.input_bfds,
1329 ".note.GNU-stack", flags);
1331 return;
1334 if (!link_info.traditional_format)
1336 bfd *elfbfd = NULL;
1337 bool warn_eh_frame = false;
1338 int seen_type = 0;
1340 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1342 int type = 0;
1344 if (bfd_input_just_syms (abfd))
1345 continue;
1347 for (s = abfd->sections; s && type < COMPACT_EH_HDR; s = s->next)
1349 const char *name = bfd_section_name (s);
1351 if (bfd_is_abs_section (s->output_section))
1352 continue;
1353 if (startswith (name, ".eh_frame_entry"))
1354 type = COMPACT_EH_HDR;
1355 else if (strcmp (name, ".eh_frame") == 0 && s->size > 8)
1356 type = DWARF2_EH_HDR;
1359 if (type != 0)
1361 if (seen_type == 0)
1363 seen_type = type;
1365 else if (seen_type != type)
1367 einfo (_("%F%P: compact frame descriptions incompatible with"
1368 " DWARF2 .eh_frame from %pB\n"),
1369 type == DWARF2_EH_HDR ? abfd : elfbfd);
1370 break;
1373 if (!elfbfd
1374 && (type == COMPACT_EH_HDR
1375 || link_info.eh_frame_hdr_type != 0))
1377 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1378 elfbfd = abfd;
1380 warn_eh_frame = true;
1384 if (seen_type == COMPACT_EH_HDR)
1385 link_info.eh_frame_hdr_type = COMPACT_EH_HDR;
1387 if (elfbfd)
1389 const struct elf_backend_data *bed;
1391 bed = get_elf_backend_data (elfbfd);
1392 s = bfd_make_section_with_flags (elfbfd, ".eh_frame_hdr",
1393 bed->dynamic_sec_flags
1394 | SEC_READONLY);
1395 if (s != NULL
1396 && bfd_set_section_alignment (s, 2))
1398 htab->eh_info.hdr_sec = s;
1399 warn_eh_frame = false;
1402 if (warn_eh_frame)
1403 einfo (_("%P: warning: cannot create .eh_frame_hdr section,"
1404 " --eh-frame-hdr ignored\n"));
1407 if (link_info.eh_frame_hdr_type == COMPACT_EH_HDR)
1408 if (!bfd_elf_parse_eh_frame_entries (NULL, &link_info))
1409 einfo (_("%F%P: failed to parse EH frame entries\n"));
1411 ldelf_handle_dt_needed (htab, use_libpath, native, is_linux,
1412 is_freebsd, elfsize, prefix);
1415 static bfd_size_type
1416 id_note_section_size (bfd *abfd ATTRIBUTE_UNUSED)
1418 const char *style = ldelf_emit_note_gnu_build_id;
1419 bfd_size_type size;
1420 bfd_size_type build_id_size;
1422 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1423 size = (size + 3) & -(bfd_size_type) 4;
1425 build_id_size = compute_build_id_size (style);
1426 if (build_id_size)
1427 size += build_id_size;
1428 else
1429 size = 0;
1431 return size;
1434 static bool
1435 write_build_id (bfd *abfd)
1437 const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1438 struct elf_obj_tdata *t = elf_tdata (abfd);
1439 const char *style;
1440 asection *asec;
1441 Elf_Internal_Shdr *i_shdr;
1442 unsigned char *contents, *id_bits;
1443 bfd_size_type size;
1444 file_ptr position;
1445 Elf_External_Note *e_note;
1447 style = t->o->build_id.style;
1448 asec = t->o->build_id.sec;
1449 if (bfd_is_abs_section (asec->output_section))
1451 einfo (_("%P: warning: .note.gnu.build-id section discarded,"
1452 " --build-id ignored\n"));
1453 return true;
1455 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1457 if (i_shdr->contents == NULL)
1459 if (asec->contents == NULL)
1460 asec->contents = (unsigned char *) xmalloc (asec->size);
1461 contents = asec->contents;
1463 else
1464 contents = i_shdr->contents + asec->output_offset;
1466 e_note = (Elf_External_Note *) contents;
1467 size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
1468 size = (size + 3) & -(bfd_size_type) 4;
1469 id_bits = contents + size;
1470 size = asec->size - size;
1472 /* Clear the build ID field. */
1473 memset (id_bits, 0, size);
1475 bfd_h_put_32 (abfd, sizeof "GNU", &e_note->namesz);
1476 bfd_h_put_32 (abfd, size, &e_note->descsz);
1477 bfd_h_put_32 (abfd, NT_GNU_BUILD_ID, &e_note->type);
1478 memcpy (e_note->name, "GNU", sizeof "GNU");
1480 generate_build_id (abfd, style, bed->s->checksum_contents, id_bits, size);
1482 position = i_shdr->sh_offset + asec->output_offset;
1483 size = asec->size;
1484 return (bfd_seek (abfd, position, SEEK_SET) == 0
1485 && bfd_write (contents, size, abfd) == size);
1488 /* Make .note.gnu.build-id section, and set up elf_tdata->build_id. */
1490 bool
1491 ldelf_setup_build_id (bfd *ibfd)
1493 asection *s;
1494 bfd_size_type size;
1495 flagword flags;
1497 size = id_note_section_size (ibfd);
1498 if (size == 0)
1500 einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1501 return false;
1504 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1505 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1506 s = bfd_make_section_anyway_with_flags (ibfd, ".note.gnu.build-id",
1507 flags);
1508 if (s != NULL && bfd_set_section_alignment (s, 2))
1510 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1511 t->o->build_id.after_write_object_contents = &write_build_id;
1512 t->o->build_id.style = ldelf_emit_note_gnu_build_id;
1513 t->o->build_id.sec = s;
1514 elf_section_type (s) = SHT_NOTE;
1515 s->size = size;
1516 return true;
1519 einfo (_("%P: warning: cannot create .note.gnu.build-id section,"
1520 " --build-id ignored\n"));
1521 return false;
1524 static bool
1525 write_package_metadata (bfd *abfd)
1527 struct elf_obj_tdata *t = elf_tdata (abfd);
1528 const char *json;
1529 asection *asec;
1530 Elf_Internal_Shdr *i_shdr;
1531 unsigned char *contents, *json_bits;
1532 bfd_size_type size;
1533 file_ptr position;
1534 Elf_External_Note *e_note;
1536 json = t->o->package_metadata.json;
1537 asec = t->o->package_metadata.sec;
1538 if (bfd_is_abs_section (asec->output_section))
1540 einfo (_("%P: warning: .note.package section discarded,"
1541 " --package-metadata ignored\n"));
1542 return true;
1544 i_shdr = &elf_section_data (asec->output_section)->this_hdr;
1546 if (i_shdr->contents == NULL)
1548 if (asec->contents == NULL)
1549 asec->contents = (unsigned char *) xmalloc (asec->size);
1550 contents = asec->contents;
1552 else
1553 contents = i_shdr->contents + asec->output_offset;
1555 e_note = (Elf_External_Note *) contents;
1556 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1557 size = (size + 3) & -(bfd_size_type) 4;
1558 json_bits = contents + size;
1559 size = asec->size - size;
1561 /* Clear the package metadata field. */
1562 memset (json_bits, 0, size);
1564 bfd_h_put_32 (abfd, sizeof "FDO", &e_note->namesz);
1565 bfd_h_put_32 (abfd, size, &e_note->descsz);
1566 bfd_h_put_32 (abfd, FDO_PACKAGING_METADATA, &e_note->type);
1567 memcpy (e_note->name, "FDO", sizeof "FDO");
1568 memcpy (json_bits, json, strlen(json));
1570 position = i_shdr->sh_offset + asec->output_offset;
1571 size = asec->size;
1572 return (bfd_seek (abfd, position, SEEK_SET) == 0
1573 && bfd_write (contents, size, abfd) == size);
1576 /* Make .note.package section.
1577 https://systemd.io/ELF_PACKAGE_METADATA/ */
1579 bool
1580 ldelf_setup_package_metadata (bfd *ibfd)
1582 asection *s;
1583 bfd_size_type size;
1584 size_t json_length;
1585 flagword flags;
1587 /* If the option wasn't specified, silently return. */
1588 if (!ldelf_emit_note_fdo_package_metadata)
1589 return false;
1591 /* The option was specified, but it's empty, log and return. */
1592 json_length = strlen (ldelf_emit_note_fdo_package_metadata);
1593 if (json_length == 0)
1595 einfo (_("%P: warning: --package-metadata is empty, ignoring\n"));
1596 return false;
1599 #ifdef HAVE_JANSSON
1600 json_error_t json_error;
1601 json_t *json = json_loads (ldelf_emit_note_fdo_package_metadata,
1602 0, &json_error);
1603 if (!json)
1605 einfo (_("%P: warning: --package-metadata=%s does not contain valid "
1606 "JSON, ignoring: %s\n"),
1607 ldelf_emit_note_fdo_package_metadata, json_error.text);
1608 return false;
1610 else
1611 json_decref (json);
1612 #endif
1614 size = offsetof (Elf_External_Note, name[sizeof "FDO"]);
1615 size += json_length + 1;
1616 size = (size + 3) & -(bfd_size_type) 4;
1618 flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1619 | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1620 s = bfd_make_section_anyway_with_flags (ibfd, ".note.package",
1621 flags);
1622 if (s != NULL && bfd_set_section_alignment (s, 2))
1624 struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
1625 t->o->package_metadata.after_write_object_contents
1626 = &write_package_metadata;
1627 t->o->package_metadata.json = ldelf_emit_note_fdo_package_metadata;
1628 t->o->package_metadata.sec = s;
1629 elf_section_type (s) = SHT_NOTE;
1630 s->size = size;
1631 return true;
1634 einfo (_("%P: warning: cannot create .note.package section,"
1635 " --package-metadata ignored\n"));
1636 return false;
1639 /* Look through an expression for an assignment statement. */
1641 static void
1642 ldelf_find_exp_assignment (etree_type *exp)
1644 bool provide = false;
1646 switch (exp->type.node_class)
1648 case etree_provide:
1649 case etree_provided:
1650 provide = true;
1651 /* Fallthru */
1652 case etree_assign:
1653 /* We call record_link_assignment even if the symbol is defined.
1654 This is because if it is defined by a dynamic object, we
1655 actually want to use the value defined by the linker script,
1656 not the value from the dynamic object (because we are setting
1657 symbols like etext). If the symbol is defined by a regular
1658 object, then, as it happens, calling record_link_assignment
1659 will do no harm. */
1660 if (strcmp (exp->assign.dst, ".") != 0)
1662 if (!bfd_elf_record_link_assignment (link_info.output_bfd,
1663 &link_info,
1664 exp->assign.dst, provide,
1665 exp->assign.hidden))
1666 einfo (_("%F%P: failed to record assignment to %s: %E\n"),
1667 exp->assign.dst);
1669 ldelf_find_exp_assignment (exp->assign.src);
1670 break;
1672 case etree_binary:
1673 ldelf_find_exp_assignment (exp->binary.lhs);
1674 ldelf_find_exp_assignment (exp->binary.rhs);
1675 break;
1677 case etree_trinary:
1678 ldelf_find_exp_assignment (exp->trinary.cond);
1679 ldelf_find_exp_assignment (exp->trinary.lhs);
1680 ldelf_find_exp_assignment (exp->trinary.rhs);
1681 break;
1683 case etree_unary:
1684 ldelf_find_exp_assignment (exp->unary.child);
1685 break;
1687 default:
1688 break;
1692 /* This is called by the before_allocation routine via
1693 lang_for_each_statement. It locates any assignment statements, and
1694 tells the ELF backend about them, in case they are assignments to
1695 symbols which are referred to by dynamic objects. */
1697 static void
1698 ldelf_find_statement_assignment (lang_statement_union_type *s)
1700 if (s->header.type == lang_assignment_statement_enum)
1701 ldelf_find_exp_assignment (s->assignment_statement.exp);
1704 /* Used by before_allocation and handle_option. */
1706 void
1707 ldelf_append_to_separated_string (char **to, char *op_arg)
1709 if (*to == NULL)
1710 *to = xstrdup (op_arg);
1711 else
1713 size_t to_len = strlen (*to);
1714 size_t op_arg_len = strlen (op_arg);
1715 char *buf;
1716 char *cp = *to;
1718 /* First see whether OPTARG is already in the path. */
1721 if (strncmp (op_arg, cp, op_arg_len) == 0
1722 && (cp[op_arg_len] == 0
1723 || cp[op_arg_len] == config.rpath_separator))
1724 /* We found it. */
1725 break;
1727 /* Not yet found. */
1728 cp = strchr (cp, config.rpath_separator);
1729 if (cp != NULL)
1730 ++cp;
1732 while (cp != NULL);
1734 if (cp == NULL)
1736 buf = xmalloc (to_len + op_arg_len + 2);
1737 sprintf (buf, "%s%c%s", *to,
1738 config.rpath_separator, op_arg);
1739 free (*to);
1740 *to = buf;
1745 /* This is called after the sections have been attached to output
1746 sections, but before any sizes or addresses have been set. */
1748 void
1749 ldelf_before_allocation (char *audit, char *depaudit,
1750 const char *default_interpreter_name)
1752 const char *rpath;
1753 asection *sinterp;
1754 bfd *abfd;
1755 struct bfd_link_hash_entry *ehdr_start = NULL;
1756 unsigned char ehdr_start_save_type = 0;
1757 char ehdr_start_save_u[sizeof ehdr_start->u
1758 - sizeof ehdr_start->u.def.next] = "";
1760 if (is_elf_hash_table (link_info.hash))
1762 _bfd_elf_tls_setup (link_info.output_bfd, &link_info);
1764 /* Make __ehdr_start hidden if it has been referenced, to
1765 prevent the symbol from being dynamic. */
1766 if (!bfd_link_relocatable (&link_info))
1768 struct elf_link_hash_table *htab = elf_hash_table (&link_info);
1769 struct elf_link_hash_entry *h
1770 = elf_link_hash_lookup (htab, "__ehdr_start", false, false, true);
1772 /* Only adjust the export class if the symbol was referenced
1773 and not defined, otherwise leave it alone. */
1774 if (h != NULL
1775 && (h->root.type == bfd_link_hash_new
1776 || h->root.type == bfd_link_hash_undefined
1777 || h->root.type == bfd_link_hash_undefweak
1778 || h->root.type == bfd_link_hash_common))
1780 /* Don't leave the symbol undefined. Undefined hidden
1781 symbols typically won't have dynamic relocations, but
1782 we most likely will need dynamic relocations for
1783 __ehdr_start if we are building a PIE or shared
1784 library. */
1785 ehdr_start = &h->root;
1786 ehdr_start_save_type = ehdr_start->type;
1787 memcpy (ehdr_start_save_u,
1788 (char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1789 sizeof ehdr_start_save_u);
1790 ehdr_start->type = bfd_link_hash_defined;
1791 /* It will be converted to section-relative later. */
1792 ehdr_start->u.def.section = bfd_abs_section_ptr;
1793 ehdr_start->u.def.value = 0;
1797 /* If we are going to make any variable assignments, we need to
1798 let the ELF backend know about them in case the variables are
1799 referred to by dynamic objects. */
1800 lang_for_each_statement (ldelf_find_statement_assignment);
1803 /* Let the ELF backend work out the sizes of any sections required
1804 by dynamic linking. */
1805 rpath = command_line.rpath;
1806 if (rpath == NULL)
1807 rpath = (const char *) getenv ("LD_RUN_PATH");
1809 for (abfd = link_info.input_bfds; abfd; abfd = abfd->link.next)
1810 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1812 const char *audit_libs = elf_dt_audit (abfd);
1814 /* If the input bfd contains an audit entry, we need to add it as
1815 a dep audit entry. */
1816 if (audit_libs && *audit_libs != '\0')
1818 char *cp = xstrdup (audit_libs);
1821 int more = 0;
1822 char *cp2 = strchr (cp, config.rpath_separator);
1824 if (cp2)
1826 *cp2 = '\0';
1827 more = 1;
1830 if (cp != NULL && *cp != '\0')
1831 ldelf_append_to_separated_string (&depaudit, cp);
1833 cp = more ? ++cp2 : NULL;
1835 while (cp != NULL);
1839 if (! (bfd_elf_size_dynamic_sections
1840 (link_info.output_bfd, command_line.soname, rpath,
1841 command_line.filter_shlib, audit, depaudit,
1842 (const char * const *) command_line.auxiliary_filters,
1843 &link_info, &sinterp)))
1844 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1846 if (sinterp != NULL)
1848 /* Let the user override the dynamic linker we are using. */
1849 if (command_line.interpreter != NULL)
1850 default_interpreter_name = command_line.interpreter;
1851 if (default_interpreter_name != NULL)
1853 sinterp->contents = (bfd_byte *) default_interpreter_name;
1854 sinterp->size = strlen ((char *) sinterp->contents) + 1;
1858 /* Look for any sections named .gnu.warning. As a GNU extensions,
1859 we treat such sections as containing warning messages. We print
1860 out the warning message, and then zero out the section size so
1861 that it does not get copied into the output file. */
1864 LANG_FOR_EACH_INPUT_STATEMENT (is)
1866 asection *s;
1867 bfd_size_type sz;
1868 char *msg;
1870 if (is->flags.just_syms)
1871 continue;
1873 s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1874 if (s == NULL)
1875 continue;
1877 sz = s->size;
1878 msg = (char *) xmalloc ((size_t) (sz + 1));
1879 if (! bfd_get_section_contents (is->the_bfd, s, msg,
1880 (file_ptr) 0, sz))
1881 einfo (_("%F%P: %pB: can't read contents of section .gnu.warning: %E\n"),
1882 is->the_bfd);
1883 msg[sz] = '\0';
1884 (*link_info.callbacks->warning) (&link_info, msg,
1885 (const char *) NULL, is->the_bfd,
1886 (asection *) NULL, (bfd_vma) 0);
1887 free (msg);
1889 /* Clobber the section size, so that we don't waste space
1890 copying the warning into the output file. If we've already
1891 sized the output section, adjust its size. The adjustment
1892 is on rawsize because targets that size sections early will
1893 have called lang_reset_memory_regions after sizing. */
1894 if (s->output_section != NULL
1895 && s->output_section->rawsize >= s->size)
1896 s->output_section->rawsize -= s->size;
1898 s->size = 0;
1900 /* Also set SEC_EXCLUDE, so that local symbols defined in the
1901 warning section don't get copied to the output. */
1902 s->flags |= SEC_EXCLUDE | SEC_KEEP;
1906 before_allocation_default ();
1908 if (!bfd_elf_size_dynsym_hash_dynstr (link_info.output_bfd, &link_info))
1909 einfo (_("%F%P: failed to set dynamic section sizes: %E\n"));
1911 if (ehdr_start != NULL)
1913 /* If we twiddled __ehdr_start to defined earlier, put it back
1914 as it was. */
1915 ehdr_start->type = ehdr_start_save_type;
1916 memcpy ((char *) &ehdr_start->u + sizeof ehdr_start->u.def.next,
1917 ehdr_start_save_u,
1918 sizeof ehdr_start_save_u);
1921 /* Try to open a dynamic archive. This is where we know that ELF
1922 dynamic libraries have an extension of .so (or .sl on oddball systems
1923 like hpux). */
1925 bool
1926 ldelf_open_dynamic_archive (const char *arch, search_dirs_type *search,
1927 lang_input_statement_type *entry)
1929 const char *filename;
1930 char *string;
1931 size_t len;
1932 bool opened = false;
1934 if (! entry->flags.maybe_archive)
1935 return false;
1937 filename = entry->filename;
1938 len = strlen (search->name) + strlen (filename);
1939 if (entry->flags.full_name_provided)
1941 len += sizeof "/";
1942 string = (char *) xmalloc (len);
1943 sprintf (string, "%s/%s", search->name, filename);
1945 else
1947 size_t xlen = 0;
1949 len += strlen (arch) + sizeof "/lib.so";
1950 #ifdef EXTRA_SHLIB_EXTENSION
1951 xlen = (strlen (EXTRA_SHLIB_EXTENSION) > 3
1952 ? strlen (EXTRA_SHLIB_EXTENSION) - 3
1953 : 0);
1954 #endif
1955 string = (char *) xmalloc (len + xlen);
1956 sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1957 #ifdef EXTRA_SHLIB_EXTENSION
1958 /* Try the .so extension first. If that fails build a new filename
1959 using EXTRA_SHLIB_EXTENSION. */
1960 opened = ldfile_try_open_bfd (string, entry);
1961 if (!opened)
1962 strcpy (string + len - 4, EXTRA_SHLIB_EXTENSION);
1963 #endif
1966 if (!opened && !ldfile_try_open_bfd (string, entry))
1968 free (string);
1969 return false;
1972 entry->filename = string;
1974 /* We have found a dynamic object to include in the link. The ELF
1975 backend linker will create a DT_NEEDED entry in the .dynamic
1976 section naming this file. If this file includes a DT_SONAME
1977 entry, it will be used. Otherwise, the ELF linker will just use
1978 the name of the file. For an archive found by searching, like
1979 this one, the DT_NEEDED entry should consist of just the name of
1980 the file, without the path information used to find it. Note
1981 that we only need to do this if we have a dynamic object; an
1982 archive will never be referenced by a DT_NEEDED entry.
1984 FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1985 very pretty. I haven't been able to think of anything that is
1986 pretty, though. */
1987 if (bfd_check_format (entry->the_bfd, bfd_object)
1988 && (entry->the_bfd->flags & DYNAMIC) != 0)
1990 ASSERT (entry->flags.maybe_archive && entry->flags.search_dirs);
1992 /* Rather than duplicating the logic above. Just use the
1993 filename we recorded earlier. */
1995 if (!entry->flags.full_name_provided)
1996 filename = lbasename (entry->filename);
1997 bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
2000 return true;
2003 /* A variant of lang_output_section_find used by place_orphan. */
2005 static lang_output_section_statement_type *
2006 output_rel_find (int isdyn, int rela)
2008 lang_output_section_statement_type *lookup;
2009 lang_output_section_statement_type *last = NULL;
2010 lang_output_section_statement_type *last_alloc = NULL;
2011 lang_output_section_statement_type *last_ro_alloc = NULL;
2012 lang_output_section_statement_type *last_rel = NULL;
2013 lang_output_section_statement_type *last_rel_alloc = NULL;
2015 for (lookup = (void *) lang_os_list.head;
2016 lookup != NULL;
2017 lookup = lookup->next)
2019 if (lookup->constraint >= 0
2020 && startswith (lookup->name, ".rel"))
2022 int lookrela = lookup->name[4] == 'a';
2024 /* .rel.dyn must come before all other reloc sections, to suit
2025 GNU ld.so. */
2026 if (isdyn)
2027 break;
2029 /* Don't place after .rel.plt as doing so results in wrong
2030 dynamic tags. */
2031 if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
2032 break;
2034 if (rela == lookrela || last_rel == NULL)
2035 last_rel = lookup;
2036 if ((rela == lookrela || last_rel_alloc == NULL)
2037 && lookup->bfd_section != NULL
2038 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2039 last_rel_alloc = lookup;
2042 last = lookup;
2043 if (lookup->bfd_section != NULL
2044 && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
2046 last_alloc = lookup;
2047 if ((lookup->bfd_section->flags & SEC_READONLY) != 0)
2048 last_ro_alloc = lookup;
2052 if (last_rel_alloc)
2053 return last_rel_alloc;
2055 if (last_rel)
2056 return last_rel;
2058 if (last_ro_alloc)
2059 return last_ro_alloc;
2061 if (last_alloc)
2062 return last_alloc;
2064 return last;
2067 /* Return whether IN is suitable to be part of OUT. */
2069 static bool
2070 elf_orphan_compatible (asection *in, asection *out)
2072 /* Non-zero sh_info implies a section with SHF_INFO_LINK with
2073 unknown semantics for the generic linker, or a SHT_REL/SHT_RELA
2074 section where sh_info specifies a symbol table. (We won't see
2075 SHT_GROUP, SHT_SYMTAB or SHT_DYNSYM sections here.) We clearly
2076 can't merge SHT_REL/SHT_RELA using differing symbol tables, and
2077 shouldn't merge sections with differing unknown semantics. */
2078 if (elf_section_data (out)->this_hdr.sh_info
2079 != elf_section_data (in)->this_hdr.sh_info)
2080 return false;
2081 /* We can't merge with a member of an output section group or merge
2082 two sections with differing SHF_EXCLUDE or other processor and OS
2083 specific flags or with different SHF_LINK_ORDER when doing a
2084 relocatable link. */
2085 if (bfd_link_relocatable (&link_info)
2086 && (elf_next_in_group (out) != NULL
2087 || ((elf_section_flags (in) & SHF_LINK_ORDER) != 0
2088 && (elf_section_flags (out) & SHF_LINK_ORDER) != 0
2089 && (elf_linked_to_section (in)->output_section
2090 != elf_linked_to_section (out)->output_section))
2091 || ((elf_section_flags (out) ^ elf_section_flags (in))
2092 & (SHF_MASKPROC | SHF_MASKOS)) != 0))
2093 return false;
2094 return _bfd_elf_match_sections_by_type (link_info.output_bfd, out,
2095 in->owner, in);
2098 /* Place an orphan section. We use this to put random SHF_ALLOC
2099 sections in the right segment. */
2101 lang_output_section_statement_type *
2102 ldelf_place_orphan (asection *s, const char *secname, int constraint)
2104 static struct orphan_save hold[] =
2106 { ".text",
2107 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2108 0, 0, 0, 0 },
2109 { ".rodata",
2110 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2111 0, 0, 0, 0 },
2112 { ".tdata",
2113 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_THREAD_LOCAL,
2114 0, 0, 0, 0 },
2115 { ".data",
2116 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2117 0, 0, 0, 0 },
2118 { ".bss",
2119 SEC_ALLOC,
2120 0, 0, 0, 0 },
2121 { 0,
2122 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2123 0, 0, 0, 0 },
2124 { ".interp",
2125 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2126 0, 0, 0, 0 },
2127 { ".sdata",
2128 SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
2129 0, 0, 0, 0 },
2130 { ".comment",
2131 SEC_HAS_CONTENTS,
2132 0, 0, 0, 0 },
2134 enum orphan_save_index
2136 orphan_text = 0,
2137 orphan_rodata,
2138 orphan_tdata,
2139 orphan_data,
2140 orphan_bss,
2141 orphan_rel,
2142 orphan_interp,
2143 orphan_sdata,
2144 orphan_nonalloc
2146 static int orphan_init_done = 0;
2147 struct orphan_save *place;
2148 lang_output_section_statement_type *after;
2149 lang_output_section_statement_type *os;
2150 lang_output_section_statement_type *match_by_name = NULL;
2151 int isdyn = 0;
2152 int elfinput = s->owner->xvec->flavour == bfd_target_elf_flavour;
2153 int elfoutput = link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour;
2154 unsigned int sh_type = elfinput ? elf_section_type (s) : SHT_NULL;
2155 flagword flags;
2156 asection *nexts;
2158 if (!bfd_link_relocatable (&link_info)
2159 && link_info.combreloc
2160 && (s->flags & SEC_ALLOC))
2162 if (elfinput)
2163 switch (sh_type)
2165 case SHT_RELA:
2166 secname = ".rela.dyn";
2167 isdyn = 1;
2168 break;
2169 case SHT_REL:
2170 secname = ".rel.dyn";
2171 isdyn = 1;
2172 break;
2173 default:
2174 break;
2176 else if (startswith (secname, ".rel"))
2178 secname = secname[4] == 'a' ? ".rela.dyn" : ".rel.dyn";
2179 isdyn = 1;
2183 if (!bfd_link_relocatable (&link_info)
2184 && elfinput
2185 && elfoutput
2186 && (s->flags & SEC_ALLOC) != 0
2187 && (elf_tdata (s->owner)->has_gnu_osabi & elf_gnu_osabi_mbind) != 0
2188 && (elf_section_flags (s) & SHF_GNU_MBIND) != 0)
2190 /* Find the output mbind section with the same type, attributes
2191 and sh_info field. */
2192 for (os = (void *) lang_os_list.head;
2193 os != NULL;
2194 os = os->next)
2195 if (os->bfd_section != NULL
2196 && !bfd_is_abs_section (os->bfd_section)
2197 && (elf_section_flags (os->bfd_section) & SHF_GNU_MBIND) != 0
2198 && ((s->flags & (SEC_ALLOC
2199 | SEC_LOAD
2200 | SEC_HAS_CONTENTS
2201 | SEC_READONLY
2202 | SEC_CODE))
2203 == (os->bfd_section->flags & (SEC_ALLOC
2204 | SEC_LOAD
2205 | SEC_HAS_CONTENTS
2206 | SEC_READONLY
2207 | SEC_CODE)))
2208 && (elf_section_data (os->bfd_section)->this_hdr.sh_info
2209 == elf_section_data (s)->this_hdr.sh_info))
2211 lang_add_section (&os->children, s, NULL, NULL, os);
2212 return os;
2215 /* Create the output mbind section with the ".mbind." prefix
2216 in section name. */
2217 if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2218 secname = ".mbind.bss";
2219 else if ((s->flags & SEC_READONLY) == 0)
2220 secname = ".mbind.data";
2221 else if ((s->flags & SEC_CODE) == 0)
2222 secname = ".mbind.rodata";
2223 else
2224 secname = ".mbind.text";
2225 elf_tdata (link_info.output_bfd)->has_gnu_osabi |= elf_gnu_osabi_mbind;
2228 /* Look through the script to see where to place this section. The
2229 script includes entries added by previous lang_insert_orphan
2230 calls, so this loop puts multiple compatible orphans of the same
2231 name into a single output section. */
2232 if (constraint == 0)
2233 for (os = lang_output_section_find (secname);
2234 os != NULL;
2235 os = next_matching_output_section_statement (os, 0))
2237 /* If we don't match an existing output section, tell
2238 lang_insert_orphan to create a new output section. */
2239 constraint = SPECIAL;
2241 /* Check to see if we already have an output section statement
2242 with this name, and its bfd section has compatible flags.
2243 If the section already exists but does not have any flags
2244 set, then it has been created by the linker, possibly as a
2245 result of a --section-start command line switch. */
2246 if (os->bfd_section != NULL
2247 && (os->bfd_section->flags == 0
2248 || (((s->flags ^ os->bfd_section->flags)
2249 & (SEC_LOAD | SEC_ALLOC)) == 0
2250 && (!elfinput
2251 || !elfoutput
2252 || elf_orphan_compatible (s, os->bfd_section)))))
2254 lang_add_section (&os->children, s, NULL, NULL, os);
2255 return os;
2258 /* Save unused output sections in case we can match them
2259 against orphans later. */
2260 if (os->bfd_section == NULL)
2261 match_by_name = os;
2264 /* If we didn't match an active output section, see if we matched an
2265 unused one and use that. */
2266 if (match_by_name)
2268 lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2269 return match_by_name;
2272 if (!orphan_init_done)
2274 struct orphan_save *ho;
2276 for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
2277 if (ho->name != NULL)
2279 ho->os = lang_output_section_find (ho->name);
2280 if (ho->os != NULL && ho->os->flags == 0)
2281 ho->os->flags = ho->flags;
2283 orphan_init_done = 1;
2286 /* If this is a final link, then always put .gnu.warning.SYMBOL
2287 sections into the .text section to get them out of the way. */
2288 if (bfd_link_executable (&link_info)
2289 && startswith (s->name, ".gnu.warning.")
2290 && hold[orphan_text].os != NULL)
2292 os = hold[orphan_text].os;
2293 lang_add_section (&os->children, s, NULL, NULL, os);
2294 return os;
2297 flags = s->flags;
2298 if (!bfd_link_relocatable (&link_info))
2300 nexts = s;
2301 while ((nexts = bfd_get_next_section_by_name (nexts->owner, nexts))
2302 != NULL)
2303 if (nexts->output_section == NULL
2304 && (nexts->flags & SEC_EXCLUDE) == 0
2305 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2306 && (nexts->owner->flags & DYNAMIC) == 0
2307 && !bfd_input_just_syms (nexts->owner)
2308 && _bfd_elf_match_sections_by_type (nexts->owner, nexts,
2309 s->owner, s))
2310 flags = (((flags ^ SEC_READONLY)
2311 | (nexts->flags ^ SEC_READONLY))
2312 ^ SEC_READONLY);
2315 /* Decide which segment the section should go in based on the
2316 section name and section flags. We put loadable .note sections
2317 right after the .interp section, so that the PT_NOTE segment is
2318 stored right after the program headers where the OS can read it
2319 in the first page. */
2321 place = NULL;
2322 if ((flags & (SEC_ALLOC | SEC_DEBUGGING)) == 0)
2323 place = &hold[orphan_nonalloc];
2324 else if ((flags & SEC_ALLOC) == 0)
2326 else if ((flags & SEC_LOAD) != 0
2327 && (elfinput
2328 ? sh_type == SHT_NOTE
2329 : startswith (secname, ".note")))
2330 place = &hold[orphan_interp];
2331 else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS | SEC_THREAD_LOCAL)) == 0)
2332 place = &hold[orphan_bss];
2333 else if ((flags & SEC_SMALL_DATA) != 0)
2334 place = &hold[orphan_sdata];
2335 else if ((flags & SEC_THREAD_LOCAL) != 0)
2336 place = &hold[orphan_tdata];
2337 else if ((flags & SEC_READONLY) == 0)
2338 place = &hold[orphan_data];
2339 else if ((flags & SEC_LOAD) != 0
2340 && (elfinput
2341 ? sh_type == SHT_RELA || sh_type == SHT_REL
2342 : startswith (secname, ".rel")))
2343 place = &hold[orphan_rel];
2344 else if ((flags & SEC_CODE) == 0)
2345 place = &hold[orphan_rodata];
2346 else
2347 place = &hold[orphan_text];
2349 after = NULL;
2350 if (place != NULL)
2352 if (place->os == NULL)
2354 if (place->name != NULL)
2355 place->os = lang_output_section_find (place->name);
2356 else
2358 int rela = elfinput ? sh_type == SHT_RELA : secname[4] == 'a';
2359 place->os = output_rel_find (isdyn, rela);
2362 after = place->os;
2363 if (after == NULL)
2364 after
2365 = lang_output_section_find_by_flags (s, flags, &place->os,
2366 _bfd_elf_match_sections_by_type);
2367 if (after == NULL)
2368 /* *ABS* is always the first output section statement. */
2369 after = (void *) lang_os_list.head;
2372 return lang_insert_orphan (s, secname, constraint, after, place, NULL, NULL);
2375 void
2376 ldelf_before_place_orphans (void)
2378 bfd *abfd;
2380 for (abfd = link_info.input_bfds;
2381 abfd != (bfd *) NULL; abfd = abfd->link.next)
2382 if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
2383 && bfd_count_sections (abfd) != 0
2384 && !bfd_input_just_syms (abfd))
2386 asection *isec;
2387 for (isec = abfd->sections; isec != NULL; isec = isec->next)
2389 /* Discard a section if any of its linked-to section has
2390 been discarded. */
2391 asection *linked_to_sec;
2392 for (linked_to_sec = elf_linked_to_section (isec);
2393 linked_to_sec != NULL && !linked_to_sec->linker_mark;
2394 linked_to_sec = elf_linked_to_section (linked_to_sec))
2396 if (discarded_section (linked_to_sec))
2398 isec->output_section = bfd_abs_section_ptr;
2399 isec->flags |= SEC_EXCLUDE;
2400 break;
2402 linked_to_sec->linker_mark = 1;
2404 for (linked_to_sec = elf_linked_to_section (isec);
2405 linked_to_sec != NULL && linked_to_sec->linker_mark;
2406 linked_to_sec = elf_linked_to_section (linked_to_sec))
2407 linked_to_sec->linker_mark = 0;
2412 void
2413 ldelf_set_output_arch (void)
2415 set_output_arch_default ();
2416 if (link_info.output_bfd->xvec->flavour == bfd_target_elf_flavour)
2417 elf_link_info (link_info.output_bfd) = &link_info;