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