Back to index

cell-binutils  2.17cvs20070401
elf.c
Go to the documentation of this file.
00001 /* ELF executable support for BFD.
00002 
00003    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
00004    2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
00005 
00006    This file is part of BFD, the Binary File Descriptor library.
00007 
00008    This program is free software; you can redistribute it and/or modify
00009    it under the terms of the GNU General Public License as published by
00010    the Free Software Foundation; either version 2 of the License, or
00011    (at your option) any later version.
00012 
00013    This program is distributed in the hope that it will be useful,
00014    but WITHOUT ANY WARRANTY; without even the implied warranty of
00015    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016    GNU General Public License for more details.
00017 
00018    You should have received a copy of the GNU General Public License
00019    along with this program; if not, write to the Free Software
00020    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
00021 
00022 /*
00023 SECTION
00024        ELF backends
00025 
00026        BFD support for ELF formats is being worked on.
00027        Currently, the best supported back ends are for sparc and i386
00028        (running svr4 or Solaris 2).
00029 
00030        Documentation of the internals of the support code still needs
00031        to be written.  The code is changing quickly enough that we
00032        haven't bothered yet.  */
00033 
00034 /* For sparc64-cross-sparc32.  */
00035 #define _SYSCALL32
00036 #include "bfd.h"
00037 #include "sysdep.h"
00038 #include "bfdlink.h"
00039 #include "libbfd.h"
00040 #define ARCH_SIZE 0
00041 #include "elf-bfd.h"
00042 #include "libiberty.h"
00043 
00044 static int elf_sort_sections (const void *, const void *);
00045 static bfd_boolean assign_file_positions_except_relocs (bfd *, struct bfd_link_info *);
00046 static bfd_boolean prep_headers (bfd *);
00047 static bfd_boolean swap_out_syms (bfd *, struct bfd_strtab_hash **, int) ;
00048 static bfd_boolean elfcore_read_notes (bfd *, file_ptr, bfd_size_type) ;
00049 
00050 /* Swap version information in and out.  The version information is
00051    currently size independent.  If that ever changes, this code will
00052    need to move into elfcode.h.  */
00053 
00054 /* Swap in a Verdef structure.  */
00055 
00056 void
00057 _bfd_elf_swap_verdef_in (bfd *abfd,
00058                       const Elf_External_Verdef *src,
00059                       Elf_Internal_Verdef *dst)
00060 {
00061   dst->vd_version = H_GET_16 (abfd, src->vd_version);
00062   dst->vd_flags   = H_GET_16 (abfd, src->vd_flags);
00063   dst->vd_ndx     = H_GET_16 (abfd, src->vd_ndx);
00064   dst->vd_cnt     = H_GET_16 (abfd, src->vd_cnt);
00065   dst->vd_hash    = H_GET_32 (abfd, src->vd_hash);
00066   dst->vd_aux     = H_GET_32 (abfd, src->vd_aux);
00067   dst->vd_next    = H_GET_32 (abfd, src->vd_next);
00068 }
00069 
00070 /* Swap out a Verdef structure.  */
00071 
00072 void
00073 _bfd_elf_swap_verdef_out (bfd *abfd,
00074                        const Elf_Internal_Verdef *src,
00075                        Elf_External_Verdef *dst)
00076 {
00077   H_PUT_16 (abfd, src->vd_version, dst->vd_version);
00078   H_PUT_16 (abfd, src->vd_flags, dst->vd_flags);
00079   H_PUT_16 (abfd, src->vd_ndx, dst->vd_ndx);
00080   H_PUT_16 (abfd, src->vd_cnt, dst->vd_cnt);
00081   H_PUT_32 (abfd, src->vd_hash, dst->vd_hash);
00082   H_PUT_32 (abfd, src->vd_aux, dst->vd_aux);
00083   H_PUT_32 (abfd, src->vd_next, dst->vd_next);
00084 }
00085 
00086 /* Swap in a Verdaux structure.  */
00087 
00088 void
00089 _bfd_elf_swap_verdaux_in (bfd *abfd,
00090                        const Elf_External_Verdaux *src,
00091                        Elf_Internal_Verdaux *dst)
00092 {
00093   dst->vda_name = H_GET_32 (abfd, src->vda_name);
00094   dst->vda_next = H_GET_32 (abfd, src->vda_next);
00095 }
00096 
00097 /* Swap out a Verdaux structure.  */
00098 
00099 void
00100 _bfd_elf_swap_verdaux_out (bfd *abfd,
00101                         const Elf_Internal_Verdaux *src,
00102                         Elf_External_Verdaux *dst)
00103 {
00104   H_PUT_32 (abfd, src->vda_name, dst->vda_name);
00105   H_PUT_32 (abfd, src->vda_next, dst->vda_next);
00106 }
00107 
00108 /* Swap in a Verneed structure.  */
00109 
00110 void
00111 _bfd_elf_swap_verneed_in (bfd *abfd,
00112                        const Elf_External_Verneed *src,
00113                        Elf_Internal_Verneed *dst)
00114 {
00115   dst->vn_version = H_GET_16 (abfd, src->vn_version);
00116   dst->vn_cnt     = H_GET_16 (abfd, src->vn_cnt);
00117   dst->vn_file    = H_GET_32 (abfd, src->vn_file);
00118   dst->vn_aux     = H_GET_32 (abfd, src->vn_aux);
00119   dst->vn_next    = H_GET_32 (abfd, src->vn_next);
00120 }
00121 
00122 /* Swap out a Verneed structure.  */
00123 
00124 void
00125 _bfd_elf_swap_verneed_out (bfd *abfd,
00126                         const Elf_Internal_Verneed *src,
00127                         Elf_External_Verneed *dst)
00128 {
00129   H_PUT_16 (abfd, src->vn_version, dst->vn_version);
00130   H_PUT_16 (abfd, src->vn_cnt, dst->vn_cnt);
00131   H_PUT_32 (abfd, src->vn_file, dst->vn_file);
00132   H_PUT_32 (abfd, src->vn_aux, dst->vn_aux);
00133   H_PUT_32 (abfd, src->vn_next, dst->vn_next);
00134 }
00135 
00136 /* Swap in a Vernaux structure.  */
00137 
00138 void
00139 _bfd_elf_swap_vernaux_in (bfd *abfd,
00140                        const Elf_External_Vernaux *src,
00141                        Elf_Internal_Vernaux *dst)
00142 {
00143   dst->vna_hash  = H_GET_32 (abfd, src->vna_hash);
00144   dst->vna_flags = H_GET_16 (abfd, src->vna_flags);
00145   dst->vna_other = H_GET_16 (abfd, src->vna_other);
00146   dst->vna_name  = H_GET_32 (abfd, src->vna_name);
00147   dst->vna_next  = H_GET_32 (abfd, src->vna_next);
00148 }
00149 
00150 /* Swap out a Vernaux structure.  */
00151 
00152 void
00153 _bfd_elf_swap_vernaux_out (bfd *abfd,
00154                         const Elf_Internal_Vernaux *src,
00155                         Elf_External_Vernaux *dst)
00156 {
00157   H_PUT_32 (abfd, src->vna_hash, dst->vna_hash);
00158   H_PUT_16 (abfd, src->vna_flags, dst->vna_flags);
00159   H_PUT_16 (abfd, src->vna_other, dst->vna_other);
00160   H_PUT_32 (abfd, src->vna_name, dst->vna_name);
00161   H_PUT_32 (abfd, src->vna_next, dst->vna_next);
00162 }
00163 
00164 /* Swap in a Versym structure.  */
00165 
00166 void
00167 _bfd_elf_swap_versym_in (bfd *abfd,
00168                       const Elf_External_Versym *src,
00169                       Elf_Internal_Versym *dst)
00170 {
00171   dst->vs_vers = H_GET_16 (abfd, src->vs_vers);
00172 }
00173 
00174 /* Swap out a Versym structure.  */
00175 
00176 void
00177 _bfd_elf_swap_versym_out (bfd *abfd,
00178                        const Elf_Internal_Versym *src,
00179                        Elf_External_Versym *dst)
00180 {
00181   H_PUT_16 (abfd, src->vs_vers, dst->vs_vers);
00182 }
00183 
00184 /* Standard ELF hash function.  Do not change this function; you will
00185    cause invalid hash tables to be generated.  */
00186 
00187 unsigned long
00188 bfd_elf_hash (const char *namearg)
00189 {
00190   const unsigned char *name = (const unsigned char *) namearg;
00191   unsigned long h = 0;
00192   unsigned long g;
00193   int ch;
00194 
00195   while ((ch = *name++) != '\0')
00196     {
00197       h = (h << 4) + ch;
00198       if ((g = (h & 0xf0000000)) != 0)
00199        {
00200          h ^= g >> 24;
00201          /* The ELF ABI says `h &= ~g', but this is equivalent in
00202             this case and on some machines one insn instead of two.  */
00203          h ^= g;
00204        }
00205     }
00206   return h & 0xffffffff;
00207 }
00208 
00209 /* DT_GNU_HASH hash function.  Do not change this function; you will
00210    cause invalid hash tables to be generated.  */
00211 
00212 unsigned long
00213 bfd_elf_gnu_hash (const char *namearg)
00214 {
00215   const unsigned char *name = (const unsigned char *) namearg;
00216   unsigned long h = 5381;
00217   unsigned char ch;
00218 
00219   while ((ch = *name++) != '\0')
00220     h = (h << 5) + h + ch;
00221   return h & 0xffffffff;
00222 }
00223 
00224 bfd_boolean
00225 bfd_elf_mkobject (bfd *abfd)
00226 {
00227   if (abfd->tdata.any == NULL)
00228     {
00229       abfd->tdata.any = bfd_zalloc (abfd, sizeof (struct elf_obj_tdata));
00230       if (abfd->tdata.any == NULL)
00231        return FALSE;
00232     }
00233 
00234   elf_tdata (abfd)->program_header_size = (bfd_size_type) -1;
00235 
00236   return TRUE;
00237 }
00238 
00239 bfd_boolean
00240 bfd_elf_mkcorefile (bfd *abfd)
00241 {
00242   /* I think this can be done just like an object file.  */
00243   return bfd_elf_mkobject (abfd);
00244 }
00245 
00246 char *
00247 bfd_elf_get_str_section (bfd *abfd, unsigned int shindex)
00248 {
00249   Elf_Internal_Shdr **i_shdrp;
00250   bfd_byte *shstrtab = NULL;
00251   file_ptr offset;
00252   bfd_size_type shstrtabsize;
00253 
00254   i_shdrp = elf_elfsections (abfd);
00255   if (i_shdrp == 0 || i_shdrp[shindex] == 0)
00256     return NULL;
00257 
00258   shstrtab = i_shdrp[shindex]->contents;
00259   if (shstrtab == NULL)
00260     {
00261       /* No cached one, attempt to read, and cache what we read.  */
00262       offset = i_shdrp[shindex]->sh_offset;
00263       shstrtabsize = i_shdrp[shindex]->sh_size;
00264 
00265       /* Allocate and clear an extra byte at the end, to prevent crashes
00266         in case the string table is not terminated.  */
00267       if (shstrtabsize + 1 == 0
00268          || (shstrtab = bfd_alloc (abfd, shstrtabsize + 1)) == NULL
00269          || bfd_seek (abfd, offset, SEEK_SET) != 0)
00270        shstrtab = NULL;
00271       else if (bfd_bread (shstrtab, shstrtabsize, abfd) != shstrtabsize)
00272        {
00273          if (bfd_get_error () != bfd_error_system_call)
00274            bfd_set_error (bfd_error_file_truncated);
00275          shstrtab = NULL;
00276        }
00277       else
00278        shstrtab[shstrtabsize] = '\0';
00279       i_shdrp[shindex]->contents = shstrtab;
00280     }
00281   return (char *) shstrtab;
00282 }
00283 
00284 char *
00285 bfd_elf_string_from_elf_section (bfd *abfd,
00286                              unsigned int shindex,
00287                              unsigned int strindex)
00288 {
00289   Elf_Internal_Shdr *hdr;
00290 
00291   if (strindex == 0)
00292     return "";
00293 
00294   hdr = elf_elfsections (abfd)[shindex];
00295 
00296   if (hdr->contents == NULL
00297       && bfd_elf_get_str_section (abfd, shindex) == NULL)
00298     return NULL;
00299 
00300   if (strindex >= hdr->sh_size)
00301     {
00302       unsigned int shstrndx = elf_elfheader(abfd)->e_shstrndx;
00303       (*_bfd_error_handler)
00304        (_("%B: invalid string offset %u >= %lu for section `%s'"),
00305         abfd, strindex, (unsigned long) hdr->sh_size,
00306         (shindex == shstrndx && strindex == hdr->sh_name
00307          ? ".shstrtab"
00308          : bfd_elf_string_from_elf_section (abfd, shstrndx, hdr->sh_name)));
00309       return "";
00310     }
00311 
00312   return ((char *) hdr->contents) + strindex;
00313 }
00314 
00315 /* Read and convert symbols to internal format.
00316    SYMCOUNT specifies the number of symbols to read, starting from
00317    symbol SYMOFFSET.  If any of INTSYM_BUF, EXTSYM_BUF or EXTSHNDX_BUF
00318    are non-NULL, they are used to store the internal symbols, external
00319    symbols, and symbol section index extensions, respectively.  */
00320 
00321 Elf_Internal_Sym *
00322 bfd_elf_get_elf_syms (bfd *ibfd,
00323                     Elf_Internal_Shdr *symtab_hdr,
00324                     size_t symcount,
00325                     size_t symoffset,
00326                     Elf_Internal_Sym *intsym_buf,
00327                     void *extsym_buf,
00328                     Elf_External_Sym_Shndx *extshndx_buf)
00329 {
00330   Elf_Internal_Shdr *shndx_hdr;
00331   void *alloc_ext;
00332   const bfd_byte *esym;
00333   Elf_External_Sym_Shndx *alloc_extshndx;
00334   Elf_External_Sym_Shndx *shndx;
00335   Elf_Internal_Sym *isym;
00336   Elf_Internal_Sym *isymend;
00337   const struct elf_backend_data *bed;
00338   size_t extsym_size;
00339   bfd_size_type amt;
00340   file_ptr pos;
00341 
00342   if (symcount == 0)
00343     return intsym_buf;
00344 
00345   /* Normal syms might have section extension entries.  */
00346   shndx_hdr = NULL;
00347   if (symtab_hdr == &elf_tdata (ibfd)->symtab_hdr)
00348     shndx_hdr = &elf_tdata (ibfd)->symtab_shndx_hdr;
00349 
00350   /* Read the symbols.  */
00351   alloc_ext = NULL;
00352   alloc_extshndx = NULL;
00353   bed = get_elf_backend_data (ibfd);
00354   extsym_size = bed->s->sizeof_sym;
00355   amt = symcount * extsym_size;
00356   pos = symtab_hdr->sh_offset + symoffset * extsym_size;
00357   if (extsym_buf == NULL)
00358     {
00359       alloc_ext = bfd_malloc2 (symcount, extsym_size);
00360       extsym_buf = alloc_ext;
00361     }
00362   if (extsym_buf == NULL
00363       || bfd_seek (ibfd, pos, SEEK_SET) != 0
00364       || bfd_bread (extsym_buf, amt, ibfd) != amt)
00365     {
00366       intsym_buf = NULL;
00367       goto out;
00368     }
00369 
00370   if (shndx_hdr == NULL || shndx_hdr->sh_size == 0)
00371     extshndx_buf = NULL;
00372   else
00373     {
00374       amt = symcount * sizeof (Elf_External_Sym_Shndx);
00375       pos = shndx_hdr->sh_offset + symoffset * sizeof (Elf_External_Sym_Shndx);
00376       if (extshndx_buf == NULL)
00377        {
00378          alloc_extshndx = bfd_malloc2 (symcount,
00379                                    sizeof (Elf_External_Sym_Shndx));
00380          extshndx_buf = alloc_extshndx;
00381        }
00382       if (extshndx_buf == NULL
00383          || bfd_seek (ibfd, pos, SEEK_SET) != 0
00384          || bfd_bread (extshndx_buf, amt, ibfd) != amt)
00385        {
00386          intsym_buf = NULL;
00387          goto out;
00388        }
00389     }
00390 
00391   if (intsym_buf == NULL)
00392     {
00393       intsym_buf = bfd_malloc2 (symcount, sizeof (Elf_Internal_Sym));
00394       if (intsym_buf == NULL)
00395        goto out;
00396     }
00397 
00398   /* Convert the symbols to internal form.  */
00399   isymend = intsym_buf + symcount;
00400   for (esym = extsym_buf, isym = intsym_buf, shndx = extshndx_buf;
00401        isym < isymend;
00402        esym += extsym_size, isym++, shndx = shndx != NULL ? shndx + 1 : NULL)
00403     if (!(*bed->s->swap_symbol_in) (ibfd, esym, shndx, isym))
00404       {
00405        symoffset += (esym - (bfd_byte *) extsym_buf) / extsym_size;
00406        (*_bfd_error_handler) (_("%B symbol number %lu references "
00407                              "nonexistent SHT_SYMTAB_SHNDX section"),
00408                             ibfd, (unsigned long) symoffset);
00409        intsym_buf = NULL;
00410        goto out;
00411       }
00412 
00413  out:
00414   if (alloc_ext != NULL)
00415     free (alloc_ext);
00416   if (alloc_extshndx != NULL)
00417     free (alloc_extshndx);
00418 
00419   return intsym_buf;
00420 }
00421 
00422 /* Look up a symbol name.  */
00423 const char *
00424 bfd_elf_sym_name (bfd *abfd,
00425                 Elf_Internal_Shdr *symtab_hdr,
00426                 Elf_Internal_Sym *isym,
00427                 asection *sym_sec)
00428 {
00429   const char *name;
00430   unsigned int iname = isym->st_name;
00431   unsigned int shindex = symtab_hdr->sh_link;
00432 
00433   if (iname == 0 && ELF_ST_TYPE (isym->st_info) == STT_SECTION
00434       /* Check for a bogus st_shndx to avoid crashing.  */
00435       && isym->st_shndx < elf_numsections (abfd)
00436       && !(isym->st_shndx >= SHN_LORESERVE && isym->st_shndx <= SHN_HIRESERVE))
00437     {
00438       iname = elf_elfsections (abfd)[isym->st_shndx]->sh_name;
00439       shindex = elf_elfheader (abfd)->e_shstrndx;
00440     }
00441 
00442   name = bfd_elf_string_from_elf_section (abfd, shindex, iname);
00443   if (name == NULL)
00444     name = "(null)";
00445   else if (sym_sec && *name == '\0')
00446     name = bfd_section_name (abfd, sym_sec);
00447 
00448   return name;
00449 }
00450 
00451 /* Elf_Internal_Shdr->contents is an array of these for SHT_GROUP
00452    sections.  The first element is the flags, the rest are section
00453    pointers.  */
00454 
00455 typedef union elf_internal_group {
00456   Elf_Internal_Shdr *shdr;
00457   unsigned int flags;
00458 } Elf_Internal_Group;
00459 
00460 /* Return the name of the group signature symbol.  Why isn't the
00461    signature just a string?  */
00462 
00463 static const char *
00464 group_signature (bfd *abfd, Elf_Internal_Shdr *ghdr)
00465 {
00466   Elf_Internal_Shdr *hdr;
00467   unsigned char esym[sizeof (Elf64_External_Sym)];
00468   Elf_External_Sym_Shndx eshndx;
00469   Elf_Internal_Sym isym;
00470 
00471   /* First we need to ensure the symbol table is available.  Make sure
00472      that it is a symbol table section.  */
00473   hdr = elf_elfsections (abfd) [ghdr->sh_link];
00474   if (hdr->sh_type != SHT_SYMTAB
00475       || ! bfd_section_from_shdr (abfd, ghdr->sh_link))
00476     return NULL;
00477 
00478   /* Go read the symbol.  */
00479   hdr = &elf_tdata (abfd)->symtab_hdr;
00480   if (bfd_elf_get_elf_syms (abfd, hdr, 1, ghdr->sh_info,
00481                          &isym, esym, &eshndx) == NULL)
00482     return NULL;
00483 
00484   return bfd_elf_sym_name (abfd, hdr, &isym, NULL);
00485 }
00486 
00487 /* Set next_in_group list pointer, and group name for NEWSECT.  */
00488 
00489 static bfd_boolean
00490 setup_group (bfd *abfd, Elf_Internal_Shdr *hdr, asection *newsect)
00491 {
00492   unsigned int num_group = elf_tdata (abfd)->num_group;
00493 
00494   /* If num_group is zero, read in all SHT_GROUP sections.  The count
00495      is set to -1 if there are no SHT_GROUP sections.  */
00496   if (num_group == 0)
00497     {
00498       unsigned int i, shnum;
00499 
00500       /* First count the number of groups.  If we have a SHT_GROUP
00501         section with just a flag word (ie. sh_size is 4), ignore it.  */
00502       shnum = elf_numsections (abfd);
00503       num_group = 0;
00504       
00505 #define IS_VALID_GROUP_SECTION_HEADER(shdr)             \
00506        (   (shdr)->sh_type == SHT_GROUP          \
00507         && (shdr)->sh_size >= (2 * GRP_ENTRY_SIZE)      \
00508         && (shdr)->sh_entsize == GRP_ENTRY_SIZE  \
00509         && ((shdr)->sh_size % GRP_ENTRY_SIZE) == 0)
00510        
00511       for (i = 0; i < shnum; i++)
00512        {
00513          Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
00514 
00515          if (IS_VALID_GROUP_SECTION_HEADER (shdr))
00516            num_group += 1;
00517        }
00518 
00519       if (num_group == 0)
00520        {
00521          num_group = (unsigned) -1;
00522          elf_tdata (abfd)->num_group = num_group;
00523        }
00524       else
00525        {
00526          /* We keep a list of elf section headers for group sections,
00527             so we can find them quickly.  */
00528          bfd_size_type amt;
00529 
00530          elf_tdata (abfd)->num_group = num_group;
00531          elf_tdata (abfd)->group_sect_ptr
00532            = bfd_alloc2 (abfd, num_group, sizeof (Elf_Internal_Shdr *));
00533          if (elf_tdata (abfd)->group_sect_ptr == NULL)
00534            return FALSE;
00535 
00536          num_group = 0;
00537          for (i = 0; i < shnum; i++)
00538            {
00539              Elf_Internal_Shdr *shdr = elf_elfsections (abfd)[i];
00540 
00541              if (IS_VALID_GROUP_SECTION_HEADER (shdr))
00542               {
00543                 unsigned char *src;
00544                 Elf_Internal_Group *dest;
00545 
00546                 /* Add to list of sections.  */
00547                 elf_tdata (abfd)->group_sect_ptr[num_group] = shdr;
00548                 num_group += 1;
00549 
00550                 /* Read the raw contents.  */
00551                 BFD_ASSERT (sizeof (*dest) >= 4);
00552                 amt = shdr->sh_size * sizeof (*dest) / 4;
00553                 shdr->contents = bfd_alloc2 (abfd, shdr->sh_size,
00554                                           sizeof (*dest) / 4);
00555                 /* PR binutils/4110: Handle corrupt group headers.  */
00556                 if (shdr->contents == NULL)
00557                   {
00558                     _bfd_error_handler
00559                      (_("%B: Corrupt size field in group section header: 0x%lx"), abfd, shdr->sh_size);
00560                     bfd_set_error (bfd_error_bad_value);
00561                     return FALSE;
00562                   }
00563 
00564                 memset (shdr->contents, 0, amt);
00565 
00566                 if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0
00567                     || (bfd_bread (shdr->contents, shdr->sh_size, abfd)
00568                        != shdr->sh_size))
00569                   return FALSE;
00570 
00571                 /* Translate raw contents, a flag word followed by an
00572                    array of elf section indices all in target byte order,
00573                    to the flag word followed by an array of elf section
00574                    pointers.  */
00575                 src = shdr->contents + shdr->sh_size;
00576                 dest = (Elf_Internal_Group *) (shdr->contents + amt);
00577                 while (1)
00578                   {
00579                     unsigned int idx;
00580 
00581                     src -= 4;
00582                     --dest;
00583                     idx = H_GET_32 (abfd, src);
00584                     if (src == shdr->contents)
00585                      {
00586                        dest->flags = idx;
00587                        if (shdr->bfd_section != NULL && (idx & GRP_COMDAT))
00588                          shdr->bfd_section->flags
00589                            |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
00590                        break;
00591                      }
00592                     if (idx >= shnum)
00593                      {
00594                        ((*_bfd_error_handler)
00595                         (_("%B: invalid SHT_GROUP entry"), abfd));
00596                        idx = 0;
00597                      }
00598                     dest->shdr = elf_elfsections (abfd)[idx];
00599                   }
00600               }
00601            }
00602        }
00603     }
00604 
00605   if (num_group != (unsigned) -1)
00606     {
00607       unsigned int i;
00608 
00609       for (i = 0; i < num_group; i++)
00610        {
00611          Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
00612          Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
00613          unsigned int n_elt = shdr->sh_size / 4;
00614 
00615          /* Look through this group's sections to see if current
00616             section is a member.  */
00617          while (--n_elt != 0)
00618            if ((++idx)->shdr == hdr)
00619              {
00620               asection *s = NULL;
00621 
00622               /* We are a member of this group.  Go looking through
00623                  other members to see if any others are linked via
00624                  next_in_group.  */
00625               idx = (Elf_Internal_Group *) shdr->contents;
00626               n_elt = shdr->sh_size / 4;
00627               while (--n_elt != 0)
00628                 if ((s = (++idx)->shdr->bfd_section) != NULL
00629                     && elf_next_in_group (s) != NULL)
00630                   break;
00631               if (n_elt != 0)
00632                 {
00633                   /* Snarf the group name from other member, and
00634                      insert current section in circular list.  */
00635                   elf_group_name (newsect) = elf_group_name (s);
00636                   elf_next_in_group (newsect) = elf_next_in_group (s);
00637                   elf_next_in_group (s) = newsect;
00638                 }
00639               else
00640                 {
00641                   const char *gname;
00642 
00643                   gname = group_signature (abfd, shdr);
00644                   if (gname == NULL)
00645                     return FALSE;
00646                   elf_group_name (newsect) = gname;
00647 
00648                   /* Start a circular list with one element.  */
00649                   elf_next_in_group (newsect) = newsect;
00650                 }
00651 
00652               /* If the group section has been created, point to the
00653                  new member.  */
00654               if (shdr->bfd_section != NULL)
00655                 elf_next_in_group (shdr->bfd_section) = newsect;
00656 
00657               i = num_group - 1;
00658               break;
00659              }
00660        }
00661     }
00662 
00663   if (elf_group_name (newsect) == NULL)
00664     {
00665       (*_bfd_error_handler) (_("%B: no group info for section %A"),
00666                           abfd, newsect);
00667     }
00668   return TRUE;
00669 }
00670 
00671 bfd_boolean
00672 _bfd_elf_setup_sections (bfd *abfd)
00673 {
00674   unsigned int i;
00675   unsigned int num_group = elf_tdata (abfd)->num_group;
00676   bfd_boolean result = TRUE;
00677   asection *s;
00678 
00679   /* Process SHF_LINK_ORDER.  */
00680   for (s = abfd->sections; s != NULL; s = s->next)
00681     {
00682       Elf_Internal_Shdr *this_hdr = &elf_section_data (s)->this_hdr;
00683       if ((this_hdr->sh_flags & SHF_LINK_ORDER) != 0)
00684        {
00685          unsigned int elfsec = this_hdr->sh_link;
00686          /* FIXME: The old Intel compiler and old strip/objcopy may
00687             not set the sh_link or sh_info fields.  Hence we could
00688             get the situation where elfsec is 0.  */
00689          if (elfsec == 0)
00690            {
00691              const struct elf_backend_data *bed
00692               = get_elf_backend_data (abfd);
00693              if (bed->link_order_error_handler)
00694               bed->link_order_error_handler
00695                 (_("%B: warning: sh_link not set for section `%A'"),
00696                  abfd, s);
00697            }
00698          else
00699            {
00700              asection *link;
00701 
00702              this_hdr = elf_elfsections (abfd)[elfsec];
00703 
00704              /* PR 1991, 2008:
00705                Some strip/objcopy may leave an incorrect value in
00706                sh_link.  We don't want to proceed.  */
00707              link = this_hdr->bfd_section;
00708              if (link == NULL)
00709               {
00710                 (*_bfd_error_handler)
00711                   (_("%B: sh_link [%d] in section `%A' is incorrect"),
00712                    s->owner, s, elfsec);
00713                 result = FALSE;
00714               }
00715 
00716              elf_linked_to_section (s) = link;
00717            }
00718        }
00719     }
00720 
00721   /* Process section groups.  */
00722   if (num_group == (unsigned) -1)
00723     return result;
00724 
00725   for (i = 0; i < num_group; i++)
00726     {
00727       Elf_Internal_Shdr *shdr = elf_tdata (abfd)->group_sect_ptr[i];
00728       Elf_Internal_Group *idx = (Elf_Internal_Group *) shdr->contents;
00729       unsigned int n_elt = shdr->sh_size / 4;
00730 
00731       while (--n_elt != 0)
00732        if ((++idx)->shdr->bfd_section)
00733          elf_sec_group (idx->shdr->bfd_section) = shdr->bfd_section;
00734        else if (idx->shdr->sh_type == SHT_RELA
00735                || idx->shdr->sh_type == SHT_REL)
00736          /* We won't include relocation sections in section groups in
00737             output object files. We adjust the group section size here
00738             so that relocatable link will work correctly when
00739             relocation sections are in section group in input object
00740             files.  */
00741          shdr->bfd_section->size -= 4;
00742        else
00743          {
00744            /* There are some unknown sections in the group.  */
00745            (*_bfd_error_handler)
00746              (_("%B: unknown [%d] section `%s' in group [%s]"),
00747               abfd,
00748               (unsigned int) idx->shdr->sh_type,
00749               bfd_elf_string_from_elf_section (abfd,
00750                                           (elf_elfheader (abfd)
00751                                            ->e_shstrndx),
00752                                           idx->shdr->sh_name),
00753               shdr->bfd_section->name);
00754            result = FALSE;
00755          }
00756     }
00757   return result;
00758 }
00759 
00760 bfd_boolean
00761 bfd_elf_is_group_section (bfd *abfd ATTRIBUTE_UNUSED, const asection *sec)
00762 {
00763   return elf_next_in_group (sec) != NULL;
00764 }
00765 
00766 /* Make a BFD section from an ELF section.  We store a pointer to the
00767    BFD section in the bfd_section field of the header.  */
00768 
00769 bfd_boolean
00770 _bfd_elf_make_section_from_shdr (bfd *abfd,
00771                              Elf_Internal_Shdr *hdr,
00772                              const char *name,
00773                              int shindex)
00774 {
00775   asection *newsect;
00776   flagword flags;
00777   const struct elf_backend_data *bed;
00778 
00779   if (hdr->bfd_section != NULL)
00780     {
00781       BFD_ASSERT (strcmp (name,
00782                        bfd_get_section_name (abfd, hdr->bfd_section)) == 0);
00783       return TRUE;
00784     }
00785 
00786   newsect = bfd_make_section_anyway (abfd, name);
00787   if (newsect == NULL)
00788     return FALSE;
00789 
00790   hdr->bfd_section = newsect;
00791   elf_section_data (newsect)->this_hdr = *hdr;
00792   elf_section_data (newsect)->this_idx = shindex;
00793 
00794   /* Always use the real type/flags.  */
00795   elf_section_type (newsect) = hdr->sh_type;
00796   elf_section_flags (newsect) = hdr->sh_flags;
00797 
00798   newsect->filepos = hdr->sh_offset;
00799 
00800   if (! bfd_set_section_vma (abfd, newsect, hdr->sh_addr)
00801       || ! bfd_set_section_size (abfd, newsect, hdr->sh_size)
00802       || ! bfd_set_section_alignment (abfd, newsect,
00803                                   bfd_log2 ((bfd_vma) hdr->sh_addralign)))
00804     return FALSE;
00805 
00806   flags = SEC_NO_FLAGS;
00807   if (hdr->sh_type != SHT_NOBITS)
00808     flags |= SEC_HAS_CONTENTS;
00809   if (hdr->sh_type == SHT_GROUP)
00810     flags |= SEC_GROUP | SEC_EXCLUDE;
00811   if ((hdr->sh_flags & SHF_ALLOC) != 0)
00812     {
00813       flags |= SEC_ALLOC;
00814       if (hdr->sh_type != SHT_NOBITS)
00815        flags |= SEC_LOAD;
00816     }
00817   if ((hdr->sh_flags & SHF_WRITE) == 0)
00818     flags |= SEC_READONLY;
00819   if ((hdr->sh_flags & SHF_EXECINSTR) != 0)
00820     flags |= SEC_CODE;
00821   else if ((flags & SEC_LOAD) != 0)
00822     flags |= SEC_DATA;
00823   if ((hdr->sh_flags & SHF_MERGE) != 0)
00824     {
00825       flags |= SEC_MERGE;
00826       newsect->entsize = hdr->sh_entsize;
00827       if ((hdr->sh_flags & SHF_STRINGS) != 0)
00828        flags |= SEC_STRINGS;
00829     }
00830   if (hdr->sh_flags & SHF_GROUP)
00831     if (!setup_group (abfd, hdr, newsect))
00832       return FALSE;
00833   if ((hdr->sh_flags & SHF_TLS) != 0)
00834     flags |= SEC_THREAD_LOCAL;
00835 
00836   if ((flags & SEC_ALLOC) == 0)
00837     {
00838       /* The debugging sections appear to be recognized only by name,
00839         not any sort of flag.  Their SEC_ALLOC bits are cleared.  */
00840       static const struct
00841        {
00842          const char *name;
00843          int len;
00844        } debug_sections [] =
00845        {
00846          { STRING_COMMA_LEN ("debug") },  /* 'd' */
00847          { NULL,             0  }, /* 'e' */
00848          { NULL,             0  }, /* 'f' */
00849          { STRING_COMMA_LEN ("gnu.linkonce.wi.") },     /* 'g' */
00850          { NULL,             0  }, /* 'h' */
00851          { NULL,             0  }, /* 'i' */
00852          { NULL,             0  }, /* 'j' */
00853          { NULL,             0  }, /* 'k' */
00854          { STRING_COMMA_LEN ("line") },   /* 'l' */
00855          { NULL,             0  }, /* 'm' */
00856          { NULL,             0  }, /* 'n' */
00857          { NULL,             0  }, /* 'o' */
00858          { NULL,             0  }, /* 'p' */
00859          { NULL,             0  }, /* 'q' */
00860          { NULL,             0  }, /* 'r' */
00861          { STRING_COMMA_LEN ("stab") }    /* 's' */
00862        };
00863       
00864       if (name [0] == '.')
00865        {
00866          int i = name [1] - 'd';
00867          if (i >= 0
00868              && i < (int) ARRAY_SIZE (debug_sections)
00869              && debug_sections [i].name != NULL
00870              && strncmp (&name [1], debug_sections [i].name,
00871                        debug_sections [i].len) == 0)
00872            flags |= SEC_DEBUGGING;
00873        }
00874     }
00875 
00876   /* As a GNU extension, if the name begins with .gnu.linkonce, we
00877      only link a single copy of the section.  This is used to support
00878      g++.  g++ will emit each template expansion in its own section.
00879      The symbols will be defined as weak, so that multiple definitions
00880      are permitted.  The GNU linker extension is to actually discard
00881      all but one of the sections.  */
00882   if (CONST_STRNEQ (name, ".gnu.linkonce")
00883       && elf_next_in_group (newsect) == NULL)
00884     flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
00885 
00886   bed = get_elf_backend_data (abfd);
00887   if (bed->elf_backend_section_flags)
00888     if (! bed->elf_backend_section_flags (&flags, hdr))
00889       return FALSE;
00890 
00891   if (! bfd_set_section_flags (abfd, newsect, flags))
00892     return FALSE;
00893 
00894   if ((flags & SEC_ALLOC) != 0)
00895     {
00896       Elf_Internal_Phdr *phdr;
00897       unsigned int i;
00898 
00899       /* Look through the phdrs to see if we need to adjust the lma.
00900          If all the p_paddr fields are zero, we ignore them, since
00901          some ELF linkers produce such output.  */
00902       phdr = elf_tdata (abfd)->phdr;
00903       for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
00904        {
00905          if (phdr->p_paddr != 0)
00906            break;
00907        }
00908       if (i < elf_elfheader (abfd)->e_phnum)
00909        {
00910          phdr = elf_tdata (abfd)->phdr;
00911          for (i = 0; i < elf_elfheader (abfd)->e_phnum; i++, phdr++)
00912            {
00913              /* This section is part of this segment if its file
00914                offset plus size lies within the segment's memory
00915                span and, if the section is loaded, the extent of the
00916                loaded data lies within the extent of the segment.
00917 
00918                Note - we used to check the p_paddr field as well, and
00919                refuse to set the LMA if it was 0.  This is wrong
00920                though, as a perfectly valid initialised segment can
00921                have a p_paddr of zero.  Some architectures, eg ARM,
00922                 place special significance on the address 0 and
00923                 executables need to be able to have a segment which
00924                 covers this address.  */
00925              if (phdr->p_type == PT_LOAD
00926                 && (bfd_vma) hdr->sh_offset >= phdr->p_offset
00927                 && (hdr->sh_offset + hdr->sh_size
00928                     <= phdr->p_offset + phdr->p_memsz)
00929                 && ((flags & SEC_LOAD) == 0
00930                     || (hdr->sh_offset + hdr->sh_size
00931                        <= phdr->p_offset + phdr->p_filesz)))
00932               {
00933                 if ((flags & SEC_LOAD) == 0)
00934                   newsect->lma = (phdr->p_paddr
00935                                 + hdr->sh_addr - phdr->p_vaddr);
00936                 else
00937                   /* We used to use the same adjustment for SEC_LOAD
00938                      sections, but that doesn't work if the segment
00939                      is packed with code from multiple VMAs.
00940                      Instead we calculate the section LMA based on
00941                      the segment LMA.  It is assumed that the
00942                      segment will contain sections with contiguous
00943                      LMAs, even if the VMAs are not.  */
00944                   newsect->lma = (phdr->p_paddr
00945                                 + hdr->sh_offset - phdr->p_offset);
00946 
00947                 /* With contiguous segments, we can't tell from file
00948                    offsets whether a section with zero size should
00949                    be placed at the end of one segment or the
00950                    beginning of the next.  Decide based on vaddr.  */
00951                 if (hdr->sh_addr >= phdr->p_vaddr
00952                     && (hdr->sh_addr + hdr->sh_size
00953                        <= phdr->p_vaddr + phdr->p_memsz))
00954                   break;
00955               }
00956            }
00957        }
00958     }
00959 
00960   return TRUE;
00961 }
00962 
00963 /*
00964 INTERNAL_FUNCTION
00965        bfd_elf_find_section
00966 
00967 SYNOPSIS
00968        struct elf_internal_shdr *bfd_elf_find_section (bfd *abfd, char *name);
00969 
00970 DESCRIPTION
00971        Helper functions for GDB to locate the string tables.
00972        Since BFD hides string tables from callers, GDB needs to use an
00973        internal hook to find them.  Sun's .stabstr, in particular,
00974        isn't even pointed to by the .stab section, so ordinary
00975        mechanisms wouldn't work to find it, even if we had some.
00976 */
00977 
00978 struct elf_internal_shdr *
00979 bfd_elf_find_section (bfd *abfd, char *name)
00980 {
00981   Elf_Internal_Shdr **i_shdrp;
00982   char *shstrtab;
00983   unsigned int max;
00984   unsigned int i;
00985 
00986   i_shdrp = elf_elfsections (abfd);
00987   if (i_shdrp != NULL)
00988     {
00989       shstrtab = bfd_elf_get_str_section (abfd,
00990                                      elf_elfheader (abfd)->e_shstrndx);
00991       if (shstrtab != NULL)
00992        {
00993          max = elf_numsections (abfd);
00994          for (i = 1; i < max; i++)
00995            if (!strcmp (&shstrtab[i_shdrp[i]->sh_name], name))
00996              return i_shdrp[i];
00997        }
00998     }
00999   return 0;
01000 }
01001 
01002 const char *const bfd_elf_section_type_names[] = {
01003   "SHT_NULL", "SHT_PROGBITS", "SHT_SYMTAB", "SHT_STRTAB",
01004   "SHT_RELA", "SHT_HASH", "SHT_DYNAMIC", "SHT_NOTE",
01005   "SHT_NOBITS", "SHT_REL", "SHT_SHLIB", "SHT_DYNSYM",
01006 };
01007 
01008 /* ELF relocs are against symbols.  If we are producing relocatable
01009    output, and the reloc is against an external symbol, and nothing
01010    has given us any additional addend, the resulting reloc will also
01011    be against the same symbol.  In such a case, we don't want to
01012    change anything about the way the reloc is handled, since it will
01013    all be done at final link time.  Rather than put special case code
01014    into bfd_perform_relocation, all the reloc types use this howto
01015    function.  It just short circuits the reloc if producing
01016    relocatable output against an external symbol.  */
01017 
01018 bfd_reloc_status_type
01019 bfd_elf_generic_reloc (bfd *abfd ATTRIBUTE_UNUSED,
01020                      arelent *reloc_entry,
01021                      asymbol *symbol,
01022                      void *data ATTRIBUTE_UNUSED,
01023                      asection *input_section,
01024                      bfd *output_bfd,
01025                      char **error_message ATTRIBUTE_UNUSED)
01026 {
01027   if (output_bfd != NULL
01028       && (symbol->flags & BSF_SECTION_SYM) == 0
01029       && (! reloc_entry->howto->partial_inplace
01030          || reloc_entry->addend == 0))
01031     {
01032       reloc_entry->address += input_section->output_offset;
01033       return bfd_reloc_ok;
01034     }
01035 
01036   return bfd_reloc_continue;
01037 }
01038 
01039 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
01040 
01041 static void
01042 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
01043                          asection *sec)
01044 {
01045   BFD_ASSERT (sec->sec_info_type == ELF_INFO_TYPE_MERGE);
01046   sec->sec_info_type = ELF_INFO_TYPE_NONE;
01047 }
01048 
01049 /* Finish SHF_MERGE section merging.  */
01050 
01051 bfd_boolean
01052 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
01053 {
01054   bfd *ibfd;
01055   asection *sec;
01056 
01057   if (!is_elf_hash_table (info->hash))
01058     return FALSE;
01059 
01060   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
01061     if ((ibfd->flags & DYNAMIC) == 0)
01062       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
01063        if ((sec->flags & SEC_MERGE) != 0
01064            && !bfd_is_abs_section (sec->output_section))
01065          {
01066            struct bfd_elf_section_data *secdata;
01067 
01068            secdata = elf_section_data (sec);
01069            if (! _bfd_add_merge_section (abfd,
01070                                      &elf_hash_table (info)->merge_info,
01071                                      sec, &secdata->sec_info))
01072              return FALSE;
01073            else if (secdata->sec_info)
01074              sec->sec_info_type = ELF_INFO_TYPE_MERGE;
01075          }
01076 
01077   if (elf_hash_table (info)->merge_info != NULL)
01078     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
01079                       merge_sections_remove_hook);
01080   return TRUE;
01081 }
01082 
01083 void
01084 _bfd_elf_link_just_syms (asection *sec, struct bfd_link_info *info)
01085 {
01086   sec->output_section = bfd_abs_section_ptr;
01087   sec->output_offset = sec->vma;
01088   if (!is_elf_hash_table (info->hash))
01089     return;
01090 
01091   sec->sec_info_type = ELF_INFO_TYPE_JUST_SYMS;
01092 }
01093 
01094 /* Copy the program header and other data from one object module to
01095    another.  */
01096 
01097 bfd_boolean
01098 _bfd_elf_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
01099 {
01100   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
01101       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
01102     return TRUE;
01103 
01104   BFD_ASSERT (!elf_flags_init (obfd)
01105              || (elf_elfheader (obfd)->e_flags
01106                 == elf_elfheader (ibfd)->e_flags));
01107 
01108   elf_gp (obfd) = elf_gp (ibfd);
01109   elf_elfheader (obfd)->e_flags = elf_elfheader (ibfd)->e_flags;
01110   elf_flags_init (obfd) = TRUE;
01111   return TRUE;
01112 }
01113 
01114 static const char *
01115 get_segment_type (unsigned int p_type)
01116 {
01117   const char *pt;
01118   switch (p_type)
01119     {
01120     case PT_NULL: pt = "NULL"; break;
01121     case PT_LOAD: pt = "LOAD"; break;
01122     case PT_DYNAMIC: pt = "DYNAMIC"; break;
01123     case PT_INTERP: pt = "INTERP"; break;
01124     case PT_NOTE: pt = "NOTE"; break;
01125     case PT_SHLIB: pt = "SHLIB"; break;
01126     case PT_PHDR: pt = "PHDR"; break;
01127     case PT_TLS: pt = "TLS"; break;
01128     case PT_GNU_EH_FRAME: pt = "EH_FRAME"; break;
01129     case PT_GNU_STACK: pt = "STACK"; break;
01130     case PT_GNU_RELRO: pt = "RELRO"; break;
01131     default: pt = NULL; break;
01132     }
01133   return pt;
01134 }
01135 
01136 /* Print out the program headers.  */
01137 
01138 bfd_boolean
01139 _bfd_elf_print_private_bfd_data (bfd *abfd, void *farg)
01140 {
01141   FILE *f = farg;
01142   Elf_Internal_Phdr *p;
01143   asection *s;
01144   bfd_byte *dynbuf = NULL;
01145 
01146   p = elf_tdata (abfd)->phdr;
01147   if (p != NULL)
01148     {
01149       unsigned int i, c;
01150 
01151       fprintf (f, _("\nProgram Header:\n"));
01152       c = elf_elfheader (abfd)->e_phnum;
01153       for (i = 0; i < c; i++, p++)
01154        {
01155          const char *pt = get_segment_type (p->p_type);
01156          char buf[20];
01157 
01158          if (pt == NULL)
01159            {
01160              sprintf (buf, "0x%lx", p->p_type);
01161              pt = buf;
01162            }
01163          fprintf (f, "%8s off    0x", pt);
01164          bfd_fprintf_vma (abfd, f, p->p_offset);
01165          fprintf (f, " vaddr 0x");
01166          bfd_fprintf_vma (abfd, f, p->p_vaddr);
01167          fprintf (f, " paddr 0x");
01168          bfd_fprintf_vma (abfd, f, p->p_paddr);
01169          fprintf (f, " align 2**%u\n", bfd_log2 (p->p_align));
01170          fprintf (f, "         filesz 0x");
01171          bfd_fprintf_vma (abfd, f, p->p_filesz);
01172          fprintf (f, " memsz 0x");
01173          bfd_fprintf_vma (abfd, f, p->p_memsz);
01174          fprintf (f, " flags %c%c%c",
01175                  (p->p_flags & PF_R) != 0 ? 'r' : '-',
01176                  (p->p_flags & PF_W) != 0 ? 'w' : '-',
01177                  (p->p_flags & PF_X) != 0 ? 'x' : '-');
01178          if ((p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X)) != 0)
01179            fprintf (f, " %lx", p->p_flags &~ (unsigned) (PF_R | PF_W | PF_X));
01180          fprintf (f, "\n");
01181        }
01182     }
01183 
01184   s = bfd_get_section_by_name (abfd, ".dynamic");
01185   if (s != NULL)
01186     {
01187       int elfsec;
01188       unsigned long shlink;
01189       bfd_byte *extdyn, *extdynend;
01190       size_t extdynsize;
01191       void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
01192 
01193       fprintf (f, _("\nDynamic Section:\n"));
01194 
01195       if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
01196        goto error_return;
01197 
01198       elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
01199       if (elfsec == -1)
01200        goto error_return;
01201       shlink = elf_elfsections (abfd)[elfsec]->sh_link;
01202 
01203       extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
01204       swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
01205 
01206       extdyn = dynbuf;
01207       extdynend = extdyn + s->size;
01208       for (; extdyn < extdynend; extdyn += extdynsize)
01209        {
01210          Elf_Internal_Dyn dyn;
01211          const char *name;
01212          char ab[20];
01213          bfd_boolean stringp;
01214 
01215          (*swap_dyn_in) (abfd, extdyn, &dyn);
01216 
01217          if (dyn.d_tag == DT_NULL)
01218            break;
01219 
01220          stringp = FALSE;
01221          switch (dyn.d_tag)
01222            {
01223            default:
01224              sprintf (ab, "0x%lx", (unsigned long) dyn.d_tag);
01225              name = ab;
01226              break;
01227 
01228            case DT_NEEDED: name = "NEEDED"; stringp = TRUE; break;
01229            case DT_PLTRELSZ: name = "PLTRELSZ"; break;
01230            case DT_PLTGOT: name = "PLTGOT"; break;
01231            case DT_HASH: name = "HASH"; break;
01232            case DT_STRTAB: name = "STRTAB"; break;
01233            case DT_SYMTAB: name = "SYMTAB"; break;
01234            case DT_RELA: name = "RELA"; break;
01235            case DT_RELASZ: name = "RELASZ"; break;
01236            case DT_RELAENT: name = "RELAENT"; break;
01237            case DT_STRSZ: name = "STRSZ"; break;
01238            case DT_SYMENT: name = "SYMENT"; break;
01239            case DT_INIT: name = "INIT"; break;
01240            case DT_FINI: name = "FINI"; break;
01241            case DT_SONAME: name = "SONAME"; stringp = TRUE; break;
01242            case DT_RPATH: name = "RPATH"; stringp = TRUE; break;
01243            case DT_SYMBOLIC: name = "SYMBOLIC"; break;
01244            case DT_REL: name = "REL"; break;
01245            case DT_RELSZ: name = "RELSZ"; break;
01246            case DT_RELENT: name = "RELENT"; break;
01247            case DT_PLTREL: name = "PLTREL"; break;
01248            case DT_DEBUG: name = "DEBUG"; break;
01249            case DT_TEXTREL: name = "TEXTREL"; break;
01250            case DT_JMPREL: name = "JMPREL"; break;
01251            case DT_BIND_NOW: name = "BIND_NOW"; break;
01252            case DT_INIT_ARRAY: name = "INIT_ARRAY"; break;
01253            case DT_FINI_ARRAY: name = "FINI_ARRAY"; break;
01254            case DT_INIT_ARRAYSZ: name = "INIT_ARRAYSZ"; break;
01255            case DT_FINI_ARRAYSZ: name = "FINI_ARRAYSZ"; break;
01256            case DT_RUNPATH: name = "RUNPATH"; stringp = TRUE; break;
01257            case DT_FLAGS: name = "FLAGS"; break;
01258            case DT_PREINIT_ARRAY: name = "PREINIT_ARRAY"; break;
01259            case DT_PREINIT_ARRAYSZ: name = "PREINIT_ARRAYSZ"; break;
01260            case DT_CHECKSUM: name = "CHECKSUM"; break;
01261            case DT_PLTPADSZ: name = "PLTPADSZ"; break;
01262            case DT_MOVEENT: name = "MOVEENT"; break;
01263            case DT_MOVESZ: name = "MOVESZ"; break;
01264            case DT_FEATURE: name = "FEATURE"; break;
01265            case DT_POSFLAG_1: name = "POSFLAG_1"; break;
01266            case DT_SYMINSZ: name = "SYMINSZ"; break;
01267            case DT_SYMINENT: name = "SYMINENT"; break;
01268            case DT_CONFIG: name = "CONFIG"; stringp = TRUE; break;
01269            case DT_DEPAUDIT: name = "DEPAUDIT"; stringp = TRUE; break;
01270            case DT_AUDIT: name = "AUDIT"; stringp = TRUE; break;
01271            case DT_PLTPAD: name = "PLTPAD"; break;
01272            case DT_MOVETAB: name = "MOVETAB"; break;
01273            case DT_SYMINFO: name = "SYMINFO"; break;
01274            case DT_RELACOUNT: name = "RELACOUNT"; break;
01275            case DT_RELCOUNT: name = "RELCOUNT"; break;
01276            case DT_FLAGS_1: name = "FLAGS_1"; break;
01277            case DT_VERSYM: name = "VERSYM"; break;
01278            case DT_VERDEF: name = "VERDEF"; break;
01279            case DT_VERDEFNUM: name = "VERDEFNUM"; break;
01280            case DT_VERNEED: name = "VERNEED"; break;
01281            case DT_VERNEEDNUM: name = "VERNEEDNUM"; break;
01282            case DT_AUXILIARY: name = "AUXILIARY"; stringp = TRUE; break;
01283            case DT_USED: name = "USED"; break;
01284            case DT_FILTER: name = "FILTER"; stringp = TRUE; break;
01285            case DT_GNU_HASH: name = "GNU_HASH"; break;
01286            }
01287 
01288          fprintf (f, "  %-11s ", name);
01289          if (! stringp)
01290            fprintf (f, "0x%lx", (unsigned long) dyn.d_un.d_val);
01291          else
01292            {
01293              const char *string;
01294              unsigned int tagv = dyn.d_un.d_val;
01295 
01296              string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
01297              if (string == NULL)
01298               goto error_return;
01299              fprintf (f, "%s", string);
01300            }
01301          fprintf (f, "\n");
01302        }
01303 
01304       free (dynbuf);
01305       dynbuf = NULL;
01306     }
01307 
01308   if ((elf_dynverdef (abfd) != 0 && elf_tdata (abfd)->verdef == NULL)
01309       || (elf_dynverref (abfd) != 0 && elf_tdata (abfd)->verref == NULL))
01310     {
01311       if (! _bfd_elf_slurp_version_tables (abfd, FALSE))
01312        return FALSE;
01313     }
01314 
01315   if (elf_dynverdef (abfd) != 0)
01316     {
01317       Elf_Internal_Verdef *t;
01318 
01319       fprintf (f, _("\nVersion definitions:\n"));
01320       for (t = elf_tdata (abfd)->verdef; t != NULL; t = t->vd_nextdef)
01321        {
01322          fprintf (f, "%d 0x%2.2x 0x%8.8lx %s\n", t->vd_ndx,
01323                  t->vd_flags, t->vd_hash,
01324                  t->vd_nodename ? t->vd_nodename : "<corrupt>");
01325          if (t->vd_auxptr != NULL && t->vd_auxptr->vda_nextptr != NULL)
01326            {
01327              Elf_Internal_Verdaux *a;
01328 
01329              fprintf (f, "\t");
01330              for (a = t->vd_auxptr->vda_nextptr;
01331                  a != NULL;
01332                  a = a->vda_nextptr)
01333               fprintf (f, "%s ",
01334                       a->vda_nodename ? a->vda_nodename : "<corrupt>");
01335              fprintf (f, "\n");
01336            }
01337        }
01338     }
01339 
01340   if (elf_dynverref (abfd) != 0)
01341     {
01342       Elf_Internal_Verneed *t;
01343 
01344       fprintf (f, _("\nVersion References:\n"));
01345       for (t = elf_tdata (abfd)->verref; t != NULL; t = t->vn_nextref)
01346        {
01347          Elf_Internal_Vernaux *a;
01348 
01349          fprintf (f, _("  required from %s:\n"),
01350                  t->vn_filename ? t->vn_filename : "<corrupt>");
01351          for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
01352            fprintf (f, "    0x%8.8lx 0x%2.2x %2.2d %s\n", a->vna_hash,
01353                    a->vna_flags, a->vna_other,
01354                    a->vna_nodename ? a->vna_nodename : "<corrupt>");
01355        }
01356     }
01357 
01358   return TRUE;
01359 
01360  error_return:
01361   if (dynbuf != NULL)
01362     free (dynbuf);
01363   return FALSE;
01364 }
01365 
01366 /* Display ELF-specific fields of a symbol.  */
01367 
01368 void
01369 bfd_elf_print_symbol (bfd *abfd,
01370                     void *filep,
01371                     asymbol *symbol,
01372                     bfd_print_symbol_type how)
01373 {
01374   FILE *file = filep;
01375   switch (how)
01376     {
01377     case bfd_print_symbol_name:
01378       fprintf (file, "%s", symbol->name);
01379       break;
01380     case bfd_print_symbol_more:
01381       fprintf (file, "elf ");
01382       bfd_fprintf_vma (abfd, file, symbol->value);
01383       fprintf (file, " %lx", (long) symbol->flags);
01384       break;
01385     case bfd_print_symbol_all:
01386       {
01387        const char *section_name;
01388        const char *name = NULL;
01389        const struct elf_backend_data *bed;
01390        unsigned char st_other;
01391        bfd_vma val;
01392 
01393        section_name = symbol->section ? symbol->section->name : "(*none*)";
01394 
01395        bed = get_elf_backend_data (abfd);
01396        if (bed->elf_backend_print_symbol_all)
01397          name = (*bed->elf_backend_print_symbol_all) (abfd, filep, symbol);
01398 
01399        if (name == NULL)
01400          {
01401            name = symbol->name;
01402            bfd_print_symbol_vandf (abfd, file, symbol);
01403          }
01404 
01405        fprintf (file, " %s\t", section_name);
01406        /* Print the "other" value for a symbol.  For common symbols,
01407           we've already printed the size; now print the alignment.
01408           For other symbols, we have no specified alignment, and
01409           we've printed the address; now print the size.  */
01410        if (bfd_is_com_section (symbol->section))
01411          val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
01412        else
01413          val = ((elf_symbol_type *) symbol)->internal_elf_sym.st_size;
01414        bfd_fprintf_vma (abfd, file, val);
01415 
01416        /* If we have version information, print it.  */
01417        if (elf_tdata (abfd)->dynversym_section != 0
01418            && (elf_tdata (abfd)->dynverdef_section != 0
01419               || elf_tdata (abfd)->dynverref_section != 0))
01420          {
01421            unsigned int vernum;
01422            const char *version_string;
01423 
01424            vernum = ((elf_symbol_type *) symbol)->version & VERSYM_VERSION;
01425 
01426            if (vernum == 0)
01427              version_string = "";
01428            else if (vernum == 1)
01429              version_string = "Base";
01430            else if (vernum <= elf_tdata (abfd)->cverdefs)
01431              version_string =
01432               elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
01433            else
01434              {
01435               Elf_Internal_Verneed *t;
01436 
01437               version_string = "";
01438               for (t = elf_tdata (abfd)->verref;
01439                    t != NULL;
01440                    t = t->vn_nextref)
01441                 {
01442                   Elf_Internal_Vernaux *a;
01443 
01444                   for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
01445                     {
01446                      if (a->vna_other == vernum)
01447                        {
01448                          version_string = a->vna_nodename;
01449                          break;
01450                        }
01451                     }
01452                 }
01453              }
01454 
01455            if ((((elf_symbol_type *) symbol)->version & VERSYM_HIDDEN) == 0)
01456              fprintf (file, "  %-11s", version_string);
01457            else
01458              {
01459               int i;
01460 
01461               fprintf (file, " (%s)", version_string);
01462               for (i = 10 - strlen (version_string); i > 0; --i)
01463                 putc (' ', file);
01464              }
01465          }
01466 
01467        /* If the st_other field is not zero, print it.  */
01468        st_other = ((elf_symbol_type *) symbol)->internal_elf_sym.st_other;
01469 
01470        switch (st_other)
01471          {
01472          case 0: break;
01473          case STV_INTERNAL:  fprintf (file, " .internal");  break;
01474          case STV_HIDDEN:    fprintf (file, " .hidden");    break;
01475          case STV_PROTECTED: fprintf (file, " .protected"); break;
01476          default:
01477            /* Some other non-defined flags are also present, so print
01478               everything hex.  */
01479            fprintf (file, " 0x%02x", (unsigned int) st_other);
01480          }
01481 
01482        fprintf (file, " %s", name);
01483       }
01484       break;
01485     }
01486 }
01487 
01488 /* Create an entry in an ELF linker hash table.  */
01489 
01490 struct bfd_hash_entry *
01491 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
01492                          struct bfd_hash_table *table,
01493                          const char *string)
01494 {
01495   /* Allocate the structure if it has not already been allocated by a
01496      subclass.  */
01497   if (entry == NULL)
01498     {
01499       entry = bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
01500       if (entry == NULL)
01501        return entry;
01502     }
01503 
01504   /* Call the allocation method of the superclass.  */
01505   entry = _bfd_link_hash_newfunc (entry, table, string);
01506   if (entry != NULL)
01507     {
01508       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
01509       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
01510 
01511       /* Set local fields.  */
01512       ret->indx = -1;
01513       ret->dynindx = -1;
01514       ret->got = htab->init_got_refcount;
01515       ret->plt = htab->init_plt_refcount;
01516       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
01517                            - offsetof (struct elf_link_hash_entry, size)));
01518       /* Assume that we have been called by a non-ELF symbol reader.
01519          This flag is then reset by the code which reads an ELF input
01520          file.  This ensures that a symbol created by a non-ELF symbol
01521          reader will have the flag set correctly.  */
01522       ret->non_elf = 1;
01523     }
01524 
01525   return entry;
01526 }
01527 
01528 /* Copy data from an indirect symbol to its direct symbol, hiding the
01529    old indirect symbol.  Also used for copying flags to a weakdef.  */
01530 
01531 void
01532 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
01533                               struct elf_link_hash_entry *dir,
01534                               struct elf_link_hash_entry *ind)
01535 {
01536   struct elf_link_hash_table *htab;
01537 
01538   /* Copy down any references that we may have already seen to the
01539      symbol which just became indirect.  */
01540 
01541   dir->ref_dynamic |= ind->ref_dynamic;
01542   dir->ref_regular |= ind->ref_regular;
01543   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
01544   dir->non_got_ref |= ind->non_got_ref;
01545   dir->needs_plt |= ind->needs_plt;
01546   dir->pointer_equality_needed |= ind->pointer_equality_needed;
01547 
01548   if (ind->root.type != bfd_link_hash_indirect)
01549     return;
01550 
01551   /* Copy over the global and procedure linkage table refcount entries.
01552      These may have been already set up by a check_relocs routine.  */
01553   htab = elf_hash_table (info);
01554   if (ind->got.refcount > htab->init_got_refcount.refcount)
01555     {
01556       if (dir->got.refcount < 0)
01557        dir->got.refcount = 0;
01558       dir->got.refcount += ind->got.refcount;
01559       ind->got.refcount = htab->init_got_refcount.refcount;
01560     }
01561 
01562   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
01563     {
01564       if (dir->plt.refcount < 0)
01565        dir->plt.refcount = 0;
01566       dir->plt.refcount += ind->plt.refcount;
01567       ind->plt.refcount = htab->init_plt_refcount.refcount;
01568     }
01569 
01570   if (ind->dynindx != -1)
01571     {
01572       if (dir->dynindx != -1)
01573        _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
01574       dir->dynindx = ind->dynindx;
01575       dir->dynstr_index = ind->dynstr_index;
01576       ind->dynindx = -1;
01577       ind->dynstr_index = 0;
01578     }
01579 }
01580 
01581 void
01582 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
01583                             struct elf_link_hash_entry *h,
01584                             bfd_boolean force_local)
01585 {
01586   h->plt = elf_hash_table (info)->init_plt_offset;
01587   h->needs_plt = 0;
01588   if (force_local)
01589     {
01590       h->forced_local = 1;
01591       if (h->dynindx != -1)
01592        {
01593          h->dynindx = -1;
01594          _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
01595                               h->dynstr_index);
01596        }
01597     }
01598 }
01599 
01600 /* Initialize an ELF linker hash table.  */
01601 
01602 bfd_boolean
01603 _bfd_elf_link_hash_table_init
01604   (struct elf_link_hash_table *table,
01605    bfd *abfd,
01606    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
01607                                   struct bfd_hash_table *,
01608                                   const char *),
01609    unsigned int entsize)
01610 {
01611   bfd_boolean ret;
01612   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
01613 
01614   memset (table, 0, sizeof * table);
01615   table->init_got_refcount.refcount = can_refcount - 1;
01616   table->init_plt_refcount.refcount = can_refcount - 1;
01617   table->init_got_offset.offset = -(bfd_vma) 1;
01618   table->init_plt_offset.offset = -(bfd_vma) 1;
01619   /* The first dynamic symbol is a dummy.  */
01620   table->dynsymcount = 1;
01621 
01622   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
01623   table->root.type = bfd_link_elf_hash_table;
01624 
01625   return ret;
01626 }
01627 
01628 /* Create an ELF linker hash table.  */
01629 
01630 struct bfd_link_hash_table *
01631 _bfd_elf_link_hash_table_create (bfd *abfd)
01632 {
01633   struct elf_link_hash_table *ret;
01634   bfd_size_type amt = sizeof (struct elf_link_hash_table);
01635 
01636   ret = bfd_malloc (amt);
01637   if (ret == NULL)
01638     return NULL;
01639 
01640   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
01641                                    sizeof (struct elf_link_hash_entry)))
01642     {
01643       free (ret);
01644       return NULL;
01645     }
01646 
01647   return &ret->root;
01648 }
01649 
01650 /* This is a hook for the ELF emulation code in the generic linker to
01651    tell the backend linker what file name to use for the DT_NEEDED
01652    entry for a dynamic object.  */
01653 
01654 void
01655 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
01656 {
01657   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
01658       && bfd_get_format (abfd) == bfd_object)
01659     elf_dt_name (abfd) = name;
01660 }
01661 
01662 int
01663 bfd_elf_get_dyn_lib_class (bfd *abfd)
01664 {
01665   int lib_class;
01666   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
01667       && bfd_get_format (abfd) == bfd_object)
01668     lib_class = elf_dyn_lib_class (abfd);
01669   else
01670     lib_class = 0;
01671   return lib_class;
01672 }
01673 
01674 void
01675 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
01676 {
01677   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
01678       && bfd_get_format (abfd) == bfd_object)
01679     elf_dyn_lib_class (abfd) = lib_class;
01680 }
01681 
01682 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
01683    the linker ELF emulation code.  */
01684 
01685 struct bfd_link_needed_list *
01686 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
01687                       struct bfd_link_info *info)
01688 {
01689   if (! is_elf_hash_table (info->hash))
01690     return NULL;
01691   return elf_hash_table (info)->needed;
01692 }
01693 
01694 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
01695    hook for the linker ELF emulation code.  */
01696 
01697 struct bfd_link_needed_list *
01698 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
01699                        struct bfd_link_info *info)
01700 {
01701   if (! is_elf_hash_table (info->hash))
01702     return NULL;
01703   return elf_hash_table (info)->runpath;
01704 }
01705 
01706 /* Get the name actually used for a dynamic object for a link.  This
01707    is the SONAME entry if there is one.  Otherwise, it is the string
01708    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
01709 
01710 const char *
01711 bfd_elf_get_dt_soname (bfd *abfd)
01712 {
01713   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
01714       && bfd_get_format (abfd) == bfd_object)
01715     return elf_dt_name (abfd);
01716   return NULL;
01717 }
01718 
01719 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
01720    the ELF linker emulation code.  */
01721 
01722 bfd_boolean
01723 bfd_elf_get_bfd_needed_list (bfd *abfd,
01724                           struct bfd_link_needed_list **pneeded)
01725 {
01726   asection *s;
01727   bfd_byte *dynbuf = NULL;
01728   int elfsec;
01729   unsigned long shlink;
01730   bfd_byte *extdyn, *extdynend;
01731   size_t extdynsize;
01732   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
01733 
01734   *pneeded = NULL;
01735 
01736   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
01737       || bfd_get_format (abfd) != bfd_object)
01738     return TRUE;
01739 
01740   s = bfd_get_section_by_name (abfd, ".dynamic");
01741   if (s == NULL || s->size == 0)
01742     return TRUE;
01743 
01744   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
01745     goto error_return;
01746 
01747   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
01748   if (elfsec == -1)
01749     goto error_return;
01750 
01751   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
01752 
01753   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
01754   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
01755 
01756   extdyn = dynbuf;
01757   extdynend = extdyn + s->size;
01758   for (; extdyn < extdynend; extdyn += extdynsize)
01759     {
01760       Elf_Internal_Dyn dyn;
01761 
01762       (*swap_dyn_in) (abfd, extdyn, &dyn);
01763 
01764       if (dyn.d_tag == DT_NULL)
01765        break;
01766 
01767       if (dyn.d_tag == DT_NEEDED)
01768        {
01769          const char *string;
01770          struct bfd_link_needed_list *l;
01771          unsigned int tagv = dyn.d_un.d_val;
01772          bfd_size_type amt;
01773 
01774          string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
01775          if (string == NULL)
01776            goto error_return;
01777 
01778          amt = sizeof *l;
01779          l = bfd_alloc (abfd, amt);
01780          if (l == NULL)
01781            goto error_return;
01782 
01783          l->by = abfd;
01784          l->name = string;
01785          l->next = *pneeded;
01786          *pneeded = l;
01787        }
01788     }
01789 
01790   free (dynbuf);
01791 
01792   return TRUE;
01793 
01794  error_return:
01795   if (dynbuf != NULL)
01796     free (dynbuf);
01797   return FALSE;
01798 }
01799 
01800 /* Allocate an ELF string table--force the first byte to be zero.  */
01801 
01802 struct bfd_strtab_hash *
01803 _bfd_elf_stringtab_init (void)
01804 {
01805   struct bfd_strtab_hash *ret;
01806 
01807   ret = _bfd_stringtab_init ();
01808   if (ret != NULL)
01809     {
01810       bfd_size_type loc;
01811 
01812       loc = _bfd_stringtab_add (ret, "", TRUE, FALSE);
01813       BFD_ASSERT (loc == 0 || loc == (bfd_size_type) -1);
01814       if (loc == (bfd_size_type) -1)
01815        {
01816          _bfd_stringtab_free (ret);
01817          ret = NULL;
01818        }
01819     }
01820   return ret;
01821 }
01822 
01823 /* ELF .o/exec file reading */
01824 
01825 /* Create a new bfd section from an ELF section header.  */
01826 
01827 bfd_boolean
01828 bfd_section_from_shdr (bfd *abfd, unsigned int shindex)
01829 {
01830   Elf_Internal_Shdr *hdr = elf_elfsections (abfd)[shindex];
01831   Elf_Internal_Ehdr *ehdr = elf_elfheader (abfd);
01832   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
01833   const char *name;
01834 
01835   name = bfd_elf_string_from_elf_section (abfd,
01836                                      elf_elfheader (abfd)->e_shstrndx,
01837                                      hdr->sh_name);
01838   if (name == NULL)
01839     return FALSE;
01840 
01841   switch (hdr->sh_type)
01842     {
01843     case SHT_NULL:
01844       /* Inactive section. Throw it away.  */
01845       return TRUE;
01846 
01847     case SHT_PROGBITS:      /* Normal section with contents.  */
01848     case SHT_NOBITS: /* .bss section.  */
01849     case SHT_HASH:   /* .hash section.  */
01850     case SHT_NOTE:   /* .note section.  */
01851     case SHT_INIT_ARRAY:    /* .init_array section.  */
01852     case SHT_FINI_ARRAY:    /* .fini_array section.  */
01853     case SHT_PREINIT_ARRAY: /* .preinit_array section.  */
01854     case SHT_GNU_LIBLIST:   /* .gnu.liblist section.  */
01855     case SHT_GNU_HASH:             /* .gnu.hash section.  */
01856       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
01857 
01858     case SHT_DYNAMIC:       /* Dynamic linking information.  */
01859       if (! _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
01860        return FALSE;
01861       if (hdr->sh_link > elf_numsections (abfd)
01862          || elf_elfsections (abfd)[hdr->sh_link] == NULL)
01863        return FALSE;
01864       if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_STRTAB)
01865        {
01866          Elf_Internal_Shdr *dynsymhdr;
01867 
01868          /* The shared libraries distributed with hpux11 have a bogus
01869             sh_link field for the ".dynamic" section.  Find the
01870             string table for the ".dynsym" section instead.  */
01871          if (elf_dynsymtab (abfd) != 0)
01872            {
01873              dynsymhdr = elf_elfsections (abfd)[elf_dynsymtab (abfd)];
01874              hdr->sh_link = dynsymhdr->sh_link;
01875            }
01876          else
01877            {
01878              unsigned int i, num_sec;
01879 
01880              num_sec = elf_numsections (abfd);
01881              for (i = 1; i < num_sec; i++)
01882               {
01883                 dynsymhdr = elf_elfsections (abfd)[i];
01884                 if (dynsymhdr->sh_type == SHT_DYNSYM)
01885                   {
01886                     hdr->sh_link = dynsymhdr->sh_link;
01887                     break;
01888                   }
01889               }
01890            }
01891        }
01892       break;
01893 
01894     case SHT_SYMTAB:        /* A symbol table */
01895       if (elf_onesymtab (abfd) == shindex)
01896        return TRUE;
01897 
01898       if (hdr->sh_entsize != bed->s->sizeof_sym)
01899        return FALSE;
01900       BFD_ASSERT (elf_onesymtab (abfd) == 0);
01901       elf_onesymtab (abfd) = shindex;
01902       elf_tdata (abfd)->symtab_hdr = *hdr;
01903       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->symtab_hdr;
01904       abfd->flags |= HAS_SYMS;
01905 
01906       /* Sometimes a shared object will map in the symbol table.  If
01907          SHF_ALLOC is set, and this is a shared object, then we also
01908          treat this section as a BFD section.  We can not base the
01909          decision purely on SHF_ALLOC, because that flag is sometimes
01910          set in a relocatable object file, which would confuse the
01911          linker.  */
01912       if ((hdr->sh_flags & SHF_ALLOC) != 0
01913          && (abfd->flags & DYNAMIC) != 0
01914          && ! _bfd_elf_make_section_from_shdr (abfd, hdr, name,
01915                                           shindex))
01916        return FALSE;
01917 
01918       /* Go looking for SHT_SYMTAB_SHNDX too, since if there is one we
01919         can't read symbols without that section loaded as well.  It
01920         is most likely specified by the next section header.  */
01921       if (elf_elfsections (abfd)[elf_symtab_shndx (abfd)]->sh_link != shindex)
01922        {
01923          unsigned int i, num_sec;
01924 
01925          num_sec = elf_numsections (abfd);
01926          for (i = shindex + 1; i < num_sec; i++)
01927            {
01928              Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
01929              if (hdr2->sh_type == SHT_SYMTAB_SHNDX
01930                 && hdr2->sh_link == shindex)
01931               break;
01932            }
01933          if (i == num_sec)
01934            for (i = 1; i < shindex; i++)
01935              {
01936               Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
01937               if (hdr2->sh_type == SHT_SYMTAB_SHNDX
01938                   && hdr2->sh_link == shindex)
01939                 break;
01940              }
01941          if (i != shindex)
01942            return bfd_section_from_shdr (abfd, i);
01943        }
01944       return TRUE;
01945 
01946     case SHT_DYNSYM:        /* A dynamic symbol table */
01947       if (elf_dynsymtab (abfd) == shindex)
01948        return TRUE;
01949 
01950       if (hdr->sh_entsize != bed->s->sizeof_sym)
01951        return FALSE;
01952       BFD_ASSERT (elf_dynsymtab (abfd) == 0);
01953       elf_dynsymtab (abfd) = shindex;
01954       elf_tdata (abfd)->dynsymtab_hdr = *hdr;
01955       elf_elfsections (abfd)[shindex] = hdr = &elf_tdata (abfd)->dynsymtab_hdr;
01956       abfd->flags |= HAS_SYMS;
01957 
01958       /* Besides being a symbol table, we also treat this as a regular
01959         section, so that objcopy can handle it.  */
01960       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
01961 
01962     case SHT_SYMTAB_SHNDX:  /* Symbol section indices when >64k sections */
01963       if (elf_symtab_shndx (abfd) == shindex)
01964        return TRUE;
01965 
01966       BFD_ASSERT (elf_symtab_shndx (abfd) == 0);
01967       elf_symtab_shndx (abfd) = shindex;
01968       elf_tdata (abfd)->symtab_shndx_hdr = *hdr;
01969       elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->symtab_shndx_hdr;
01970       return TRUE;
01971 
01972     case SHT_STRTAB:        /* A string table */
01973       if (hdr->bfd_section != NULL)
01974        return TRUE;
01975       if (ehdr->e_shstrndx == shindex)
01976        {
01977          elf_tdata (abfd)->shstrtab_hdr = *hdr;
01978          elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->shstrtab_hdr;
01979          return TRUE;
01980        }
01981       if (elf_elfsections (abfd)[elf_onesymtab (abfd)]->sh_link == shindex)
01982        {
01983        symtab_strtab:
01984          elf_tdata (abfd)->strtab_hdr = *hdr;
01985          elf_elfsections (abfd)[shindex] = &elf_tdata (abfd)->strtab_hdr;
01986          return TRUE;
01987        }
01988       if (elf_elfsections (abfd)[elf_dynsymtab (abfd)]->sh_link == shindex)
01989        {
01990        dynsymtab_strtab:
01991          elf_tdata (abfd)->dynstrtab_hdr = *hdr;
01992          hdr = &elf_tdata (abfd)->dynstrtab_hdr;
01993          elf_elfsections (abfd)[shindex] = hdr;
01994          /* We also treat this as a regular section, so that objcopy
01995             can handle it.  */
01996          return _bfd_elf_make_section_from_shdr (abfd, hdr, name,
01997                                             shindex);
01998        }
01999 
02000       /* If the string table isn't one of the above, then treat it as a
02001         regular section.  We need to scan all the headers to be sure,
02002         just in case this strtab section appeared before the above.  */
02003       if (elf_onesymtab (abfd) == 0 || elf_dynsymtab (abfd) == 0)
02004        {
02005          unsigned int i, num_sec;
02006 
02007          num_sec = elf_numsections (abfd);
02008          for (i = 1; i < num_sec; i++)
02009            {
02010              Elf_Internal_Shdr *hdr2 = elf_elfsections (abfd)[i];
02011              if (hdr2->sh_link == shindex)
02012               {
02013                 /* Prevent endless recursion on broken objects.  */
02014                 if (i == shindex)
02015                   return FALSE;
02016                 if (! bfd_section_from_shdr (abfd, i))
02017                   return FALSE;
02018                 if (elf_onesymtab (abfd) == i)
02019                   goto symtab_strtab;
02020                 if (elf_dynsymtab (abfd) == i)
02021                   goto dynsymtab_strtab;
02022               }
02023            }
02024        }
02025       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
02026 
02027     case SHT_REL:
02028     case SHT_RELA:
02029       /* *These* do a lot of work -- but build no sections!  */
02030       {
02031        asection *target_sect;
02032        Elf_Internal_Shdr *hdr2;
02033        unsigned int num_sec = elf_numsections (abfd);
02034 
02035        if (hdr->sh_entsize
02036            != (bfd_size_type) (hdr->sh_type == SHT_REL
02037                             ? bed->s->sizeof_rel : bed->s->sizeof_rela))
02038          return FALSE;
02039 
02040        /* Check for a bogus link to avoid crashing.  */
02041        if ((hdr->sh_link >= SHN_LORESERVE && hdr->sh_link <= SHN_HIRESERVE)
02042            || hdr->sh_link >= num_sec)
02043          {
02044            ((*_bfd_error_handler)
02045             (_("%B: invalid link %lu for reloc section %s (index %u)"),
02046              abfd, hdr->sh_link, name, shindex));
02047            return _bfd_elf_make_section_from_shdr (abfd, hdr, name,
02048                                               shindex);
02049          }
02050 
02051        /* For some incomprehensible reason Oracle distributes
02052           libraries for Solaris in which some of the objects have
02053           bogus sh_link fields.  It would be nice if we could just
02054           reject them, but, unfortunately, some people need to use
02055           them.  We scan through the section headers; if we find only
02056           one suitable symbol table, we clobber the sh_link to point
02057           to it.  I hope this doesn't break anything.  */
02058        if (elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_SYMTAB
02059            && elf_elfsections (abfd)[hdr->sh_link]->sh_type != SHT_DYNSYM)
02060          {
02061            unsigned int scan;
02062            int found;
02063 
02064            found = 0;
02065            for (scan = 1; scan < num_sec; scan++)
02066              {
02067               if (elf_elfsections (abfd)[scan]->sh_type == SHT_SYMTAB
02068                   || elf_elfsections (abfd)[scan]->sh_type == SHT_DYNSYM)
02069                 {
02070                   if (found != 0)
02071                     {
02072                      found = 0;
02073                      break;
02074                     }
02075                   found = scan;
02076                 }
02077              }
02078            if (found != 0)
02079              hdr->sh_link = found;
02080          }
02081 
02082        /* Get the symbol table.  */
02083        if ((elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_SYMTAB
02084             || elf_elfsections (abfd)[hdr->sh_link]->sh_type == SHT_DYNSYM)
02085            && ! bfd_section_from_shdr (abfd, hdr->sh_link))
02086          return FALSE;
02087 
02088        /* If this reloc section does not use the main symbol table we
02089           don't treat it as a reloc section.  BFD can't adequately
02090           represent such a section, so at least for now, we don't
02091           try.  We just present it as a normal section.  We also
02092           can't use it as a reloc section if it points to the null
02093           section, an invalid section, or another reloc section.  */
02094        if (hdr->sh_link != elf_onesymtab (abfd)
02095            || hdr->sh_info == SHN_UNDEF
02096            || (hdr->sh_info >= SHN_LORESERVE && hdr->sh_info <= SHN_HIRESERVE)
02097            || hdr->sh_info >= num_sec
02098            || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_REL
02099            || elf_elfsections (abfd)[hdr->sh_info]->sh_type == SHT_RELA)
02100          return _bfd_elf_make_section_from_shdr (abfd, hdr, name,
02101                                             shindex);
02102 
02103        if (! bfd_section_from_shdr (abfd, hdr->sh_info))
02104          return FALSE;
02105        target_sect = bfd_section_from_elf_index (abfd, hdr->sh_info);
02106        if (target_sect == NULL)
02107          return FALSE;
02108 
02109        if ((target_sect->flags & SEC_RELOC) == 0
02110            || target_sect->reloc_count == 0)
02111          hdr2 = &elf_section_data (target_sect)->rel_hdr;
02112        else
02113          {
02114            bfd_size_type amt;
02115            BFD_ASSERT (elf_section_data (target_sect)->rel_hdr2 == NULL);
02116            amt = sizeof (*hdr2);
02117            hdr2 = bfd_alloc (abfd, amt);
02118            elf_section_data (target_sect)->rel_hdr2 = hdr2;
02119          }
02120        *hdr2 = *hdr;
02121        elf_elfsections (abfd)[shindex] = hdr2;
02122        target_sect->reloc_count += NUM_SHDR_ENTRIES (hdr);
02123        target_sect->flags |= SEC_RELOC;
02124        target_sect->relocation = NULL;
02125        target_sect->rel_filepos = hdr->sh_offset;
02126        /* In the section to which the relocations apply, mark whether
02127           its relocations are of the REL or RELA variety.  */
02128        if (hdr->sh_size != 0)
02129          target_sect->use_rela_p = hdr->sh_type == SHT_RELA;
02130        abfd->flags |= HAS_RELOC;
02131        return TRUE;
02132       }
02133 
02134     case SHT_GNU_verdef:
02135       elf_dynverdef (abfd) = shindex;
02136       elf_tdata (abfd)->dynverdef_hdr = *hdr;
02137       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
02138 
02139     case SHT_GNU_versym:
02140       if (hdr->sh_entsize != sizeof (Elf_External_Versym))
02141        return FALSE;
02142       elf_dynversym (abfd) = shindex;
02143       elf_tdata (abfd)->dynversym_hdr = *hdr;
02144       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
02145 
02146     case SHT_GNU_verneed:
02147       elf_dynverref (abfd) = shindex;
02148       elf_tdata (abfd)->dynverref_hdr = *hdr;
02149       return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
02150 
02151     case SHT_SHLIB:
02152       return TRUE;
02153 
02154     case SHT_GROUP:
02155       /* We need a BFD section for objcopy and relocatable linking,
02156         and it's handy to have the signature available as the section
02157         name.  */
02158       if (! IS_VALID_GROUP_SECTION_HEADER (hdr))
02159        return FALSE;
02160       name = group_signature (abfd, hdr);
02161       if (name == NULL)
02162        return FALSE;
02163       if (!_bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex))
02164        return FALSE;
02165       if (hdr->contents != NULL)
02166        {
02167          Elf_Internal_Group *idx = (Elf_Internal_Group *) hdr->contents;
02168          unsigned int n_elt = hdr->sh_size / GRP_ENTRY_SIZE;
02169          asection *s;
02170 
02171          if (idx->flags & GRP_COMDAT)
02172            hdr->bfd_section->flags
02173              |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
02174 
02175          /* We try to keep the same section order as it comes in.  */
02176          idx += n_elt;
02177          while (--n_elt != 0)
02178            {
02179              --idx;
02180 
02181              if (idx->shdr != NULL
02182                 && (s = idx->shdr->bfd_section) != NULL
02183                 && elf_next_in_group (s) != NULL)
02184               {
02185                 elf_next_in_group (hdr->bfd_section) = s;
02186                 break;
02187               }
02188            }
02189        }
02190       break;
02191 
02192     default:
02193       /* Check for any processor-specific section types.  */
02194       if (bed->elf_backend_section_from_shdr (abfd, hdr, name, shindex))
02195        return TRUE;
02196 
02197       if (hdr->sh_type >= SHT_LOUSER && hdr->sh_type <= SHT_HIUSER)
02198        {
02199          if ((hdr->sh_flags & SHF_ALLOC) != 0)
02200            /* FIXME: How to properly handle allocated section reserved
02201               for applications?  */
02202            (*_bfd_error_handler)
02203              (_("%B: don't know how to handle allocated, application "
02204                "specific section `%s' [0x%8x]"),
02205               abfd, name, hdr->sh_type);
02206          else
02207            /* Allow sections reserved for applications.  */
02208            return _bfd_elf_make_section_from_shdr (abfd, hdr, name,
02209                                               shindex);
02210        }
02211       else if (hdr->sh_type >= SHT_LOPROC
02212               && hdr->sh_type <= SHT_HIPROC)
02213        /* FIXME: We should handle this section.  */
02214        (*_bfd_error_handler)
02215          (_("%B: don't know how to handle processor specific section "
02216             "`%s' [0x%8x]"),
02217           abfd, name, hdr->sh_type);
02218       else if (hdr->sh_type >= SHT_LOOS && hdr->sh_type <= SHT_HIOS)
02219        {
02220          /* Unrecognised OS-specific sections.  */
02221          if ((hdr->sh_flags & SHF_OS_NONCONFORMING) != 0)
02222            /* SHF_OS_NONCONFORMING indicates that special knowledge is
02223               required to correctly process the section and the file should 
02224               be rejected with an error message.  */
02225            (*_bfd_error_handler)
02226              (_("%B: don't know how to handle OS specific section "
02227                "`%s' [0x%8x]"),
02228               abfd, name, hdr->sh_type);
02229          else
02230            /* Otherwise it should be processed.  */
02231            return _bfd_elf_make_section_from_shdr (abfd, hdr, name, shindex);
02232        }
02233       else
02234        /* FIXME: We should handle this section.  */
02235        (*_bfd_error_handler)
02236          (_("%B: don't know how to handle section `%s' [0x%8x]"),
02237           abfd, name, hdr->sh_type);
02238 
02239       return FALSE;
02240     }
02241 
02242   return TRUE;
02243 }
02244 
02245 /* Return the section for the local symbol specified by ABFD, R_SYMNDX.
02246    Return SEC for sections that have no elf section, and NULL on error.  */
02247 
02248 asection *
02249 bfd_section_from_r_symndx (bfd *abfd,
02250                         struct sym_sec_cache *cache,
02251                         asection *sec,
02252                         unsigned long r_symndx)
02253 {
02254   Elf_Internal_Shdr *symtab_hdr;
02255   unsigned char esym[sizeof (Elf64_External_Sym)];
02256   Elf_External_Sym_Shndx eshndx;
02257   Elf_Internal_Sym isym;
02258   unsigned int ent = r_symndx % LOCAL_SYM_CACHE_SIZE;
02259 
02260   if (cache->abfd == abfd && cache->indx[ent] == r_symndx)
02261     return cache->sec[ent];
02262 
02263   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
02264   if (bfd_elf_get_elf_syms (abfd, symtab_hdr, 1, r_symndx,
02265                          &isym, esym, &eshndx) == NULL)
02266     return NULL;
02267 
02268   if (cache->abfd != abfd)
02269     {
02270       memset (cache->indx, -1, sizeof (cache->indx));
02271       cache->abfd = abfd;
02272     }
02273   cache->indx[ent] = r_symndx;
02274   cache->sec[ent] = sec;
02275   if ((isym.st_shndx != SHN_UNDEF && isym.st_shndx < SHN_LORESERVE)
02276       || isym.st_shndx > SHN_HIRESERVE)
02277     {
02278       asection *s;
02279       s = bfd_section_from_elf_index (abfd, isym.st_shndx);
02280       if (s != NULL)
02281        cache->sec[ent] = s;
02282     }
02283   return cache->sec[ent];
02284 }
02285 
02286 /* Given an ELF section number, retrieve the corresponding BFD
02287    section.  */
02288 
02289 asection *
02290 bfd_section_from_elf_index (bfd *abfd, unsigned int index)
02291 {
02292   if (index >= elf_numsections (abfd))
02293     return NULL;
02294   return elf_elfsections (abfd)[index]->bfd_section;
02295 }
02296 
02297 static const struct bfd_elf_special_section special_sections_b[] =
02298 {
02299   { STRING_COMMA_LEN (".bss"), -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE },
02300   { NULL,                   0,  0, 0,            0 }
02301 };
02302 
02303 static const struct bfd_elf_special_section special_sections_c[] =
02304 {
02305   { STRING_COMMA_LEN (".comment"), 0, SHT_PROGBITS, 0 },
02306   { NULL,                       0, 0, 0,            0 }
02307 };
02308 
02309 static const struct bfd_elf_special_section special_sections_d[] =
02310 {
02311   { STRING_COMMA_LEN (".data"),         -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
02312   { STRING_COMMA_LEN (".data1"),         0, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE },
02313   { STRING_COMMA_LEN (".debug"),         0, SHT_PROGBITS, 0 },
02314   { STRING_COMMA_LEN (".debug_line"),    0, SHT_PROGBITS, 0 },
02315   { STRING_COMMA_LEN (".debug_info"),    0, SHT_PROGBITS, 0 },
02316   { STRING_COMMA_LEN (".debug_abbrev"),  0, SHT_PROGBITS, 0 },
02317   { STRING_COMMA_LEN (".debug_aranges"), 0, SHT_PROGBITS, 0 },
02318   { STRING_COMMA_LEN (".dynamic"),       0, SHT_DYNAMIC,  SHF_ALLOC },
02319   { STRING_COMMA_LEN (".dynstr"),        0, SHT_STRTAB,   SHF_ALLOC },
02320   { STRING_COMMA_LEN (".dynsym"),        0, SHT_DYNSYM,   SHF_ALLOC },
02321   { NULL,                      0,        0, 0,            0 }
02322 };
02323 
02324 static const struct bfd_elf_special_section special_sections_f[] =
02325 {
02326   { STRING_COMMA_LEN (".fini"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
02327   { STRING_COMMA_LEN (".fini_array"), 0, SHT_FINI_ARRAY, SHF_ALLOC + SHF_WRITE },
02328   { NULL,                          0, 0, 0,              0 }
02329 };
02330 
02331 static const struct bfd_elf_special_section special_sections_g[] =
02332 {
02333   { STRING_COMMA_LEN (".gnu.linkonce.b"), -2, SHT_NOBITS,      SHF_ALLOC + SHF_WRITE },
02334   { STRING_COMMA_LEN (".got"),             0, SHT_PROGBITS,    SHF_ALLOC + SHF_WRITE },
02335   { STRING_COMMA_LEN (".gnu.version"),     0, SHT_GNU_versym,  0 },
02336   { STRING_COMMA_LEN (".gnu.version_d"),   0, SHT_GNU_verdef,  0 },
02337   { STRING_COMMA_LEN (".gnu.version_r"),   0, SHT_GNU_verneed, 0 },
02338   { STRING_COMMA_LEN (".gnu.liblist"),     0, SHT_GNU_LIBLIST, SHF_ALLOC },
02339   { STRING_COMMA_LEN (".gnu.conflict"),    0, SHT_RELA,        SHF_ALLOC },
02340   { STRING_COMMA_LEN (".gnu.hash"),        0, SHT_GNU_HASH,    SHF_ALLOC },
02341   { NULL,                        0,        0, 0,               0 }
02342 };
02343 
02344 static const struct bfd_elf_special_section special_sections_h[] =
02345 {
02346   { STRING_COMMA_LEN (".hash"), 0, SHT_HASH,     SHF_ALLOC },
02347   { NULL,                    0, 0, 0,            0 }
02348 };
02349 
02350 static const struct bfd_elf_special_section special_sections_i[] =
02351 {
02352   { STRING_COMMA_LEN (".init"),       0, SHT_PROGBITS,   SHF_ALLOC + SHF_EXECINSTR },
02353   { STRING_COMMA_LEN (".init_array"), 0, SHT_INIT_ARRAY, SHF_ALLOC + SHF_WRITE },
02354   { STRING_COMMA_LEN (".interp"),     0, SHT_PROGBITS,   0 },
02355   { NULL,                      0,     0, 0,              0 }
02356 };
02357 
02358 static const struct bfd_elf_special_section special_sections_l[] =
02359 {
02360   { STRING_COMMA_LEN (".line"), 0, SHT_PROGBITS, 0 },
02361   { NULL,                    0, 0, 0,            0 }
02362 };
02363 
02364 static const struct bfd_elf_special_section special_sections_n[] =
02365 {
02366   { STRING_COMMA_LEN (".note.GNU-stack"), 0, SHT_PROGBITS, 0 },
02367   { STRING_COMMA_LEN (".note"),          -1, SHT_NOTE,     0 },
02368   { NULL,                    0,           0, 0,            0 }
02369 };
02370 
02371 static const struct bfd_elf_special_section special_sections_p[] =
02372 {
02373   { STRING_COMMA_LEN (".preinit_array"), 0, SHT_PREINIT_ARRAY, SHF_ALLOC + SHF_WRITE },
02374   { STRING_COMMA_LEN (".plt"),           0, SHT_PROGBITS,      SHF_ALLOC + SHF_EXECINSTR },
02375   { NULL,                   0,           0, 0,                 0 }
02376 };
02377 
02378 static const struct bfd_elf_special_section special_sections_r[] =
02379 {
02380   { STRING_COMMA_LEN (".rodata"), -2, SHT_PROGBITS, SHF_ALLOC },
02381   { STRING_COMMA_LEN (".rodata1"), 0, SHT_PROGBITS, SHF_ALLOC },
02382   { STRING_COMMA_LEN (".rela"),   -1, SHT_RELA,     0 },
02383   { STRING_COMMA_LEN (".rel"),    -1, SHT_REL,      0 },
02384   { NULL,                   0,     0, 0,            0 }
02385 };
02386 
02387 static const struct bfd_elf_special_section special_sections_s[] =
02388 {
02389   { STRING_COMMA_LEN (".shstrtab"), 0, SHT_STRTAB, 0 },
02390   { STRING_COMMA_LEN (".strtab"),   0, SHT_STRTAB, 0 },
02391   { STRING_COMMA_LEN (".symtab"),   0, SHT_SYMTAB, 0 },
02392   /* See struct bfd_elf_special_section declaration for the semantics of
02393      this special case where .prefix_length != strlen (.prefix).  */
02394   { ".stabstr",                    5,  3, SHT_STRTAB, 0 },
02395   { NULL,                       0,  0, 0,          0 }
02396 };
02397 
02398 static const struct bfd_elf_special_section special_sections_t[] =
02399 {
02400   { STRING_COMMA_LEN (".text"),  -2, SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR },
02401   { STRING_COMMA_LEN (".tbss"),  -2, SHT_NOBITS,   SHF_ALLOC + SHF_WRITE + SHF_TLS },
02402   { STRING_COMMA_LEN (".tdata"), -2, SHT_PROGBITS, SHF_ALLOC + SHF_WRITE + SHF_TLS },
02403   { NULL,                     0,  0, 0,            0 }
02404 };
02405 
02406 static const struct bfd_elf_special_section *special_sections[] =
02407 {
02408   special_sections_b,              /* 'b' */
02409   special_sections_c,              /* 'b' */
02410   special_sections_d,              /* 'd' */
02411   NULL,                            /* 'e' */
02412   special_sections_f,              /* 'f' */
02413   special_sections_g,              /* 'g' */
02414   special_sections_h,              /* 'h' */
02415   special_sections_i,              /* 'i' */
02416   NULL,                            /* 'j' */
02417   NULL,                            /* 'k' */
02418   special_sections_l,              /* 'l' */
02419   NULL,                            /* 'm' */
02420   special_sections_n,              /* 'n' */
02421   NULL,                            /* 'o' */
02422   special_sections_p,              /* 'p' */
02423   NULL,                            /* 'q' */
02424   special_sections_r,              /* 'r' */
02425   special_sections_s,              /* 's' */
02426   special_sections_t,              /* 't' */
02427 };
02428 
02429 const struct bfd_elf_special_section *
02430 _bfd_elf_get_special_section (const char *name,
02431                            const struct bfd_elf_special_section *spec,
02432                            unsigned int rela)
02433 {
02434   int i;
02435   int len;
02436 
02437   len = strlen (name);
02438 
02439   for (i = 0; spec[i].prefix != NULL; i++)
02440     {
02441       int suffix_len;
02442       int prefix_len = spec[i].prefix_length;
02443 
02444       if (len < prefix_len)
02445        continue;
02446       if (memcmp (name, spec[i].prefix, prefix_len) != 0)
02447        continue;
02448 
02449       suffix_len = spec[i].suffix_length;
02450       if (suffix_len <= 0)
02451        {
02452          if (name[prefix_len] != 0)
02453            {
02454              if (suffix_len == 0)
02455               continue;
02456              if (name[prefix_len] != '.'
02457                 && (suffix_len == -2
02458                     || (rela && spec[i].type == SHT_REL)))
02459               continue;
02460            }
02461        }
02462       else
02463        {
02464          if (len < prefix_len + suffix_len)
02465            continue;
02466          if (memcmp (name + len - suffix_len,
02467                     spec[i].prefix + prefix_len,
02468                     suffix_len) != 0)
02469            continue;
02470        }
02471       return &spec[i];
02472     }
02473 
02474   return NULL;
02475 }
02476 
02477 const struct bfd_elf_special_section *
02478 _bfd_elf_get_sec_type_attr (bfd *abfd, asection *sec)
02479 {
02480   int i;
02481   const struct bfd_elf_special_section *spec;
02482   const struct elf_backend_data *bed;
02483 
02484   /* See if this is one of the special sections.  */
02485   if (sec->name == NULL)
02486     return NULL;
02487 
02488   bed = get_elf_backend_data (abfd);
02489   spec = bed->special_sections;
02490   if (spec)
02491     {
02492       spec = _bfd_elf_get_special_section (sec->name,
02493                                       bed->special_sections,
02494                                       sec->use_rela_p);
02495       if (spec != NULL)
02496        return spec;
02497     }
02498 
02499   if (sec->name[0] != '.')
02500     return NULL;
02501 
02502   i = sec->name[1] - 'b';
02503   if (i < 0 || i > 't' - 'b')
02504     return NULL;
02505 
02506   spec = special_sections[i];
02507 
02508   if (spec == NULL)
02509     return NULL;
02510 
02511   return _bfd_elf_get_special_section (sec->name, spec, sec->use_rela_p);
02512 }
02513 
02514 bfd_boolean
02515 _bfd_elf_new_section_hook (bfd *abfd, asection *sec)
02516 {
02517   struct bfd_elf_section_data *sdata;
02518   const struct elf_backend_data *bed;
02519   const struct bfd_elf_special_section *ssect;
02520 
02521   sdata = (struct bfd_elf_section_data *) sec->used_by_bfd;
02522   if (sdata == NULL)
02523     {
02524       sdata = bfd_zalloc (abfd, sizeof (*sdata));
02525       if (sdata == NULL)
02526        return FALSE;
02527       sec->used_by_bfd = sdata;
02528     }
02529 
02530   /* Indicate whether or not this section should use RELA relocations.  */
02531   bed = get_elf_backend_data (abfd);
02532   sec->use_rela_p = bed->default_use_rela_p;
02533 
02534   /* When we read a file, we don't need to set ELF section type and
02535      flags.  They will be overridden in _bfd_elf_make_section_from_shdr
02536      anyway.  We will set ELF section type and flags for all linker
02537      created sections.  If user specifies BFD section flags, we will
02538      set ELF section type and flags based on BFD section flags in
02539      elf_fake_sections.  */
02540   if ((!sec->flags && abfd->direction != read_direction)
02541       || (sec->flags & SEC_LINKER_CREATED) != 0)
02542     {
02543       ssect = (*bed->get_sec_type_attr) (abfd, sec);
02544       if (ssect != NULL)
02545        {
02546          elf_section_type (sec) = ssect->type;
02547          elf_section_flags (sec) = ssect->attr;
02548        }
02549     }
02550 
02551   return _bfd_generic_new_section_hook (abfd, sec);
02552 }
02553 
02554 /* Create a new bfd section from an ELF program header.
02555 
02556    Since program segments have no names, we generate a synthetic name
02557    of the form segment<NUM>, where NUM is generally the index in the
02558    program header table.  For segments that are split (see below) we
02559    generate the names segment<NUM>a and segment<NUM>b.
02560 
02561    Note that some program segments may have a file size that is different than
02562    (less than) the memory size.  All this means is that at execution the
02563    system must allocate the amount of memory specified by the memory size,
02564    but only initialize it with the first "file size" bytes read from the
02565    file.  This would occur for example, with program segments consisting
02566    of combined data+bss.
02567 
02568    To handle the above situation, this routine generates TWO bfd sections
02569    for the single program segment.  The first has the length specified by
02570    the file size of the segment, and the second has the length specified
02571    by the difference between the two sizes.  In effect, the segment is split
02572    into it's initialized and uninitialized parts.
02573 
02574  */
02575 
02576 bfd_boolean
02577 _bfd_elf_make_section_from_phdr (bfd *abfd,
02578                              Elf_Internal_Phdr *hdr,
02579                              int index,
02580                              const char *typename)
02581 {
02582   asection *newsect;
02583   char *name;
02584   char namebuf[64];
02585   size_t len;
02586   int split;
02587 
02588   split = ((hdr->p_memsz > 0)
02589            && (hdr->p_filesz > 0)
02590            && (hdr->p_memsz > hdr->p_filesz));
02591   sprintf (namebuf, "%s%d%s", typename, index, split ? "a" : "");
02592   len = strlen (namebuf) + 1;
02593   name = bfd_alloc (abfd, len);
02594   if (!name)
02595     return FALSE;
02596   memcpy (name, namebuf, len);
02597   newsect = bfd_make_section (abfd, name);
02598   if (newsect == NULL)
02599     return FALSE;
02600   newsect->vma = hdr->p_vaddr;
02601   newsect->lma = hdr->p_paddr;
02602   newsect->size = hdr->p_filesz;
02603   newsect->filepos = hdr->p_offset;
02604   newsect->flags |= SEC_HAS_CONTENTS;
02605   newsect->alignment_power = bfd_log2 (hdr->p_align);
02606   if (hdr->p_type == PT_LOAD)
02607     {
02608       newsect->flags |= SEC_ALLOC;
02609       newsect->flags |= SEC_LOAD;
02610       if (hdr->p_flags & PF_X)
02611        {
02612          /* FIXME: all we known is that it has execute PERMISSION,
02613             may be data.  */
02614          newsect->flags |= SEC_CODE;
02615        }
02616     }
02617   if (!(hdr->p_flags & PF_W))
02618     {
02619       newsect->flags |= SEC_READONLY;
02620     }
02621 
02622   if (split)
02623     {
02624       sprintf (namebuf, "%s%db", typename, index);
02625       len = strlen (namebuf) + 1;
02626       name = bfd_alloc (abfd, len);
02627       if (!name)
02628        return FALSE;
02629       memcpy (name, namebuf, len);
02630       newsect = bfd_make_section (abfd, name);
02631       if (newsect == NULL)
02632        return FALSE;
02633       newsect->vma = hdr->p_vaddr + hdr->p_filesz;
02634       newsect->lma = hdr->p_paddr + hdr->p_filesz;
02635       newsect->size = hdr->p_memsz - hdr->p_filesz;
02636       if (hdr->p_type == PT_LOAD)
02637        {
02638          newsect->flags |= SEC_ALLOC;
02639          if (hdr->p_flags & PF_X)
02640            newsect->flags |= SEC_CODE;
02641        }
02642       if (!(hdr->p_flags & PF_W))
02643        newsect->flags |= SEC_READONLY;
02644     }
02645 
02646   return TRUE;
02647 }
02648 
02649 bfd_boolean
02650 bfd_section_from_phdr (bfd *abfd, Elf_Internal_Phdr *hdr, int index)
02651 {
02652   const struct elf_backend_data *bed;
02653 
02654   switch (hdr->p_type)
02655     {
02656     case PT_NULL:
02657       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "null");
02658 
02659     case PT_LOAD:
02660       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "load");
02661 
02662     case PT_DYNAMIC:
02663       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "dynamic");
02664 
02665     case PT_INTERP:
02666       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "interp");
02667 
02668     case PT_NOTE:
02669       if (! _bfd_elf_make_section_from_phdr (abfd, hdr, index, "note"))
02670        return FALSE;
02671       if (! elfcore_read_notes (abfd, hdr->p_offset, hdr->p_filesz))
02672        return FALSE;
02673       return TRUE;
02674 
02675     case PT_SHLIB:
02676       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "shlib");
02677 
02678     case PT_PHDR:
02679       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "phdr");
02680 
02681     case PT_GNU_EH_FRAME:
02682       return _bfd_elf_make_section_from_phdr (abfd, hdr, index,
02683                                          "eh_frame_hdr");
02684 
02685     case PT_GNU_STACK:
02686       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "stack");
02687 
02688     case PT_GNU_RELRO:
02689       return _bfd_elf_make_section_from_phdr (abfd, hdr, index, "relro");
02690 
02691     default:
02692       /* Check for any processor-specific program segment types.  */
02693       bed = get_elf_backend_data (abfd);
02694       return bed->elf_backend_section_from_phdr (abfd, hdr, index, "proc");
02695     }
02696 }
02697 
02698 /* Initialize REL_HDR, the section-header for new section, containing
02699    relocations against ASECT.  If USE_RELA_P is TRUE, we use RELA
02700    relocations; otherwise, we use REL relocations.  */
02701 
02702 bfd_boolean
02703 _bfd_elf_init_reloc_shdr (bfd *abfd,
02704                        Elf_Internal_Shdr *rel_hdr,
02705                        asection *asect,
02706                        bfd_boolean use_rela_p)
02707 {
02708   char *name;
02709   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
02710   bfd_size_type amt = sizeof ".rela" + strlen (asect->name);
02711 
02712   name = bfd_alloc (abfd, amt);
02713   if (name == NULL)
02714     return FALSE;
02715   sprintf (name, "%s%s", use_rela_p ? ".rela" : ".rel", asect->name);
02716   rel_hdr->sh_name =
02717     (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd), name,
02718                                    FALSE);
02719   if (rel_hdr->sh_name == (unsigned int) -1)
02720     return FALSE;
02721   rel_hdr->sh_type = use_rela_p ? SHT_RELA : SHT_REL;
02722   rel_hdr->sh_entsize = (use_rela_p
02723                       ? bed->s->sizeof_rela
02724                       : bed->s->sizeof_rel);
02725   rel_hdr->sh_addralign = 1 << bed->s->log_file_align;
02726   rel_hdr->sh_flags = 0;
02727   rel_hdr->sh_addr = 0;
02728   rel_hdr->sh_size = 0;
02729   rel_hdr->sh_offset = 0;
02730 
02731   return TRUE;
02732 }
02733 
02734 /* Set up an ELF internal section header for a section.  */
02735 
02736 static void
02737 elf_fake_sections (bfd *abfd, asection *asect, void *failedptrarg)
02738 {
02739   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
02740   bfd_boolean *failedptr = failedptrarg;
02741   Elf_Internal_Shdr *this_hdr;
02742 
02743   if (*failedptr)
02744     {
02745       /* We already failed; just get out of the bfd_map_over_sections
02746          loop.  */
02747       return;
02748     }
02749 
02750   this_hdr = &elf_section_data (asect)->this_hdr;
02751 
02752   this_hdr->sh_name = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
02753                                                    asect->name, FALSE);
02754   if (this_hdr->sh_name == (unsigned int) -1)
02755     {
02756       *failedptr = TRUE;
02757       return;
02758     }
02759 
02760   /* Don't clear sh_flags. Assembler may set additional bits.  */
02761 
02762   if ((asect->flags & SEC_ALLOC) != 0
02763       || asect->user_set_vma)
02764     this_hdr->sh_addr = asect->vma;
02765   else
02766     this_hdr->sh_addr = 0;
02767 
02768   this_hdr->sh_offset = 0;
02769   this_hdr->sh_size = asect->size;
02770   this_hdr->sh_link = 0;
02771   this_hdr->sh_addralign = 1 << asect->alignment_power;
02772   /* The sh_entsize and sh_info fields may have been set already by
02773      copy_private_section_data.  */
02774 
02775   this_hdr->bfd_section = asect;
02776   this_hdr->contents = NULL;
02777 
02778   /* If the section type is unspecified, we set it based on
02779      asect->flags.  */
02780   if (this_hdr->sh_type == SHT_NULL)
02781     {
02782       if ((asect->flags & SEC_GROUP) != 0)
02783        this_hdr->sh_type = SHT_GROUP;
02784       else if ((asect->flags & SEC_ALLOC) != 0
02785               && (((asect->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
02786                  || (asect->flags & SEC_NEVER_LOAD) != 0))
02787        this_hdr->sh_type = SHT_NOBITS;
02788       else
02789        this_hdr->sh_type = SHT_PROGBITS;
02790     }
02791 
02792   switch (this_hdr->sh_type)
02793     {
02794     default:
02795       break;
02796 
02797     case SHT_STRTAB:
02798     case SHT_INIT_ARRAY:
02799     case SHT_FINI_ARRAY:
02800     case SHT_PREINIT_ARRAY:
02801     case SHT_NOTE:
02802     case SHT_NOBITS:
02803     case SHT_PROGBITS:
02804       break;
02805 
02806     case SHT_HASH:
02807       this_hdr->sh_entsize = bed->s->sizeof_hash_entry;
02808       break;
02809 
02810     case SHT_DYNSYM:
02811       this_hdr->sh_entsize = bed->s->sizeof_sym;
02812       break;
02813 
02814     case SHT_DYNAMIC:
02815       this_hdr->sh_entsize = bed->s->sizeof_dyn;
02816       break;
02817 
02818     case SHT_RELA:
02819       if (get_elf_backend_data (abfd)->may_use_rela_p)
02820        this_hdr->sh_entsize = bed->s->sizeof_rela;
02821       break;
02822 
02823      case SHT_REL:
02824       if (get_elf_backend_data (abfd)->may_use_rel_p)
02825        this_hdr->sh_entsize = bed->s->sizeof_rel;
02826       break;
02827 
02828      case SHT_GNU_versym:
02829       this_hdr->sh_entsize = sizeof (Elf_External_Versym);
02830       break;
02831 
02832      case SHT_GNU_verdef:
02833       this_hdr->sh_entsize = 0;
02834       /* objcopy or strip will copy over sh_info, but may not set
02835          cverdefs.  The linker will set cverdefs, but sh_info will be
02836          zero.  */
02837       if (this_hdr->sh_info == 0)
02838        this_hdr->sh_info = elf_tdata (abfd)->cverdefs;
02839       else
02840        BFD_ASSERT (elf_tdata (abfd)->cverdefs == 0
02841                   || this_hdr->sh_info == elf_tdata (abfd)->cverdefs);
02842       break;
02843 
02844     case SHT_GNU_verneed:
02845       this_hdr->sh_entsize = 0;
02846       /* objcopy or strip will copy over sh_info, but may not set
02847          cverrefs.  The linker will set cverrefs, but sh_info will be
02848          zero.  */
02849       if (this_hdr->sh_info == 0)
02850        this_hdr->sh_info = elf_tdata (abfd)->cverrefs;
02851       else
02852        BFD_ASSERT (elf_tdata (abfd)->cverrefs == 0
02853                   || this_hdr->sh_info == elf_tdata (abfd)->cverrefs);
02854       break;
02855 
02856     case SHT_GROUP:
02857       this_hdr->sh_entsize = GRP_ENTRY_SIZE;
02858       break;
02859 
02860     case SHT_GNU_HASH:
02861       this_hdr->sh_entsize = bed->s->arch_size == 64 ? 0 : 4;
02862       break;
02863     }
02864 
02865   if ((asect->flags & SEC_ALLOC) != 0)
02866     this_hdr->sh_flags |= SHF_ALLOC;
02867   if ((asect->flags & SEC_READONLY) == 0)
02868     this_hdr->sh_flags |= SHF_WRITE;
02869   if ((asect->flags & SEC_CODE) != 0)
02870     this_hdr->sh_flags |= SHF_EXECINSTR;
02871   if ((asect->flags & SEC_MERGE) != 0)
02872     {
02873       this_hdr->sh_flags |= SHF_MERGE;
02874       this_hdr->sh_entsize = asect->entsize;
02875       if ((asect->flags & SEC_STRINGS) != 0)
02876        this_hdr->sh_flags |= SHF_STRINGS;
02877     }
02878   if ((asect->flags & SEC_GROUP) == 0 && elf_group_name (asect) != NULL)
02879     this_hdr->sh_flags |= SHF_GROUP;
02880   if ((asect->flags & SEC_THREAD_LOCAL) != 0)
02881     {
02882       this_hdr->sh_flags |= SHF_TLS;
02883       if (asect->size == 0
02884          && (asect->flags & SEC_HAS_CONTENTS) == 0)
02885        {
02886          struct bfd_link_order *o = asect->map_tail.link_order;
02887 
02888          this_hdr->sh_size = 0;
02889          if (o != NULL)
02890            {
02891              this_hdr->sh_size = o->offset + o->size;
02892              if (this_hdr->sh_size != 0)
02893               this_hdr->sh_type = SHT_NOBITS;
02894            }
02895        }
02896     }
02897 
02898   /* Check for processor-specific section types.  */
02899   if (bed->elf_backend_fake_sections
02900       && !(*bed->elf_backend_fake_sections) (abfd, this_hdr, asect))
02901     *failedptr = TRUE;
02902 
02903   /* If the section has relocs, set up a section header for the
02904      SHT_REL[A] section.  If two relocation sections are required for
02905      this section, it is up to the processor-specific back-end to
02906      create the other.  */
02907   if ((asect->flags & SEC_RELOC) != 0
02908       && !_bfd_elf_init_reloc_shdr (abfd,
02909                                 &elf_section_data (asect)->rel_hdr,
02910                                 asect,
02911                                 asect->use_rela_p))
02912     *failedptr = TRUE;
02913 }
02914 
02915 /* Fill in the contents of a SHT_GROUP section.  */
02916 
02917 void
02918 bfd_elf_set_group_contents (bfd *abfd, asection *sec, void *failedptrarg)
02919 {
02920   bfd_boolean *failedptr = failedptrarg;
02921   unsigned long symindx;
02922   asection *elt, *first;
02923   unsigned char *loc;
02924   bfd_boolean gas;
02925 
02926   /* Ignore linker created group section.  See elfNN_ia64_object_p in
02927      elfxx-ia64.c.  */
02928   if (((sec->flags & (SEC_GROUP | SEC_LINKER_CREATED)) != SEC_GROUP)
02929       || *failedptr)
02930     return;
02931 
02932   symindx = 0;
02933   if (elf_group_id (sec) != NULL)
02934     symindx = elf_group_id (sec)->udata.i;
02935 
02936   if (symindx == 0)
02937     {
02938       /* If called from the assembler, swap_out_syms will have set up
02939         elf_section_syms;  If called for "ld -r", use target_index.  */
02940       if (elf_section_syms (abfd) != NULL)
02941        symindx = elf_section_syms (abfd)[sec->index]->udata.i;
02942       else
02943        symindx = sec->target_index;
02944     }
02945   elf_section_data (sec)->this_hdr.sh_info = symindx;
02946 
02947   /* The contents won't be allocated for "ld -r" or objcopy.  */
02948   gas = TRUE;
02949   if (sec->contents == NULL)
02950     {
02951       gas = FALSE;
02952       sec->contents = bfd_alloc (abfd, sec->size);
02953 
02954       /* Arrange for the section to be written out.  */
02955       elf_section_data (sec)->this_hdr.contents = sec->contents;
02956       if (sec->contents == NULL)
02957        {
02958          *failedptr = TRUE;
02959          return;
02960        }
02961     }
02962 
02963   loc = sec->contents + sec->size;
02964 
02965   /* Get the pointer to the first section in the group that gas
02966      squirreled away here.  objcopy arranges for this to be set to the
02967      start of the input section group.  */
02968   first = elt = elf_next_in_group (sec);
02969 
02970   /* First element is a flag word.  Rest of section is elf section
02971      indices for all the sections of the group.  Write them backwards
02972      just to keep the group in the same order as given in .section
02973      directives, not that it matters.  */
02974   while (elt != NULL)
02975     {
02976       asection *s;
02977       unsigned int idx;
02978 
02979       loc -= 4;
02980       s = elt;
02981       if (!gas)
02982        s = s->output_section;
02983       idx = 0;
02984       if (s != NULL)
02985        idx = elf_section_data (s)->this_idx;
02986       H_PUT_32 (abfd, idx, loc);
02987       elt = elf_next_in_group (elt);
02988       if (elt == first)
02989        break;
02990     }
02991 
02992   if ((loc -= 4) != sec->contents)
02993     abort ();
02994 
02995   H_PUT_32 (abfd, sec->flags & SEC_LINK_ONCE ? GRP_COMDAT : 0, loc);
02996 }
02997 
02998 /* Assign all ELF section numbers.  The dummy first section is handled here
02999    too.  The link/info pointers for the standard section types are filled
03000    in here too, while we're at it.  */
03001 
03002 static bfd_boolean
03003 assign_section_numbers (bfd *abfd, struct bfd_link_info *link_info)
03004 {
03005   struct elf_obj_tdata *t = elf_tdata (abfd);
03006   asection *sec;
03007   unsigned int section_number, secn;
03008   Elf_Internal_Shdr **i_shdrp;
03009   struct bfd_elf_section_data *d;
03010 
03011   section_number = 1;
03012 
03013   _bfd_elf_strtab_clear_all_refs (elf_shstrtab (abfd));
03014 
03015   /* SHT_GROUP sections are in relocatable files only.  */
03016   if (link_info == NULL || link_info->relocatable)
03017     {
03018       /* Put SHT_GROUP sections first.  */
03019       for (sec = abfd->sections; sec != NULL; sec = sec->next)
03020        {
03021          d = elf_section_data (sec);
03022 
03023          if (d->this_hdr.sh_type == SHT_GROUP)
03024            { 
03025              if (sec->flags & SEC_LINKER_CREATED)
03026               {
03027                 /* Remove the linker created SHT_GROUP sections.  */
03028                 bfd_section_list_remove (abfd, sec);
03029                 abfd->section_count--;
03030               }
03031              else 
03032               {
03033                 if (section_number == SHN_LORESERVE)
03034                   section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03035                 d->this_idx = section_number++;
03036               }
03037            }
03038        }
03039     }
03040 
03041   for (sec = abfd->sections; sec; sec = sec->next)
03042     {
03043       d = elf_section_data (sec);
03044 
03045       if (d->this_hdr.sh_type != SHT_GROUP)
03046        {
03047          if (section_number == SHN_LORESERVE)
03048            section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03049          d->this_idx = section_number++;
03050        }
03051       _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->this_hdr.sh_name);
03052       if ((sec->flags & SEC_RELOC) == 0)
03053        d->rel_idx = 0;
03054       else
03055        {
03056          if (section_number == SHN_LORESERVE)
03057            section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03058          d->rel_idx = section_number++;
03059          _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr.sh_name);
03060        }
03061 
03062       if (d->rel_hdr2)
03063        {
03064          if (section_number == SHN_LORESERVE)
03065            section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03066          d->rel_idx2 = section_number++;
03067          _bfd_elf_strtab_addref (elf_shstrtab (abfd), d->rel_hdr2->sh_name);
03068        }
03069       else
03070        d->rel_idx2 = 0;
03071     }
03072 
03073   if (section_number == SHN_LORESERVE)
03074     section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03075   t->shstrtab_section = section_number++;
03076   _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->shstrtab_hdr.sh_name);
03077   elf_elfheader (abfd)->e_shstrndx = t->shstrtab_section;
03078 
03079   if (bfd_get_symcount (abfd) > 0)
03080     {
03081       if (section_number == SHN_LORESERVE)
03082        section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03083       t->symtab_section = section_number++;
03084       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->symtab_hdr.sh_name);
03085       if (section_number > SHN_LORESERVE - 2)
03086        {
03087          if (section_number == SHN_LORESERVE)
03088            section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03089          t->symtab_shndx_section = section_number++;
03090          t->symtab_shndx_hdr.sh_name
03091            = (unsigned int) _bfd_elf_strtab_add (elf_shstrtab (abfd),
03092                                             ".symtab_shndx", FALSE);
03093          if (t->symtab_shndx_hdr.sh_name == (unsigned int) -1)
03094            return FALSE;
03095        }
03096       if (section_number == SHN_LORESERVE)
03097        section_number += SHN_HIRESERVE + 1 - SHN_LORESERVE;
03098       t->strtab_section = section_number++;
03099       _bfd_elf_strtab_addref (elf_shstrtab (abfd), t->strtab_hdr.sh_name);
03100     }
03101 
03102   _bfd_elf_strtab_finalize (elf_shstrtab (abfd));
03103   t->shstrtab_hdr.sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
03104 
03105   elf_numsections (abfd) = section_number;
03106   elf_elfheader (abfd)->e_shnum = section_number;
03107   if (section_number > SHN_LORESERVE)
03108     elf_elfheader (abfd)->e_shnum -= SHN_HIRESERVE + 1 - SHN_LORESERVE;
03109 
03110   /* Set up the list of section header pointers, in agreement with the
03111      indices.  */
03112   i_shdrp = bfd_zalloc2 (abfd, section_number, sizeof (Elf_Internal_Shdr *));
03113   if (i_shdrp == NULL)
03114     return FALSE;
03115 
03116   i_shdrp[0] = bfd_zalloc (abfd, sizeof (Elf_Internal_Shdr));
03117   if (i_shdrp[0] == NULL)
03118     {
03119       bfd_release (abfd, i_shdrp);
03120       return FALSE;
03121     }
03122 
03123   elf_elfsections (abfd) = i_shdrp;
03124 
03125   i_shdrp[t->shstrtab_section] = &t->shstrtab_hdr;
03126   if (bfd_get_symcount (abfd) > 0)
03127     {
03128       i_shdrp[t->symtab_section] = &t->symtab_hdr;
03129       if (elf_numsections (abfd) > SHN_LORESERVE)
03130        {
03131          i_shdrp[t->symtab_shndx_section] = &t->symtab_shndx_hdr;
03132          t->symtab_shndx_hdr.sh_link = t->symtab_section;
03133        }
03134       i_shdrp[t->strtab_section] = &t->strtab_hdr;
03135       t->symtab_hdr.sh_link = t->strtab_section;
03136     }
03137 
03138   for (sec = abfd->sections; sec; sec = sec->next)
03139     {
03140       struct bfd_elf_section_data *d = elf_section_data (sec);
03141       asection *s;
03142       const char *name;
03143 
03144       i_shdrp[d->this_idx] = &d->this_hdr;
03145       if (d->rel_idx != 0)
03146        i_shdrp[d->rel_idx] = &d->rel_hdr;
03147       if (d->rel_idx2 != 0)
03148        i_shdrp[d->rel_idx2] = d->rel_hdr2;
03149 
03150       /* Fill in the sh_link and sh_info fields while we're at it.  */
03151 
03152       /* sh_link of a reloc section is the section index of the symbol
03153         table.  sh_info is the section index of the section to which
03154         the relocation entries apply.  */
03155       if (d->rel_idx != 0)
03156        {
03157          d->rel_hdr.sh_link = t->symtab_section;
03158          d->rel_hdr.sh_info = d->this_idx;
03159        }
03160       if (d->rel_idx2 != 0)
03161        {
03162          d->rel_hdr2->sh_link = t->symtab_section;
03163          d->rel_hdr2->sh_info = d->this_idx;
03164        }
03165 
03166       /* We need to set up sh_link for SHF_LINK_ORDER.  */
03167       if ((d->this_hdr.sh_flags & SHF_LINK_ORDER) != 0)
03168        {
03169          s = elf_linked_to_section (sec);
03170          if (s)
03171            {
03172              /* elf_linked_to_section points to the input section.  */
03173              if (link_info != NULL)
03174               {
03175                 /* Check discarded linkonce section.  */
03176                 if (elf_discarded_section (s))
03177                   {
03178                     asection *kept;
03179                     (*_bfd_error_handler)
03180                      (_("%B: sh_link of section `%A' points to discarded section `%A' of `%B'"),
03181                       abfd, d->this_hdr.bfd_section,
03182                       s, s->owner);
03183                     /* Point to the kept section if it has the same
03184                       size as the discarded one.  */
03185                     kept = _bfd_elf_check_kept_section (s, link_info);
03186                     if (kept == NULL)
03187                      {
03188                        bfd_set_error (bfd_error_bad_value);
03189                        return FALSE;
03190                      }
03191                     s = kept;
03192                   }
03193 
03194                 s = s->output_section;
03195                 BFD_ASSERT (s != NULL);
03196               }
03197              else
03198               {
03199                 /* Handle objcopy. */
03200                 if (s->output_section == NULL)
03201                   {
03202                     (*_bfd_error_handler)
03203                      (_("%B: sh_link of section `%A' points to removed section `%A' of `%B'"),
03204                       abfd, d->this_hdr.bfd_section, s, s->owner);
03205                     bfd_set_error (bfd_error_bad_value);
03206                     return FALSE;
03207                   }
03208                 s = s->output_section;
03209               }
03210              d->this_hdr.sh_link = elf_section_data (s)->this_idx;
03211            }
03212          else
03213            {
03214              /* PR 290:
03215                The Intel C compiler generates SHT_IA_64_UNWIND with
03216                SHF_LINK_ORDER.  But it doesn't set the sh_link or
03217                sh_info fields.  Hence we could get the situation
03218                 where s is NULL.  */
03219              const struct elf_backend_data *bed
03220               = get_elf_backend_data (abfd);
03221              if (bed->link_order_error_handler)
03222               bed->link_order_error_handler
03223                 (_("%B: warning: sh_link not set for section `%A'"),
03224                  abfd, sec);
03225            }
03226        }
03227 
03228       switch (d->this_hdr.sh_type)
03229        {
03230        case SHT_REL:
03231        case SHT_RELA:
03232          /* A reloc section which we are treating as a normal BFD
03233             section.  sh_link is the section index of the symbol
03234             table.  sh_info is the section index of the section to
03235             which the relocation entries apply.  We assume that an
03236             allocated reloc section uses the dynamic symbol table.
03237             FIXME: How can we be sure?  */
03238          s = bfd_get_section_by_name (abfd, ".dynsym");
03239          if (s != NULL)
03240            d->this_hdr.sh_link = elf_section_data (s)->this_idx;
03241 
03242          /* We look up the section the relocs apply to by name.  */
03243          name = sec->name;
03244          if (d->this_hdr.sh_type == SHT_REL)
03245            name += 4;
03246          else
03247            name += 5;
03248          s = bfd_get_section_by_name (abfd, name);
03249          if (s != NULL)
03250            d->this_hdr.sh_info = elf_section_data (s)->this_idx;
03251          break;
03252 
03253        case SHT_STRTAB:
03254          /* We assume that a section named .stab*str is a stabs
03255             string section.  We look for a section with the same name
03256             but without the trailing ``str'', and set its sh_link
03257             field to point to this section.  */
03258          if (CONST_STRNEQ (sec->name, ".stab")
03259              && strcmp (sec->name + strlen (sec->name) - 3, "str") == 0)
03260            {
03261              size_t len;
03262              char *alc;
03263 
03264              len = strlen (sec->name);
03265              alc = bfd_malloc (len - 2);
03266              if (alc == NULL)
03267               return FALSE;
03268              memcpy (alc, sec->name, len - 3);
03269              alc[len - 3] = '\0';
03270              s = bfd_get_section_by_name (abfd, alc);
03271              free (alc);
03272              if (s != NULL)
03273               {
03274                 elf_section_data (s)->this_hdr.sh_link = d->this_idx;
03275 
03276                 /* This is a .stab section.  */
03277                 if (elf_section_data (s)->this_hdr.sh_entsize == 0)
03278                   elf_section_data (s)->this_hdr.sh_entsize
03279                     = 4 + 2 * bfd_get_arch_size (abfd) / 8;
03280               }
03281            }
03282          break;
03283 
03284        case SHT_DYNAMIC:
03285        case SHT_DYNSYM:
03286        case SHT_GNU_verneed:
03287        case SHT_GNU_verdef:
03288          /* sh_link is the section header index of the string table
03289             used for the dynamic entries, or the symbol table, or the
03290             version strings.  */
03291          s = bfd_get_section_by_name (abfd, ".dynstr");
03292          if (s != NULL)
03293            d->this_hdr.sh_link = elf_section_data (s)->this_idx;
03294          break;
03295 
03296        case SHT_GNU_LIBLIST:
03297          /* sh_link is the section header index of the prelink library
03298             list 
03299             used for the dynamic entries, or the symbol table, or the
03300             version strings.  */
03301          s = bfd_get_section_by_name (abfd, (sec->flags & SEC_ALLOC)
03302                                         ? ".dynstr" : ".gnu.libstr");
03303          if (s != NULL)
03304            d->this_hdr.sh_link = elf_section_data (s)->this_idx;
03305          break;
03306 
03307        case SHT_HASH:
03308        case SHT_GNU_HASH:
03309        case SHT_GNU_versym:
03310          /* sh_link is the section header index of the symbol table
03311             this hash table or version table is for.  */
03312          s = bfd_get_section_by_name (abfd, ".dynsym");
03313          if (s != NULL)
03314            d->this_hdr.sh_link = elf_section_data (s)->this_idx;
03315          break;
03316 
03317        case SHT_GROUP:
03318          d->this_hdr.sh_link = t->symtab_section;
03319        }
03320     }
03321 
03322   for (secn = 1; secn < section_number; ++secn)
03323     if (i_shdrp[secn] == NULL)
03324       i_shdrp[secn] = i_shdrp[0];
03325     else
03326       i_shdrp[secn]->sh_name = _bfd_elf_strtab_offset (elf_shstrtab (abfd),
03327                                                  i_shdrp[secn]->sh_name);
03328   return TRUE;
03329 }
03330 
03331 /* Map symbol from it's internal number to the external number, moving
03332    all local symbols to be at the head of the list.  */
03333 
03334 static bfd_boolean
03335 sym_is_global (bfd *abfd, asymbol *sym)
03336 {
03337   /* If the backend has a special mapping, use it.  */
03338   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
03339   if (bed->elf_backend_sym_is_global)
03340     return (*bed->elf_backend_sym_is_global) (abfd, sym);
03341 
03342   return ((sym->flags & (BSF_GLOBAL | BSF_WEAK)) != 0
03343          || bfd_is_und_section (bfd_get_section (sym))
03344          || bfd_is_com_section (bfd_get_section (sym)));
03345 }
03346 
03347 /* Don't output section symbols for sections that are not going to be
03348    output.  Also, don't output section symbols for reloc and other
03349    special sections.  */
03350 
03351 static bfd_boolean
03352 ignore_section_sym (bfd *abfd, asymbol *sym)
03353 {
03354   return ((sym->flags & BSF_SECTION_SYM) != 0
03355          && (sym->value != 0
03356              || (sym->section->owner != abfd
03357                 && (sym->section->output_section->owner != abfd
03358                     || sym->section->output_offset != 0))));
03359 }
03360 
03361 static bfd_boolean
03362 elf_map_symbols (bfd *abfd)
03363 {
03364   unsigned int symcount = bfd_get_symcount (abfd);
03365   asymbol **syms = bfd_get_outsymbols (abfd);
03366   asymbol **sect_syms;
03367   unsigned int num_locals = 0;
03368   unsigned int num_globals = 0;
03369   unsigned int num_locals2 = 0;
03370   unsigned int num_globals2 = 0;
03371   int max_index = 0;
03372   unsigned int idx;
03373   asection *asect;
03374   asymbol **new_syms;
03375 
03376 #ifdef DEBUG
03377   fprintf (stderr, "elf_map_symbols\n");
03378   fflush (stderr);
03379 #endif
03380 
03381   for (asect = abfd->sections; asect; asect = asect->next)
03382     {
03383       if (max_index < asect->index)
03384        max_index = asect->index;
03385     }
03386 
03387   max_index++;
03388   sect_syms = bfd_zalloc2 (abfd, max_index, sizeof (asymbol *));
03389   if (sect_syms == NULL)
03390     return FALSE;
03391   elf_section_syms (abfd) = sect_syms;
03392   elf_num_section_syms (abfd) = max_index;
03393 
03394   /* Init sect_syms entries for any section symbols we have already
03395      decided to output.  */
03396   for (idx = 0; idx < symcount; idx++)
03397     {
03398       asymbol *sym = syms[idx];
03399 
03400       if ((sym->flags & BSF_SECTION_SYM) != 0
03401          && !ignore_section_sym (abfd, sym))
03402        {
03403          asection *sec = sym->section;
03404 
03405          if (sec->owner != abfd)
03406            sec = sec->output_section;
03407 
03408          sect_syms[sec->index] = syms[idx];
03409        }
03410     }
03411 
03412   /* Classify all of the symbols.  */
03413   for (idx = 0; idx < symcount; idx++)
03414     {
03415       if (ignore_section_sym (abfd, syms[idx]))
03416        continue;
03417       if (!sym_is_global (abfd, syms[idx]))
03418        num_locals++;
03419       else
03420        num_globals++;
03421     }
03422 
03423   /* We will be adding a section symbol for each normal BFD section.  Most
03424      sections will already have a section symbol in outsymbols, but
03425      eg. SHT_GROUP sections will not, and we need the section symbol mapped
03426      at least in that case.  */
03427   for (asect = abfd->sections; asect; asect = asect->next)
03428     {
03429       if (sect_syms[asect->index] == NULL)
03430        {
03431          if (!sym_is_global (abfd, asect->symbol))
03432            num_locals++;
03433          else
03434            num_globals++;
03435        }
03436     }
03437 
03438   /* Now sort the symbols so the local symbols are first.  */
03439   new_syms = bfd_alloc2 (abfd, num_locals + num_globals, sizeof (asymbol *));
03440 
03441   if (new_syms == NULL)
03442     return FALSE;
03443 
03444   for (idx = 0; idx < symcount; idx++)
03445     {
03446       asymbol *sym = syms[idx];
03447       unsigned int i;
03448 
03449       if (ignore_section_sym (abfd, sym))
03450        continue;
03451       if (!sym_is_global (abfd, sym))
03452        i = num_locals2++;
03453       else
03454        i = num_locals + num_globals2++;
03455       new_syms[i] = sym;
03456       sym->udata.i = i + 1;
03457     }
03458   for (asect = abfd->sections; asect; asect = asect->next)
03459     {
03460       if (sect_syms[asect->index] == NULL)
03461        {
03462          asymbol *sym = asect->symbol;
03463          unsigned int i;
03464 
03465          sect_syms[asect->index] = sym;
03466          if (!sym_is_global (abfd, sym))
03467            i = num_locals2++;
03468          else
03469            i = num_locals + num_globals2++;
03470          new_syms[i] = sym;
03471          sym->udata.i = i + 1;
03472        }
03473     }
03474 
03475   bfd_set_symtab (abfd, new_syms, num_locals + num_globals);
03476 
03477   elf_num_locals (abfd) = num_locals;
03478   elf_num_globals (abfd) = num_globals;
03479   return TRUE;
03480 }
03481 
03482 /* Align to the maximum file alignment that could be required for any
03483    ELF data structure.  */
03484 
03485 static inline file_ptr
03486 align_file_position (file_ptr off, int align)
03487 {
03488   return (off + align - 1) & ~(align - 1);
03489 }
03490 
03491 /* Assign a file position to a section, optionally aligning to the
03492    required section alignment.  */
03493 
03494 file_ptr
03495 _bfd_elf_assign_file_position_for_section (Elf_Internal_Shdr *i_shdrp,
03496                                       file_ptr offset,
03497                                       bfd_boolean align)
03498 {
03499   if (align)
03500     {
03501       unsigned int al;
03502 
03503       al = i_shdrp->sh_addralign;
03504       if (al > 1)
03505        offset = BFD_ALIGN (offset, al);
03506     }
03507   i_shdrp->sh_offset = offset;
03508   if (i_shdrp->bfd_section != NULL)
03509     i_shdrp->bfd_section->filepos = offset;
03510   if (i_shdrp->sh_type != SHT_NOBITS)
03511     offset += i_shdrp->sh_size;
03512   return offset;
03513 }
03514 
03515 /* Compute the file positions we are going to put the sections at, and
03516    otherwise prepare to begin writing out the ELF file.  If LINK_INFO
03517    is not NULL, this is being called by the ELF backend linker.  */
03518 
03519 bfd_boolean
03520 _bfd_elf_compute_section_file_positions (bfd *abfd,
03521                                     struct bfd_link_info *link_info)
03522 {
03523   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
03524   bfd_boolean failed;
03525   struct bfd_strtab_hash *strtab = NULL;
03526   Elf_Internal_Shdr *shstrtab_hdr;
03527 
03528   if (abfd->output_has_begun)
03529     return TRUE;
03530 
03531   /* Do any elf backend specific processing first.  */
03532   if (bed->elf_backend_begin_write_processing)
03533     (*bed->elf_backend_begin_write_processing) (abfd, link_info);
03534 
03535   if (! prep_headers (abfd))
03536     return FALSE;
03537 
03538   /* Post process the headers if necessary.  */
03539   if (bed->elf_backend_post_process_headers)
03540     (*bed->elf_backend_post_process_headers) (abfd, link_info);
03541 
03542   failed = FALSE;
03543   bfd_map_over_sections (abfd, elf_fake_sections, &failed);
03544   if (failed)
03545     return FALSE;
03546 
03547   if (!assign_section_numbers (abfd, link_info))
03548     return FALSE;
03549 
03550   /* The backend linker builds symbol table information itself.  */
03551   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
03552     {
03553       /* Non-zero if doing a relocatable link.  */
03554       int relocatable_p = ! (abfd->flags & (EXEC_P | DYNAMIC));
03555 
03556       if (! swap_out_syms (abfd, &strtab, relocatable_p))
03557        return FALSE;
03558     }
03559 
03560   if (link_info == NULL)
03561     {
03562       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
03563       if (failed)
03564        return FALSE;
03565     }
03566 
03567   shstrtab_hdr = &elf_tdata (abfd)->shstrtab_hdr;
03568   /* sh_name was set in prep_headers.  */
03569   shstrtab_hdr->sh_type = SHT_STRTAB;
03570   shstrtab_hdr->sh_flags = 0;
03571   shstrtab_hdr->sh_addr = 0;
03572   shstrtab_hdr->sh_size = _bfd_elf_strtab_size (elf_shstrtab (abfd));
03573   shstrtab_hdr->sh_entsize = 0;
03574   shstrtab_hdr->sh_link = 0;
03575   shstrtab_hdr->sh_info = 0;
03576   /* sh_offset is set in assign_file_positions_except_relocs.  */
03577   shstrtab_hdr->sh_addralign = 1;
03578 
03579   if (!assign_file_positions_except_relocs (abfd, link_info))
03580     return FALSE;
03581 
03582   if (link_info == NULL && bfd_get_symcount (abfd) > 0)
03583     {
03584       file_ptr off;
03585       Elf_Internal_Shdr *hdr;
03586 
03587       off = elf_tdata (abfd)->next_file_pos;
03588 
03589       hdr = &elf_tdata (abfd)->symtab_hdr;
03590       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
03591 
03592       hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
03593       if (hdr->sh_size != 0)
03594        off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
03595 
03596       hdr = &elf_tdata (abfd)->strtab_hdr;
03597       off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
03598 
03599       elf_tdata (abfd)->next_file_pos = off;
03600 
03601       /* Now that we know where the .strtab section goes, write it
03602          out.  */
03603       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
03604          || ! _bfd_stringtab_emit (abfd, strtab))
03605        return FALSE;
03606       _bfd_stringtab_free (strtab);
03607     }
03608 
03609   abfd->output_has_begun = TRUE;
03610 
03611   return TRUE;
03612 }
03613 
03614 /* Make an initial estimate of the size of the program header.  If we
03615    get the number wrong here, we'll redo section placement.  */
03616 
03617 static bfd_size_type
03618 get_program_header_size (bfd *abfd, struct bfd_link_info *info)
03619 {
03620   size_t segs;
03621   asection *s;
03622   const struct elf_backend_data *bed;
03623 
03624   /* Assume we will need exactly two PT_LOAD segments: one for text
03625      and one for data.  */
03626   segs = 2;
03627 
03628   s = bfd_get_section_by_name (abfd, ".interp");
03629   if (s != NULL && (s->flags & SEC_LOAD) != 0)
03630     {
03631       /* If we have a loadable interpreter section, we need a
03632         PT_INTERP segment.  In this case, assume we also need a
03633         PT_PHDR segment, although that may not be true for all
03634         targets.  */
03635       segs += 2;
03636     }
03637 
03638   if (bfd_get_section_by_name (abfd, ".dynamic") != NULL)
03639     {
03640       /* We need a PT_DYNAMIC segment.  */
03641       ++segs;
03642       
03643       if (elf_tdata (abfd)->relro)
03644        {
03645          /* We need a PT_GNU_RELRO segment only when there is a
03646             PT_DYNAMIC segment.  */
03647          ++segs;
03648        }
03649     }
03650 
03651   if (elf_tdata (abfd)->eh_frame_hdr)
03652     {
03653       /* We need a PT_GNU_EH_FRAME segment.  */
03654       ++segs;
03655     }
03656 
03657   if (elf_tdata (abfd)->stack_flags)
03658     {
03659       /* We need a PT_GNU_STACK segment.  */
03660       ++segs;
03661     }
03662 
03663   for (s = abfd->sections; s != NULL; s = s->next)
03664     {
03665       if ((s->flags & SEC_LOAD) != 0
03666          && CONST_STRNEQ (s->name, ".note"))
03667        {
03668          /* We need a PT_NOTE segment.  */
03669          ++segs;
03670        }
03671     }
03672 
03673   for (s = abfd->sections; s != NULL; s = s->next)
03674     {
03675       if (s->flags & SEC_THREAD_LOCAL)
03676        {
03677          /* We need a PT_TLS segment.  */
03678          ++segs;
03679          break;
03680        }
03681     }
03682 
03683   /* Let the backend count up any program headers it might need.  */
03684   bed = get_elf_backend_data (abfd);
03685   if (bed->elf_backend_additional_program_headers)
03686     {
03687       int a;
03688 
03689       a = (*bed->elf_backend_additional_program_headers) (abfd, info);
03690       if (a == -1)
03691        abort ();
03692       segs += a;
03693     }
03694 
03695   return segs * bed->s->sizeof_phdr;
03696 }
03697 
03698 /* Create a mapping from a set of sections to a program segment.  */
03699 
03700 static struct elf_segment_map *
03701 make_mapping (bfd *abfd,
03702              asection **sections,
03703              unsigned int from,
03704              unsigned int to,
03705              bfd_boolean phdr)
03706 {
03707   struct elf_segment_map *m;
03708   unsigned int i;
03709   asection **hdrpp;
03710   bfd_size_type amt;
03711 
03712   amt = sizeof (struct elf_segment_map);
03713   amt += (to - from - 1) * sizeof (asection *);
03714   m = bfd_zalloc (abfd, amt);
03715   if (m == NULL)
03716     return NULL;
03717   m->next = NULL;
03718   m->p_type = PT_LOAD;
03719   for (i = from, hdrpp = sections + from; i < to; i++, hdrpp++)
03720     m->sections[i - from] = *hdrpp;
03721   m->count = to - from;
03722 
03723   if (from == 0 && phdr)
03724     {
03725       /* Include the headers in the first PT_LOAD segment.  */
03726       m->includes_filehdr = 1;
03727       m->includes_phdrs = 1;
03728     }
03729 
03730   return m;
03731 }
03732 
03733 /* Create the PT_DYNAMIC segment, which includes DYNSEC.  Returns NULL
03734    on failure.  */
03735 
03736 struct elf_segment_map *
03737 _bfd_elf_make_dynamic_segment (bfd *abfd, asection *dynsec)
03738 {
03739   struct elf_segment_map *m;
03740 
03741   m = bfd_zalloc (abfd, sizeof (struct elf_segment_map));
03742   if (m == NULL)
03743     return NULL;
03744   m->next = NULL;
03745   m->p_type = PT_DYNAMIC;
03746   m->count = 1;
03747   m->sections[0] = dynsec;
03748   
03749   return m;
03750 }
03751 
03752 /* Possibly add or remove segments from the segment map.  */
03753 
03754 static bfd_boolean
03755 elf_modify_segment_map (bfd *abfd, struct bfd_link_info *info)
03756 {
03757   struct elf_segment_map **m;
03758   const struct elf_backend_data *bed;
03759 
03760   /* The placement algorithm assumes that non allocated sections are
03761      not in PT_LOAD segments.  We ensure this here by removing such
03762      sections from the segment map.  We also remove excluded
03763      sections.  Finally, any PT_LOAD segment without sections is
03764      removed.  */
03765   m = &elf_tdata (abfd)->segment_map;
03766   while (*m)
03767     {
03768       unsigned int i, new_count;
03769 
03770       for (new_count = 0, i = 0; i < (*m)->count; i++)
03771        {
03772          if (((*m)->sections[i]->flags & SEC_EXCLUDE) == 0
03773              && (((*m)->sections[i]->flags & SEC_ALLOC) != 0
03774                 || (*m)->p_type != PT_LOAD))
03775            {
03776              (*m)->sections[new_count] = (*m)->sections[i];
03777              new_count++;
03778            }
03779        }
03780       (*m)->count = new_count;
03781 
03782       if ((*m)->p_type == PT_LOAD && (*m)->count == 0)
03783        *m = (*m)->next;
03784       else
03785        m = &(*m)->next;
03786     }
03787 
03788   bed = get_elf_backend_data (abfd);
03789   if (bed->elf_backend_modify_segment_map != NULL)
03790     {
03791       if (!(*bed->elf_backend_modify_segment_map) (abfd, info))
03792        return FALSE;
03793     }
03794 
03795   return TRUE;
03796 }
03797 
03798 /* Set up a mapping from BFD sections to program segments.  */
03799 
03800 bfd_boolean
03801 _bfd_elf_map_sections_to_segments (bfd *abfd, struct bfd_link_info *info)
03802 {
03803   unsigned int count;
03804   struct elf_segment_map *m;
03805   asection **sections = NULL;
03806   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
03807 
03808   if (elf_tdata (abfd)->segment_map == NULL
03809       && bfd_count_sections (abfd) != 0)
03810     {
03811       asection *s;
03812       unsigned int i;
03813       struct elf_segment_map *mfirst;
03814       struct elf_segment_map **pm;
03815       asection *last_hdr;
03816       bfd_vma last_size;
03817       unsigned int phdr_index;
03818       bfd_vma maxpagesize;
03819       asection **hdrpp;
03820       bfd_boolean phdr_in_segment = TRUE;
03821       bfd_boolean writable;
03822       int tls_count = 0;
03823       asection *first_tls = NULL;
03824       asection *dynsec, *eh_frame_hdr;
03825       bfd_size_type amt;
03826 
03827       /* Select the allocated sections, and sort them.  */
03828 
03829       sections = bfd_malloc2 (bfd_count_sections (abfd), sizeof (asection *));
03830       if (sections == NULL)
03831        goto error_return;
03832 
03833       i = 0;
03834       for (s = abfd->sections; s != NULL; s = s->next)
03835        {
03836          if ((s->flags & SEC_ALLOC) != 0)
03837            {
03838              sections[i] = s;
03839              ++i;
03840            }
03841        }
03842       BFD_ASSERT (i <= bfd_count_sections (abfd));
03843       count = i;
03844 
03845       qsort (sections, (size_t) count, sizeof (asection *), elf_sort_sections);
03846 
03847       /* Build the mapping.  */
03848 
03849       mfirst = NULL;
03850       pm = &mfirst;
03851 
03852       /* If we have a .interp section, then create a PT_PHDR segment for
03853         the program headers and a PT_INTERP segment for the .interp
03854         section.  */
03855       s = bfd_get_section_by_name (abfd, ".interp");
03856       if (s != NULL && (s->flags & SEC_LOAD) != 0)
03857        {
03858          amt = sizeof (struct elf_segment_map);
03859          m = bfd_zalloc (abfd, amt);
03860          if (m == NULL)
03861            goto error_return;
03862          m->next = NULL;
03863          m->p_type = PT_PHDR;
03864          /* FIXME: UnixWare and Solaris set PF_X, Irix 5 does not.  */
03865          m->p_flags = PF_R | PF_X;
03866          m->p_flags_valid = 1;
03867          m->includes_phdrs = 1;
03868 
03869          *pm = m;
03870          pm = &m->next;
03871 
03872          amt = sizeof (struct elf_segment_map);
03873          m = bfd_zalloc (abfd, amt);
03874          if (m == NULL)
03875            goto error_return;
03876          m->next = NULL;
03877          m->p_type = PT_INTERP;
03878          m->count = 1;
03879          m->sections[0] = s;
03880 
03881          *pm = m;
03882          pm = &m->next;
03883        }
03884 
03885       /* Look through the sections.  We put sections in the same program
03886         segment when the start of the second section can be placed within
03887         a few bytes of the end of the first section.  */
03888       last_hdr = NULL;
03889       last_size = 0;
03890       phdr_index = 0;
03891       maxpagesize = bed->maxpagesize;
03892       writable = FALSE;
03893       dynsec = bfd_get_section_by_name (abfd, ".dynamic");
03894       if (dynsec != NULL
03895          && (dynsec->flags & SEC_LOAD) == 0)
03896        dynsec = NULL;
03897 
03898       /* Deal with -Ttext or something similar such that the first section
03899         is not adjacent to the program headers.  This is an
03900         approximation, since at this point we don't know exactly how many
03901         program headers we will need.  */
03902       if (count > 0)
03903        {
03904          bfd_size_type phdr_size = elf_tdata (abfd)->program_header_size;
03905 
03906          if (phdr_size == (bfd_size_type) -1)
03907            phdr_size = get_program_header_size (abfd, info);
03908          if ((abfd->flags & D_PAGED) == 0
03909              || sections[0]->lma < phdr_size
03910              || sections[0]->lma % maxpagesize < phdr_size % maxpagesize)
03911            phdr_in_segment = FALSE;
03912        }
03913 
03914       for (i = 0, hdrpp = sections; i < count; i++, hdrpp++)
03915        {
03916          asection *hdr;
03917          bfd_boolean new_segment;
03918 
03919          hdr = *hdrpp;
03920 
03921          /* See if this section and the last one will fit in the same
03922             segment.  */
03923 
03924          if (last_hdr == NULL)
03925            {
03926              /* If we don't have a segment yet, then we don't need a new
03927                one (we build the last one after this loop).  */
03928              new_segment = FALSE;
03929            }
03930          else if (last_hdr->lma - last_hdr->vma != hdr->lma - hdr->vma)
03931            {
03932              /* If this section has a different relation between the
03933                virtual address and the load address, then we need a new
03934                segment.  */
03935              new_segment = TRUE;
03936            }
03937          else if (BFD_ALIGN (last_hdr->lma + last_size, maxpagesize)
03938                  < BFD_ALIGN (hdr->lma, maxpagesize))
03939            {
03940              /* If putting this section in this segment would force us to
03941                skip a page in the segment, then we need a new segment.  */
03942              new_segment = TRUE;
03943            }
03944          else if ((last_hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0
03945                  && (hdr->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) != 0)
03946            {
03947              /* We don't want to put a loadable section after a
03948                nonloadable section in the same segment.
03949                Consider .tbss sections as loadable for this purpose.  */
03950              new_segment = TRUE;
03951            }
03952          else if ((abfd->flags & D_PAGED) == 0)
03953            {
03954              /* If the file is not demand paged, which means that we
03955                don't require the sections to be correctly aligned in the
03956                file, then there is no other reason for a new segment.  */
03957              new_segment = FALSE;
03958            }
03959          else if (! writable
03960                  && (hdr->flags & SEC_READONLY) == 0
03961                  && (((last_hdr->lma + last_size - 1)
03962                      & ~(maxpagesize - 1))
03963                      != (hdr->lma & ~(maxpagesize - 1))))
03964            {
03965              /* We don't want to put a writable section in a read only
03966                segment, unless they are on the same page in memory
03967                anyhow.  We already know that the last section does not
03968                bring us past the current section on the page, so the
03969                only case in which the new section is not on the same
03970                page as the previous section is when the previous section
03971                ends precisely on a page boundary.  */
03972              new_segment = TRUE;
03973            }
03974          else
03975            {
03976              /* Otherwise, we can use the same segment.  */
03977              new_segment = FALSE;
03978            }
03979 
03980          /* Allow interested parties a chance to override our decision.  */
03981          if (last_hdr && info->callbacks->override_segment_assignment)
03982            new_segment = info->callbacks->override_segment_assignment (info, abfd, hdr, last_hdr, new_segment);
03983 
03984          if (! new_segment)
03985            {
03986              if ((hdr->flags & SEC_READONLY) == 0)
03987               writable = TRUE;
03988              last_hdr = hdr;
03989              /* .tbss sections effectively have zero size.  */
03990              if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD))
03991                 != SEC_THREAD_LOCAL)
03992               last_size = hdr->size;
03993              else
03994               last_size = 0;
03995              continue;
03996            }
03997 
03998          /* We need a new program segment.  We must create a new program
03999             header holding all the sections from phdr_index until hdr.  */
04000 
04001          m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
04002          if (m == NULL)
04003            goto error_return;
04004 
04005          *pm = m;
04006          pm = &m->next;
04007 
04008          if ((hdr->flags & SEC_READONLY) == 0)
04009            writable = TRUE;
04010          else
04011            writable = FALSE;
04012 
04013          last_hdr = hdr;
04014          /* .tbss sections effectively have zero size.  */
04015          if ((hdr->flags & (SEC_THREAD_LOCAL | SEC_LOAD)) != SEC_THREAD_LOCAL)
04016            last_size = hdr->size;
04017          else
04018            last_size = 0;
04019          phdr_index = i;
04020          phdr_in_segment = FALSE;
04021        }
04022 
04023       /* Create a final PT_LOAD program segment.  */
04024       if (last_hdr != NULL)
04025        {
04026          m = make_mapping (abfd, sections, phdr_index, i, phdr_in_segment);
04027          if (m == NULL)
04028            goto error_return;
04029 
04030          *pm = m;
04031          pm = &m->next;
04032        }
04033 
04034       /* If there is a .dynamic section, throw in a PT_DYNAMIC segment.  */
04035       if (dynsec != NULL)
04036        {
04037          m = _bfd_elf_make_dynamic_segment (abfd, dynsec);
04038          if (m == NULL)
04039            goto error_return;
04040          *pm = m;
04041          pm = &m->next;
04042        }
04043 
04044       /* For each loadable .note section, add a PT_NOTE segment.  We don't
04045         use bfd_get_section_by_name, because if we link together
04046         nonloadable .note sections and loadable .note sections, we will
04047         generate two .note sections in the output file.  FIXME: Using
04048         names for section types is bogus anyhow.  */
04049       for (s = abfd->sections; s != NULL; s = s->next)
04050        {
04051          if ((s->flags & SEC_LOAD) != 0
04052              && CONST_STRNEQ (s->name, ".note"))
04053            {
04054              amt = sizeof (struct elf_segment_map);
04055              m = bfd_zalloc (abfd, amt);
04056              if (m == NULL)
04057               goto error_return;
04058              m->next = NULL;
04059              m->p_type = PT_NOTE;
04060              m->count = 1;
04061              m->sections[0] = s;
04062 
04063              *pm = m;
04064              pm = &m->next;
04065            }
04066          if (s->flags & SEC_THREAD_LOCAL)
04067            {
04068              if (! tls_count)
04069               first_tls = s;
04070              tls_count++;
04071            }
04072        }
04073 
04074       /* If there are any SHF_TLS output sections, add PT_TLS segment.  */
04075       if (tls_count > 0)
04076        {
04077          int i;
04078 
04079          amt = sizeof (struct elf_segment_map);
04080          amt += (tls_count - 1) * sizeof (asection *);
04081          m = bfd_zalloc (abfd, amt);
04082          if (m == NULL)
04083            goto error_return;
04084          m->next = NULL;
04085          m->p_type = PT_TLS;
04086          m->count = tls_count;
04087          /* Mandated PF_R.  */
04088          m->p_flags = PF_R;
04089          m->p_flags_valid = 1;
04090          for (i = 0; i < tls_count; ++i)
04091            {
04092              BFD_ASSERT (first_tls->flags & SEC_THREAD_LOCAL);
04093              m->sections[i] = first_tls;
04094              first_tls = first_tls->next;
04095            }
04096 
04097          *pm = m;
04098          pm = &m->next;
04099        }
04100 
04101       /* If there is a .eh_frame_hdr section, throw in a PT_GNU_EH_FRAME
04102         segment.  */
04103       eh_frame_hdr = elf_tdata (abfd)->eh_frame_hdr;
04104       if (eh_frame_hdr != NULL
04105          && (eh_frame_hdr->output_section->flags & SEC_LOAD) != 0)
04106        {
04107          amt = sizeof (struct elf_segment_map);
04108          m = bfd_zalloc (abfd, amt);
04109          if (m == NULL)
04110            goto error_return;
04111          m->next = NULL;
04112          m->p_type = PT_GNU_EH_FRAME;
04113          m->count = 1;
04114          m->sections[0] = eh_frame_hdr->output_section;
04115 
04116          *pm = m;
04117          pm = &m->next;
04118        }
04119 
04120       if (elf_tdata (abfd)->stack_flags)
04121        {
04122          amt = sizeof (struct elf_segment_map);
04123          m = bfd_zalloc (abfd, amt);
04124          if (m == NULL)
04125            goto error_return;
04126          m->next = NULL;
04127          m->p_type = PT_GNU_STACK;
04128          m->p_flags = elf_tdata (abfd)->stack_flags;
04129          m->p_flags_valid = 1;
04130 
04131          *pm = m;
04132          pm = &m->next;
04133        }
04134 
04135       if (dynsec != NULL && elf_tdata (abfd)->relro)
04136        {
04137          /* We make a PT_GNU_RELRO segment only when there is a
04138             PT_DYNAMIC segment.  */
04139          amt = sizeof (struct elf_segment_map);
04140          m = bfd_zalloc (abfd, amt);
04141          if (m == NULL)
04142            goto error_return;
04143          m->next = NULL;
04144          m->p_type = PT_GNU_RELRO;
04145          m->p_flags = PF_R;
04146          m->p_flags_valid = 1;
04147 
04148          *pm = m;
04149          pm = &m->next;
04150        }
04151 
04152       free (sections);
04153       elf_tdata (abfd)->segment_map = mfirst;
04154     }
04155 
04156   if (!elf_modify_segment_map (abfd, info))
04157     return FALSE;
04158 
04159   for (count = 0, m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
04160     ++count;
04161   elf_tdata (abfd)->program_header_size = count * bed->s->sizeof_phdr;
04162 
04163   return TRUE;
04164 
04165  error_return:
04166   if (sections != NULL)
04167     free (sections);
04168   return FALSE;
04169 }
04170 
04171 /* Sort sections by address.  */
04172 
04173 static int
04174 elf_sort_sections (const void *arg1, const void *arg2)
04175 {
04176   const asection *sec1 = *(const asection **) arg1;
04177   const asection *sec2 = *(const asection **) arg2;
04178   bfd_size_type size1, size2;
04179 
04180   /* Sort by LMA first, since this is the address used to
04181      place the section into a segment.  */
04182   if (sec1->lma < sec2->lma)
04183     return -1;
04184   else if (sec1->lma > sec2->lma)
04185     return 1;
04186 
04187   /* Then sort by VMA.  Normally the LMA and the VMA will be
04188      the same, and this will do nothing.  */
04189   if (sec1->vma < sec2->vma)
04190     return -1;
04191   else if (sec1->vma > sec2->vma)
04192     return 1;
04193 
04194   /* Put !SEC_LOAD sections after SEC_LOAD ones.  */
04195 
04196 #define TOEND(x) (((x)->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == 0)
04197 
04198   if (TOEND (sec1))
04199     {
04200       if (TOEND (sec2))
04201        {
04202          /* If the indicies are the same, do not return 0
04203             here, but continue to try the next comparison.  */
04204          if (sec1->target_index - sec2->target_index != 0)
04205            return sec1->target_index - sec2->target_index;
04206        }
04207       else
04208        return 1;
04209     }
04210   else if (TOEND (sec2))
04211     return -1;
04212 
04213 #undef TOEND
04214 
04215   /* Sort by size, to put zero sized sections
04216      before others at the same address.  */
04217 
04218   size1 = (sec1->flags & SEC_LOAD) ? sec1->size : 0;
04219   size2 = (sec2->flags & SEC_LOAD) ? sec2->size : 0;
04220 
04221   if (size1 < size2)
04222     return -1;
04223   if (size1 > size2)
04224     return 1;
04225 
04226   return sec1->target_index - sec2->target_index;
04227 }
04228 
04229 /* Ian Lance Taylor writes:
04230 
04231    We shouldn't be using % with a negative signed number.  That's just
04232    not good.  We have to make sure either that the number is not
04233    negative, or that the number has an unsigned type.  When the types
04234    are all the same size they wind up as unsigned.  When file_ptr is a
04235    larger signed type, the arithmetic winds up as signed long long,
04236    which is wrong.
04237 
04238    What we're trying to say here is something like ``increase OFF by
04239    the least amount that will cause it to be equal to the VMA modulo
04240    the page size.''  */
04241 /* In other words, something like:
04242 
04243    vma_offset = m->sections[0]->vma % bed->maxpagesize;
04244    off_offset = off % bed->maxpagesize;
04245    if (vma_offset < off_offset)
04246      adjustment = vma_offset + bed->maxpagesize - off_offset;
04247    else
04248      adjustment = vma_offset - off_offset;
04249      
04250    which can can be collapsed into the expression below.  */
04251 
04252 static file_ptr
04253 vma_page_aligned_bias (bfd_vma vma, ufile_ptr off, bfd_vma maxpagesize)
04254 {
04255   return ((vma - off) % maxpagesize);
04256 }
04257 
04258 /* Assign file positions to the sections based on the mapping from
04259    sections to segments.  This function also sets up some fields in
04260    the file header.  */
04261 
04262 static bfd_boolean
04263 assign_file_positions_for_load_sections (bfd *abfd,
04264                                     struct bfd_link_info *link_info)
04265 {
04266   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
04267   struct elf_segment_map *m;
04268   Elf_Internal_Phdr *phdrs;
04269   Elf_Internal_Phdr *p;
04270   file_ptr off, voff;
04271   bfd_size_type maxpagesize;
04272   unsigned int alloc;
04273   unsigned int i, j;
04274 
04275   if (link_info == NULL
04276       && !elf_modify_segment_map (abfd, link_info))
04277     return FALSE;
04278 
04279   alloc = 0;
04280   for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
04281     ++alloc;
04282 
04283   elf_elfheader (abfd)->e_phoff = bed->s->sizeof_ehdr;
04284   elf_elfheader (abfd)->e_phentsize = bed->s->sizeof_phdr;
04285   elf_elfheader (abfd)->e_phnum = alloc;
04286 
04287   if (elf_tdata (abfd)->program_header_size == (bfd_size_type) -1)
04288     elf_tdata (abfd)->program_header_size = alloc * bed->s->sizeof_phdr;
04289   else
04290     BFD_ASSERT (elf_tdata (abfd)->program_header_size
04291               >= alloc * bed->s->sizeof_phdr);
04292 
04293   if (alloc == 0)
04294     {
04295       elf_tdata (abfd)->next_file_pos = bed->s->sizeof_ehdr;
04296       return TRUE;
04297     }
04298 
04299   phdrs = bfd_alloc2 (abfd, alloc, sizeof (Elf_Internal_Phdr));
04300   elf_tdata (abfd)->phdr = phdrs;
04301   if (phdrs == NULL)
04302     return FALSE;
04303 
04304   maxpagesize = 1;
04305   if ((abfd->flags & D_PAGED) != 0)
04306     maxpagesize = bed->maxpagesize;
04307 
04308   off = bed->s->sizeof_ehdr;
04309   off += alloc * bed->s->sizeof_phdr;
04310 
04311   for (m = elf_tdata (abfd)->segment_map, p = phdrs, j = 0;
04312        m != NULL;
04313        m = m->next, p++, j++)
04314     {
04315       asection **secpp;
04316 
04317       /* If elf_segment_map is not from map_sections_to_segments, the
04318          sections may not be correctly ordered.  NOTE: sorting should
04319         not be done to the PT_NOTE section of a corefile, which may
04320         contain several pseudo-sections artificially created by bfd.
04321         Sorting these pseudo-sections breaks things badly.  */
04322       if (m->count > 1
04323          && !(elf_elfheader (abfd)->e_type == ET_CORE
04324               && m->p_type == PT_NOTE))
04325        qsort (m->sections, (size_t) m->count, sizeof (asection *),
04326               elf_sort_sections);
04327 
04328       /* An ELF segment (described by Elf_Internal_Phdr) may contain a
04329         number of sections with contents contributing to both p_filesz
04330         and p_memsz, followed by a number of sections with no contents
04331         that just contribute to p_memsz.  In this loop, OFF tracks next
04332         available file offset for PT_LOAD and PT_NOTE segments.  VOFF is
04333         an adjustment we use for segments that have no file contents
04334         but need zero filled memory allocation.  */
04335       voff = 0;
04336       p->p_type = m->p_type;
04337       p->p_flags = m->p_flags;
04338 
04339       if (m->count == 0)
04340        p->p_vaddr = 0;
04341       else
04342        p->p_vaddr = m->sections[0]->vma - m->p_vaddr_offset;
04343 
04344       if (m->p_paddr_valid)
04345        p->p_paddr = m->p_paddr;
04346       else if (m->count == 0)
04347        p->p_paddr = 0;
04348       else
04349        p->p_paddr = m->sections[0]->lma;
04350 
04351       if (p->p_type == PT_LOAD
04352          && (abfd->flags & D_PAGED) != 0)
04353        {
04354          /* p_align in demand paged PT_LOAD segments effectively stores
04355             the maximum page size.  When copying an executable with
04356             objcopy, we set m->p_align from the input file.  Use this
04357             value for maxpagesize rather than bed->maxpagesize, which
04358             may be different.  Note that we use maxpagesize for PT_TLS
04359             segment alignment later in this function, so we are relying
04360             on at least one PT_LOAD segment appearing before a PT_TLS
04361             segment.  */
04362          if (m->p_align_valid)
04363            maxpagesize = m->p_align;
04364 
04365          p->p_align = maxpagesize;
04366        }
04367       else if (m->count == 0)
04368        p->p_align = 1 << bed->s->log_file_align;
04369       else if (m->p_align_valid)
04370        p->p_align = m->p_align;
04371       else
04372        p->p_align = 0;
04373 
04374       if (p->p_type == PT_LOAD
04375          && m->count > 0)
04376        {
04377          bfd_size_type align;
04378          bfd_vma adjust;
04379          unsigned int align_power = 0;
04380 
04381          if (m->p_align_valid)
04382            align = p->p_align;
04383          else
04384            {
04385              for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
04386               {
04387                 unsigned int secalign;
04388                 
04389                 secalign = bfd_get_section_alignment (abfd, *secpp);
04390                 if (secalign > align_power)
04391                   align_power = secalign;
04392               }
04393              align = (bfd_size_type) 1 << align_power;
04394              if (align < maxpagesize)
04395               align = maxpagesize;
04396            }
04397 
04398          adjust = vma_page_aligned_bias (m->sections[0]->vma, off, align);
04399          off += adjust;
04400          if (adjust != 0
04401              && !m->includes_filehdr
04402              && !m->includes_phdrs
04403              && (ufile_ptr) off >= align)
04404            {
04405              /* If the first section isn't loadable, the same holds for
04406                any other sections.  Since the segment won't need file
04407                space, we can make p_offset overlap some prior segment.
04408                However, .tbss is special.  If a segment starts with
04409                .tbss, we need to look at the next section to decide
04410                whether the segment has any loadable sections.  */
04411              i = 0;
04412              while ((m->sections[i]->flags & SEC_LOAD) == 0
04413                    && (m->sections[i]->flags & SEC_HAS_CONTENTS) == 0)
04414               {
04415                 if ((m->sections[i]->flags & SEC_THREAD_LOCAL) == 0
04416                     || ++i >= m->count)
04417                   {
04418                     off -= adjust;
04419                     voff = adjust - align;
04420                     break;
04421                   }
04422               }
04423            }
04424        }
04425       /* Make sure the .dynamic section is the first section in the
04426         PT_DYNAMIC segment.  */
04427       else if (p->p_type == PT_DYNAMIC
04428               && m->count > 1
04429               && strcmp (m->sections[0]->name, ".dynamic") != 0)
04430        {
04431          _bfd_error_handler
04432            (_("%B: The first section in the PT_DYNAMIC segment is not the .dynamic section"),
04433             abfd);
04434          bfd_set_error (bfd_error_bad_value);
04435          return FALSE;
04436        }
04437 
04438       p->p_offset = 0;
04439       p->p_filesz = 0;
04440       p->p_memsz = 0;
04441 
04442       if (m->includes_filehdr)
04443        {
04444          if (! m->p_flags_valid)
04445            p->p_flags |= PF_R;
04446          p->p_filesz = bed->s->sizeof_ehdr;
04447          p->p_memsz = bed->s->sizeof_ehdr;
04448          if (m->count > 0)
04449            {
04450              BFD_ASSERT (p->p_type == PT_LOAD);
04451 
04452              if (p->p_vaddr < (bfd_vma) off)
04453               {
04454                 (*_bfd_error_handler)
04455                   (_("%B: Not enough room for program headers, try linking with -N"),
04456                    abfd);
04457                 bfd_set_error (bfd_error_bad_value);
04458                 return FALSE;
04459               }
04460 
04461              p->p_vaddr -= off;
04462              if (! m->p_paddr_valid)
04463               p->p_paddr -= off;
04464            }
04465        }
04466 
04467       if (m->includes_phdrs)
04468        {
04469          if (! m->p_flags_valid)
04470            p->p_flags |= PF_R;
04471 
04472          if (!m->includes_filehdr)
04473            {
04474              p->p_offset = bed->s->sizeof_ehdr;
04475 
04476              if (m->count > 0)
04477               {
04478                 BFD_ASSERT (p->p_type == PT_LOAD);
04479                 p->p_vaddr -= off - p->p_offset;
04480                 if (! m->p_paddr_valid)
04481                   p->p_paddr -= off - p->p_offset;
04482               }
04483            }
04484 
04485          p->p_filesz += alloc * bed->s->sizeof_phdr;
04486          p->p_memsz += alloc * bed->s->sizeof_phdr;
04487        }
04488 
04489       if (p->p_type == PT_LOAD
04490          || (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core))
04491        {
04492          if (! m->includes_filehdr && ! m->includes_phdrs)
04493            p->p_offset = off + voff;
04494          else
04495            {
04496              file_ptr adjust;
04497 
04498              adjust = off - (p->p_offset + p->p_filesz);
04499              p->p_filesz += adjust;
04500              p->p_memsz += adjust;
04501            }
04502        }
04503 
04504       /* Set up p_filesz, p_memsz, p_align and p_flags from the section
04505         maps.  Set filepos for sections in PT_LOAD segments, and in
04506         core files, for sections in PT_NOTE segments.
04507         assign_file_positions_for_non_load_sections will set filepos
04508         for other sections and update p_filesz for other segments.  */
04509       for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
04510        {
04511          asection *sec;
04512          flagword flags;
04513          bfd_size_type align;
04514 
04515          sec = *secpp;
04516          flags = sec->flags;
04517          align = (bfd_size_type) 1 << bfd_get_section_alignment (abfd, sec);
04518 
04519          if (p->p_type == PT_LOAD
04520              || p->p_type == PT_TLS)
04521            {
04522              bfd_signed_vma adjust = sec->lma - (p->p_paddr + p->p_filesz);
04523 
04524              if ((flags & SEC_LOAD) != 0
04525                 || ((flags & SEC_ALLOC) != 0
04526                     && ((flags & SEC_THREAD_LOCAL) == 0
04527                        || p->p_type == PT_TLS)))
04528               {
04529                 if (adjust < 0)
04530                   {
04531                     (*_bfd_error_handler)
04532                      (_("%B: section %A lma 0x%lx overlaps previous sections"),
04533                       abfd, sec, (unsigned long) sec->lma);
04534                     adjust = 0;
04535                   }
04536                 p->p_memsz += adjust;
04537 
04538                 if ((flags & SEC_LOAD) != 0)
04539                   {
04540                     off += adjust;
04541                     p->p_filesz += adjust;
04542                   }
04543               }
04544            }
04545 
04546          if (p->p_type == PT_NOTE && bfd_get_format (abfd) == bfd_core)
04547            {
04548              /* The section at i == 0 is the one that actually contains
04549                everything.  */
04550              if (i == 0)
04551               {
04552                 sec->filepos = off;
04553                 off += sec->size;
04554                 p->p_filesz = sec->size;
04555                 p->p_memsz = 0;
04556                 p->p_align = 1;
04557               }
04558              else
04559               {
04560                 /* The rest are fake sections that shouldn't be written.  */
04561                 sec->filepos = 0;
04562                 sec->size = 0;
04563                 sec->flags = 0;
04564                 continue;
04565               }
04566            }
04567          else
04568            {
04569              if (p->p_type == PT_LOAD)
04570               {
04571                 sec->filepos = off + voff;
04572                 /* FIXME: The SEC_HAS_CONTENTS test here dates back to
04573                    1997, and the exact reason for it isn't clear.  One
04574                    plausible explanation is that it is to work around
04575                    a problem we have with linker scripts using data
04576                    statements in NOLOAD sections.  I don't think it
04577                    makes a great deal of sense to have such a section
04578                    assigned to a PT_LOAD segment, but apparently
04579                    people do this.  The data statement results in a
04580                    bfd_data_link_order being built, and these need
04581                    section contents to write into.  Eventually, we get
04582                    to _bfd_elf_write_object_contents which writes any
04583                    section with contents to the output.  Make room
04584                    here for the write, so that following segments are
04585                    not trashed.  */
04586                 if ((flags & SEC_LOAD) != 0
04587                     || (flags & SEC_HAS_CONTENTS) != 0)
04588                   off += sec->size;
04589               }
04590 
04591              if ((flags & SEC_LOAD) != 0)
04592               {
04593                 p->p_filesz += sec->size;
04594                 p->p_memsz += sec->size;
04595               }
04596 
04597              /* .tbss is special.  It doesn't contribute to p_memsz of
04598                normal segments.  */
04599              else if ((flags & SEC_ALLOC) != 0
04600                      && ((flags & SEC_THREAD_LOCAL) == 0
04601                         || p->p_type == PT_TLS))
04602               p->p_memsz += sec->size;
04603 
04604              if (p->p_type == PT_TLS
04605                 && sec->size == 0
04606                 && (sec->flags & SEC_HAS_CONTENTS) == 0)
04607               {
04608                 struct bfd_link_order *o = sec->map_tail.link_order;
04609                 if (o != NULL)
04610                   p->p_memsz += o->offset + o->size;
04611               }
04612 
04613              if (p->p_type == PT_GNU_RELRO)
04614               p->p_align = 1;
04615              else if (align > p->p_align
04616                      && !m->p_align_valid
04617                      && (p->p_type != PT_LOAD
04618                         || (abfd->flags & D_PAGED) == 0))
04619               p->p_align = align;
04620            }
04621 
04622          if (! m->p_flags_valid)
04623            {
04624              p->p_flags |= PF_R;
04625              if ((flags & SEC_CODE) != 0)
04626               p->p_flags |= PF_X;
04627              if ((flags & SEC_READONLY) == 0)
04628               p->p_flags |= PF_W;
04629            }
04630        }
04631 
04632       /* Check if all sections are in the segment.  Skip PT_GNU_RELRO
04633         and PT_NOTE segments since they will be processed by
04634         assign_file_positions_for_non_load_sections later.  */
04635       if (p->p_type != PT_GNU_RELRO
04636          && p->p_type != PT_NOTE)
04637        for (i = 0, secpp = m->sections; i < m->count; i++, secpp++)
04638          {
04639            Elf_Internal_Shdr *this_hdr;
04640            asection *sec;
04641 
04642            sec = *secpp;
04643            this_hdr = &(elf_section_data(sec)->this_hdr);
04644            if (this_hdr->sh_size != 0
04645               && !ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, p))
04646              {
04647               (*_bfd_error_handler)
04648                 (_("%B: section `%A' can't be allocated in segment %d"),
04649                  abfd, sec, j);
04650               bfd_set_error (bfd_error_bad_value);
04651               return FALSE;
04652              }
04653          }
04654     }
04655 
04656   elf_tdata (abfd)->next_file_pos = off;
04657   return TRUE;
04658 }
04659 
04660 /* Assign file positions for the other sections.  */
04661 
04662 static bfd_boolean
04663 assign_file_positions_for_non_load_sections (bfd *abfd,
04664                                         struct bfd_link_info *link_info)
04665 {
04666   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
04667   Elf_Internal_Shdr **i_shdrpp;
04668   Elf_Internal_Shdr **hdrpp;
04669   Elf_Internal_Phdr *phdrs;
04670   Elf_Internal_Phdr *p;
04671   struct elf_segment_map *m;
04672   bfd_vma filehdr_vaddr, filehdr_paddr;
04673   bfd_vma phdrs_vaddr, phdrs_paddr;
04674   file_ptr off;
04675   unsigned int num_sec;
04676   unsigned int i;
04677   unsigned int count;
04678 
04679   i_shdrpp = elf_elfsections (abfd);
04680   num_sec = elf_numsections (abfd);
04681   off = elf_tdata (abfd)->next_file_pos;
04682   for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
04683     {
04684       struct elf_obj_tdata *tdata = elf_tdata (abfd);
04685       Elf_Internal_Shdr *hdr;
04686 
04687       hdr = *hdrpp;
04688       if (hdr->bfd_section != NULL
04689          && (hdr->bfd_section->filepos != 0
04690              || (hdr->sh_type == SHT_NOBITS
04691                 && hdr->contents == NULL)))
04692        hdr->sh_offset = hdr->bfd_section->filepos;
04693       else if ((hdr->sh_flags & SHF_ALLOC) != 0)
04694        {
04695          if (hdr->sh_size != 0)
04696            ((*_bfd_error_handler)
04697             (_("%B: warning: allocated section `%s' not in segment"),
04698              abfd,
04699              (hdr->bfd_section == NULL
04700               ? "*unknown*"
04701               : hdr->bfd_section->name)));
04702          /* We don't need to page align empty sections.  */
04703          if ((abfd->flags & D_PAGED) != 0 && hdr->sh_size != 0)
04704            off += vma_page_aligned_bias (hdr->sh_addr, off,
04705                                      bed->maxpagesize);
04706          else
04707            off += vma_page_aligned_bias (hdr->sh_addr, off,
04708                                      hdr->sh_addralign);
04709          off = _bfd_elf_assign_file_position_for_section (hdr, off,
04710                                                     FALSE);
04711        }
04712       else if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
04713               && hdr->bfd_section == NULL)
04714               || hdr == i_shdrpp[tdata->symtab_section]
04715               || hdr == i_shdrpp[tdata->symtab_shndx_section]
04716               || hdr == i_shdrpp[tdata->strtab_section])
04717        hdr->sh_offset = -1;
04718       else
04719        off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
04720 
04721       if (i == SHN_LORESERVE - 1)
04722        {
04723          i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
04724          hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
04725        }
04726     }
04727 
04728   /* Now that we have set the section file positions, we can set up
04729      the file positions for the non PT_LOAD segments.  */
04730   count = 0;
04731   filehdr_vaddr = 0;
04732   filehdr_paddr = 0;
04733   phdrs_vaddr = bed->maxpagesize + bed->s->sizeof_ehdr;
04734   phdrs_paddr = 0;
04735   phdrs = elf_tdata (abfd)->phdr;
04736   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
04737        m != NULL;
04738        m = m->next, p++)
04739     {
04740       ++count;
04741       if (p->p_type != PT_LOAD)
04742        continue;
04743 
04744       if (m->includes_filehdr)
04745        {
04746          filehdr_vaddr = p->p_vaddr;
04747          filehdr_paddr = p->p_paddr;
04748        }
04749       if (m->includes_phdrs)
04750        {
04751          phdrs_vaddr = p->p_vaddr;
04752          phdrs_paddr = p->p_paddr;
04753          if (m->includes_filehdr)
04754            {
04755              phdrs_vaddr += bed->s->sizeof_ehdr;
04756              phdrs_paddr += bed->s->sizeof_ehdr;
04757            }
04758        }
04759     }
04760 
04761   for (m = elf_tdata (abfd)->segment_map, p = phdrs;
04762        m != NULL;
04763        m = m->next, p++)
04764     {
04765       if (m->count != 0)
04766        {
04767          if (p->p_type != PT_LOAD
04768              && (p->p_type != PT_NOTE || bfd_get_format (abfd) != bfd_core))
04769            {
04770              Elf_Internal_Shdr *hdr;
04771              BFD_ASSERT (!m->includes_filehdr && !m->includes_phdrs);
04772 
04773              hdr = &elf_section_data (m->sections[m->count - 1])->this_hdr;
04774              p->p_filesz = (m->sections[m->count - 1]->filepos
04775                           - m->sections[0]->filepos);
04776              if (hdr->sh_type != SHT_NOBITS)
04777               p->p_filesz += hdr->sh_size;
04778 
04779              p->p_offset = m->sections[0]->filepos;
04780            }
04781        }
04782       else
04783        {
04784          if (m->includes_filehdr)
04785            {
04786              p->p_vaddr = filehdr_vaddr;
04787              if (! m->p_paddr_valid)
04788               p->p_paddr = filehdr_paddr;
04789            }
04790          else if (m->includes_phdrs)
04791            {
04792              p->p_vaddr = phdrs_vaddr;
04793              if (! m->p_paddr_valid)
04794               p->p_paddr = phdrs_paddr;
04795            }
04796          else if (p->p_type == PT_GNU_RELRO)
04797            {
04798              Elf_Internal_Phdr *lp;
04799 
04800              for (lp = phdrs; lp < phdrs + count; ++lp)
04801               {
04802                 if (lp->p_type == PT_LOAD
04803                     && lp->p_vaddr <= link_info->relro_end
04804                     && lp->p_vaddr >= link_info->relro_start
04805                     && (lp->p_vaddr + lp->p_filesz
04806                        >= link_info->relro_end))
04807                   break;
04808               }
04809 
04810              if (lp < phdrs + count
04811                 && link_info->relro_end > lp->p_vaddr)
04812               {
04813                 p->p_vaddr = lp->p_vaddr;
04814                 p->p_paddr = lp->p_paddr;
04815                 p->p_offset = lp->p_offset;
04816                 p->p_filesz = link_info->relro_end - lp->p_vaddr;
04817                 p->p_memsz = p->p_filesz;
04818                 p->p_align = 1;
04819                 p->p_flags = (lp->p_flags & ~PF_W);
04820               }
04821              else
04822               {
04823                 memset (p, 0, sizeof *p);
04824                 p->p_type = PT_NULL;
04825               }
04826            }
04827        }
04828     }
04829 
04830   elf_tdata (abfd)->next_file_pos = off;
04831 
04832   return TRUE;
04833 }
04834 
04835 /* Work out the file positions of all the sections.  This is called by
04836    _bfd_elf_compute_section_file_positions.  All the section sizes and
04837    VMAs must be known before this is called.
04838 
04839    Reloc sections come in two flavours: Those processed specially as
04840    "side-channel" data attached to a section to which they apply, and
04841    those that bfd doesn't process as relocations.  The latter sort are
04842    stored in a normal bfd section by bfd_section_from_shdr.   We don't
04843    consider the former sort here, unless they form part of the loadable
04844    image.  Reloc sections not assigned here will be handled later by
04845    assign_file_positions_for_relocs.
04846 
04847    We also don't set the positions of the .symtab and .strtab here.  */
04848 
04849 static bfd_boolean
04850 assign_file_positions_except_relocs (bfd *abfd,
04851                                  struct bfd_link_info *link_info)
04852 {
04853   struct elf_obj_tdata *tdata = elf_tdata (abfd);
04854   Elf_Internal_Ehdr *i_ehdrp = elf_elfheader (abfd);
04855   file_ptr off;
04856   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
04857 
04858   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
04859       && bfd_get_format (abfd) != bfd_core)
04860     {
04861       Elf_Internal_Shdr ** const i_shdrpp = elf_elfsections (abfd);
04862       unsigned int num_sec = elf_numsections (abfd);
04863       Elf_Internal_Shdr **hdrpp;
04864       unsigned int i;
04865 
04866       /* Start after the ELF header.  */
04867       off = i_ehdrp->e_ehsize;
04868 
04869       /* We are not creating an executable, which means that we are
04870         not creating a program header, and that the actual order of
04871         the sections in the file is unimportant.  */
04872       for (i = 1, hdrpp = i_shdrpp + 1; i < num_sec; i++, hdrpp++)
04873        {
04874          Elf_Internal_Shdr *hdr;
04875 
04876          hdr = *hdrpp;
04877          if (((hdr->sh_type == SHT_REL || hdr->sh_type == SHT_RELA)
04878               && hdr->bfd_section == NULL)
04879              || i == tdata->symtab_section
04880              || i == tdata->symtab_shndx_section
04881              || i == tdata->strtab_section)
04882            {
04883              hdr->sh_offset = -1;
04884            }
04885          else
04886            off = _bfd_elf_assign_file_position_for_section (hdr, off, TRUE);
04887 
04888          if (i == SHN_LORESERVE - 1)
04889            {
04890              i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
04891              hdrpp += SHN_HIRESERVE + 1 - SHN_LORESERVE;
04892            }
04893        }
04894     }
04895   else
04896     {
04897       unsigned int alloc;
04898 
04899       /* Assign file positions for the loaded sections based on the
04900          assignment of sections to segments.  */
04901       if (!assign_file_positions_for_load_sections (abfd, link_info))
04902        return FALSE;
04903 
04904       /* And for non-load sections.  */
04905       if (!assign_file_positions_for_non_load_sections (abfd, link_info))
04906        return FALSE;
04907 
04908       if (bed->elf_backend_modify_program_headers != NULL)
04909        {
04910          if (!(*bed->elf_backend_modify_program_headers) (abfd, link_info))
04911            return FALSE;
04912        }
04913 
04914       /* Write out the program headers.  */
04915       alloc = tdata->program_header_size / bed->s->sizeof_phdr;
04916       if (bfd_seek (abfd, (bfd_signed_vma) bed->s->sizeof_ehdr, SEEK_SET) != 0
04917          || bed->s->write_out_phdrs (abfd, tdata->phdr, alloc) != 0)
04918        return FALSE;
04919 
04920       off = tdata->next_file_pos;
04921     }
04922 
04923   /* Place the section headers.  */
04924   off = align_file_position (off, 1 << bed->s->log_file_align);
04925   i_ehdrp->e_shoff = off;
04926   off += i_ehdrp->e_shnum * i_ehdrp->e_shentsize;
04927 
04928   tdata->next_file_pos = off;
04929 
04930   return TRUE;
04931 }
04932 
04933 static bfd_boolean
04934 prep_headers (bfd *abfd)
04935 {
04936   Elf_Internal_Ehdr *i_ehdrp;      /* Elf file header, internal form */
04937   Elf_Internal_Phdr *i_phdrp = 0; /* Program header table, internal form */
04938   Elf_Internal_Shdr **i_shdrp;     /* Section header table, internal form */
04939   struct elf_strtab_hash *shstrtab;
04940   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
04941 
04942   i_ehdrp = elf_elfheader (abfd);
04943   i_shdrp = elf_elfsections (abfd);
04944 
04945   shstrtab = _bfd_elf_strtab_init ();
04946   if (shstrtab == NULL)
04947     return FALSE;
04948 
04949   elf_shstrtab (abfd) = shstrtab;
04950 
04951   i_ehdrp->e_ident[EI_MAG0] = ELFMAG0;
04952   i_ehdrp->e_ident[EI_MAG1] = ELFMAG1;
04953   i_ehdrp->e_ident[EI_MAG2] = ELFMAG2;
04954   i_ehdrp->e_ident[EI_MAG3] = ELFMAG3;
04955 
04956   i_ehdrp->e_ident[EI_CLASS] = bed->s->elfclass;
04957   i_ehdrp->e_ident[EI_DATA] =
04958     bfd_big_endian (abfd) ? ELFDATA2MSB : ELFDATA2LSB;
04959   i_ehdrp->e_ident[EI_VERSION] = bed->s->ev_current;
04960 
04961   if ((abfd->flags & DYNAMIC) != 0)
04962     i_ehdrp->e_type = ET_DYN;
04963   else if ((abfd->flags & EXEC_P) != 0)
04964     i_ehdrp->e_type = ET_EXEC;
04965   else if (bfd_get_format (abfd) == bfd_core)
04966     i_ehdrp->e_type = ET_CORE;
04967   else
04968     i_ehdrp->e_type = ET_REL;
04969 
04970   switch (bfd_get_arch (abfd))
04971     {
04972     case bfd_arch_unknown:
04973       i_ehdrp->e_machine = EM_NONE;
04974       break;
04975 
04976       /* There used to be a long list of cases here, each one setting
04977         e_machine to the same EM_* macro #defined as ELF_MACHINE_CODE
04978         in the corresponding bfd definition.  To avoid duplication,
04979         the switch was removed.  Machines that need special handling
04980         can generally do it in elf_backend_final_write_processing(),
04981         unless they need the information earlier than the final write.
04982         Such need can generally be supplied by replacing the tests for
04983         e_machine with the conditions used to determine it.  */
04984     default:
04985       i_ehdrp->e_machine = bed->elf_machine_code;
04986     }
04987 
04988   i_ehdrp->e_version = bed->s->ev_current;
04989   i_ehdrp->e_ehsize = bed->s->sizeof_ehdr;
04990 
04991   /* No program header, for now.  */
04992   i_ehdrp->e_phoff = 0;
04993   i_ehdrp->e_phentsize = 0;
04994   i_ehdrp->e_phnum = 0;
04995 
04996   /* Each bfd section is section header entry.  */
04997   i_ehdrp->e_entry = bfd_get_start_address (abfd);
04998   i_ehdrp->e_shentsize = bed->s->sizeof_shdr;
04999 
05000   /* If we're building an executable, we'll need a program header table.  */
05001   if (abfd->flags & EXEC_P)
05002     /* It all happens later.  */
05003     ;
05004   else
05005     {
05006       i_ehdrp->e_phentsize = 0;
05007       i_phdrp = 0;
05008       i_ehdrp->e_phoff = 0;
05009     }
05010 
05011   elf_tdata (abfd)->symtab_hdr.sh_name =
05012     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".symtab", FALSE);
05013   elf_tdata (abfd)->strtab_hdr.sh_name =
05014     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".strtab", FALSE);
05015   elf_tdata (abfd)->shstrtab_hdr.sh_name =
05016     (unsigned int) _bfd_elf_strtab_add (shstrtab, ".shstrtab", FALSE);
05017   if (elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
05018       || elf_tdata (abfd)->symtab_hdr.sh_name == (unsigned int) -1
05019       || elf_tdata (abfd)->shstrtab_hdr.sh_name == (unsigned int) -1)
05020     return FALSE;
05021 
05022   return TRUE;
05023 }
05024 
05025 /* Assign file positions for all the reloc sections which are not part
05026    of the loadable file image.  */
05027 
05028 void
05029 _bfd_elf_assign_file_positions_for_relocs (bfd *abfd)
05030 {
05031   file_ptr off;
05032   unsigned int i, num_sec;
05033   Elf_Internal_Shdr **shdrpp;
05034 
05035   off = elf_tdata (abfd)->next_file_pos;
05036 
05037   num_sec = elf_numsections (abfd);
05038   for (i = 1, shdrpp = elf_elfsections (abfd) + 1; i < num_sec; i++, shdrpp++)
05039     {
05040       Elf_Internal_Shdr *shdrp;
05041 
05042       shdrp = *shdrpp;
05043       if ((shdrp->sh_type == SHT_REL || shdrp->sh_type == SHT_RELA)
05044          && shdrp->sh_offset == -1)
05045        off = _bfd_elf_assign_file_position_for_section (shdrp, off, TRUE);
05046     }
05047 
05048   elf_tdata (abfd)->next_file_pos = off;
05049 }
05050 
05051 bfd_boolean
05052 _bfd_elf_write_object_contents (bfd *abfd)
05053 {
05054   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
05055   Elf_Internal_Ehdr *i_ehdrp;
05056   Elf_Internal_Shdr **i_shdrp;
05057   bfd_boolean failed;
05058   unsigned int count, num_sec;
05059 
05060   if (! abfd->output_has_begun
05061       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
05062     return FALSE;
05063 
05064   i_shdrp = elf_elfsections (abfd);
05065   i_ehdrp = elf_elfheader (abfd);
05066 
05067   failed = FALSE;
05068   bfd_map_over_sections (abfd, bed->s->write_relocs, &failed);
05069   if (failed)
05070     return FALSE;
05071 
05072   _bfd_elf_assign_file_positions_for_relocs (abfd);
05073 
05074   /* After writing the headers, we need to write the sections too...  */
05075   num_sec = elf_numsections (abfd);
05076   for (count = 1; count < num_sec; count++)
05077     {
05078       if (bed->elf_backend_section_processing)
05079        (*bed->elf_backend_section_processing) (abfd, i_shdrp[count]);
05080       if (i_shdrp[count]->contents)
05081        {
05082          bfd_size_type amt = i_shdrp[count]->sh_size;
05083 
05084          if (bfd_seek (abfd, i_shdrp[count]->sh_offset, SEEK_SET) != 0
05085              || bfd_bwrite (i_shdrp[count]->contents, amt, abfd) != amt)
05086            return FALSE;
05087        }
05088       if (count == SHN_LORESERVE - 1)
05089        count += SHN_HIRESERVE + 1 - SHN_LORESERVE;
05090     }
05091 
05092   /* Write out the section header names.  */
05093   if (elf_shstrtab (abfd) != NULL
05094       && (bfd_seek (abfd, elf_tdata (abfd)->shstrtab_hdr.sh_offset, SEEK_SET) != 0
05095           || ! _bfd_elf_strtab_emit (abfd, elf_shstrtab (abfd))))
05096     return FALSE;
05097 
05098   if (bed->elf_backend_final_write_processing)
05099     (*bed->elf_backend_final_write_processing) (abfd,
05100                                           elf_tdata (abfd)->linker);
05101 
05102   return bed->s->write_shdrs_and_ehdr (abfd);
05103 }
05104 
05105 bfd_boolean
05106 _bfd_elf_write_corefile_contents (bfd *abfd)
05107 {
05108   /* Hopefully this can be done just like an object file.  */
05109   return _bfd_elf_write_object_contents (abfd);
05110 }
05111 
05112 /* Given a section, search the header to find them.  */
05113 
05114 int
05115 _bfd_elf_section_from_bfd_section (bfd *abfd, struct bfd_section *asect)
05116 {
05117   const struct elf_backend_data *bed;
05118   int index;
05119 
05120   if (elf_section_data (asect) != NULL
05121       && elf_section_data (asect)->this_idx != 0)
05122     return elf_section_data (asect)->this_idx;
05123 
05124   if (bfd_is_abs_section (asect))
05125     index = SHN_ABS;
05126   else if (bfd_is_com_section (asect))
05127     index = SHN_COMMON;
05128   else if (bfd_is_und_section (asect))
05129     index = SHN_UNDEF;
05130   else
05131     index = -1;
05132 
05133   bed = get_elf_backend_data (abfd);
05134   if (bed->elf_backend_section_from_bfd_section)
05135     {
05136       int retval = index;
05137 
05138       if ((*bed->elf_backend_section_from_bfd_section) (abfd, asect, &retval))
05139        return retval;
05140     }
05141 
05142   if (index == -1)
05143     bfd_set_error (bfd_error_nonrepresentable_section);
05144 
05145   return index;
05146 }
05147 
05148 /* Given a BFD symbol, return the index in the ELF symbol table, or -1
05149    on error.  */
05150 
05151 int
05152 _bfd_elf_symbol_from_bfd_symbol (bfd *abfd, asymbol **asym_ptr_ptr)
05153 {
05154   asymbol *asym_ptr = *asym_ptr_ptr;
05155   int idx;
05156   flagword flags = asym_ptr->flags;
05157 
05158   /* When gas creates relocations against local labels, it creates its
05159      own symbol for the section, but does put the symbol into the
05160      symbol chain, so udata is 0.  When the linker is generating
05161      relocatable output, this section symbol may be for one of the
05162      input sections rather than the output section.  */
05163   if (asym_ptr->udata.i == 0
05164       && (flags & BSF_SECTION_SYM)
05165       && asym_ptr->section)
05166     {
05167       asection *sec;
05168       int indx;
05169 
05170       sec = asym_ptr->section;
05171       if (sec->owner != abfd && sec->output_section != NULL)
05172        sec = sec->output_section;
05173       if (sec->owner == abfd
05174          && (indx = sec->index) < elf_num_section_syms (abfd)
05175          && elf_section_syms (abfd)[indx] != NULL)
05176        asym_ptr->udata.i = elf_section_syms (abfd)[indx]->udata.i;
05177     }
05178 
05179   idx = asym_ptr->udata.i;
05180 
05181   if (idx == 0)
05182     {
05183       /* This case can occur when using --strip-symbol on a symbol
05184          which is used in a relocation entry.  */
05185       (*_bfd_error_handler)
05186        (_("%B: symbol `%s' required but not present"),
05187         abfd, bfd_asymbol_name (asym_ptr));
05188       bfd_set_error (bfd_error_no_symbols);
05189       return -1;
05190     }
05191 
05192 #if DEBUG & 4
05193   {
05194     fprintf (stderr,
05195             "elf_symbol_from_bfd_symbol 0x%.8lx, name = %s, sym num = %d, flags = 0x%.8lx%s\n",
05196             (long) asym_ptr, asym_ptr->name, idx, flags,
05197             elf_symbol_flags (flags));
05198     fflush (stderr);
05199   }
05200 #endif
05201 
05202   return idx;
05203 }
05204 
05205 /* Rewrite program header information.  */
05206 
05207 static bfd_boolean
05208 rewrite_elf_program_header (bfd *ibfd, bfd *obfd)
05209 {
05210   Elf_Internal_Ehdr *iehdr;
05211   struct elf_segment_map *map;
05212   struct elf_segment_map *map_first;
05213   struct elf_segment_map **pointer_to_map;
05214   Elf_Internal_Phdr *segment;
05215   asection *section;
05216   unsigned int i;
05217   unsigned int num_segments;
05218   bfd_boolean phdr_included = FALSE;
05219   bfd_vma maxpagesize;
05220   struct elf_segment_map *phdr_adjust_seg = NULL;
05221   unsigned int phdr_adjust_num = 0;
05222   const struct elf_backend_data *bed;
05223 
05224   bed = get_elf_backend_data (ibfd);
05225   iehdr = elf_elfheader (ibfd);
05226 
05227   map_first = NULL;
05228   pointer_to_map = &map_first;
05229 
05230   num_segments = elf_elfheader (ibfd)->e_phnum;
05231   maxpagesize = get_elf_backend_data (obfd)->maxpagesize;
05232 
05233   /* Returns the end address of the segment + 1.  */
05234 #define SEGMENT_END(segment, start)                                   \
05235   (start + (segment->p_memsz > segment->p_filesz               \
05236            ? segment->p_memsz : segment->p_filesz))
05237 
05238 #define SECTION_SIZE(section, segment)                                \
05239   (((section->flags & (SEC_HAS_CONTENTS | SEC_THREAD_LOCAL))          \
05240     != SEC_THREAD_LOCAL || segment->p_type == PT_TLS)                 \
05241    ? section->size : 0)
05242 
05243   /* Returns TRUE if the given section is contained within
05244      the given segment.  VMA addresses are compared.  */
05245 #define IS_CONTAINED_BY_VMA(section, segment)                         \
05246   (section->vma >= segment->p_vaddr                                   \
05247    && (section->vma + SECTION_SIZE (section, segment)                 \
05248        <= (SEGMENT_END (segment, segment->p_vaddr))))
05249 
05250   /* Returns TRUE if the given section is contained within
05251      the given segment.  LMA addresses are compared.  */
05252 #define IS_CONTAINED_BY_LMA(section, segment, base)                   \
05253   (section->lma >= base                                               \
05254    && (section->lma + SECTION_SIZE (section, segment)                 \
05255        <= SEGMENT_END (segment, base)))
05256 
05257   /* Special case: corefile "NOTE" section containing regs, prpsinfo etc.  */
05258 #define IS_COREFILE_NOTE(p, s)                                        \
05259   (p->p_type == PT_NOTE                                               \
05260    && bfd_get_format (ibfd) == bfd_core                               \
05261    && s->vma == 0 && s->lma == 0                               \
05262    && (bfd_vma) s->filepos >= p->p_offset                      \
05263    && ((bfd_vma) s->filepos + s->size                                 \
05264        <= p->p_offset + p->p_filesz))
05265 
05266   /* The complicated case when p_vaddr is 0 is to handle the Solaris
05267      linker, which generates a PT_INTERP section with p_vaddr and
05268      p_memsz set to 0.  */
05269 #define IS_SOLARIS_PT_INTERP(p, s)                             \
05270   (p->p_vaddr == 0                                             \
05271    && p->p_paddr == 0                                                 \
05272    && p->p_memsz == 0                                                 \
05273    && p->p_filesz > 0                                                 \
05274    && (s->flags & SEC_HAS_CONTENTS) != 0                       \
05275    && s->size > 0                                              \
05276    && (bfd_vma) s->filepos >= p->p_offset                      \
05277    && ((bfd_vma) s->filepos + s->size                                 \
05278        <= p->p_offset + p->p_filesz))
05279 
05280   /* Decide if the given section should be included in the given segment.
05281      A section will be included if:
05282        1. It is within the address space of the segment -- we use the LMA
05283           if that is set for the segment and the VMA otherwise,
05284        2. It is an allocated segment,
05285        3. There is an output section associated with it,
05286        4. The section has not already been allocated to a previous segment.
05287        5. PT_GNU_STACK segments do not include any sections.
05288        6. PT_TLS segment includes only SHF_TLS sections.
05289        7. SHF_TLS sections are only in PT_TLS or PT_LOAD segments.
05290        8. PT_DYNAMIC should not contain empty sections at the beginning
05291           (with the possible exception of .dynamic).  */
05292 #define IS_SECTION_IN_INPUT_SEGMENT(section, segment, bed)            \
05293   ((((segment->p_paddr                                                \
05294       ? IS_CONTAINED_BY_LMA (section, segment, segment->p_paddr)      \
05295       : IS_CONTAINED_BY_VMA (section, segment))                       \
05296      && (section->flags & SEC_ALLOC) != 0)                            \
05297     || IS_COREFILE_NOTE (segment, section))                           \
05298    && segment->p_type != PT_GNU_STACK                                 \
05299    && (segment->p_type != PT_TLS                               \
05300        || (section->flags & SEC_THREAD_LOCAL))                        \
05301    && (segment->p_type == PT_LOAD                              \
05302        || segment->p_type == PT_TLS                                   \
05303        || (section->flags & SEC_THREAD_LOCAL) == 0)                   \
05304    && (segment->p_type != PT_DYNAMIC                                  \
05305        || SECTION_SIZE (section, segment) > 0                         \
05306        || (segment->p_paddr                                    \
05307            ? segment->p_paddr != section->lma                         \
05308            : segment->p_vaddr != section->vma)                        \
05309        || (strcmp (bfd_get_section_name (ibfd, section), ".dynamic")  \
05310            == 0))                                              \
05311    && ! section->segment_mark)
05312 
05313 /* If the output section of a section in the input segment is NULL,
05314    it is removed from the corresponding output segment.   */
05315 #define INCLUDE_SECTION_IN_SEGMENT(section, segment, bed)             \
05316   (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed)         \
05317    && section->output_section != NULL)
05318 
05319   /* Returns TRUE iff seg1 starts after the end of seg2.  */
05320 #define SEGMENT_AFTER_SEGMENT(seg1, seg2, field)               \
05321   (seg1->field >= SEGMENT_END (seg2, seg2->field))
05322 
05323   /* Returns TRUE iff seg1 and seg2 overlap. Segments overlap iff both
05324      their VMA address ranges and their LMA address ranges overlap.
05325      It is possible to have overlapping VMA ranges without overlapping LMA
05326      ranges.  RedBoot images for example can have both .data and .bss mapped
05327      to the same VMA range, but with the .data section mapped to a different
05328      LMA.  */
05329 #define SEGMENT_OVERLAPS(seg1, seg2)                                  \
05330   (   !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_vaddr)                   \
05331         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_vaddr))               \
05332    && !(SEGMENT_AFTER_SEGMENT (seg1, seg2, p_paddr)                   \
05333         || SEGMENT_AFTER_SEGMENT (seg2, seg1, p_paddr)))
05334 
05335   /* Initialise the segment mark field.  */
05336   for (section = ibfd->sections; section != NULL; section = section->next)
05337     section->segment_mark = FALSE;
05338 
05339   /* Scan through the segments specified in the program header
05340      of the input BFD.  For this first scan we look for overlaps
05341      in the loadable segments.  These can be created by weird
05342      parameters to objcopy.  Also, fix some solaris weirdness.  */
05343   for (i = 0, segment = elf_tdata (ibfd)->phdr;
05344        i < num_segments;
05345        i++, segment++)
05346     {
05347       unsigned int j;
05348       Elf_Internal_Phdr *segment2;
05349 
05350       if (segment->p_type == PT_INTERP)
05351        for (section = ibfd->sections; section; section = section->next)
05352          if (IS_SOLARIS_PT_INTERP (segment, section))
05353            {
05354              /* Mininal change so that the normal section to segment
05355                assignment code will work.  */
05356              segment->p_vaddr = section->vma;
05357              break;
05358            }
05359 
05360       if (segment->p_type != PT_LOAD)
05361        continue;
05362 
05363       /* Determine if this segment overlaps any previous segments.  */
05364       for (j = 0, segment2 = elf_tdata (ibfd)->phdr; j < i; j++, segment2 ++)
05365        {
05366          bfd_signed_vma extra_length;
05367 
05368          if (segment2->p_type != PT_LOAD
05369              || ! SEGMENT_OVERLAPS (segment, segment2))
05370            continue;
05371 
05372          /* Merge the two segments together.  */
05373          if (segment2->p_vaddr < segment->p_vaddr)
05374            {
05375              /* Extend SEGMENT2 to include SEGMENT and then delete
05376                  SEGMENT.  */
05377              extra_length =
05378               SEGMENT_END (segment, segment->p_vaddr)
05379               - SEGMENT_END (segment2, segment2->p_vaddr);
05380 
05381              if (extra_length > 0)
05382               {
05383                 segment2->p_memsz  += extra_length;
05384                 segment2->p_filesz += extra_length;
05385               }
05386 
05387              segment->p_type = PT_NULL;
05388 
05389              /* Since we have deleted P we must restart the outer loop.  */
05390              i = 0;
05391              segment = elf_tdata (ibfd)->phdr;
05392              break;
05393            }
05394          else
05395            {
05396              /* Extend SEGMENT to include SEGMENT2 and then delete
05397                  SEGMENT2.  */
05398              extra_length =
05399               SEGMENT_END (segment2, segment2->p_vaddr)
05400               - SEGMENT_END (segment, segment->p_vaddr);
05401 
05402              if (extra_length > 0)
05403               {
05404                 segment->p_memsz  += extra_length;
05405                 segment->p_filesz += extra_length;
05406               }
05407 
05408              segment2->p_type = PT_NULL;
05409            }
05410        }
05411     }
05412 
05413   /* The second scan attempts to assign sections to segments.  */
05414   for (i = 0, segment = elf_tdata (ibfd)->phdr;
05415        i < num_segments;
05416        i ++, segment ++)
05417     {
05418       unsigned int  section_count;
05419       asection **   sections;
05420       asection *    output_section;
05421       unsigned int  isec;
05422       bfd_vma       matching_lma;
05423       bfd_vma       suggested_lma;
05424       unsigned int  j;
05425       bfd_size_type amt;
05426       asection *    first_section;
05427 
05428       if (segment->p_type == PT_NULL)
05429        continue;
05430 
05431       first_section = NULL;
05432       /* Compute how many sections might be placed into this segment.  */
05433       for (section = ibfd->sections, section_count = 0;
05434           section != NULL;
05435           section = section->next)
05436        {
05437          /* Find the first section in the input segment, which may be
05438             removed from the corresponding output segment.   */
05439          if (IS_SECTION_IN_INPUT_SEGMENT (section, segment, bed))
05440            {
05441              if (first_section == NULL)
05442               first_section = section;
05443              if (section->output_section != NULL)
05444               ++section_count;
05445            }
05446        }
05447 
05448       /* Allocate a segment map big enough to contain
05449         all of the sections we have selected.  */
05450       amt = sizeof (struct elf_segment_map);
05451       amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
05452       map = bfd_zalloc (obfd, amt);
05453       if (map == NULL)
05454        return FALSE;
05455 
05456       /* Initialise the fields of the segment map.  Default to
05457         using the physical address of the segment in the input BFD.  */
05458       map->next          = NULL;
05459       map->p_type        = segment->p_type;
05460       map->p_flags       = segment->p_flags;
05461       map->p_flags_valid = 1;
05462 
05463       /* If the first section in the input segment is removed, there is
05464         no need to preserve segment physical address in the corresponding
05465         output segment.  */
05466       if (!first_section || first_section->output_section != NULL)
05467        {
05468          map->p_paddr = segment->p_paddr;
05469          map->p_paddr_valid = 1;
05470        }
05471 
05472       /* Determine if this segment contains the ELF file header
05473         and if it contains the program headers themselves.  */
05474       map->includes_filehdr = (segment->p_offset == 0
05475                             && segment->p_filesz >= iehdr->e_ehsize);
05476 
05477       map->includes_phdrs = 0;
05478 
05479       if (! phdr_included || segment->p_type != PT_LOAD)
05480        {
05481          map->includes_phdrs =
05482            (segment->p_offset <= (bfd_vma) iehdr->e_phoff
05483             && (segment->p_offset + segment->p_filesz
05484                >= ((bfd_vma) iehdr->e_phoff
05485                    + iehdr->e_phnum * iehdr->e_phentsize)));
05486 
05487          if (segment->p_type == PT_LOAD && map->includes_phdrs)
05488            phdr_included = TRUE;
05489        }
05490 
05491       if (section_count == 0)
05492        {
05493          /* Special segments, such as the PT_PHDR segment, may contain
05494             no sections, but ordinary, loadable segments should contain
05495             something.  They are allowed by the ELF spec however, so only
05496             a warning is produced.  */
05497          if (segment->p_type == PT_LOAD)
05498            (*_bfd_error_handler)
05499              (_("%B: warning: Empty loadable segment detected, is this intentional ?\n"),
05500               ibfd);
05501 
05502          map->count = 0;
05503          *pointer_to_map = map;
05504          pointer_to_map = &map->next;
05505 
05506          continue;
05507        }
05508 
05509       /* Now scan the sections in the input BFD again and attempt
05510         to add their corresponding output sections to the segment map.
05511         The problem here is how to handle an output section which has
05512         been moved (ie had its LMA changed).  There are four possibilities:
05513 
05514         1. None of the sections have been moved.
05515            In this case we can continue to use the segment LMA from the
05516            input BFD.
05517 
05518         2. All of the sections have been moved by the same amount.
05519            In this case we can change the segment's LMA to match the LMA
05520            of the first section.
05521 
05522         3. Some of the sections have been moved, others have not.
05523            In this case those sections which have not been moved can be
05524            placed in the current segment which will have to have its size,
05525            and possibly its LMA changed, and a new segment or segments will
05526            have to be created to contain the other sections.
05527 
05528         4. The sections have been moved, but not by the same amount.
05529            In this case we can change the segment's LMA to match the LMA
05530            of the first section and we will have to create a new segment
05531            or segments to contain the other sections.
05532 
05533         In order to save time, we allocate an array to hold the section
05534         pointers that we are interested in.  As these sections get assigned
05535         to a segment, they are removed from this array.  */
05536 
05537       /* Gcc 2.96 miscompiles this code on mips. Don't do casting here
05538         to work around this long long bug.  */
05539       sections = bfd_malloc2 (section_count, sizeof (asection *));
05540       if (sections == NULL)
05541        return FALSE;
05542 
05543       /* Step One: Scan for segment vs section LMA conflicts.
05544         Also add the sections to the section array allocated above.
05545         Also add the sections to the current segment.  In the common
05546         case, where the sections have not been moved, this means that
05547         we have completely filled the segment, and there is nothing
05548         more to do.  */
05549       isec = 0;
05550       matching_lma = 0;
05551       suggested_lma = 0;
05552 
05553       for (j = 0, section = ibfd->sections;
05554           section != NULL;
05555           section = section->next)
05556        {
05557          if (INCLUDE_SECTION_IN_SEGMENT (section, segment, bed))
05558            {
05559              output_section = section->output_section;
05560 
05561              sections[j ++] = section;
05562 
05563              /* The Solaris native linker always sets p_paddr to 0.
05564                We try to catch that case here, and set it to the
05565                correct value.  Note - some backends require that
05566                p_paddr be left as zero.  */
05567              if (segment->p_paddr == 0
05568                 && segment->p_vaddr != 0
05569                 && (! bed->want_p_paddr_set_to_zero)
05570                 && isec == 0
05571                 && output_section->lma != 0
05572                 && (output_section->vma == (segment->p_vaddr
05573                                          + (map->includes_filehdr
05574                                            ? iehdr->e_ehsize
05575                                            : 0)
05576                                          + (map->includes_phdrs
05577                                            ? (iehdr->e_phnum
05578                                               * iehdr->e_phentsize)
05579                                            : 0))))
05580               map->p_paddr = segment->p_vaddr;
05581 
05582              /* Match up the physical address of the segment with the
05583                LMA address of the output section.  */
05584              if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
05585                 || IS_COREFILE_NOTE (segment, section)
05586                 || (bed->want_p_paddr_set_to_zero &&
05587                     IS_CONTAINED_BY_VMA (output_section, segment))
05588                 )
05589               {
05590                 if (matching_lma == 0)
05591                   matching_lma = output_section->lma;
05592 
05593                 /* We assume that if the section fits within the segment
05594                    then it does not overlap any other section within that
05595                    segment.  */
05596                 map->sections[isec ++] = output_section;
05597               }
05598              else if (suggested_lma == 0)
05599               suggested_lma = output_section->lma;
05600            }
05601        }
05602 
05603       BFD_ASSERT (j == section_count);
05604 
05605       /* Step Two: Adjust the physical address of the current segment,
05606         if necessary.  */
05607       if (isec == section_count)
05608        {
05609          /* All of the sections fitted within the segment as currently
05610             specified.  This is the default case.  Add the segment to
05611             the list of built segments and carry on to process the next
05612             program header in the input BFD.  */
05613          map->count = section_count;
05614          *pointer_to_map = map;
05615          pointer_to_map = &map->next;
05616          
05617          if (matching_lma != map->p_paddr
05618              && !map->includes_filehdr && !map->includes_phdrs)
05619            /* There is some padding before the first section in the
05620               segment.  So, we must account for that in the output
05621               segment's vma.  */
05622            map->p_vaddr_offset = matching_lma - map->p_paddr;
05623          
05624          free (sections);
05625          continue;
05626        }
05627       else
05628        {
05629          if (matching_lma != 0)
05630            {
05631              /* At least one section fits inside the current segment.
05632                Keep it, but modify its physical address to match the
05633                LMA of the first section that fitted.  */
05634              map->p_paddr = matching_lma;
05635            }
05636          else
05637            {
05638              /* None of the sections fitted inside the current segment.
05639                Change the current segment's physical address to match
05640                the LMA of the first section.  */
05641              map->p_paddr = suggested_lma;
05642            }
05643 
05644          /* Offset the segment physical address from the lma
05645             to allow for space taken up by elf headers.  */
05646          if (map->includes_filehdr)
05647            map->p_paddr -= iehdr->e_ehsize;
05648 
05649          if (map->includes_phdrs)
05650            {
05651              map->p_paddr -= iehdr->e_phnum * iehdr->e_phentsize;
05652 
05653              /* iehdr->e_phnum is just an estimate of the number
05654                of program headers that we will need.  Make a note
05655                here of the number we used and the segment we chose
05656                to hold these headers, so that we can adjust the
05657                offset when we know the correct value.  */
05658              phdr_adjust_num = iehdr->e_phnum;
05659              phdr_adjust_seg = map;
05660            }
05661        }
05662 
05663       /* Step Three: Loop over the sections again, this time assigning
05664         those that fit to the current segment and removing them from the
05665         sections array; but making sure not to leave large gaps.  Once all
05666         possible sections have been assigned to the current segment it is
05667         added to the list of built segments and if sections still remain
05668         to be assigned, a new segment is constructed before repeating
05669         the loop.  */
05670       isec = 0;
05671       do
05672        {
05673          map->count = 0;
05674          suggested_lma = 0;
05675 
05676          /* Fill the current segment with sections that fit.  */
05677          for (j = 0; j < section_count; j++)
05678            {
05679              section = sections[j];
05680 
05681              if (section == NULL)
05682               continue;
05683 
05684              output_section = section->output_section;
05685 
05686              BFD_ASSERT (output_section != NULL);
05687 
05688              if (IS_CONTAINED_BY_LMA (output_section, segment, map->p_paddr)
05689                 || IS_COREFILE_NOTE (segment, section))
05690               {
05691                 if (map->count == 0)
05692                   {
05693                     /* If the first section in a segment does not start at
05694                       the beginning of the segment, then something is
05695                       wrong.  */
05696                     if (output_section->lma !=
05697                        (map->p_paddr
05698                         + (map->includes_filehdr ? iehdr->e_ehsize : 0)
05699                         + (map->includes_phdrs
05700                            ? iehdr->e_phnum * iehdr->e_phentsize
05701                            : 0)))
05702                      abort ();
05703                   }
05704                 else
05705                   {
05706                     asection * prev_sec;
05707 
05708                     prev_sec = map->sections[map->count - 1];
05709 
05710                     /* If the gap between the end of the previous section
05711                       and the start of this section is more than
05712                       maxpagesize then we need to start a new segment.  */
05713                     if ((BFD_ALIGN (prev_sec->lma + prev_sec->size,
05714                                   maxpagesize)
05715                         < BFD_ALIGN (output_section->lma, maxpagesize))
05716                        || ((prev_sec->lma + prev_sec->size)
05717                            > output_section->lma))
05718                      {
05719                        if (suggested_lma == 0)
05720                          suggested_lma = output_section->lma;
05721 
05722                        continue;
05723                      }
05724                   }
05725 
05726                 map->sections[map->count++] = output_section;
05727                 ++isec;
05728                 sections[j] = NULL;
05729                 section->segment_mark = TRUE;
05730               }
05731              else if (suggested_lma == 0)
05732               suggested_lma = output_section->lma;
05733            }
05734 
05735          BFD_ASSERT (map->count > 0);
05736 
05737          /* Add the current segment to the list of built segments.  */
05738          *pointer_to_map = map;
05739          pointer_to_map = &map->next;
05740 
05741          if (isec < section_count)
05742            {
05743              /* We still have not allocated all of the sections to
05744                segments.  Create a new segment here, initialise it
05745                and carry on looping.  */
05746              amt = sizeof (struct elf_segment_map);
05747              amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
05748              map = bfd_alloc (obfd, amt);
05749              if (map == NULL)
05750               {
05751                 free (sections);
05752                 return FALSE;
05753               }
05754 
05755              /* Initialise the fields of the segment map.  Set the physical
05756                physical address to the LMA of the first section that has
05757                not yet been assigned.  */
05758              map->next             = NULL;
05759              map->p_type           = segment->p_type;
05760              map->p_flags          = segment->p_flags;
05761              map->p_flags_valid    = 1;
05762              map->p_paddr          = suggested_lma;
05763              map->p_paddr_valid    = 1;
05764              map->includes_filehdr = 0;
05765              map->includes_phdrs   = 0;
05766            }
05767        }
05768       while (isec < section_count);
05769 
05770       free (sections);
05771     }
05772 
05773   /* The Solaris linker creates program headers in which all the
05774      p_paddr fields are zero.  When we try to objcopy or strip such a
05775      file, we get confused.  Check for this case, and if we find it
05776      reset the p_paddr_valid fields.  */
05777   for (map = map_first; map != NULL; map = map->next)
05778     if (map->p_paddr != 0)
05779       break;
05780   if (map == NULL)
05781     for (map = map_first; map != NULL; map = map->next)
05782       map->p_paddr_valid = 0;
05783 
05784   elf_tdata (obfd)->segment_map = map_first;
05785 
05786   /* If we had to estimate the number of program headers that were
05787      going to be needed, then check our estimate now and adjust
05788      the offset if necessary.  */
05789   if (phdr_adjust_seg != NULL)
05790     {
05791       unsigned int count;
05792 
05793       for (count = 0, map = map_first; map != NULL; map = map->next)
05794        count++;
05795 
05796       if (count > phdr_adjust_num)
05797        phdr_adjust_seg->p_paddr
05798          -= (count - phdr_adjust_num) * iehdr->e_phentsize;
05799     }
05800 
05801 #undef SEGMENT_END
05802 #undef SECTION_SIZE
05803 #undef IS_CONTAINED_BY_VMA
05804 #undef IS_CONTAINED_BY_LMA
05805 #undef IS_COREFILE_NOTE
05806 #undef IS_SOLARIS_PT_INTERP
05807 #undef IS_SECTION_IN_INPUT_SEGMENT
05808 #undef INCLUDE_SECTION_IN_SEGMENT
05809 #undef SEGMENT_AFTER_SEGMENT
05810 #undef SEGMENT_OVERLAPS
05811   return TRUE;
05812 }
05813 
05814 /* Copy ELF program header information.  */
05815 
05816 static bfd_boolean
05817 copy_elf_program_header (bfd *ibfd, bfd *obfd)
05818 {
05819   Elf_Internal_Ehdr *iehdr;
05820   struct elf_segment_map *map;
05821   struct elf_segment_map *map_first;
05822   struct elf_segment_map **pointer_to_map;
05823   Elf_Internal_Phdr *segment;
05824   unsigned int i;
05825   unsigned int num_segments;
05826   bfd_boolean phdr_included = FALSE;
05827 
05828   iehdr = elf_elfheader (ibfd);
05829 
05830   map_first = NULL;
05831   pointer_to_map = &map_first;
05832 
05833   num_segments = elf_elfheader (ibfd)->e_phnum;
05834   for (i = 0, segment = elf_tdata (ibfd)->phdr;
05835        i < num_segments;
05836        i++, segment++)
05837     {
05838       asection *section;
05839       unsigned int section_count;
05840       bfd_size_type amt;
05841       Elf_Internal_Shdr *this_hdr;
05842       asection *first_section = NULL;
05843 
05844       /* FIXME: Do we need to copy PT_NULL segment?  */
05845       if (segment->p_type == PT_NULL)
05846        continue;
05847 
05848       /* Compute how many sections are in this segment.  */
05849       for (section = ibfd->sections, section_count = 0;
05850           section != NULL;
05851           section = section->next)
05852        {
05853          this_hdr = &(elf_section_data(section)->this_hdr);
05854          if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
05855            {
05856              if (!first_section)
05857               first_section = section;
05858              section_count++;
05859            }
05860        }
05861 
05862       /* Allocate a segment map big enough to contain
05863         all of the sections we have selected.  */
05864       amt = sizeof (struct elf_segment_map);
05865       if (section_count != 0)
05866        amt += ((bfd_size_type) section_count - 1) * sizeof (asection *);
05867       map = bfd_zalloc (obfd, amt);
05868       if (map == NULL)
05869        return FALSE;
05870 
05871       /* Initialize the fields of the output segment map with the
05872         input segment.  */
05873       map->next = NULL;
05874       map->p_type = segment->p_type;
05875       map->p_flags = segment->p_flags;
05876       map->p_flags_valid = 1;
05877       map->p_paddr = segment->p_paddr;
05878       map->p_paddr_valid = 1;
05879       map->p_align = segment->p_align;
05880       map->p_align_valid = 1;
05881       map->p_vaddr_offset = 0;
05882 
05883       /* Determine if this segment contains the ELF file header
05884         and if it contains the program headers themselves.  */
05885       map->includes_filehdr = (segment->p_offset == 0
05886                             && segment->p_filesz >= iehdr->e_ehsize);
05887 
05888       map->includes_phdrs = 0;
05889       if (! phdr_included || segment->p_type != PT_LOAD)
05890        {
05891          map->includes_phdrs =
05892            (segment->p_offset <= (bfd_vma) iehdr->e_phoff
05893             && (segment->p_offset + segment->p_filesz
05894                >= ((bfd_vma) iehdr->e_phoff
05895                    + iehdr->e_phnum * iehdr->e_phentsize)));
05896 
05897          if (segment->p_type == PT_LOAD && map->includes_phdrs)
05898            phdr_included = TRUE;
05899        }
05900 
05901       if (!map->includes_phdrs && !map->includes_filehdr)
05902        /* There is some other padding before the first section.  */
05903        map->p_vaddr_offset = ((first_section ? first_section->lma : 0)
05904                             - segment->p_paddr);
05905       
05906       if (section_count != 0)
05907        {
05908          unsigned int isec = 0;
05909 
05910          for (section = first_section;
05911               section != NULL;
05912               section = section->next)
05913            {
05914              this_hdr = &(elf_section_data(section)->this_hdr);
05915              if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
05916               {
05917                 map->sections[isec++] = section->output_section;
05918                 if (isec == section_count)
05919                   break;
05920               }
05921            }
05922        }
05923 
05924       map->count = section_count;
05925       *pointer_to_map = map;
05926       pointer_to_map = &map->next;
05927     }
05928 
05929   elf_tdata (obfd)->segment_map = map_first;
05930   return TRUE;
05931 }
05932 
05933 /* Copy private BFD data.  This copies or rewrites ELF program header
05934    information.  */
05935 
05936 static bfd_boolean
05937 copy_private_bfd_data (bfd *ibfd, bfd *obfd)
05938 {
05939   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
05940       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
05941     return TRUE;
05942 
05943   if (elf_tdata (ibfd)->phdr == NULL)
05944     return TRUE;
05945 
05946   if (ibfd->xvec == obfd->xvec)
05947     {
05948       /* Check to see if any sections in the input BFD
05949         covered by ELF program header have changed.  */
05950       Elf_Internal_Phdr *segment;
05951       asection *section, *osec;
05952       unsigned int i, num_segments;
05953       Elf_Internal_Shdr *this_hdr;
05954 
05955       /* Initialize the segment mark field.  */
05956       for (section = obfd->sections; section != NULL;
05957           section = section->next)
05958        section->segment_mark = FALSE;
05959 
05960       num_segments = elf_elfheader (ibfd)->e_phnum;
05961       for (i = 0, segment = elf_tdata (ibfd)->phdr;
05962           i < num_segments;
05963           i++, segment++)
05964        {
05965          /* PR binutils/3535.  The Solaris linker always sets the p_paddr
05966             and p_memsz fields of special segments (DYNAMIC, INTERP) to 0
05967             which severly confuses things, so always regenerate the segment
05968             map in this case.  */
05969          if (segment->p_paddr == 0
05970              && segment->p_memsz == 0
05971              && (segment->p_type == PT_INTERP || segment->p_type == PT_DYNAMIC))
05972            goto rewrite;
05973 
05974          for (section = ibfd->sections;
05975               section != NULL; section = section->next)
05976            {
05977              /* We mark the output section so that we know it comes
05978                from the input BFD.  */
05979              osec = section->output_section;
05980              if (osec)
05981               osec->segment_mark = TRUE;
05982 
05983              /* Check if this section is covered by the segment.  */
05984              this_hdr = &(elf_section_data(section)->this_hdr);
05985              if (ELF_IS_SECTION_IN_SEGMENT_FILE (this_hdr, segment))
05986               {
05987                 /* FIXME: Check if its output section is changed or
05988                    removed.  What else do we need to check?  */
05989                 if (osec == NULL
05990                     || section->flags != osec->flags
05991                     || section->lma != osec->lma
05992                     || section->vma != osec->vma
05993                     || section->size != osec->size
05994                     || section->rawsize != osec->rawsize
05995                     || section->alignment_power != osec->alignment_power)
05996                   goto rewrite;
05997               }
05998            }
05999        }
06000 
06001       /* Check to see if any output section do not come from the
06002         input BFD.  */
06003       for (section = obfd->sections; section != NULL;
06004           section = section->next)
06005        {
06006          if (section->segment_mark == FALSE)
06007            goto rewrite;
06008          else
06009            section->segment_mark = FALSE;
06010        }
06011 
06012       return copy_elf_program_header (ibfd, obfd);
06013     }
06014 
06015 rewrite:
06016   return rewrite_elf_program_header (ibfd, obfd);
06017 }
06018 
06019 /* Initialize private output section information from input section.  */
06020 
06021 bfd_boolean
06022 _bfd_elf_init_private_section_data (bfd *ibfd,
06023                                 asection *isec,
06024                                 bfd *obfd,
06025                                 asection *osec,
06026                                 struct bfd_link_info *link_info)
06027 
06028 {
06029   Elf_Internal_Shdr *ihdr, *ohdr;
06030   bfd_boolean need_group = link_info == NULL || link_info->relocatable;
06031 
06032   if (ibfd->xvec->flavour != bfd_target_elf_flavour
06033       || obfd->xvec->flavour != bfd_target_elf_flavour)
06034     return TRUE;
06035 
06036   /* Don't copy the output ELF section type from input if the
06037      output BFD section flags have been set to something different.
06038      elf_fake_sections will set ELF section type based on BFD
06039      section flags.  */
06040   if (osec->flags == isec->flags || !osec->flags)
06041     {
06042       BFD_ASSERT (osec->flags == isec->flags 
06043                 || (!osec->flags
06044                     && elf_section_type (osec) == SHT_NULL));
06045       elf_section_type (osec) = elf_section_type (isec);
06046     }
06047 
06048   /* FIXME: Is this correct for all OS/PROC specific flags?  */
06049   elf_section_flags (osec) |= (elf_section_flags (isec)
06050                             & (SHF_MASKOS | SHF_MASKPROC));
06051 
06052   /* Set things up for objcopy and relocatable link.  The output
06053      SHT_GROUP section will have its elf_next_in_group pointing back
06054      to the input group members.  Ignore linker created group section.
06055      See elfNN_ia64_object_p in elfxx-ia64.c.  */
06056   if (need_group)
06057     {
06058       if (elf_sec_group (isec) == NULL
06059          || (elf_sec_group (isec)->flags & SEC_LINKER_CREATED) == 0)
06060        {
06061          if (elf_section_flags (isec) & SHF_GROUP)
06062            elf_section_flags (osec) |= SHF_GROUP;
06063          elf_next_in_group (osec) = elf_next_in_group (isec);
06064          elf_group_name (osec) = elf_group_name (isec);
06065        }
06066     }
06067 
06068   ihdr = &elf_section_data (isec)->this_hdr;
06069 
06070   /* We need to handle elf_linked_to_section for SHF_LINK_ORDER. We
06071      don't use the output section of the linked-to section since it
06072      may be NULL at this point.  */
06073   if ((ihdr->sh_flags & SHF_LINK_ORDER) != 0)
06074     {
06075       ohdr = &elf_section_data (osec)->this_hdr;
06076       ohdr->sh_flags |= SHF_LINK_ORDER;
06077       elf_linked_to_section (osec) = elf_linked_to_section (isec);
06078     }
06079 
06080   osec->use_rela_p = isec->use_rela_p;
06081 
06082   return TRUE;
06083 }
06084 
06085 /* Copy private section information.  This copies over the entsize
06086    field, and sometimes the info field.  */
06087 
06088 bfd_boolean
06089 _bfd_elf_copy_private_section_data (bfd *ibfd,
06090                                 asection *isec,
06091                                 bfd *obfd,
06092                                 asection *osec)
06093 {
06094   Elf_Internal_Shdr *ihdr, *ohdr;
06095 
06096   if (ibfd->xvec->flavour != bfd_target_elf_flavour
06097       || obfd->xvec->flavour != bfd_target_elf_flavour)
06098     return TRUE;
06099 
06100   ihdr = &elf_section_data (isec)->this_hdr;
06101   ohdr = &elf_section_data (osec)->this_hdr;
06102 
06103   ohdr->sh_entsize = ihdr->sh_entsize;
06104 
06105   if (ihdr->sh_type == SHT_SYMTAB
06106       || ihdr->sh_type == SHT_DYNSYM
06107       || ihdr->sh_type == SHT_GNU_verneed
06108       || ihdr->sh_type == SHT_GNU_verdef)
06109     ohdr->sh_info = ihdr->sh_info;
06110 
06111   return _bfd_elf_init_private_section_data (ibfd, isec, obfd, osec,
06112                                         NULL);
06113 }
06114 
06115 /* Copy private header information.  */
06116 
06117 bfd_boolean
06118 _bfd_elf_copy_private_header_data (bfd *ibfd, bfd *obfd)
06119 {
06120   asection *isec;
06121 
06122   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
06123       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
06124     return TRUE;
06125 
06126   /* Copy over private BFD data if it has not already been copied.
06127      This must be done here, rather than in the copy_private_bfd_data
06128      entry point, because the latter is called after the section
06129      contents have been set, which means that the program headers have
06130      already been worked out.  */
06131   if (elf_tdata (obfd)->segment_map == NULL && elf_tdata (ibfd)->phdr != NULL)
06132     {
06133       if (! copy_private_bfd_data (ibfd, obfd))
06134        return FALSE;
06135     }
06136 
06137   /* _bfd_elf_copy_private_section_data copied over the SHF_GROUP flag
06138      but this might be wrong if we deleted the group section.  */
06139   for (isec = ibfd->sections; isec != NULL; isec = isec->next)
06140     if (elf_section_type (isec) == SHT_GROUP
06141        && isec->output_section == NULL)
06142       {
06143        asection *first = elf_next_in_group (isec);
06144        asection *s = first;
06145        while (s != NULL)
06146          {
06147            if (s->output_section != NULL)
06148              {
06149               elf_section_flags (s->output_section) &= ~SHF_GROUP;
06150               elf_group_name (s->output_section) = NULL;
06151              }
06152            s = elf_next_in_group (s);
06153            if (s == first)
06154              break;
06155          }
06156       }
06157 
06158   return TRUE;
06159 }
06160 
06161 /* Copy private symbol information.  If this symbol is in a section
06162    which we did not map into a BFD section, try to map the section
06163    index correctly.  We use special macro definitions for the mapped
06164    section indices; these definitions are interpreted by the
06165    swap_out_syms function.  */
06166 
06167 #define MAP_ONESYMTAB (SHN_HIOS + 1)
06168 #define MAP_DYNSYMTAB (SHN_HIOS + 2)
06169 #define MAP_STRTAB    (SHN_HIOS + 3)
06170 #define MAP_SHSTRTAB  (SHN_HIOS + 4)
06171 #define MAP_SYM_SHNDX (SHN_HIOS + 5)
06172 
06173 bfd_boolean
06174 _bfd_elf_copy_private_symbol_data (bfd *ibfd,
06175                                asymbol *isymarg,
06176                                bfd *obfd,
06177                                asymbol *osymarg)
06178 {
06179   elf_symbol_type *isym, *osym;
06180 
06181   if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
06182       || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
06183     return TRUE;
06184 
06185   isym = elf_symbol_from (ibfd, isymarg);
06186   osym = elf_symbol_from (obfd, osymarg);
06187 
06188   if (isym != NULL
06189       && osym != NULL
06190       && bfd_is_abs_section (isym->symbol.section))
06191     {
06192       unsigned int shndx;
06193 
06194       shndx = isym->internal_elf_sym.st_shndx;
06195       if (shndx == elf_onesymtab (ibfd))
06196        shndx = MAP_ONESYMTAB;
06197       else if (shndx == elf_dynsymtab (ibfd))
06198        shndx = MAP_DYNSYMTAB;
06199       else if (shndx == elf_tdata (ibfd)->strtab_section)
06200        shndx = MAP_STRTAB;
06201       else if (shndx == elf_tdata (ibfd)->shstrtab_section)
06202        shndx = MAP_SHSTRTAB;
06203       else if (shndx == elf_tdata (ibfd)->symtab_shndx_section)
06204        shndx = MAP_SYM_SHNDX;
06205       osym->internal_elf_sym.st_shndx = shndx;
06206     }
06207 
06208   return TRUE;
06209 }
06210 
06211 /* Swap out the symbols.  */
06212 
06213 static bfd_boolean
06214 swap_out_syms (bfd *abfd,
06215               struct bfd_strtab_hash **sttp,
06216               int relocatable_p)
06217 {
06218   const struct elf_backend_data *bed;
06219   int symcount;
06220   asymbol **syms;
06221   struct bfd_strtab_hash *stt;
06222   Elf_Internal_Shdr *symtab_hdr;
06223   Elf_Internal_Shdr *symtab_shndx_hdr;
06224   Elf_Internal_Shdr *symstrtab_hdr;
06225   bfd_byte *outbound_syms;
06226   bfd_byte *outbound_shndx;
06227   int idx;
06228   bfd_size_type amt;
06229   bfd_boolean name_local_sections;
06230 
06231   if (!elf_map_symbols (abfd))
06232     return FALSE;
06233 
06234   /* Dump out the symtabs.  */
06235   stt = _bfd_elf_stringtab_init ();
06236   if (stt == NULL)
06237     return FALSE;
06238 
06239   bed = get_elf_backend_data (abfd);
06240   symcount = bfd_get_symcount (abfd);
06241   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
06242   symtab_hdr->sh_type = SHT_SYMTAB;
06243   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
06244   symtab_hdr->sh_size = symtab_hdr->sh_entsize * (symcount + 1);
06245   symtab_hdr->sh_info = elf_num_locals (abfd) + 1;
06246   symtab_hdr->sh_addralign = 1 << bed->s->log_file_align;
06247 
06248   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
06249   symstrtab_hdr->sh_type = SHT_STRTAB;
06250 
06251   outbound_syms = bfd_alloc2 (abfd, 1 + symcount, bed->s->sizeof_sym);
06252   if (outbound_syms == NULL)
06253     {
06254       _bfd_stringtab_free (stt);
06255       return FALSE;
06256     }
06257   symtab_hdr->contents = outbound_syms;
06258 
06259   outbound_shndx = NULL;
06260   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
06261   if (symtab_shndx_hdr->sh_name != 0)
06262     {
06263       amt = (bfd_size_type) (1 + symcount) * sizeof (Elf_External_Sym_Shndx);
06264       outbound_shndx = bfd_zalloc2 (abfd, 1 + symcount,
06265                                 sizeof (Elf_External_Sym_Shndx));
06266       if (outbound_shndx == NULL)
06267        {
06268          _bfd_stringtab_free (stt);
06269          return FALSE;
06270        }
06271 
06272       symtab_shndx_hdr->contents = outbound_shndx;
06273       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
06274       symtab_shndx_hdr->sh_size = amt;
06275       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
06276       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
06277     }
06278 
06279   /* Now generate the data (for "contents").  */
06280   {
06281     /* Fill in zeroth symbol and swap it out.  */
06282     Elf_Internal_Sym sym;
06283     sym.st_name = 0;
06284     sym.st_value = 0;
06285     sym.st_size = 0;
06286     sym.st_info = 0;
06287     sym.st_other = 0;
06288     sym.st_shndx = SHN_UNDEF;
06289     bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
06290     outbound_syms += bed->s->sizeof_sym;
06291     if (outbound_shndx != NULL)
06292       outbound_shndx += sizeof (Elf_External_Sym_Shndx);
06293   }
06294 
06295   name_local_sections
06296     = (bed->elf_backend_name_local_section_symbols
06297        && bed->elf_backend_name_local_section_symbols (abfd));
06298 
06299   syms = bfd_get_outsymbols (abfd);
06300   for (idx = 0; idx < symcount; idx++)
06301     {
06302       Elf_Internal_Sym sym;
06303       bfd_vma value = syms[idx]->value;
06304       elf_symbol_type *type_ptr;
06305       flagword flags = syms[idx]->flags;
06306       int type;
06307 
06308       if (!name_local_sections
06309          && (flags & (BSF_SECTION_SYM | BSF_GLOBAL)) == BSF_SECTION_SYM)
06310        {
06311          /* Local section symbols have no name.  */
06312          sym.st_name = 0;
06313        }
06314       else
06315        {
06316          sym.st_name = (unsigned long) _bfd_stringtab_add (stt,
06317                                                      syms[idx]->name,
06318                                                      TRUE, FALSE);
06319          if (sym.st_name == (unsigned long) -1)
06320            {
06321              _bfd_stringtab_free (stt);
06322              return FALSE;
06323            }
06324        }
06325 
06326       type_ptr = elf_symbol_from (abfd, syms[idx]);
06327 
06328       if ((flags & BSF_SECTION_SYM) == 0
06329          && bfd_is_com_section (syms[idx]->section))
06330        {
06331          /* ELF common symbols put the alignment into the `value' field,
06332             and the size into the `size' field.  This is backwards from
06333             how BFD handles it, so reverse it here.  */
06334          sym.st_size = value;
06335          if (type_ptr == NULL
06336              || type_ptr->internal_elf_sym.st_value == 0)
06337            sym.st_value = value >= 16 ? 16 : (1 << bfd_log2 (value));
06338          else
06339            sym.st_value = type_ptr->internal_elf_sym.st_value;
06340          sym.st_shndx = _bfd_elf_section_from_bfd_section
06341            (abfd, syms[idx]->section);
06342        }
06343       else
06344        {
06345          asection *sec = syms[idx]->section;
06346          int shndx;
06347 
06348          if (sec->output_section)
06349            {
06350              value += sec->output_offset;
06351              sec = sec->output_section;
06352            }
06353 
06354          /* Don't add in the section vma for relocatable output.  */
06355          if (! relocatable_p)
06356            value += sec->vma;
06357          sym.st_value = value;
06358          sym.st_size = type_ptr ? type_ptr->internal_elf_sym.st_size : 0;
06359 
06360          if (bfd_is_abs_section (sec)
06361              && type_ptr != NULL
06362              && type_ptr->internal_elf_sym.st_shndx != 0)
06363            {
06364              /* This symbol is in a real ELF section which we did
06365                not create as a BFD section.  Undo the mapping done
06366                by copy_private_symbol_data.  */
06367              shndx = type_ptr->internal_elf_sym.st_shndx;
06368              switch (shndx)
06369               {
06370               case MAP_ONESYMTAB:
06371                 shndx = elf_onesymtab (abfd);
06372                 break;
06373               case MAP_DYNSYMTAB:
06374                 shndx = elf_dynsymtab (abfd);
06375                 break;
06376               case MAP_STRTAB:
06377                 shndx = elf_tdata (abfd)->strtab_section;
06378                 break;
06379               case MAP_SHSTRTAB:
06380                 shndx = elf_tdata (abfd)->shstrtab_section;
06381                 break;
06382               case MAP_SYM_SHNDX:
06383                 shndx = elf_tdata (abfd)->symtab_shndx_section;
06384                 break;
06385               default:
06386                 break;
06387               }
06388            }
06389          else
06390            {
06391              shndx = _bfd_elf_section_from_bfd_section (abfd, sec);
06392 
06393              if (shndx == -1)
06394               {
06395                 asection *sec2;
06396 
06397                 /* Writing this would be a hell of a lot easier if
06398                    we had some decent documentation on bfd, and
06399                    knew what to expect of the library, and what to
06400                    demand of applications.  For example, it
06401                    appears that `objcopy' might not set the
06402                    section of a symbol to be a section that is
06403                    actually in the output file.  */
06404                 sec2 = bfd_get_section_by_name (abfd, sec->name);
06405                 if (sec2 == NULL)
06406                   {
06407                     _bfd_error_handler (_("\
06408 Unable to find equivalent output section for symbol '%s' from section '%s'"),
06409                                      syms[idx]->name ? syms[idx]->name : "<Local sym>",
06410                                      sec->name);
06411                     bfd_set_error (bfd_error_invalid_operation);
06412                     _bfd_stringtab_free (stt);
06413                     return FALSE;
06414                   }
06415 
06416                 shndx = _bfd_elf_section_from_bfd_section (abfd, sec2);
06417                 BFD_ASSERT (shndx != -1);
06418               }
06419            }
06420 
06421          sym.st_shndx = shndx;
06422        }
06423 
06424       if ((flags & BSF_THREAD_LOCAL) != 0)
06425        type = STT_TLS;
06426       else if ((flags & BSF_FUNCTION) != 0)
06427        type = STT_FUNC;
06428       else if ((flags & BSF_OBJECT) != 0)
06429        type = STT_OBJECT;
06430       else if ((flags & BSF_RELC) != 0)
06431        type = STT_RELC;
06432       else if ((flags & BSF_SRELC) != 0)
06433        type = STT_SRELC;
06434       else
06435        type = STT_NOTYPE;
06436 
06437       if (syms[idx]->section->flags & SEC_THREAD_LOCAL)
06438        type = STT_TLS;
06439 
06440       /* Processor-specific types.  */
06441       if (type_ptr != NULL
06442          && bed->elf_backend_get_symbol_type)
06443        type = ((*bed->elf_backend_get_symbol_type)
06444               (&type_ptr->internal_elf_sym, type));
06445 
06446       if (flags & BSF_SECTION_SYM)
06447        {
06448          if (flags & BSF_GLOBAL)
06449            sym.st_info = ELF_ST_INFO (STB_GLOBAL, STT_SECTION);
06450          else
06451            sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
06452        }
06453       else if (bfd_is_com_section (syms[idx]->section))
06454        sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
06455       else if (bfd_is_und_section (syms[idx]->section))
06456        sym.st_info = ELF_ST_INFO (((flags & BSF_WEAK)
06457                                 ? STB_WEAK
06458                                 : STB_GLOBAL),
06459                                type);
06460       else if (flags & BSF_FILE)
06461        sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
06462       else
06463        {
06464          int bind = STB_LOCAL;
06465 
06466          if (flags & BSF_LOCAL)
06467            bind = STB_LOCAL;
06468          else if (flags & BSF_WEAK)
06469            bind = STB_WEAK;
06470          else if (flags & BSF_GLOBAL)
06471            bind = STB_GLOBAL;
06472 
06473          sym.st_info = ELF_ST_INFO (bind, type);
06474        }
06475 
06476       if (type_ptr != NULL)
06477        sym.st_other = type_ptr->internal_elf_sym.st_other;
06478       else
06479        sym.st_other = 0;
06480 
06481       bed->s->swap_symbol_out (abfd, &sym, outbound_syms, outbound_shndx);
06482       outbound_syms += bed->s->sizeof_sym;
06483       if (outbound_shndx != NULL)
06484        outbound_shndx += sizeof (Elf_External_Sym_Shndx);
06485     }
06486 
06487   *sttp = stt;
06488   symstrtab_hdr->sh_size = _bfd_stringtab_size (stt);
06489   symstrtab_hdr->sh_type = SHT_STRTAB;
06490 
06491   symstrtab_hdr->sh_flags = 0;
06492   symstrtab_hdr->sh_addr = 0;
06493   symstrtab_hdr->sh_entsize = 0;
06494   symstrtab_hdr->sh_link = 0;
06495   symstrtab_hdr->sh_info = 0;
06496   symstrtab_hdr->sh_addralign = 1;
06497 
06498   return TRUE;
06499 }
06500 
06501 /* Return the number of bytes required to hold the symtab vector.
06502 
06503    Note that we base it on the count plus 1, since we will null terminate
06504    the vector allocated based on this size.  However, the ELF symbol table
06505    always has a dummy entry as symbol #0, so it ends up even.  */
06506 
06507 long
06508 _bfd_elf_get_symtab_upper_bound (bfd *abfd)
06509 {
06510   long symcount;
06511   long symtab_size;
06512   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->symtab_hdr;
06513 
06514   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
06515   symtab_size = (symcount + 1) * (sizeof (asymbol *));
06516   if (symcount > 0)
06517     symtab_size -= sizeof (asymbol *);
06518 
06519   return symtab_size;
06520 }
06521 
06522 long
06523 _bfd_elf_get_dynamic_symtab_upper_bound (bfd *abfd)
06524 {
06525   long symcount;
06526   long symtab_size;
06527   Elf_Internal_Shdr *hdr = &elf_tdata (abfd)->dynsymtab_hdr;
06528 
06529   if (elf_dynsymtab (abfd) == 0)
06530     {
06531       bfd_set_error (bfd_error_invalid_operation);
06532       return -1;
06533     }
06534 
06535   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
06536   symtab_size = (symcount + 1) * (sizeof (asymbol *));
06537   if (symcount > 0)
06538     symtab_size -= sizeof (asymbol *);
06539 
06540   return symtab_size;
06541 }
06542 
06543 long
06544 _bfd_elf_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED,
06545                             sec_ptr asect)
06546 {
06547   return (asect->reloc_count + 1) * sizeof (arelent *);
06548 }
06549 
06550 /* Canonicalize the relocs.  */
06551 
06552 long
06553 _bfd_elf_canonicalize_reloc (bfd *abfd,
06554                           sec_ptr section,
06555                           arelent **relptr,
06556                           asymbol **symbols)
06557 {
06558   arelent *tblptr;
06559   unsigned int i;
06560   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
06561 
06562   if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
06563     return -1;
06564 
06565   tblptr = section->relocation;
06566   for (i = 0; i < section->reloc_count; i++)
06567     *relptr++ = tblptr++;
06568 
06569   *relptr = NULL;
06570 
06571   return section->reloc_count;
06572 }
06573 
06574 long
06575 _bfd_elf_canonicalize_symtab (bfd *abfd, asymbol **allocation)
06576 {
06577   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
06578   long symcount = bed->s->slurp_symbol_table (abfd, allocation, FALSE);
06579 
06580   if (symcount >= 0)
06581     bfd_get_symcount (abfd) = symcount;
06582   return symcount;
06583 }
06584 
06585 long
06586 _bfd_elf_canonicalize_dynamic_symtab (bfd *abfd,
06587                                   asymbol **allocation)
06588 {
06589   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
06590   long symcount = bed->s->slurp_symbol_table (abfd, allocation, TRUE);
06591 
06592   if (symcount >= 0)
06593     bfd_get_dynamic_symcount (abfd) = symcount;
06594   return symcount;
06595 }
06596 
06597 /* Return the size required for the dynamic reloc entries.  Any loadable
06598    section that was actually installed in the BFD, and has type SHT_REL
06599    or SHT_RELA, and uses the dynamic symbol table, is considered to be a
06600    dynamic reloc section.  */
06601 
06602 long
06603 _bfd_elf_get_dynamic_reloc_upper_bound (bfd *abfd)
06604 {
06605   long ret;
06606   asection *s;
06607 
06608   if (elf_dynsymtab (abfd) == 0)
06609     {
06610       bfd_set_error (bfd_error_invalid_operation);
06611       return -1;
06612     }
06613 
06614   ret = sizeof (arelent *);
06615   for (s = abfd->sections; s != NULL; s = s->next)
06616     if ((s->flags & SEC_LOAD) != 0
06617        && elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
06618        && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
06619            || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
06620       ret += ((s->size / elf_section_data (s)->this_hdr.sh_entsize)
06621              * sizeof (arelent *));
06622 
06623   return ret;
06624 }
06625 
06626 /* Canonicalize the dynamic relocation entries.  Note that we return the
06627    dynamic relocations as a single block, although they are actually
06628    associated with particular sections; the interface, which was
06629    designed for SunOS style shared libraries, expects that there is only
06630    one set of dynamic relocs.  Any loadable section that was actually
06631    installed in the BFD, and has type SHT_REL or SHT_RELA, and uses the
06632    dynamic symbol table, is considered to be a dynamic reloc section.  */
06633 
06634 long
06635 _bfd_elf_canonicalize_dynamic_reloc (bfd *abfd,
06636                                  arelent **storage,
06637                                  asymbol **syms)
06638 {
06639   bfd_boolean (*slurp_relocs) (bfd *, asection *, asymbol **, bfd_boolean);
06640   asection *s;
06641   long ret;
06642 
06643   if (elf_dynsymtab (abfd) == 0)
06644     {
06645       bfd_set_error (bfd_error_invalid_operation);
06646       return -1;
06647     }
06648 
06649   slurp_relocs = get_elf_backend_data (abfd)->s->slurp_reloc_table;
06650   ret = 0;
06651   for (s = abfd->sections; s != NULL; s = s->next)
06652     {
06653       if ((s->flags & SEC_LOAD) != 0
06654          && elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
06655          && (elf_section_data (s)->this_hdr.sh_type == SHT_REL
06656              || elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
06657        {
06658          arelent *p;
06659          long count, i;
06660 
06661          if (! (*slurp_relocs) (abfd, s, syms, TRUE))
06662            return -1;
06663          count = s->size / elf_section_data (s)->this_hdr.sh_entsize;
06664          p = s->relocation;
06665          for (i = 0; i < count; i++)
06666            *storage++ = p++;
06667          ret += count;
06668        }
06669     }
06670 
06671   *storage = NULL;
06672 
06673   return ret;
06674 }
06675 
06676 /* Read in the version information.  */
06677 
06678 bfd_boolean
06679 _bfd_elf_slurp_version_tables (bfd *abfd, bfd_boolean default_imported_symver)
06680 {
06681   bfd_byte *contents = NULL;
06682   unsigned int freeidx = 0;
06683 
06684   if (elf_dynverref (abfd) != 0)
06685     {
06686       Elf_Internal_Shdr *hdr;
06687       Elf_External_Verneed *everneed;
06688       Elf_Internal_Verneed *iverneed;
06689       unsigned int i;
06690       bfd_byte *contents_end;
06691 
06692       hdr = &elf_tdata (abfd)->dynverref_hdr;
06693 
06694       elf_tdata (abfd)->verref = bfd_zalloc2 (abfd, hdr->sh_info,
06695                                          sizeof (Elf_Internal_Verneed));
06696       if (elf_tdata (abfd)->verref == NULL)
06697        goto error_return;
06698 
06699       elf_tdata (abfd)->cverrefs = hdr->sh_info;
06700 
06701       contents = bfd_malloc (hdr->sh_size);
06702       if (contents == NULL)
06703        {
06704 error_return_verref:
06705          elf_tdata (abfd)->verref = NULL;
06706          elf_tdata (abfd)->cverrefs = 0;
06707          goto error_return;
06708        }
06709       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
06710          || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
06711        goto error_return_verref;
06712 
06713       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verneed))
06714        goto error_return_verref;
06715 
06716       BFD_ASSERT (sizeof (Elf_External_Verneed)
06717                 == sizeof (Elf_External_Vernaux));
06718       contents_end = contents + hdr->sh_size - sizeof (Elf_External_Verneed);
06719       everneed = (Elf_External_Verneed *) contents;
06720       iverneed = elf_tdata (abfd)->verref;
06721       for (i = 0; i < hdr->sh_info; i++, iverneed++)
06722        {
06723          Elf_External_Vernaux *evernaux;
06724          Elf_Internal_Vernaux *ivernaux;
06725          unsigned int j;
06726 
06727          _bfd_elf_swap_verneed_in (abfd, everneed, iverneed);
06728 
06729          iverneed->vn_bfd = abfd;
06730 
06731          iverneed->vn_filename =
06732            bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
06733                                         iverneed->vn_file);
06734          if (iverneed->vn_filename == NULL)
06735            goto error_return_verref;
06736 
06737          if (iverneed->vn_cnt == 0)
06738            iverneed->vn_auxptr = NULL;
06739          else
06740            {
06741              iverneed->vn_auxptr = bfd_alloc2 (abfd, iverneed->vn_cnt,
06742                                           sizeof (Elf_Internal_Vernaux));
06743              if (iverneed->vn_auxptr == NULL)
06744               goto error_return_verref;
06745            }
06746 
06747          if (iverneed->vn_aux
06748              > (size_t) (contents_end - (bfd_byte *) everneed))
06749            goto error_return_verref;
06750 
06751          evernaux = ((Elf_External_Vernaux *)
06752                     ((bfd_byte *) everneed + iverneed->vn_aux));
06753          ivernaux = iverneed->vn_auxptr;
06754          for (j = 0; j < iverneed->vn_cnt; j++, ivernaux++)
06755            {
06756              _bfd_elf_swap_vernaux_in (abfd, evernaux, ivernaux);
06757 
06758              ivernaux->vna_nodename =
06759               bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
06760                                            ivernaux->vna_name);
06761              if (ivernaux->vna_nodename == NULL)
06762               goto error_return_verref;
06763 
06764              if (j + 1 < iverneed->vn_cnt)
06765               ivernaux->vna_nextptr = ivernaux + 1;
06766              else
06767               ivernaux->vna_nextptr = NULL;
06768 
06769              if (ivernaux->vna_next
06770                 > (size_t) (contents_end - (bfd_byte *) evernaux))
06771               goto error_return_verref;
06772 
06773              evernaux = ((Elf_External_Vernaux *)
06774                        ((bfd_byte *) evernaux + ivernaux->vna_next));
06775 
06776              if (ivernaux->vna_other > freeidx)
06777               freeidx = ivernaux->vna_other;
06778            }
06779 
06780          if (i + 1 < hdr->sh_info)
06781            iverneed->vn_nextref = iverneed + 1;
06782          else
06783            iverneed->vn_nextref = NULL;
06784 
06785          if (iverneed->vn_next
06786              > (size_t) (contents_end - (bfd_byte *) everneed))
06787            goto error_return_verref;
06788 
06789          everneed = ((Elf_External_Verneed *)
06790                     ((bfd_byte *) everneed + iverneed->vn_next));
06791        }
06792 
06793       free (contents);
06794       contents = NULL;
06795     }
06796 
06797   if (elf_dynverdef (abfd) != 0)
06798     {
06799       Elf_Internal_Shdr *hdr;
06800       Elf_External_Verdef *everdef;
06801       Elf_Internal_Verdef *iverdef;
06802       Elf_Internal_Verdef *iverdefarr;
06803       Elf_Internal_Verdef iverdefmem;
06804       unsigned int i;
06805       unsigned int maxidx;
06806       bfd_byte *contents_end_def, *contents_end_aux;
06807 
06808       hdr = &elf_tdata (abfd)->dynverdef_hdr;
06809 
06810       contents = bfd_malloc (hdr->sh_size);
06811       if (contents == NULL)
06812        goto error_return;
06813       if (bfd_seek (abfd, hdr->sh_offset, SEEK_SET) != 0
06814          || bfd_bread (contents, hdr->sh_size, abfd) != hdr->sh_size)
06815        goto error_return;
06816 
06817       if (hdr->sh_info && hdr->sh_size < sizeof (Elf_External_Verdef))
06818        goto error_return;
06819 
06820       BFD_ASSERT (sizeof (Elf_External_Verdef)
06821                 >= sizeof (Elf_External_Verdaux));
06822       contents_end_def = contents + hdr->sh_size
06823                       - sizeof (Elf_External_Verdef);
06824       contents_end_aux = contents + hdr->sh_size
06825                       - sizeof (Elf_External_Verdaux);
06826 
06827       /* We know the number of entries in the section but not the maximum
06828         index.  Therefore we have to run through all entries and find
06829         the maximum.  */
06830       everdef = (Elf_External_Verdef *) contents;
06831       maxidx = 0;
06832       for (i = 0; i < hdr->sh_info; ++i)
06833        {
06834          _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
06835 
06836          if ((iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION)) > maxidx)
06837            maxidx = iverdefmem.vd_ndx & ((unsigned) VERSYM_VERSION);
06838 
06839          if (iverdefmem.vd_next
06840              > (size_t) (contents_end_def - (bfd_byte *) everdef))
06841            goto error_return;
06842 
06843          everdef = ((Elf_External_Verdef *)
06844                    ((bfd_byte *) everdef + iverdefmem.vd_next));
06845        }
06846 
06847       if (default_imported_symver)
06848        {
06849          if (freeidx > maxidx)
06850            maxidx = ++freeidx;
06851          else
06852            freeidx = ++maxidx;
06853        }
06854       elf_tdata (abfd)->verdef = bfd_zalloc2 (abfd, maxidx,
06855                                          sizeof (Elf_Internal_Verdef));
06856       if (elf_tdata (abfd)->verdef == NULL)
06857        goto error_return;
06858 
06859       elf_tdata (abfd)->cverdefs = maxidx;
06860 
06861       everdef = (Elf_External_Verdef *) contents;
06862       iverdefarr = elf_tdata (abfd)->verdef;
06863       for (i = 0; i < hdr->sh_info; i++)
06864        {
06865          Elf_External_Verdaux *everdaux;
06866          Elf_Internal_Verdaux *iverdaux;
06867          unsigned int j;
06868 
06869          _bfd_elf_swap_verdef_in (abfd, everdef, &iverdefmem);
06870 
06871          if ((iverdefmem.vd_ndx & VERSYM_VERSION) == 0)
06872            {
06873 error_return_verdef:
06874              elf_tdata (abfd)->verdef = NULL;
06875              elf_tdata (abfd)->cverdefs = 0;
06876              goto error_return;
06877            }
06878 
06879          iverdef = &iverdefarr[(iverdefmem.vd_ndx & VERSYM_VERSION) - 1];
06880          memcpy (iverdef, &iverdefmem, sizeof (Elf_Internal_Verdef));
06881 
06882          iverdef->vd_bfd = abfd;
06883 
06884          if (iverdef->vd_cnt == 0)
06885            iverdef->vd_auxptr = NULL;
06886          else
06887            {
06888              iverdef->vd_auxptr = bfd_alloc2 (abfd, iverdef->vd_cnt,
06889                                           sizeof (Elf_Internal_Verdaux));
06890              if (iverdef->vd_auxptr == NULL)
06891               goto error_return_verdef;
06892            }
06893 
06894          if (iverdef->vd_aux
06895              > (size_t) (contents_end_aux - (bfd_byte *) everdef))
06896            goto error_return_verdef;
06897 
06898          everdaux = ((Elf_External_Verdaux *)
06899                     ((bfd_byte *) everdef + iverdef->vd_aux));
06900          iverdaux = iverdef->vd_auxptr;
06901          for (j = 0; j < iverdef->vd_cnt; j++, iverdaux++)
06902            {
06903              _bfd_elf_swap_verdaux_in (abfd, everdaux, iverdaux);
06904 
06905              iverdaux->vda_nodename =
06906               bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
06907                                            iverdaux->vda_name);
06908              if (iverdaux->vda_nodename == NULL)
06909               goto error_return_verdef;
06910 
06911              if (j + 1 < iverdef->vd_cnt)
06912               iverdaux->vda_nextptr = iverdaux + 1;
06913              else
06914               iverdaux->vda_nextptr = NULL;
06915 
06916              if (iverdaux->vda_next
06917                 > (size_t) (contents_end_aux - (bfd_byte *) everdaux))
06918               goto error_return_verdef;
06919 
06920              everdaux = ((Elf_External_Verdaux *)
06921                        ((bfd_byte *) everdaux + iverdaux->vda_next));
06922            }
06923 
06924          if (iverdef->vd_cnt)
06925            iverdef->vd_nodename = iverdef->vd_auxptr->vda_nodename;
06926 
06927          if ((size_t) (iverdef - iverdefarr) + 1 < maxidx)
06928            iverdef->vd_nextdef = iverdef + 1;
06929          else
06930            iverdef->vd_nextdef = NULL;
06931 
06932          everdef = ((Elf_External_Verdef *)
06933                    ((bfd_byte *) everdef + iverdef->vd_next));
06934        }
06935 
06936       free (contents);
06937       contents = NULL;
06938     }
06939   else if (default_imported_symver)
06940     {
06941       if (freeidx < 3)
06942        freeidx = 3;
06943       else
06944        freeidx++;
06945 
06946       elf_tdata (abfd)->verdef = bfd_zalloc2 (abfd, freeidx,
06947                                          sizeof (Elf_Internal_Verdef));
06948       if (elf_tdata (abfd)->verdef == NULL)
06949        goto error_return;
06950 
06951       elf_tdata (abfd)->cverdefs = freeidx;
06952     }
06953 
06954   /* Create a default version based on the soname.  */
06955   if (default_imported_symver)
06956     {
06957       Elf_Internal_Verdef *iverdef;
06958       Elf_Internal_Verdaux *iverdaux;
06959 
06960       iverdef = &elf_tdata (abfd)->verdef[freeidx - 1];;
06961 
06962       iverdef->vd_version = VER_DEF_CURRENT;
06963       iverdef->vd_flags = 0;
06964       iverdef->vd_ndx = freeidx;
06965       iverdef->vd_cnt = 1;
06966 
06967       iverdef->vd_bfd = abfd;
06968 
06969       iverdef->vd_nodename = bfd_elf_get_dt_soname (abfd);
06970       if (iverdef->vd_nodename == NULL)
06971        goto error_return_verdef;
06972       iverdef->vd_nextdef = NULL;
06973       iverdef->vd_auxptr = bfd_alloc (abfd, sizeof (Elf_Internal_Verdaux));
06974       if (iverdef->vd_auxptr == NULL)
06975        goto error_return_verdef;
06976 
06977       iverdaux = iverdef->vd_auxptr;
06978       iverdaux->vda_nodename = iverdef->vd_nodename;
06979       iverdaux->vda_nextptr = NULL;
06980     }
06981 
06982   return TRUE;
06983 
06984  error_return:
06985   if (contents != NULL)
06986     free (contents);
06987   return FALSE;
06988 }
06989 
06990 asymbol *
06991 _bfd_elf_make_empty_symbol (bfd *abfd)
06992 {
06993   elf_symbol_type *newsym;
06994   bfd_size_type amt = sizeof (elf_symbol_type);
06995 
06996   newsym = bfd_zalloc (abfd, amt);
06997   if (!newsym)
06998     return NULL;
06999   else
07000     {
07001       newsym->symbol.the_bfd = abfd;
07002       return &newsym->symbol;
07003     }
07004 }
07005 
07006 void
07007 _bfd_elf_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
07008                        asymbol *symbol,
07009                        symbol_info *ret)
07010 {
07011   bfd_symbol_info (symbol, ret);
07012 }
07013 
07014 /* Return whether a symbol name implies a local symbol.  Most targets
07015    use this function for the is_local_label_name entry point, but some
07016    override it.  */
07017 
07018 bfd_boolean
07019 _bfd_elf_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
07020                            const char *name)
07021 {
07022   /* Normal local symbols start with ``.L''.  */
07023   if (name[0] == '.' && name[1] == 'L')
07024     return TRUE;
07025 
07026   /* At least some SVR4 compilers (e.g., UnixWare 2.1 cc) generate
07027      DWARF debugging symbols starting with ``..''.  */
07028   if (name[0] == '.' && name[1] == '.')
07029     return TRUE;
07030 
07031   /* gcc will sometimes generate symbols beginning with ``_.L_'' when
07032      emitting DWARF debugging output.  I suspect this is actually a
07033      small bug in gcc (it calls ASM_OUTPUT_LABEL when it should call
07034      ASM_GENERATE_INTERNAL_LABEL, and this causes the leading
07035      underscore to be emitted on some ELF targets).  For ease of use,
07036      we treat such symbols as local.  */
07037   if (name[0] == '_' && name[1] == '.' && name[2] == 'L' && name[3] == '_')
07038     return TRUE;
07039 
07040   return FALSE;
07041 }
07042 
07043 alent *
07044 _bfd_elf_get_lineno (bfd *abfd ATTRIBUTE_UNUSED,
07045                    asymbol *symbol ATTRIBUTE_UNUSED)
07046 {
07047   abort ();
07048   return NULL;
07049 }
07050 
07051 bfd_boolean
07052 _bfd_elf_set_arch_mach (bfd *abfd,
07053                      enum bfd_architecture arch,
07054                      unsigned long machine)
07055 {
07056   /* If this isn't the right architecture for this backend, and this
07057      isn't the generic backend, fail.  */
07058   if (arch != get_elf_backend_data (abfd)->arch
07059       && arch != bfd_arch_unknown
07060       && get_elf_backend_data (abfd)->arch != bfd_arch_unknown)
07061     return FALSE;
07062 
07063   return bfd_default_set_arch_mach (abfd, arch, machine);
07064 }
07065 
07066 /* Find the function to a particular section and offset,
07067    for error reporting.  */
07068 
07069 static bfd_boolean
07070 elf_find_function (bfd *abfd ATTRIBUTE_UNUSED,
07071                  asection *section,
07072                  asymbol **symbols,
07073                  bfd_vma offset,
07074                  const char **filename_ptr,
07075                  const char **functionname_ptr)
07076 {
07077   const char *filename;
07078   asymbol *func, *file;
07079   bfd_vma low_func;
07080   asymbol **p;
07081   /* ??? Given multiple file symbols, it is impossible to reliably
07082      choose the right file name for global symbols.  File symbols are
07083      local symbols, and thus all file symbols must sort before any
07084      global symbols.  The ELF spec may be interpreted to say that a
07085      file symbol must sort before other local symbols, but currently
07086      ld -r doesn't do this.  So, for ld -r output, it is possible to
07087      make a better choice of file name for local symbols by ignoring
07088      file symbols appearing after a given local symbol.  */
07089   enum { nothing_seen, symbol_seen, file_after_symbol_seen } state;
07090 
07091   filename = NULL;
07092   func = NULL;
07093   file = NULL;
07094   low_func = 0;
07095   state = nothing_seen;
07096 
07097   for (p = symbols; *p != NULL; p++)
07098     {
07099       elf_symbol_type *q;
07100 
07101       q = (elf_symbol_type *) *p;
07102 
07103       switch (ELF_ST_TYPE (q->internal_elf_sym.st_info))
07104        {
07105        default:
07106          break;
07107        case STT_FILE:
07108          file = &q->symbol;
07109          if (state == symbol_seen)
07110            state = file_after_symbol_seen;
07111          continue;
07112        case STT_NOTYPE:
07113        case STT_FUNC:
07114          if (bfd_get_section (&q->symbol) == section
07115              && q->symbol.value >= low_func
07116              && q->symbol.value <= offset)
07117            {
07118              func = (asymbol *) q;
07119              low_func = q->symbol.value;
07120              filename = NULL;
07121              if (file != NULL
07122                 && (ELF_ST_BIND (q->internal_elf_sym.st_info) == STB_LOCAL
07123                     || state != file_after_symbol_seen))
07124               filename = bfd_asymbol_name (file);
07125            }
07126          break;
07127        }
07128       if (state == nothing_seen)
07129        state = symbol_seen;
07130     }
07131 
07132   if (func == NULL)
07133     return FALSE;
07134 
07135   if (filename_ptr)
07136     *filename_ptr = filename;
07137   if (functionname_ptr)
07138     *functionname_ptr = bfd_asymbol_name (func);
07139 
07140   return TRUE;
07141 }
07142 
07143 /* Find the nearest line to a particular section and offset,
07144    for error reporting.  */
07145 
07146 bfd_boolean
07147 _bfd_elf_find_nearest_line (bfd *abfd,
07148                          asection *section,
07149                          asymbol **symbols,
07150                          bfd_vma offset,
07151                          const char **filename_ptr,
07152                          const char **functionname_ptr,
07153                          unsigned int *line_ptr)
07154 {
07155   bfd_boolean found;
07156 
07157   if (_bfd_dwarf1_find_nearest_line (abfd, section, symbols, offset,
07158                                  filename_ptr, functionname_ptr,
07159                                  line_ptr))
07160     {
07161       if (!*functionname_ptr)
07162        elf_find_function (abfd, section, symbols, offset,
07163                         *filename_ptr ? NULL : filename_ptr,
07164                         functionname_ptr);
07165 
07166       return TRUE;
07167     }
07168 
07169   if (_bfd_dwarf2_find_nearest_line (abfd, section, symbols, offset,
07170                                  filename_ptr, functionname_ptr,
07171                                  line_ptr, 0,
07172                                  &elf_tdata (abfd)->dwarf2_find_line_info))
07173     {
07174       if (!*functionname_ptr)
07175        elf_find_function (abfd, section, symbols, offset,
07176                         *filename_ptr ? NULL : filename_ptr,
07177                         functionname_ptr);
07178 
07179       return TRUE;
07180     }
07181 
07182   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
07183                                         &found, filename_ptr,
07184                                         functionname_ptr, line_ptr,
07185                                         &elf_tdata (abfd)->line_info))
07186     return FALSE;
07187   if (found && (*functionname_ptr || *line_ptr))
07188     return TRUE;
07189 
07190   if (symbols == NULL)
07191     return FALSE;
07192 
07193   if (! elf_find_function (abfd, section, symbols, offset,
07194                         filename_ptr, functionname_ptr))
07195     return FALSE;
07196 
07197   *line_ptr = 0;
07198   return TRUE;
07199 }
07200 
07201 /* Find the line for a symbol.  */
07202 
07203 bfd_boolean
07204 _bfd_elf_find_line (bfd *abfd, asymbol **symbols, asymbol *symbol,
07205                   const char **filename_ptr, unsigned int *line_ptr)
07206 {
07207   return _bfd_dwarf2_find_line (abfd, symbols, symbol,
07208                             filename_ptr, line_ptr, 0,
07209                             &elf_tdata (abfd)->dwarf2_find_line_info);
07210 }
07211 
07212 /* After a call to bfd_find_nearest_line, successive calls to
07213    bfd_find_inliner_info can be used to get source information about
07214    each level of function inlining that terminated at the address
07215    passed to bfd_find_nearest_line.  Currently this is only supported
07216    for DWARF2 with appropriate DWARF3 extensions. */
07217 
07218 bfd_boolean
07219 _bfd_elf_find_inliner_info (bfd *abfd,
07220                          const char **filename_ptr,
07221                          const char **functionname_ptr,
07222                          unsigned int *line_ptr)
07223 {
07224   bfd_boolean found;
07225   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
07226                                     functionname_ptr, line_ptr,
07227                                     & elf_tdata (abfd)->dwarf2_find_line_info);
07228   return found;
07229 }
07230 
07231 int
07232 _bfd_elf_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
07233 {
07234   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
07235   int ret = bed->s->sizeof_ehdr;
07236 
07237   if (!info->relocatable)
07238     {
07239       bfd_size_type phdr_size = elf_tdata (abfd)->program_header_size;
07240 
07241       if (phdr_size == (bfd_size_type) -1)
07242        {
07243          struct elf_segment_map *m;
07244 
07245          phdr_size = 0;
07246          for (m = elf_tdata (abfd)->segment_map; m != NULL; m = m->next)
07247            phdr_size += bed->s->sizeof_phdr;
07248 
07249          if (phdr_size == 0)
07250            phdr_size = get_program_header_size (abfd, info);
07251        }
07252 
07253       elf_tdata (abfd)->program_header_size = phdr_size;
07254       ret += phdr_size;
07255     }
07256 
07257   return ret;
07258 }
07259 
07260 bfd_boolean
07261 _bfd_elf_set_section_contents (bfd *abfd,
07262                             sec_ptr section,
07263                             const void *location,
07264                             file_ptr offset,
07265                             bfd_size_type count)
07266 {
07267   Elf_Internal_Shdr *hdr;
07268   bfd_signed_vma pos;
07269 
07270   if (! abfd->output_has_begun
07271       && ! _bfd_elf_compute_section_file_positions (abfd, NULL))
07272     return FALSE;
07273 
07274   hdr = &elf_section_data (section)->this_hdr;
07275   pos = hdr->sh_offset + offset;
07276   if (bfd_seek (abfd, pos, SEEK_SET) != 0
07277       || bfd_bwrite (location, count, abfd) != count)
07278     return FALSE;
07279 
07280   return TRUE;
07281 }
07282 
07283 void
07284 _bfd_elf_no_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
07285                         arelent *cache_ptr ATTRIBUTE_UNUSED,
07286                         Elf_Internal_Rela *dst ATTRIBUTE_UNUSED)
07287 {
07288   abort ();
07289 }
07290 
07291 /* Try to convert a non-ELF reloc into an ELF one.  */
07292 
07293 bfd_boolean
07294 _bfd_elf_validate_reloc (bfd *abfd, arelent *areloc)
07295 {
07296   /* Check whether we really have an ELF howto.  */
07297 
07298   if ((*areloc->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec)
07299     {
07300       bfd_reloc_code_real_type code;
07301       reloc_howto_type *howto;
07302 
07303       /* Alien reloc: Try to determine its type to replace it with an
07304         equivalent ELF reloc.  */
07305 
07306       if (areloc->howto->pc_relative)
07307        {
07308          switch (areloc->howto->bitsize)
07309            {
07310            case 8:
07311              code = BFD_RELOC_8_PCREL;
07312              break;
07313            case 12:
07314              code = BFD_RELOC_12_PCREL;
07315              break;
07316            case 16:
07317              code = BFD_RELOC_16_PCREL;
07318              break;
07319            case 24:
07320              code = BFD_RELOC_24_PCREL;
07321              break;
07322            case 32:
07323              code = BFD_RELOC_32_PCREL;
07324              break;
07325            case 64:
07326              code = BFD_RELOC_64_PCREL;
07327              break;
07328            default:
07329              goto fail;
07330            }
07331 
07332          howto = bfd_reloc_type_lookup (abfd, code);
07333 
07334          if (areloc->howto->pcrel_offset != howto->pcrel_offset)
07335            {
07336              if (howto->pcrel_offset)
07337               areloc->addend += areloc->address;
07338              else
07339               areloc->addend -= areloc->address; /* addend is unsigned!! */
07340            }
07341        }
07342       else
07343        {
07344          switch (areloc->howto->bitsize)
07345            {
07346            case 8:
07347              code = BFD_RELOC_8;
07348              break;
07349            case 14:
07350              code = BFD_RELOC_14;
07351              break;
07352            case 16:
07353              code = BFD_RELOC_16;
07354              break;
07355            case 26:
07356              code = BFD_RELOC_26;
07357              break;
07358            case 32:
07359              code = BFD_RELOC_32;
07360              break;
07361            case 64:
07362              code = BFD_RELOC_64;
07363              break;
07364            default:
07365              goto fail;
07366            }
07367 
07368          howto = bfd_reloc_type_lookup (abfd, code);
07369        }
07370 
07371       if (howto)
07372        areloc->howto = howto;
07373       else
07374        goto fail;
07375     }
07376 
07377   return TRUE;
07378 
07379  fail:
07380   (*_bfd_error_handler)
07381     (_("%B: unsupported relocation type %s"),
07382      abfd, areloc->howto->name);
07383   bfd_set_error (bfd_error_bad_value);
07384   return FALSE;
07385 }
07386 
07387 bfd_boolean
07388 _bfd_elf_close_and_cleanup (bfd *abfd)
07389 {
07390   if (bfd_get_format (abfd) == bfd_object)
07391     {
07392       if (elf_tdata (abfd) != NULL && elf_shstrtab (abfd) != NULL)
07393        _bfd_elf_strtab_free (elf_shstrtab (abfd));
07394       _bfd_dwarf2_cleanup_debug_info (abfd);
07395     }
07396 
07397   return _bfd_generic_close_and_cleanup (abfd);
07398 }
07399 
07400 /* For Rel targets, we encode meaningful data for BFD_RELOC_VTABLE_ENTRY
07401    in the relocation's offset.  Thus we cannot allow any sort of sanity
07402    range-checking to interfere.  There is nothing else to do in processing
07403    this reloc.  */
07404 
07405 bfd_reloc_status_type
07406 _bfd_elf_rel_vtable_reloc_fn
07407   (bfd *abfd ATTRIBUTE_UNUSED, arelent *re ATTRIBUTE_UNUSED,
07408    struct bfd_symbol *symbol ATTRIBUTE_UNUSED,
07409    void *data ATTRIBUTE_UNUSED, asection *is ATTRIBUTE_UNUSED,
07410    bfd *obfd ATTRIBUTE_UNUSED, char **errmsg ATTRIBUTE_UNUSED)
07411 {
07412   return bfd_reloc_ok;
07413 }
07414 
07415 /* Elf core file support.  Much of this only works on native
07416    toolchains, since we rely on knowing the
07417    machine-dependent procfs structure in order to pick
07418    out details about the corefile.  */
07419 
07420 #ifdef HAVE_SYS_PROCFS_H
07421 # include <sys/procfs.h>
07422 #endif
07423 
07424 /* FIXME: this is kinda wrong, but it's what gdb wants.  */
07425 
07426 static int
07427 elfcore_make_pid (bfd *abfd)
07428 {
07429   return ((elf_tdata (abfd)->core_lwpid << 16)
07430          + (elf_tdata (abfd)->core_pid));
07431 }
07432 
07433 /* If there isn't a section called NAME, make one, using
07434    data from SECT.  Note, this function will generate a
07435    reference to NAME, so you shouldn't deallocate or
07436    overwrite it.  */
07437 
07438 static bfd_boolean
07439 elfcore_maybe_make_sect (bfd *abfd, char *name, asection *sect)
07440 {
07441   asection *sect2;
07442 
07443   if (bfd_get_section_by_name (abfd, name) != NULL)
07444     return TRUE;
07445 
07446   sect2 = bfd_make_section_with_flags (abfd, name, sect->flags);
07447   if (sect2 == NULL)
07448     return FALSE;
07449 
07450   sect2->size = sect->size;
07451   sect2->filepos = sect->filepos;
07452   sect2->alignment_power = sect->alignment_power;
07453   return TRUE;
07454 }
07455 
07456 /* Create a pseudosection containing SIZE bytes at FILEPOS.  This
07457    actually creates up to two pseudosections:
07458    - For the single-threaded case, a section named NAME, unless
07459      such a section already exists.
07460    - For the multi-threaded case, a section named "NAME/PID", where
07461      PID is elfcore_make_pid (abfd).
07462    Both pseudosections have identical contents. */
07463 bfd_boolean
07464 _bfd_elfcore_make_pseudosection (bfd *abfd,
07465                              char *name,
07466                              size_t size,
07467                              ufile_ptr filepos)
07468 {
07469   char buf[100];
07470   char *threaded_name;
07471   size_t len;
07472   asection *sect;
07473 
07474   /* Build the section name.  */
07475 
07476   sprintf (buf, "%s/%d", name, elfcore_make_pid (abfd));
07477   len = strlen (buf) + 1;
07478   threaded_name = bfd_alloc (abfd, len);
07479   if (threaded_name == NULL)
07480     return FALSE;
07481   memcpy (threaded_name, buf, len);
07482 
07483   sect = bfd_make_section_anyway_with_flags (abfd, threaded_name,
07484                                         SEC_HAS_CONTENTS);
07485   if (sect == NULL)
07486     return FALSE;
07487   sect->size = size;
07488   sect->filepos = filepos;
07489   sect->alignment_power = 2;
07490 
07491   return elfcore_maybe_make_sect (abfd, name, sect);
07492 }
07493 
07494 /* prstatus_t exists on:
07495      solaris 2.5+
07496      linux 2.[01] + glibc
07497      unixware 4.2
07498 */
07499 
07500 #if defined (HAVE_PRSTATUS_T)
07501 
07502 static bfd_boolean
07503 elfcore_grok_prstatus (bfd *abfd, Elf_Internal_Note *note)
07504 {
07505   size_t size;
07506   int offset;
07507 
07508   if (note->descsz == sizeof (prstatus_t))
07509     {
07510       prstatus_t prstat;
07511 
07512       size = sizeof (prstat.pr_reg);
07513       offset   = offsetof (prstatus_t, pr_reg);
07514       memcpy (&prstat, note->descdata, sizeof (prstat));
07515 
07516       /* Do not overwrite the core signal if it
07517         has already been set by another thread.  */
07518       if (elf_tdata (abfd)->core_signal == 0)
07519        elf_tdata (abfd)->core_signal = prstat.pr_cursig;
07520       elf_tdata (abfd)->core_pid = prstat.pr_pid;
07521 
07522       /* pr_who exists on:
07523         solaris 2.5+
07524         unixware 4.2
07525         pr_who doesn't exist on:
07526         linux 2.[01]
07527         */
07528 #if defined (HAVE_PRSTATUS_T_PR_WHO)
07529       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
07530 #endif
07531     }
07532 #if defined (HAVE_PRSTATUS32_T)
07533   else if (note->descsz == sizeof (prstatus32_t))
07534     {
07535       /* 64-bit host, 32-bit corefile */
07536       prstatus32_t prstat;
07537 
07538       size = sizeof (prstat.pr_reg);
07539       offset   = offsetof (prstatus32_t, pr_reg);
07540       memcpy (&prstat, note->descdata, sizeof (prstat));
07541 
07542       /* Do not overwrite the core signal if it
07543         has already been set by another thread.  */
07544       if (elf_tdata (abfd)->core_signal == 0)
07545        elf_tdata (abfd)->core_signal = prstat.pr_cursig;
07546       elf_tdata (abfd)->core_pid = prstat.pr_pid;
07547 
07548       /* pr_who exists on:
07549         solaris 2.5+
07550         unixware 4.2
07551         pr_who doesn't exist on:
07552         linux 2.[01]
07553         */
07554 #if defined (HAVE_PRSTATUS32_T_PR_WHO)
07555       elf_tdata (abfd)->core_lwpid = prstat.pr_who;
07556 #endif
07557     }
07558 #endif /* HAVE_PRSTATUS32_T */
07559   else
07560     {
07561       /* Fail - we don't know how to handle any other
07562         note size (ie. data object type).  */
07563       return TRUE;
07564     }
07565 
07566   /* Make a ".reg/999" section and a ".reg" section.  */
07567   return _bfd_elfcore_make_pseudosection (abfd, ".reg",
07568                                      size, note->descpos + offset);
07569 }
07570 #endif /* defined (HAVE_PRSTATUS_T) */
07571 
07572 /* Create a pseudosection containing the exact contents of NOTE.  */
07573 static bfd_boolean
07574 elfcore_make_note_pseudosection (bfd *abfd,
07575                              char *name,
07576                              Elf_Internal_Note *note)
07577 {
07578   return _bfd_elfcore_make_pseudosection (abfd, name,
07579                                      note->descsz, note->descpos);
07580 }
07581 
07582 /* There isn't a consistent prfpregset_t across platforms,
07583    but it doesn't matter, because we don't have to pick this
07584    data structure apart.  */
07585 
07586 static bfd_boolean
07587 elfcore_grok_prfpreg (bfd *abfd, Elf_Internal_Note *note)
07588 {
07589   return elfcore_make_note_pseudosection (abfd, ".reg2", note);
07590 }
07591 
07592 /* Linux dumps the Intel SSE regs in a note named "LINUX" with a note
07593    type of 5 (NT_PRXFPREG).  Just include the whole note's contents
07594    literally.  */
07595 
07596 static bfd_boolean
07597 elfcore_grok_prxfpreg (bfd *abfd, Elf_Internal_Note *note)
07598 {
07599   return elfcore_make_note_pseudosection (abfd, ".reg-xfp", note);
07600 }
07601 
07602 #if defined (HAVE_PRPSINFO_T)
07603 typedef prpsinfo_t   elfcore_psinfo_t;
07604 #if defined (HAVE_PRPSINFO32_T)           /* Sparc64 cross Sparc32 */
07605 typedef prpsinfo32_t elfcore_psinfo32_t;
07606 #endif
07607 #endif
07608 
07609 #if defined (HAVE_PSINFO_T)
07610 typedef psinfo_t   elfcore_psinfo_t;
07611 #if defined (HAVE_PSINFO32_T)             /* Sparc64 cross Sparc32 */
07612 typedef psinfo32_t elfcore_psinfo32_t;
07613 #endif
07614 #endif
07615 
07616 /* return a malloc'ed copy of a string at START which is at
07617    most MAX bytes long, possibly without a terminating '\0'.
07618    the copy will always have a terminating '\0'.  */
07619 
07620 char *
07621 _bfd_elfcore_strndup (bfd *abfd, char *start, size_t max)
07622 {
07623   char *dups;
07624   char *end = memchr (start, '\0', max);
07625   size_t len;
07626 
07627   if (end == NULL)
07628     len = max;
07629   else
07630     len = end - start;
07631 
07632   dups = bfd_alloc (abfd, len + 1);
07633   if (dups == NULL)
07634     return NULL;
07635 
07636   memcpy (dups, start, len);
07637   dups[len] = '\0';
07638 
07639   return dups;
07640 }
07641 
07642 #if defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T)
07643 static bfd_boolean
07644 elfcore_grok_psinfo (bfd *abfd, Elf_Internal_Note *note)
07645 {
07646   if (note->descsz == sizeof (elfcore_psinfo_t))
07647     {
07648       elfcore_psinfo_t psinfo;
07649 
07650       memcpy (&psinfo, note->descdata, sizeof (psinfo));
07651 
07652       elf_tdata (abfd)->core_program
07653        = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
07654                             sizeof (psinfo.pr_fname));
07655 
07656       elf_tdata (abfd)->core_command
07657        = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
07658                             sizeof (psinfo.pr_psargs));
07659     }
07660 #if defined (HAVE_PRPSINFO32_T) || defined (HAVE_PSINFO32_T)
07661   else if (note->descsz == sizeof (elfcore_psinfo32_t))
07662     {
07663       /* 64-bit host, 32-bit corefile */
07664       elfcore_psinfo32_t psinfo;
07665 
07666       memcpy (&psinfo, note->descdata, sizeof (psinfo));
07667 
07668       elf_tdata (abfd)->core_program
07669        = _bfd_elfcore_strndup (abfd, psinfo.pr_fname,
07670                             sizeof (psinfo.pr_fname));
07671 
07672       elf_tdata (abfd)->core_command
07673        = _bfd_elfcore_strndup (abfd, psinfo.pr_psargs,
07674                             sizeof (psinfo.pr_psargs));
07675     }
07676 #endif
07677 
07678   else
07679     {
07680       /* Fail - we don't know how to handle any other
07681         note size (ie. data object type).  */
07682       return TRUE;
07683     }
07684 
07685   /* Note that for some reason, a spurious space is tacked
07686      onto the end of the args in some (at least one anyway)
07687      implementations, so strip it off if it exists.  */
07688 
07689   {
07690     char *command = elf_tdata (abfd)->core_command;
07691     int n = strlen (command);
07692 
07693     if (0 < n && command[n - 1] == ' ')
07694       command[n - 1] = '\0';
07695   }
07696 
07697   return TRUE;
07698 }
07699 #endif /* defined (HAVE_PRPSINFO_T) || defined (HAVE_PSINFO_T) */
07700 
07701 #if defined (HAVE_PSTATUS_T)
07702 static bfd_boolean
07703 elfcore_grok_pstatus (bfd *abfd, Elf_Internal_Note *note)
07704 {
07705   if (note->descsz == sizeof (pstatus_t)
07706 #if defined (HAVE_PXSTATUS_T)
07707       || note->descsz == sizeof (pxstatus_t)
07708 #endif
07709       )
07710     {
07711       pstatus_t pstat;
07712 
07713       memcpy (&pstat, note->descdata, sizeof (pstat));
07714 
07715       elf_tdata (abfd)->core_pid = pstat.pr_pid;
07716     }
07717 #if defined (HAVE_PSTATUS32_T)
07718   else if (note->descsz == sizeof (pstatus32_t))
07719     {
07720       /* 64-bit host, 32-bit corefile */
07721       pstatus32_t pstat;
07722 
07723       memcpy (&pstat, note->descdata, sizeof (pstat));
07724 
07725       elf_tdata (abfd)->core_pid = pstat.pr_pid;
07726     }
07727 #endif
07728   /* Could grab some more details from the "representative"
07729      lwpstatus_t in pstat.pr_lwp, but we'll catch it all in an
07730      NT_LWPSTATUS note, presumably.  */
07731 
07732   return TRUE;
07733 }
07734 #endif /* defined (HAVE_PSTATUS_T) */
07735 
07736 #if defined (HAVE_LWPSTATUS_T)
07737 static bfd_boolean
07738 elfcore_grok_lwpstatus (bfd *abfd, Elf_Internal_Note *note)
07739 {
07740   lwpstatus_t lwpstat;
07741   char buf[100];
07742   char *name;
07743   size_t len;
07744   asection *sect;
07745 
07746   if (note->descsz != sizeof (lwpstat)
07747 #if defined (HAVE_LWPXSTATUS_T)
07748       && note->descsz != sizeof (lwpxstatus_t)
07749 #endif
07750       )
07751     return TRUE;
07752 
07753   memcpy (&lwpstat, note->descdata, sizeof (lwpstat));
07754 
07755   elf_tdata (abfd)->core_lwpid = lwpstat.pr_lwpid;
07756   elf_tdata (abfd)->core_signal = lwpstat.pr_cursig;
07757 
07758   /* Make a ".reg/999" section.  */
07759 
07760   sprintf (buf, ".reg/%d", elfcore_make_pid (abfd));
07761   len = strlen (buf) + 1;
07762   name = bfd_alloc (abfd, len);
07763   if (name == NULL)
07764     return FALSE;
07765   memcpy (name, buf, len);
07766 
07767   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
07768   if (sect == NULL)
07769     return FALSE;
07770 
07771 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
07772   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.gregs);
07773   sect->filepos = note->descpos
07774     + offsetof (lwpstatus_t, pr_context.uc_mcontext.gregs);
07775 #endif
07776 
07777 #if defined (HAVE_LWPSTATUS_T_PR_REG)
07778   sect->size = sizeof (lwpstat.pr_reg);
07779   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_reg);
07780 #endif
07781 
07782   sect->alignment_power = 2;
07783 
07784   if (!elfcore_maybe_make_sect (abfd, ".reg", sect))
07785     return FALSE;
07786 
07787   /* Make a ".reg2/999" section */
07788 
07789   sprintf (buf, ".reg2/%d", elfcore_make_pid (abfd));
07790   len = strlen (buf) + 1;
07791   name = bfd_alloc (abfd, len);
07792   if (name == NULL)
07793     return FALSE;
07794   memcpy (name, buf, len);
07795 
07796   sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
07797   if (sect == NULL)
07798     return FALSE;
07799 
07800 #if defined (HAVE_LWPSTATUS_T_PR_CONTEXT)
07801   sect->size = sizeof (lwpstat.pr_context.uc_mcontext.fpregs);
07802   sect->filepos = note->descpos
07803     + offsetof (lwpstatus_t, pr_context.uc_mcontext.fpregs);
07804 #endif
07805 
07806 #if defined (HAVE_LWPSTATUS_T_PR_FPREG)
07807   sect->size = sizeof (lwpstat.pr_fpreg);
07808   sect->filepos = note->descpos + offsetof (lwpstatus_t, pr_fpreg);
07809 #endif
07810 
07811   sect->alignment_power = 2;
07812 
07813   return elfcore_maybe_make_sect (abfd, ".reg2", sect);
07814 }
07815 #endif /* defined (HAVE_LWPSTATUS_T) */
07816 
07817 #if defined (HAVE_WIN32_PSTATUS_T)
07818 static bfd_boolean
07819 elfcore_grok_win32pstatus (bfd *abfd, Elf_Internal_Note *note)
07820 {
07821   char buf[30];
07822   char *name;
07823   size_t len;
07824   asection *sect;
07825   win32_pstatus_t pstatus;
07826 
07827   if (note->descsz < sizeof (pstatus))
07828     return TRUE;
07829 
07830   memcpy (&pstatus, note->descdata, sizeof (pstatus));
07831 
07832   switch (pstatus.data_type)
07833     {
07834     case NOTE_INFO_PROCESS:
07835       /* FIXME: need to add ->core_command.  */
07836       elf_tdata (abfd)->core_signal = pstatus.data.process_info.signal;
07837       elf_tdata (abfd)->core_pid = pstatus.data.process_info.pid;
07838       break;
07839 
07840     case NOTE_INFO_THREAD:
07841       /* Make a ".reg/999" section.  */
07842       sprintf (buf, ".reg/%ld", (long) pstatus.data.thread_info.tid);
07843 
07844       len = strlen (buf) + 1;
07845       name = bfd_alloc (abfd, len);
07846       if (name == NULL)
07847        return FALSE;
07848 
07849       memcpy (name, buf, len);
07850 
07851       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
07852       if (sect == NULL)
07853        return FALSE;
07854 
07855       sect->size = sizeof (pstatus.data.thread_info.thread_context);
07856       sect->filepos = (note->descpos
07857                      + offsetof (struct win32_pstatus,
07858                                data.thread_info.thread_context));
07859       sect->alignment_power = 2;
07860 
07861       if (pstatus.data.thread_info.is_active_thread)
07862        if (! elfcore_maybe_make_sect (abfd, ".reg", sect))
07863          return FALSE;
07864       break;
07865 
07866     case NOTE_INFO_MODULE:
07867       /* Make a ".module/xxxxxxxx" section.  */
07868       sprintf (buf, ".module/%08lx",
07869               (long) pstatus.data.module_info.base_address);
07870 
07871       len = strlen (buf) + 1;
07872       name = bfd_alloc (abfd, len);
07873       if (name == NULL)
07874        return FALSE;
07875 
07876       memcpy (name, buf, len);
07877 
07878       sect = bfd_make_section_anyway_with_flags (abfd, name, SEC_HAS_CONTENTS);
07879 
07880       if (sect == NULL)
07881        return FALSE;
07882 
07883       sect->size = note->descsz;
07884       sect->filepos = note->descpos;
07885       sect->alignment_power = 2;
07886       break;
07887 
07888     default:
07889       return TRUE;
07890     }
07891 
07892   return TRUE;
07893 }
07894 #endif /* HAVE_WIN32_PSTATUS_T */
07895 
07896 static bfd_boolean
07897 elfcore_grok_note (bfd *abfd, Elf_Internal_Note *note)
07898 {
07899   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
07900 
07901   switch (note->type)
07902     {
07903     default:
07904       return TRUE;
07905 
07906     case NT_PRSTATUS:
07907       if (bed->elf_backend_grok_prstatus)
07908        if ((*bed->elf_backend_grok_prstatus) (abfd, note))
07909          return TRUE;
07910 #if defined (HAVE_PRSTATUS_T)
07911       return elfcore_grok_prstatus (abfd, note);
07912 #else
07913