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