Home | History | Annotate | Download | only in bfd
      1 /* ELF executable support for BFD.
      2 
      3    Copyright (C) 1993-2014 Free Software Foundation, Inc.
      4 
      5    This file is part of BFD, the Binary File Descriptor library.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program; if not, write to the Free Software
     19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
     20    MA 02110-1301, USA.  */
     21 
     22 
     23 /*
     24 SECTION
     25 	ELF backends
     26 
     27 	BFD support for ELF formats is being worked on.
     28 	Currently, the best supported back ends are for sparc and i386
     29 	(running svr4 or Solaris 2).
     30 
     31 	Documentation of the internals of the support code still needs
     32 	to be written.  The code is changing quickly enough that we
     33 	haven't bothered yet.  */
     34 
     35 /* For sparc64-cross-sparc32.  */
     36 #define _SYSCALL32
     37 #include "sysdep.h"
     38 #include "bfd.h"
     39 #include "bfdlink.h"
     40 #include "libbfd.h"
     41 #define ARCH_SIZE 0
     42 #include "elf-bfd.h"
     43 #include "libiberty.h"
     44 #include "safe-ctype.h"
     45 #include "elf-linux-psinfo.h"
     46 
     47 #ifdef CORE_HEADER
     48 #include CORE_HEADER
     49 #endif
     50 
     51 static int elf_sort_sections (const void *, const void *);
     52 static bfd_boolean assign_file_positions_except_relocs (bfd *, struct bfd_link_info *);
     53 static bfd_boolean prep_headers (bfd *);
     54 static bfd_boolean swap_out_syms (bfd *, struct bfd_strtab_hash **, int) ;
     55 static bfd_boolean elf_read_notes (bfd *, file_ptr, bfd_size_type) ;
     56 static bfd_boolean elf_parse_notes (bfd *abfd, char *buf, size_t size,
     57 				    file_ptr offset);
     58 
     59 /* Swap version information in and out.  The version information is
     60    currently size independent.  If that ever changes, this code will
     61    need to move into elfcode.h.  */
     62 
     63 /* Swap in a Verdef structure.  */
     64 
     65 void
     66 _bfd_elf_swap_verdef_in (bfd *abfd,
     67 			 const Elf_External_Verdef *src,
     68 			 Elf_Internal_Verdef *dst)
     69 {
     70   dst->vd_version = H_GET_16 (abfd, src->vd_version);
     71   dst->vd_flags   = H_GET_16 (abfd, src->vd_flags);
     72   dst->vd_ndx     = H_GET_16 (abfd, src->vd_ndx);
     73   dst->vd_cnt     = H_GET_16 (abfd, src->vd_cnt);
     74   dst->vd_hash    = H_GET_32 (abfd, src->vd_hash);
     75   dst->vd_aux     = H_GET_32 (abfd, src->vd_aux);
     76   dst->vd_next    = H_GET_32 (abfd, src->vd_next);
     77 }
     78 
     79 /* Swap out a Verdef structure.  */
     80 
     81 void
     82 _bfd_elf_swap_verdef_out (bfd *abfd,
     83 			  const Elf_Internal_Verdef *src,
     84 			  Elf_External_Verdef *dst)
     85 {
     86   H_PUT_16 (abfd, src->vd_version, dst->vd_version);
     87   H_PUT_16 (abfd, src->vd_flags, dst->vd_flags);
     88   H_PUT_16 (abfd, src->vd_ndx, dst->vd_ndx);
     89   H_PUT_16 (abfd, src->vd_cnt, dst->vd_cnt);
     90   H_PUT_32 (abfd, src->vd_hash, dst->vd_hash);
     91   H_PUT_32 (abfd, src->vd_aux, dst->vd_aux);
     92   H_PUT_32 (abfd, src->vd_next, dst->vd_next);
     93 }
     94 
     95 /* Swap in a Verdaux structure.  */
     96 
     97 void
     98 _bfd_elf_swap_verdaux_in (bfd *abfd,
     99 			  const Elf_External_Verdaux *src,
    100 			  Elf_Internal_Verdaux *dst)
    101 {
    102   dst->vda_name = H_GET_32 (abfd, src->vda_name);
    103   dst->vda_next = H_GET_32 (abfd, src->vda_next);
    104 }
    105 
    106 /* Swap out a Verdaux structure.  */
    107 
    108 void
    109 _bfd_elf_swap_verdaux_out (bfd *abfd,
    110 			   const Elf_Internal_Verdaux *src,
    111 			   Elf_External_Verdaux *dst)
    112 {
    113   H_PUT_32 (abfd, src->vda_name, dst->vda_name);
    114   H_PUT_32 (abfd, src->vda_next, dst->vda_next);
    115 }
    116 
    117 /* Swap in a Verneed structure.  */
    118 
    119 void
    120 _bfd_elf_swap_verneed_in (bfd *abfd,
    121 			  const Elf_External_Verneed *src,
    122 			  Elf_Internal_Verneed *dst)
    123 {
    124   dst->vn_version = H_GET_16 (abfd, src->vn_version);
    125   dst->vn_cnt     = H_GET_16 (abfd, src->vn_cnt);
    126   dst->vn_file    = H_GET_32 (abfd, src->vn_file);
    127   dst->vn_aux     = H_GET_32 (abfd, src->vn_aux);
    128   dst->vn_next    = H_GET_32 (abfd, src->vn_next);
    129 }
    130 
    131 /* Swap out a Verneed structure.  */
    132 
    133 void
    134 _bfd_elf_swap_verneed_out (bfd *abfd,
    135 			   const Elf_Internal_Verneed *src,
    136 			   Elf_External_Verneed *dst)
    137 {
    138   H_PUT_16 (abfd, src->vn_version, dst->vn_version);
    139   H_PUT_16 (abfd, src->vn_cnt, dst->vn_cnt);
    140   H_PUT_32 (abfd, src->vn_file, dst->vn_file);
    141   H_PUT_32 (abfd, src->vn_aux, dst->vn_aux);
    142   H_PUT_32 (abfd, src->vn_next, dst->vn_next);
    143 }
    144 
    145 /* Swap in a Vernaux structure.  */
    146 
    147 void
    148 _bfd_elf_swap_vernaux_in (bfd *abfd,
    149 			  const Elf_External_Vernaux *src,
    150 			  Elf_Internal_Vernaux *dst)
    151 {
    152   dst->vna_hash  = H_GET_32 (abfd, src->vna_hash);
    153   dst->vna_flags = H_GET_16 (abfd, src->vna_flags);
    154   dst->vna_other = H_GET_16 (abfd, src->vna_other);
    155   dst->vna_name  = H_GET_32 (abfd, src->vna_name);
    156   dst->vna_next  = H_GET_32 (abfd, src->vna_next);
    157 }
    158 
    159 /* Swap out a Vernaux structure.  */
    160 
    161 void
    162 _bfd_elf_swap_vernaux_out (bfd *abfd,
    163 			   const Elf_Internal_Vernaux *src,
    164 			   Elf_External_Vernaux *dst)
    165 {
    166   H_PUT_32 (abfd, src->vna_hash, dst->vna_hash);
    167   H_PUT_16 (abfd, src->vna_flags, dst->vna_flags);
    168   H_PUT_16 (abfd, src->vna_other, dst->vna_other);
    169   H_PUT_32 (abfd, src->vna_name, dst->vna_name);
    170   H_PUT_32 (abfd, src->vna_next, dst->vna_next);
    171 }
    172 
    173 /* Swap in a Versym structure.  */
    174 
    175 void
    176 _bfd_elf_swap_versym_in (bfd *abfd,
    177 			 const Elf_External_Versym *src,
    178 			 Elf_Internal_Versym *dst)
    179 {
    180   dst->vs_vers = H_GET_16 (abfd, src->vs_vers);
    181 }
    182 
    183 /* Swap out a Versym structure.  */
    184 
    185 void
    186 _bfd_elf_swap_versym_out (bfd *abfd,
    187 			  const Elf_Internal_Versym *src,
    188 			  Elf_External_Versym *dst)
    189 {
    190   H_PUT_16 (abfd, src->vs_vers, dst->vs_vers);
    191 }
    192 
    193 /* Standard ELF hash function.  Do not change this function; you will
    194    cause invalid hash tables to be generated.  */
    195 
    196 unsigned long
    197 bfd_elf_hash (const char *namearg)
    198 {
    199   const unsigned char *name = (const unsigned char *) namearg;
    200   unsigned long h = 0;
    201   unsigned long g;
    202   int ch;
    203 
    204   while ((ch = *name++) != '\0')
    205     {
    206       h = (h << 4) + ch;
    207       if ((g = (h & 0xf0000000)) != 0)
    208 	{
    209 	  h ^= g >> 24;
    210 	  /* The ELF ABI says `h &= ~g', but this is equivalent in
    211 	     this case and on some machines one insn instead of two.  */
    212 	  h ^= g;
    213 	}
    214     }
    215   return h & 0xffffffff;
    216 }
    217 
    218 /* DT_GNU_HASH hash function.  Do not change this function; you will
    219    cause invalid hash tables to be generated.  */
    220 
    221 unsigned long
    222 bfd_elf_gnu_hash (const char *namearg)
    223 {
    224   const unsigned char *name = (const unsigned char *) namearg;
    225   unsigned long h = 5381;
    226   unsigned char ch;
    227 
    228   while ((ch = *name++) != '\0')
    229     h = (h << 5) + h + ch;
    230   return h & 0xffffffff;
    231 }
    232 
    233 /* Create a tdata field OBJECT_SIZE bytes in length, zeroed out and with
    234    the object_id field of an elf_obj_tdata field set to OBJECT_ID.  */
    235 bfd_boolean
    236 bfd_elf_allocate_object (bfd *abfd,
    237 			 size_t object_size,
    238 			 enum elf_target_id object_id)
    239 {
    240   BFD_ASSERT (object_size >= sizeof (struct elf_obj_tdata));
    241   abfd->tdata.any = bfd_zalloc (abfd, object_size);
    242   if (abfd->tdata.any == NULL)
    243     return FALSE;
    244 
    245   elf_object_id (abfd) = object_id;
    246   if (abfd->direction != read_direction)
    247     {
    248       struct output_elf_obj_tdata *o = bfd_zalloc (abfd, sizeof *o);
    249       if (o == NULL)
    250 	return FALSE;
    251       elf_tdata (abfd)->o = o;
    252       elf_program_header_size (abfd) = (bfd_size_type) -1;
    253     }
    254   return TRUE;
    255 }
    256 
    257 
    258 bfd_boolean
    259 bfd_elf_make_object (bfd *abfd)
    260 {
    261   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
    262   return bfd_elf_allocate_object (abfd, sizeof (struct elf_obj_tdata),
    263 				  bed->target_id);
    264 }
    265 
    266 bfd_boolean
    267 bfd_elf_mkcorefile (bfd *abfd)
    268 {
    269   /* I think this can be done just like an object file.  */
    270   if (!abfd->xvec->_bfd_set_format[(int) bfd_object] (abfd))
    271     return FALSE;
    272   elf_tdata (abfd)->core = bfd_zalloc (abfd, sizeof (*elf_tdata (abfd)->core));
    273   return elf_tdata (abfd)->core != NULL;
    274 }
    275 
    276 static char *
    277 bfd_elf_get_str_section (bfd *abfd, unsigned int shindex)
    278 {
    279   Elf_Internal_Shdr **i_shdrp;
    280   bfd_byte *shstrtab = NULL;
    281   file_ptr offset;
    282   bfd_size_type shstrtabsize;
    283 
    284   i_shdrp = elf_elfsections (abfd);
    285   if (i_shdrp == 0
    286       || shindex >= elf_numsections (abfd)
    287       || i_shdrp[shindex] == 0)
    288     return NULL;
    289 
    290   shstrtab = i_shdrp[shindex]->contents;
    291   if (shstrtab == NULL)
    292     {
    293       /* No cached one, attempt to read, and cache what we read.  */
    294       offset = i_shdrp[shindex]->sh_offset;
    295       shstrtabsize = i_shdrp[shindex]->sh_size;
    296 
    297       /* Allocate and clear an extra byte at the end, to prevent crashes
    298 	 in case the string table is not terminated.  */
    299       if (shstrtabsize + 1 <= 1
    300 	  || (shstrtab = (bfd_byte *) bfd_alloc (abfd, shstrtabsize + 1)) == NULL
    301 	  || bfd_seek (abfd, offset, SEEK_SET) != 0)
    302 	shstrtab = NULL;
    303       else if (bfd_bread (shstrtab, shstrtabsize, abfd) != shstrtabsize)
    304 	{
    305 	  if (bfd_get_error () != bfd_error_system_call)
    306 	    bfd_set_error (bfd_error_file_truncated);
    307 	  shstrtab = NULL;
    308 	  /* Once we've failed to read it, make sure we don't keep
    309 	     trying.  Otherwise, we'll keep allocating space for
    310 	     the string table over and over.  */
    311 	  i_shdrp[shindex]->sh_size = 0;
    312 	}
    313       else
    314 	shstrtab[shstrtabsize] = '\0';
    315       i_shdrp[shindex]->contents = shstrtab;
    316     }
    317   return (char *) shstrtab;
    318 }
    319 
    320 char *
    321 bfd_elf_string_from_elf_section (bfd *abfd,
    322 				 unsigned int shindex,
    323 				 unsigned int strindex)
    324 {
    325   Elf_Internal_Shdr *hdr;
    326 
    327   if (strindex == 0)
    328     return "";
    329 
    330   if (elf_elfsections (abfd) == NULL || shindex >= elf_numsections (abfd))
    331     return NULL;
    332 
    333   hdr = elf_elfsections (abfd)[shindex];
    334 
    335   if (hdr->contents == NULL
    336       && bfd_elf_get_str_section (abfd, shindex) == NULL)
    337     return NULL;
    338 
    339   if (strindex >= hdr->sh_size)
    340     {
    341       unsigned int shstrndx = elf_elfheader(abfd)->e_shstrndx;
    342       (*_bfd_error_handler)
    343 	(_("%B: invalid string offset %u >= %lu for section `%s'"),
    344 	 abfd, strindex, (unsigned long) hdr->sh_size,
    345 	 (shindex == shstrndx && strindex == hdr->sh_name
    346 	  ? ".shstrtab"
    347 	  : bfd_elf_string_from_elf_section (abfd, shstrndx, hdr->sh_name)));
    348       return NULL;
    349     }
    350 
    351   return ((char *) hdr->contents) + strindex;
    352 }
    353 
    354 /* Read and convert symbols to internal format.
    355    SYMCOUNT specifies the number of symbols to read, starting from
    356    symbol SYMOFFSET.  If any of INTSYM_BUF, EXTSYM_BUF or EXTSHNDX_BUF
    357    are non-NULL, they are used to store the internal symbols, external
    358    symbols, and symbol section index extensions, respectively.
    359    Returns a pointer to the internal symbol buffer (malloced if necessary)
    360    or NULL if there were no symbols or some kind of problem.  */
    361 
    362 Elf_Internal_Sym *
    363 bfd_elf_get_elf_syms (bfd *ibfd,
    364 		      Elf_Internal_Shdr *symtab_hdr,
    365 		      size_t symcount,
    366 		      size_t symoffset,
    367 		      Elf_Internal_Sym *intsym_buf,
    368 		      void *extsym_buf,
    369 		      Elf_External_Sym_Shndx *extshndx_buf)
    370 {
    371   Elf_Internal_Shdr *shndx_hdr;
    372   void *alloc_ext;
    373   const bfd_byte *esym;
    374   Elf_External_Sym_Shndx *alloc_extshndx;
    375   Elf_External_Sym_Shndx *shndx;
    376   Elf_Internal_Sym *alloc_intsym;
    377   Elf_Internal_Sym *isym;
    378   Elf_Internal_Sym *isymend;
    379   const struct elf_backend_data *bed;
    380   size_t extsym_size;
    381   bfd_size_type amt;
    382   file_ptr pos;
    383 
    384   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
    385     abort ();
    386 
    387   if (symcount == 0)
    388     return intsym_buf;
    389 
    390   /* Normal syms might have section extension entries.  */
    391   shndx_hdr = NULL;
    392   if (symtab_hdr == &elf_tdata (ibfd)->symtab_hdr)
    393     shndx_hdr = &elf_tdata (ibfd)->symtab_shndx_hdr;
    394 
    395   /* Read the symbols.  */
    396   alloc_ext = NULL;
    397   alloc_extshndx = NULL;
    398   alloc_intsym = NULL;
    399   bed = get_elf_backend_data (ibfd);
    400   extsym_size = bed->s->sizeof_sym;
    401   amt = symcount * extsym_size;
    402   pos = symtab_hdr->sh_offset + symoffset * extsym_size;
    403   if (extsym_buf == NULL)
    404     {
    405       alloc_ext = bfd_malloc2 (symcount, extsym_size);
    406       extsym_buf = alloc_ext;
    407     }
    408   if (extsym_buf == NULL
    409       || bfd_seek (ibfd, pos, SEEK_SET) != 0
    410       || bfd_bread (extsym_buf, amt, ibfd) != amt)
    411     {
    412       intsym_buf = NULL;
    413       goto out;
    414     }
    415 
    416   if (shndx_hdr == NULL || shndx_hdr->sh_size == 0)
    417     extshndx_buf = NULL;
    418   else
    419     {
    420       amt = symcount * sizeof (Elf_External_Sym_Shndx);
    421       pos = shndx_hdr->sh_offset + symoffset * sizeof (Elf_External_Sym_Shndx);
    422       if (extshndx_buf == NULL)
    423 	{
    424 	  alloc_extshndx = (Elf_External_Sym_Shndx *)
    425               bfd_malloc2 (symcount, sizeof (Elf_External_Sym_Shndx));
    426 	  extshndx_buf = alloc_extshndx;
    427 	}
    428       if (extshndx_buf == NULL
    429 	  || bfd_seek (ibfd, pos, SEEK_SET) != 0
    430 	  || bfd_bread (extshndx_buf, amt, ibfd) != amt)
    431 	{
    432 	  intsym_buf = NULL;
    433 	  goto out;
    434 	}
    435     }
    436 
    437   if (intsym_buf == NULL)
    438     {
    439       alloc_intsym = (Elf_Internal_Sym *)
    440           bfd_malloc2 (symcount, sizeof (Elf_Internal_Sym));
    441       intsym_buf = alloc_intsym;
    442       if (intsym_buf == NULL)
    443 	goto out;
    444     }
    445 
    446   /* Convert the symbols to internal form.  */
    447   isymend = intsym_buf + symcount;
    448   for (esym = (const bfd_byte *) extsym_buf, isym = intsym_buf,
    449            shndx = extshndx_buf;
    450        isym < isymend;
    451        esym += extsym_size, isym++, shndx = shndx != NULL ? shndx + 1 : NULL)
    452     if (!(*bed->s->swap_symbol_in) (ibfd, esym, shndx, isym))
    453       {
    454 	symoffset += (esym - (bfd_byte *) extsym_buf) / extsym_size;
    455 	(*_bfd_error_handler) (_("%B symbol number %lu references "
    456 				 "nonexistent SHT_SYMTAB_SHNDX section"),
    457 			       ibfd, (unsigned long) symoffset);
    458 	if (alloc_intsym != NULL)
    459 	  free (alloc_intsym);
    460 	intsym_buf = NULL;
    461 	goto out;
    462       }
    463 
    464  out:
    465   if (alloc_ext != NULL)
    466     free (alloc_ext);
    467   if (alloc_extshndx != NULL)
    468     free (alloc_extshndx);
    469 
    470   return intsym_buf;
    471 }
    472 
    473 /* Look up a symbol name.  */
    474 const char *
    475 bfd_elf_sym_name (bfd *abfd,
    476 		  Elf_Internal_Shdr *symtab_hdr,
    477 		  Elf_Internal_Sym *isym,
    478 		  asection *sym_sec)
    479 {
    480   const char *name;
    481   unsigned int iname = isym->st_name;
    482   unsigned int shindex = symtab_hdr->sh_link;
    483 
    484   if (iname == 0 && ELF_ST_TYPE (isym->st_info) == STT_SECTION
    485       /* Check for a bogus st_shndx to avoid crashing.  */
    486       && isym->st_shndx < elf_numsections (abfd))
    487     {
    488       iname = elf_elfsections (abfd)[isym->st_shndx]->sh_name;
    489       shindex = elf_elfheader (abfd)->e_shstrndx;
    490     }
    491 
    492   name = bfd_elf_string_from_elf_section (abfd, shindex, iname);
    493   if (name == NULL)
    494     name = "(null)";
    495   else if (sym_sec && *name == '\0')
    496     name = bfd_section_name (abfd, sym_sec);
    497 
    498   return name;
    499 }
    500 
    501 /* Elf_Internal_Shdr->contents is an array of these for SHT_GROUP
    502    sections.  The first element is the flags, the rest are section
    503    pointers.  */
    504 
    505 typedef union elf_internal_group {
    506   Elf_Internal_Shdr *shdr;
    507   unsigned int flags;
    508 } Elf_Internal_Group;
    509 
    510 /* Return the name of the group signature symbol.  Why isn't the
    511    signature just a string?  */
    512 
    513 static const char *
    514 group_signature (bfd *abfd, Elf_Internal_Shdr *ghdr)
    515 {
    516   Elf_Internal_Shdr *hdr;
    517   unsigned char esym[sizeof (Elf64_External_Sym)];
    518   Elf_External_Sym_Shndx eshndx;
    519   Elf_Internal_Sym isym;
    520 
    521   /* First we need to ensure the symbol table is available.  Make sure
    522      that it is a symbol table section.  */
    523   if (ghdr->sh_link >= elf_numsections (abfd))
    524     return NULL;
    525   hdr = elf_elfsections (abfd) [ghdr->sh_link];
    526   if (hdr->sh_type != SHT_SYMTAB
    527       || ! bfd_section_from_shdr (abfd, ghdr->sh_link))
    528     return NULL;
    529 
    530   /* Go read the symbol.  */
    531   hdr = &elf_tdata (abfd)->symtab_hdr;
    532   if (bfd_elf_get_elf_syms (abfd, hdr, 1, ghdr->sh_info,
    533 			    &isym, esym, &eshndx) == NULL)
    534     return NULL;
    535 
    536   return bfd_elf_sym_name (abfd, hdr, &isym, NULL);
    537 }
    538 
    539 /* Set next_in_group list pointer, and group name for NEWSECT.  */
    540 
    541 static bfd_boolean
    542 setup_group (bfd *abfd, Elf_Internal_Shdr *hdr, asection *newsect)
    543 {
    544   unsigned int num_group = elf_tdata (abfd)->num_group;
    545 
    546   /* If num_group is zero, read in all SHT_GROUP sections.  The count
    547      is set to -1 if there are no SHT_GROUP sections.  */
    548   if (num_group == 0)
    549     {
    550       unsigned int i, shnum;
    551 
    552       /* First count the number of groups.  If we have a SHT_GROUP
    553 	 section with just a flag word (ie. sh_size is 4), ignore it.  */
    554       shnum = elf_numsections (abfd);
    555       num_group = 0;
    556 
    557 #define IS_VALID_GROUP_SECTION_HEADER(shdr, minsize)	\
    558 	(   (shdr)->sh_type == SHT_GROUP		\
    559 	 && (shdr)->sh_size >= minsize			\
    560 	 && (shdr)->sh_entsize == GRP_ENTRY_SIZE	\
    561 	 && ((shdr)->sh_size % GRP_ENTRY_SIZE) == 0)
    562 
    563       for (i = 0; i < shnum; i++)
    564 	{
    565 	  Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
    566 
    567 	  if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
    568 	    num_group += 1;
    569 	}
    570 
    571       if (num_group == 0)
    572 	{
    573 	  num_group = (unsigned) -1;
    574 	  elf_tdata (abfd)->num_group = num_group;
    575 	}
    576       else
    577 	{
    578 	  /* We keep a list of elf section headers for group sections,
    579 	     so we can find them quickly.  */
    580 	  bfd_size_type amt;
    581 
    582 	  elf_tdata (abfd)->num_group = num_group;
    583 	  elf_tdata (abfd)->group_sect_ptr = (Elf_Internal_Shdr **)
    584               bfd_alloc2 (abfd, num_group, sizeof (Elf_Internal_Shdr *));
    585 	  if (elf_tdata (abfd)->group_sect_ptr == NULL)
    586 	    return FALSE;
    587 
    588 	  num_group = 0;
    589 	  for (i = 0; i < shnum; i++)
    590 	    {
    591 	      Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
    592 
    593 	      if (IS_VALID_GROUP_SECTION_HEADER (shdr, 2 * GRP_ENTRY_SIZE))
    594 		{
    595 		  unsigned char *src;
    596 		  Elf_Internal_Group *dest;
    597 
    598 		  /* Add to list of sections.  */
    599 		  elf_tdata (abfd)->group_sect_ptr[num_group] = shdr;
    600 		  num_group += 1;
    601 
    602 		  /* Read the raw contents.  */
    603 		  BFD_ASSERT (sizeof (*dest) >= 4);
    604 		  amt = shdr->sh_size * sizeof (*dest) / 4;
    605 		  shdr->contents = (unsigned char *)
    606                       bfd_alloc2 (abfd, shdr->sh_size, sizeof (*dest) / 4);
    607 		  /* PR binutils/4110: Handle corrupt group headers.  */
    608 		  if (shdr->contents == NULL)
    609 		    {
    610 		      _bfd_error_handler
    611 			(_("%B: corrupt size field in group section header: 0x%lx"), abfd, shdr->sh_size);
    612 		      bfd_set_error (bfd_error_bad_value);
    613 		      -- num_group;
    614 		      continue;
    615 		    }
    616 
    617 		  memset (shdr->contents, 0, amt);
    618 
    619 		  if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0
    620 		      || (bfd_bread (shdr->contents, shdr->sh_size, abfd)
    621 			  != shdr->sh_size))
    622 		    {
    623 		      _bfd_error_handler
    624 			(_("%B: invalid size field in group section header: 0x%lx"), abfd, shdr->sh_size);
    625 		      bfd_set_error (bfd_error_bad_value);
    626 		      -- num_group;
    627 		      /* PR 17510: If the group contents are even partially
    628 			 corrupt, do not allow any of the contents to be used.  */
    629 		      memset (shdr->contents, 0, amt);
    630 		      continue;
    631 		    }
    632 
    633 		  /* Translate raw contents, a flag word followed by an
    634 		     array of elf section indices all in target byte order,
    635 		     to the flag word followed by an array of elf section
    636 		     pointers.  */
    637 		  src = shdr->contents + shdr->sh_size;
    638 		  dest = (Elf_Internal_Group *) (shdr->contents + amt);
    639 		  while (1)
    640 		    {
    641 		      unsigned int idx;
    642 
    643 		      src -= 4;
    644 		      --dest;
    645 		      idx = H_GET_32 (abfd, src);
    646 		      if (src == shdr->contents)
    647 			{
    648 			  dest->flags = idx;
    649 			  if (shdr->bfd_section != NULL && (idx & GRP_COMDAT))
    650 			    shdr->bfd_section->flags
    651 			      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
    652 			  break;
    653 			}
    654 		      if (idx >= shnum)
    655 			{
    656 			  ((*_bfd_error_handler)
    657 			   (_("%B: invalid SHT_GROUP entry"), abfd));
    658 			  idx = 0;
    659 			}
    660 		      dest->shdr = elf_elfsections (abfd)[idx];
    661 		    }
    662 		}
    663 	    }
    664 
    665 	  /* PR 17510: Corrupt binaries might contain invalid groups.  */
    666 	  if (num_group != (unsigned) elf_tdata (abfd)->num_group)
    667 	    {
    668 	      elf_tdata (abfd)->num_group = num_group;
    669 
    670 	      /* If all groups are invalid then fail.  */
    671 	      if (num_group == 0)
    672 		{
    673 		  elf_tdata (abfd)->group_sect_ptr = NULL;
    674 		  elf_tdata (abfd)->num_group = num_group = -1;
    675 		  (*_bfd_error_handler) (_("%B: no valid group sections found"), abfd);
    676 		  bfd_set_error (bfd_error_bad_value);
    677 		}
    678 	    }
    679 	}
    680     }
    681 
    682   if (num_group != (unsigned) -1)
    683     {
    684       unsigned int i;
    685 
    686       for (i = 0; i < num_group; i++)
    687 	{
    688 	  Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
    689 	  Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
    690 	  unsigned int n_elt = shdr->sh_size / 4;
    691 
    692 	  /* Look through this group's sections to see if current
    693 	     section is a member.  */
    694 	  while (--n_elt != 0)
    695 	    if ((++idx)->shdr == hdr)
    696 	      {
    697 		asection *s = NULL;
    698 
    699 		/* We are a member of this group.  Go looking through
    700 		   other members to see if any others are linked via
    701 		   next_in_group.  */
    702 		idx = (Elf_Internal_Group *) shdr->contents;
    703 		n_elt = shdr->sh_size / 4;
    704 		while (--n_elt != 0)
    705 		  if ((s = (++idx)->shdr->bfd_section) != NULL
    706 		      && elf_next_in_group (s) != NULL)
    707 		    break;
    708 		if (n_elt != 0)
    709 		  {
    710 		    /* Snarf the group name from other member, and
    711 		       insert current section in circular list.  */
    712 		    elf_group_name (newsect) = elf_group_name (s);
    713 		    elf_next_in_group (newsect) = elf_next_in_group (s);
    714 		    elf_next_in_group (s) = newsect;
    715 		  }
    716 		else
    717 		  {
    718 		    const char *gname;
    719 
    720 		    gname = group_signature (abfd, shdr);
    721 		    if (gname == NULL)
    722 		      return FALSE;
    723 		    elf_group_name (newsect) = gname;
    724 
    725 		    /* Start a circular list with one element.  */
    726 		    elf_next_in_group (newsect) = newsect;
    727 		  }
    728 
    729 		/* If the group section has been created, point to the
    730 		   new member.  */
    731 		if (shdr->bfd_section != NULL)
    732 		  elf_next_in_group (shdr->bfd_section) = newsect;
    733 
    734 		i = num_group - 1;
    735 		break;
    736 	      }
    737 	}
    738     }
    739 
    740   if (elf_group_name (newsect) == NULL)
    741     {
    742       (*_bfd_error_handler) (_("%B: no group info for section %A"),
    743 			     abfd, newsect);
    744       return FALSE;
    745     }
    746   return TRUE;
    747 }
    748 
    749 bfd_boolean
    750 _bfd_elf_setup_sections (bfd *abfd)
    751 {
    752   unsigned int i;
    753   unsigned int num_group = elf_tdata (abfd)->num_group;
    754   bfd_boolean result = TRUE;
    755   asection *s;
    756 
    757   /* Process SHF_LINK_ORDER.  */
    758   for (s = abfd->sections; s != NULL; s = s->next)
    759     {
    760       Elf_Internal_Shdr *this_hdr = &elf_section_data (s)->this_hdr;
    761       if ((this_hdr->sh_flags & SHF_LINK_ORDER) != 0)
    762 	{
    763 	  unsigned int elfsec = this_hdr->sh_link;
    764 	  /* FIXME: The old Intel compiler and old strip/objcopy may
    765 	     not set the sh_link or sh_info fields.  Hence we could
    766 	     get the situation where elfsec is 0.  */
    767 	  if (elfsec == 0)
    768 	    {
    769 	      const struct elf_backend_data *bed = get_elf_backend_data (abfd);
    770 	      if (bed->link_order_error_handler)
    771 		bed->link_order_error_handler
    772 		  (_("%B: warning: sh_link not set for section `%A'"),
    773 		   abfd, s);
    774 	    }
    775 	  else
    776 	    {
    777 	      asection *linksec = NULL;
    778 
    779 	      if (elfsec < elf_numsections (abfd))
    780 		{
    781 		  this_hdr = elf_elfsections (abfd)[elfsec];
    782 		  linksec = this_hdr->bfd_section;
    783 		}
    784 
    785 	      /* PR 1991, 2008:
    786 		 Some strip/objcopy may leave an incorrect value in
    787 		 sh_link.  We don't want to proceed.  */
    788 	      if (linksec == NULL)
    789 		{
    790 		  (*_bfd_error_handler)
    791 		    (_("%B: sh_link [%d] in section `%A' is incorrect"),
    792 		     s->owner, s, elfsec);
    793 		  result = FALSE;
    794 		}
    795 
    796 	      elf_linked_to_section (s) = linksec;
    797 	    }
    798 	}
    799     }
    800 
    801   /* Process section groups.  */
    802   if (num_group == (unsigned) -1)
    803     return result;
    804 
    805   for (i = 0; i < num_group; i++)
    806     {
    807       Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
    808       Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
    809       unsigned int n_elt = shdr->sh_size / 4;
    810 
    811       while (--n_elt != 0)
    812 	if ((++idx)->shdr->bfd_section)
    813 	  elf_sec_group (idx->shdr->bfd_section) = shdr->bfd_section;
    814 	else if (idx->shdr->sh_type == SHT_RELA
    815 		 || idx->shdr->sh_type == SHT_REL)
    816 	  /* We won't include relocation sections in section groups in
    817 	     output object files. We adjust the group section size here
    818 	     so that relocatable link will work correctly when
    819 	     relocation sections are in section group in input object
    820 	     files.  */
    821 	  shdr->bfd_section->size -= 4;
    822 	else
    823 	  {
    824 	    /* There are some unknown sections in the group.  */
    825 	    (*_bfd_error_handler)
    826 	      (_("%B: unknown [%d] section `%s' in group [%s]"),
    827 	       abfd,
    828 	       (unsigned int) idx->shdr->sh_type,
    829 	       bfd_elf_string_from_elf_section (abfd,
    830 						(elf_elfheader (abfd)
    831 						 ->e_shstrndx),
    832 						idx->shdr->sh_name),
    833 	       shdr->bfd_section->name);
    834 	    result = FALSE;
    835 	  }
    836     }
    837   return result;
    838 }
    839 
    840 bfd_boolean
    841 bfd_elf_is_group_section (bfd *abfd ATTRIBUTE_UNUSED, const asection *sec)
    842 {
    843   return elf_next_in_group (sec) != NULL;
    844 }
    845 
    846 /* Make a BFD section from an ELF section.  We store a pointer to the
    847    BFD section in the bfd_section field of the header.  */
    848 
    849 bfd_boolean
    850 _bfd_elf_make_section_from_shdr (bfd *abfd,
    851 				 Elf_Internal_Shdr *hdr,
    852 				 const char *name,
    853 				 int shindex)
    854 {
    855   asection *newsect;
    856   flagword flags;
    857   const struct elf_backend_data *bed;
    858 
    859   if (hdr->bfd_section != NULL)
    860     return TRUE;
    861 
    862   newsect = bfd_make_section_anyway (abfd, name);
    863   if (newsect == NULL)
    864     return FALSE;
    865 
    866   hdr->bfd_section = newsect;
    867   elf_section_data (newsect)->this_hdr = *hdr;
    868   elf_section_data (newsect)->this_idx = shindex;
    869 
    870   /* Always use the real type/flags.  */
    871   elf_section_type (newsect) = hdr->sh_type;
    872   elf_section_flags (newsect) = hdr->sh_flags;
    873 
    874   newsect->filepos = hdr->sh_offset;
    875 
    876   if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
    877       || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
    878       || ! bfd_set_section_alignment (abfd, newsect,
    879 				      bfd_log2 (hdr->sh_addralign)))
    880     return FALSE;
    881 
    882   flags = SEC_NO_FLAGS;
    883   if (hdr->sh_type != SHT_NOBITS)
    884     flags |= SEC_HAS_CONTENTS;
    885   if (hdr->sh_type == SHT_GROUP)
    886     flags |= SEC_GROUP | SEC_EXCLUDE;
    887   if ((hdr->sh_flags & SHF_ALLOC) != 0)
    888     {
    889       flags |= SEC_ALLOC;
    890       if (hdr->sh_type != SHT_NOBITS)
    891 	flags |= SEC_LOAD;
    892     }
    893   if ((hdr->sh_flags & SHF_WRITE) == 0)
    894     flags |= SEC_READONLY;
    895   if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
    896     flags |= SEC_CODE;
    897   else if ((flags & SEC_LOAD) != 0)
    898     flags |= SEC_DATA;
    899   if ((hdr->sh_flags & SHF_MERGE) != 0)
    900     {
    901       flags |= SEC_MERGE;
    902       newsect->entsize = hdr->sh_entsize;
    903       if ((hdr->sh_flags & SHF_STRINGS) != 0)
    904 	flags |= SEC_STRINGS;
    905     }
    906   if (hdr->sh_flags & SHF_GROUP)
    907     if (!setup_group (abfd, hdr, newsect))
    908       return FALSE;
    909   if ((hdr->sh_flags & SHF_TLS) != 0)
    910     flags |= SEC_THREAD_LOCAL;
    911   if ((hdr->sh_flags & SHF_EXCLUDE) != 0)
    912     flags |= SEC_EXCLUDE;
    913 
    914   if ((flags & SEC_ALLOC) == 0)
    915     {
    916       /* The debugging sections appear to be recognized only by name,
    917 	 not any sort of flag.  Their SEC_ALLOC bits are cleared.  */
    918       if (name [0] == '.')
    919 	{
    920 	  const char *p;
    921 	  int n;
    922 	  if (name[1] == 'd')
    923 	    p = ".debug", n = 6;
    924 	  else if (name[1] == 'g' && name[2] == 'n')
    925 	    p = ".gnu.linkonce.wi.", n = 17;
    926 	  else if (name[1] == 'g' && name[2] == 'd')
    927 	    p = ".gdb_index", n = 11; /* yes we really do mean 11.  */
    928 	  else if (name[1] == 'l')
    929 	    p = ".line", n = 5;
    930 	  else if (name[1] == 's')
    931 	    p = ".stab", n = 5;
    932 	  else if (name[1] == 'z')
    933 	    p = ".zdebug", n = 7;
    934 	  else
    935 	    p = NULL, n = 0;
    936 	  if (p != NULL && strncmp (name, p, n) == 0)
    937 	    flags |= SEC_DEBUGGING;
    938 	}
    939     }
    940 
    941   /* As a GNU extension, if the name begins with .gnu.linkonce, we
    942      only link a single copy of the section.  This is used to support
    943      g++.  g++ will emit each template expansion in its own section.
    944      The symbols will be defined as weak, so that multiple definitions
    945      are permitted.  The GNU linker extension is to actually discard
    946      all but one of the sections.  */
    947   if (CONST_STRNEQ (name, ".gnu.linkonce")
    948       && elf_next_in_group (newsect) == NULL)
    949     flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
    950 
    951   bed = get_elf_backend_data (abfd);
    952   if (bed->elf_backend_section_flags)
    953     if (! bed->elf_backend_section_flags (&flags, hdr))
    954       return FALSE;
    955 
    956   if (! bfd_set_section_flags (abfd, newsect, flags))
    957     return FALSE;
    958 
    959   /* We do not parse the PT_NOTE segments as we are interested even in the
    960      separate debug info files which may have the segments offsets corrupted.
    961      PT_NOTEs from the core files are currently not parsed using BFD.  */
    962   if (hdr->sh_type == SHT_NOTE)
    963     {
    964       bfd_byte *contents;
    965 
    966       if (!bfd_malloc_and_get_section (abfd, newsect, &contents))
    967 	return FALSE;
    968 
    969       elf_parse_notes (abfd, (char *) contents, hdr->sh_size, -1);
    970       free (contents);
    971     }
    972 
    973   if ((flags & SEC_ALLOC) != 0)
    974     {
    975       Elf_Internal_Phdr *phdr;
    976       unsigned int i, nload;
    977 
    978       /* Some ELF linkers produce binaries with all the program header
    979 	 p_paddr fields zero.  If we have such a binary with more than
    980 	 one PT_LOAD header, then leave the section lma equal to vma
    981 	 so that we don't create sections with overlapping lma.  */
    982       phdr = elf_tdata (abfd)->phdr;
    983       for (nload = 0, i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
    984 	if (phdr->p_paddr != 0)
    985 	  break;
    986 	else if (phdr->p_type == PT_LOAD && phdr->p_memsz != 0)
    987 	  ++nload;
    988       if (i >= elf_elfheader (abfd)->e_phnum && nload > 1)
    989 	return TRUE;
    990 
    991       phdr = elf_tdata (abfd)->phdr;
    992       for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
    993 	{
    994 	  if (((phdr->p_type == PT_LOAD
    995 		&& (hdr->sh_flags & SHF_TLS) == 0)
    996 	       || phdr->p_type == PT_TLS)
    997 	      && ELF_SECTION_IN_SEGMENT (hdr, phdr))
    998 	    {
    999 	      if ((flags & SEC_LOAD) == 0)
   1000 		newsect->lma = (phdr->p_paddr
   1001 				+ hdr->sh_addr - phdr->p_vaddr);
   1002 	      else
   1003 		/* We used to use the same adjustment for SEC_LOAD
   1004 		   sections, but that doesn't work if the segment
   1005 		   is packed with code from multiple VMAs.
   1006 		   Instead we calculate the section LMA based on
   1007 		   the segment LMA.  It is assumed that the
   1008 		   segment will contain sections with contiguous
   1009 		   LMAs, even if the VMAs are not.  */
   1010 		newsect->lma = (phdr->p_paddr
   1011 				+ hdr->sh_offset - phdr->p_offset);
   1012 
   1013 	      /* With contiguous segments, we can't tell from file
   1014 		 offsets whether a section with zero size should
   1015 		 be placed at the end of one segment or the
   1016 		 beginning of the next.  Decide based on vaddr.  */
   1017 	      if (hdr->sh_addr >= phdr->p_vaddr
   1018 		  && (hdr->sh_addr + hdr->sh_size
   1019 		      <= phdr->p_vaddr + phdr->p_memsz))
   1020 		break;
   1021 	    }
   1022 	}
   1023     }
   1024 
   1025   /* Compress/decompress DWARF debug sections with names: .debug_* and
   1026      .zdebug_*, after the section flags is set.  */
   1027   if ((flags & SEC_DEBUGGING)
   1028       && ((name[1] == 'd' && name[6] == '_')
   1029 	  || (name[1] == 'z' && name[7] == '_')))
   1030     {
   1031       enum { nothing, compress, decompress } action = nothing;
   1032       char *new_name;
   1033 
   1034       if (bfd_is_section_compressed (abfd, newsect))
   1035 	{
   1036 	  /* Compressed section.  Check if we should decompress.  */
   1037 	  if ((abfd->flags & BFD_DECOMPRESS))
   1038 	    action = decompress;
   1039 	}
   1040       else
   1041 	{
   1042 	  /* Normal section.  Check if we should compress.  */
   1043 	  if ((abfd->flags & BFD_COMPRESS) && newsect->size != 0)
   1044 	    action = compress;
   1045 	}
   1046 
   1047       new_name = NULL;
   1048       switch (action)
   1049 	{
   1050 	case nothing:
   1051 	  break;
   1052 	case compress:
   1053 	  if (!bfd_init_section_compress_status (abfd, newsect))
   1054 	    {
   1055 	      (*_bfd_error_handler)
   1056 		(_("%B: unable to initialize compress status for section %s"),
   1057 		 abfd, name);
   1058 	      return FALSE;
   1059 	    }
   1060 	  if (name[1] != 'z')
   1061 	    {
   1062 	      unsigned int len = strlen (name);
   1063 
   1064 	      new_name = bfd_alloc (abfd, len + 2);
   1065 	      if (new_name == NULL)
   1066 		return FALSE;
   1067 	      new_name[0] = '.';
   1068 	      new_name[1] = 'z';
   1069 	      memcpy (new_name + 2, name + 1, len);
   1070 	    }
   1071 	  break;
   1072 	case decompress:
   1073 	  if (!bfd_init_section_decompress_status (abfd, newsect))
   1074 	    {
   1075 	      (*_bfd_error_handler)
   1076 		(_("%B: unable to initialize decompress status for section %s"),
   1077 		 abfd, name);
   1078 	      return FALSE;
   1079 	    }
   1080 	  if (name[1] == 'z')
   1081 	    {
   1082 	      unsigned int len = strlen (name);
   1083 
   1084 	      new_name = bfd_alloc (abfd, len);
   1085 	      if (new_name == NULL)
   1086 		return FALSE;
   1087 	      new_name[0] = '.';
   1088 	      memcpy (new_name + 1, name + 2, len - 1);
   1089 	    }
   1090 	  break;
   1091 	}
   1092       if (new_name != NULL)
   1093 	bfd_rename_section (abfd, newsect, new_name);
   1094     }
   1095 
   1096   return TRUE;
   1097 }
   1098 
   1099 const char *const bfd_elf_section_type_names[] = {
   1100   "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
   1101   "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
   1102   "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
   1103 };
   1104 
   1105 /* ELF relocs are against symbols.  If we are producing relocatable
   1106    output, and the reloc is against an external symbol, and nothing
   1107    has given us any additional addend, the resulting reloc will also
   1108    be against the same symbol.  In such a case, we don't want to
   1109    change anything about the way the reloc is handled, since it will
   1110    all be done at final link time.  Rather than put special case code
   1111    into bfd_perform_relocation, all the reloc types use this howto
   1112    function.  It just short circuits the reloc if producing
   1113    relocatable output against an external symbol.  */
   1114 
   1115 bfd_reloc_status_type
   1116 bfd_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED,
   1117 		       arelent *reloc_entry,
   1118 		       asymbol *symbol,
   1119 		       void *data ATTRIBUTE_UNUSED,
   1120 		       asection *input_section,
   1121 		       bfd *output_bfd,
   1122 		       char **error_message ATTRIBUTE_UNUSED)
   1123 {
   1124   if (output_bfd != NULL
   1125       && (symbol->flags & BSF_SECTION_SYM) == 0
   1126       && (! reloc_entry->howto->partial_inplace
   1127 	  || reloc_entry->addend == 0))
   1128     {
   1129       reloc_entry->address += input_section->output_offset;
   1130       return bfd_reloc_ok;
   1131     }
   1132 
   1133   return bfd_reloc_continue;
   1134 }
   1135 
   1136 /* Copy the program header and other data from one object module to
   1138    another.  */
   1139 
   1140 bfd_boolean
   1141 _bfd_elf_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
   1142 {
   1143   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
   1144       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
   1145     return TRUE;
   1146 
   1147   if (!elf_flags_init (obfd))
   1148     {
   1149       elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
   1150       elf_flags_init (obfd) = TRUE;
   1151     }
   1152 
   1153   elf_gp (obfd) = elf_gp (ibfd);
   1154 
   1155   /* Also copy the EI_OSABI field.  */
   1156   elf_elfheader (obfd)->e_ident[EI_OSABI] =
   1157     elf_elfheader (ibfd)->e_ident[EI_OSABI];
   1158 
   1159   /* Copy object attributes.  */
   1160   _bfd_elf_copy_obj_attributes (ibfd, obfd);
   1161   return TRUE;
   1162 }
   1163 
   1164 static const char *
   1165 get_segment_type (unsigned int p_type)
   1166 {
   1167   const char *pt;
   1168   switch (p_type)
   1169     {
   1170     case PT_NULL: pt = "NULL"; break;
   1171     case PT_LOAD: pt = "LOAD"; break;
   1172     case PT_DYNAMIC: pt = "DYNAMIC"; break;
   1173     case PT_INTERP: pt = "INTERP"; break;
   1174     case PT_NOTE: pt = "NOTE"; break;
   1175     case PT_SHLIB: pt = "SHLIB"; break;
   1176     case PT_PHDR: pt = "PHDR"; break;
   1177     case PT_TLS: pt = "TLS"; break;
   1178     case PT_GNU_EH_FRAME: pt = "EH_FRAME"; break;
   1179     case PT_GNU_STACK: pt = "STACK"; break;
   1180     case PT_GNU_RELRO: pt = "RELRO"; break;
   1181     default: pt = NULL; break;
   1182     }
   1183   return pt;
   1184 }
   1185 
   1186 /* Print out the program headers.  */
   1187 
   1188 bfd_boolean
   1189 _bfd_elf_print_private_bfd_data (bfd *abfd, void *farg)
   1190 {
   1191   FILE *f = (FILE *) farg;
   1192   Elf_Internal_Phdr *p;
   1193   asection *s;
   1194   bfd_byte *dynbuf = NULL;
   1195 
   1196   p = elf_tdata (abfd)->phdr;
   1197   if (p != NULL)
   1198     {
   1199       unsigned int i, c;
   1200 
   1201       fprintf (f, _("\nProgram Header:\n"));
   1202       c = elf_elfheader (abfd)->e_phnum;
   1203       for (i = 0; i < c; i++, p++)
   1204 	{
   1205 	  const char *pt = get_segment_type (p->p_type);
   1206 	  char buf[20];
   1207 
   1208 	  if (pt == NULL)
   1209 	    {
   1210 	      sprintf (buf, "0x%lx", p->p_type);
   1211 	      pt = buf;
   1212 	    }
   1213 	  fprintf (f, "%8s off    0x", pt);
   1214 	  bfd_fprintf_vma (abfd, f, p->p_offset);
   1215 	  fprintf (f, " vaddr 0x");
   1216 	  bfd_fprintf_vma (abfd, f, p->p_vaddr);
   1217 	  fprintf (f, " paddr 0x");
   1218 	  bfd_fprintf_vma (abfd, f, p->p_paddr);
   1219 	  fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
   1220 	  fprintf (f, "         filesz 0x");
   1221 	  bfd_fprintf_vma (abfd, f, p->p_filesz);
   1222 	  fprintf (f, " memsz 0x");
   1223 	  bfd_fprintf_vma (abfd, f, p->p_memsz);
   1224 	  fprintf (f, " flags %c%c%c",
   1225 		   (p->p_flags & PF_R) != 0 ? 'r' : '-',
   1226 		   (p->p_flags & PF_W) != 0 ? 'w' : '-',
   1227 		   (p->p_flags & PF_X) != 0 ? 'x' : '-');
   1228 	  if ((p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X)) != 0)
   1229 	    fprintf (f, " %lx", p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X));
   1230 	  fprintf (f, "\n");
   1231 	}
   1232     }
   1233 
   1234   s = bfd_get_section_by_name (abfd, ".dynamic");
   1235   if (s != NULL)
   1236     {
   1237       unsigned int elfsec;
   1238       unsigned long shlink;
   1239       bfd_byte *extdyn, *extdynend;
   1240       size_t extdynsize;
   1241       void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
   1242 
   1243       fprintf (f, _("\nDynamic Section:\n"));
   1244 
   1245       if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
   1246 	goto error_return;
   1247 
   1248       elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
   1249       if (elfsec == SHN_BAD)
   1250 	goto error_return;
   1251       shlink = elf_elfsections (abfd)[elfsec]->sh_link;
   1252 
   1253       extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
   1254       swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
   1255 
   1256       extdyn = dynbuf;
   1257       extdynend = extdyn + s->size;
   1258       for (; extdyn < extdynend; extdyn += extdynsize)
   1259 	{
   1260 	  Elf_Internal_Dyn dyn;
   1261 	  const char *name = "";
   1262 	  char ab[20];
   1263 	  bfd_boolean stringp;
   1264 	  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   1265 
   1266 	  (*swap_dyn_in) (abfd, extdyn, &dyn);
   1267 
   1268 	  if (dyn.d_tag == DT_NULL)
   1269 	    break;
   1270 
   1271 	  stringp = FALSE;
   1272 	  switch (dyn.d_tag)
   1273 	    {
   1274 	    default:
   1275 	      if (bed->elf_backend_get_target_dtag)
   1276 		name = (*bed->elf_backend_get_target_dtag) (dyn.d_tag);
   1277 
   1278 	      if (!strcmp (name, ""))
   1279 		{
   1280 		  sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
   1281 		  name = ab;
   1282 		}
   1283 	      break;
   1284 
   1285 	    case DT_NEEDED: name = "NEEDED"; stringp = TRUE; break;
   1286 	    case DT_PLTRELSZ: name = "PLTRELSZ"; break;
   1287 	    case DT_PLTGOT: name = "PLTGOT"; break;
   1288 	    case DT_HASH: name = "HASH"; break;
   1289 	    case DT_STRTAB: name = "STRTAB"; break;
   1290 	    case DT_SYMTAB: name = "SYMTAB"; break;
   1291 	    case DT_RELA: name = "RELA"; break;
   1292 	    case DT_RELASZ: name = "RELASZ"; break;
   1293 	    case DT_RELAENT: name = "RELAENT"; break;
   1294 	    case DT_STRSZ: name = "STRSZ"; break;
   1295 	    case DT_SYMENT: name = "SYMENT"; break;
   1296 	    case DT_INIT: name = "INIT"; break;
   1297 	    case DT_FINI: name = "FINI"; break;
   1298 	    case DT_SONAME: name = "SONAME"; stringp = TRUE; break;
   1299 	    case DT_RPATH: name = "RPATH"; stringp = TRUE; break;
   1300 	    case DT_SYMBOLIC: name = "SYMBOLIC"; break;
   1301 	    case DT_REL: name = "REL"; break;
   1302 	    case DT_RELSZ: name = "RELSZ"; break;
   1303 	    case DT_RELENT: name = "RELENT"; break;
   1304 	    case DT_PLTREL: name = "PLTREL"; break;
   1305 	    case DT_DEBUG: name = "DEBUG"; break;
   1306 	    case DT_TEXTREL: name = "TEXTREL"; break;
   1307 	    case DT_JMPREL: name = "JMPREL"; break;
   1308 	    case DT_BIND_NOW: name = "BIND_NOW"; break;
   1309 	    case DT_INIT_ARRAY: name = "INIT_ARRAY"; break;
   1310 	    case DT_FINI_ARRAY: name = "FINI_ARRAY"; break;
   1311 	    case DT_INIT_ARRAYSZ: name = "INIT_ARRAYSZ"; break;
   1312 	    case DT_FINI_ARRAYSZ: name = "FINI_ARRAYSZ"; break;
   1313 	    case DT_RUNPATH: name = "RUNPATH"; stringp = TRUE; break;
   1314 	    case DT_FLAGS: name = "FLAGS"; break;
   1315 	    case DT_PREINIT_ARRAY: name = "PREINIT_ARRAY"; break;
   1316 	    case DT_PREINIT_ARRAYSZ: name = "PREINIT_ARRAYSZ"; break;
   1317 	    case DT_CHECKSUM: name = "CHECKSUM"; break;
   1318 	    case DT_PLTPADSZ: name = "PLTPADSZ"; break;
   1319 	    case DT_MOVEENT: name = "MOVEENT"; break;
   1320 	    case DT_MOVESZ: name = "MOVESZ"; break;
   1321 	    case DT_FEATURE: name = "FEATURE"; break;
   1322 	    case DT_POSFLAG_1: name = "POSFLAG_1"; break;
   1323 	    case DT_SYMINSZ: name = "SYMINSZ"; break;
   1324 	    case DT_SYMINENT: name = "SYMINENT"; break;
   1325 	    case DT_CONFIG: name = "CONFIG"; stringp = TRUE; break;
   1326 	    case DT_DEPAUDIT: name = "DEPAUDIT"; stringp = TRUE; break;
   1327 	    case DT_AUDIT: name = "AUDIT"; stringp = TRUE; break;
   1328 	    case DT_PLTPAD: name = "PLTPAD"; break;
   1329 	    case DT_MOVETAB: name = "MOVETAB"; break;
   1330 	    case DT_SYMINFO: name = "SYMINFO"; break;
   1331 	    case DT_RELACOUNT: name = "RELACOUNT"; break;
   1332 	    case DT_RELCOUNT: name = "RELCOUNT"; break;
   1333 	    case DT_FLAGS_1: name = "FLAGS_1"; break;
   1334 	    case DT_VERSYM: name = "VERSYM"; break;
   1335 	    case DT_VERDEF: name = "VERDEF"; break;
   1336 	    case DT_VERDEFNUM: name = "VERDEFNUM"; break;
   1337 	    case DT_VERNEED: name = "VERNEED"; break;
   1338 	    case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
   1339 	    case DT_AUXILIARY: name = "AUXILIARY"; stringp = TRUE; break;
   1340 	    case DT_USED: name = "USED"; break;
   1341 	    case DT_FILTER: name = "FILTER"; stringp = TRUE; break;
   1342 	    case DT_GNU_HASH: name = "GNU_HASH"; break;
   1343 	    }
   1344 
   1345 	  fprintf (f, "  %-20s ", name);
   1346 	  if (! stringp)
   1347 	    {
   1348 	      fprintf (f, "0x");
   1349 	      bfd_fprintf_vma (abfd, f, dyn.d_un.d_val);
   1350 	    }
   1351 	  else
   1352 	    {
   1353 	      const char *string;
   1354 	      unsigned int tagv = dyn.d_un.d_val;
   1355 
   1356 	      string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
   1357 	      if (string == NULL)
   1358 		goto error_return;
   1359 	      fprintf (f, "%s", string);
   1360 	    }
   1361 	  fprintf (f, "\n");
   1362 	}
   1363 
   1364       free (dynbuf);
   1365       dynbuf = NULL;
   1366     }
   1367 
   1368   if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
   1369       || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
   1370     {
   1371       if (! _bfd_elf_slurp_version_tables (abfd, FALSE))
   1372 	return FALSE;
   1373     }
   1374 
   1375   if (elf_dynverdef (abfd) != 0)
   1376     {
   1377       Elf_Internal_Verdef *t;
   1378 
   1379       fprintf (f, _("\nVersion definitions:\n"));
   1380       for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
   1381 	{
   1382 	  fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
   1383 		   t->vd_flags, t->vd_hash,
   1384 		   t->vd_nodename ? t->vd_nodename : "<corrupt>");
   1385 	  if (t->vd_auxptr != NULL && t->vd_auxptr->vda_nextptr != NULL)
   1386 	    {
   1387 	      Elf_Internal_Verdaux *a;
   1388 
   1389 	      fprintf (f, "\t");
   1390 	      for (a = t->vd_auxptr->vda_nextptr;
   1391 		   a != NULL;
   1392 		   a = a->vda_nextptr)
   1393 		fprintf (f, "%s ",
   1394 			 a->vda_nodename ? a->vda_nodename : "<corrupt>");
   1395 	      fprintf (f, "\n");
   1396 	    }
   1397 	}
   1398     }
   1399 
   1400   if (elf_dynverref (abfd) != 0)
   1401     {
   1402       Elf_Internal_Verneed *t;
   1403 
   1404       fprintf (f, _("\nVersion References:\n"));
   1405       for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
   1406 	{
   1407 	  Elf_Internal_Vernaux *a;
   1408 
   1409 	  fprintf (f, _("  required from %s:\n"),
   1410 		   t->vn_filename ? t->vn_filename : "<corrupt>");
   1411 	  for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
   1412 	    fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
   1413 		     a->vna_flags, a->vna_other,
   1414 		     a->vna_nodename ? a->vna_nodename : "<corrupt>");
   1415 	}
   1416     }
   1417 
   1418   return TRUE;
   1419 
   1420  error_return:
   1421   if (dynbuf != NULL)
   1422     free (dynbuf);
   1423   return FALSE;
   1424 }
   1425 
   1426 /* Display ELF-specific fields of a symbol.  */
   1427 
   1428 void
   1429 bfd_elf_print_symbol (bfd *abfd,
   1430 		      void *filep,
   1431 		      asymbol *symbol,
   1432 		      bfd_print_symbol_type how)
   1433 {
   1434   FILE *file = (FILE *) filep;
   1435   switch (how)
   1436     {
   1437     case bfd_print_symbol_name:
   1438       fprintf (file, "%s", symbol->name);
   1439       break;
   1440     case bfd_print_symbol_more:
   1441       fprintf (file, "elf ");
   1442       bfd_fprintf_vma (abfd, file, symbol->value);
   1443       fprintf (file, " %lx", (unsigned long) symbol->flags);
   1444       break;
   1445     case bfd_print_symbol_all:
   1446       {
   1447 	const char *section_name;
   1448 	const char *name = NULL;
   1449 	const struct elf_backend_data *bed;
   1450 	unsigned char st_other;
   1451 	bfd_vma val;
   1452 
   1453 	section_name = symbol->section ? symbol->section->name : "(*none*)";
   1454 
   1455 	bed = get_elf_backend_data (abfd);
   1456 	if (bed->elf_backend_print_symbol_all)
   1457 	  name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
   1458 
   1459 	if (name == NULL)
   1460 	  {
   1461 	    name = symbol->name;
   1462 	    bfd_print_symbol_vandf (abfd, file, symbol);
   1463 	  }
   1464 
   1465 	fprintf (file, " %s\t", section_name);
   1466 	/* Print the "other" value for a symbol.  For common symbols,
   1467 	   we've already printed the size; now print the alignment.
   1468 	   For other symbols, we have no specified alignment, and
   1469 	   we've printed the address; now print the size.  */
   1470 	if (symbol->section && bfd_is_com_section (symbol->section))
   1471 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
   1472 	else
   1473 	  val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_size;
   1474 	bfd_fprintf_vma (abfd, file, val);
   1475 
   1476 	/* If we have version information, print it.  */
   1477 	if (elf_dynversym (abfd) != 0
   1478 	    && (elf_dynverdef (abfd) != 0
   1479 		|| elf_dynverref (abfd) != 0))
   1480 	  {
   1481 	    unsigned int vernum;
   1482 	    const char *version_string;
   1483 
   1484 	    vernum = ((elf_symbol_type *) symbol)->version & VERSYM_VERSION;
   1485 
   1486 	    if (vernum == 0)
   1487 	      version_string = "";
   1488 	    else if (vernum == 1)
   1489 	      version_string = "Base";
   1490 	    else if (vernum <= elf_tdata (abfd)->cverdefs)
   1491 	      version_string =
   1492 		elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
   1493 	    else
   1494 	      {
   1495 		Elf_Internal_Verneed *t;
   1496 
   1497 		version_string = "";
   1498 		for (t = elf_tdata (abfd)->verref;
   1499 		     t != NULL;
   1500 		     t = t->vn_nextref)
   1501 		  {
   1502 		    Elf_Internal_Vernaux *a;
   1503 
   1504 		    for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
   1505 		      {
   1506 			if (a->vna_other == vernum)
   1507 			  {
   1508 			    version_string = a->vna_nodename;
   1509 			    break;
   1510 			  }
   1511 		      }
   1512 		  }
   1513 	      }
   1514 
   1515 	    if ((((elf_symbol_type *) symbol)->version & VERSYM_HIDDEN) == 0)
   1516 	      fprintf (file, "  %-11s", version_string);
   1517 	    else
   1518 	      {
   1519 		int i;
   1520 
   1521 		fprintf (file, " (%s)", version_string);
   1522 		for (i = 10 - strlen (version_string); i > 0; --i)
   1523 		  putc (' ', file);
   1524 	      }
   1525 	  }
   1526 
   1527 	/* If the st_other field is not zero, print it.  */
   1528 	st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
   1529 
   1530 	switch (st_other)
   1531 	  {
   1532 	  case 0: break;
   1533 	  case STV_INTERNAL:  fprintf (file, " .internal");  break;
   1534 	  case STV_HIDDEN:    fprintf (file, " .hidden");    break;
   1535 	  case STV_PROTECTED: fprintf (file, " .protected"); break;
   1536 	  default:
   1537 	    /* Some other non-defined flags are also present, so print
   1538 	       everything hex.  */
   1539 	    fprintf (file, " 0x%02x", (unsigned int) st_other);
   1540 	  }
   1541 
   1542 	fprintf (file, " %s", name);
   1543       }
   1544       break;
   1545     }
   1546 }
   1547 
   1548 /* Allocate an ELF string table--force the first byte to be zero.  */
   1549 
   1550 struct bfd_strtab_hash *
   1551 _bfd_elf_stringtab_init (void)
   1552 {
   1553   struct bfd_strtab_hash *ret;
   1554 
   1555   ret = _bfd_stringtab_init ();
   1556   if (ret != NULL)
   1557     {
   1558       bfd_size_type loc;
   1559 
   1560       loc = _bfd_stringtab_add (ret, "", TRUE, FALSE);
   1561       BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
   1562       if (loc == (bfd_size_type) -1)
   1563 	{
   1564 	  _bfd_stringtab_free (ret);
   1565 	  ret = NULL;
   1566 	}
   1567     }
   1568   return ret;
   1569 }
   1570 
   1571 /* ELF .o/exec file reading */
   1573 
   1574 /* Create a new bfd section from an ELF section header.  */
   1575 
   1576 bfd_boolean
   1577 bfd_section_from_shdr (bfd *abfd, unsigned int shindex)
   1578 {
   1579   Elf_Internal_Shdr *hdr;
   1580   Elf_Internal_Ehdr *ehdr;
   1581   const struct elf_backend_data *bed;
   1582   const char *name;
   1583   bfd_boolean ret = TRUE;
   1584   static bfd_boolean * sections_being_created = NULL;
   1585   static bfd * sections_being_created_abfd = NULL;
   1586   static unsigned int nesting = 0;
   1587 
   1588   if (shindex >= elf_numsections (abfd))
   1589     return FALSE;
   1590 
   1591   if (++ nesting > 3)
   1592     {
   1593       /* PR17512: A corrupt ELF binary might contain a recursive group of
   1594 	 sections, each the string indicies pointing to the next in the
   1595 	 loop.  Detect this here, by refusing to load a section that we are
   1596 	 already in the process of loading.  We only trigger this test if
   1597 	 we have nested at least three sections deep as normal ELF binaries
   1598 	 can expect to recurse at least once.
   1599 
   1600 	 FIXME: It would be better if this array was attached to the bfd,
   1601 	 rather than being held in a static pointer.  */
   1602 
   1603       if (sections_being_created_abfd != abfd)
   1604 	sections_being_created = NULL;
   1605       if (sections_being_created == NULL)
   1606 	{
   1607 	  /* FIXME: It would be more efficient to attach this array to the bfd somehow.  */
   1608 	  sections_being_created = (bfd_boolean *)
   1609 	    bfd_zalloc (abfd, elf_numsections (abfd) * sizeof (bfd_boolean));
   1610 	  sections_being_created_abfd = abfd;
   1611 	}
   1612       if (sections_being_created [shindex])
   1613 	{
   1614 	  (*_bfd_error_handler)
   1615 	    (_("%B: warning: loop in section dependencies detected"), abfd);
   1616 	  return FALSE;
   1617 	}
   1618       sections_being_created [shindex] = TRUE;
   1619     }
   1620 
   1621   hdr = elf_elfsections (abfd)[shindex];
   1622   ehdr = elf_elfheader (abfd);
   1623   name = bfd_elf_string_from_elf_section (abfd, ehdr->e_shstrndx,
   1624 					  hdr->sh_name);
   1625   if (name == NULL)
   1626     goto fail;
   1627 
   1628   bed = get_elf_backend_data (abfd);
   1629   switch (hdr->sh_type)
   1630     {
   1631     case SHT_NULL:
   1632       /* Inactive section. Throw it away.  */
   1633       goto success;
   1634 
   1635     case SHT_PROGBITS:		/* Normal section with contents.  */
   1636     case SHT_NOBITS:		/* .bss section.  */
   1637     case SHT_HASH:		/* .hash section.  */
   1638     case SHT_NOTE:		/* .note section.  */
   1639     case SHT_INIT_ARRAY:	/* .init_array section.  */
   1640     case SHT_FINI_ARRAY:	/* .fini_array section.  */
   1641     case SHT_PREINIT_ARRAY:	/* .preinit_array section.  */
   1642     case SHT_GNU_LIBLIST:	/* .gnu.liblist section.  */
   1643     case SHT_GNU_HASH:		/* .gnu.hash section.  */
   1644       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   1645       goto success;
   1646 
   1647     case SHT_DYNAMIC:	/* Dynamic linking information.  */
   1648       if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
   1649 	goto fail;
   1650 
   1651       if (hdr->sh_link > elf_numsections (abfd))
   1652 	{
   1653 	  /* PR 10478: Accept Solaris binaries with a sh_link
   1654 	     field set to SHN_BEFORE or SHN_AFTER.  */
   1655 	  switch (bfd_get_arch (abfd))
   1656 	    {
   1657 	    case bfd_arch_i386:
   1658 	    case bfd_arch_sparc:
   1659 	      if (hdr->sh_link == (SHN_LORESERVE & 0xffff) /* SHN_BEFORE */
   1660 		  || hdr->sh_link == ((SHN_LORESERVE + 1) & 0xffff) /* SHN_AFTER */)
   1661 		break;
   1662 	      /* Otherwise fall through.  */
   1663 	    default:
   1664 	      goto fail;
   1665 	    }
   1666 	}
   1667       else if (elf_elfsections (abfd)[hdr->sh_link] == NULL)
   1668 	goto fail;
   1669       else if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_STRTAB)
   1670 	{
   1671 	  Elf_Internal_Shdr *dynsymhdr;
   1672 
   1673 	  /* The shared libraries distributed with hpux11 have a bogus
   1674 	     sh_link field for the ".dynamic" section.  Find the
   1675 	     string table for the ".dynsym" section instead.  */
   1676 	  if (elf_dynsymtab (abfd) != 0)
   1677 	    {
   1678 	      dynsymhdr = elf_elfsections (abfd)[elf_dynsymtab (abfd)];
   1679 	      hdr->sh_link = dynsymhdr->sh_link;
   1680 	    }
   1681 	  else
   1682 	    {
   1683 	      unsigned int i, num_sec;
   1684 
   1685 	      num_sec = elf_numsections (abfd);
   1686 	      for (i = 1; i < num_sec; i++)
   1687 		{
   1688 		  dynsymhdr = elf_elfsections (abfd)[i];
   1689 		  if (dynsymhdr->sh_type == SHT_DYNSYM)
   1690 		    {
   1691 		      hdr->sh_link = dynsymhdr->sh_link;
   1692 		      break;
   1693 		    }
   1694 		}
   1695 	    }
   1696 	}
   1697       goto success;
   1698 
   1699     case SHT_SYMTAB:		/* A symbol table.  */
   1700       if (elf_onesymtab (abfd) == shindex)
   1701 	goto success;
   1702 
   1703       if (hdr->sh_entsize != bed->s->sizeof_sym)
   1704 	goto fail;
   1705 
   1706       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
   1707 	{
   1708 	  if (hdr->sh_size != 0)
   1709 	    goto fail;
   1710 	  /* Some assemblers erroneously set sh_info to one with a
   1711 	     zero sh_size.  ld sees this as a global symbol count
   1712 	     of (unsigned) -1.  Fix it here.  */
   1713 	  hdr->sh_info = 0;
   1714 	  goto success;
   1715 	}
   1716 
   1717       BFD_ASSERT (elf_onesymtab (abfd) == 0);
   1718       elf_onesymtab (abfd) = shindex;
   1719       elf_tdata (abfd)->symtab_hdr = *hdr;
   1720       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->symtab_hdr;
   1721       abfd->flags |= HAS_SYMS;
   1722 
   1723       /* Sometimes a shared object will map in the symbol table.  If
   1724 	 SHF_ALLOC is set, and this is a shared object, then we also
   1725 	 treat this section as a BFD section.  We can not base the
   1726 	 decision purely on SHF_ALLOC, because that flag is sometimes
   1727 	 set in a relocatable object file, which would confuse the
   1728 	 linker.  */
   1729       if ((hdr->sh_flags & SHF_ALLOC) != 0
   1730 	  && (abfd->flags & DYNAMIC) != 0
   1731 	  && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name,
   1732 						shindex))
   1733 	goto fail;
   1734 
   1735       /* Go looking for SHT_SYMTAB_SHNDX too, since if there is one we
   1736 	 can't read symbols without that section loaded as well.  It
   1737 	 is most likely specified by the next section header.  */
   1738       if (elf_elfsections (abfd)[elf_symtab_shndx (abfd)]->sh_link != shindex)
   1739 	{
   1740 	  unsigned int i, num_sec;
   1741 
   1742 	  num_sec = elf_numsections (abfd);
   1743 	  for (i = shindex + 1; i < num_sec; i++)
   1744 	    {
   1745 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
   1746 	      if (hdr2->sh_type == SHT_SYMTAB_SHNDX
   1747 		  && hdr2->sh_link == shindex)
   1748 		break;
   1749 	    }
   1750 	  if (i == num_sec)
   1751 	    for (i = 1; i < shindex; i++)
   1752 	      {
   1753 		Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
   1754 		if (hdr2->sh_type == SHT_SYMTAB_SHNDX
   1755 		    && hdr2->sh_link == shindex)
   1756 		  break;
   1757 	      }
   1758 	  if (i != shindex)
   1759 	    ret = bfd_section_from_shdr (abfd, i);
   1760 	}
   1761       goto success;
   1762 
   1763     case SHT_DYNSYM:		/* A dynamic symbol table.  */
   1764       if (elf_dynsymtab (abfd) == shindex)
   1765 	goto success;
   1766 
   1767       if (hdr->sh_entsize != bed->s->sizeof_sym)
   1768 	goto fail;
   1769 
   1770       if (hdr->sh_info * hdr->sh_entsize > hdr->sh_size)
   1771 	{
   1772 	  if (hdr->sh_size != 0)
   1773 	    goto fail;
   1774 
   1775 	  /* Some linkers erroneously set sh_info to one with a
   1776 	     zero sh_size.  ld sees this as a global symbol count
   1777 	     of (unsigned) -1.  Fix it here.  */
   1778 	  hdr->sh_info = 0;
   1779 	  goto success;
   1780 	}
   1781 
   1782       BFD_ASSERT (elf_dynsymtab (abfd) == 0);
   1783       elf_dynsymtab (abfd) = shindex;
   1784       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
   1785       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
   1786       abfd->flags |= HAS_SYMS;
   1787 
   1788       /* Besides being a symbol table, we also treat this as a regular
   1789 	 section, so that objcopy can handle it.  */
   1790       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   1791       goto success;
   1792 
   1793     case SHT_SYMTAB_SHNDX:	/* Symbol section indices when >64k sections.  */
   1794       if (elf_symtab_shndx (abfd) == shindex)
   1795 	goto success;
   1796 
   1797       BFD_ASSERT (elf_symtab_shndx (abfd) == 0);
   1798       elf_symtab_shndx (abfd) = shindex;
   1799       elf_tdata (abfd)->symtab_shndx_hdr = *hdr;
   1800       elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->symtab_shndx_hdr;
   1801       goto success;
   1802 
   1803     case SHT_STRTAB:		/* A string table.  */
   1804       if (hdr->bfd_section != NULL)
   1805 	goto success;
   1806 
   1807       if (ehdr->e_shstrndx == shindex)
   1808 	{
   1809 	  elf_tdata (abfd)->shstrtab_hdr = *hdr;
   1810 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
   1811 	  goto success;
   1812 	}
   1813 
   1814       if (elf_elfsections (abfd)[elf_onesymtab (abfd)]->sh_link == shindex)
   1815 	{
   1816 	symtab_strtab:
   1817 	  elf_tdata (abfd)->strtab_hdr = *hdr;
   1818 	  elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->strtab_hdr;
   1819 	  goto success;
   1820 	}
   1821 
   1822       if (elf_elfsections (abfd)[elf_dynsymtab (abfd)]->sh_link == shindex)
   1823 	{
   1824 	dynsymtab_strtab:
   1825 	  elf_tdata (abfd)->dynstrtab_hdr = *hdr;
   1826 	  hdr = &elf_tdata (abfd)->dynstrtab_hdr;
   1827 	  elf_elfsections (abfd)[shindex] = hdr;
   1828 	  /* We also treat this as a regular section, so that objcopy
   1829 	     can handle it.  */
   1830 	  ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
   1831 						 shindex);
   1832 	  goto success;
   1833 	}
   1834 
   1835       /* If the string table isn't one of the above, then treat it as a
   1836 	 regular section.  We need to scan all the headers to be sure,
   1837 	 just in case this strtab section appeared before the above.  */
   1838       if (elf_onesymtab (abfd) == 0 || elf_dynsymtab (abfd) == 0)
   1839 	{
   1840 	  unsigned int i, num_sec;
   1841 
   1842 	  num_sec = elf_numsections (abfd);
   1843 	  for (i = 1; i < num_sec; i++)
   1844 	    {
   1845 	      Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
   1846 	      if (hdr2->sh_link == shindex)
   1847 		{
   1848 		  /* Prevent endless recursion on broken objects.  */
   1849 		  if (i == shindex)
   1850 		    goto fail;
   1851 		  if (! bfd_section_from_shdr (abfd, i))
   1852 		    goto fail;
   1853 		  if (elf_onesymtab (abfd) == i)
   1854 		    goto symtab_strtab;
   1855 		  if (elf_dynsymtab (abfd) == i)
   1856 		    goto dynsymtab_strtab;
   1857 		}
   1858 	    }
   1859 	}
   1860       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   1861       goto success;
   1862 
   1863     case SHT_REL:
   1864     case SHT_RELA:
   1865       /* *These* do a lot of work -- but build no sections!  */
   1866       {
   1867 	asection *target_sect;
   1868 	Elf_Internal_Shdr *hdr2, **p_hdr;
   1869 	unsigned int num_sec = elf_numsections (abfd);
   1870 	struct bfd_elf_section_data *esdt;
   1871 	bfd_size_type amt;
   1872 
   1873 	if (hdr->sh_entsize
   1874 	    != (bfd_size_type) (hdr->sh_type == SHT_REL
   1875 				? bed->s->sizeof_rel : bed->s->sizeof_rela))
   1876 	  goto fail;
   1877 
   1878 	/* Check for a bogus link to avoid crashing.  */
   1879 	if (hdr->sh_link >= num_sec)
   1880 	  {
   1881 	    ((*_bfd_error_handler)
   1882 	     (_("%B: invalid link %lu for reloc section %s (index %u)"),
   1883 	      abfd, hdr->sh_link, name, shindex));
   1884 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
   1885 						   shindex);
   1886 	    goto success;
   1887 	  }
   1888 
   1889 	/* For some incomprehensible reason Oracle distributes
   1890 	   libraries for Solaris in which some of the objects have
   1891 	   bogus sh_link fields.  It would be nice if we could just
   1892 	   reject them, but, unfortunately, some people need to use
   1893 	   them.  We scan through the section headers; if we find only
   1894 	   one suitable symbol table, we clobber the sh_link to point
   1895 	   to it.  I hope this doesn't break anything.
   1896 
   1897 	   Don't do it on executable nor shared library.  */
   1898 	if ((abfd->flags & (DYNAMIC | EXEC_P)) == 0
   1899 	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
   1900 	    && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
   1901 	  {
   1902 	    unsigned int scan;
   1903 	    int found;
   1904 
   1905 	    found = 0;
   1906 	    for (scan = 1; scan < num_sec; scan++)
   1907 	      {
   1908 		if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
   1909 		    || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
   1910 		  {
   1911 		    if (found != 0)
   1912 		      {
   1913 			found = 0;
   1914 			break;
   1915 		      }
   1916 		    found = scan;
   1917 		  }
   1918 	      }
   1919 	    if (found != 0)
   1920 	      hdr->sh_link = found;
   1921 	  }
   1922 
   1923 	/* Get the symbol table.  */
   1924 	if ((elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
   1925 	     || elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_DYNSYM)
   1926 	    && ! bfd_section_from_shdr (abfd, hdr->sh_link))
   1927 	  goto fail;
   1928 
   1929 	/* If this reloc section does not use the main symbol table we
   1930 	   don't treat it as a reloc section.  BFD can't adequately
   1931 	   represent such a section, so at least for now, we don't
   1932 	   try.  We just present it as a normal section.  We also
   1933 	   can't use it as a reloc section if it points to the null
   1934 	   section, an invalid section, another reloc section, or its
   1935 	   sh_link points to the null section.  */
   1936 	if (hdr->sh_link != elf_onesymtab (abfd)
   1937 	    || hdr->sh_link == SHN_UNDEF
   1938 	    || hdr->sh_info == SHN_UNDEF
   1939 	    || hdr->sh_info >= num_sec
   1940 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_REL
   1941 	    || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_RELA)
   1942 	  {
   1943 	    ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
   1944 						   shindex);
   1945 	    goto success;
   1946 	  }
   1947 
   1948 	if (! bfd_section_from_shdr (abfd, hdr->sh_info))
   1949 	  goto fail;
   1950 
   1951 	target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
   1952 	if (target_sect == NULL)
   1953 	  goto fail;
   1954 
   1955 	esdt = elf_section_data (target_sect);
   1956 	if (hdr->sh_type == SHT_RELA)
   1957 	  p_hdr = &esdt->rela.hdr;
   1958 	else
   1959 	  p_hdr = &esdt->rel.hdr;
   1960 
   1961 	BFD_ASSERT (*p_hdr == NULL);
   1962 	amt = sizeof (*hdr2);
   1963 	hdr2 = (Elf_Internal_Shdr *) bfd_alloc (abfd, amt);
   1964 	if (hdr2 == NULL)
   1965 	  goto fail;
   1966 	*hdr2 = *hdr;
   1967 	*p_hdr = hdr2;
   1968 	elf_elfsections (abfd)[shindex] = hdr2;
   1969 	target_sect->reloc_count += NUM_SHDR_ENTRIES (hdr);
   1970 	target_sect->flags |= SEC_RELOC;
   1971 	target_sect->relocation = NULL;
   1972 	target_sect->rel_filepos = hdr->sh_offset;
   1973 	/* In the section to which the relocations apply, mark whether
   1974 	   its relocations are of the REL or RELA variety.  */
   1975 	if (hdr->sh_size != 0)
   1976 	  {
   1977 	    if (hdr->sh_type == SHT_RELA)
   1978 	      target_sect->use_rela_p = 1;
   1979 	  }
   1980 	abfd->flags |= HAS_RELOC;
   1981 	goto success;
   1982       }
   1983 
   1984     case SHT_GNU_verdef:
   1985       elf_dynverdef (abfd) = shindex;
   1986       elf_tdata (abfd)->dynverdef_hdr = *hdr;
   1987       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   1988       goto success;
   1989 
   1990     case SHT_GNU_versym:
   1991       if (hdr->sh_entsize != sizeof (Elf_External_Versym))
   1992 	goto fail;
   1993 
   1994       elf_dynversym (abfd) = shindex;
   1995       elf_tdata (abfd)->dynversym_hdr = *hdr;
   1996       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   1997       goto success;
   1998 
   1999     case SHT_GNU_verneed:
   2000       elf_dynverref (abfd) = shindex;
   2001       elf_tdata (abfd)->dynverref_hdr = *hdr;
   2002       ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   2003       goto success;
   2004 
   2005     case SHT_SHLIB:
   2006       goto success;
   2007 
   2008     case SHT_GROUP:
   2009       if (! IS_VALID_GROUP_SECTION_HEADER (hdr, GRP_ENTRY_SIZE))
   2010 	goto fail;
   2011 
   2012       if (!_bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
   2013 	goto fail;
   2014 
   2015       if (hdr->contents != NULL)
   2016 	{
   2017 	  Elf_Internal_Group *idx = (Elf_Internal_Group *) hdr->contents;
   2018 	  unsigned int n_elt = hdr->sh_size / GRP_ENTRY_SIZE;
   2019 	  asection *s;
   2020 
   2021 	  if (idx->flags & GRP_COMDAT)
   2022 	    hdr->bfd_section->flags
   2023 	      |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
   2024 
   2025 	  /* We try to keep the same section order as it comes in.  */
   2026 	  idx += n_elt;
   2027 	  while (--n_elt != 0)
   2028 	    {
   2029 	      --idx;
   2030 
   2031 	      if (idx->shdr != NULL
   2032 		  && (s = idx->shdr->bfd_section) != NULL
   2033 		  && elf_next_in_group (s) != NULL)
   2034 		{
   2035 		  elf_next_in_group (hdr->bfd_section) = s;
   2036 		  break;
   2037 		}
   2038 	    }
   2039 	}
   2040       goto success;
   2041 
   2042     default:
   2043       /* Possibly an attributes section.  */
   2044       if (hdr->sh_type == SHT_GNU_ATTRIBUTES
   2045 	  || hdr->sh_type == bed->obj_attrs_section_type)
   2046 	{
   2047 	  if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
   2048 	    goto fail;
   2049 	  _bfd_elf_parse_attributes (abfd, hdr);
   2050 	  goto success;
   2051 	}
   2052 
   2053       /* Check for any processor-specific section types.  */
   2054       if (bed->elf_backend_section_from_shdr (abfd, hdr, name, shindex))
   2055 	goto success;
   2056 
   2057       if (hdr->sh_type >= SHT_LOUSER && hdr->sh_type <= SHT_HIUSER)
   2058 	{
   2059 	  if ((hdr->sh_flags & SHF_ALLOC) != 0)
   2060 	    /* FIXME: How to properly handle allocated section reserved
   2061 	       for applications?  */
   2062 	    (*_bfd_error_handler)
   2063 	      (_("%B: don't know how to handle allocated, application "
   2064 		 "specific section `%s' [0x%8x]"),
   2065 	       abfd, name, hdr->sh_type);
   2066 	  else
   2067 	    {
   2068 	      /* Allow sections reserved for applications.  */
   2069 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name,
   2070 						     shindex);
   2071 	      goto success;
   2072 	    }
   2073 	}
   2074       else if (hdr->sh_type >= SHT_LOPROC
   2075 	       && hdr->sh_type <= SHT_HIPROC)
   2076 	/* FIXME: We should handle this section.  */
   2077 	(*_bfd_error_handler)
   2078 	  (_("%B: don't know how to handle processor specific section "
   2079 	     "`%s' [0x%8x]"),
   2080 	   abfd, name, hdr->sh_type);
   2081       else if (hdr->sh_type >= SHT_LOOS && hdr->sh_type <= SHT_HIOS)
   2082 	{
   2083 	  /* Unrecognised OS-specific sections.  */
   2084 	  if ((hdr->sh_flags & SHF_OS_NONCONFORMING) != 0)
   2085 	    /* SHF_OS_NONCONFORMING indicates that special knowledge is
   2086 	       required to correctly process the section and the file should
   2087 	       be rejected with an error message.  */
   2088 	    (*_bfd_error_handler)
   2089 	      (_("%B: don't know how to handle OS specific section "
   2090 		 "`%s' [0x%8x]"),
   2091 	       abfd, name, hdr->sh_type);
   2092 	  else
   2093 	    {
   2094 	      /* Otherwise it should be processed.  */
   2095 	      ret = _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
   2096 	      goto success;
   2097 	    }
   2098 	}
   2099       else
   2100 	/* FIXME: We should handle this section.  */
   2101 	(*_bfd_error_handler)
   2102 	  (_("%B: don't know how to handle section `%s' [0x%8x]"),
   2103 	   abfd, name, hdr->sh_type);
   2104 
   2105       goto fail;
   2106     }
   2107 
   2108  fail:
   2109   ret = FALSE;
   2110  success:
   2111   if (sections_being_created && sections_being_created_abfd == abfd)
   2112     sections_being_created [shindex] = FALSE;
   2113   if (-- nesting == 0)
   2114     {
   2115       sections_being_created = NULL;
   2116       sections_being_created_abfd = abfd;
   2117     }
   2118   return ret;
   2119 }
   2120 
   2121 /* Return the local symbol specified by ABFD, R_SYMNDX.  */
   2122 
   2123 Elf_Internal_Sym *
   2124 bfd_sym_from_r_symndx (struct sym_cache *cache,
   2125 		       bfd *abfd,
   2126 		       unsigned long r_symndx)
   2127 {
   2128   unsigned int ent = r_symndx % LOCAL_SYM_CACHE_SIZE;
   2129 
   2130   if (cache->abfd != abfd || cache->indx[ent] != r_symndx)
   2131     {
   2132       Elf_Internal_Shdr *symtab_hdr;
   2133       unsigned char esym[sizeof (Elf64_External_Sym)];
   2134       Elf_External_Sym_Shndx eshndx;
   2135 
   2136       symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
   2137       if (bfd_elf_get_elf_syms (abfd, symtab_hdr, 1, r_symndx,
   2138 				&cache->sym[ent], esym, &eshndx) == NULL)
   2139 	return NULL;
   2140 
   2141       if (cache->abfd != abfd)
   2142 	{
   2143 	  memset (cache->indx, -1, sizeof (cache->indx));
   2144 	  cache->abfd = abfd;
   2145 	}
   2146       cache->indx[ent] = r_symndx;
   2147     }
   2148 
   2149   return &cache->sym[ent];
   2150 }
   2151 
   2152 /* Given an ELF section number, retrieve the corresponding BFD
   2153    section.  */
   2154 
   2155 asection *
   2156 bfd_section_from_elf_index (bfd *abfd, unsigned int sec_index)
   2157 {
   2158   if (sec_index >= elf_numsections (abfd))
   2159     return NULL;
   2160   return elf_elfsections (abfd)[sec_index]->bfd_section;
   2161 }
   2162 
   2163 static const struct bfd_elf_special_section special_sections_b[] =
   2164 {
   2165   { STRING_COMMA_LEN (".bss"), -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
   2166   { NULL,                   0,  0, 0,            0 }
   2167 };
   2168 
   2169 static const struct bfd_elf_special_section special_sections_c[] =
   2170 {
   2171   { STRING_COMMA_LEN (".comment"), 0, SHT_PROGBITS, 0 },
   2172   { NULL,                       0, 0, 0,            0 }
   2173 };
   2174 
   2175 static const struct bfd_elf_special_section special_sections_d[] =
   2176 {
   2177   { STRING_COMMA_LEN (".data"),         -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
   2178   { STRING_COMMA_LEN (".data1"),         0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
   2179   /* There are more DWARF sections than these, but they needn't be added here
   2180      unless you have to cope with broken compilers that don't emit section
   2181      attributes or you want to help the user writing assembler.  */
   2182   { STRING_COMMA_LEN (".debug"),         0, SHT_PROGBITS, 0 },
   2183   { STRING_COMMA_LEN (".debug_line"),    0, SHT_PROGBITS, 0 },
   2184   { STRING_COMMA_LEN (".debug_info"),    0, SHT_PROGBITS, 0 },
   2185   { STRING_COMMA_LEN (".debug_abbrev"),  0, SHT_PROGBITS, 0 },
   2186   { STRING_COMMA_LEN (".debug_aranges"), 0, SHT_PROGBITS, 0 },
   2187   { STRING_COMMA_LEN (".dynamic"),       0, SHT_DYNAMIC,  SHF_ALLOC },
   2188   { STRING_COMMA_LEN (".dynstr"),        0, SHT_STRTAB,   SHF_ALLOC },
   2189   { STRING_COMMA_LEN (".dynsym"),        0, SHT_DYNSYM,   SHF_ALLOC },
   2190   { NULL,                      0,        0, 0,            0 }
   2191 };
   2192 
   2193 static const struct bfd_elf_special_section special_sections_f[] =
   2194 {
   2195   { STRING_COMMA_LEN (".fini"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
   2196   { STRING_COMMA_LEN (".fini_array"), 0, SHT_FINI_ARRAY, SHF_ALLOC + SHF_WRITE },
   2197   { NULL,                          0, 0, 0,              0 }
   2198 };
   2199 
   2200 static const struct bfd_elf_special_section special_sections_g[] =
   2201 {
   2202   { STRING_COMMA_LEN (".gnu.linkonce.b"), -2, SHT_NOBITS,      SHF_ALLOC + SHF_WRITE },
   2203   { STRING_COMMA_LEN (".gnu.lto_"),       -1, SHT_PROGBITS,    SHF_EXCLUDE },
   2204   { STRING_COMMA_LEN (".got"),             0, SHT_PROGBITS,    SHF_ALLOC + SHF_WRITE },
   2205   { STRING_COMMA_LEN (".gnu.version"),     0, SHT_GNU_versym,  0 },
   2206   { STRING_COMMA_LEN (".gnu.version_d"),   0, SHT_GNU_verdef,  0 },
   2207   { STRING_COMMA_LEN (".gnu.version_r"),   0, SHT_GNU_verneed, 0 },
   2208   { STRING_COMMA_LEN (".gnu.liblist"),     0, SHT_GNU_LIBLIST, SHF_ALLOC },
   2209   { STRING_COMMA_LEN (".gnu.conflict"),    0, SHT_RELA,        SHF_ALLOC },
   2210   { STRING_COMMA_LEN (".gnu.hash"),        0, SHT_GNU_HASH,    SHF_ALLOC },
   2211   { NULL,                        0,        0, 0,               0 }
   2212 };
   2213 
   2214 static const struct bfd_elf_special_section special_sections_h[] =
   2215 {
   2216   { STRING_COMMA_LEN (".hash"), 0, SHT_HASH,     SHF_ALLOC },
   2217   { NULL,                    0, 0, 0,            0 }
   2218 };
   2219 
   2220 static const struct bfd_elf_special_section special_sections_i[] =
   2221 {
   2222   { STRING_COMMA_LEN (".init"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
   2223   { STRING_COMMA_LEN (".init_array"), 0, SHT_INIT_ARRAY, SHF_ALLOC + SHF_WRITE },
   2224   { STRING_COMMA_LEN (".interp"),     0, SHT_PROGBITS,   0 },
   2225   { NULL,                      0,     0, 0,              0 }
   2226 };
   2227 
   2228 static const struct bfd_elf_special_section special_sections_l[] =
   2229 {
   2230   { STRING_COMMA_LEN (".line"), 0, SHT_PROGBITS, 0 },
   2231   { NULL,                    0, 0, 0,            0 }
   2232 };
   2233 
   2234 static const struct bfd_elf_special_section special_sections_n[] =
   2235 {
   2236   { STRING_COMMA_LEN (".note.GNU-stack"), 0, SHT_PROGBITS, 0 },
   2237   { STRING_COMMA_LEN (".note"),          -1, SHT_NOTE,     0 },
   2238   { NULL,                    0,           0, 0,            0 }
   2239 };
   2240 
   2241 static const struct bfd_elf_special_section special_sections_p[] =
   2242 {
   2243   { STRING_COMMA_LEN (".preinit_array"), 0, SHT_PREINIT_ARRAY, SHF_ALLOC + SHF_WRITE },
   2244   { STRING_COMMA_LEN (".plt"),           0, SHT_PROGBITS,      SHF_ALLOC + SHF_EXECINSTR },
   2245   { NULL,                   0,           0, 0,                 0 }
   2246 };
   2247 
   2248 static const struct bfd_elf_special_section special_sections_r[] =
   2249 {
   2250   { STRING_COMMA_LEN (".rodata"), -2, SHT_PROGBITS, SHF_ALLOC },
   2251   { STRING_COMMA_LEN (".rodata1"), 0, SHT_PROGBITS, SHF_ALLOC },
   2252   { STRING_COMMA_LEN (".rela"),   -1, SHT_RELA,     0 },
   2253   { STRING_COMMA_LEN (".rel"),    -1, SHT_REL,      0 },
   2254   { NULL,                   0,     0, 0,            0 }
   2255 };
   2256 
   2257 static const struct bfd_elf_special_section special_sections_s[] =
   2258 {
   2259   { STRING_COMMA_LEN (".shstrtab"), 0, SHT_STRTAB, 0 },
   2260   { STRING_COMMA_LEN (".strtab"),   0, SHT_STRTAB, 0 },
   2261   { STRING_COMMA_LEN (".symtab"),   0, SHT_SYMTAB, 0 },
   2262   /* See struct bfd_elf_special_section declaration for the semantics of
   2263      this special case where .prefix_length != strlen (.prefix).  */
   2264   { ".stabstr",			5,  3, SHT_STRTAB, 0 },
   2265   { NULL,                       0,  0, 0,          0 }
   2266 };
   2267 
   2268 static const struct bfd_elf_special_section special_sections_t[] =
   2269 {
   2270   { STRING_COMMA_LEN (".text"),  -2, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
   2271   { STRING_COMMA_LEN (".tbss"),  -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE + SHF_TLS },
   2272   { STRING_COMMA_LEN (".tdata"), -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_TLS },
   2273   { NULL,                     0,  0, 0,            0 }
   2274 };
   2275 
   2276 static const struct bfd_elf_special_section special_sections_z[] =
   2277 {
   2278   { STRING_COMMA_LEN (".zdebug_line"),    0, SHT_PROGBITS, 0 },
   2279   { STRING_COMMA_LEN (".zdebug_info"),    0, SHT_PROGBITS, 0 },
   2280   { STRING_COMMA_LEN (".zdebug_abbrev"),  0, SHT_PROGBITS, 0 },
   2281   { STRING_COMMA_LEN (".zdebug_aranges"), 0, SHT_PROGBITS, 0 },
   2282   { NULL,                     0,  0, 0,            0 }
   2283 };
   2284 
   2285 static const struct bfd_elf_special_section * const special_sections[] =
   2286 {
   2287   special_sections_b,		/* 'b' */
   2288   special_sections_c,		/* 'c' */
   2289   special_sections_d,		/* 'd' */
   2290   NULL,				/* 'e' */
   2291   special_sections_f,		/* 'f' */
   2292   special_sections_g,		/* 'g' */
   2293   special_sections_h,		/* 'h' */
   2294   special_sections_i,		/* 'i' */
   2295   NULL,				/* 'j' */
   2296   NULL,				/* 'k' */
   2297   special_sections_l,		/* 'l' */
   2298   NULL,				/* 'm' */
   2299   special_sections_n,		/* 'n' */
   2300   NULL,				/* 'o' */
   2301   special_sections_p,		/* 'p' */
   2302   NULL,				/* 'q' */
   2303   special_sections_r,		/* 'r' */
   2304   special_sections_s,		/* 's' */
   2305   special_sections_t,		/* 't' */
   2306   NULL,				/* 'u' */
   2307   NULL,				/* 'v' */
   2308   NULL,				/* 'w' */
   2309   NULL,				/* 'x' */
   2310   NULL,				/* 'y' */
   2311   special_sections_z		/* 'z' */
   2312 };
   2313 
   2314 const struct bfd_elf_special_section *
   2315 _bfd_elf_get_special_section (const char *name,
   2316 			      const struct bfd_elf_special_section *spec,
   2317 			      unsigned int rela)
   2318 {
   2319   int i;
   2320   int len;
   2321 
   2322   len = strlen (name);
   2323 
   2324   for (i = 0; spec[i].prefix != NULL; i++)
   2325     {
   2326       int suffix_len;
   2327       int prefix_len = spec[i].prefix_length;
   2328 
   2329       if (len < prefix_len)
   2330 	continue;
   2331       if (memcmp (name, spec[i].prefix, prefix_len) != 0)
   2332 	continue;
   2333 
   2334       suffix_len = spec[i].suffix_length;
   2335       if (suffix_len <= 0)
   2336 	{
   2337 	  if (name[prefix_len] != 0)
   2338 	    {
   2339 	      if (suffix_len == 0)
   2340 		continue;
   2341 	      if (name[prefix_len] != '.'
   2342 		  && (suffix_len == -2
   2343 		      || (rela && spec[i].type == SHT_REL)))
   2344 		continue;
   2345 	    }
   2346 	}
   2347       else
   2348 	{
   2349 	  if (len < prefix_len + suffix_len)
   2350 	    continue;
   2351 	  if (memcmp (name + len - suffix_len,
   2352 		      spec[i].prefix + prefix_len,
   2353 		      suffix_len) != 0)
   2354 	    continue;
   2355 	}
   2356       return &spec[i];
   2357     }
   2358 
   2359   return NULL;
   2360 }
   2361 
   2362 const struct bfd_elf_special_section *
   2363 _bfd_elf_get_sec_type_attr (bfd *abfd, asection *sec)
   2364 {
   2365   int i;
   2366   const struct bfd_elf_special_section *spec;
   2367   const struct elf_backend_data *bed;
   2368 
   2369   /* See if this is one of the special sections.  */
   2370   if (sec->name == NULL)
   2371     return NULL;
   2372 
   2373   bed = get_elf_backend_data (abfd);
   2374   spec = bed->special_sections;
   2375   if (spec)
   2376     {
   2377       spec = _bfd_elf_get_special_section (sec->name,
   2378 					   bed->special_sections,
   2379 					   sec->use_rela_p);
   2380       if (spec != NULL)
   2381 	return spec;
   2382     }
   2383 
   2384   if (sec->name[0] != '.')
   2385     return NULL;
   2386 
   2387   i = sec->name[1] - 'b';
   2388   if (i < 0 || i > 'z' - 'b')
   2389     return NULL;
   2390 
   2391   spec = special_sections[i];
   2392 
   2393   if (spec == NULL)
   2394     return NULL;
   2395 
   2396   return _bfd_elf_get_special_section (sec->name, spec, sec->use_rela_p);
   2397 }
   2398 
   2399 bfd_boolean
   2400 _bfd_elf_new_section_hook (bfd *abfd, asection *sec)
   2401 {
   2402   struct bfd_elf_section_data *sdata;
   2403   const struct elf_backend_data *bed;
   2404   const struct bfd_elf_special_section *ssect;
   2405 
   2406   sdata = (struct bfd_elf_section_data *) sec->used_by_bfd;
   2407   if (sdata == NULL)
   2408     {
   2409       sdata = (struct bfd_elf_section_data *) bfd_zalloc (abfd,
   2410                                                           sizeof (*sdata));
   2411       if (sdata == NULL)
   2412 	return FALSE;
   2413       sec->used_by_bfd = sdata;
   2414     }
   2415 
   2416   /* Indicate whether or not this section should use RELA relocations.  */
   2417   bed = get_elf_backend_data (abfd);
   2418   sec->use_rela_p = bed->default_use_rela_p;
   2419 
   2420   /* When we read a file, we don't need to set ELF section type and
   2421      flags.  They will be overridden in _bfd_elf_make_section_from_shdr
   2422      anyway.  We will set ELF section type and flags for all linker
   2423      created sections.  If user specifies BFD section flags, we will
   2424      set ELF section type and flags based on BFD section flags in
   2425      elf_fake_sections.  Special handling for .init_array/.fini_array
   2426      output sections since they may contain .ctors/.dtors input
   2427      sections.  We don't want _bfd_elf_init_private_section_data to
   2428      copy ELF section type from .ctors/.dtors input sections.  */
   2429   if (abfd->direction != read_direction
   2430       || (sec->flags & SEC_LINKER_CREATED) != 0)
   2431     {
   2432       ssect = (*bed->get_sec_type_attr) (abfd, sec);
   2433       if (ssect != NULL
   2434 	  && (!sec->flags
   2435 	      || (sec->flags & SEC_LINKER_CREATED) != 0
   2436 	      || ssect->type == SHT_INIT_ARRAY
   2437 	      || ssect->type == SHT_FINI_ARRAY))
   2438 	{
   2439 	  elf_section_type (sec) = ssect->type;
   2440 	  elf_section_flags (sec) = ssect->attr;
   2441 	}
   2442     }
   2443 
   2444   return _bfd_generic_new_section_hook (abfd, sec);
   2445 }
   2446 
   2447 /* Create a new bfd section from an ELF program header.
   2448 
   2449    Since program segments have no names, we generate a synthetic name
   2450    of the form segment<NUM>, where NUM is generally the index in the
   2451    program header table.  For segments that are split (see below) we
   2452    generate the names segment<NUM>a and segment<NUM>b.
   2453 
   2454    Note that some program segments may have a file size that is different than
   2455    (less than) the memory size.  All this means is that at execution the
   2456    system must allocate the amount of memory specified by the memory size,
   2457    but only initialize it with the first "file size" bytes read from the
   2458    file.  This would occur for example, with program segments consisting
   2459    of combined data+bss.
   2460 
   2461    To handle the above situation, this routine generates TWO bfd sections
   2462    for the single program segment.  The first has the length specified by
   2463    the file size of the segment, and the second has the length specified
   2464    by the difference between the two sizes.  In effect, the segment is split
   2465    into its initialized and uninitialized parts.
   2466 
   2467  */
   2468 
   2469 bfd_boolean
   2470 _bfd_elf_make_section_from_phdr (bfd *abfd,
   2471 				 Elf_Internal_Phdr *hdr,
   2472 				 int hdr_index,
   2473 				 const char *type_name)
   2474 {
   2475   asection *newsect;
   2476   char *name;
   2477   char namebuf[64];
   2478   size_t len;
   2479   int split;
   2480 
   2481   split = ((hdr->p_memsz > 0)
   2482 	    && (hdr->p_filesz > 0)
   2483 	    && (hdr->p_memsz > hdr->p_filesz));
   2484 
   2485   if (hdr->p_filesz > 0)
   2486     {
   2487       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "a" : "");
   2488       len = strlen (namebuf) + 1;
   2489       name = (char *) bfd_alloc (abfd, len);
   2490       if (!name)
   2491 	return FALSE;
   2492       memcpy (name, namebuf, len);
   2493       newsect = bfd_make_section (abfd, name);
   2494       if (newsect == NULL)
   2495 	return FALSE;
   2496       newsect->vma = hdr->p_vaddr;
   2497       newsect->lma = hdr->p_paddr;
   2498       newsect->size = hdr->p_filesz;
   2499       newsect->filepos = hdr->p_offset;
   2500       newsect->flags |= SEC_HAS_CONTENTS;
   2501       newsect->alignment_power = bfd_log2 (hdr->p_align);
   2502       if (hdr->p_type == PT_LOAD)
   2503 	{
   2504 	  newsect->flags |= SEC_ALLOC;
   2505 	  newsect->flags |= SEC_LOAD;
   2506 	  if (hdr->p_flags & PF_X)
   2507 	    {
   2508 	      /* FIXME: all we known is that it has execute PERMISSION,
   2509 		 may be data.  */
   2510 	      newsect->flags |= SEC_CODE;
   2511 	    }
   2512 	}
   2513       if (!(hdr->p_flags & PF_W))
   2514 	{
   2515 	  newsect->flags |= SEC_READONLY;
   2516 	}
   2517     }
   2518 
   2519   if (hdr->p_memsz > hdr->p_filesz)
   2520     {
   2521       bfd_vma align;
   2522 
   2523       sprintf (namebuf, "%s%d%s", type_name, hdr_index, split ? "b" : "");
   2524       len = strlen (namebuf) + 1;
   2525       name = (char *) bfd_alloc (abfd, len);
   2526       if (!name)
   2527 	return FALSE;
   2528       memcpy (name, namebuf, len);
   2529       newsect = bfd_make_section (abfd, name);
   2530       if (newsect == NULL)
   2531 	return FALSE;
   2532       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
   2533       newsect->lma = hdr->p_paddr + hdr->p_filesz;
   2534       newsect->size = hdr->p_memsz - hdr->p_filesz;
   2535       newsect->filepos = hdr->p_offset + hdr->p_filesz;
   2536       align = newsect->vma & -newsect->vma;
   2537       if (align == 0 || align > hdr->p_align)
   2538 	align = hdr->p_align;
   2539       newsect->alignment_power = bfd_log2 (align);
   2540       if (hdr->p_type == PT_LOAD)
   2541 	{
   2542 	  /* Hack for gdb.  Segments that have not been modified do
   2543 	     not have their contents written to a core file, on the
   2544 	     assumption that a debugger can find the contents in the
   2545 	     executable.  We flag this case by setting the fake
   2546 	     section size to zero.  Note that "real" bss sections will
   2547 	     always have their contents dumped to the core file.  */
   2548 	  if (bfd_get_format (abfd) == bfd_core)
   2549 	    newsect->size = 0;
   2550 	  newsect->flags |= SEC_ALLOC;
   2551 	  if (hdr->p_flags & PF_X)
   2552 	    newsect->flags |= SEC_CODE;
   2553 	}
   2554       if (!(hdr->p_flags & PF_W))
   2555 	newsect->flags |= SEC_READONLY;
   2556     }
   2557 
   2558   return TRUE;
   2559 }
   2560 
   2561 bfd_boolean
   2562 bfd_section_from_phdr (bfd *abfd, Elf_Internal_Phdr *hdr, int hdr_index)
   2563 {
   2564   const struct elf_backend_data *bed;
   2565 
   2566   switch (hdr->p_type)
   2567     {
   2568     case PT_NULL:
   2569       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "null");
   2570 
   2571     case PT_LOAD:
   2572       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "load");
   2573 
   2574     case PT_DYNAMIC:
   2575       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "dynamic");
   2576 
   2577     case PT_INTERP:
   2578       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "interp");
   2579 
   2580     case PT_NOTE:
   2581       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "note"))
   2582 	return FALSE;
   2583       if (! elf_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
   2584 	return FALSE;
   2585       return TRUE;
   2586 
   2587     case PT_SHLIB:
   2588       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "shlib");
   2589 
   2590     case PT_PHDR:
   2591       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "phdr");
   2592 
   2593     case PT_GNU_EH_FRAME:
   2594       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index,
   2595 					      "eh_frame_hdr");
   2596 
   2597     case PT_GNU_STACK:
   2598       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "stack");
   2599 
   2600     case PT_GNU_RELRO:
   2601       return _bfd_elf_make_section_from_phdr (abfd, hdr, hdr_index, "relro");
   2602 
   2603     default:
   2604       /* Check for any processor-specific program segment types.  */
   2605       bed = get_elf_backend_data (abfd);
   2606       return bed->elf_backend_section_from_phdr (abfd, hdr, hdr_index, "proc");
   2607     }
   2608 }
   2609 
   2610 /* Return the REL_HDR for SEC, assuming there is only a single one, either
   2611    REL or RELA.  */
   2612 
   2613 Elf_Internal_Shdr *
   2614 _bfd_elf_single_rel_hdr (asection *sec)
   2615 {
   2616   if (elf_section_data (sec)->rel.hdr)
   2617     {
   2618       BFD_ASSERT (elf_section_data (sec)->rela.hdr == NULL);
   2619       return elf_section_data (sec)->rel.hdr;
   2620     }
   2621   else
   2622     return elf_section_data (sec)->rela.hdr;
   2623 }
   2624 
   2625 /* Allocate and initialize a section-header for a new reloc section,
   2626    containing relocations against ASECT.  It is stored in RELDATA.  If
   2627    USE_RELA_P is TRUE, we use RELA relocations; otherwise, we use REL
   2628    relocations.  */
   2629 
   2630 static bfd_boolean
   2631 _bfd_elf_init_reloc_shdr (bfd *abfd,
   2632 			  struct bfd_elf_section_reloc_data *reldata,
   2633 			  asection *asect,
   2634 			  bfd_boolean use_rela_p)
   2635 {
   2636   Elf_Internal_Shdr *rel_hdr;
   2637   char *name;
   2638   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   2639   bfd_size_type amt;
   2640 
   2641   amt = sizeof (Elf_Internal_Shdr);
   2642   BFD_ASSERT (reldata->hdr == NULL);
   2643   rel_hdr = bfd_zalloc (abfd, amt);
   2644   reldata->hdr = rel_hdr;
   2645 
   2646   amt = sizeof ".rela" + strlen (asect->name);
   2647   name = (char *) bfd_alloc (abfd, amt);
   2648   if (name == NULL)
   2649     return FALSE;
   2650   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
   2651   rel_hdr->sh_name =
   2652     (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
   2653 					FALSE);
   2654   if (rel_hdr->sh_name == (unsigned int) -1)
   2655     return FALSE;
   2656   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
   2657   rel_hdr->sh_entsize = (use_rela_p
   2658 			 ? bed->s->sizeof_rela
   2659 			 : bed->s->sizeof_rel);
   2660   rel_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
   2661   rel_hdr->sh_flags = 0;
   2662   rel_hdr->sh_addr = 0;
   2663   rel_hdr->sh_size = 0;
   2664   rel_hdr->sh_offset = 0;
   2665 
   2666   return TRUE;
   2667 }
   2668 
   2669 /* Return the default section type based on the passed in section flags.  */
   2670 
   2671 int
   2672 bfd_elf_get_default_section_type (flagword flags)
   2673 {
   2674   if ((flags & SEC_ALLOC) != 0
   2675       && (flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
   2676     return SHT_NOBITS;
   2677   return SHT_PROGBITS;
   2678 }
   2679 
   2680 struct fake_section_arg
   2681 {
   2682   struct bfd_link_info *link_info;
   2683   bfd_boolean failed;
   2684 };
   2685 
   2686 /* Set up an ELF internal section header for a section.  */
   2687 
   2688 static void
   2689 elf_fake_sections (bfd *abfd, asection *asect, void *fsarg)
   2690 {
   2691   struct fake_section_arg *arg = (struct fake_section_arg *)fsarg;
   2692   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   2693   struct bfd_elf_section_data *esd = elf_section_data (asect);
   2694   Elf_Internal_Shdr *this_hdr;
   2695   unsigned int sh_type;
   2696 
   2697   if (arg->failed)
   2698     {
   2699       /* We already failed; just get out of the bfd_map_over_sections
   2700 	 loop.  */
   2701       return;
   2702     }
   2703 
   2704   this_hdr = &esd->this_hdr;
   2705 
   2706   this_hdr->sh_name = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
   2707 							  asect->name, FALSE);
   2708   if (this_hdr->sh_name == (unsigned int) -1)
   2709     {
   2710       arg->failed = TRUE;
   2711       return;
   2712     }
   2713 
   2714   /* Don't clear sh_flags. Assembler may set additional bits.  */
   2715 
   2716   if ((asect->flags & SEC_ALLOC) != 0
   2717       || asect->user_set_vma)
   2718     this_hdr->sh_addr = asect->vma;
   2719   else
   2720     this_hdr->sh_addr = 0;
   2721 
   2722   this_hdr->sh_offset = 0;
   2723   this_hdr->sh_size = asect->size;
   2724   this_hdr->sh_link = 0;
   2725   this_hdr->sh_addralign = (bfd_vma) 1 << asect->alignment_power;
   2726   /* The sh_entsize and sh_info fields may have been set already by
   2727      copy_private_section_data.  */
   2728 
   2729   this_hdr->bfd_section = asect;
   2730   this_hdr->contents = NULL;
   2731 
   2732   /* If the section type is unspecified, we set it based on
   2733      asect->flags.  */
   2734   if ((asect->flags & SEC_GROUP) != 0)
   2735     sh_type = SHT_GROUP;
   2736   else
   2737     sh_type = bfd_elf_get_default_section_type (asect->flags);
   2738 
   2739   if (this_hdr->sh_type == SHT_NULL)
   2740     this_hdr->sh_type = sh_type;
   2741   else if (this_hdr->sh_type == SHT_NOBITS
   2742 	   && sh_type == SHT_PROGBITS
   2743 	   && (asect->flags & SEC_ALLOC) != 0)
   2744     {
   2745       /* Warn if we are changing a NOBITS section to PROGBITS, but
   2746 	 allow the link to proceed.  This can happen when users link
   2747 	 non-bss input sections to bss output sections, or emit data
   2748 	 to a bss output section via a linker script.  */
   2749       (*_bfd_error_handler)
   2750 	(_("warning: section `%A' type changed to PROGBITS"), asect);
   2751       this_hdr->sh_type = sh_type;
   2752     }
   2753 
   2754   switch (this_hdr->sh_type)
   2755     {
   2756     default:
   2757       break;
   2758 
   2759     case SHT_STRTAB:
   2760     case SHT_INIT_ARRAY:
   2761     case SHT_FINI_ARRAY:
   2762     case SHT_PREINIT_ARRAY:
   2763     case SHT_NOTE:
   2764     case SHT_NOBITS:
   2765     case SHT_PROGBITS:
   2766       break;
   2767 
   2768     case SHT_HASH:
   2769       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
   2770       break;
   2771 
   2772     case SHT_DYNSYM:
   2773       this_hdr->sh_entsize = bed->s->sizeof_sym;
   2774       break;
   2775 
   2776     case SHT_DYNAMIC:
   2777       this_hdr->sh_entsize = bed->s->sizeof_dyn;
   2778       break;
   2779 
   2780     case SHT_RELA:
   2781       if (get_elf_backend_data (abfd)->may_use_rela_p)
   2782 	this_hdr->sh_entsize = bed->s->sizeof_rela;
   2783       break;
   2784 
   2785      case SHT_REL:
   2786       if (get_elf_backend_data (abfd)->may_use_rel_p)
   2787 	this_hdr->sh_entsize = bed->s->sizeof_rel;
   2788       break;
   2789 
   2790      case SHT_GNU_versym:
   2791       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
   2792       break;
   2793 
   2794      case SHT_GNU_verdef:
   2795       this_hdr->sh_entsize = 0;
   2796       /* objcopy or strip will copy over sh_info, but may not set
   2797 	 cverdefs.  The linker will set cverdefs, but sh_info will be
   2798 	 zero.  */
   2799       if (this_hdr->sh_info == 0)
   2800 	this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
   2801       else
   2802 	BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
   2803 		    || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
   2804       break;
   2805 
   2806     case SHT_GNU_verneed:
   2807       this_hdr->sh_entsize = 0;
   2808       /* objcopy or strip will copy over sh_info, but may not set
   2809 	 cverrefs.  The linker will set cverrefs, but sh_info will be
   2810 	 zero.  */
   2811       if (this_hdr->sh_info == 0)
   2812 	this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
   2813       else
   2814 	BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
   2815 		    || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
   2816       break;
   2817 
   2818     case SHT_GROUP:
   2819       this_hdr->sh_entsize = GRP_ENTRY_SIZE;
   2820       break;
   2821 
   2822     case SHT_GNU_HASH:
   2823       this_hdr->sh_entsize = bed->s->arch_size == 64 ? 0 : 4;
   2824       break;
   2825     }
   2826 
   2827   if ((asect->flags & SEC_ALLOC) != 0)
   2828     this_hdr->sh_flags |= SHF_ALLOC;
   2829   if ((asect->flags & SEC_READONLY) == 0)
   2830     this_hdr->sh_flags |= SHF_WRITE;
   2831   if ((asect->flags & SEC_CODE) != 0)
   2832     this_hdr->sh_flags |= SHF_EXECINSTR;
   2833   if ((asect->flags & SEC_MERGE) != 0)
   2834     {
   2835       this_hdr->sh_flags |= SHF_MERGE;
   2836       this_hdr->sh_entsize = asect->entsize;
   2837       if ((asect->flags & SEC_STRINGS) != 0)
   2838 	this_hdr->sh_flags |= SHF_STRINGS;
   2839     }
   2840   if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
   2841     this_hdr->sh_flags |= SHF_GROUP;
   2842   if ((asect->flags & SEC_THREAD_LOCAL) != 0)
   2843     {
   2844       this_hdr->sh_flags |= SHF_TLS;
   2845       if (asect->size == 0
   2846 	  && (asect->flags & SEC_HAS_CONTENTS) == 0)
   2847 	{
   2848 	  struct bfd_link_order *o = asect->map_tail.link_order;
   2849 
   2850 	  this_hdr->sh_size = 0;
   2851 	  if (o != NULL)
   2852 	    {
   2853 	      this_hdr->sh_size = o->offset + o->size;
   2854 	      if (this_hdr->sh_size != 0)
   2855 		this_hdr->sh_type = SHT_NOBITS;
   2856 	    }
   2857 	}
   2858     }
   2859   if ((asect->flags & (SEC_GROUP | SEC_EXCLUDE)) == SEC_EXCLUDE)
   2860     this_hdr->sh_flags |= SHF_EXCLUDE;
   2861 
   2862   /* If the section has relocs, set up a section header for the
   2863      SHT_REL[A] section.  If two relocation sections are required for
   2864      this section, it is up to the processor-specific back-end to
   2865      create the other.  */
   2866   if ((asect->flags & SEC_RELOC) != 0)
   2867     {
   2868       /* When doing a relocatable link, create both REL and RELA sections if
   2869 	 needed.  */
   2870       if (arg->link_info
   2871 	  /* Do the normal setup if we wouldn't create any sections here.  */
   2872 	  && esd->rel.count + esd->rela.count > 0
   2873 	  && (arg->link_info->relocatable || arg->link_info->emitrelocations))
   2874 	{
   2875 	  if (esd->rel.count && esd->rel.hdr == NULL
   2876 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rel, asect, FALSE))
   2877 	    {
   2878 	      arg->failed = TRUE;
   2879 	      return;
   2880 	    }
   2881 	  if (esd->rela.count && esd->rela.hdr == NULL
   2882 	      && !_bfd_elf_init_reloc_shdr (abfd, &esd->rela, asect, TRUE))
   2883 	    {
   2884 	      arg->failed = TRUE;
   2885 	      return;
   2886 	    }
   2887 	}
   2888       else if (!_bfd_elf_init_reloc_shdr (abfd,
   2889 					  (asect->use_rela_p
   2890 					   ? &esd->rela : &esd->rel),
   2891 					  asect,
   2892 					  asect->use_rela_p))
   2893 	  arg->failed = TRUE;
   2894     }
   2895 
   2896   /* Check for processor-specific section types.  */
   2897   sh_type = this_hdr->sh_type;
   2898   if (bed->elf_backend_fake_sections
   2899       && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
   2900     arg->failed = TRUE;
   2901 
   2902   if (sh_type == SHT_NOBITS && asect->size != 0)
   2903     {
   2904       /* Don't change the header type from NOBITS if we are being
   2905 	 called for objcopy --only-keep-debug.  */
   2906       this_hdr->sh_type = sh_type;
   2907     }
   2908 }
   2909 
   2910 /* Fill in the contents of a SHT_GROUP section.  Called from
   2911    _bfd_elf_compute_section_file_positions for gas, objcopy, and
   2912    when ELF targets use the generic linker, ld.  Called for ld -r
   2913    from bfd_elf_final_link.  */
   2914 
   2915 void
   2916 bfd_elf_set_group_contents (bfd *abfd, asection *sec, void *failedptrarg)
   2917 {
   2918   bfd_boolean *failedptr = (bfd_boolean *) failedptrarg;
   2919   asection *elt, *first;
   2920   unsigned char *loc;
   2921   bfd_boolean gas;
   2922 
   2923   /* Ignore linker created group section.  See elfNN_ia64_object_p in
   2924      elfxx-ia64.c.  */
   2925   if (((sec->flags & (SEC_GROUP | SEC_LINKER_CREATED)) != SEC_GROUP)
   2926       || *failedptr)
   2927     return;
   2928 
   2929   if (elf_section_data (sec)->this_hdr.sh_info == 0)
   2930     {
   2931       unsigned long symindx = 0;
   2932 
   2933       /* elf_group_id will have been set up by objcopy and the
   2934 	 generic linker.  */
   2935       if (elf_group_id (sec) != NULL)
   2936 	symindx = elf_group_id (sec)->udata.i;
   2937 
   2938       if (symindx == 0)
   2939 	{
   2940 	  /* If called from the assembler, swap_out_syms will have set up
   2941 	     elf_section_syms.  */
   2942 	  BFD_ASSERT (elf_section_syms (abfd) != NULL);
   2943 	  symindx = elf_section_syms (abfd)[sec->index]->udata.i;
   2944 	}
   2945       elf_section_data (sec)->this_hdr.sh_info = symindx;
   2946     }
   2947   else if (elf_section_data (sec)->this_hdr.sh_info == (unsigned int) -2)
   2948     {
   2949       /* The ELF backend linker sets sh_info to -2 when the group
   2950 	 signature symbol is global, and thus the index can't be
   2951 	 set until all local symbols are output.  */
   2952       asection *igroup = elf_sec_group (elf_next_in_group (sec));
   2953       struct bfd_elf_section_data *sec_data = elf_section_data (igroup);
   2954       unsigned long symndx = sec_data->this_hdr.sh_info;
   2955       unsigned long extsymoff = 0;
   2956       struct elf_link_hash_entry *h;
   2957 
   2958       if (!elf_bad_symtab (igroup->owner))
   2959 	{
   2960 	  Elf_Internal_Shdr *symtab_hdr;
   2961 
   2962 	  symtab_hdr = &elf_tdata (igroup->owner)->symtab_hdr;
   2963 	  extsymoff = symtab_hdr->sh_info;
   2964 	}
   2965       h = elf_sym_hashes (igroup->owner)[symndx - extsymoff];
   2966       while (h->root.type == bfd_link_hash_indirect
   2967 	     || h->root.type == bfd_link_hash_warning)
   2968 	h = (struct elf_link_hash_entry *) h->root.u.i.link;
   2969 
   2970       elf_section_data (sec)->this_hdr.sh_info = h->indx;
   2971     }
   2972 
   2973   /* The contents won't be allocated for "ld -r" or objcopy.  */
   2974   gas = TRUE;
   2975   if (sec->contents == NULL)
   2976     {
   2977       gas = FALSE;
   2978       sec->contents = (unsigned char *) bfd_alloc (abfd, sec->size);
   2979 
   2980       /* Arrange for the section to be written out.  */
   2981       elf_section_data (sec)->this_hdr.contents = sec->contents;
   2982       if (sec->contents == NULL)
   2983 	{
   2984 	  *failedptr = TRUE;
   2985 	  return;
   2986 	}
   2987     }
   2988 
   2989   loc = sec->contents + sec->size;
   2990 
   2991   /* Get the pointer to the first section in the group that gas
   2992      squirreled away here.  objcopy arranges for this to be set to the
   2993      start of the input section group.  */
   2994   first = elt = elf_next_in_group (sec);
   2995 
   2996   /* First element is a flag word.  Rest of section is elf section
   2997      indices for all the sections of the group.  Write them backwards
   2998      just to keep the group in the same order as given in .section
   2999      directives, not that it matters.  */
   3000   while (elt != NULL)
   3001     {
   3002       asection *s;
   3003 
   3004       s = elt;
   3005       if (!gas)
   3006 	s = s->output_section;
   3007       if (s != NULL
   3008 	  && !bfd_is_abs_section (s))
   3009 	{
   3010 	  unsigned int idx = elf_section_data (s)->this_idx;
   3011 
   3012 	  loc -= 4;
   3013 	  H_PUT_32 (abfd, idx, loc);
   3014 	}
   3015       elt = elf_next_in_group (elt);
   3016       if (elt == first)
   3017 	break;
   3018     }
   3019 
   3020   if ((loc -= 4) != sec->contents)
   3021     abort ();
   3022 
   3023   H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
   3024 }
   3025 
   3026 /* Assign all ELF section numbers.  The dummy first section is handled here
   3027    too.  The link/info pointers for the standard section types are filled
   3028    in here too, while we're at it.  */
   3029 
   3030 static bfd_boolean
   3031 assign_section_numbers (bfd *abfd, struct bfd_link_info *link_info)
   3032 {
   3033   struct elf_obj_tdata *t = elf_tdata (abfd);
   3034   asection *sec;
   3035   unsigned int section_number, secn;
   3036   Elf_Internal_Shdr **i_shdrp;
   3037   struct bfd_elf_section_data *d;
   3038   bfd_boolean need_symtab;
   3039 
   3040   section_number = 1;
   3041 
   3042   _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
   3043 
   3044   /* SHT_GROUP sections are in relocatable files only.  */
   3045   if (link_info == NULL || link_info->relocatable)
   3046     {
   3047       /* Put SHT_GROUP sections first.  */
   3048       for (sec = abfd->sections; sec != NULL; sec = sec->next)
   3049 	{
   3050 	  d = elf_section_data (sec);
   3051 
   3052 	  if (d->this_hdr.sh_type == SHT_GROUP)
   3053 	    {
   3054 	      if (sec->flags & SEC_LINKER_CREATED)
   3055 		{
   3056 		  /* Remove the linker created SHT_GROUP sections.  */
   3057 		  bfd_section_list_remove (abfd, sec);
   3058 		  abfd->section_count--;
   3059 		}
   3060 	      else
   3061 		d->this_idx = section_number++;
   3062 	    }
   3063 	}
   3064     }
   3065 
   3066   for (sec = abfd->sections; sec; sec = sec->next)
   3067     {
   3068       d = elf_section_data (sec);
   3069 
   3070       if (d->this_hdr.sh_type != SHT_GROUP)
   3071 	d->this_idx = section_number++;
   3072       _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
   3073       if (d->rel.hdr)
   3074 	{
   3075 	  d->rel.idx = section_number++;
   3076 	  _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel.hdr->sh_name);
   3077 	}
   3078       else
   3079 	d->rel.idx = 0;
   3080 
   3081       if (d->rela.hdr)
   3082 	{
   3083 	  d->rela.idx = section_number++;
   3084 	  _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rela.hdr->sh_name);
   3085 	}
   3086       else
   3087 	d->rela.idx = 0;
   3088     }
   3089 
   3090   elf_shstrtab_sec (abfd) = section_number++;
   3091   _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
   3092   elf_elfheader (abfd)->e_shstrndx = elf_shstrtab_sec (abfd);
   3093 
   3094   need_symtab = (bfd_get_symcount (abfd) > 0
   3095 		|| (link_info == NULL
   3096 		    && ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
   3097 			== HAS_RELOC)));
   3098   if (need_symtab)
   3099     {
   3100       elf_onesymtab (abfd) = section_number++;
   3101       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
   3102       if (section_number > ((SHN_LORESERVE - 2) & 0xFFFF))
   3103 	{
   3104 	  elf_symtab_shndx (abfd) = section_number++;
   3105 	  t->symtab_shndx_hdr.sh_name
   3106 	    = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
   3107 						  ".symtab_shndx", FALSE);
   3108 	  if (t->symtab_shndx_hdr.sh_name == (unsigned int) -1)
   3109 	    return FALSE;
   3110 	}
   3111       elf_strtab_sec (abfd) = section_number++;
   3112       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
   3113     }
   3114 
   3115   if (section_number >= SHN_LORESERVE)
   3116     {
   3117       _bfd_error_handler (_("%B: too many sections: %u"),
   3118 			  abfd, section_number);
   3119       return FALSE;
   3120     }
   3121 
   3122   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
   3123   t->shstrtab_hdr.sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
   3124 
   3125   elf_numsections (abfd) = section_number;
   3126   elf_elfheader (abfd)->e_shnum = section_number;
   3127 
   3128   /* Set up the list of section header pointers, in agreement with the
   3129      indices.  */
   3130   i_shdrp = (Elf_Internal_Shdr **) bfd_zalloc2 (abfd, section_number,
   3131                                                 sizeof (Elf_Internal_Shdr *));
   3132   if (i_shdrp == NULL)
   3133     return FALSE;
   3134 
   3135   i_shdrp[0] = (Elf_Internal_Shdr *) bfd_zalloc (abfd,
   3136                                                  sizeof (Elf_Internal_Shdr));
   3137   if (i_shdrp[0] == NULL)
   3138     {
   3139       bfd_release (abfd, i_shdrp);
   3140       return FALSE;
   3141     }
   3142 
   3143   elf_elfsections (abfd) = i_shdrp;
   3144 
   3145   i_shdrp[elf_shstrtab_sec (abfd)] = &t->shstrtab_hdr;
   3146   if (need_symtab)
   3147     {
   3148       i_shdrp[elf_onesymtab (abfd)] = &t->symtab_hdr;
   3149       if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
   3150 	{
   3151 	  i_shdrp[elf_symtab_shndx (abfd)] = &t->symtab_shndx_hdr;
   3152 	  t->symtab_shndx_hdr.sh_link = elf_onesymtab (abfd);
   3153 	}
   3154       i_shdrp[elf_strtab_sec (abfd)] = &t->strtab_hdr;
   3155       t->symtab_hdr.sh_link = elf_strtab_sec (abfd);
   3156     }
   3157 
   3158   for (sec = abfd->sections; sec; sec = sec->next)
   3159     {
   3160       asection *s;
   3161       const char *name;
   3162 
   3163       d = elf_section_data (sec);
   3164 
   3165       i_shdrp[d->this_idx] = &d->this_hdr;
   3166       if (d->rel.idx != 0)
   3167 	i_shdrp[d->rel.idx] = d->rel.hdr;
   3168       if (d->rela.idx != 0)
   3169 	i_shdrp[d->rela.idx] = d->rela.hdr;
   3170 
   3171       /* Fill in the sh_link and sh_info fields while we're at it.  */
   3172 
   3173       /* sh_link of a reloc section is the section index of the symbol
   3174 	 table.  sh_info is the section index of the section to which
   3175 	 the relocation entries apply.  */
   3176       if (d->rel.idx != 0)
   3177 	{
   3178 	  d->rel.hdr->sh_link = elf_onesymtab (abfd);
   3179 	  d->rel.hdr->sh_info = d->this_idx;
   3180 	  d->rel.hdr->sh_flags |= SHF_INFO_LINK;
   3181 	}
   3182       if (d->rela.idx != 0)
   3183 	{
   3184 	  d->rela.hdr->sh_link = elf_onesymtab (abfd);
   3185 	  d->rela.hdr->sh_info = d->this_idx;
   3186 	  d->rela.hdr->sh_flags |= SHF_INFO_LINK;
   3187 	}
   3188 
   3189       /* We need to set up sh_link for SHF_LINK_ORDER.  */
   3190       if ((d->this_hdr.sh_flags & SHF_LINK_ORDER) != 0)
   3191 	{
   3192 	  s = elf_linked_to_section (sec);
   3193 	  if (s)
   3194 	    {
   3195 	      /* elf_linked_to_section points to the input section.  */
   3196 	      if (link_info != NULL)
   3197 		{
   3198 		  /* Check discarded linkonce section.  */
   3199 		  if (discarded_section (s))
   3200 		    {
   3201 		      asection *kept;
   3202 		      (*_bfd_error_handler)
   3203 			(_("%B: sh_link of section `%A' points to discarded section `%A' of `%B'"),
   3204 			 abfd, d->this_hdr.bfd_section,
   3205 			 s, s->owner);
   3206 		      /* Point to the kept section if it has the same
   3207 			 size as the discarded one.  */
   3208 		      kept = _bfd_elf_check_kept_section (s, link_info);
   3209 		      if (kept == NULL)
   3210 			{
   3211 			  bfd_set_error (bfd_error_bad_value);
   3212 			  return FALSE;
   3213 			}
   3214 		      s = kept;
   3215 		    }
   3216 
   3217 		  s = s->output_section;
   3218 		  BFD_ASSERT (s != NULL);
   3219 		}
   3220 	      else
   3221 		{
   3222 		  /* Handle objcopy. */
   3223 		  if (s->output_section == NULL)
   3224 		    {
   3225 		      (*_bfd_error_handler)
   3226 			(_("%B: sh_link of section `%A' points to removed section `%A' of `%B'"),
   3227 			 abfd, d->this_hdr.bfd_section, s, s->owner);
   3228 		      bfd_set_error (bfd_error_bad_value);
   3229 		      return FALSE;
   3230 		    }
   3231 		  s = s->output_section;
   3232 		}
   3233 	      d->this_hdr.sh_link = elf_section_data (s)->this_idx;
   3234 	    }
   3235 	  else
   3236 	    {
   3237 	      /* PR 290:
   3238 		 The Intel C compiler generates SHT_IA_64_UNWIND with
   3239 		 SHF_LINK_ORDER.  But it doesn't set the sh_link or
   3240 		 sh_info fields.  Hence we could get the situation
   3241 		 where s is NULL.  */
   3242 	      const struct elf_backend_data *bed
   3243 		= get_elf_backend_data (abfd);
   3244 	      if (bed->link_order_error_handler)
   3245 		bed->link_order_error_handler
   3246 		  (_("%B: warning: sh_link not set for section `%A'"),
   3247 		   abfd, sec);
   3248 	    }
   3249 	}
   3250 
   3251       switch (d->this_hdr.sh_type)
   3252 	{
   3253 	case SHT_REL:
   3254 	case SHT_RELA:
   3255 	  /* A reloc section which we are treating as a normal BFD
   3256 	     section.  sh_link is the section index of the symbol
   3257 	     table.  sh_info is the section index of the section to
   3258 	     which the relocation entries apply.  We assume that an
   3259 	     allocated reloc section uses the dynamic symbol table.
   3260 	     FIXME: How can we be sure?  */
   3261 	  s = bfd_get_section_by_name (abfd, ".dynsym");
   3262 	  if (s != NULL)
   3263 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
   3264 
   3265 	  /* We look up the section the relocs apply to by name.  */
   3266 	  name = sec->name;
   3267 	  if (d->this_hdr.sh_type == SHT_REL)
   3268 	    name += 4;
   3269 	  else
   3270 	    name += 5;
   3271 	  s = bfd_get_section_by_name (abfd, name);
   3272 	  if (s != NULL)
   3273 	    {
   3274 	      d->this_hdr.sh_info = elf_section_data (s)->this_idx;
   3275 	      d->this_hdr.sh_flags |= SHF_INFO_LINK;
   3276 	    }
   3277 	  break;
   3278 
   3279 	case SHT_STRTAB:
   3280 	  /* We assume that a section named .stab*str is a stabs
   3281 	     string section.  We look for a section with the same name
   3282 	     but without the trailing ``str'', and set its sh_link
   3283 	     field to point to this section.  */
   3284 	  if (CONST_STRNEQ (sec->name, ".stab")
   3285 	      && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
   3286 	    {
   3287 	      size_t len;
   3288 	      char *alc;
   3289 
   3290 	      len = strlen (sec->name);
   3291 	      alc = (char *) bfd_malloc (len - 2);
   3292 	      if (alc == NULL)
   3293 		return FALSE;
   3294 	      memcpy (alc, sec->name, len - 3);
   3295 	      alc[len - 3] = '\0';
   3296 	      s = bfd_get_section_by_name (abfd, alc);
   3297 	      free (alc);
   3298 	      if (s != NULL)
   3299 		{
   3300 		  elf_section_data (s)->this_hdr.sh_link = d->this_idx;
   3301 
   3302 		  /* This is a .stab section.  */
   3303 		  if (elf_section_data (s)->this_hdr.sh_entsize == 0)
   3304 		    elf_section_data (s)->this_hdr.sh_entsize
   3305 		      = 4 + 2 * bfd_get_arch_size (abfd) / 8;
   3306 		}
   3307 	    }
   3308 	  break;
   3309 
   3310 	case SHT_DYNAMIC:
   3311 	case SHT_DYNSYM:
   3312 	case SHT_GNU_verneed:
   3313 	case SHT_GNU_verdef:
   3314 	  /* sh_link is the section header index of the string table
   3315 	     used for the dynamic entries, or the symbol table, or the
   3316 	     version strings.  */
   3317 	  s = bfd_get_section_by_name (abfd, ".dynstr");
   3318 	  if (s != NULL)
   3319 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
   3320 	  break;
   3321 
   3322 	case SHT_GNU_LIBLIST:
   3323 	  /* sh_link is the section header index of the prelink library
   3324 	     list used for the dynamic entries, or the symbol table, or
   3325 	     the version strings.  */
   3326 	  s = bfd_get_section_by_name (abfd, (sec->flags & SEC_ALLOC)
   3327 					     ? ".dynstr" : ".gnu.libstr");
   3328 	  if (s != NULL)
   3329 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
   3330 	  break;
   3331 
   3332 	case SHT_HASH:
   3333 	case SHT_GNU_HASH:
   3334 	case SHT_GNU_versym:
   3335 	  /* sh_link is the section header index of the symbol table
   3336 	     this hash table or version table is for.  */
   3337 	  s = bfd_get_section_by_name (abfd, ".dynsym");
   3338 	  if (s != NULL)
   3339 	    d->this_hdr.sh_link = elf_section_data (s)->this_idx;
   3340 	  break;
   3341 
   3342 	case SHT_GROUP:
   3343 	  d->this_hdr.sh_link = elf_onesymtab (abfd);
   3344 	}
   3345     }
   3346 
   3347   for (secn = 1; secn < section_number; ++secn)
   3348     if (i_shdrp[secn] == NULL)
   3349       i_shdrp[secn] = i_shdrp[0];
   3350     else
   3351       i_shdrp[secn]->sh_name = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
   3352 						       i_shdrp[secn]->sh_name);
   3353   return TRUE;
   3354 }
   3355 
   3356 static bfd_boolean
   3357 sym_is_global (bfd *abfd, asymbol *sym)
   3358 {
   3359   /* If the backend has a special mapping, use it.  */
   3360   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   3361   if (bed->elf_backend_sym_is_global)
   3362     return (*bed->elf_backend_sym_is_global) (abfd, sym);
   3363 
   3364   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK | BSF_GNU_UNIQUE)) != 0
   3365 	  || bfd_is_und_section (bfd_get_section (sym))
   3366 	  || bfd_is_com_section (bfd_get_section (sym)));
   3367 }
   3368 
   3369 /* Don't output section symbols for sections that are not going to be
   3370    output, that are duplicates or there is no BFD section.  */
   3371 
   3372 static bfd_boolean
   3373 ignore_section_sym (bfd *abfd, asymbol *sym)
   3374 {
   3375   elf_symbol_type *type_ptr;
   3376 
   3377   if ((sym->flags & BSF_SECTION_SYM) == 0)
   3378     return FALSE;
   3379 
   3380   type_ptr = elf_symbol_from (abfd, sym);
   3381   return ((type_ptr != NULL
   3382 	   && type_ptr->internal_elf_sym.st_shndx != 0
   3383 	   && bfd_is_abs_section (sym->section))
   3384 	  || !(sym->section->owner == abfd
   3385 	       || (sym->section->output_section->owner == abfd
   3386 		   && sym->section->output_offset == 0)
   3387 	       || bfd_is_abs_section (sym->section)));
   3388 }
   3389 
   3390 /* Map symbol from it's internal number to the external number, moving
   3391    all local symbols to be at the head of the list.  */
   3392 
   3393 static bfd_boolean
   3394 elf_map_symbols (bfd *abfd, unsigned int *pnum_locals)
   3395 {
   3396   unsigned int symcount = bfd_get_symcount (abfd);
   3397   asymbol **syms = bfd_get_outsymbols (abfd);
   3398   asymbol **sect_syms;
   3399   unsigned int num_locals = 0;
   3400   unsigned int num_globals = 0;
   3401   unsigned int num_locals2 = 0;
   3402   unsigned int num_globals2 = 0;
   3403   int max_index = 0;
   3404   unsigned int idx;
   3405   asection *asect;
   3406   asymbol **new_syms;
   3407 
   3408 #ifdef DEBUG
   3409   fprintf (stderr, "elf_map_symbols\n");
   3410   fflush (stderr);
   3411 #endif
   3412 
   3413   for (asect = abfd->sections; asect; asect = asect->next)
   3414     {
   3415       if (max_index < asect->index)
   3416 	max_index = asect->index;
   3417     }
   3418 
   3419   max_index++;
   3420   sect_syms = (asymbol **) bfd_zalloc2 (abfd, max_index, sizeof (asymbol *));
   3421   if (sect_syms == NULL)
   3422     return FALSE;
   3423   elf_section_syms (abfd) = sect_syms;
   3424   elf_num_section_syms (abfd) = max_index;
   3425 
   3426   /* Init sect_syms entries for any section symbols we have already
   3427      decided to output.  */
   3428   for (idx = 0; idx < symcount; idx++)
   3429     {
   3430       asymbol *sym = syms[idx];
   3431 
   3432       if ((sym->flags & BSF_SECTION_SYM) != 0
   3433 	  && sym->value == 0
   3434 	  && !ignore_section_sym (abfd, sym)
   3435 	  && !bfd_is_abs_section (sym->section))
   3436 	{
   3437 	  asection *sec = sym->section;
   3438 
   3439 	  if (sec->owner != abfd)
   3440 	    sec = sec->output_section;
   3441 
   3442 	  sect_syms[sec->index] = syms[idx];
   3443 	}
   3444     }
   3445 
   3446   /* Classify all of the symbols.  */
   3447   for (idx = 0; idx < symcount; idx++)
   3448     {
   3449       if (sym_is_global (abfd, syms[idx]))
   3450 	num_globals++;
   3451       else if (!ignore_section_sym (abfd, syms[idx]))
   3452 	num_locals++;
   3453     }
   3454 
   3455   /* We will be adding a section symbol for each normal BFD section.  Most
   3456      sections will already have a section symbol in outsymbols, but
   3457      eg. SHT_GROUP sections will not, and we need the section symbol mapped
   3458      at least in that case.  */
   3459   for (asect = abfd->sections; asect; asect = asect->next)
   3460     {
   3461       if (sect_syms[asect->index] == NULL)
   3462 	{
   3463 	  if (!sym_is_global (abfd, asect->symbol))
   3464 	    num_locals++;
   3465 	  else
   3466 	    num_globals++;
   3467 	}
   3468     }
   3469 
   3470   /* Now sort the symbols so the local symbols are first.  */
   3471   new_syms = (asymbol **) bfd_alloc2 (abfd, num_locals + num_globals,
   3472                                       sizeof (asymbol *));
   3473 
   3474   if (new_syms == NULL)
   3475     return FALSE;
   3476 
   3477   for (idx = 0; idx < symcount; idx++)
   3478     {
   3479       asymbol *sym = syms[idx];
   3480       unsigned int i;
   3481 
   3482       if (sym_is_global (abfd, sym))
   3483 	i = num_locals + num_globals2++;
   3484       else if (!ignore_section_sym (abfd, sym))
   3485 	i = num_locals2++;
   3486       else
   3487 	continue;
   3488       new_syms[i] = sym;
   3489       sym->udata.i = i + 1;
   3490     }
   3491   for (asect = abfd->sections; asect; asect = asect->next)
   3492     {
   3493       if (sect_syms[asect->index] == NULL)
   3494 	{
   3495 	  asymbol *sym = asect->symbol;
   3496 	  unsigned int i;
   3497 
   3498 	  sect_syms[asect->index] = sym;
   3499 	  if (!sym_is_global (abfd, sym))
   3500 	    i = num_locals2++;
   3501 	  else
   3502 	    i = num_locals + num_globals2++;
   3503 	  new_syms[i] = sym;
   3504 	  sym->udata.i = i + 1;
   3505 	}
   3506     }
   3507 
   3508   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
   3509 
   3510   *pnum_locals = num_locals;
   3511   return TRUE;
   3512 }
   3513 
   3514 /* Align to the maximum file alignment that could be required for any
   3515    ELF data structure.  */
   3516 
   3517 static inline file_ptr
   3518 align_file_position (file_ptr off, int align)
   3519 {
   3520   return (off + align - 1) & ~(align - 1);
   3521 }
   3522 
   3523 /* Assign a file position to a section, optionally aligning to the
   3524    required section alignment.  */
   3525 
   3526 file_ptr
   3527 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
   3528 					   file_ptr offset,
   3529 					   bfd_boolean align)
   3530 {
   3531   if (align && i_shdrp->sh_addralign > 1)
   3532     offset = BFD_ALIGN (offset, i_shdrp->sh_addralign);
   3533   i_shdrp->sh_offset = offset;
   3534   if (i_shdrp->bfd_section != NULL)
   3535     i_shdrp->bfd_section->filepos = offset;
   3536   if (i_shdrp->sh_type != SHT_NOBITS)
   3537     offset += i_shdrp->sh_size;
   3538   return offset;
   3539 }
   3540 
   3541 /* Compute the file positions we are going to put the sections at, and
   3542    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
   3543    is not NULL, this is being called by the ELF backend linker.  */
   3544 
   3545 bfd_boolean
   3546 _bfd_elf_compute_section_file_positions (bfd *abfd,
   3547 					 struct bfd_link_info *link_info)
   3548 {
   3549   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   3550   struct fake_section_arg fsargs;
   3551   bfd_boolean failed;
   3552   struct bfd_strtab_hash *strtab = NULL;
   3553   Elf_Internal_Shdr *shstrtab_hdr;
   3554   bfd_boolean need_symtab;
   3555 
   3556   if (abfd->output_has_begun)
   3557     return TRUE;
   3558 
   3559   /* Do any elf backend specific processing first.  */
   3560   if (bed->elf_backend_begin_write_processing)
   3561     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
   3562 
   3563   if (! prep_headers (abfd))
   3564     return FALSE;
   3565 
   3566   /* Post process the headers if necessary.  */
   3567   (*bed->elf_backend_post_process_headers) (abfd, link_info);
   3568 
   3569   fsargs.failed = FALSE;
   3570   fsargs.link_info = link_info;
   3571   bfd_map_over_sections (abfd, elf_fake_sections, &fsargs);
   3572   if (fsargs.failed)
   3573     return FALSE;
   3574 
   3575   if (!assign_section_numbers (abfd, link_info))
   3576     return FALSE;
   3577 
   3578   /* The backend linker builds symbol table information itself.  */
   3579   need_symtab = (link_info == NULL
   3580 		 && (bfd_get_symcount (abfd) > 0
   3581 		     || ((abfd->flags & (EXEC_P | DYNAMIC | HAS_RELOC))
   3582 			 == HAS_RELOC)));
   3583   if (need_symtab)
   3584     {
   3585       /* Non-zero if doing a relocatable link.  */
   3586       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
   3587 
   3588       if (! swap_out_syms (abfd, &strtab, relocatable_p))
   3589 	return FALSE;
   3590     }
   3591 
   3592   failed = FALSE;
   3593   if (link_info == NULL)
   3594     {
   3595       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
   3596       if (failed)
   3597 	return FALSE;
   3598     }
   3599 
   3600   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
   3601   /* sh_name was set in prep_headers.  */
   3602   shstrtab_hdr->sh_type = SHT_STRTAB;
   3603   shstrtab_hdr->sh_flags = 0;
   3604   shstrtab_hdr->sh_addr = 0;
   3605   shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
   3606   shstrtab_hdr->sh_entsize = 0;
   3607   shstrtab_hdr->sh_link = 0;
   3608   shstrtab_hdr->sh_info = 0;
   3609   /* sh_offset is set in assign_file_positions_except_relocs.  */
   3610   shstrtab_hdr->sh_addralign = 1;
   3611 
   3612   if (!assign_file_positions_except_relocs (abfd, link_info))
   3613     return FALSE;
   3614 
   3615   if (need_symtab)
   3616     {
   3617       file_ptr off;
   3618       Elf_Internal_Shdr *hdr;
   3619 
   3620       off = elf_next_file_pos (abfd);
   3621 
   3622       hdr = &elf_tdata (abfd)->symtab_hdr;
   3623       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
   3624 
   3625       hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
   3626       if (hdr->sh_size != 0)
   3627 	off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
   3628 
   3629       hdr = &elf_tdata (abfd)->strtab_hdr;
   3630       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
   3631 
   3632       elf_next_file_pos (abfd) = off;
   3633 
   3634       /* Now that we know where the .strtab section goes, write it
   3635 	 out.  */
   3636       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
   3637 	  || ! _bfd_stringtab_emit (abfd, strtab))
   3638 	return FALSE;
   3639       _bfd_stringtab_free (strtab);
   3640     }
   3641 
   3642   abfd->output_has_begun = TRUE;
   3643 
   3644   return TRUE;
   3645 }
   3646 
   3647 /* Make an initial estimate of the size of the program header.  If we
   3648    get the number wrong here, we'll redo section placement.  */
   3649 
   3650 static bfd_size_type
   3651 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
   3652 {
   3653   size_t segs;
   3654   asection *s;
   3655   const struct elf_backend_data *bed;
   3656 
   3657   /* Assume we will need exactly two PT_LOAD segments: one for text
   3658      and one for data.  */
   3659   segs = 2;
   3660 
   3661   s = bfd_get_section_by_name (abfd, ".interp");
   3662   if (s != NULL && (s->flags & SEC_LOAD) != 0)
   3663     {
   3664       /* If we have a loadable interpreter section, we need a
   3665 	 PT_INTERP segment.  In this case, assume we also need a
   3666 	 PT_PHDR segment, although that may not be true for all
   3667 	 targets.  */
   3668       segs += 2;
   3669     }
   3670 
   3671   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
   3672     {
   3673       /* We need a PT_DYNAMIC segment.  */
   3674       ++segs;
   3675     }
   3676 
   3677   if (info != NULL && info->relro)
   3678     {
   3679       /* We need a PT_GNU_RELRO segment.  */
   3680       ++segs;
   3681     }
   3682 
   3683   if (elf_eh_frame_hdr (abfd))
   3684     {
   3685       /* We need a PT_GNU_EH_FRAME segment.  */
   3686       ++segs;
   3687     }
   3688 
   3689   if (elf_stack_flags (abfd))
   3690     {
   3691       /* We need a PT_GNU_STACK segment.  */
   3692       ++segs;
   3693     }
   3694 
   3695   for (s = abfd->sections; s != NULL; s = s->next)
   3696     {
   3697       if ((s->flags & SEC_LOAD) != 0
   3698 	  && CONST_STRNEQ (s->name, ".note"))
   3699 	{
   3700 	  /* We need a PT_NOTE segment.  */
   3701 	  ++segs;
   3702 	  /* Try to create just one PT_NOTE segment
   3703 	     for all adjacent loadable .note* sections.
   3704 	     gABI requires that within a PT_NOTE segment
   3705 	     (and also inside of each SHT_NOTE section)
   3706 	     each note is padded to a multiple of 4 size,
   3707 	     so we check whether the sections are correctly
   3708 	     aligned.  */
   3709 	  if (s->alignment_power == 2)
   3710 	    while (s->next != NULL
   3711 		   && s->next->alignment_power == 2
   3712 		   && (s->next->flags & SEC_LOAD) != 0
   3713 		   && CONST_STRNEQ (s->next->name, ".note"))
   3714 	      s = s->next;
   3715 	}
   3716     }
   3717 
   3718   for (s = abfd->sections; s != NULL; s = s->next)
   3719     {
   3720       if (s->flags & SEC_THREAD_LOCAL)
   3721 	{
   3722 	  /* We need a PT_TLS segment.  */
   3723 	  ++segs;
   3724 	  break;
   3725 	}
   3726     }
   3727 
   3728   /* Let the backend count up any program headers it might need.  */
   3729   bed = get_elf_backend_data (abfd);
   3730   if (bed->elf_backend_additional_program_headers)
   3731     {
   3732       int a;
   3733 
   3734       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
   3735       if (a == -1)
   3736 	abort ();
   3737       segs += a;
   3738     }
   3739 
   3740   return segs * bed->s->sizeof_phdr;
   3741 }
   3742 
   3743 /* Find the segment that contains the output_section of section.  */
   3744 
   3745 Elf_Internal_Phdr *
   3746 _bfd_elf_find_segment_containing_section (bfd * abfd, asection * section)
   3747 {
   3748   struct elf_segment_map *m;
   3749   Elf_Internal_Phdr *p;
   3750 
   3751   for (m = elf_seg_map (abfd), p = elf_tdata (abfd)->phdr;
   3752        m != NULL;
   3753        m = m->next, p++)
   3754     {
   3755       int i;
   3756 
   3757       for (i = m->count - 1; i >= 0; i--)
   3758 	if (m->sections[i] == section)
   3759 	  return p;
   3760     }
   3761 
   3762   return NULL;
   3763 }
   3764 
   3765 /* Create a mapping from a set of sections to a program segment.  */
   3766 
   3767 static struct elf_segment_map *
   3768 make_mapping (bfd *abfd,
   3769 	      asection **sections,
   3770 	      unsigned int from,
   3771 	      unsigned int to,
   3772 	      bfd_boolean phdr)
   3773 {
   3774   struct elf_segment_map *m;
   3775   unsigned int i;
   3776   asection **hdrpp;
   3777   bfd_size_type amt;
   3778 
   3779   amt = sizeof (struct elf_segment_map);
   3780   amt += (to - from - 1) * sizeof (asection *);
   3781   m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   3782   if (m == NULL)
   3783     return NULL;
   3784   m->next = NULL;
   3785   m->p_type = PT_LOAD;
   3786   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
   3787     m->sections[i - from] = *hdrpp;
   3788   m->count = to - from;
   3789 
   3790   if (from == 0 && phdr)
   3791     {
   3792       /* Include the headers in the first PT_LOAD segment.  */
   3793       m->includes_filehdr = 1;
   3794       m->includes_phdrs = 1;
   3795     }
   3796 
   3797   return m;
   3798 }
   3799 
   3800 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
   3801    on failure.  */
   3802 
   3803 struct elf_segment_map *
   3804 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
   3805 {
   3806   struct elf_segment_map *m;
   3807 
   3808   m = (struct elf_segment_map *) bfd_zalloc (abfd,
   3809                                              sizeof (struct elf_segment_map));
   3810   if (m == NULL)
   3811     return NULL;
   3812   m->next = NULL;
   3813   m->p_type = PT_DYNAMIC;
   3814   m->count = 1;
   3815   m->sections[0] = dynsec;
   3816 
   3817   return m;
   3818 }
   3819 
   3820 /* Possibly add or remove segments from the segment map.  */
   3821 
   3822 static bfd_boolean
   3823 elf_modify_segment_map (bfd *abfd,
   3824 			struct bfd_link_info *info,
   3825 			bfd_boolean remove_empty_load)
   3826 {
   3827   struct elf_segment_map **m;
   3828   const struct elf_backend_data *bed;
   3829 
   3830   /* The placement algorithm assumes that non allocated sections are
   3831      not in PT_LOAD segments.  We ensure this here by removing such
   3832      sections from the segment map.  We also remove excluded
   3833      sections.  Finally, any PT_LOAD segment without sections is
   3834      removed.  */
   3835   m = &elf_seg_map (abfd);
   3836   while (*m)
   3837     {
   3838       unsigned int i, new_count;
   3839 
   3840       for (new_count = 0, i = 0; i < (*m)->count; i++)
   3841 	{
   3842 	  if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
   3843 	      && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
   3844 		  || (*m)->p_type != PT_LOAD))
   3845 	    {
   3846 	      (*m)->sections[new_count] = (*m)->sections[i];
   3847 	      new_count++;
   3848 	    }
   3849 	}
   3850       (*m)->count = new_count;
   3851 
   3852       if (remove_empty_load && (*m)->p_type == PT_LOAD && (*m)->count == 0)
   3853 	*m = (*m)->next;
   3854       else
   3855 	m = &(*m)->next;
   3856     }
   3857 
   3858   bed = get_elf_backend_data (abfd);
   3859   if (bed->elf_backend_modify_segment_map != NULL)
   3860     {
   3861       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
   3862 	return FALSE;
   3863     }
   3864 
   3865   return TRUE;
   3866 }
   3867 
   3868 /* Set up a mapping from BFD sections to program segments.  */
   3869 
   3870 bfd_boolean
   3871 _bfd_elf_map_sections_to_segments (bfd *abfd, struct bfd_link_info *info)
   3872 {
   3873   unsigned int count;
   3874   struct elf_segment_map *m;
   3875   asection **sections = NULL;
   3876   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   3877   bfd_boolean no_user_phdrs;
   3878 
   3879   no_user_phdrs = elf_seg_map (abfd) == NULL;
   3880 
   3881   if (info != NULL)
   3882     info->user_phdrs = !no_user_phdrs;
   3883 
   3884   if (no_user_phdrs && bfd_count_sections (abfd) != 0)
   3885     {
   3886       asection *s;
   3887       unsigned int i;
   3888       struct elf_segment_map *mfirst;
   3889       struct elf_segment_map **pm;
   3890       asection *last_hdr;
   3891       bfd_vma last_size;
   3892       unsigned int phdr_index;
   3893       bfd_vma maxpagesize;
   3894       asection **hdrpp;
   3895       bfd_boolean phdr_in_segment = TRUE;
   3896       bfd_boolean writable;
   3897       int tls_count = 0;
   3898       asection *first_tls = NULL;
   3899       asection *dynsec, *eh_frame_hdr;
   3900       bfd_size_type amt;
   3901       bfd_vma addr_mask, wrap_to = 0;
   3902 
   3903       /* Select the allocated sections, and sort them.  */
   3904 
   3905       sections = (asection **) bfd_malloc2 (bfd_count_sections (abfd),
   3906                                             sizeof (asection *));
   3907       if (sections == NULL)
   3908 	goto error_return;
   3909 
   3910       /* Calculate top address, avoiding undefined behaviour of shift
   3911 	 left operator when shift count is equal to size of type
   3912 	 being shifted.  */
   3913       addr_mask = ((bfd_vma) 1 << (bfd_arch_bits_per_address (abfd) - 1)) - 1;
   3914       addr_mask = (addr_mask << 1) + 1;
   3915 
   3916       i = 0;
   3917       for (s = abfd->sections; s != NULL; s = s->next)
   3918 	{
   3919 	  if ((s->flags & SEC_ALLOC) != 0)
   3920 	    {
   3921 	      sections[i] = s;
   3922 	      ++i;
   3923 	      /* A wrapping section potentially clashes with header.  */
   3924 	      if (((s->lma + s->size) & addr_mask) < (s->lma & addr_mask))
   3925 		wrap_to = (s->lma + s->size) & addr_mask;
   3926 	    }
   3927 	}
   3928       BFD_ASSERT (i <= bfd_count_sections (abfd));
   3929       count = i;
   3930 
   3931       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
   3932 
   3933       /* Build the mapping.  */
   3934 
   3935       mfirst = NULL;
   3936       pm = &mfirst;
   3937 
   3938       /* If we have a .interp section, then create a PT_PHDR segment for
   3939 	 the program headers and a PT_INTERP segment for the .interp
   3940 	 section.  */
   3941       s = bfd_get_section_by_name (abfd, ".interp");
   3942       if (s != NULL && (s->flags & SEC_LOAD) != 0)
   3943 	{
   3944 	  amt = sizeof (struct elf_segment_map);
   3945 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   3946 	  if (m == NULL)
   3947 	    goto error_return;
   3948 	  m->next = NULL;
   3949 	  m->p_type = PT_PHDR;
   3950 	  /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
   3951 	  m->p_flags = PF_R | PF_X;
   3952 	  m->p_flags_valid = 1;
   3953 	  m->includes_phdrs = 1;
   3954 
   3955 	  *pm = m;
   3956 	  pm = &m->next;
   3957 
   3958 	  amt = sizeof (struct elf_segment_map);
   3959 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   3960 	  if (m == NULL)
   3961 	    goto error_return;
   3962 	  m->next = NULL;
   3963 	  m->p_type = PT_INTERP;
   3964 	  m->count = 1;
   3965 	  m->sections[0] = s;
   3966 
   3967 	  *pm = m;
   3968 	  pm = &m->next;
   3969 	}
   3970 
   3971       /* Look through the sections.  We put sections in the same program
   3972 	 segment when the start of the second section can be placed within
   3973 	 a few bytes of the end of the first section.  */
   3974       last_hdr = NULL;
   3975       last_size = 0;
   3976       phdr_index = 0;
   3977       maxpagesize = bed->maxpagesize;
   3978       writable = FALSE;
   3979       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
   3980       if (dynsec != NULL
   3981 	  && (dynsec->flags & SEC_LOAD) == 0)
   3982 	dynsec = NULL;
   3983 
   3984       /* Deal with -Ttext or something similar such that the first section
   3985 	 is not adjacent to the program headers.  This is an
   3986 	 approximation, since at this point we don't know exactly how many
   3987 	 program headers we will need.  */
   3988       if (count > 0)
   3989 	{
   3990 	  bfd_size_type phdr_size = elf_program_header_size (abfd);
   3991 
   3992 	  if (phdr_size == (bfd_size_type) -1)
   3993 	    phdr_size = get_program_header_size (abfd, info);
   3994 	  phdr_size += bed->s->sizeof_ehdr;
   3995 	  if ((abfd->flags & D_PAGED) == 0
   3996 	      || (sections[0]->lma & addr_mask) < phdr_size
   3997 	      || ((sections[0]->lma & addr_mask) % maxpagesize
   3998 		  < phdr_size % maxpagesize)
   3999 	      || (sections[0]->lma & addr_mask & -maxpagesize) < wrap_to)
   4000 	    phdr_in_segment = FALSE;
   4001 	}
   4002 
   4003       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
   4004 	{
   4005 	  asection *hdr;
   4006 	  bfd_boolean new_segment;
   4007 
   4008 	  hdr = *hdrpp;
   4009 
   4010 	  /* See if this section and the last one will fit in the same
   4011 	     segment.  */
   4012 
   4013 	  if (last_hdr == NULL)
   4014 	    {
   4015 	      /* If we don't have a segment yet, then we don't need a new
   4016 		 one (we build the last one after this loop).  */
   4017 	      new_segment = FALSE;
   4018 	    }
   4019 	  else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
   4020 	    {
   4021 	      /* If this section has a different relation between the
   4022 		 virtual address and the load address, then we need a new
   4023 		 segment.  */
   4024 	      new_segment = TRUE;
   4025 	    }
   4026 	  else if (hdr->lma < last_hdr->lma + last_size
   4027 		   || last_hdr->lma + last_size < last_hdr->lma)
   4028 	    {
   4029 	      /* If this section has a load address that makes it overlap
   4030 		 the previous section, then we need a new segment.  */
   4031 	      new_segment = TRUE;
   4032 	    }
   4033 	  /* In the next test we have to be careful when last_hdr->lma is close
   4034 	     to the end of the address space.  If the aligned address wraps
   4035 	     around to the start of the address space, then there are no more
   4036 	     pages left in memory and it is OK to assume that the current
   4037 	     section can be included in the current segment.  */
   4038 	  else if ((BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
   4039 		    > last_hdr->lma)
   4040 		   && (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize) + maxpagesize
   4041 		       <= hdr->lma))
   4042 	    {
   4043 	      /* If putting this section in this segment would force us to
   4044 		 skip a page in the segment, then we need a new segment.  */
   4045 	      new_segment = TRUE;
   4046 	    }
   4047 	  else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
   4048 		   && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
   4049 	    {
   4050 	      /* We don't want to put a loadable section after a
   4051 		 nonloadable section in the same segment.
   4052 		 Consider .tbss sections as loadable for this purpose.  */
   4053 	      new_segment = TRUE;
   4054 	    }
   4055 	  else if ((abfd->flags & D_PAGED) == 0)
   4056 	    {
   4057 	      /* If the file is not demand paged, which means that we
   4058 		 don't require the sections to be correctly aligned in the
   4059 		 file, then there is no other reason for a new segment.  */
   4060 	      new_segment = FALSE;
   4061 	    }
   4062 	  else if (! writable
   4063 		   && (hdr->flags & SEC_READONLY) == 0
   4064 		   && (((last_hdr->lma + last_size - 1) & -maxpagesize)
   4065 		       != (hdr->lma & -maxpagesize)))
   4066 	    {
   4067 	      /* We don't want to put a writable section in a read only
   4068 		 segment, unless they are on the same page in memory
   4069 		 anyhow.  We already know that the last section does not
   4070 		 bring us past the current section on the page, so the
   4071 		 only case in which the new section is not on the same
   4072 		 page as the previous section is when the previous section
   4073 		 ends precisely on a page boundary.  */
   4074 	      new_segment = TRUE;
   4075 	    }
   4076 	  else
   4077 	    {
   4078 	      /* Otherwise, we can use the same segment.  */
   4079 	      new_segment = FALSE;
   4080 	    }
   4081 
   4082 	  /* Allow interested parties a chance to override our decision.  */
   4083 	  if (last_hdr != NULL
   4084 	      && info != NULL
   4085 	      && info->callbacks->override_segment_assignment != NULL)
   4086 	    new_segment
   4087 	      = info->callbacks->override_segment_assignment (info, abfd, hdr,
   4088 							      last_hdr,
   4089 							      new_segment);
   4090 
   4091 	  if (! new_segment)
   4092 	    {
   4093 	      if ((hdr->flags & SEC_READONLY) == 0)
   4094 		writable = TRUE;
   4095 	      last_hdr = hdr;
   4096 	      /* .tbss sections effectively have zero size.  */
   4097 	      if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
   4098 		  != SEC_THREAD_LOCAL)
   4099 		last_size = hdr->size;
   4100 	      else
   4101 		last_size = 0;
   4102 	      continue;
   4103 	    }
   4104 
   4105 	  /* We need a new program segment.  We must create a new program
   4106 	     header holding all the sections from phdr_index until hdr.  */
   4107 
   4108 	  m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
   4109 	  if (m == NULL)
   4110 	    goto error_return;
   4111 
   4112 	  *pm = m;
   4113 	  pm = &m->next;
   4114 
   4115 	  if ((hdr->flags & SEC_READONLY) == 0)
   4116 	    writable = TRUE;
   4117 	  else
   4118 	    writable = FALSE;
   4119 
   4120 	  last_hdr = hdr;
   4121 	  /* .tbss sections effectively have zero size.  */
   4122 	  if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
   4123 	    last_size = hdr->size;
   4124 	  else
   4125 	    last_size = 0;
   4126 	  phdr_index = i;
   4127 	  phdr_in_segment = FALSE;
   4128 	}
   4129 
   4130       /* Create a final PT_LOAD program segment, but not if it's just
   4131 	 for .tbss.  */
   4132       if (last_hdr != NULL
   4133 	  && (i - phdr_index != 1
   4134 	      || ((last_hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
   4135 		  != SEC_THREAD_LOCAL)))
   4136 	{
   4137 	  m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
   4138 	  if (m == NULL)
   4139 	    goto error_return;
   4140 
   4141 	  *pm = m;
   4142 	  pm = &m->next;
   4143 	}
   4144 
   4145       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
   4146       if (dynsec != NULL)
   4147 	{
   4148 	  m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
   4149 	  if (m == NULL)
   4150 	    goto error_return;
   4151 	  *pm = m;
   4152 	  pm = &m->next;
   4153 	}
   4154 
   4155       /* For each batch of consecutive loadable .note sections,
   4156 	 add a PT_NOTE segment.  We don't use bfd_get_section_by_name,
   4157 	 because if we link together nonloadable .note sections and
   4158 	 loadable .note sections, we will generate two .note sections
   4159 	 in the output file.  FIXME: Using names for section types is
   4160 	 bogus anyhow.  */
   4161       for (s = abfd->sections; s != NULL; s = s->next)
   4162 	{
   4163 	  if ((s->flags & SEC_LOAD) != 0
   4164 	      && CONST_STRNEQ (s->name, ".note"))
   4165 	    {
   4166 	      asection *s2;
   4167 
   4168 	      count = 1;
   4169 	      amt = sizeof (struct elf_segment_map);
   4170 	      if (s->alignment_power == 2)
   4171 		for (s2 = s; s2->next != NULL; s2 = s2->next)
   4172 		  {
   4173 		    if (s2->next->alignment_power == 2
   4174 			&& (s2->next->flags & SEC_LOAD) != 0
   4175 			&& CONST_STRNEQ (s2->next->name, ".note")
   4176 			&& align_power (s2->lma + s2->size, 2)
   4177 			   == s2->next->lma)
   4178 		      count++;
   4179 		    else
   4180 		      break;
   4181 		  }
   4182 	      amt += (count - 1) * sizeof (asection *);
   4183 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   4184 	      if (m == NULL)
   4185 		goto error_return;
   4186 	      m->next = NULL;
   4187 	      m->p_type = PT_NOTE;
   4188 	      m->count = count;
   4189 	      while (count > 1)
   4190 		{
   4191 		  m->sections[m->count - count--] = s;
   4192 		  BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
   4193 		  s = s->next;
   4194 		}
   4195 	      m->sections[m->count - 1] = s;
   4196 	      BFD_ASSERT ((s->flags & SEC_THREAD_LOCAL) == 0);
   4197 	      *pm = m;
   4198 	      pm = &m->next;
   4199 	    }
   4200 	  if (s->flags & SEC_THREAD_LOCAL)
   4201 	    {
   4202 	      if (! tls_count)
   4203 		first_tls = s;
   4204 	      tls_count++;
   4205 	    }
   4206 	}
   4207 
   4208       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
   4209       if (tls_count > 0)
   4210 	{
   4211 	  amt = sizeof (struct elf_segment_map);
   4212 	  amt += (tls_count - 1) * sizeof (asection *);
   4213 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   4214 	  if (m == NULL)
   4215 	    goto error_return;
   4216 	  m->next = NULL;
   4217 	  m->p_type = PT_TLS;
   4218 	  m->count = tls_count;
   4219 	  /* Mandated PF_R.  */
   4220 	  m->p_flags = PF_R;
   4221 	  m->p_flags_valid = 1;
   4222 	  s = first_tls;
   4223 	  for (i = 0; i < (unsigned int) tls_count; ++i)
   4224 	    {
   4225 	      if ((s->flags & SEC_THREAD_LOCAL) == 0)
   4226 		{
   4227 		  _bfd_error_handler
   4228 		    (_("%B: TLS sections are not adjacent:"), abfd);
   4229 		  s = first_tls;
   4230 		  i = 0;
   4231 		  while (i < (unsigned int) tls_count)
   4232 		    {
   4233 		      if ((s->flags & SEC_THREAD_LOCAL) != 0)
   4234 			{
   4235 			  _bfd_error_handler (_("	    TLS: %A"), s);
   4236 			  i++;
   4237 			}
   4238 		      else
   4239 			_bfd_error_handler (_("	non-TLS: %A"), s);
   4240 		      s = s->next;
   4241 		    }
   4242 		  bfd_set_error (bfd_error_bad_value);
   4243 		  goto error_return;
   4244 		}
   4245 	      m->sections[i] = s;
   4246 	      s = s->next;
   4247 	    }
   4248 
   4249 	  *pm = m;
   4250 	  pm = &m->next;
   4251 	}
   4252 
   4253       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
   4254 	 segment.  */
   4255       eh_frame_hdr = elf_eh_frame_hdr (abfd);
   4256       if (eh_frame_hdr != NULL
   4257 	  && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
   4258 	{
   4259 	  amt = sizeof (struct elf_segment_map);
   4260 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   4261 	  if (m == NULL)
   4262 	    goto error_return;
   4263 	  m->next = NULL;
   4264 	  m->p_type = PT_GNU_EH_FRAME;
   4265 	  m->count = 1;
   4266 	  m->sections[0] = eh_frame_hdr->output_section;
   4267 
   4268 	  *pm = m;
   4269 	  pm = &m->next;
   4270 	}
   4271 
   4272       if (elf_stack_flags (abfd))
   4273 	{
   4274 	  amt = sizeof (struct elf_segment_map);
   4275 	  m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   4276 	  if (m == NULL)
   4277 	    goto error_return;
   4278 	  m->next = NULL;
   4279 	  m->p_type = PT_GNU_STACK;
   4280 	  m->p_flags = elf_stack_flags (abfd);
   4281 	  m->p_align = bed->stack_align;
   4282 	  m->p_flags_valid = 1;
   4283 	  m->p_align_valid = m->p_align != 0;
   4284 	  if (info->stacksize > 0)
   4285 	    {
   4286 	      m->p_size = info->stacksize;
   4287 	      m->p_size_valid = 1;
   4288 	    }
   4289 
   4290 	  *pm = m;
   4291 	  pm = &m->next;
   4292 	}
   4293 
   4294       if (info != NULL && info->relro)
   4295 	{
   4296 	  for (m = mfirst; m != NULL; m = m->next)
   4297 	    {
   4298 	      if (m->p_type == PT_LOAD
   4299 		  && m->count != 0
   4300 		  && m->sections[0]->vma >= info->relro_start
   4301 		  && m->sections[0]->vma < info->relro_end)
   4302 		{
   4303 		  i = m->count;
   4304 		  while (--i != (unsigned) -1)
   4305 		    if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS))
   4306 			== (SEC_LOAD | SEC_HAS_CONTENTS))
   4307 		      break;
   4308 
   4309 		  if (i != (unsigned) -1)
   4310 		    break;
   4311 		}
   4312 	    }
   4313 
   4314 	  /* Make a PT_GNU_RELRO segment only when it isn't empty.  */
   4315 	  if (m != NULL)
   4316 	    {
   4317 	      amt = sizeof (struct elf_segment_map);
   4318 	      m = (struct elf_segment_map *) bfd_zalloc (abfd, amt);
   4319 	      if (m == NULL)
   4320 		goto error_return;
   4321 	      m->next = NULL;
   4322 	      m->p_type = PT_GNU_RELRO;
   4323 	      m->p_flags = PF_R;
   4324 	      m->p_flags_valid = 1;
   4325 
   4326 	      *pm = m;
   4327 	      pm = &m->next;
   4328 	    }
   4329 	}
   4330 
   4331       free (sections);
   4332       elf_seg_map (abfd) = mfirst;
   4333     }
   4334 
   4335   if (!elf_modify_segment_map (abfd, info, no_user_phdrs))
   4336     return FALSE;
   4337 
   4338   for (count = 0, m = elf_seg_map (abfd); m != NULL; m = m->next)
   4339     ++count;
   4340   elf_program_header_size (abfd) = count * bed->s->sizeof_phdr;
   4341 
   4342   return TRUE;
   4343 
   4344  error_return:
   4345   if (sections != NULL)
   4346     free (sections);
   4347   return FALSE;
   4348 }
   4349 
   4350 /* Sort sections by address.  */
   4351 
   4352 static int
   4353 elf_sort_sections (const void *arg1, const void *arg2)
   4354 {
   4355   const asection *sec1 = *(const asection **) arg1;
   4356   const asection *sec2 = *(const asection **) arg2;
   4357   bfd_size_type size1, size2;
   4358 
   4359   /* Sort by LMA first, since this is the address used to
   4360      place the section into a segment.  */
   4361   if (sec1->lma < sec2->lma)
   4362     return -1;
   4363   else if (sec1->lma > sec2->lma)
   4364     return 1;
   4365 
   4366   /* Then sort by VMA.  Normally the LMA and the VMA will be
   4367      the same, and this will do nothing.  */
   4368   if (sec1->vma < sec2->vma)
   4369     return -1;
   4370   else if (sec1->vma > sec2->vma)
   4371     return 1;
   4372 
   4373   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
   4374 
   4375 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
   4376 
   4377   if (TOEND (sec1))
   4378     {
   4379       if (TOEND (sec2))
   4380 	{
   4381 	  /* If the indicies are the same, do not return 0
   4382 	     here, but continue to try the next comparison.  */
   4383 	  if (sec1->target_index - sec2->target_index != 0)
   4384 	    return sec1->target_index - sec2->target_index;
   4385 	}
   4386       else
   4387 	return 1;
   4388     }
   4389   else if (TOEND (sec2))
   4390     return -1;
   4391 
   4392 #undef TOEND
   4393 
   4394   /* Sort by size, to put zero sized sections
   4395      before others at the same address.  */
   4396 
   4397   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
   4398   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
   4399 
   4400   if (size1 < size2)
   4401     return -1;
   4402   if (size1 > size2)
   4403     return 1;
   4404 
   4405   return sec1->target_index - sec2->target_index;
   4406 }
   4407 
   4408 /* Ian Lance Taylor writes:
   4409 
   4410    We shouldn't be using % with a negative signed number.  That's just
   4411    not good.  We have to make sure either that the number is not
   4412    negative, or that the number has an unsigned type.  When the types
   4413    are all the same size they wind up as unsigned.  When file_ptr is a
   4414    larger signed type, the arithmetic winds up as signed long long,
   4415    which is wrong.
   4416 
   4417    What we're trying to say here is something like ``increase OFF by
   4418    the least amount that will cause it to be equal to the VMA modulo
   4419    the page size.''  */
   4420 /* In other words, something like:
   4421 
   4422    vma_offset = m->sections[0]->vma % bed->maxpagesize;
   4423    off_offset = off % bed->maxpagesize;
   4424    if (vma_offset < off_offset)
   4425      adjustment = vma_offset + bed->maxpagesize - off_offset;
   4426    else
   4427      adjustment = vma_offset - off_offset;
   4428 
   4429    which can can be collapsed into the expression below.  */
   4430 
   4431 static file_ptr
   4432 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
   4433 {
   4434   /* PR binutils/16199: Handle an alignment of zero.  */
   4435   if (maxpagesize == 0)
   4436     maxpagesize = 1;
   4437   return ((vma - off) % maxpagesize);
   4438 }
   4439 
   4440 static void
   4441 print_segment_map (const struct elf_segment_map *m)
   4442 {
   4443   unsigned int j;
   4444   const char *pt = get_segment_type (m->p_type);
   4445   char buf[32];
   4446 
   4447   if (pt == NULL)
   4448     {
   4449       if (m->p_type >= PT_LOPROC && m->p_type <= PT_HIPROC)
   4450 	sprintf (buf, "LOPROC+%7.7x",
   4451 		 (unsigned int) (m->p_type - PT_LOPROC));
   4452       else if (m->p_type >= PT_LOOS && m->p_type <= PT_HIOS)
   4453 	sprintf (buf, "LOOS+%7.7x",
   4454 		 (unsigned int) (m->p_type - PT_LOOS));
   4455       else
   4456 	snprintf (buf, sizeof (buf), "%8.8x",
   4457 		  (unsigned int) m->p_type);
   4458       pt = buf;
   4459     }
   4460   fflush (stdout);
   4461   fprintf (stderr, "%s:", pt);
   4462   for (j = 0; j < m->count; j++)
   4463     fprintf (stderr, " %s", m->sections [j]->name);
   4464   putc ('\n',stderr);
   4465   fflush (stderr);
   4466 }
   4467 
   4468 static bfd_boolean
   4469 write_zeros (bfd *abfd, file_ptr pos, bfd_size_type len)
   4470 {
   4471   void *buf;
   4472   bfd_boolean ret;
   4473 
   4474   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
   4475     return FALSE;
   4476   buf = bfd_zmalloc (len);
   4477   if (buf == NULL)
   4478     return FALSE;
   4479   ret = bfd_bwrite (buf, len, abfd) == len;
   4480   free (buf);
   4481   return ret;
   4482 }
   4483 
   4484 /* Assign file positions to the sections based on the mapping from
   4485    sections to segments.  This function also sets up some fields in
   4486    the file header.  */
   4487 
   4488 static bfd_boolean
   4489 assign_file_positions_for_load_sections (bfd *abfd,
   4490 					 struct bfd_link_info *link_info)
   4491 {
   4492   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   4493   struct elf_segment_map *m;
   4494   Elf_Internal_Phdr *phdrs;
   4495   Elf_Internal_Phdr *p;
   4496   file_ptr off;
   4497   bfd_size_type maxpagesize;
   4498   unsigned int alloc;
   4499   unsigned int i, j;
   4500   bfd_vma header_pad = 0;
   4501 
   4502   if (link_info == NULL
   4503       && !_bfd_elf_map_sections_to_segments (abfd, link_info))
   4504     return FALSE;
   4505 
   4506   alloc = 0;
   4507   for (m = elf_seg_map (abfd); m != NULL; m = m->next)
   4508     {
   4509       ++alloc;
   4510       if (m->header_size)
   4511 	header_pad = m->header_size;
   4512     }
   4513 
   4514   if (alloc)
   4515     {
   4516       elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
   4517       elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
   4518     }
   4519   else
   4520     {
   4521       /* PR binutils/12467.  */
   4522       elf_elfheader (abfd)->e_phoff = 0;
   4523       elf_elfheader (abfd)->e_phentsize = 0;
   4524     }
   4525 
   4526   elf_elfheader (abfd)->e_phnum = alloc;
   4527 
   4528   if (elf_program_header_size (abfd) == (bfd_size_type) -1)
   4529     elf_program_header_size (abfd) = alloc * bed->s->sizeof_phdr;
   4530   else
   4531     BFD_ASSERT (elf_program_header_size (abfd)
   4532 		>= alloc * bed->s->sizeof_phdr);
   4533 
   4534   if (alloc == 0)
   4535     {
   4536       elf_next_file_pos (abfd) = bed->s->sizeof_ehdr;
   4537       return TRUE;
   4538     }
   4539 
   4540   /* We're writing the size in elf_program_header_size (abfd),
   4541      see assign_file_positions_except_relocs, so make sure we have
   4542      that amount allocated, with trailing space cleared.
   4543      The variable alloc contains the computed need, while
   4544      elf_program_header_size (abfd) contains the size used for the
   4545      layout.
   4546      See ld/emultempl/elf-generic.em:gld${EMULATION_NAME}_map_segments
   4547      where the layout is forced to according to a larger size in the
   4548      last iterations for the testcase ld-elf/header.  */
   4549   BFD_ASSERT (elf_program_header_size (abfd) % bed->s->sizeof_phdr
   4550 	      == 0);
   4551   phdrs = (Elf_Internal_Phdr *)
   4552      bfd_zalloc2 (abfd,
   4553                   (elf_program_header_size (abfd) / bed->s->sizeof_phdr),
   4554                   sizeof (Elf_Internal_Phdr));
   4555   elf_tdata (abfd)->phdr = phdrs;
   4556   if (phdrs == NULL)
   4557     return FALSE;
   4558 
   4559   maxpagesize = 1;
   4560   if ((abfd->flags & D_PAGED) != 0)
   4561     maxpagesize = bed->maxpagesize;
   4562 
   4563   off = bed->s->sizeof_ehdr;
   4564   off += alloc * bed->s->sizeof_phdr;
   4565   if (header_pad < (bfd_vma) off)
   4566     header_pad = 0;
   4567   else
   4568     header_pad -= off;
   4569   off += header_pad;
   4570 
   4571   for (m = elf_seg_map (abfd), p = phdrs, j = 0;
   4572        m != NULL;
   4573        m = m->next, p++, j++)
   4574     {
   4575       asection **secpp;
   4576       bfd_vma off_adjust;
   4577       bfd_boolean no_contents;
   4578 
   4579       /* If elf_segment_map is not from map_sections_to_segments, the
   4580 	 sections may not be correctly ordered.  NOTE: sorting should
   4581 	 not be done to the PT_NOTE section of a corefile, which may
   4582 	 contain several pseudo-sections artificially created by bfd.
   4583 	 Sorting these pseudo-sections breaks things badly.  */
   4584       if (m->count > 1
   4585 	  && !(elf_elfheader (abfd)->e_type == ET_CORE
   4586 	       && m->p_type == PT_NOTE))
   4587 	qsort (m->sections, (size_t) m->count, sizeof (asection *),
   4588 	       elf_sort_sections);
   4589 
   4590       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
   4591 	 number of sections with contents contributing to both p_filesz
   4592 	 and p_memsz, followed by a number of sections with no contents
   4593 	 that just contribute to p_memsz.  In this loop, OFF tracks next
   4594 	 available file offset for PT_LOAD and PT_NOTE segments.  */
   4595       p->p_type = m->p_type;
   4596       p->p_flags = m->p_flags;
   4597 
   4598       if (m->count == 0)
   4599 	p->p_vaddr = 0;
   4600       else
   4601 	p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
   4602 
   4603       if (m->p_paddr_valid)
   4604 	p->p_paddr = m->p_paddr;
   4605       else if (m->count == 0)
   4606 	p->p_paddr = 0;
   4607       else
   4608 	p->p_paddr = m->sections[0]->lma - m->p_vaddr_offset;
   4609 
   4610       if (p->p_type == PT_LOAD
   4611 	  && (abfd->flags & D_PAGED) != 0)
   4612 	{
   4613 	  /* p_align in demand paged PT_LOAD segments effectively stores
   4614 	     the maximum page size.  When copying an executable with
   4615 	     objcopy, we set m->p_align from the input file.  Use this
   4616 	     value for maxpagesize rather than bed->maxpagesize, which
   4617 	     may be different.  Note that we use maxpagesize for PT_TLS
   4618 	     segment alignment later in this function, so we are relying
   4619 	     on at least one PT_LOAD segment appearing before a PT_TLS
   4620 	     segment.  */
   4621 	  if (m->p_align_valid)
   4622 	    maxpagesize = m->p_align;
   4623 
   4624 	  p->p_align = maxpagesize;
   4625 	}
   4626       else if (m->p_align_valid)
   4627 	p->p_align = m->p_align;
   4628       else if (m->count == 0)
   4629 	p->p_align = 1 << bed->s->log_file_align;
   4630       else
   4631 	p->p_align = 0;
   4632 
   4633       no_contents = FALSE;
   4634       off_adjust = 0;
   4635       if (p->p_type == PT_LOAD
   4636 	  && m->count > 0)
   4637 	{
   4638 	  bfd_size_type align;
   4639 	  unsigned int align_power = 0;
   4640 
   4641 	  if (m->p_align_valid)
   4642 	    align = p->p_align;
   4643 	  else
   4644 	    {
   4645 	      for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
   4646 		{
   4647 		  unsigned int secalign;
   4648 
   4649 		  secalign = bfd_get_section_alignment (abfd, *secpp);
   4650 		  if (secalign > align_power)
   4651 		    align_power = secalign;
   4652 		}
   4653 	      align = (bfd_size_type) 1 << align_power;
   4654 	      if (align < maxpagesize)
   4655 		align = maxpagesize;
   4656 	    }
   4657 
   4658 	  for (i = 0; i < m->count; i++)
   4659 	    if ((m->sections[i]->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
   4660 	      /* If we aren't making room for this section, then
   4661 		 it must be SHT_NOBITS regardless of what we've
   4662 		 set via struct bfd_elf_special_section.  */
   4663 	      elf_section_type (m->sections[i]) = SHT_NOBITS;
   4664 
   4665 	  /* Find out whether this segment contains any loadable
   4666 	     sections.  */
   4667 	  no_contents = TRUE;
   4668 	  for (i = 0; i < m->count; i++)
   4669 	    if (elf_section_type (m->sections[i]) != SHT_NOBITS)
   4670 	      {
   4671 		no_contents = FALSE;
   4672 		break;
   4673 	      }
   4674 
   4675 	  off_adjust = vma_page_aligned_bias (p->p_vaddr, off, align);
   4676 	  off += off_adjust;
   4677 	  if (no_contents)
   4678 	    {
   4679 	      /* We shouldn't need to align the segment on disk since
   4680 		 the segment doesn't need file space, but the gABI
   4681 		 arguably requires the alignment and glibc ld.so
   4682 		 checks it.  So to comply with the alignment
   4683 		 requirement but not waste file space, we adjust
   4684 		 p_offset for just this segment.  (OFF_ADJUST is
   4685 		 subtracted from OFF later.)  This may put p_offset
   4686 		 past the end of file, but that shouldn't matter.  */
   4687 	    }
   4688 	  else
   4689 	    off_adjust = 0;
   4690 	}
   4691       /* Make sure the .dynamic section is the first section in the
   4692 	 PT_DYNAMIC segment.  */
   4693       else if (p->p_type == PT_DYNAMIC
   4694 	       && m->count > 1
   4695 	       && strcmp (m->sections[0]->name, ".dynamic") != 0)
   4696 	{
   4697 	  _bfd_error_handler
   4698 	    (_("%B: The first section in the PT_DYNAMIC segment is not the .dynamic section"),
   4699 	     abfd);
   4700 	  bfd_set_error (bfd_error_bad_value);
   4701 	  return FALSE;
   4702 	}
   4703       /* Set the note section type to SHT_NOTE.  */
   4704       else if (p->p_type == PT_NOTE)
   4705 	for (i = 0; i < m->count; i++)
   4706 	  elf_section_type (m->sections[i]) = SHT_NOTE;
   4707 
   4708       p->p_offset = 0;
   4709       p->p_filesz = 0;
   4710       p->p_memsz = 0;
   4711 
   4712       if (m->includes_filehdr)
   4713 	{
   4714 	  if (!m->p_flags_valid)
   4715 	    p->p_flags |= PF_R;
   4716 	  p->p_filesz = bed->s->sizeof_ehdr;
   4717 	  p->p_memsz = bed->s->sizeof_ehdr;
   4718 	  if (m->count > 0)
   4719 	    {
   4720 	      if (p->p_vaddr < (bfd_vma) off)
   4721 		{
   4722 		  (*_bfd_error_handler)
   4723 		    (_("%B: Not enough room for program headers, try linking with -N"),
   4724 		     abfd);
   4725 		  bfd_set_error (bfd_error_bad_value);
   4726 		  return FALSE;
   4727 		}
   4728 
   4729 	      p->p_vaddr -= off;
   4730 	      if (!m->p_paddr_valid)
   4731 		p->p_paddr -= off;
   4732 	    }
   4733 	}
   4734 
   4735       if (m->includes_phdrs)
   4736 	{
   4737 	  if (!m->p_flags_valid)
   4738 	    p->p_flags |= PF_R;
   4739 
   4740 	  if (!m->includes_filehdr)
   4741 	    {
   4742 	      p->p_offset = bed->s->sizeof_ehdr;
   4743 
   4744 	      if (m->count > 0)
   4745 		{
   4746 		  p->p_vaddr -= off - p->p_offset;
   4747 		  if (!m->p_paddr_valid)
   4748 		    p->p_paddr -= off - p->p_offset;
   4749 		}
   4750 	    }
   4751 
   4752 	  p->p_filesz += alloc * bed->s->sizeof_phdr;
   4753 	  p->p_memsz += alloc * bed->s->sizeof_phdr;
   4754 	  if (m->count)
   4755 	    {
   4756 	      p->p_filesz += header_pad;
   4757 	      p->p_memsz += header_pad;
   4758 	    }
   4759 	}
   4760 
   4761       if (p->p_type == PT_LOAD
   4762 	  || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
   4763 	{
   4764 	  if (!m->includes_filehdr && !m->includes_phdrs)
   4765 	    p->p_offset = off;
   4766 	  else
   4767 	    {
   4768 	      file_ptr adjust;
   4769 
   4770 	      adjust = off - (p->p_offset + p->p_filesz);
   4771 	      if (!no_contents)
   4772 		p->p_filesz += adjust;
   4773 	      p->p_memsz += adjust;
   4774 	    }
   4775 	}
   4776 
   4777       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
   4778 	 maps.  Set filepos for sections in PT_LOAD segments, and in
   4779 	 core files, for sections in PT_NOTE segments.
   4780 	 assign_file_positions_for_non_load_sections will set filepos
   4781 	 for other sections and update p_filesz for other segments.  */
   4782       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
   4783 	{
   4784 	  asection *sec;
   4785 	  bfd_size_type align;
   4786 	  Elf_Internal_Shdr *this_hdr;
   4787 
   4788 	  sec = *secpp;
   4789 	  this_hdr = &elf_section_data (sec)->this_hdr;
   4790 	  align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
   4791 
   4792 	  if ((p->p_type == PT_LOAD
   4793 	       || p->p_type == PT_TLS)
   4794 	      && (this_hdr->sh_type != SHT_NOBITS
   4795 		  || ((this_hdr->sh_flags & SHF_ALLOC) != 0
   4796 		      && ((this_hdr->sh_flags & SHF_TLS) == 0
   4797 			  || p->p_type == PT_TLS))))
   4798 	    {
   4799 	      bfd_vma p_start = p->p_paddr;
   4800 	      bfd_vma p_end = p_start + p->p_memsz;
   4801 	      bfd_vma s_start = sec->lma;
   4802 	      bfd_vma adjust = s_start - p_end;
   4803 
   4804 	      if (adjust != 0
   4805 		  && (s_start < p_end
   4806 		      || p_end < p_start))
   4807 		{
   4808 		  (*_bfd_error_handler)
   4809 		    (_("%B: section %A lma %#lx adjusted to %#lx"), abfd, sec,
   4810 		     (unsigned long) s_start, (unsigned long) p_end);
   4811 		  adjust = 0;
   4812 		  sec->lma = p_end;
   4813 		}
   4814 	      p->p_memsz += adjust;
   4815 
   4816 	      if (this_hdr->sh_type != SHT_NOBITS)
   4817 		{
   4818 		  if (p->p_filesz + adjust < p->p_memsz)
   4819 		    {
   4820 		      /* We have a PROGBITS section following NOBITS ones.
   4821 		         Allocate file space for the NOBITS section(s) and
   4822 			 zero it.  */
   4823 		      adjust = p->p_memsz - p->p_filesz;
   4824 		      if (!write_zeros (abfd, off, adjust))
   4825 			return FALSE;
   4826 		    }
   4827 		  off += adjust;
   4828 		  p->p_filesz += adjust;
   4829 		}
   4830 	    }
   4831 
   4832 	  if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
   4833 	    {
   4834 	      /* The section at i == 0 is the one that actually contains
   4835 		 everything.  */
   4836 	      if (i == 0)
   4837 		{
   4838 		  this_hdr->sh_offset = sec->filepos = off;
   4839 		  off += this_hdr->sh_size;
   4840 		  p->p_filesz = this_hdr->sh_size;
   4841 		  p->p_memsz = 0;
   4842 		  p->p_align = 1;
   4843 		}
   4844 	      else
   4845 		{
   4846 		  /* The rest are fake sections that shouldn't be written.  */
   4847 		  sec->filepos = 0;
   4848 		  sec->size = 0;
   4849 		  sec->flags = 0;
   4850 		  continue;
   4851 		}
   4852 	    }
   4853 	  else
   4854 	    {
   4855 	      if (p->p_type == PT_LOAD)
   4856 		{
   4857 		  this_hdr->sh_offset = sec->filepos = off;
   4858 		  if (this_hdr->sh_type != SHT_NOBITS)
   4859 		    off += this_hdr->sh_size;
   4860 		}
   4861 	      else if (this_hdr->sh_type == SHT_NOBITS
   4862 		       && (this_hdr->sh_flags & SHF_TLS) != 0
   4863 		       && this_hdr->sh_offset == 0)
   4864 		{
   4865 		  /* This is a .tbss section that didn't get a PT_LOAD.
   4866 		     (See _bfd_elf_map_sections_to_segments "Create a
   4867 		     final PT_LOAD".)  Set sh_offset to the value it
   4868 		     would have if we had created a zero p_filesz and
   4869 		     p_memsz PT_LOAD header for the section.  This
   4870 		     also makes the PT_TLS header have the same
   4871 		     p_offset value.  */
   4872 		  bfd_vma adjust = vma_page_aligned_bias (this_hdr->sh_addr,
   4873 							  off, align);
   4874 		  this_hdr->sh_offset = sec->filepos = off + adjust;
   4875 		}
   4876 
   4877 	      if (this_hdr->sh_type != SHT_NOBITS)
   4878 		{
   4879 		  p->p_filesz += this_hdr->sh_size;
   4880 		  /* A load section without SHF_ALLOC is something like
   4881 		     a note section in a PT_NOTE segment.  These take
   4882 		     file space but are not loaded into memory.  */
   4883 		  if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
   4884 		    p->p_memsz += this_hdr->sh_size;
   4885 		}
   4886 	      else if ((this_hdr->sh_flags & SHF_ALLOC) != 0)
   4887 		{
   4888 		  if (p->p_type == PT_TLS)
   4889 		    p->p_memsz += this_hdr->sh_size;
   4890 
   4891 		  /* .tbss is special.  It doesn't contribute to p_memsz of
   4892 		     normal segments.  */
   4893 		  else if ((this_hdr->sh_flags & SHF_TLS) == 0)
   4894 		    p->p_memsz += this_hdr->sh_size;
   4895 		}
   4896 
   4897 	      if (align > p->p_align
   4898 		  && !m->p_align_valid
   4899 		  && (p->p_type != PT_LOAD
   4900 		      || (abfd->flags & D_PAGED) == 0))
   4901 		p->p_align = align;
   4902 	    }
   4903 
   4904 	  if (!m->p_flags_valid)
   4905 	    {
   4906 	      p->p_flags |= PF_R;
   4907 	      if ((this_hdr->sh_flags & SHF_EXECINSTR) != 0)
   4908 		p->p_flags |= PF_X;
   4909 	      if ((this_hdr->sh_flags & SHF_WRITE) != 0)
   4910 		p->p_flags |= PF_W;
   4911 	    }
   4912 	}
   4913 
   4914       off -= off_adjust;
   4915 
   4916       /* Check that all sections are in a PT_LOAD segment.
   4917 	 Don't check funky gdb generated core files.  */
   4918       if (p->p_type == PT_LOAD && bfd_get_format (abfd) != bfd_core)
   4919 	{
   4920 	  bfd_boolean check_vma = TRUE;
   4921 
   4922 	  for (i = 1; i < m->count; i++)
   4923 	    if (m->sections[i]->vma == m->sections[i - 1]->vma
   4924 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i])
   4925 				       ->this_hdr), p) != 0
   4926 		&& ELF_SECTION_SIZE (&(elf_section_data (m->sections[i - 1])
   4927 				       ->this_hdr), p) != 0)
   4928 	      {
   4929 		/* Looks like we have overlays packed into the segment.  */
   4930 		check_vma = FALSE;
   4931 		break;
   4932 	      }
   4933 
   4934 	  for (i = 0; i < m->count; i++)
   4935 	    {
   4936 	      Elf_Internal_Shdr *this_hdr;
   4937 	      asection *sec;
   4938 
   4939 	      sec = m->sections[i];
   4940 	      this_hdr = &(elf_section_data(sec)->this_hdr);
   4941 	      if (!ELF_SECTION_IN_SEGMENT_1 (this_hdr, p, check_vma, 0)
   4942 		  && !ELF_TBSS_SPECIAL (this_hdr, p))
   4943 		{
   4944 		  (*_bfd_error_handler)
   4945 		    (_("%B: section `%A' can't be allocated in segment %d"),
   4946 		     abfd, sec, j);
   4947 		  print_segment_map (m);
   4948 		}
   4949 	    }
   4950 	}
   4951     }
   4952 
   4953   elf_next_file_pos (abfd) = off;
   4954   return TRUE;
   4955 }
   4956 
   4957 /* Assign file positions for the other sections.  */
   4958 
   4959 static bfd_boolean
   4960 assign_file_positions_for_non_load_sections (bfd *abfd,
   4961 					     struct bfd_link_info *link_info)
   4962 {
   4963   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   4964   Elf_Internal_Shdr **i_shdrpp;
   4965   Elf_Internal_Shdr **hdrpp;
   4966   Elf_Internal_Phdr *phdrs;
   4967   Elf_Internal_Phdr *p;
   4968   struct elf_segment_map *m;
   4969   struct elf_segment_map *hdrs_segment;
   4970   bfd_vma filehdr_vaddr, filehdr_paddr;
   4971   bfd_vma phdrs_vaddr, phdrs_paddr;
   4972   file_ptr off;
   4973   unsigned int num_sec;
   4974   unsigned int i;
   4975   unsigned int count;
   4976 
   4977   i_shdrpp = elf_elfsections (abfd);
   4978   num_sec = elf_numsections (abfd);
   4979   off = elf_next_file_pos (abfd);
   4980   for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
   4981     {
   4982       Elf_Internal_Shdr *hdr;
   4983 
   4984       hdr = *hdrpp;
   4985       if (hdr->bfd_section != NULL
   4986 	  && (hdr->bfd_section->filepos != 0
   4987 	      || (hdr->sh_type == SHT_NOBITS
   4988 		  && hdr->contents == NULL)))
   4989 	BFD_ASSERT (hdr->sh_offset == hdr->bfd_section->filepos);
   4990       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
   4991 	{
   4992 	  if (hdr->sh_size != 0)
   4993 	    (*_bfd_error_handler)
   4994 	      (_("%B: warning: allocated section `%s' not in segment"),
   4995 	       abfd,
   4996 	       (hdr->bfd_section == NULL
   4997 		? "*unknown*"
   4998 		: hdr->bfd_section->name));
   4999 	  /* We don't need to page align empty sections.  */
   5000 	  if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
   5001 	    off += vma_page_aligned_bias (hdr->sh_addr, off,
   5002 					  bed->maxpagesize);
   5003 	  else
   5004 	    off += vma_page_aligned_bias (hdr->sh_addr, off,
   5005 					  hdr->sh_addralign);
   5006 	  off = _bfd_elf_assign_file_position_for_section (hdr, off,
   5007 							   FALSE);
   5008 	}
   5009       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
   5010 		&& hdr->bfd_section == NULL)
   5011 	       || hdr == i_shdrpp[elf_onesymtab (abfd)]
   5012 	       || hdr == i_shdrpp[elf_symtab_shndx (abfd)]
   5013 	       || hdr == i_shdrpp[elf_strtab_sec (abfd)])
   5014 	hdr->sh_offset = -1;
   5015       else
   5016 	off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
   5017     }
   5018 
   5019   /* Now that we have set the section file positions, we can set up
   5020      the file positions for the non PT_LOAD segments.  */
   5021   count = 0;
   5022   filehdr_vaddr = 0;
   5023   filehdr_paddr = 0;
   5024   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
   5025   phdrs_paddr = 0;
   5026   hdrs_segment = NULL;
   5027   phdrs = elf_tdata (abfd)->phdr;
   5028   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
   5029     {
   5030       ++count;
   5031       if (p->p_type != PT_LOAD)
   5032 	continue;
   5033 
   5034       if (m->includes_filehdr)
   5035 	{
   5036 	  filehdr_vaddr = p->p_vaddr;
   5037 	  filehdr_paddr = p->p_paddr;
   5038 	}
   5039       if (m->includes_phdrs)
   5040 	{
   5041 	  phdrs_vaddr = p->p_vaddr;
   5042 	  phdrs_paddr = p->p_paddr;
   5043 	  if (m->includes_filehdr)
   5044 	    {
   5045 	      hdrs_segment = m;
   5046 	      phdrs_vaddr += bed->s->sizeof_ehdr;
   5047 	      phdrs_paddr += bed->s->sizeof_ehdr;
   5048 	    }
   5049 	}
   5050     }
   5051 
   5052   if (hdrs_segment != NULL && link_info != NULL)
   5053     {
   5054       /* There is a segment that contains both the file headers and the
   5055 	 program headers, so provide a symbol __ehdr_start pointing there.
   5056 	 A program can use this to examine itself robustly.  */
   5057 
   5058       struct elf_link_hash_entry *hash
   5059 	= elf_link_hash_lookup (elf_hash_table (link_info), "__ehdr_start",
   5060 				FALSE, FALSE, TRUE);
   5061       /* If the symbol was referenced and not defined, define it.  */
   5062       if (hash != NULL
   5063 	  && (hash->root.type == bfd_link_hash_new
   5064 	      || hash->root.type == bfd_link_hash_undefined
   5065 	      || hash->root.type == bfd_link_hash_undefweak
   5066 	      || hash->root.type == bfd_link_hash_common))
   5067 	{
   5068 	  asection *s = NULL;
   5069 	  if (hdrs_segment->count != 0)
   5070 	    /* The segment contains sections, so use the first one.  */
   5071 	    s = hdrs_segment->sections[0];
   5072 	  else
   5073 	    /* Use the first (i.e. lowest-addressed) section in any segment.  */
   5074 	    for (m = elf_seg_map (abfd); m != NULL; m = m->next)
   5075 	      if (m->count != 0)
   5076 		{
   5077 		  s = m->sections[0];
   5078 		  break;
   5079 		}
   5080 
   5081 	  if (s != NULL)
   5082 	    {
   5083 	      hash->root.u.def.value = filehdr_vaddr - s->vma;
   5084 	      hash->root.u.def.section = s;
   5085 	    }
   5086 	  else
   5087 	    {
   5088 	      hash->root.u.def.value = filehdr_vaddr;
   5089 	      hash->root.u.def.section = bfd_abs_section_ptr;
   5090 	    }
   5091 
   5092 	  hash->root.type = bfd_link_hash_defined;
   5093 	  hash->def_regular = 1;
   5094 	  hash->non_elf = 0;
   5095 	}
   5096     }
   5097 
   5098   for (m = elf_seg_map (abfd), p = phdrs; m != NULL; m = m->next, p++)
   5099     {
   5100       if (p->p_type == PT_GNU_RELRO)
   5101 	{
   5102 	  const Elf_Internal_Phdr *lp;
   5103 	  struct elf_segment_map *lm;
   5104 
   5105 	  if (link_info != NULL)
   5106 	    {
   5107 	      /* During linking the range of the RELRO segment is passed
   5108 		 in link_info.  */
   5109 	      for (lm = elf_seg_map (abfd), lp = phdrs;
   5110 		   lm != NULL;
   5111 		   lm = lm->next, lp++)
   5112 		{
   5113 		  if (lp->p_type == PT_LOAD
   5114 		      && lp->p_vaddr < link_info->relro_end
   5115 		      && lm->count != 0
   5116 		      && lm->sections[0]->vma >= link_info->relro_start)
   5117 		    break;
   5118 		}
   5119 
   5120 	      BFD_ASSERT (lm != NULL);
   5121 	    }
   5122 	  else
   5123 	    {
   5124 	      /* Otherwise we are copying an executable or shared
   5125 		 library, but we need to use the same linker logic.  */
   5126 	      for (lp = phdrs; lp < phdrs + count; ++lp)
   5127 		{
   5128 		  if (lp->p_type == PT_LOAD
   5129 		      && lp->p_paddr == p->p_paddr)
   5130 		    break;
   5131 		}
   5132 	    }
   5133 
   5134 	  if (lp < phdrs + count)
   5135 	    {
   5136 	      p->p_vaddr = lp->p_vaddr;
   5137 	      p->p_paddr = lp->p_paddr;
   5138 	      p->p_offset = lp->p_offset;
   5139 	      if (link_info != NULL)
   5140 		p->p_filesz = link_info->relro_end - lp->p_vaddr;
   5141 	      else if (m->p_size_valid)
   5142 		p->p_filesz = m->p_size;
   5143 	      else
   5144 		abort ();
   5145 	      p->p_memsz = p->p_filesz;
   5146 	      /* Preserve the alignment and flags if they are valid. The
   5147 	         gold linker generates RW/4 for the PT_GNU_RELRO section.
   5148 		 It is better for objcopy/strip to honor these attributes
   5149 		 otherwise gdb will choke when using separate debug files.
   5150 	       */
   5151 	      if (!m->p_align_valid)
   5152 		p->p_align = 1;
   5153 	      if (!m->p_flags_valid)
   5154 		p->p_flags = (lp->p_flags & ~PF_W);
   5155 	    }
   5156 	  else
   5157 	    {
   5158 	      memset (p, 0, sizeof *p);
   5159 	      p->p_type = PT_NULL;
   5160 	    }
   5161 	}
   5162       else if (p->p_type == PT_GNU_STACK)
   5163 	{
   5164 	  if (m->p_size_valid)
   5165 	    p->p_memsz = m->p_size;
   5166 	}
   5167       else if (m->count != 0)
   5168 	{
   5169 	  if (p->p_type != PT_LOAD
   5170 	      && (p->p_type != PT_NOTE
   5171 		  || bfd_get_format (abfd) != bfd_core))
   5172 	    {
   5173 	      BFD_ASSERT (!m->includes_filehdr && !m->includes_phdrs);
   5174 
   5175 	      p->p_filesz = 0;
   5176 	      p->p_offset = m->sections[0]->filepos;
   5177 	      for (i = m->count; i-- != 0;)
   5178 		{
   5179 		  asection *sect = m->sections[i];
   5180 		  Elf_Internal_Shdr *hdr = &elf_section_data (sect)->this_hdr;
   5181 		  if (hdr->sh_type != SHT_NOBITS)
   5182 		    {
   5183 		      p->p_filesz = (sect->filepos - m->sections[0]->filepos
   5184 				     + hdr->sh_size);
   5185 		      break;
   5186 		    }
   5187 		}
   5188 	    }
   5189 	}
   5190       else if (m->includes_filehdr)
   5191 	{
   5192 	  p->p_vaddr = filehdr_vaddr;
   5193 	  if (! m->p_paddr_valid)
   5194 	    p->p_paddr = filehdr_paddr;
   5195 	}
   5196       else if (m->includes_phdrs)
   5197 	{
   5198 	  p->p_vaddr = phdrs_vaddr;
   5199 	  if (! m->p_paddr_valid)
   5200 	    p->p_paddr = phdrs_paddr;
   5201 	}
   5202     }
   5203 
   5204   elf_next_file_pos (abfd) = off;
   5205 
   5206   return TRUE;
   5207 }
   5208 
   5209 /* Work out the file positions of all the sections.  This is called by
   5210    _bfd_elf_compute_section_file_positions.  All the section sizes and
   5211    VMAs must be known before this is called.
   5212 
   5213    Reloc sections come in two flavours: Those processed specially as
   5214    "side-channel" data attached to a section to which they apply, and
   5215    those that bfd doesn't process as relocations.  The latter sort are
   5216    stored in a normal bfd section by bfd_section_from_shdr.   We don't
   5217    consider the former sort here, unless they form part of the loadable
   5218    image.  Reloc sections not assigned here will be handled later by
   5219    assign_file_positions_for_relocs.
   5220 
   5221    We also don't set the positions of the .symtab and .strtab here.  */
   5222 
   5223 static bfd_boolean
   5224 assign_file_positions_except_relocs (bfd *abfd,
   5225 				     struct bfd_link_info *link_info)
   5226 {
   5227   struct elf_obj_tdata *tdata = elf_tdata (abfd);
   5228   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
   5229   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   5230 
   5231   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
   5232       && bfd_get_format (abfd) != bfd_core)
   5233     {
   5234       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
   5235       unsigned int num_sec = elf_numsections (abfd);
   5236       Elf_Internal_Shdr **hdrpp;
   5237       unsigned int i;
   5238       file_ptr off;
   5239 
   5240       /* Start after the ELF header.  */
   5241       off = i_ehdrp->e_ehsize;
   5242 
   5243       /* We are not creating an executable, which means that we are
   5244 	 not creating a program header, and that the actual order of
   5245 	 the sections in the file is unimportant.  */
   5246       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
   5247 	{
   5248 	  Elf_Internal_Shdr *hdr;
   5249 
   5250 	  hdr = *hdrpp;
   5251 	  if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
   5252 	       && hdr->bfd_section == NULL)
   5253 	      || i == elf_onesymtab (abfd)
   5254 	      || i == elf_symtab_shndx (abfd)
   5255 	      || i == elf_strtab_sec (abfd))
   5256 	    {
   5257 	      hdr->sh_offset = -1;
   5258 	    }
   5259 	  else
   5260 	    off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
   5261 	}
   5262 
   5263       elf_next_file_pos (abfd) = off;
   5264     }
   5265   else
   5266     {
   5267       unsigned int alloc;
   5268 
   5269       /* Assign file positions for the loaded sections based on the
   5270 	 assignment of sections to segments.  */
   5271       if (!assign_file_positions_for_load_sections (abfd, link_info))
   5272 	return FALSE;
   5273 
   5274       /* And for non-load sections.  */
   5275       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
   5276 	return FALSE;
   5277 
   5278       if (bed->elf_backend_modify_program_headers != NULL)
   5279 	{
   5280 	  if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
   5281 	    return FALSE;
   5282 	}
   5283 
   5284       /* Set e_type in ELF header to ET_EXEC for -pie -Ttext-segment=.  */
   5285       if (link_info != NULL
   5286 	  && link_info->executable
   5287 	  && link_info->shared)
   5288 	{
   5289 	  unsigned int num_segments = elf_elfheader (abfd)->e_phnum;
   5290 	  Elf_Internal_Phdr *segment = elf_tdata (abfd)->phdr;
   5291 	  Elf_Internal_Phdr *end_segment = &segment[num_segments];
   5292 
   5293 	  /* Find the lowest p_vaddr in PT_LOAD segments.  */
   5294 	  bfd_vma p_vaddr = (bfd_vma) -1;
   5295 	  for (; segment < end_segment; segment++)
   5296 	    if (segment->p_type == PT_LOAD && p_vaddr > segment->p_vaddr)
   5297 	      p_vaddr = segment->p_vaddr;
   5298 
   5299 	  /* Set e_type to ET_EXEC if the lowest p_vaddr in PT_LOAD
   5300 	     segments is non-zero.  */
   5301 	  if (p_vaddr)
   5302 	    i_ehdrp->e_type = ET_EXEC;
   5303 	}
   5304 
   5305       /* Write out the program headers.  */
   5306       alloc = elf_program_header_size (abfd) / bed->s->sizeof_phdr;
   5307       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
   5308 	  || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
   5309 	return FALSE;
   5310     }
   5311 
   5312   return TRUE;
   5313 }
   5314 
   5315 static bfd_boolean
   5316 prep_headers (bfd *abfd)
   5317 {
   5318   Elf_Internal_Ehdr *i_ehdrp;	/* Elf file header, internal form.  */
   5319   struct elf_strtab_hash *shstrtab;
   5320   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   5321 
   5322   i_ehdrp = elf_elfheader (abfd);
   5323 
   5324   shstrtab = _bfd_elf_strtab_init ();
   5325   if (shstrtab == NULL)
   5326     return FALSE;
   5327 
   5328   elf_shstrtab (abfd) = shstrtab;
   5329 
   5330   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
   5331   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
   5332   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
   5333   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
   5334 
   5335   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
   5336   i_ehdrp->e_ident[EI_DATA] =
   5337     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
   5338   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
   5339 
   5340   if ((abfd->flags & DYNAMIC) != 0)
   5341     i_ehdrp->e_type = ET_DYN;
   5342   else if ((abfd->flags & EXEC_P) != 0)
   5343     i_ehdrp->e_type = ET_EXEC;
   5344   else if (bfd_get_format (abfd) == bfd_core)
   5345     i_ehdrp->e_type = ET_CORE;
   5346   else
   5347     i_ehdrp->e_type = ET_REL;
   5348 
   5349   switch (bfd_get_arch (abfd))
   5350     {
   5351     case bfd_arch_unknown:
   5352       i_ehdrp->e_machine = EM_NONE;
   5353       break;
   5354 
   5355       /* There used to be a long list of cases here, each one setting
   5356 	 e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
   5357 	 in the corresponding bfd definition.  To avoid duplication,
   5358 	 the switch was removed.  Machines that need special handling
   5359 	 can generally do it in elf_backend_final_write_processing(),
   5360 	 unless they need the information earlier than the final write.
   5361 	 Such need can generally be supplied by replacing the tests for
   5362 	 e_machine with the conditions used to determine it.  */
   5363     default:
   5364       i_ehdrp->e_machine = bed->elf_machine_code;
   5365     }
   5366 
   5367   i_ehdrp->e_version = bed->s->ev_current;
   5368   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
   5369 
   5370   /* No program header, for now.  */
   5371   i_ehdrp->e_phoff = 0;
   5372   i_ehdrp->e_phentsize = 0;
   5373   i_ehdrp->e_phnum = 0;
   5374 
   5375   /* Each bfd section is section header entry.  */
   5376   i_ehdrp->e_entry = bfd_get_start_address (abfd);
   5377   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
   5378 
   5379   /* If we're building an executable, we'll need a program header table.  */
   5380   if (abfd->flags & EXEC_P)
   5381     /* It all happens later.  */
   5382     ;
   5383   else
   5384     {
   5385       i_ehdrp->e_phentsize = 0;
   5386       i_ehdrp->e_phoff = 0;
   5387     }
   5388 
   5389   elf_tdata (abfd)->symtab_hdr.sh_name =
   5390     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
   5391   elf_tdata (abfd)->strtab_hdr.sh_name =
   5392     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
   5393   elf_tdata (abfd)->shstrtab_hdr.sh_name =
   5394     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
   5395   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
   5396       || elf_tdata (abfd)->strtab_hdr.sh_name == (unsigned int) -1
   5397       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
   5398     return FALSE;
   5399 
   5400   return TRUE;
   5401 }
   5402 
   5403 /* Assign file positions for all the reloc sections which are not part
   5404    of the loadable file image, and the file position of section headers.  */
   5405 
   5406 static void
   5407 _bfd_elf_assign_file_positions_for_relocs (bfd *abfd)
   5408 {
   5409   file_ptr off;
   5410   unsigned int i, num_sec;
   5411   Elf_Internal_Shdr **shdrpp;
   5412   Elf_Internal_Ehdr *i_ehdrp;
   5413   const struct elf_backend_data *bed;
   5414 
   5415   off = elf_next_file_pos (abfd);
   5416 
   5417   num_sec = elf_numsections (abfd);
   5418   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
   5419     {
   5420       Elf_Internal_Shdr *shdrp;
   5421 
   5422       shdrp = *shdrpp;
   5423       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
   5424 	  && shdrp->sh_offset == -1)
   5425 	off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
   5426     }
   5427 
   5428 /* Place the section headers.  */
   5429   i_ehdrp = elf_elfheader (abfd);
   5430   bed = get_elf_backend_data (abfd);
   5431   off = align_file_position (off, 1 << bed->s->log_file_align);
   5432   i_ehdrp->e_shoff = off;
   5433   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
   5434   elf_next_file_pos (abfd) = off;
   5435 }
   5436 
   5437 bfd_boolean
   5438 _bfd_elf_write_object_contents (bfd *abfd)
   5439 {
   5440   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   5441   Elf_Internal_Shdr **i_shdrp;
   5442   bfd_boolean failed;
   5443   unsigned int count, num_sec;
   5444   struct elf_obj_tdata *t;
   5445 
   5446   if (! abfd->output_has_begun
   5447       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
   5448     return FALSE;
   5449 
   5450   i_shdrp = elf_elfsections (abfd);
   5451 
   5452   failed = FALSE;
   5453   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
   5454   if (failed)
   5455     return FALSE;
   5456 
   5457   _bfd_elf_assign_file_positions_for_relocs (abfd);
   5458 
   5459   /* After writing the headers, we need to write the sections too...  */
   5460   num_sec = elf_numsections (abfd);
   5461   for (count = 1; count < num_sec; count++)
   5462     {
   5463       if (bed->elf_backend_section_processing)
   5464 	(*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
   5465       if (i_shdrp[count]->contents)
   5466 	{
   5467 	  bfd_size_type amt = i_shdrp[count]->sh_size;
   5468 
   5469 	  if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
   5470 	      || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
   5471 	    return FALSE;
   5472 	}
   5473     }
   5474 
   5475   /* Write out the section header names.  */
   5476   t = elf_tdata (abfd);
   5477   if (elf_shstrtab (abfd) != NULL
   5478       && (bfd_seek (abfd, t->shstrtab_hdr.sh_offset, SEEK_SET) != 0
   5479 	  || !_bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
   5480     return FALSE;
   5481 
   5482   if (bed->elf_backend_final_write_processing)
   5483     (*bed->elf_backend_final_write_processing) (abfd, elf_linker (abfd));
   5484 
   5485   if (!bed->s->write_shdrs_and_ehdr (abfd))
   5486     return FALSE;
   5487 
   5488   /* This is last since write_shdrs_and_ehdr can touch i_shdrp[0].  */
   5489   if (t->o->build_id.after_write_object_contents != NULL)
   5490     return (*t->o->build_id.after_write_object_contents) (abfd);
   5491 
   5492   return TRUE;
   5493 }
   5494 
   5495 bfd_boolean
   5496 _bfd_elf_write_corefile_contents (bfd *abfd)
   5497 {
   5498   /* Hopefully this can be done just like an object file.  */
   5499   return _bfd_elf_write_object_contents (abfd);
   5500 }
   5501 
   5502 /* Given a section, search the header to find them.  */
   5503 
   5504 unsigned int
   5505 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
   5506 {
   5507   const struct elf_backend_data *bed;
   5508   unsigned int sec_index;
   5509 
   5510   if (elf_section_data (asect) != NULL
   5511       && elf_section_data (asect)->this_idx != 0)
   5512     return elf_section_data (asect)->this_idx;
   5513 
   5514   if (bfd_is_abs_section (asect))
   5515     sec_index = SHN_ABS;
   5516   else if (bfd_is_com_section (asect))
   5517     sec_index = SHN_COMMON;
   5518   else if (bfd_is_und_section (asect))
   5519     sec_index = SHN_UNDEF;
   5520   else
   5521     sec_index = SHN_BAD;
   5522 
   5523   bed = get_elf_backend_data (abfd);
   5524   if (bed->elf_backend_section_from_bfd_section)
   5525     {
   5526       int retval = sec_index;
   5527 
   5528       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
   5529 	return retval;
   5530     }
   5531 
   5532   if (sec_index == SHN_BAD)
   5533     bfd_set_error (bfd_error_nonrepresentable_section);
   5534 
   5535   return sec_index;
   5536 }
   5537 
   5538 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
   5539    on error.  */
   5540 
   5541 int
   5542 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
   5543 {
   5544   asymbol *asym_ptr = *asym_ptr_ptr;
   5545   int idx;
   5546   flagword flags = asym_ptr->flags;
   5547 
   5548   /* When gas creates relocations against local labels, it creates its
   5549      own symbol for the section, but does put the symbol into the
   5550      symbol chain, so udata is 0.  When the linker is generating
   5551      relocatable output, this section symbol may be for one of the
   5552      input sections rather than the output section.  */
   5553   if (asym_ptr->udata.i == 0
   5554       && (flags & BSF_SECTION_SYM)
   5555       && asym_ptr->section)
   5556     {
   5557       asection *sec;
   5558       int indx;
   5559 
   5560       sec = asym_ptr->section;
   5561       if (sec->owner != abfd && sec->output_section != NULL)
   5562 	sec = sec->output_section;
   5563       if (sec->owner == abfd
   5564 	  && (indx = sec->index) < elf_num_section_syms (abfd)
   5565 	  && elf_section_syms (abfd)[indx] != NULL)
   5566 	asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
   5567     }
   5568 
   5569   idx = asym_ptr->udata.i;
   5570 
   5571   if (idx == 0)
   5572     {
   5573       /* This case can occur when using --strip-symbol on a symbol
   5574 	 which is used in a relocation entry.  */
   5575       (*_bfd_error_handler)
   5576 	(_("%B: symbol `%s' required but not present"),
   5577 	 abfd, bfd_asymbol_name (asym_ptr));
   5578       bfd_set_error (bfd_error_no_symbols);
   5579       return -1;
   5580     }
   5581 
   5582 #if DEBUG & 4
   5583   {
   5584     fprintf (stderr,
   5585 	     "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx\n",
   5586 	     (long) asym_ptr, asym_ptr->name, idx, (long) flags);
   5587     fflush (stderr);
   5588   }
   5589 #endif
   5590 
   5591   return idx;
   5592 }
   5593 
   5594 /* Rewrite program header information.  */
   5595 
   5596 static bfd_boolean
   5597 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
   5598 {
   5599   Elf_Internal_Ehdr *iehdr;
   5600   struct elf_segment_map *map;
   5601   struct elf_segment_map *map_first;
   5602   struct elf_segment_map **pointer_to_map;
   5603   Elf_Internal_Phdr *segment;
   5604   asection *section;
   5605   unsigned int i;
   5606   unsigned int num_segments;
   5607   bfd_boolean phdr_included = FALSE;
   5608   bfd_boolean p_paddr_valid;
   5609   bfd_vma maxpagesize;
   5610   struct elf_segment_map *phdr_adjust_seg = NULL;
   5611   unsigned int phdr_adjust_num = 0;
   5612   const struct elf_backend_data *bed;
   5613 
   5614   bed = get_elf_backend_data (ibfd);
   5615   iehdr = elf_elfheader (ibfd);
   5616 
   5617   map_first = NULL;
   5618   pointer_to_map = &map_first;
   5619 
   5620   num_segments = elf_elfheader (ibfd)->e_phnum;
   5621   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
   5622 
   5623   /* Returns the end address of the segment + 1.  */
   5624 #define SEGMENT_END(segment, start)					\
   5625   (start + (segment->p_memsz > segment->p_filesz			\
   5626 	    ? segment->p_memsz : segment->p_filesz))
   5627 
   5628 #define SECTION_SIZE(section, segment)					\
   5629   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))		\
   5630     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)			\
   5631    ? section->size : 0)
   5632 
   5633   /* Returns TRUE if the given section is contained within
   5634      the given segment.  VMA addresses are compared.  */
   5635 #define IS_CONTAINED_BY_VMA(section, segment)				\
   5636   (section->vma >= segment->p_vaddr					\
   5637    && (section->vma + SECTION_SIZE (section, segment)			\
   5638        <= (SEGMENT_END (segment, segment->p_vaddr))))
   5639 
   5640   /* Returns TRUE if the given section is contained within
   5641      the given segment.  LMA addresses are compared.  */
   5642 #define IS_CONTAINED_BY_LMA(section, segment, base)			\
   5643   (section->lma >= base							\
   5644    && (section->lma + SECTION_SIZE (section, segment)			\
   5645        <= SEGMENT_END (segment, base)))
   5646 
   5647   /* Handle PT_NOTE segment.  */
   5648 #define IS_NOTE(p, s)							\
   5649   (p->p_type == PT_NOTE							\
   5650    && elf_section_type (s) == SHT_NOTE					\
   5651    && (bfd_vma) s->filepos >= p->p_offset				\
   5652    && ((bfd_vma) s->filepos + s->size					\
   5653        <= p->p_offset + p->p_filesz))
   5654 
   5655   /* Special case: corefile "NOTE" section containing regs, prpsinfo
   5656      etc.  */
   5657 #define IS_COREFILE_NOTE(p, s)						\
   5658   (IS_NOTE (p, s)							\
   5659    && bfd_get_format (ibfd) == bfd_core					\
   5660    && s->vma == 0							\
   5661    && s->lma == 0)
   5662 
   5663   /* The complicated case when p_vaddr is 0 is to handle the Solaris
   5664      linker, which generates a PT_INTERP section with p_vaddr and
   5665      p_memsz set to 0.  */
   5666 #define IS_SOLARIS_PT_INTERP(p, s)					\
   5667   (p->p_vaddr == 0							\
   5668    && p->p_paddr == 0							\
   5669    && p->p_memsz == 0							\
   5670    && p->p_filesz > 0							\
   5671    && (s->flags & SEC_HAS_CONTENTS) != 0				\
   5672    && s->size > 0							\
   5673    && (bfd_vma) s->filepos >= p->p_offset				\
   5674    && ((bfd_vma) s->filepos + s->size					\
   5675        <= p->p_offset + p->p_filesz))
   5676 
   5677   /* Decide if the given section should be included in the given segment.
   5678      A section will be included if:
   5679        1. It is within the address space of the segment -- we use the LMA
   5680 	  if that is set for the segment and the VMA otherwise,
   5681        2. It is an allocated section or a NOTE section in a PT_NOTE
   5682 	  segment.
   5683        3. There is an output section associated with it,
   5684        4. The section has not already been allocated to a previous segment.
   5685        5. PT_GNU_STACK segments do not include any sections.
   5686        6. PT_TLS segment includes only SHF_TLS sections.
   5687        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
   5688        8. PT_DYNAMIC should not contain empty sections at the beginning
   5689 	  (with the possible exception of .dynamic).  */
   5690 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)		\
   5691   ((((segment->p_paddr							\
   5692       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)	\
   5693       : IS_CONTAINED_BY_VMA (section, segment))				\
   5694      && (section->flags & SEC_ALLOC) != 0)				\
   5695     || IS_NOTE (segment, section))					\
   5696    && segment->p_type != PT_GNU_STACK					\
   5697    && (segment->p_type != PT_TLS					\
   5698        || (section->flags & SEC_THREAD_LOCAL))				\
   5699    && (segment->p_type == PT_LOAD					\
   5700        || segment->p_type == PT_TLS					\
   5701        || (section->flags & SEC_THREAD_LOCAL) == 0)			\
   5702    && (segment->p_type != PT_DYNAMIC					\
   5703        || SECTION_SIZE (section, segment) > 0				\
   5704        || (segment->p_paddr						\
   5705 	   ? segment->p_paddr != section->lma				\
   5706 	   : segment->p_vaddr != section->vma)				\
   5707        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")	\
   5708 	   == 0))							\
   5709    && !section->segment_mark)
   5710 
   5711 /* If the output section of a section in the input segment is NULL,
   5712    it is removed from the corresponding output segment.   */
   5713 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)		\
   5714   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)		\
   5715    && section->output_section != NULL)
   5716 
   5717   /* Returns TRUE iff seg1 starts after the end of seg2.  */
   5718 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)			\
   5719   (seg1->field >= SEGMENT_END (seg2, seg2->field))
   5720 
   5721   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
   5722      their VMA address ranges and their LMA address ranges overlap.
   5723      It is possible to have overlapping VMA ranges without overlapping LMA
   5724      ranges.  RedBoot images for example can have both .data and .bss mapped
   5725      to the same VMA range, but with the .data section mapped to a different
   5726      LMA.  */
   5727 #define SEGMENT_OVERLAPS(seg1, seg2)					\
   5728   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)			\
   5729 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))			\
   5730    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)			\
   5731 	|| SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
   5732 
   5733   /* Initialise the segment mark field.  */
   5734   for (section = ibfd->sections; section != NULL; section = section->next)
   5735     section->segment_mark = FALSE;
   5736 
   5737   /* The Solaris linker creates program headers in which all the
   5738      p_paddr fields are zero.  When we try to objcopy or strip such a
   5739      file, we get confused.  Check for this case, and if we find it
   5740      don't set the p_paddr_valid fields.  */
   5741   p_paddr_valid = FALSE;
   5742   for (i = 0, segment = elf_tdata (ibfd)->phdr;
   5743        i < num_segments;
   5744        i++, segment++)
   5745     if (segment->p_paddr != 0)
   5746       {
   5747 	p_paddr_valid = TRUE;
   5748 	break;
   5749       }
   5750 
   5751   /* Scan through the segments specified in the program header
   5752      of the input BFD.  For this first scan we look for overlaps
   5753      in the loadable segments.  These can be created by weird
   5754      parameters to objcopy.  Also, fix some solaris weirdness.  */
   5755   for (i = 0, segment = elf_tdata (ibfd)->phdr;
   5756        i < num_segments;
   5757        i++, segment++)
   5758     {
   5759       unsigned int j;
   5760       Elf_Internal_Phdr *segment2;
   5761 
   5762       if (segment->p_type == PT_INTERP)
   5763 	for (section = ibfd->sections; section; section = section->next)
   5764 	  if (IS_SOLARIS_PT_INTERP (segment, section))
   5765 	    {
   5766 	      /* Mininal change so that the normal section to segment
   5767 		 assignment code will work.  */
   5768 	      segment->p_vaddr = section->vma;
   5769 	      break;
   5770 	    }
   5771 
   5772       if (segment->p_type != PT_LOAD)
   5773 	{
   5774 	  /* Remove PT_GNU_RELRO segment.  */
   5775 	  if (segment->p_type == PT_GNU_RELRO)
   5776 	    segment->p_type = PT_NULL;
   5777 	  continue;
   5778 	}
   5779 
   5780       /* Determine if this segment overlaps any previous segments.  */
   5781       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2++)
   5782 	{
   5783 	  bfd_signed_vma extra_length;
   5784 
   5785 	  if (segment2->p_type != PT_LOAD
   5786 	      || !SEGMENT_OVERLAPS (segment, segment2))
   5787 	    continue;
   5788 
   5789 	  /* Merge the two segments together.  */
   5790 	  if (segment2->p_vaddr < segment->p_vaddr)
   5791 	    {
   5792 	      /* Extend SEGMENT2 to include SEGMENT and then delete
   5793 		 SEGMENT.  */
   5794 	      extra_length = (SEGMENT_END (segment, segment->p_vaddr)
   5795 			      - SEGMENT_END (segment2, segment2->p_vaddr));
   5796 
   5797 	      if (extra_length > 0)
   5798 		{
   5799 		  segment2->p_memsz += extra_length;
   5800 		  segment2->p_filesz += extra_length;
   5801 		}
   5802 
   5803 	      segment->p_type = PT_NULL;
   5804 
   5805 	      /* Since we have deleted P we must restart the outer loop.  */
   5806 	      i = 0;
   5807 	      segment = elf_tdata (ibfd)->phdr;
   5808 	      break;
   5809 	    }
   5810 	  else
   5811 	    {
   5812 	      /* Extend SEGMENT to include SEGMENT2 and then delete
   5813 		 SEGMENT2.  */
   5814 	      extra_length = (SEGMENT_END (segment2, segment2->p_vaddr)
   5815 			      - SEGMENT_END (segment, segment->p_vaddr));
   5816 
   5817 	      if (extra_length > 0)
   5818 		{
   5819 		  segment->p_memsz += extra_length;
   5820 		  segment->p_filesz += extra_length;
   5821 		}
   5822 
   5823 	      segment2->p_type = PT_NULL;
   5824 	    }
   5825 	}
   5826     }
   5827 
   5828   /* The second scan attempts to assign sections to segments.  */
   5829   for (i = 0, segment = elf_tdata (ibfd)->phdr;
   5830        i < num_segments;
   5831        i++, segment++)
   5832     {
   5833       unsigned int section_count;
   5834       asection **sections;
   5835       asection *output_section;
   5836       unsigned int isec;
   5837       bfd_vma matching_lma;
   5838       bfd_vma suggested_lma;
   5839       unsigned int j;
   5840       bfd_size_type amt;
   5841       asection *first_section;
   5842       bfd_boolean first_matching_lma;
   5843       bfd_boolean first_suggested_lma;
   5844 
   5845       if (segment->p_type == PT_NULL)
   5846 	continue;
   5847 
   5848       first_section = NULL;
   5849       /* Compute how many sections might be placed into this segment.  */
   5850       for (section = ibfd->sections, section_count = 0;
   5851 	   section != NULL;
   5852 	   section = section->next)
   5853 	{
   5854 	  /* Find the first section in the input segment, which may be
   5855 	     removed from the corresponding output segment.   */
   5856 	  if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
   5857 	    {
   5858 	      if (first_section == NULL)
   5859 		first_section = section;
   5860 	      if (section->output_section != NULL)
   5861 		++section_count;
   5862 	    }
   5863 	}
   5864 
   5865       /* Allocate a segment map big enough to contain
   5866 	 all of the sections we have selected.  */
   5867       amt = sizeof (struct elf_segment_map);
   5868       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
   5869       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
   5870       if (map == NULL)
   5871 	return FALSE;
   5872 
   5873       /* Initialise the fields of the segment map.  Default to
   5874 	 using the physical address of the segment in the input BFD.  */
   5875       map->next = NULL;
   5876       map->p_type = segment->p_type;
   5877       map->p_flags = segment->p_flags;
   5878       map->p_flags_valid = 1;
   5879 
   5880       /* If the first section in the input segment is removed, there is
   5881 	 no need to preserve segment physical address in the corresponding
   5882 	 output segment.  */
   5883       if (!first_section || first_section->output_section != NULL)
   5884 	{
   5885 	  map->p_paddr = segment->p_paddr;
   5886 	  map->p_paddr_valid = p_paddr_valid;
   5887 	}
   5888 
   5889       /* Determine if this segment contains the ELF file header
   5890 	 and if it contains the program headers themselves.  */
   5891       map->includes_filehdr = (segment->p_offset == 0
   5892 			       && segment->p_filesz >= iehdr->e_ehsize);
   5893       map->includes_phdrs = 0;
   5894 
   5895       if (!phdr_included || segment->p_type != PT_LOAD)
   5896 	{
   5897 	  map->includes_phdrs =
   5898 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
   5899 	     && (segment->p_offset + segment->p_filesz
   5900 		 >= ((bfd_vma) iehdr->e_phoff
   5901 		     + iehdr->e_phnum * iehdr->e_phentsize)));
   5902 
   5903 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
   5904 	    phdr_included = TRUE;
   5905 	}
   5906 
   5907       if (section_count == 0)
   5908 	{
   5909 	  /* Special segments, such as the PT_PHDR segment, may contain
   5910 	     no sections, but ordinary, loadable segments should contain
   5911 	     something.  They are allowed by the ELF spec however, so only
   5912 	     a warning is produced.  */
   5913 	  if (segment->p_type == PT_LOAD)
   5914 	    (*_bfd_error_handler) (_("%B: warning: Empty loadable segment"
   5915 				     " detected, is this intentional ?\n"),
   5916 				   ibfd);
   5917 
   5918 	  map->count = 0;
   5919 	  *pointer_to_map = map;
   5920 	  pointer_to_map = &map->next;
   5921 
   5922 	  continue;
   5923 	}
   5924 
   5925       /* Now scan the sections in the input BFD again and attempt
   5926 	 to add their corresponding output sections to the segment map.
   5927 	 The problem here is how to handle an output section which has
   5928 	 been moved (ie had its LMA changed).  There are four possibilities:
   5929 
   5930 	 1. None of the sections have been moved.
   5931 	    In this case we can continue to use the segment LMA from the
   5932 	    input BFD.
   5933 
   5934 	 2. All of the sections have been moved by the same amount.
   5935 	    In this case we can change the segment's LMA to match the LMA
   5936 	    of the first section.
   5937 
   5938 	 3. Some of the sections have been moved, others have not.
   5939 	    In this case those sections which have not been moved can be
   5940 	    placed in the current segment which will have to have its size,
   5941 	    and possibly its LMA changed, and a new segment or segments will
   5942 	    have to be created to contain the other sections.
   5943 
   5944 	 4. The sections have been moved, but not by the same amount.
   5945 	    In this case we can change the segment's LMA to match the LMA
   5946 	    of the first section and we will have to create a new segment
   5947 	    or segments to contain the other sections.
   5948 
   5949 	 In order to save time, we allocate an array to hold the section
   5950 	 pointers that we are interested in.  As these sections get assigned
   5951 	 to a segment, they are removed from this array.  */
   5952 
   5953       sections = (asection **) bfd_malloc2 (section_count, sizeof (asection *));
   5954       if (sections == NULL)
   5955 	return FALSE;
   5956 
   5957       /* Step One: Scan for segment vs section LMA conflicts.
   5958 	 Also add the sections to the section array allocated above.
   5959 	 Also add the sections to the current segment.  In the common
   5960 	 case, where the sections have not been moved, this means that
   5961 	 we have completely filled the segment, and there is nothing
   5962 	 more to do.  */
   5963       isec = 0;
   5964       matching_lma = 0;
   5965       suggested_lma = 0;
   5966       first_matching_lma = TRUE;
   5967       first_suggested_lma = TRUE;
   5968 
   5969       for (section = ibfd->sections;
   5970 	   section != NULL;
   5971 	   section = section->next)
   5972 	if (section == first_section)
   5973 	  break;
   5974 
   5975       for (j = 0; section != NULL; section = section->next)
   5976 	{
   5977 	  if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
   5978 	    {
   5979 	      output_section = section->output_section;
   5980 
   5981 	      sections[j++] = section;
   5982 
   5983 	      /* The Solaris native linker always sets p_paddr to 0.
   5984 		 We try to catch that case here, and set it to the
   5985 		 correct value.  Note - some backends require that
   5986 		 p_paddr be left as zero.  */
   5987 	      if (!p_paddr_valid
   5988 		  && segment->p_vaddr != 0
   5989 		  && !bed->want_p_paddr_set_to_zero
   5990 		  && isec == 0
   5991 		  && output_section->lma != 0
   5992 		  && output_section->vma == (segment->p_vaddr
   5993 					     + (map->includes_filehdr
   5994 						? iehdr->e_ehsize
   5995 						: 0)
   5996 					     + (map->includes_phdrs
   5997 						? (iehdr->e_phnum
   5998 						   * iehdr->e_phentsize)
   5999 						: 0)))
   6000 		map->p_paddr = segment->p_vaddr;
   6001 
   6002 	      /* Match up the physical address of the segment with the
   6003 		 LMA address of the output section.  */
   6004 	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
   6005 		  || IS_COREFILE_NOTE (segment, section)
   6006 		  || (bed->want_p_paddr_set_to_zero
   6007 		      && IS_CONTAINED_BY_VMA (output_section, segment)))
   6008 		{
   6009 		  if (first_matching_lma || output_section->lma < matching_lma)
   6010 		    {
   6011 		      matching_lma = output_section->lma;
   6012 		      first_matching_lma = FALSE;
   6013 		    }
   6014 
   6015 		  /* We assume that if the section fits within the segment
   6016 		     then it does not overlap any other section within that
   6017 		     segment.  */
   6018 		  map->sections[isec++] = output_section;
   6019 		}
   6020 	      else if (first_suggested_lma)
   6021 		{
   6022 		  suggested_lma = output_section->lma;
   6023 		  first_suggested_lma = FALSE;
   6024 		}
   6025 
   6026 	      if (j == section_count)
   6027 		break;
   6028 	    }
   6029 	}
   6030 
   6031       BFD_ASSERT (j == section_count);
   6032 
   6033       /* Step Two: Adjust the physical address of the current segment,
   6034 	 if necessary.  */
   6035       if (isec == section_count)
   6036 	{
   6037 	  /* All of the sections fitted within the segment as currently
   6038 	     specified.  This is the default case.  Add the segment to
   6039 	     the list of built segments and carry on to process the next
   6040 	     program header in the input BFD.  */
   6041 	  map->count = section_count;
   6042 	  *pointer_to_map = map;
   6043 	  pointer_to_map = &map->next;
   6044 
   6045 	  if (p_paddr_valid
   6046 	      && !bed->want_p_paddr_set_to_zero
   6047 	      && matching_lma != map->p_paddr
   6048 	      && !map->includes_filehdr
   6049 	      && !map->includes_phdrs)
   6050 	    /* There is some padding before the first section in the
   6051 	       segment.  So, we must account for that in the output
   6052 	       segment's vma.  */
   6053 	    map->p_vaddr_offset = matching_lma - map->p_paddr;
   6054 
   6055 	  free (sections);
   6056 	  continue;
   6057 	}
   6058       else
   6059 	{
   6060 	  if (!first_matching_lma)
   6061 	    {
   6062 	      /* At least one section fits inside the current segment.
   6063 		 Keep it, but modify its physical address to match the
   6064 		 LMA of the first section that fitted.  */
   6065 	      map->p_paddr = matching_lma;
   6066 	    }
   6067 	  else
   6068 	    {
   6069 	      /* None of the sections fitted inside the current segment.
   6070 		 Change the current segment's physical address to match
   6071 		 the LMA of the first section.  */
   6072 	      map->p_paddr = suggested_lma;
   6073 	    }
   6074 
   6075 	  /* Offset the segment physical address from the lma
   6076 	     to allow for space taken up by elf headers.  */
   6077 	  if (map->includes_filehdr)
   6078 	    {
   6079 	      if (map->p_paddr >= iehdr->e_ehsize)
   6080 		map->p_paddr -= iehdr->e_ehsize;
   6081 	      else
   6082 		{
   6083 		  map->includes_filehdr = FALSE;
   6084 		  map->includes_phdrs = FALSE;
   6085 		}
   6086 	    }
   6087 
   6088 	  if (map->includes_phdrs)
   6089 	    {
   6090 	      if (map->p_paddr >= iehdr->e_phnum * iehdr->e_phentsize)
   6091 		{
   6092 		  map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
   6093 
   6094 		  /* iehdr->e_phnum is just an estimate of the number
   6095 		     of program headers that we will need.  Make a note
   6096 		     here of the number we used and the segment we chose
   6097 		     to hold these headers, so that we can adjust the
   6098 		     offset when we know the correct value.  */
   6099 		  phdr_adjust_num = iehdr->e_phnum;
   6100 		  phdr_adjust_seg = map;
   6101 		}
   6102 	      else
   6103 		map->includes_phdrs = FALSE;
   6104 	    }
   6105 	}
   6106 
   6107       /* Step Three: Loop over the sections again, this time assigning
   6108 	 those that fit to the current segment and removing them from the
   6109 	 sections array; but making sure not to leave large gaps.  Once all
   6110 	 possible sections have been assigned to the current segment it is
   6111 	 added to the list of built segments and if sections still remain
   6112 	 to be assigned, a new segment is constructed before repeating
   6113 	 the loop.  */
   6114       isec = 0;
   6115       do
   6116 	{
   6117 	  map->count = 0;
   6118 	  suggested_lma = 0;
   6119 	  first_suggested_lma = TRUE;
   6120 
   6121 	  /* Fill the current segment with sections that fit.  */
   6122 	  for (j = 0; j < section_count; j++)
   6123 	    {
   6124 	      section = sections[j];
   6125 
   6126 	      if (section == NULL)
   6127 		continue;
   6128 
   6129 	      output_section = section->output_section;
   6130 
   6131 	      BFD_ASSERT (output_section != NULL);
   6132 
   6133 	      if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
   6134 		  || IS_COREFILE_NOTE (segment, section))
   6135 		{
   6136 		  if (map->count == 0)
   6137 		    {
   6138 		      /* If the first section in a segment does not start at
   6139 			 the beginning of the segment, then something is
   6140 			 wrong.  */
   6141 		      if (output_section->lma
   6142 			  != (map->p_paddr
   6143 			      + (map->includes_filehdr ? iehdr->e_ehsize : 0)
   6144 			      + (map->includes_phdrs
   6145 				 ? iehdr->e_phnum * iehdr->e_phentsize
   6146 				 : 0)))
   6147 			abort ();
   6148 		    }
   6149 		  else
   6150 		    {
   6151 		      asection *prev_sec;
   6152 
   6153 		      prev_sec = map->sections[map->count - 1];
   6154 
   6155 		      /* If the gap between the end of the previous section
   6156 			 and the start of this section is more than
   6157 			 maxpagesize then we need to start a new segment.  */
   6158 		      if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
   6159 				      maxpagesize)
   6160 			   < BFD_ALIGN (output_section->lma, maxpagesize))
   6161 			  || (prev_sec->lma + prev_sec->size
   6162 			      > output_section->lma))
   6163 			{
   6164 			  if (first_suggested_lma)
   6165 			    {
   6166 			      suggested_lma = output_section->lma;
   6167 			      first_suggested_lma = FALSE;
   6168 			    }
   6169 
   6170 			  continue;
   6171 			}
   6172 		    }
   6173 
   6174 		  map->sections[map->count++] = output_section;
   6175 		  ++isec;
   6176 		  sections[j] = NULL;
   6177 		  section->segment_mark = TRUE;
   6178 		}
   6179 	      else if (first_suggested_lma)
   6180 		{
   6181 		  suggested_lma = output_section->lma;
   6182 		  first_suggested_lma = FALSE;
   6183 		}
   6184 	    }
   6185 
   6186 	  BFD_ASSERT (map->count > 0);
   6187 
   6188 	  /* Add the current segment to the list of built segments.  */
   6189 	  *pointer_to_map = map;
   6190 	  pointer_to_map = &map->next;
   6191 
   6192 	  if (isec < section_count)
   6193 	    {
   6194 	      /* We still have not allocated all of the sections to
   6195 		 segments.  Create a new segment here, initialise it
   6196 		 and carry on looping.  */
   6197 	      amt = sizeof (struct elf_segment_map);
   6198 	      amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
   6199 	      map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
   6200 	      if (map == NULL)
   6201 		{
   6202 		  free (sections);
   6203 		  return FALSE;
   6204 		}
   6205 
   6206 	      /* Initialise the fields of the segment map.  Set the physical
   6207 		 physical address to the LMA of the first section that has
   6208 		 not yet been assigned.  */
   6209 	      map->next = NULL;
   6210 	      map->p_type = segment->p_type;
   6211 	      map->p_flags = segment->p_flags;
   6212 	      map->p_flags_valid = 1;
   6213 	      map->p_paddr = suggested_lma;
   6214 	      map->p_paddr_valid = p_paddr_valid;
   6215 	      map->includes_filehdr = 0;
   6216 	      map->includes_phdrs = 0;
   6217 	    }
   6218 	}
   6219       while (isec < section_count);
   6220 
   6221       free (sections);
   6222     }
   6223 
   6224   elf_seg_map (obfd) = map_first;
   6225 
   6226   /* If we had to estimate the number of program headers that were
   6227      going to be needed, then check our estimate now and adjust
   6228      the offset if necessary.  */
   6229   if (phdr_adjust_seg != NULL)
   6230     {
   6231       unsigned int count;
   6232 
   6233       for (count = 0, map = map_first; map != NULL; map = map->next)
   6234 	count++;
   6235 
   6236       if (count > phdr_adjust_num)
   6237 	phdr_adjust_seg->p_paddr
   6238 	  -= (count - phdr_adjust_num) * iehdr->e_phentsize;
   6239     }
   6240 
   6241 #undef SEGMENT_END
   6242 #undef SECTION_SIZE
   6243 #undef IS_CONTAINED_BY_VMA
   6244 #undef IS_CONTAINED_BY_LMA
   6245 #undef IS_NOTE
   6246 #undef IS_COREFILE_NOTE
   6247 #undef IS_SOLARIS_PT_INTERP
   6248 #undef IS_SECTION_IN_INPUT_SEGMENT
   6249 #undef INCLUDE_SECTION_IN_SEGMENT
   6250 #undef SEGMENT_AFTER_SEGMENT
   6251 #undef SEGMENT_OVERLAPS
   6252   return TRUE;
   6253 }
   6254 
   6255 /* Copy ELF program header information.  */
   6256 
   6257 static bfd_boolean
   6258 copy_elf_program_header (bfd *ibfd, bfd *obfd)
   6259 {
   6260   Elf_Internal_Ehdr *iehdr;
   6261   struct elf_segment_map *map;
   6262   struct elf_segment_map *map_first;
   6263   struct elf_segment_map **pointer_to_map;
   6264   Elf_Internal_Phdr *segment;
   6265   unsigned int i;
   6266   unsigned int num_segments;
   6267   bfd_boolean phdr_included = FALSE;
   6268   bfd_boolean p_paddr_valid;
   6269 
   6270   iehdr = elf_elfheader (ibfd);
   6271 
   6272   map_first = NULL;
   6273   pointer_to_map = &map_first;
   6274 
   6275   /* If all the segment p_paddr fields are zero, don't set
   6276      map->p_paddr_valid.  */
   6277   p_paddr_valid = FALSE;
   6278   num_segments = elf_elfheader (ibfd)->e_phnum;
   6279   for (i = 0, segment = elf_tdata (ibfd)->phdr;
   6280        i < num_segments;
   6281        i++, segment++)
   6282     if (segment->p_paddr != 0)
   6283       {
   6284 	p_paddr_valid = TRUE;
   6285 	break;
   6286       }
   6287 
   6288   for (i = 0, segment = elf_tdata (ibfd)->phdr;
   6289        i < num_segments;
   6290        i++, segment++)
   6291     {
   6292       asection *section;
   6293       unsigned int section_count;
   6294       bfd_size_type amt;
   6295       Elf_Internal_Shdr *this_hdr;
   6296       asection *first_section = NULL;
   6297       asection *lowest_section;
   6298 
   6299       /* Compute how many sections are in this segment.  */
   6300       for (section = ibfd->sections, section_count = 0;
   6301 	   section != NULL;
   6302 	   section = section->next)
   6303 	{
   6304 	  this_hdr = &(elf_section_data(section)->this_hdr);
   6305 	  if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
   6306 	    {
   6307 	      if (first_section == NULL)
   6308 		first_section = section;
   6309 	      section_count++;
   6310 	    }
   6311 	}
   6312 
   6313       /* Allocate a segment map big enough to contain
   6314 	 all of the sections we have selected.  */
   6315       amt = sizeof (struct elf_segment_map);
   6316       if (section_count != 0)
   6317 	amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
   6318       map = (struct elf_segment_map *) bfd_zalloc (obfd, amt);
   6319       if (map == NULL)
   6320 	return FALSE;
   6321 
   6322       /* Initialize the fields of the output segment map with the
   6323 	 input segment.  */
   6324       map->next = NULL;
   6325       map->p_type = segment->p_type;
   6326       map->p_flags = segment->p_flags;
   6327       map->p_flags_valid = 1;
   6328       map->p_paddr = segment->p_paddr;
   6329       map->p_paddr_valid = p_paddr_valid;
   6330       map->p_align = segment->p_align;
   6331       map->p_align_valid = 1;
   6332       map->p_vaddr_offset = 0;
   6333 
   6334       if (map->p_type == PT_GNU_RELRO
   6335 	  || map->p_type == PT_GNU_STACK)
   6336 	{
   6337 	  /* The PT_GNU_RELRO segment may contain the first a few
   6338 	     bytes in the .got.plt section even if the whole .got.plt
   6339 	     section isn't in the PT_GNU_RELRO segment.  We won't
   6340 	     change the size of the PT_GNU_RELRO segment.
   6341 	     Similarly, PT_GNU_STACK size is significant on uclinux
   6342 	     systems.    */
   6343 	  map->p_size = segment->p_memsz;
   6344 	  map->p_size_valid = 1;
   6345 	}
   6346 
   6347       /* Determine if this segment contains the ELF file header
   6348 	 and if it contains the program headers themselves.  */
   6349       map->includes_filehdr = (segment->p_offset == 0
   6350 			       && segment->p_filesz >= iehdr->e_ehsize);
   6351 
   6352       map->includes_phdrs = 0;
   6353       if (! phdr_included || segment->p_type != PT_LOAD)
   6354 	{
   6355 	  map->includes_phdrs =
   6356 	    (segment->p_offset <= (bfd_vma) iehdr->e_phoff
   6357 	     && (segment->p_offset + segment->p_filesz
   6358 		 >= ((bfd_vma) iehdr->e_phoff
   6359 		     + iehdr->e_phnum * iehdr->e_phentsize)));
   6360 
   6361 	  if (segment->p_type == PT_LOAD && map->includes_phdrs)
   6362 	    phdr_included = TRUE;
   6363 	}
   6364 
   6365       lowest_section = NULL;
   6366       if (section_count != 0)
   6367 	{
   6368 	  unsigned int isec = 0;
   6369 
   6370 	  for (section = first_section;
   6371 	       section != NULL;
   6372 	       section = section->next)
   6373 	    {
   6374 	      this_hdr = &(elf_section_data(section)->this_hdr);
   6375 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
   6376 		{
   6377 		  map->sections[isec++] = section->output_section;
   6378 		  if ((section->flags & SEC_ALLOC) != 0)
   6379 		    {
   6380 		      bfd_vma seg_off;
   6381 
   6382 		      if (lowest_section == NULL
   6383 			  || section->lma < lowest_section->lma)
   6384 			lowest_section = section;
   6385 
   6386 		      /* Section lmas are set up from PT_LOAD header
   6387 			 p_paddr in _bfd_elf_make_section_from_shdr.
   6388 			 If this header has a p_paddr that disagrees
   6389 			 with the section lma, flag the p_paddr as
   6390 			 invalid.  */
   6391 		      if ((section->flags & SEC_LOAD) != 0)
   6392 			seg_off = this_hdr->sh_offset - segment->p_offset;
   6393 		      else
   6394 			seg_off = this_hdr->sh_addr - segment->p_vaddr;
   6395 		      if (section->lma - segment->p_paddr != seg_off)
   6396 			map->p_paddr_valid = FALSE;
   6397 		    }
   6398 		  if (isec == section_count)
   6399 		    break;
   6400 		}
   6401 	    }
   6402 	}
   6403 
   6404       if (map->includes_filehdr && lowest_section != NULL)
   6405 	/* We need to keep the space used by the headers fixed.  */
   6406 	map->header_size = lowest_section->vma - segment->p_vaddr;
   6407 
   6408       if (!map->includes_phdrs
   6409 	  && !map->includes_filehdr
   6410 	  && map->p_paddr_valid)
   6411 	/* There is some other padding before the first section.  */
   6412 	map->p_vaddr_offset = ((lowest_section ? lowest_section->lma : 0)
   6413 			       - segment->p_paddr);
   6414 
   6415       map->count = section_count;
   6416       *pointer_to_map = map;
   6417       pointer_to_map = &map->next;
   6418     }
   6419 
   6420   elf_seg_map (obfd) = map_first;
   6421   return TRUE;
   6422 }
   6423 
   6424 /* Copy private BFD data.  This copies or rewrites ELF program header
   6425    information.  */
   6426 
   6427 static bfd_boolean
   6428 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
   6429 {
   6430   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
   6431       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
   6432     return TRUE;
   6433 
   6434   if (elf_tdata (ibfd)->phdr == NULL)
   6435     return TRUE;
   6436 
   6437   if (ibfd->xvec == obfd->xvec)
   6438     {
   6439       /* Check to see if any sections in the input BFD
   6440 	 covered by ELF program header have changed.  */
   6441       Elf_Internal_Phdr *segment;
   6442       asection *section, *osec;
   6443       unsigned int i, num_segments;
   6444       Elf_Internal_Shdr *this_hdr;
   6445       const struct elf_backend_data *bed;
   6446 
   6447       bed = get_elf_backend_data (ibfd);
   6448 
   6449       /* Regenerate the segment map if p_paddr is set to 0.  */
   6450       if (bed->want_p_paddr_set_to_zero)
   6451 	goto rewrite;
   6452 
   6453       /* Initialize the segment mark field.  */
   6454       for (section = obfd->sections; section != NULL;
   6455 	   section = section->next)
   6456 	section->segment_mark = FALSE;
   6457 
   6458       num_segments = elf_elfheader (ibfd)->e_phnum;
   6459       for (i = 0, segment = elf_tdata (ibfd)->phdr;
   6460 	   i < num_segments;
   6461 	   i++, segment++)
   6462 	{
   6463 	  /* PR binutils/3535.  The Solaris linker always sets the p_paddr
   6464 	     and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
   6465 	     which severly confuses things, so always regenerate the segment
   6466 	     map in this case.  */
   6467 	  if (segment->p_paddr == 0
   6468 	      && segment->p_memsz == 0
   6469 	      && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
   6470 	    goto rewrite;
   6471 
   6472 	  for (section = ibfd->sections;
   6473 	       section != NULL; section = section->next)
   6474 	    {
   6475 	      /* We mark the output section so that we know it comes
   6476 		 from the input BFD.  */
   6477 	      osec = section->output_section;
   6478 	      if (osec)
   6479 		osec->segment_mark = TRUE;
   6480 
   6481 	      /* Check if this section is covered by the segment.  */
   6482 	      this_hdr = &(elf_section_data(section)->this_hdr);
   6483 	      if (ELF_SECTION_IN_SEGMENT (this_hdr, segment))
   6484 		{
   6485 		  /* FIXME: Check if its output section is changed or
   6486 		     removed.  What else do we need to check?  */
   6487 		  if (osec == NULL
   6488 		      || section->flags != osec->flags
   6489 		      || section->lma != osec->lma
   6490 		      || section->vma != osec->vma
   6491 		      || section->size != osec->size
   6492 		      || section->rawsize != osec->rawsize
   6493 		      || section->alignment_power != osec->alignment_power)
   6494 		    goto rewrite;
   6495 		}
   6496 	    }
   6497 	}
   6498 
   6499       /* Check to see if any output section do not come from the
   6500 	 input BFD.  */
   6501       for (section = obfd->sections; section != NULL;
   6502 	   section = section->next)
   6503 	{
   6504 	  if (section->segment_mark == FALSE)
   6505 	    goto rewrite;
   6506 	  else
   6507 	    section->segment_mark = FALSE;
   6508 	}
   6509 
   6510       return copy_elf_program_header (ibfd, obfd);
   6511     }
   6512 
   6513 rewrite:
   6514   if (ibfd->xvec == obfd->xvec)
   6515     {
   6516       /* When rewriting program header, set the output maxpagesize to
   6517 	 the maximum alignment of input PT_LOAD segments.  */
   6518       Elf_Internal_Phdr *segment;
   6519       unsigned int i;
   6520       unsigned int num_segments = elf_elfheader (ibfd)->e_phnum;
   6521       bfd_vma maxpagesize = 0;
   6522 
   6523       for (i = 0, segment = elf_tdata (ibfd)->phdr;
   6524 	   i < num_segments;
   6525 	   i++, segment++)
   6526 	if (segment->p_type == PT_LOAD
   6527 	    && maxpagesize < segment->p_align)
   6528 	  maxpagesize = segment->p_align;
   6529 
   6530       if (maxpagesize != get_elf_backend_data (obfd)->maxpagesize)
   6531 	bfd_emul_set_maxpagesize (bfd_get_target (obfd), maxpagesize);
   6532     }
   6533 
   6534   return rewrite_elf_program_header (ibfd, obfd);
   6535 }
   6536 
   6537 /* Initialize private output section information from input section.  */
   6538 
   6539 bfd_boolean
   6540 _bfd_elf_init_private_section_data (bfd *ibfd,
   6541 				    asection *isec,
   6542 				    bfd *obfd,
   6543 				    asection *osec,
   6544 				    struct bfd_link_info *link_info)
   6545 
   6546 {
   6547   Elf_Internal_Shdr *ihdr, *ohdr;
   6548   bfd_boolean final_link = link_info != NULL && !link_info->relocatable;
   6549 
   6550   if (ibfd->xvec->flavour != bfd_target_elf_flavour
   6551       || obfd->xvec->flavour != bfd_target_elf_flavour)
   6552     return TRUE;
   6553 
   6554   BFD_ASSERT (elf_section_data (osec) != NULL);
   6555 
   6556   /* For objcopy and relocatable link, don't copy the output ELF
   6557      section type from input if the output BFD section flags have been
   6558      set to something different.  For a final link allow some flags
   6559      that the linker clears to differ.  */
   6560   if (elf_section_type (osec) == SHT_NULL
   6561       && (osec->flags == isec->flags
   6562 	  || (final_link
   6563 	      && ((osec->flags ^ isec->flags)
   6564 		  & ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC)) == 0)))
   6565     elf_section_type (osec) = elf_section_type (isec);
   6566 
   6567   /* FIXME: Is this correct for all OS/PROC specific flags?  */
   6568   elf_section_flags (osec) |= (elf_section_flags (isec)
   6569 			       & (SHF_MASKOS | SHF_MASKPROC));
   6570 
   6571   /* Set things up for objcopy and relocatable link.  The output
   6572      SHT_GROUP section will have its elf_next_in_group pointing back
   6573      to the input group members.  Ignore linker created group section.
   6574      See elfNN_ia64_object_p in elfxx-ia64.c.  */
   6575   if (!final_link)
   6576     {
   6577       if (elf_sec_group (isec) == NULL
   6578 	  || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0)
   6579 	{
   6580 	  if (elf_section_flags (isec) & SHF_GROUP)
   6581 	    elf_section_flags (osec) |= SHF_GROUP;
   6582 	  elf_next_in_group (osec) = elf_next_in_group (isec);
   6583 	  elf_section_data (osec)->group = elf_section_data (isec)->group;
   6584 	}
   6585     }
   6586 
   6587   ihdr = &elf_section_data (isec)->this_hdr;
   6588 
   6589   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
   6590      don't use the output section of the linked-to section since it
   6591      may be NULL at this point.  */
   6592   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
   6593     {
   6594       ohdr = &elf_section_data (osec)->this_hdr;
   6595       ohdr->sh_flags |= SHF_LINK_ORDER;
   6596       elf_linked_to_section (osec) = elf_linked_to_section (isec);
   6597     }
   6598 
   6599   osec->use_rela_p = isec->use_rela_p;
   6600 
   6601   return TRUE;
   6602 }
   6603 
   6604 /* Copy private section information.  This copies over the entsize
   6605    field, and sometimes the info field.  */
   6606 
   6607 bfd_boolean
   6608 _bfd_elf_copy_private_section_data (bfd *ibfd,
   6609 				    asection *isec,
   6610 				    bfd *obfd,
   6611 				    asection *osec)
   6612 {
   6613   Elf_Internal_Shdr *ihdr, *ohdr;
   6614 
   6615   if (ibfd->xvec->flavour != bfd_target_elf_flavour
   6616       || obfd->xvec->flavour != bfd_target_elf_flavour)
   6617     return TRUE;
   6618 
   6619   ihdr = &elf_section_data (isec)->this_hdr;
   6620   ohdr = &elf_section_data (osec)->this_hdr;
   6621 
   6622   ohdr->sh_entsize = ihdr->sh_entsize;
   6623 
   6624   if (ihdr->sh_type == SHT_SYMTAB
   6625       || ihdr->sh_type == SHT_DYNSYM
   6626       || ihdr->sh_type == SHT_GNU_verneed
   6627       || ihdr->sh_type == SHT_GNU_verdef)
   6628     ohdr->sh_info = ihdr->sh_info;
   6629 
   6630   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
   6631 					     NULL);
   6632 }
   6633 
   6634 /* Look at all the SHT_GROUP sections in IBFD, making any adjustments
   6635    necessary if we are removing either the SHT_GROUP section or any of
   6636    the group member sections.  DISCARDED is the value that a section's
   6637    output_section has if the section will be discarded, NULL when this
   6638    function is called from objcopy, bfd_abs_section_ptr when called
   6639    from the linker.  */
   6640 
   6641 bfd_boolean
   6642 _bfd_elf_fixup_group_sections (bfd *ibfd, asection *discarded)
   6643 {
   6644   asection *isec;
   6645 
   6646   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
   6647     if (elf_section_type (isec) == SHT_GROUP)
   6648       {
   6649 	asection *first = elf_next_in_group (isec);
   6650 	asection *s = first;
   6651 	bfd_size_type removed = 0;
   6652 
   6653 	while (s != NULL)
   6654 	  {
   6655 	    /* If this member section is being output but the
   6656 	       SHT_GROUP section is not, then clear the group info
   6657 	       set up by _bfd_elf_copy_private_section_data.  */
   6658 	    if (s->output_section != discarded
   6659 		&& isec->output_section == discarded)
   6660 	      {
   6661 		elf_section_flags (s->output_section) &= ~SHF_GROUP;
   6662 		elf_group_name (s->output_section) = NULL;
   6663 	      }
   6664 	    /* Conversely, if the member section is not being output
   6665 	       but the SHT_GROUP section is, then adjust its size.  */
   6666 	    else if (s->output_section == discarded
   6667 		     && isec->output_section != discarded)
   6668 	      removed += 4;
   6669 	    s = elf_next_in_group (s);
   6670 	    if (s == first)
   6671 	      break;
   6672 	  }
   6673 	if (removed != 0)
   6674 	  {
   6675 	    if (discarded != NULL)
   6676 	      {
   6677 		/* If we've been called for ld -r, then we need to
   6678 		   adjust the input section size.  This function may
   6679 		   be called multiple times, so save the original
   6680 		   size.  */
   6681 		if (isec->rawsize == 0)
   6682 		  isec->rawsize = isec->size;
   6683 		isec->size = isec->rawsize - removed;
   6684 	      }
   6685 	    else
   6686 	      {
   6687 		/* Adjust the output section size when called from
   6688 		   objcopy. */
   6689 		isec->output_section->size -= removed;
   6690 	      }
   6691 	  }
   6692       }
   6693 
   6694   return TRUE;
   6695 }
   6696 
   6697 /* Copy private header information.  */
   6698 
   6699 bfd_boolean
   6700 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
   6701 {
   6702   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
   6703       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
   6704     return TRUE;
   6705 
   6706   /* Copy over private BFD data if it has not already been copied.
   6707      This must be done here, rather than in the copy_private_bfd_data
   6708      entry point, because the latter is called after the section
   6709      contents have been set, which means that the program headers have
   6710      already been worked out.  */
   6711   if (elf_seg_map (obfd) == NULL && elf_tdata (ibfd)->phdr != NULL)
   6712     {
   6713       if (! copy_private_bfd_data (ibfd, obfd))
   6714 	return FALSE;
   6715     }
   6716 
   6717   return _bfd_elf_fixup_group_sections (ibfd, NULL);
   6718 }
   6719 
   6720 /* Copy private symbol information.  If this symbol is in a section
   6721    which we did not map into a BFD section, try to map the section
   6722    index correctly.  We use special macro definitions for the mapped
   6723    section indices; these definitions are interpreted by the
   6724    swap_out_syms function.  */
   6725 
   6726 #define MAP_ONESYMTAB (SHN_HIOS + 1)
   6727 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
   6728 #define MAP_STRTAB    (SHN_HIOS + 3)
   6729 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
   6730 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
   6731 
   6732 bfd_boolean
   6733 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
   6734 				   asymbol *isymarg,
   6735 				   bfd *obfd,
   6736 				   asymbol *osymarg)
   6737 {
   6738   elf_symbol_type *isym, *osym;
   6739 
   6740   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
   6741       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
   6742     return TRUE;
   6743 
   6744   isym = elf_symbol_from (ibfd, isymarg);
   6745   osym = elf_symbol_from (obfd, osymarg);
   6746 
   6747   if (isym != NULL
   6748       && isym->internal_elf_sym.st_shndx != 0
   6749       && osym != NULL
   6750       && bfd_is_abs_section (isym->symbol.section))
   6751     {
   6752       unsigned int shndx;
   6753 
   6754       shndx = isym->internal_elf_sym.st_shndx;
   6755       if (shndx == elf_onesymtab (ibfd))
   6756 	shndx = MAP_ONESYMTAB;
   6757       else if (shndx == elf_dynsymtab (ibfd))
   6758 	shndx = MAP_DYNSYMTAB;
   6759       else if (shndx == elf_strtab_sec (ibfd))
   6760 	shndx = MAP_STRTAB;
   6761       else if (shndx == elf_shstrtab_sec (ibfd))
   6762 	shndx = MAP_SHSTRTAB;
   6763       else if (shndx == elf_symtab_shndx (ibfd))
   6764 	shndx = MAP_SYM_SHNDX;
   6765       osym->internal_elf_sym.st_shndx = shndx;
   6766     }
   6767 
   6768   return TRUE;
   6769 }
   6770 
   6771 /* Swap out the symbols.  */
   6772 
   6773 static bfd_boolean
   6774 swap_out_syms (bfd *abfd,
   6775 	       struct bfd_strtab_hash **sttp,
   6776 	       int relocatable_p)
   6777 {
   6778   const struct elf_backend_data *bed;
   6779   int symcount;
   6780   asymbol **syms;
   6781   struct bfd_strtab_hash *stt;
   6782   Elf_Internal_Shdr *symtab_hdr;
   6783   Elf_Internal_Shdr *symtab_shndx_hdr;
   6784   Elf_Internal_Shdr *symstrtab_hdr;
   6785   bfd_byte *outbound_syms;
   6786   bfd_byte *outbound_shndx;
   6787   int idx;
   6788   unsigned int num_locals;
   6789   bfd_size_type amt;
   6790   bfd_boolean name_local_sections;
   6791 
   6792   if (!elf_map_symbols (abfd, &num_locals))
   6793     return FALSE;
   6794 
   6795   /* Dump out the symtabs.  */
   6796   stt = _bfd_elf_stringtab_init ();
   6797   if (stt == NULL)
   6798     return FALSE;
   6799 
   6800   bed = get_elf_backend_data (abfd);
   6801   symcount = bfd_get_symcount (abfd);
   6802   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
   6803   symtab_hdr->sh_type = SHT_SYMTAB;
   6804   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
   6805   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
   6806   symtab_hdr->sh_info = num_locals + 1;
   6807   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
   6808 
   6809   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
   6810   symstrtab_hdr->sh_type = SHT_STRTAB;
   6811 
   6812   outbound_syms = (bfd_byte *) bfd_alloc2 (abfd, 1 + symcount,
   6813                                            bed->s->sizeof_sym);
   6814   if (outbound_syms == NULL)
   6815     {
   6816       _bfd_stringtab_free (stt);
   6817       return FALSE;
   6818     }
   6819   symtab_hdr->contents = outbound_syms;
   6820 
   6821   outbound_shndx = NULL;
   6822   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
   6823   if (symtab_shndx_hdr->sh_name != 0)
   6824     {
   6825       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
   6826       outbound_shndx =  (bfd_byte *)
   6827           bfd_zalloc2 (abfd, 1 + symcount, sizeof (Elf_External_Sym_Shndx));
   6828       if (outbound_shndx == NULL)
   6829 	{
   6830 	  _bfd_stringtab_free (stt);
   6831 	  return FALSE;
   6832 	}
   6833 
   6834       symtab_shndx_hdr->contents = outbound_shndx;
   6835       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
   6836       symtab_shndx_hdr->sh_size = amt;
   6837       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
   6838       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
   6839     }
   6840 
   6841   /* Now generate the data (for "contents").  */
   6842   {
   6843     /* Fill in zeroth symbol and swap it out.  */
   6844     Elf_Internal_Sym sym;
   6845     sym.st_name = 0;
   6846     sym.st_value = 0;
   6847     sym.st_size = 0;
   6848     sym.st_info = 0;
   6849     sym.st_other = 0;
   6850     sym.st_shndx = SHN_UNDEF;
   6851     sym.st_target_internal = 0;
   6852     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
   6853     outbound_syms += bed->s->sizeof_sym;
   6854     if (outbound_shndx != NULL)
   6855       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
   6856   }
   6857 
   6858   name_local_sections
   6859     = (bed->elf_backend_name_local_section_symbols
   6860        && bed->elf_backend_name_local_section_symbols (abfd));
   6861 
   6862   syms = bfd_get_outsymbols (abfd);
   6863   for (idx = 0; idx < symcount; idx++)
   6864     {
   6865       Elf_Internal_Sym sym;
   6866       bfd_vma value = syms[idx]->value;
   6867       elf_symbol_type *type_ptr;
   6868       flagword flags = syms[idx]->flags;
   6869       int type;
   6870 
   6871       if (!name_local_sections
   6872 	  && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
   6873 	{
   6874 	  /* Local section symbols have no name.  */
   6875 	  sym.st_name = 0;
   6876 	}
   6877       else
   6878 	{
   6879 	  sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
   6880 							    syms[idx]->name,
   6881 							    TRUE, FALSE);
   6882 	  if (sym.st_name == (unsigned long) -1)
   6883 	    {
   6884 	      _bfd_stringtab_free (stt);
   6885 	      return FALSE;
   6886 	    }
   6887 	}
   6888 
   6889       type_ptr = elf_symbol_from (abfd, syms[idx]);
   6890 
   6891       if ((flags & BSF_SECTION_SYM) == 0
   6892 	  && bfd_is_com_section (syms[idx]->section))
   6893 	{
   6894 	  /* ELF common symbols put the alignment into the `value' field,
   6895 	     and the size into the `size' field.  This is backwards from
   6896 	     how BFD handles it, so reverse it here.  */
   6897 	  sym.st_size = value;
   6898 	  if (type_ptr == NULL
   6899 	      || type_ptr->internal_elf_sym.st_value == 0)
   6900 	    sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
   6901 	  else
   6902 	    sym.st_value = type_ptr->internal_elf_sym.st_value;
   6903 	  sym.st_shndx = _bfd_elf_section_from_bfd_section
   6904 	    (abfd, syms[idx]->section);
   6905 	}
   6906       else
   6907 	{
   6908 	  asection *sec = syms[idx]->section;
   6909 	  unsigned int shndx;
   6910 
   6911 	  if (sec->output_section)
   6912 	    {
   6913 	      value += sec->output_offset;
   6914 	      sec = sec->output_section;
   6915 	    }
   6916 
   6917 	  /* Don't add in the section vma for relocatable output.  */
   6918 	  if (! relocatable_p)
   6919 	    value += sec->vma;
   6920 	  sym.st_value = value;
   6921 	  sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
   6922 
   6923 	  if (bfd_is_abs_section (sec)
   6924 	      && type_ptr != NULL
   6925 	      && type_ptr->internal_elf_sym.st_shndx != 0)
   6926 	    {
   6927 	      /* This symbol is in a real ELF section which we did
   6928 		 not create as a BFD section.  Undo the mapping done
   6929 		 by copy_private_symbol_data.  */
   6930 	      shndx = type_ptr->internal_elf_sym.st_shndx;
   6931 	      switch (shndx)
   6932 		{
   6933 		case MAP_ONESYMTAB:
   6934 		  shndx = elf_onesymtab (abfd);
   6935 		  break;
   6936 		case MAP_DYNSYMTAB:
   6937 		  shndx = elf_dynsymtab (abfd);
   6938 		  break;
   6939 		case MAP_STRTAB:
   6940 		  shndx = elf_strtab_sec (abfd);
   6941 		  break;
   6942 		case MAP_SHSTRTAB:
   6943 		  shndx = elf_shstrtab_sec (abfd);
   6944 		  break;
   6945 		case MAP_SYM_SHNDX:
   6946 		  shndx = elf_symtab_shndx (abfd);
   6947 		  break;
   6948 		default:
   6949 		  shndx = SHN_ABS;
   6950 		  break;
   6951 		}
   6952 	    }
   6953 	  else
   6954 	    {
   6955 	      shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
   6956 
   6957 	      if (shndx == SHN_BAD)
   6958 		{
   6959 		  asection *sec2;
   6960 
   6961 		  /* Writing this would be a hell of a lot easier if
   6962 		     we had some decent documentation on bfd, and
   6963 		     knew what to expect of the library, and what to
   6964 		     demand of applications.  For example, it
   6965 		     appears that `objcopy' might not set the
   6966 		     section of a symbol to be a section that is
   6967 		     actually in the output file.  */
   6968 		  sec2 = bfd_get_section_by_name (abfd, sec->name);
   6969 		  if (sec2 == NULL)
   6970 		    {
   6971 		      _bfd_error_handler (_("\
   6972 Unable to find equivalent output section for symbol '%s' from section '%s'"),
   6973 					  syms[idx]->name ? syms[idx]->name : "<Local sym>",
   6974 					  sec->name);
   6975 		      bfd_set_error (bfd_error_invalid_operation);
   6976 		      _bfd_stringtab_free (stt);
   6977 		      return FALSE;
   6978 		    }
   6979 
   6980 		  shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
   6981 		  BFD_ASSERT (shndx != SHN_BAD);
   6982 		}
   6983 	    }
   6984 
   6985 	  sym.st_shndx = shndx;
   6986 	}
   6987 
   6988       if ((flags & BSF_THREAD_LOCAL) != 0)
   6989 	type = STT_TLS;
   6990       else if ((flags & BSF_GNU_INDIRECT_FUNCTION) != 0)
   6991 	type = STT_GNU_IFUNC;
   6992       else if ((flags & BSF_FUNCTION) != 0)
   6993 	type = STT_FUNC;
   6994       else if ((flags & BSF_OBJECT) != 0)
   6995 	type = STT_OBJECT;
   6996       else if ((flags & BSF_RELC) != 0)
   6997 	type = STT_RELC;
   6998       else if ((flags & BSF_SRELC) != 0)
   6999 	type = STT_SRELC;
   7000       else
   7001 	type = STT_NOTYPE;
   7002 
   7003       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
   7004 	type = STT_TLS;
   7005 
   7006       /* Processor-specific types.  */
   7007       if (type_ptr != NULL
   7008 	  && bed->elf_backend_get_symbol_type)
   7009 	type = ((*bed->elf_backend_get_symbol_type)
   7010 		(&type_ptr->internal_elf_sym, type));
   7011 
   7012       if (flags & BSF_SECTION_SYM)
   7013 	{
   7014 	  if (flags & BSF_GLOBAL)
   7015 	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
   7016 	  else
   7017 	    sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
   7018 	}
   7019       else if (bfd_is_com_section (syms[idx]->section))
   7020 	{
   7021 #ifdef USE_STT_COMMON
   7022 	  if (type == STT_OBJECT)
   7023 	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_COMMON);
   7024 	  else
   7025 #endif
   7026 	    sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
   7027 	}
   7028       else if (bfd_is_und_section (syms[idx]->section))
   7029 	sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
   7030 				    ? STB_WEAK
   7031 				    : STB_GLOBAL),
   7032 				   type);
   7033       else if (flags & BSF_FILE)
   7034 	sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
   7035       else
   7036 	{
   7037 	  int bind = STB_LOCAL;
   7038 
   7039 	  if (flags & BSF_LOCAL)
   7040 	    bind = STB_LOCAL;
   7041 	  else if (flags & BSF_GNU_UNIQUE)
   7042 	    bind = STB_GNU_UNIQUE;
   7043 	  else if (flags & BSF_WEAK)
   7044 	    bind = STB_WEAK;
   7045 	  else if (flags & BSF_GLOBAL)
   7046 	    bind = STB_GLOBAL;
   7047 
   7048 	  sym.st_info = ELF_ST_INFO (bind, type);
   7049 	}
   7050 
   7051       if (type_ptr != NULL)
   7052 	{
   7053 	  sym.st_other = type_ptr->internal_elf_sym.st_other;
   7054 	  sym.st_target_internal
   7055 	    = type_ptr->internal_elf_sym.st_target_internal;
   7056 	}
   7057       else
   7058 	{
   7059 	  sym.st_other = 0;
   7060 	  sym.st_target_internal = 0;
   7061 	}
   7062 
   7063       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
   7064       outbound_syms += bed->s->sizeof_sym;
   7065       if (outbound_shndx != NULL)
   7066 	outbound_shndx += sizeof (Elf_External_Sym_Shndx);
   7067     }
   7068 
   7069   *sttp = stt;
   7070   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
   7071   symstrtab_hdr->sh_type = SHT_STRTAB;
   7072 
   7073   symstrtab_hdr->sh_flags = 0;
   7074   symstrtab_hdr->sh_addr = 0;
   7075   symstrtab_hdr->sh_entsize = 0;
   7076   symstrtab_hdr->sh_link = 0;
   7077   symstrtab_hdr->sh_info = 0;
   7078   symstrtab_hdr->sh_addralign = 1;
   7079 
   7080   return TRUE;
   7081 }
   7082 
   7083 /* Return the number of bytes required to hold the symtab vector.
   7084 
   7085    Note that we base it on the count plus 1, since we will null terminate
   7086    the vector allocated based on this size.  However, the ELF symbol table
   7087    always has a dummy entry as symbol #0, so it ends up even.  */
   7088 
   7089 long
   7090 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
   7091 {
   7092   long symcount;
   7093   long symtab_size;
   7094   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
   7095 
   7096   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
   7097   symtab_size = (symcount + 1) * (sizeof (asymbol *));
   7098   if (symcount > 0)
   7099     symtab_size -= sizeof (asymbol *);
   7100 
   7101   return symtab_size;
   7102 }
   7103 
   7104 long
   7105 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
   7106 {
   7107   long symcount;
   7108   long symtab_size;
   7109   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
   7110 
   7111   if (elf_dynsymtab (abfd) == 0)
   7112     {
   7113       bfd_set_error (bfd_error_invalid_operation);
   7114       return -1;
   7115     }
   7116 
   7117   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
   7118   symtab_size = (symcount + 1) * (sizeof (asymbol *));
   7119   if (symcount > 0)
   7120     symtab_size -= sizeof (asymbol *);
   7121 
   7122   return symtab_size;
   7123 }
   7124 
   7125 long
   7126 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
   7127 				sec_ptr asect)
   7128 {
   7129   return (asect->reloc_count + 1) * sizeof (arelent *);
   7130 }
   7131 
   7132 /* Canonicalize the relocs.  */
   7133 
   7134 long
   7135 _bfd_elf_canonicalize_reloc (bfd *abfd,
   7136 			     sec_ptr section,
   7137 			     arelent **relptr,
   7138 			     asymbol **symbols)
   7139 {
   7140   arelent *tblptr;
   7141   unsigned int i;
   7142   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   7143 
   7144   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
   7145     return -1;
   7146 
   7147   tblptr = section->relocation;
   7148   for (i = 0; i < section->reloc_count; i++)
   7149     *relptr++ = tblptr++;
   7150 
   7151   *relptr = NULL;
   7152 
   7153   return section->reloc_count;
   7154 }
   7155 
   7156 long
   7157 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
   7158 {
   7159   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   7160   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
   7161 
   7162   if (symcount >= 0)
   7163     bfd_get_symcount (abfd) = symcount;
   7164   return symcount;
   7165 }
   7166 
   7167 long
   7168 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
   7169 				      asymbol **allocation)
   7170 {
   7171   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
   7172   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
   7173 
   7174   if (symcount >= 0)
   7175     bfd_get_dynamic_symcount (abfd) = symcount;
   7176   return symcount;
   7177 }
   7178 
   7179 /* Return the size required for the dynamic reloc entries.  Any loadable
   7180    section that was actually installed in the BFD, and has type SHT_REL
   7181    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
   7182    dynamic reloc section.  */
   7183 
   7184 long
   7185 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
   7186 {
   7187   long ret;
   7188   asection *s;
   7189 
   7190   if (elf_dynsymtab (abfd) == 0)
   7191     {
   7192       bfd_set_error (bfd_error_invalid_operation);
   7193       return -1;
   7194     }
   7195 
   7196   ret = sizeof (arelent *);
   7197   for (s = abfd->sections; s != NULL; s = s->next)
   7198     if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (