Home | History | Annotate | Download | only in bfd
      1 /* Support for the generic parts of PE/PEI; the common executable parts.
      2    Copyright (C) 1995-2014 Free Software Foundation, Inc.
      3    Written by Cygnus Solutions.
      4 
      5    This file is part of BFD, the Binary File Descriptor library.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program; if not, write to the Free Software
     19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
     20    MA 02110-1301, USA.  */
     21 
     22 
     23 /* Most of this hacked by Steve Chamberlain <sac (at) cygnus.com>.
     24 
     25    PE/PEI rearrangement (and code added): Donn Terry
     26 					  Softway Systems, Inc.  */
     27 
     28 /* Hey look, some documentation [and in a place you expect to find it]!
     29 
     30    The main reference for the pei format is "Microsoft Portable Executable
     31    and Common Object File Format Specification 4.1".  Get it if you need to
     32    do some serious hacking on this code.
     33 
     34    Another reference:
     35    "Peering Inside the PE: A Tour of the Win32 Portable Executable
     36    File Format", MSJ 1994, Volume 9.
     37 
     38    The *sole* difference between the pe format and the pei format is that the
     39    latter has an MSDOS 2.0 .exe header on the front that prints the message
     40    "This app must be run under Windows." (or some such).
     41    (FIXME: Whether that statement is *really* true or not is unknown.
     42    Are there more subtle differences between pe and pei formats?
     43    For now assume there aren't.  If you find one, then for God sakes
     44    document it here!)
     45 
     46    The Microsoft docs use the word "image" instead of "executable" because
     47    the former can also refer to a DLL (shared library).  Confusion can arise
     48    because the `i' in `pei' also refers to "image".  The `pe' format can
     49    also create images (i.e. executables), it's just that to run on a win32
     50    system you need to use the pei format.
     51 
     52    FIXME: Please add more docs here so the next poor fool that has to hack
     53    on this code has a chance of getting something accomplished without
     54    wasting too much time.  */
     55 
     56 /* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64
     57    depending on whether we're compiling for straight PE or PE+.  */
     58 #define COFF_WITH_XX
     59 
     60 #include "sysdep.h"
     61 #include "bfd.h"
     62 #include "libbfd.h"
     63 #include "coff/internal.h"
     64 #include "bfdver.h"
     65 #ifdef HAVE_WCHAR_H
     66 #include <wchar.h>
     67 #endif
     68 #ifdef HAVE_WCTYPE_H
     69 #include <wctype.h>
     70 #endif
     71 
     72 /* NOTE: it's strange to be including an architecture specific header
     73    in what's supposed to be general (to PE/PEI) code.  However, that's
     74    where the definitions are, and they don't vary per architecture
     75    within PE/PEI, so we get them from there.  FIXME: The lack of
     76    variance is an assumption which may prove to be incorrect if new
     77    PE/PEI targets are created.  */
     78 #if defined COFF_WITH_pex64
     79 # include "coff/x86_64.h"
     80 #elif defined COFF_WITH_pep
     81 # include "coff/ia64.h"
     82 #else
     83 # include "coff/i386.h"
     84 #endif
     85 
     86 #include "coff/pe.h"
     87 #include "libcoff.h"
     88 #include "libpei.h"
     89 #include "safe-ctype.h"
     90 
     91 #if defined COFF_WITH_pep || defined COFF_WITH_pex64
     92 # undef AOUTSZ
     93 # define AOUTSZ		PEPAOUTSZ
     94 # define PEAOUTHDR	PEPAOUTHDR
     95 #endif
     96 
     97 #define HighBitSet(val)      ((val) & 0x80000000)
     98 #define SetHighBit(val)      ((val) | 0x80000000)
     99 #define WithoutHighBit(val)  ((val) & 0x7fffffff)
    100 
    101 /* FIXME: This file has various tests of POWERPC_LE_PE.  Those tests
    102    worked when the code was in peicode.h, but no longer work now that
    103    the code is in peigen.c.  PowerPC NT is said to be dead.  If
    104    anybody wants to revive the code, you will have to figure out how
    105    to handle those issues.  */
    106 
    107 void
    109 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
    110 {
    111   SYMENT *ext = (SYMENT *) ext1;
    112   struct internal_syment *in = (struct internal_syment *) in1;
    113 
    114   if (ext->e.e_name[0] == 0)
    115     {
    116       in->_n._n_n._n_zeroes = 0;
    117       in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
    118     }
    119   else
    120     memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
    121 
    122   in->n_value = H_GET_32 (abfd, ext->e_value);
    123   in->n_scnum = H_GET_16 (abfd, ext->e_scnum);
    124 
    125   if (sizeof (ext->e_type) == 2)
    126     in->n_type = H_GET_16 (abfd, ext->e_type);
    127   else
    128     in->n_type = H_GET_32 (abfd, ext->e_type);
    129 
    130   in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
    131   in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
    132 
    133 #ifndef STRICT_PE_FORMAT
    134   /* This is for Gnu-created DLLs.  */
    135 
    136   /* The section symbols for the .idata$ sections have class 0x68
    137      (C_SECTION), which MS documentation indicates is a section
    138      symbol.  Unfortunately, the value field in the symbol is simply a
    139      copy of the .idata section's flags rather than something useful.
    140      When these symbols are encountered, change the value to 0 so that
    141      they will be handled somewhat correctly in the bfd code.  */
    142   if (in->n_sclass == C_SECTION)
    143     {
    144       char namebuf[SYMNMLEN + 1];
    145       const char *name = NULL;
    146 
    147       in->n_value = 0x0;
    148 
    149       /* Create synthetic empty sections as needed.  DJ */
    150       if (in->n_scnum == 0)
    151 	{
    152 	  asection *sec;
    153 
    154 	  name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
    155 	  if (name == NULL)
    156 	    {
    157 	      _bfd_error_handler (_("%B: unable to find name for empty section"),
    158 				  abfd);
    159 	      bfd_set_error (bfd_error_invalid_target);
    160 	      return;
    161 	    }
    162 
    163 	  sec = bfd_get_section_by_name (abfd, name);
    164 	  if (sec != NULL)
    165 	    in->n_scnum = sec->target_index;
    166 	}
    167 
    168       if (in->n_scnum == 0)
    169 	{
    170 	  int unused_section_number = 0;
    171 	  asection *sec;
    172 	  flagword flags;
    173 
    174 	  for (sec = abfd->sections; sec; sec = sec->next)
    175 	    if (unused_section_number <= sec->target_index)
    176 	      unused_section_number = sec->target_index + 1;
    177 
    178 	  if (name == namebuf)
    179 	    {
    180 	      name = (const char *) bfd_alloc (abfd, strlen (namebuf) + 1);
    181 	      if (name == NULL)
    182 		{
    183 		  _bfd_error_handler (_("%B: out of memory creating name for empty section"),
    184 				      abfd);
    185 		  return;
    186 		}
    187 	      strcpy ((char *) name, namebuf);
    188 	    }
    189 
    190 	  flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
    191 	  sec = bfd_make_section_anyway_with_flags (abfd, name, flags);
    192 	  if (sec == NULL)
    193 	    {
    194 	      _bfd_error_handler (_("%B: unable to create fake empty section"),
    195 				  abfd);
    196 	      return;
    197 	    }
    198 
    199 	  sec->vma = 0;
    200 	  sec->lma = 0;
    201 	  sec->size = 0;
    202 	  sec->filepos = 0;
    203 	  sec->rel_filepos = 0;
    204 	  sec->reloc_count = 0;
    205 	  sec->line_filepos = 0;
    206 	  sec->lineno_count = 0;
    207 	  sec->userdata = NULL;
    208 	  sec->next = NULL;
    209 	  sec->alignment_power = 2;
    210 
    211 	  sec->target_index = unused_section_number;
    212 
    213 	  in->n_scnum = unused_section_number;
    214 	}
    215       in->n_sclass = C_STAT;
    216     }
    217 #endif
    218 
    219 #ifdef coff_swap_sym_in_hook
    220   /* This won't work in peigen.c, but since it's for PPC PE, it's not
    221      worth fixing.  */
    222   coff_swap_sym_in_hook (abfd, ext1, in1);
    223 #endif
    224 }
    225 
    226 static bfd_boolean
    227 abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
    228 {
    229   bfd_vma abs_val = * (bfd_vma *) data;
    230 
    231   return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
    232 }
    233 
    234 unsigned int
    235 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
    236 {
    237   struct internal_syment *in = (struct internal_syment *) inp;
    238   SYMENT *ext = (SYMENT *) extp;
    239 
    240   if (in->_n._n_name[0] == 0)
    241     {
    242       H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
    243       H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
    244     }
    245   else
    246     memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
    247 
    248   /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a
    249      symbol.  This is a problem on 64-bit targets where we can generate
    250      absolute symbols with values >= 1^32.  We try to work around this
    251      problem by finding a section whose base address is sufficient to
    252      reduce the absolute value to < 1^32, and then transforming the
    253      symbol into a section relative symbol.  This of course is a hack.  */
    254   if (sizeof (in->n_value) > 4
    255       /* The strange computation of the shift amount is here in order to
    256 	 avoid a compile time warning about the comparison always being
    257 	 false.  It does not matter if this test fails to work as expected
    258 	 as the worst that can happen is that some absolute symbols are
    259 	 needlessly converted into section relative symbols.  */
    260       && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1)
    261       && in->n_scnum == -1)
    262     {
    263       asection * sec;
    264 
    265       sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
    266       if (sec)
    267 	{
    268 	  in->n_value -= sec->vma;
    269 	  in->n_scnum = sec->target_index;
    270 	}
    271       /* else: FIXME: The value is outside the range of any section.  This
    272 	 happens for __image_base__ and __ImageBase and maybe some other
    273 	 symbols as well.  We should find a way to handle these values.  */
    274     }
    275 
    276   H_PUT_32 (abfd, in->n_value, ext->e_value);
    277   H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
    278 
    279   if (sizeof (ext->e_type) == 2)
    280     H_PUT_16 (abfd, in->n_type, ext->e_type);
    281   else
    282     H_PUT_32 (abfd, in->n_type, ext->e_type);
    283 
    284   H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
    285   H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
    286 
    287   return SYMESZ;
    288 }
    289 
    290 void
    291 _bfd_XXi_swap_aux_in (bfd *	abfd,
    292 		      void *	ext1,
    293 		      int       type,
    294 		      int       in_class,
    295 		      int	indx ATTRIBUTE_UNUSED,
    296 		      int	numaux ATTRIBUTE_UNUSED,
    297 		      void * 	in1)
    298 {
    299   AUXENT *ext = (AUXENT *) ext1;
    300   union internal_auxent *in = (union internal_auxent *) in1;
    301 
    302   /* PR 17521: Make sure that all fields in the aux structure
    303      are initialised.  */
    304   memset (in, 0, sizeof * in);
    305   switch (in_class)
    306     {
    307     case C_FILE:
    308       if (ext->x_file.x_fname[0] == 0)
    309 	{
    310 	  in->x_file.x_n.x_zeroes = 0;
    311 	  in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
    312 	}
    313       else
    314 	memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
    315       return;
    316 
    317     case C_STAT:
    318     case C_LEAFSTAT:
    319     case C_HIDDEN:
    320       if (type == T_NULL)
    321 	{
    322 	  in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
    323 	  in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
    324 	  in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
    325 	  in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
    326 	  in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
    327 	  in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
    328 	  return;
    329 	}
    330       break;
    331     }
    332 
    333   in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
    334   in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
    335 
    336   if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
    337       || ISTAG (in_class))
    338     {
    339       in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
    340       in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
    341     }
    342   else
    343     {
    344       in->x_sym.x_fcnary.x_ary.x_dimen[0] =
    345 	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
    346       in->x_sym.x_fcnary.x_ary.x_dimen[1] =
    347 	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
    348       in->x_sym.x_fcnary.x_ary.x_dimen[2] =
    349 	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
    350       in->x_sym.x_fcnary.x_ary.x_dimen[3] =
    351 	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
    352     }
    353 
    354   if (ISFCN (type))
    355     {
    356       in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
    357     }
    358   else
    359     {
    360       in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
    361       in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
    362     }
    363 }
    364 
    365 unsigned int
    366 _bfd_XXi_swap_aux_out (bfd *  abfd,
    367 		       void * inp,
    368 		       int    type,
    369 		       int    in_class,
    370 		       int    indx ATTRIBUTE_UNUSED,
    371 		       int    numaux ATTRIBUTE_UNUSED,
    372 		       void * extp)
    373 {
    374   union internal_auxent *in = (union internal_auxent *) inp;
    375   AUXENT *ext = (AUXENT *) extp;
    376 
    377   memset (ext, 0, AUXESZ);
    378 
    379   switch (in_class)
    380     {
    381     case C_FILE:
    382       if (in->x_file.x_fname[0] == 0)
    383 	{
    384 	  H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
    385 	  H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
    386 	}
    387       else
    388 	memcpy (ext->x_file.x_fname, in->x_file.x_fname, FILNMLEN);
    389 
    390       return AUXESZ;
    391 
    392     case C_STAT:
    393     case C_LEAFSTAT:
    394     case C_HIDDEN:
    395       if (type == T_NULL)
    396 	{
    397 	  PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
    398 	  PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
    399 	  PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
    400 	  H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
    401 	  H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
    402 	  H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
    403 	  return AUXESZ;
    404 	}
    405       break;
    406     }
    407 
    408   H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
    409   H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
    410 
    411   if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
    412       || ISTAG (in_class))
    413     {
    414       PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr,  ext);
    415       PUT_FCN_ENDNDX  (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
    416     }
    417   else
    418     {
    419       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
    420 		ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
    421       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
    422 		ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
    423       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
    424 		ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
    425       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
    426 		ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
    427     }
    428 
    429   if (ISFCN (type))
    430     H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
    431   else
    432     {
    433       PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
    434       PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
    435     }
    436 
    437   return AUXESZ;
    438 }
    439 
    440 void
    441 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
    442 {
    443   LINENO *ext = (LINENO *) ext1;
    444   struct internal_lineno *in = (struct internal_lineno *) in1;
    445 
    446   in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
    447   in->l_lnno = GET_LINENO_LNNO (abfd, ext);
    448 }
    449 
    450 unsigned int
    451 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
    452 {
    453   struct internal_lineno *in = (struct internal_lineno *) inp;
    454   struct external_lineno *ext = (struct external_lineno *) outp;
    455   H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
    456 
    457   PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
    458   return LINESZ;
    459 }
    460 
    461 void
    462 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
    463 			  void * aouthdr_ext1,
    464 			  void * aouthdr_int1)
    465 {
    466   PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
    467   AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
    468   struct internal_aouthdr *aouthdr_int
    469     = (struct internal_aouthdr *) aouthdr_int1;
    470   struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
    471 
    472   aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
    473   aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
    474   aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
    475   aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
    476   aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
    477   aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
    478   aouthdr_int->text_start =
    479     GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
    480 
    481 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    482   /* PE32+ does not have data_start member!  */
    483   aouthdr_int->data_start =
    484     GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
    485   a->BaseOfData = aouthdr_int->data_start;
    486 #endif
    487 
    488   a->Magic = aouthdr_int->magic;
    489   a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
    490   a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
    491   a->SizeOfCode = aouthdr_int->tsize ;
    492   a->SizeOfInitializedData = aouthdr_int->dsize ;
    493   a->SizeOfUninitializedData = aouthdr_int->bsize ;
    494   a->AddressOfEntryPoint = aouthdr_int->entry;
    495   a->BaseOfCode = aouthdr_int->text_start;
    496   a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
    497   a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
    498   a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
    499   a->MajorOperatingSystemVersion =
    500     H_GET_16 (abfd, src->MajorOperatingSystemVersion);
    501   a->MinorOperatingSystemVersion =
    502     H_GET_16 (abfd, src->MinorOperatingSystemVersion);
    503   a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
    504   a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
    505   a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
    506   a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
    507   a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
    508   a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
    509   a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
    510   a->CheckSum = H_GET_32 (abfd, src->CheckSum);
    511   a->Subsystem = H_GET_16 (abfd, src->Subsystem);
    512   a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
    513   a->SizeOfStackReserve =
    514     GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
    515   a->SizeOfStackCommit =
    516     GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
    517   a->SizeOfHeapReserve =
    518     GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
    519   a->SizeOfHeapCommit =
    520     GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
    521   a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
    522   a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
    523 
    524   {
    525     int idx;
    526 
    527     /* PR 17512: Corrupt PE binaries can cause seg-faults.  */
    528     if (a->NumberOfRvaAndSizes > IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
    529       {
    530 	(*_bfd_error_handler)
    531 	  (_("%B: aout header specifies an invalid number of data-directory entries: %d"),
    532 	   abfd, a->NumberOfRvaAndSizes);
    533 	/* Paranoia: If the number is corrupt, then assume that the
    534 	   actual entries themselves might be corrupt as well.  */
    535 	a->NumberOfRvaAndSizes = 0;
    536       }
    537 
    538     for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++)
    539       {
    540         /* If data directory is empty, rva also should be 0.  */
    541 	int size =
    542 	  H_GET_32 (abfd, src->DataDirectory[idx][1]);
    543 
    544 	a->DataDirectory[idx].Size = size;
    545 
    546 	if (size)
    547 	  a->DataDirectory[idx].VirtualAddress =
    548 	    H_GET_32 (abfd, src->DataDirectory[idx][0]);
    549 	else
    550 	  a->DataDirectory[idx].VirtualAddress = 0;
    551       }
    552 
    553     while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
    554       {
    555 	a->DataDirectory[idx].Size = 0;
    556 	a->DataDirectory[idx].VirtualAddress = 0;
    557 	idx ++;
    558       }
    559   }
    560 
    561   if (aouthdr_int->entry)
    562     {
    563       aouthdr_int->entry += a->ImageBase;
    564 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    565       aouthdr_int->entry &= 0xffffffff;
    566 #endif
    567     }
    568 
    569   if (aouthdr_int->tsize)
    570     {
    571       aouthdr_int->text_start += a->ImageBase;
    572 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    573       aouthdr_int->text_start &= 0xffffffff;
    574 #endif
    575     }
    576 
    577 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    578   /* PE32+ does not have data_start member!  */
    579   if (aouthdr_int->dsize)
    580     {
    581       aouthdr_int->data_start += a->ImageBase;
    582       aouthdr_int->data_start &= 0xffffffff;
    583     }
    584 #endif
    585 
    586 #ifdef POWERPC_LE_PE
    587   /* These three fields are normally set up by ppc_relocate_section.
    588      In the case of reading a file in, we can pick them up from the
    589      DataDirectory.  */
    590   first_thunk_address = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress;
    591   thunk_size = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size;
    592   import_table_size = a->DataDirectory[PE_IMPORT_TABLE].Size;
    593 #endif
    594 }
    595 
    596 /* A support function for below.  */
    597 
    598 static void
    599 add_data_entry (bfd * abfd,
    600 		struct internal_extra_pe_aouthdr *aout,
    601 		int idx,
    602 		char *name,
    603 		bfd_vma base)
    604 {
    605   asection *sec = bfd_get_section_by_name (abfd, name);
    606 
    607   /* Add import directory information if it exists.  */
    608   if ((sec != NULL)
    609       && (coff_section_data (abfd, sec) != NULL)
    610       && (pei_section_data (abfd, sec) != NULL))
    611     {
    612       /* If data directory is empty, rva also should be 0.  */
    613       int size = pei_section_data (abfd, sec)->virt_size;
    614       aout->DataDirectory[idx].Size = size;
    615 
    616       if (size)
    617 	{
    618 	  aout->DataDirectory[idx].VirtualAddress =
    619 	    (sec->vma - base) & 0xffffffff;
    620 	  sec->flags |= SEC_DATA;
    621 	}
    622     }
    623 }
    624 
    625 unsigned int
    626 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
    627 {
    628   struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
    629   pe_data_type *pe = pe_data (abfd);
    630   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
    631   PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
    632   bfd_vma sa, fa, ib;
    633   IMAGE_DATA_DIRECTORY idata2, idata5, tls;
    634 
    635   sa = extra->SectionAlignment;
    636   fa = extra->FileAlignment;
    637   ib = extra->ImageBase;
    638 
    639   idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
    640   idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
    641   tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
    642 
    643   if (aouthdr_in->tsize)
    644     {
    645       aouthdr_in->text_start -= ib;
    646 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    647       aouthdr_in->text_start &= 0xffffffff;
    648 #endif
    649     }
    650 
    651   if (aouthdr_in->dsize)
    652     {
    653       aouthdr_in->data_start -= ib;
    654 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    655       aouthdr_in->data_start &= 0xffffffff;
    656 #endif
    657     }
    658 
    659   if (aouthdr_in->entry)
    660     {
    661       aouthdr_in->entry -= ib;
    662 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    663       aouthdr_in->entry &= 0xffffffff;
    664 #endif
    665     }
    666 
    667 #define FA(x) (((x) + fa -1 ) & (- fa))
    668 #define SA(x) (((x) + sa -1 ) & (- sa))
    669 
    670   /* We like to have the sizes aligned.  */
    671   aouthdr_in->bsize = FA (aouthdr_in->bsize);
    672 
    673   extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
    674 
    675   add_data_entry (abfd, extra, 0, ".edata", ib);
    676   add_data_entry (abfd, extra, 2, ".rsrc", ib);
    677   add_data_entry (abfd, extra, 3, ".pdata", ib);
    678 
    679   /* In theory we do not need to call add_data_entry for .idata$2 or
    680      .idata$5.  It will be done in bfd_coff_final_link where all the
    681      required information is available.  If however, we are not going
    682      to perform a final link, eg because we have been invoked by objcopy
    683      or strip, then we need to make sure that these Data Directory
    684      entries are initialised properly.
    685 
    686      So - we copy the input values into the output values, and then, if
    687      a final link is going to be performed, it can overwrite them.  */
    688   extra->DataDirectory[PE_IMPORT_TABLE]  = idata2;
    689   extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
    690   extra->DataDirectory[PE_TLS_TABLE] = tls;
    691 
    692   if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
    693     /* Until other .idata fixes are made (pending patch), the entry for
    694        .idata is needed for backwards compatibility.  FIXME.  */
    695     add_data_entry (abfd, extra, 1, ".idata", ib);
    696 
    697   /* For some reason, the virtual size (which is what's set by
    698      add_data_entry) for .reloc is not the same as the size recorded
    699      in this slot by MSVC; it doesn't seem to cause problems (so far),
    700      but since it's the best we've got, use it.  It does do the right
    701      thing for .pdata.  */
    702   if (pe->has_reloc_section)
    703     add_data_entry (abfd, extra, 5, ".reloc", ib);
    704 
    705   {
    706     asection *sec;
    707     bfd_vma hsize = 0;
    708     bfd_vma dsize = 0;
    709     bfd_vma isize = 0;
    710     bfd_vma tsize = 0;
    711 
    712     for (sec = abfd->sections; sec; sec = sec->next)
    713       {
    714 	int rounded = FA (sec->size);
    715 
    716 	/* The first non-zero section filepos is the header size.
    717 	   Sections without contents will have a filepos of 0.  */
    718 	if (hsize == 0)
    719 	  hsize = sec->filepos;
    720 	if (sec->flags & SEC_DATA)
    721 	  dsize += rounded;
    722 	if (sec->flags & SEC_CODE)
    723 	  tsize += rounded;
    724 	/* The image size is the total VIRTUAL size (which is what is
    725 	   in the virt_size field).  Files have been seen (from MSVC
    726 	   5.0 link.exe) where the file size of the .data segment is
    727 	   quite small compared to the virtual size.  Without this
    728 	   fix, strip munges the file.
    729 
    730 	   FIXME: We need to handle holes between sections, which may
    731 	   happpen when we covert from another format.  We just use
    732 	   the virtual address and virtual size of the last section
    733 	   for the image size.  */
    734 	if (coff_section_data (abfd, sec) != NULL
    735 	    && pei_section_data (abfd, sec) != NULL)
    736 	  isize = (sec->vma - extra->ImageBase
    737 		   + SA (FA (pei_section_data (abfd, sec)->virt_size)));
    738       }
    739 
    740     aouthdr_in->dsize = dsize;
    741     aouthdr_in->tsize = tsize;
    742     extra->SizeOfHeaders = hsize;
    743     extra->SizeOfImage = isize;
    744   }
    745 
    746   H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
    747 
    748 /* e.g. 219510000 is linker version 2.19  */
    749 #define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
    750 
    751   /* This piece of magic sets the "linker version" field to
    752      LINKER_VERSION.  */
    753   H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
    754 	    aouthdr_out->standard.vstamp);
    755 
    756   PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
    757   PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
    758   PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
    759   PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
    760   PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
    761 			  aouthdr_out->standard.text_start);
    762 
    763 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
    764   /* PE32+ does not have data_start member!  */
    765   PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
    766 			  aouthdr_out->standard.data_start);
    767 #endif
    768 
    769   PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
    770   H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
    771   H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
    772   H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
    773 	    aouthdr_out->MajorOperatingSystemVersion);
    774   H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
    775 	    aouthdr_out->MinorOperatingSystemVersion);
    776   H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
    777   H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
    778   H_PUT_16 (abfd, extra->MajorSubsystemVersion,
    779 	    aouthdr_out->MajorSubsystemVersion);
    780   H_PUT_16 (abfd, extra->MinorSubsystemVersion,
    781 	    aouthdr_out->MinorSubsystemVersion);
    782   H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
    783   H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
    784   H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
    785   H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
    786   H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
    787   H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
    788   PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
    789 				    aouthdr_out->SizeOfStackReserve);
    790   PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
    791 				   aouthdr_out->SizeOfStackCommit);
    792   PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
    793 				   aouthdr_out->SizeOfHeapReserve);
    794   PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
    795 				  aouthdr_out->SizeOfHeapCommit);
    796   H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
    797   H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
    798 	    aouthdr_out->NumberOfRvaAndSizes);
    799   {
    800     int idx;
    801 
    802     for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
    803       {
    804 	H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
    805 		  aouthdr_out->DataDirectory[idx][0]);
    806 	H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
    807 		  aouthdr_out->DataDirectory[idx][1]);
    808       }
    809   }
    810 
    811   return AOUTSZ;
    812 }
    813 
    814 unsigned int
    815 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
    816 {
    817   int idx;
    818   struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
    819   struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
    820 
    821   if (pe_data (abfd)->has_reloc_section
    822       || pe_data (abfd)->dont_strip_reloc)
    823     filehdr_in->f_flags &= ~F_RELFLG;
    824 
    825   if (pe_data (abfd)->dll)
    826     filehdr_in->f_flags |= F_DLL;
    827 
    828   filehdr_in->pe.e_magic    = DOSMAGIC;
    829   filehdr_in->pe.e_cblp     = 0x90;
    830   filehdr_in->pe.e_cp       = 0x3;
    831   filehdr_in->pe.e_crlc     = 0x0;
    832   filehdr_in->pe.e_cparhdr  = 0x4;
    833   filehdr_in->pe.e_minalloc = 0x0;
    834   filehdr_in->pe.e_maxalloc = 0xffff;
    835   filehdr_in->pe.e_ss       = 0x0;
    836   filehdr_in->pe.e_sp       = 0xb8;
    837   filehdr_in->pe.e_csum     = 0x0;
    838   filehdr_in->pe.e_ip       = 0x0;
    839   filehdr_in->pe.e_cs       = 0x0;
    840   filehdr_in->pe.e_lfarlc   = 0x40;
    841   filehdr_in->pe.e_ovno     = 0x0;
    842 
    843   for (idx = 0; idx < 4; idx++)
    844     filehdr_in->pe.e_res[idx] = 0x0;
    845 
    846   filehdr_in->pe.e_oemid   = 0x0;
    847   filehdr_in->pe.e_oeminfo = 0x0;
    848 
    849   for (idx = 0; idx < 10; idx++)
    850     filehdr_in->pe.e_res2[idx] = 0x0;
    851 
    852   filehdr_in->pe.e_lfanew = 0x80;
    853 
    854   /* This next collection of data are mostly just characters.  It
    855      appears to be constant within the headers put on NT exes.  */
    856   filehdr_in->pe.dos_message[0]  = 0x0eba1f0e;
    857   filehdr_in->pe.dos_message[1]  = 0xcd09b400;
    858   filehdr_in->pe.dos_message[2]  = 0x4c01b821;
    859   filehdr_in->pe.dos_message[3]  = 0x685421cd;
    860   filehdr_in->pe.dos_message[4]  = 0x70207369;
    861   filehdr_in->pe.dos_message[5]  = 0x72676f72;
    862   filehdr_in->pe.dos_message[6]  = 0x63206d61;
    863   filehdr_in->pe.dos_message[7]  = 0x6f6e6e61;
    864   filehdr_in->pe.dos_message[8]  = 0x65622074;
    865   filehdr_in->pe.dos_message[9]  = 0x6e757220;
    866   filehdr_in->pe.dos_message[10] = 0x206e6920;
    867   filehdr_in->pe.dos_message[11] = 0x20534f44;
    868   filehdr_in->pe.dos_message[12] = 0x65646f6d;
    869   filehdr_in->pe.dos_message[13] = 0x0a0d0d2e;
    870   filehdr_in->pe.dos_message[14] = 0x24;
    871   filehdr_in->pe.dos_message[15] = 0x0;
    872   filehdr_in->pe.nt_signature = NT_SIGNATURE;
    873 
    874   H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
    875   H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
    876 
    877   /* Only use a real timestamp if the option was chosen.  */
    878   if ((pe_data (abfd)->insert_timestamp))
    879     H_PUT_32 (abfd, time (0), filehdr_out->f_timdat);
    880 
    881   PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
    882 		      filehdr_out->f_symptr);
    883   H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
    884   H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
    885   H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
    886 
    887   /* Put in extra dos header stuff.  This data remains essentially
    888      constant, it just has to be tacked on to the beginning of all exes
    889      for NT.  */
    890   H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
    891   H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
    892   H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
    893   H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
    894   H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
    895   H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
    896   H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
    897   H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
    898   H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
    899   H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
    900   H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
    901   H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
    902   H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
    903   H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
    904 
    905   for (idx = 0; idx < 4; idx++)
    906     H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
    907 
    908   H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
    909   H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
    910 
    911   for (idx = 0; idx < 10; idx++)
    912     H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
    913 
    914   H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
    915 
    916   for (idx = 0; idx < 16; idx++)
    917     H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx],
    918 	      filehdr_out->dos_message[idx]);
    919 
    920   /* Also put in the NT signature.  */
    921   H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
    922 
    923   return FILHSZ;
    924 }
    925 
    926 unsigned int
    927 _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
    928 {
    929   struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
    930   FILHDR *filehdr_out = (FILHDR *) out;
    931 
    932   H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
    933   H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
    934   H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
    935   PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
    936   H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
    937   H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
    938   H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
    939 
    940   return FILHSZ;
    941 }
    942 
    943 unsigned int
    944 _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
    945 {
    946   struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
    947   SCNHDR *scnhdr_ext = (SCNHDR *) out;
    948   unsigned int ret = SCNHSZ;
    949   bfd_vma ps;
    950   bfd_vma ss;
    951 
    952   memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
    953 
    954   PUT_SCNHDR_VADDR (abfd,
    955 		    ((scnhdr_int->s_vaddr
    956 		      - pe_data (abfd)->pe_opthdr.ImageBase)
    957 		     & 0xffffffff),
    958 		    scnhdr_ext->s_vaddr);
    959 
    960   /* NT wants the size data to be rounded up to the next
    961      NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
    962      sometimes).  */
    963   if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
    964     {
    965       if (bfd_pei_p (abfd))
    966 	{
    967 	  ps = scnhdr_int->s_size;
    968 	  ss = 0;
    969 	}
    970       else
    971        {
    972          ps = 0;
    973          ss = scnhdr_int->s_size;
    974        }
    975     }
    976   else
    977     {
    978       if (bfd_pei_p (abfd))
    979 	ps = scnhdr_int->s_paddr;
    980       else
    981 	ps = 0;
    982 
    983       ss = scnhdr_int->s_size;
    984     }
    985 
    986   PUT_SCNHDR_SIZE (abfd, ss,
    987 		   scnhdr_ext->s_size);
    988 
    989   /* s_paddr in PE is really the virtual size.  */
    990   PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
    991 
    992   PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
    993 		     scnhdr_ext->s_scnptr);
    994   PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
    995 		     scnhdr_ext->s_relptr);
    996   PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
    997 		      scnhdr_ext->s_lnnoptr);
    998 
    999   {
   1000     /* Extra flags must be set when dealing with PE.  All sections should also
   1001        have the IMAGE_SCN_MEM_READ (0x40000000) flag set.  In addition, the
   1002        .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
   1003        sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
   1004        (this is especially important when dealing with the .idata section since
   1005        the addresses for routines from .dlls must be overwritten).  If .reloc
   1006        section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
   1007        (0x02000000).  Also, the resource data should also be read and
   1008        writable.  */
   1009 
   1010     /* FIXME: Alignment is also encoded in this field, at least on PPC and
   1011        ARM-WINCE.  Although - how do we get the original alignment field
   1012        back ?  */
   1013 
   1014     typedef struct
   1015     {
   1016       const char * 	section_name;
   1017       unsigned long	must_have;
   1018     }
   1019     pe_required_section_flags;
   1020 
   1021     pe_required_section_flags known_sections [] =
   1022       {
   1023 	{ ".arch",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
   1024 	{ ".bss",   IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
   1025 	{ ".data",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
   1026 	{ ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
   1027 	{ ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
   1028 	{ ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
   1029 	{ ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
   1030 	{ ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
   1031 	{ ".rsrc",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
   1032 	{ ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
   1033 	{ ".tls",   IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
   1034 	{ ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
   1035 	{ NULL, 0}
   1036       };
   1037 
   1038     pe_required_section_flags * p;
   1039 
   1040     /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
   1041        we know exactly what this specific section wants so we remove it
   1042        and then allow the must_have field to add it back in if necessary.
   1043        However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
   1044        default WP_TEXT file flag has been cleared.  WP_TEXT may be cleared
   1045        by ld --enable-auto-import (if auto-import is actually needed),
   1046        by ld --omagic, or by obcopy --writable-text.  */
   1047 
   1048     for (p = known_sections; p->section_name; p++)
   1049       if (strcmp (scnhdr_int->s_name, p->section_name) == 0)
   1050 	{
   1051 	  if (strcmp (scnhdr_int->s_name, ".text")
   1052 	      || (bfd_get_file_flags (abfd) & WP_TEXT))
   1053 	    scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
   1054 	  scnhdr_int->s_flags |= p->must_have;
   1055 	  break;
   1056 	}
   1057 
   1058     H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
   1059   }
   1060 
   1061   if (coff_data (abfd)->link_info
   1062       && ! coff_data (abfd)->link_info->relocatable
   1063       && ! coff_data (abfd)->link_info->shared
   1064       && strcmp (scnhdr_int->s_name, ".text") == 0)
   1065     {
   1066       /* By inference from looking at MS output, the 32 bit field
   1067 	 which is the combination of the number_of_relocs and
   1068 	 number_of_linenos is used for the line number count in
   1069 	 executables.  A 16-bit field won't do for cc1.  The MS
   1070 	 document says that the number of relocs is zero for
   1071 	 executables, but the 17-th bit has been observed to be there.
   1072 	 Overflow is not an issue: a 4G-line program will overflow a
   1073 	 bunch of other fields long before this!  */
   1074       H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
   1075       H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
   1076     }
   1077   else
   1078     {
   1079       if (scnhdr_int->s_nlnno <= 0xffff)
   1080 	H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
   1081       else
   1082 	{
   1083 	  (*_bfd_error_handler) (_("%s: line number overflow: 0x%lx > 0xffff"),
   1084 				 bfd_get_filename (abfd),
   1085 				 scnhdr_int->s_nlnno);
   1086 	  bfd_set_error (bfd_error_file_truncated);
   1087 	  H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
   1088 	  ret = 0;
   1089 	}
   1090 
   1091       /* Although we could encode 0xffff relocs here, we do not, to be
   1092          consistent with other parts of bfd. Also it lets us warn, as
   1093          we should never see 0xffff here w/o having the overflow flag
   1094          set.  */
   1095       if (scnhdr_int->s_nreloc < 0xffff)
   1096 	H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
   1097       else
   1098 	{
   1099 	  /* PE can deal with large #s of relocs, but not here.  */
   1100 	  H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
   1101 	  scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
   1102 	  H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
   1103 	}
   1104     }
   1105   return ret;
   1106 }
   1107 
   1108 void
   1109 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
   1110 {
   1111   struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
   1112   struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
   1113 
   1114   in->Characteristics = H_GET_32(abfd, ext->Characteristics);
   1115   in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
   1116   in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
   1117   in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
   1118   in->Type = H_GET_32(abfd, ext->Type);
   1119   in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
   1120   in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
   1121   in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
   1122 }
   1123 
   1124 unsigned int
   1125 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
   1126 {
   1127   struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
   1128   struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
   1129 
   1130   H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
   1131   H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
   1132   H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
   1133   H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
   1134   H_PUT_32(abfd, in->Type, ext->Type);
   1135   H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
   1136   H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
   1137   H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
   1138 
   1139   return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
   1140 }
   1141 
   1142 static CODEVIEW_INFO *
   1143 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo)
   1144 {
   1145   char buffer[256+1];
   1146 
   1147   if (bfd_seek (abfd, where, SEEK_SET) != 0)
   1148     return NULL;
   1149 
   1150   if (bfd_bread (buffer, 256, abfd) < 4)
   1151     return NULL;
   1152 
   1153   /* Ensure null termination of filename.  */
   1154   buffer[256] = '\0';
   1155 
   1156   cvinfo->CVSignature = H_GET_32(abfd, buffer);
   1157   cvinfo->Age = 0;
   1158 
   1159   if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
   1160       && (length > sizeof (CV_INFO_PDB70)))
   1161     {
   1162       CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
   1163 
   1164       cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
   1165 
   1166       /* A GUID consists of 4,2,2 byte values in little-endian order, followed
   1167          by 8 single bytes.  Byte swap them so we can conveniently treat the GUID
   1168          as 16 bytes in big-endian order.  */
   1169       bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
   1170       bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
   1171       bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
   1172       memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
   1173 
   1174       cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
   1175       // cvinfo->PdbFileName = cvinfo70->PdbFileName;
   1176 
   1177       return cvinfo;
   1178     }
   1179   else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
   1180            && (length > sizeof (CV_INFO_PDB20)))
   1181     {
   1182       CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
   1183       cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
   1184       memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
   1185       cvinfo->SignatureLength = 4;
   1186       // cvinfo->PdbFileName = cvinfo20->PdbFileName;
   1187 
   1188       return cvinfo;
   1189     }
   1190 
   1191   return NULL;
   1192 }
   1193 
   1194 unsigned int
   1195 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo)
   1196 {
   1197   unsigned int size = sizeof (CV_INFO_PDB70) + 1;
   1198   CV_INFO_PDB70 *cvinfo70;
   1199   char buffer[size];
   1200 
   1201   if (bfd_seek (abfd, where, SEEK_SET) != 0)
   1202     return 0;
   1203 
   1204   cvinfo70 = (CV_INFO_PDB70 *) buffer;
   1205   H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
   1206 
   1207   /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
   1208      in little-endian order, followed by 8 single bytes.  */
   1209   bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
   1210   bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
   1211   bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
   1212   memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
   1213 
   1214   H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
   1215   cvinfo70->PdbFileName[0] = '\0';
   1216 
   1217   if (bfd_bwrite (buffer, size, abfd) != size)
   1218     return 0;
   1219 
   1220   return size;
   1221 }
   1222 
   1223 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
   1224 {
   1225   N_("Export Directory [.edata (or where ever we found it)]"),
   1226   N_("Import Directory [parts of .idata]"),
   1227   N_("Resource Directory [.rsrc]"),
   1228   N_("Exception Directory [.pdata]"),
   1229   N_("Security Directory"),
   1230   N_("Base Relocation Directory [.reloc]"),
   1231   N_("Debug Directory"),
   1232   N_("Description Directory"),
   1233   N_("Special Directory"),
   1234   N_("Thread Storage Directory [.tls]"),
   1235   N_("Load Configuration Directory"),
   1236   N_("Bound Import Directory"),
   1237   N_("Import Address Table Directory"),
   1238   N_("Delay Import Directory"),
   1239   N_("CLR Runtime Header"),
   1240   N_("Reserved")
   1241 };
   1242 
   1243 #ifdef POWERPC_LE_PE
   1244 /* The code for the PPC really falls in the "architecture dependent"
   1245    category.  However, it's not clear that anyone will ever care, so
   1246    we're ignoring the issue for now; if/when PPC matters, some of this
   1247    may need to go into peicode.h, or arguments passed to enable the
   1248    PPC- specific code.  */
   1249 #endif
   1250 
   1251 static bfd_boolean
   1252 pe_print_idata (bfd * abfd, void * vfile)
   1253 {
   1254   FILE *file = (FILE *) vfile;
   1255   bfd_byte *data;
   1256   asection *section;
   1257   bfd_signed_vma adj;
   1258 
   1259 #ifdef POWERPC_LE_PE
   1260   asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
   1261 #endif
   1262 
   1263   bfd_size_type datasize = 0;
   1264   bfd_size_type dataoff;
   1265   bfd_size_type i;
   1266   int onaline = 20;
   1267 
   1268   pe_data_type *pe = pe_data (abfd);
   1269   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   1270 
   1271   bfd_vma addr;
   1272 
   1273   addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
   1274 
   1275   if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
   1276     {
   1277       /* Maybe the extra header isn't there.  Look for the section.  */
   1278       section = bfd_get_section_by_name (abfd, ".idata");
   1279       if (section == NULL)
   1280 	return TRUE;
   1281 
   1282       addr = section->vma;
   1283       datasize = section->size;
   1284       if (datasize == 0)
   1285 	return TRUE;
   1286     }
   1287   else
   1288     {
   1289       addr += extra->ImageBase;
   1290       for (section = abfd->sections; section != NULL; section = section->next)
   1291 	{
   1292 	  datasize = section->size;
   1293 	  if (addr >= section->vma && addr < section->vma + datasize)
   1294 	    break;
   1295 	}
   1296 
   1297       if (section == NULL)
   1298 	{
   1299 	  fprintf (file,
   1300 		   _("\nThere is an import table, but the section containing it could not be found\n"));
   1301 	  return TRUE;
   1302 	}
   1303       else if (!(section->flags & SEC_HAS_CONTENTS))
   1304         {
   1305 	  fprintf (file,
   1306 		   _("\nThere is an import table in %s, but that section has no contents\n"),
   1307 		   section->name);
   1308 	  return TRUE;
   1309         }
   1310     }
   1311 
   1312   fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
   1313 	   section->name, (unsigned long) addr);
   1314 
   1315   dataoff = addr - section->vma;
   1316 
   1317 #ifdef POWERPC_LE_PE
   1318   if (rel_section != 0 && rel_section->size != 0)
   1319     {
   1320       /* The toc address can be found by taking the starting address,
   1321 	 which on the PPC locates a function descriptor. The
   1322 	 descriptor consists of the function code starting address
   1323 	 followed by the address of the toc. The starting address we
   1324 	 get from the bfd, and the descriptor is supposed to be in the
   1325 	 .reldata section.  */
   1326 
   1327       bfd_vma loadable_toc_address;
   1328       bfd_vma toc_address;
   1329       bfd_vma start_address;
   1330       bfd_byte *data;
   1331       bfd_vma offset;
   1332 
   1333       if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
   1334 	{
   1335 	  if (data != NULL)
   1336 	    free (data);
   1337 	  return FALSE;
   1338 	}
   1339 
   1340       offset = abfd->start_address - rel_section->vma;
   1341 
   1342       if (offset >= rel_section->size || offset + 8 > rel_section->size)
   1343         {
   1344           if (data != NULL)
   1345             free (data);
   1346           return FALSE;
   1347         }
   1348 
   1349       start_address = bfd_get_32 (abfd, data + offset);
   1350       loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
   1351       toc_address = loadable_toc_address - 32768;
   1352 
   1353       fprintf (file,
   1354 	       _("\nFunction descriptor located at the start address: %04lx\n"),
   1355 	       (unsigned long int) (abfd->start_address));
   1356       fprintf (file,
   1357 	       _("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
   1358 	       start_address, loadable_toc_address, toc_address);
   1359       if (data != NULL)
   1360 	free (data);
   1361     }
   1362   else
   1363     {
   1364       fprintf (file,
   1365 	       _("\nNo reldata section! Function descriptor not decoded.\n"));
   1366     }
   1367 #endif
   1368 
   1369   fprintf (file,
   1370 	   _("\nThe Import Tables (interpreted %s section contents)\n"),
   1371 	   section->name);
   1372   fprintf (file,
   1373 	   _("\
   1374  vma:            Hint    Time      Forward  DLL       First\n\
   1375                  Table   Stamp     Chain    Name      Thunk\n"));
   1376 
   1377   /* Read the whole section.  Some of the fields might be before dataoff.  */
   1378   if (!bfd_malloc_and_get_section (abfd, section, &data))
   1379     {
   1380       if (data != NULL)
   1381 	free (data);
   1382       return FALSE;
   1383     }
   1384 
   1385   adj = section->vma - extra->ImageBase;
   1386 
   1387   /* Print all image import descriptors.  */
   1388   for (i = dataoff; i + onaline <= datasize; i += onaline)
   1389     {
   1390       bfd_vma hint_addr;
   1391       bfd_vma time_stamp;
   1392       bfd_vma forward_chain;
   1393       bfd_vma dll_name;
   1394       bfd_vma first_thunk;
   1395       int idx = 0;
   1396       bfd_size_type j;
   1397       char *dll;
   1398 
   1399       /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress).  */
   1400       fprintf (file, " %08lx\t", (unsigned long) (i + adj));
   1401       hint_addr = bfd_get_32 (abfd, data + i);
   1402       time_stamp = bfd_get_32 (abfd, data + i + 4);
   1403       forward_chain = bfd_get_32 (abfd, data + i + 8);
   1404       dll_name = bfd_get_32 (abfd, data + i + 12);
   1405       first_thunk = bfd_get_32 (abfd, data + i + 16);
   1406 
   1407       fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
   1408 	       (unsigned long) hint_addr,
   1409 	       (unsigned long) time_stamp,
   1410 	       (unsigned long) forward_chain,
   1411 	       (unsigned long) dll_name,
   1412 	       (unsigned long) first_thunk);
   1413 
   1414       if (hint_addr == 0 && first_thunk == 0)
   1415 	break;
   1416 
   1417       if (dll_name - adj >= section->size)
   1418         break;
   1419 
   1420       dll = (char *) data + dll_name - adj;
   1421       /* PR 17512 file: 078-12277-0.004.  */
   1422       bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
   1423       fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
   1424 
   1425       if (hint_addr != 0)
   1426 	{
   1427 	  bfd_byte *ft_data;
   1428 	  asection *ft_section;
   1429 	  bfd_vma ft_addr;
   1430 	  bfd_size_type ft_datasize;
   1431 	  int ft_idx;
   1432 	  int ft_allocated;
   1433 
   1434 	  fprintf (file, _("\tvma:  Hint/Ord Member-Name Bound-To\n"));
   1435 
   1436 	  idx = hint_addr - adj;
   1437 
   1438 	  ft_addr = first_thunk + extra->ImageBase;
   1439 	  ft_idx = first_thunk - adj;
   1440 	  ft_data = data + ft_idx;
   1441 	  ft_datasize = datasize - ft_idx;
   1442 	  ft_allocated = 0;
   1443 
   1444 	  if (first_thunk != hint_addr)
   1445 	    {
   1446 	      /* Find the section which contains the first thunk.  */
   1447 	      for (ft_section = abfd->sections;
   1448 		   ft_section != NULL;
   1449 		   ft_section = ft_section->next)
   1450 		{
   1451 		  if (ft_addr >= ft_section->vma
   1452 		      && ft_addr < ft_section->vma + ft_section->size)
   1453 		    break;
   1454 		}
   1455 
   1456 	      if (ft_section == NULL)
   1457 		{
   1458 		  fprintf (file,
   1459 		       _("\nThere is a first thunk, but the section containing it could not be found\n"));
   1460 		  continue;
   1461 		}
   1462 
   1463 	      /* Now check to see if this section is the same as our current
   1464 		 section.  If it is not then we will have to load its data in.  */
   1465 	      if (ft_section != section)
   1466 		{
   1467 		  ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
   1468 		  ft_datasize = ft_section->size - ft_idx;
   1469 		  ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
   1470 		  if (ft_data == NULL)
   1471 		    continue;
   1472 
   1473 		  /* Read ft_datasize bytes starting at offset ft_idx.  */
   1474 		  if (!bfd_get_section_contents (abfd, ft_section, ft_data,
   1475 						 (bfd_vma) ft_idx, ft_datasize))
   1476 		    {
   1477 		      free (ft_data);
   1478 		      continue;
   1479 		    }
   1480 		  ft_allocated = 1;
   1481 		}
   1482 	    }
   1483 
   1484 	  /* Print HintName vector entries.  */
   1485 #ifdef COFF_WITH_pex64
   1486 	  for (j = 0; idx + j + 8 <= datasize; j += 8)
   1487 	    {
   1488 	      bfd_size_type amt;
   1489 	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
   1490 	      unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
   1491 
   1492 	      if (!member && !member_high)
   1493 		break;
   1494 
   1495 	      amt = member - adj;
   1496 
   1497 	      if (HighBitSet (member_high))
   1498 		fprintf (file, "\t%lx%08lx\t %4lx%08lx  <none>",
   1499 			 member_high, member,
   1500 			 WithoutHighBit (member_high), member);
   1501 	      /* PR binutils/17512: Handle corrupt PE data.  */
   1502 	      else if (amt + 2 >= datasize)
   1503 		fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
   1504 	      else
   1505 		{
   1506 		  int ordinal;
   1507 		  char *member_name;
   1508 
   1509 		  ordinal = bfd_get_16 (abfd, data + amt);
   1510 		  member_name = (char *) data + amt + 2;
   1511 		  fprintf (file, "\t%04lx\t %4d  %.*s",member, ordinal,
   1512 			   (int) (datasize - (amt + 2)), member_name);
   1513 		}
   1514 
   1515 	      /* If the time stamp is not zero, the import address
   1516 		 table holds actual addresses.  */
   1517 	      if (time_stamp != 0
   1518 		  && first_thunk != 0
   1519 		  && first_thunk != hint_addr
   1520 		  && j + 4 <= ft_datasize)
   1521 		fprintf (file, "\t%04lx",
   1522 			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
   1523 	      fprintf (file, "\n");
   1524 	    }
   1525 #else
   1526 	  for (j = 0; idx + j + 4 <= datasize; j += 4)
   1527 	    {
   1528 	      bfd_size_type amt;
   1529 	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
   1530 
   1531 	      /* Print single IMAGE_IMPORT_BY_NAME vector.  */
   1532 	      if (member == 0)
   1533 		break;
   1534 
   1535 	      amt = member - adj;
   1536 	      if (HighBitSet (member))
   1537 		fprintf (file, "\t%04lx\t %4lu  <none>",
   1538 			 member, WithoutHighBit (member));
   1539 	      /* PR binutils/17512: Handle corrupt PE data.  */
   1540 	      else if (amt + 2 >= datasize)
   1541 		fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
   1542 	      else
   1543 		{
   1544 		  int ordinal;
   1545 		  char *member_name;
   1546 
   1547 		  ordinal = bfd_get_16 (abfd, data + amt);
   1548 		  member_name = (char *) data + amt + 2;
   1549 		  fprintf (file, "\t%04lx\t %4d  %.*s",
   1550 			   member, ordinal,
   1551 			   (int) (datasize - (amt + 2)), member_name);
   1552 		}
   1553 
   1554 	      /* If the time stamp is not zero, the import address
   1555 		 table holds actual addresses.  */
   1556 	      if (time_stamp != 0
   1557 		  && first_thunk != 0
   1558 		  && first_thunk != hint_addr
   1559 		  && j + 4 <= ft_datasize)
   1560 		fprintf (file, "\t%04lx",
   1561 			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
   1562 
   1563 	      fprintf (file, "\n");
   1564 	    }
   1565 #endif
   1566 	  if (ft_allocated)
   1567 	    free (ft_data);
   1568 	}
   1569 
   1570       fprintf (file, "\n");
   1571     }
   1572 
   1573   free (data);
   1574 
   1575   return TRUE;
   1576 }
   1577 
   1578 static bfd_boolean
   1579 pe_print_edata (bfd * abfd, void * vfile)
   1580 {
   1581   FILE *file = (FILE *) vfile;
   1582   bfd_byte *data;
   1583   asection *section;
   1584   bfd_size_type datasize = 0;
   1585   bfd_size_type dataoff;
   1586   bfd_size_type i;
   1587   bfd_vma       adj;
   1588   struct EDT_type
   1589   {
   1590     long export_flags;          /* Reserved - should be zero.  */
   1591     long time_stamp;
   1592     short major_ver;
   1593     short minor_ver;
   1594     bfd_vma name;               /* RVA - relative to image base.  */
   1595     long base;                  /* Ordinal base.  */
   1596     unsigned long num_functions;/* Number in the export address table.  */
   1597     unsigned long num_names;    /* Number in the name pointer table.  */
   1598     bfd_vma eat_addr;		/* RVA to the export address table.  */
   1599     bfd_vma npt_addr;		/* RVA to the Export Name Pointer Table.  */
   1600     bfd_vma ot_addr;		/* RVA to the Ordinal Table.  */
   1601   } edt;
   1602 
   1603   pe_data_type *pe = pe_data (abfd);
   1604   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   1605 
   1606   bfd_vma addr;
   1607 
   1608   addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
   1609 
   1610   if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
   1611     {
   1612       /* Maybe the extra header isn't there.  Look for the section.  */
   1613       section = bfd_get_section_by_name (abfd, ".edata");
   1614       if (section == NULL)
   1615 	return TRUE;
   1616 
   1617       addr = section->vma;
   1618       dataoff = 0;
   1619       datasize = section->size;
   1620       if (datasize == 0)
   1621 	return TRUE;
   1622     }
   1623   else
   1624     {
   1625       addr += extra->ImageBase;
   1626 
   1627       for (section = abfd->sections; section != NULL; section = section->next)
   1628 	if (addr >= section->vma && addr < section->vma + section->size)
   1629 	  break;
   1630 
   1631       if (section == NULL)
   1632 	{
   1633 	  fprintf (file,
   1634 		   _("\nThere is an export table, but the section containing it could not be found\n"));
   1635 	  return TRUE;
   1636 	}
   1637       else if (!(section->flags & SEC_HAS_CONTENTS))
   1638         {
   1639 	  fprintf (file,
   1640 		   _("\nThere is an export table in %s, but that section has no contents\n"),
   1641 		   section->name);
   1642 	  return TRUE;
   1643         }
   1644 
   1645       dataoff = addr - section->vma;
   1646       datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
   1647       if (datasize > section->size - dataoff)
   1648 	{
   1649 	  fprintf (file,
   1650 		   _("\nThere is an export table in %s, but it does not fit into that section\n"),
   1651 		   section->name);
   1652 	  return TRUE;
   1653 	}
   1654     }
   1655 
   1656   /* PR 17512: Handle corrupt PE binaries.  */
   1657   if (datasize < 36)
   1658     {
   1659       fprintf (file,
   1660 	       _("\nThere is an export table in %s, but it is too small (%d)\n"),
   1661 	       section->name, (int) datasize);
   1662       return TRUE;
   1663     }
   1664 
   1665   fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
   1666 	   section->name, (unsigned long) addr);
   1667 
   1668   data = (bfd_byte *) bfd_malloc (datasize);
   1669   if (data == NULL)
   1670     return FALSE;
   1671 
   1672   if (! bfd_get_section_contents (abfd, section, data,
   1673 				  (file_ptr) dataoff, datasize))
   1674     return FALSE;
   1675 
   1676   /* Go get Export Directory Table.  */
   1677   edt.export_flags   = bfd_get_32 (abfd, data +  0);
   1678   edt.time_stamp     = bfd_get_32 (abfd, data +  4);
   1679   edt.major_ver      = bfd_get_16 (abfd, data +  8);
   1680   edt.minor_ver      = bfd_get_16 (abfd, data + 10);
   1681   edt.name           = bfd_get_32 (abfd, data + 12);
   1682   edt.base           = bfd_get_32 (abfd, data + 16);
   1683   edt.num_functions  = bfd_get_32 (abfd, data + 20);
   1684   edt.num_names      = bfd_get_32 (abfd, data + 24);
   1685   edt.eat_addr       = bfd_get_32 (abfd, data + 28);
   1686   edt.npt_addr       = bfd_get_32 (abfd, data + 32);
   1687   edt.ot_addr        = bfd_get_32 (abfd, data + 36);
   1688 
   1689   adj = section->vma - extra->ImageBase + dataoff;
   1690 
   1691   /* Dump the EDT first.  */
   1692   fprintf (file,
   1693 	   _("\nThe Export Tables (interpreted %s section contents)\n\n"),
   1694 	   section->name);
   1695 
   1696   fprintf (file,
   1697 	   _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
   1698 
   1699   fprintf (file,
   1700 	   _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
   1701 
   1702   fprintf (file,
   1703 	   _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
   1704 
   1705   fprintf (file,
   1706 	   _("Name \t\t\t\t"));
   1707   bfd_fprintf_vma (abfd, file, edt.name);
   1708 
   1709   if ((edt.name >= adj) && (edt.name < adj + datasize))
   1710     fprintf (file, " %.*s\n",
   1711 	     (int) (datasize - (edt.name - adj)),
   1712 	     data + edt.name - adj);
   1713   else
   1714     fprintf (file, "(outside .edata section)\n");
   1715 
   1716   fprintf (file,
   1717 	   _("Ordinal Base \t\t\t%ld\n"), edt.base);
   1718 
   1719   fprintf (file,
   1720 	   _("Number in:\n"));
   1721 
   1722   fprintf (file,
   1723 	   _("\tExport Address Table \t\t%08lx\n"),
   1724 	   edt.num_functions);
   1725 
   1726   fprintf (file,
   1727 	   _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
   1728 
   1729   fprintf (file,
   1730 	   _("Table Addresses\n"));
   1731 
   1732   fprintf (file,
   1733 	   _("\tExport Address Table \t\t"));
   1734   bfd_fprintf_vma (abfd, file, edt.eat_addr);
   1735   fprintf (file, "\n");
   1736 
   1737   fprintf (file,
   1738 	   _("\tName Pointer Table \t\t"));
   1739   bfd_fprintf_vma (abfd, file, edt.npt_addr);
   1740   fprintf (file, "\n");
   1741 
   1742   fprintf (file,
   1743 	   _("\tOrdinal Table \t\t\t"));
   1744   bfd_fprintf_vma (abfd, file, edt.ot_addr);
   1745   fprintf (file, "\n");
   1746 
   1747   /* The next table to find is the Export Address Table. It's basically
   1748      a list of pointers that either locate a function in this dll, or
   1749      forward the call to another dll. Something like:
   1750       typedef union
   1751       {
   1752         long export_rva;
   1753         long forwarder_rva;
   1754       } export_address_table_entry;  */
   1755 
   1756   fprintf (file,
   1757 	  _("\nExport Address Table -- Ordinal Base %ld\n"),
   1758 	  edt.base);
   1759 
   1760   /* PR 17512: Handle corrupt PE binaries.  */
   1761   if (edt.eat_addr + (edt.num_functions * 4) - adj >= datasize
   1762       /* PR 17512 file: 140-165018-0.004.  */
   1763       || data + edt.eat_addr - adj < data)
   1764     fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
   1765 	     (long) edt.eat_addr,
   1766 	     (long) edt.num_functions);
   1767   else for (i = 0; i < edt.num_functions; ++i)
   1768     {
   1769       bfd_vma eat_member = bfd_get_32 (abfd,
   1770 				       data + edt.eat_addr + (i * 4) - adj);
   1771       if (eat_member == 0)
   1772 	continue;
   1773 
   1774       if (eat_member - adj <= datasize)
   1775 	{
   1776 	  /* This rva is to a name (forwarding function) in our section.  */
   1777 	  /* Should locate a function descriptor.  */
   1778 	  fprintf (file,
   1779 		   "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
   1780 		   (long) i,
   1781 		   (long) (i + edt.base),
   1782 		   (unsigned long) eat_member,
   1783 		   _("Forwarder RVA"),
   1784 		   (int)(datasize - (eat_member - adj)),
   1785 		   data + eat_member - adj);
   1786 	}
   1787       else
   1788 	{
   1789 	  /* Should locate a function descriptor in the reldata section.  */
   1790 	  fprintf (file,
   1791 		   "\t[%4ld] +base[%4ld] %04lx %s\n",
   1792 		   (long) i,
   1793 		   (long) (i + edt.base),
   1794 		   (unsigned long) eat_member,
   1795 		   _("Export RVA"));
   1796 	}
   1797     }
   1798 
   1799   /* The Export Name Pointer Table is paired with the Export Ordinal Table.  */
   1800   /* Dump them in parallel for clarity.  */
   1801   fprintf (file,
   1802 	   _("\n[Ordinal/Name Pointer] Table\n"));
   1803 
   1804   /* PR 17512: Handle corrupt PE binaries.  */
   1805   if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
   1806       || (data + edt.npt_addr - adj) < data)
   1807     fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
   1808 	     (long) edt.npt_addr,
   1809 	     (long) edt.num_names);
   1810   /* PR 17512: file: 140-147171-0.004.  */
   1811   else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
   1812 	   || data + edt.ot_addr - adj < data)
   1813     fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
   1814 	     (long) edt.ot_addr,
   1815 	     (long) edt.num_names);
   1816   else for (i = 0; i < edt.num_names; ++i)
   1817     {
   1818       bfd_vma  name_ptr;
   1819       bfd_vma  ord;
   1820 
   1821       ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
   1822       name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
   1823 
   1824       if ((name_ptr - adj) >= datasize)
   1825 	{
   1826 	  fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"),
   1827 		   (long) ord, (long) name_ptr);
   1828 	}
   1829       else
   1830 	{
   1831 	  char * name = (char *) data + name_ptr - adj;
   1832 
   1833 	  fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
   1834 		   (int)((char *)(data + datasize) - name), name);
   1835 	}
   1836     }
   1837 
   1838   free (data);
   1839 
   1840   return TRUE;
   1841 }
   1842 
   1843 /* This really is architecture dependent.  On IA-64, a .pdata entry
   1844    consists of three dwords containing relative virtual addresses that
   1845    specify the start and end address of the code range the entry
   1846    covers and the address of the corresponding unwind info data.
   1847 
   1848    On ARM and SH-4, a compressed PDATA structure is used :
   1849    _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
   1850    _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
   1851    See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
   1852 
   1853    This is the version for uncompressed data.  */
   1854 
   1855 static bfd_boolean
   1856 pe_print_pdata (bfd * abfd, void * vfile)
   1857 {
   1858 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   1859 # define PDATA_ROW_SIZE	(3 * 8)
   1860 #else
   1861 # define PDATA_ROW_SIZE	(5 * 4)
   1862 #endif
   1863   FILE *file = (FILE *) vfile;
   1864   bfd_byte *data = 0;
   1865   asection *section = bfd_get_section_by_name (abfd, ".pdata");
   1866   bfd_size_type datasize = 0;
   1867   bfd_size_type i;
   1868   bfd_size_type start, stop;
   1869   int onaline = PDATA_ROW_SIZE;
   1870 
   1871   if (section == NULL
   1872       || coff_section_data (abfd, section) == NULL
   1873       || pei_section_data (abfd, section) == NULL)
   1874     return TRUE;
   1875 
   1876   stop = pei_section_data (abfd, section)->virt_size;
   1877   if ((stop % onaline) != 0)
   1878     fprintf (file,
   1879 	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
   1880 	     (long) stop, onaline);
   1881 
   1882   fprintf (file,
   1883 	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
   1884 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   1885   fprintf (file,
   1886 	   _(" vma:\t\t\tBegin Address    End Address      Unwind Info\n"));
   1887 #else
   1888   fprintf (file, _("\
   1889  vma:\t\tBegin    End      EH       EH       PrologEnd  Exception\n\
   1890      \t\tAddress  Address  Handler  Data     Address    Mask\n"));
   1891 #endif
   1892 
   1893   datasize = section->size;
   1894   if (datasize == 0)
   1895     return TRUE;
   1896 
   1897   if (! bfd_malloc_and_get_section (abfd, section, &data))
   1898     {
   1899       if (data != NULL)
   1900 	free (data);
   1901       return FALSE;
   1902     }
   1903 
   1904   start = 0;
   1905 
   1906   for (i = start; i < stop; i += onaline)
   1907     {
   1908       bfd_vma begin_addr;
   1909       bfd_vma end_addr;
   1910       bfd_vma eh_handler;
   1911       bfd_vma eh_data;
   1912       bfd_vma prolog_end_addr;
   1913 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1914       int em_data;
   1915 #endif
   1916 
   1917       if (i + PDATA_ROW_SIZE > stop)
   1918 	break;
   1919 
   1920       begin_addr      = GET_PDATA_ENTRY (abfd, data + i     );
   1921       end_addr        = GET_PDATA_ENTRY (abfd, data + i +  4);
   1922       eh_handler      = GET_PDATA_ENTRY (abfd, data + i +  8);
   1923       eh_data         = GET_PDATA_ENTRY (abfd, data + i + 12);
   1924       prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
   1925 
   1926       if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
   1927 	  && eh_data == 0 && prolog_end_addr == 0)
   1928 	/* We are probably into the padding of the section now.  */
   1929 	break;
   1930 
   1931 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1932       em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
   1933 #endif
   1934       eh_handler &= ~(bfd_vma) 0x3;
   1935       prolog_end_addr &= ~(bfd_vma) 0x3;
   1936 
   1937       fputc (' ', file);
   1938       bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
   1939       bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
   1940       bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
   1941       bfd_fprintf_vma (abfd, file, eh_handler);
   1942 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1943       fputc (' ', file);
   1944       bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
   1945       bfd_fprintf_vma (abfd, file, prolog_end_addr);
   1946       fprintf (file, "   %x", em_data);
   1947 #endif
   1948 
   1949 #ifdef POWERPC_LE_PE
   1950       if (eh_handler == 0 && eh_data != 0)
   1951 	{
   1952 	  /* Special bits here, although the meaning may be a little
   1953 	     mysterious. The only one I know for sure is 0x03
   1954 	     Code Significance
   1955 	     0x00 None
   1956 	     0x01 Register Save Millicode
   1957 	     0x02 Register Restore Millicode
   1958 	     0x03 Glue Code Sequence.  */
   1959 	  switch (eh_data)
   1960 	    {
   1961 	    case 0x01:
   1962 	      fprintf (file, _(" Register save millicode"));
   1963 	      break;
   1964 	    case 0x02:
   1965 	      fprintf (file, _(" Register restore millicode"));
   1966 	      break;
   1967 	    case 0x03:
   1968 	      fprintf (file, _(" Glue code sequence"));
   1969 	      break;
   1970 	    default:
   1971 	      break;
   1972 	    }
   1973 	}
   1974 #endif
   1975       fprintf (file, "\n");
   1976     }
   1977 
   1978   free (data);
   1979 
   1980   return TRUE;
   1981 #undef PDATA_ROW_SIZE
   1982 }
   1983 
   1984 typedef struct sym_cache
   1985 {
   1986   int        symcount;
   1987   asymbol ** syms;
   1988 } sym_cache;
   1989 
   1990 static asymbol **
   1991 slurp_symtab (bfd *abfd, sym_cache *psc)
   1992 {
   1993   asymbol ** sy = NULL;
   1994   long storage;
   1995 
   1996   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
   1997     {
   1998       psc->symcount = 0;
   1999       return NULL;
   2000     }
   2001 
   2002   storage = bfd_get_symtab_upper_bound (abfd);
   2003   if (storage < 0)
   2004     return NULL;
   2005   if (storage)
   2006     sy = (asymbol **) bfd_malloc (storage);
   2007 
   2008   psc->symcount = bfd_canonicalize_symtab (abfd, sy);
   2009   if (psc->symcount < 0)
   2010     return NULL;
   2011   return sy;
   2012 }
   2013 
   2014 static const char *
   2015 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
   2016 {
   2017   int i;
   2018 
   2019   if (psc->syms == 0)
   2020     psc->syms = slurp_symtab (abfd, psc);
   2021 
   2022   for (i = 0; i < psc->symcount; i++)
   2023     {
   2024       if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
   2025 	return psc->syms[i]->name;
   2026     }
   2027 
   2028   return NULL;
   2029 }
   2030 
   2031 static void
   2032 cleanup_syms (sym_cache *psc)
   2033 {
   2034   psc->symcount = 0;
   2035   free (psc->syms);
   2036   psc->syms = NULL;
   2037 }
   2038 
   2039 /* This is the version for "compressed" pdata.  */
   2040 
   2041 bfd_boolean
   2042 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
   2043 {
   2044 # define PDATA_ROW_SIZE	(2 * 4)
   2045   FILE *file = (FILE *) vfile;
   2046   bfd_byte *data = NULL;
   2047   asection *section = bfd_get_section_by_name (abfd, ".pdata");
   2048   bfd_size_type datasize = 0;
   2049   bfd_size_type i;
   2050   bfd_size_type start, stop;
   2051   int onaline = PDATA_ROW_SIZE;
   2052   struct sym_cache cache = {0, 0} ;
   2053 
   2054   if (section == NULL
   2055       || coff_section_data (abfd, section) == NULL
   2056       || pei_section_data (abfd, section) == NULL)
   2057     return TRUE;
   2058 
   2059   stop = pei_section_data (abfd, section)->virt_size;
   2060   if ((stop % onaline) != 0)
   2061     fprintf (file,
   2062 	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
   2063 	     (long) stop, onaline);
   2064 
   2065   fprintf (file,
   2066 	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
   2067 
   2068   fprintf (file, _("\
   2069  vma:\t\tBegin    Prolog   Function Flags    Exception EH\n\
   2070      \t\tAddress  Length   Length   32b exc  Handler   Data\n"));
   2071 
   2072   datasize = section->size;
   2073   if (datasize == 0)
   2074     return TRUE;
   2075 
   2076   if (! bfd_malloc_and_get_section (abfd, section, &data))
   2077     {
   2078       if (data != NULL)
   2079 	free (data);
   2080       return FALSE;
   2081     }
   2082 
   2083   start = 0;
   2084 
   2085   for (i = start; i < stop; i += onaline)
   2086     {
   2087       bfd_vma begin_addr;
   2088       bfd_vma other_data;
   2089       bfd_vma prolog_length, function_length;
   2090       int flag32bit, exception_flag;
   2091       asection *tsection;
   2092 
   2093       if (i + PDATA_ROW_SIZE > stop)
   2094 	break;
   2095 
   2096       begin_addr = GET_PDATA_ENTRY (abfd, data + i     );
   2097       other_data = GET_PDATA_ENTRY (abfd, data + i +  4);
   2098 
   2099       if (begin_addr == 0 && other_data == 0)
   2100 	/* We are probably into the padding of the section now.  */
   2101 	break;
   2102 
   2103       prolog_length = (other_data & 0x000000FF);
   2104       function_length = (other_data & 0x3FFFFF00) >> 8;
   2105       flag32bit = (int)((other_data & 0x40000000) >> 30);
   2106       exception_flag = (int)((other_data & 0x80000000) >> 31);
   2107 
   2108       fputc (' ', file);
   2109       bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
   2110       bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
   2111       bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
   2112       bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
   2113       fprintf (file, "%2d  %2d   ", flag32bit, exception_flag);
   2114 
   2115       /* Get the exception handler's address and the data passed from the
   2116          .text section. This is really the data that belongs with the .pdata
   2117          but got "compressed" out for the ARM and SH4 architectures.  */
   2118       tsection = bfd_get_section_by_name (abfd, ".text");
   2119       if (tsection && coff_section_data (abfd, tsection)
   2120 	  && pei_section_data (abfd, tsection))
   2121 	{
   2122 	  bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
   2123 	  bfd_byte *tdata;
   2124 
   2125 	  tdata = (bfd_byte *) bfd_malloc (8);
   2126 	  if (tdata)
   2127 	    {
   2128 	      if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
   2129 		{
   2130 		  bfd_vma eh, eh_data;
   2131 
   2132 		  eh = bfd_get_32 (abfd, tdata);
   2133 		  eh_data = bfd_get_32 (abfd, tdata + 4);
   2134 		  fprintf (file, "%08x  ", (unsigned int) eh);
   2135 		  fprintf (file, "%08x", (unsigned int) eh_data);
   2136 		  if (eh != 0)
   2137 		    {
   2138 		      const char *s = my_symbol_for_address (abfd, eh, &cache);
   2139 
   2140 		      if (s)
   2141 			fprintf (file, " (%s) ", s);
   2142 		    }
   2143 		}
   2144 	      free (tdata);
   2145 	    }
   2146 	}
   2147 
   2148       fprintf (file, "\n");
   2149     }
   2150 
   2151   free (data);
   2152 
   2153   cleanup_syms (& cache);
   2154 
   2155   return TRUE;
   2156 #undef PDATA_ROW_SIZE
   2157 }
   2158 
   2159 
   2160 #define IMAGE_REL_BASED_HIGHADJ 4
   2162 static const char * const tbl[] =
   2163 {
   2164   "ABSOLUTE",
   2165   "HIGH",
   2166   "LOW",
   2167   "HIGHLOW",
   2168   "HIGHADJ",
   2169   "MIPS_JMPADDR",
   2170   "SECTION",
   2171   "REL32",
   2172   "RESERVED1",
   2173   "MIPS_JMPADDR16",
   2174   "DIR64",
   2175   "HIGH3ADJ",
   2176   "UNKNOWN",   /* MUST be last.  */
   2177 };
   2178 
   2179 static bfd_boolean
   2180 pe_print_reloc (bfd * abfd, void * vfile)
   2181 {
   2182   FILE *file = (FILE *) vfile;
   2183   bfd_byte *data = 0;
   2184   asection *section = bfd_get_section_by_name (abfd, ".reloc");
   2185   bfd_byte *p, *end;
   2186 
   2187   if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS))
   2188     return TRUE;
   2189 
   2190   fprintf (file,
   2191 	   _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
   2192 
   2193   if (! bfd_malloc_and_get_section (abfd, section, &data))
   2194     {
   2195       if (data != NULL)
   2196 	free (data);
   2197       return FALSE;
   2198     }
   2199 
   2200   p = data;
   2201   end = data + section->size;
   2202   while (p + 8 <= end)
   2203     {
   2204       int j;
   2205       bfd_vma virtual_address;
   2206       long number, size;
   2207       bfd_byte *chunk_end;
   2208 
   2209       /* The .reloc section is a sequence of blocks, with a header consisting
   2210 	 of two 32 bit quantities, followed by a number of 16 bit entries.  */
   2211       virtual_address = bfd_get_32 (abfd, p);
   2212       size = bfd_get_32 (abfd, p + 4);
   2213       p += 8;
   2214       number = (size - 8) / 2;
   2215 
   2216       if (size == 0)
   2217 	break;
   2218 
   2219       fprintf (file,
   2220 	       _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
   2221 	       (unsigned long) virtual_address, size, (unsigned long) size, number);
   2222 
   2223       chunk_end = p + size;
   2224       if (chunk_end > end)
   2225 	chunk_end = end;
   2226       j = 0;
   2227       while (p + 2 <= chunk_end)
   2228 	{
   2229 	  unsigned short e = bfd_get_16 (abfd, p);
   2230 	  unsigned int t = (e & 0xF000) >> 12;
   2231 	  int off = e & 0x0FFF;
   2232 
   2233 	  if (t >= sizeof (tbl) / sizeof (tbl[0]))
   2234 	    t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
   2235 
   2236 	  fprintf (file,
   2237 		   _("\treloc %4d offset %4x [%4lx] %s"),
   2238 		   j, off, (unsigned long) (off + virtual_address), tbl[t]);
   2239 
   2240 	  p += 2;
   2241 	  j++;
   2242 
   2243 	  /* HIGHADJ takes an argument, - the next record *is* the
   2244 	     low 16 bits of addend.  */
   2245 	  if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
   2246 	    {
   2247 	      fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
   2248 	      p += 2;
   2249 	      j++;
   2250 	    }
   2251 
   2252 	  fprintf (file, "\n");
   2253 	}
   2254     }
   2255 
   2256   free (data);
   2257 
   2258   return TRUE;
   2259 }
   2260 
   2261 /* A data structure describing the regions of a .rsrc section.
   2263    Some fields are filled in as the section is parsed.  */
   2264 
   2265 typedef struct rsrc_regions
   2266 {
   2267   bfd_byte * section_start;
   2268   bfd_byte * section_end;
   2269   bfd_byte * strings_start;
   2270   bfd_byte * resource_start;
   2271 } rsrc_regions;
   2272 
   2273 static bfd_byte *
   2274 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
   2275 			       rsrc_regions *, bfd_vma);
   2276 
   2277 /* Print the resource entry at DATA, with the text indented by INDENT.
   2278    Recusively calls rsrc_print_resource_directory to print the contents
   2279    of directory entries.
   2280    Returns the address of the end of the data associated with the entry
   2281    or section_end + 1 upon failure.  */
   2282 
   2283 static bfd_byte *
   2284 rsrc_print_resource_entries (FILE *         file,
   2285 			     bfd *          abfd,
   2286 			     unsigned int   indent,
   2287 			     bfd_boolean    is_name,
   2288 			     bfd_byte *     data,
   2289 			     rsrc_regions * regions,
   2290 			     bfd_vma        rva_bias)
   2291 {
   2292   unsigned long entry, addr, size;
   2293 
   2294   if (data + 8 >= regions->section_end)
   2295     return regions->section_end + 1;
   2296 
   2297   fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
   2298 
   2299   entry = (unsigned long) bfd_get_32 (abfd, data);
   2300   if (is_name)
   2301     {
   2302       bfd_byte * name;
   2303 
   2304       /* Note - the documentation says that this field is an RVA value
   2305 	 but windres appears to produce a section relative offset with
   2306 	 the top bit set.  Support both styles for now.  */
   2307       if (HighBitSet (entry))
   2308 	name = regions->section_start + WithoutHighBit (entry);
   2309       else
   2310 	name = regions->section_start + entry - rva_bias;
   2311 
   2312       if (name + 2 < regions->section_end && name > regions->section_start)
   2313 	{
   2314 	  unsigned int len;
   2315 
   2316 	  if (regions->strings_start == NULL)
   2317 	    regions->strings_start = name;
   2318 
   2319 	  len = bfd_get_16 (abfd, name);
   2320 
   2321 	  fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
   2322 
   2323 	  if (name + 2 + len * 2 < regions->section_end)
   2324 	    {
   2325 	      /* This strange loop is to cope with multibyte characters.  */
   2326 	      while (len --)
   2327 		{
   2328 		  char c;
   2329 
   2330 		  name += 2;
   2331 		  c = * name;
   2332 		  /* Avoid printing control characters.  */
   2333 		  if (c > 0 && c < 32)
   2334 		    fprintf (file, "^%c", c + 64);
   2335 		  else
   2336 		    fprintf (file, "%.1s", name);
   2337 		}
   2338 	    }
   2339 	  else
   2340 	    {
   2341 	      fprintf (file, _("<corrupt string length: %#x>\n"), len);
   2342 	      /* PR binutils/17512: Do not try to continue decoding a
   2343 		 corrupted resource section.  It is likely to end up with
   2344 		 reams of extraneous output.  FIXME: We could probably
   2345 		 continue if we disable the printing of strings...  */
   2346 	      return regions->section_end + 1;
   2347 	    }
   2348 	}
   2349       else
   2350 	{
   2351 	  fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
   2352 	  return regions->section_end + 1;
   2353 	}
   2354     }
   2355   else
   2356     fprintf (file, _("ID: %#08lx"), entry);
   2357 
   2358   entry = (long) bfd_get_32 (abfd, data + 4);
   2359   fprintf (file, _(", Value: %#08lx\n"), entry);
   2360 
   2361   if (HighBitSet  (entry))
   2362     {
   2363       data = regions->section_start + WithoutHighBit (entry);
   2364       if (data <= regions->section_start || data > regions->section_end)
   2365 	return regions->section_end + 1;
   2366 
   2367       /* FIXME: PR binutils/17512: A corrupt file could contain a loop
   2368 	 in the resource table.  We need some way to detect this.  */
   2369       return rsrc_print_resource_directory (file, abfd, indent + 1, data,
   2370 					    regions, rva_bias);
   2371     }
   2372 
   2373   if (regions->section_start + entry + 16 >= regions->section_end)
   2374     return regions->section_end + 1;
   2375 
   2376   fprintf (file, _("%03x %*.s  Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
   2377 	   (int) (entry),
   2378 	   indent, " ",
   2379 	   addr = (long) bfd_get_32 (abfd, regions->section_start + entry),
   2380 	   size = (long) bfd_get_32 (abfd, regions->section_start + entry + 4),
   2381 	   (int) bfd_get_32 (abfd, regions->section_start + entry + 8));
   2382 
   2383   /* Check that the reserved entry is 0.  */
   2384   if (bfd_get_32 (abfd, regions->section_start + entry + 12) != 0
   2385       /* And that the data address/size is valid too.  */
   2386       || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
   2387     return regions->section_end + 1;
   2388 
   2389   if (regions->resource_start == NULL)
   2390     regions->resource_start = regions->section_start + (addr - rva_bias);
   2391 
   2392   return regions->section_start + (addr - rva_bias) + size;
   2393 }
   2394 
   2395 #define max(a,b) ((a) > (b) ? (a) : (b))
   2396 #define min(a,b) ((a) < (b) ? (a) : (b))
   2397 
   2398 static bfd_byte *
   2399 rsrc_print_resource_directory (FILE *         file,
   2400 			       bfd *          abfd,
   2401 			       unsigned int   indent,
   2402 			       bfd_byte *     data,
   2403 			       rsrc_regions * regions,
   2404 			       bfd_vma        rva_bias)
   2405 {
   2406   unsigned int num_names, num_ids;
   2407   bfd_byte * highest_data = data;
   2408 
   2409   if (data + 16 >= regions->section_end)
   2410     return regions->section_end + 1;
   2411 
   2412   fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
   2413   switch (indent)
   2414     {
   2415     case 0: fprintf (file, "Type"); break;
   2416     case 2: fprintf (file, "Name"); break;
   2417     case 4: fprintf (file, "Language"); break;
   2418     default:
   2419       fprintf (file, _("<unknown directory type: %d>\n"), indent);
   2420       /* FIXME: For now we end the printing here.  If in the
   2421 	 future more directory types are added to the RSRC spec
   2422 	 then we will need to change this.  */
   2423       return regions->section_end + 1;
   2424     }
   2425 
   2426   fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
   2427 	   (int) bfd_get_32 (abfd, data),
   2428 	   (long) bfd_get_32 (abfd, data + 4),
   2429 	   (int)  bfd_get_16 (abfd, data + 8),
   2430 	   (int)  bfd_get_16 (abfd, data + 10),
   2431 	   num_names = (int) bfd_get_16 (abfd, data + 12),
   2432 	   num_ids =   (int) bfd_get_16 (abfd, data + 14));
   2433   data += 16;
   2434 
   2435   while (num_names --)
   2436     {
   2437       bfd_byte * entry_end;
   2438 
   2439       entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, TRUE,
   2440 					       data, regions, rva_bias);
   2441       data += 8;
   2442       highest_data = max (highest_data, entry_end);
   2443       if (entry_end >= regions->section_end)
   2444 	return entry_end;
   2445     }
   2446 
   2447   while (num_ids --)
   2448     {
   2449       bfd_byte * entry_end;
   2450 
   2451       entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, FALSE,
   2452 					       data, regions, rva_bias);
   2453       data += 8;
   2454       highest_data = max (highest_data, entry_end);
   2455       if (entry_end >= regions->section_end)
   2456 	return entry_end;
   2457     }
   2458 
   2459   return max (highest_data, data);
   2460 }
   2461 
   2462 /* Display the contents of a .rsrc section.  We do not try to
   2463    reproduce the resources, windres does that.  Instead we dump
   2464    the tables in a human readable format.  */
   2465 
   2466 static bfd_boolean
   2467 rsrc_print_section (bfd * abfd, void * vfile)
   2468 {
   2469   bfd_vma rva_bias;
   2470   pe_data_type * pe;
   2471   FILE * file = (FILE *) vfile;
   2472   bfd_size_type datasize;
   2473   asection * section;
   2474   bfd_byte * data;
   2475   rsrc_regions regions;
   2476 
   2477   pe = pe_data (abfd);
   2478   if (pe == NULL)
   2479     return TRUE;
   2480 
   2481   section = bfd_get_section_by_name (abfd, ".rsrc");
   2482   if (section == NULL)
   2483     return TRUE;
   2484   if (!(section->flags & SEC_HAS_CONTENTS))
   2485     return TRUE;
   2486 
   2487   datasize = section->size;
   2488   if (datasize == 0)
   2489     return TRUE;
   2490 
   2491   rva_bias = section->vma - pe->pe_opthdr.ImageBase;
   2492 
   2493   if (! bfd_malloc_and_get_section (abfd, section, & data))
   2494     {
   2495       if (data != NULL)
   2496 	free (data);
   2497       return FALSE;
   2498     }
   2499 
   2500   regions.section_start = data;
   2501   regions.section_end = data + datasize;
   2502   regions.strings_start = NULL;
   2503   regions.resource_start = NULL;
   2504 
   2505   fflush (file);
   2506   fprintf (file, "\nThe .rsrc Resource Directory section:\n");
   2507 
   2508   while (data < regions.section_end)
   2509     {
   2510       bfd_byte * p = data;
   2511 
   2512       data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
   2513 
   2514       if (data == regions.section_end + 1)
   2515 	fprintf (file, _("Corrupt .rsrc section detected!\n"));
   2516       else
   2517 	{
   2518 	  /* Align data before continuing.  */
   2519 	  int align = (1 << section->alignment_power) - 1;
   2520 
   2521 	  data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
   2522 	  rva_bias += data - p;
   2523 
   2524 	  /* For reasons that are unclear .rsrc sections are sometimes created
   2525 	     aligned to a 1^3 boundary even when their alignment is set at
   2526 	     1^2.  Catch that case here before we issue a spurious warning
   2527 	     message.  */
   2528 	  if (data == (regions.section_end - 4))
   2529 	    data = regions.section_end;
   2530 	  else if (data < regions.section_end)
   2531 	    {
   2532 	      /* If the extra data is all zeros then do not complain.
   2533 		 This is just padding so that the section meets the
   2534 		 page size requirements.  */
   2535 	      while (data ++ < regions.section_end)
   2536 		if (*data != 0)
   2537 		  break;
   2538 	      if (data < regions.section_end)
   2539 		fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
   2540 	    }
   2541 	}
   2542     }
   2543 
   2544   if (regions.strings_start != NULL)
   2545     fprintf (file, " String table starts at offset: %#03x\n",
   2546 	     (int) (regions.strings_start - regions.section_start));
   2547   if (regions.resource_start != NULL)
   2548     fprintf (file, " Resources start at offset: %#03x\n",
   2549 	     (int) (regions.resource_start - regions.section_start));
   2550 
   2551   free (regions.section_start);
   2552   return TRUE;
   2553 }
   2554 
   2555 #define IMAGE_NUMBEROF_DEBUG_TYPES 12
   2556 
   2557 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
   2558 {
   2559   "Unknown",
   2560   "COFF",
   2561   "CodeView",
   2562   "FPO",
   2563   "Misc",
   2564   "Exception",
   2565   "Fixup",
   2566   "OMAP-to-SRC",
   2567   "OMAP-from-SRC",
   2568   "Borland",
   2569   "Reserved",
   2570   "CLSID",
   2571 };
   2572 
   2573 static bfd_boolean
   2574 pe_print_debugdata (bfd * abfd, void * vfile)
   2575 {
   2576   FILE *file = (FILE *) vfile;
   2577   pe_data_type *pe = pe_data (abfd);
   2578   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   2579   asection *section;
   2580   bfd_byte *data = 0;
   2581   bfd_size_type dataoff;
   2582   unsigned int i;
   2583 
   2584   bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
   2585   bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
   2586 
   2587   if (size == 0)
   2588     return TRUE;
   2589 
   2590   addr += extra->ImageBase;
   2591   for (section = abfd->sections; section != NULL; section = section->next)
   2592     {
   2593       if ((addr >= section->vma) && (addr < (section->vma + section->size)))
   2594         break;
   2595     }
   2596 
   2597   if (section == NULL)
   2598     {
   2599       fprintf (file,
   2600                _("\nThere is a debug directory, but the section containing it could not be found\n"));
   2601       return TRUE;
   2602     }
   2603   else if (!(section->flags & SEC_HAS_CONTENTS))
   2604     {
   2605       fprintf (file,
   2606                _("\nThere is a debug directory in %s, but that section has no contents\n"),
   2607                section->name);
   2608       return TRUE;
   2609     }
   2610   else if (section->size < size)
   2611     {
   2612       fprintf (file,
   2613                _("\nError: section %s contains the debug data starting address but it is too small\n"),
   2614                section->name);
   2615       return FALSE;
   2616     }
   2617 
   2618   fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
   2619 	   section->name, (unsigned long) addr);
   2620 
   2621   dataoff = addr - section->vma;
   2622 
   2623   if (size > (section->size - dataoff))
   2624     {
   2625       fprintf (file, _("The debug data size field in the data directory is too big for the section"));
   2626       return FALSE;
   2627     }
   2628 
   2629   fprintf (file,
   2630 	   _("Type                Size     Rva      Offset\n"));
   2631 
   2632   /* Read the whole section.  */
   2633   if (!bfd_malloc_and_get_section (abfd, section, &data))
   2634     {
   2635       if (data != NULL)
   2636 	free (data);
   2637       return FALSE;
   2638     }
   2639 
   2640   for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
   2641     {
   2642       const char *type_name;
   2643       struct external_IMAGE_DEBUG_DIRECTORY *ext
   2644 	= &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
   2645       struct internal_IMAGE_DEBUG_DIRECTORY idd;
   2646 
   2647       _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
   2648 
   2649       if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
   2650         type_name = debug_type_names[0];
   2651       else
   2652         type_name = debug_type_names[idd.Type];
   2653 
   2654       fprintf (file, " %2ld  %14s %08lx %08lx %08lx\n",
   2655 	       idd.Type, type_name, idd.SizeOfData,
   2656 	       idd.AddressOfRawData, idd.PointerToRawData);
   2657 
   2658       if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
   2659         {
   2660           char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
   2661           char buffer[256 + 1];
   2662           CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
   2663 
   2664           /* The debug entry doesn't have to have to be in a section,
   2665 	     in which case AddressOfRawData is 0, so always use PointerToRawData.  */
   2666           if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
   2667 					       idd.SizeOfData, cvinfo))
   2668             continue;
   2669 
   2670           for (i = 0; i < cvinfo->SignatureLength; i++)
   2671             sprintf (&signature[i*2], "%02x", cvinfo->Signature[i] & 0xff);
   2672 
   2673           fprintf (file, "(format %c%c%c%c signature %s age %ld)\n",
   2674 		   buffer[0], buffer[1], buffer[2], buffer[3],
   2675 		   signature, cvinfo->Age);
   2676         }
   2677     }
   2678 
   2679   if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
   2680     fprintf (file,
   2681             _("The debug directory size is not a multiple of the debug directory entry size\n"));
   2682 
   2683   return TRUE;
   2684 }
   2685 
   2686 /* Print out the program headers.  */
   2687 
   2688 bfd_boolean
   2689 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
   2690 {
   2691   FILE *file = (FILE *) vfile;
   2692   int j;
   2693   pe_data_type *pe = pe_data (abfd);
   2694   struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
   2695   const char *subsystem_name = NULL;
   2696   const char *name;
   2697 
   2698   /* The MS dumpbin program reportedly ands with 0xff0f before
   2699      printing the characteristics field.  Not sure why.  No reason to
   2700      emulate it here.  */
   2701   fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
   2702 #undef PF
   2703 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
   2704   PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
   2705   PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
   2706   PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
   2707   PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
   2708   PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
   2709   PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
   2710   PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
   2711   PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
   2712   PF (IMAGE_FILE_SYSTEM, "system file");
   2713   PF (IMAGE_FILE_DLL, "DLL");
   2714   PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
   2715 #undef PF
   2716 
   2717   /* ctime implies '\n'.  */
   2718   {
   2719     time_t t = pe->coff.timestamp;
   2720     fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
   2721   }
   2722 
   2723 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
   2724 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
   2725 #endif
   2726 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
   2727 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
   2728 #endif
   2729 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
   2730 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
   2731 #endif
   2732 
   2733   switch (i->Magic)
   2734     {
   2735     case IMAGE_NT_OPTIONAL_HDR_MAGIC:
   2736       name = "PE32";
   2737       break;
   2738     case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
   2739       name = "PE32+";
   2740       break;
   2741     case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
   2742       name = "ROM";
   2743       break;
   2744     default:
   2745       name = NULL;
   2746       break;
   2747     }
   2748   fprintf (file, "Magic\t\t\t%04x", i->Magic);
   2749   if (name)
   2750     fprintf (file, "\t(%s)",name);
   2751   fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
   2752   fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
   2753   fprintf (file, "SizeOfCode\t\t%08lx\n", (unsigned long) i->SizeOfCode);
   2754   fprintf (file, "SizeOfInitializedData\t%08lx\n",
   2755 	   (unsigned long) i->SizeOfInitializedData);
   2756   fprintf (file, "SizeOfUninitializedData\t%08lx\n",
   2757 	   (unsigned long) i->SizeOfUninitializedData);
   2758   fprintf (file, "AddressOfEntryPoint\t");
   2759   bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
   2760   fprintf (file, "\nBaseOfCode\t\t");
   2761   bfd_fprintf_vma (abfd, file, i->BaseOfCode);
   2762 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   2763   /* PE32+ does not have BaseOfData member!  */
   2764   fprintf (file, "\nBaseOfData\t\t");
   2765   bfd_fprintf_vma (abfd, file, i->BaseOfData);
   2766 #endif
   2767 
   2768   fprintf (file, "\nImageBase\t\t");
   2769   bfd_fprintf_vma (abfd, file, i->ImageBase);
   2770   fprintf (file, "\nSectionAlignment\t");
   2771   bfd_fprintf_vma (abfd, file, i->SectionAlignment);
   2772   fprintf (file, "\nFileAlignment\t\t");
   2773   bfd_fprintf_vma (abfd, file, i->FileAlignment);
   2774   fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
   2775   fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
   2776   fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
   2777   fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
   2778   fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
   2779   fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
   2780   fprintf (file, "Win32Version\t\t%08lx\n", (unsigned long) i->Reserved1);
   2781   fprintf (file, "SizeOfImage\t\t%08lx\n", (unsigned long) i->SizeOfImage);
   2782   fprintf (file, "SizeOfHeaders\t\t%08lx\n", (unsigned long) i->SizeOfHeaders);
   2783   fprintf (file, "CheckSum\t\t%08lx\n", (unsigned long) i->CheckSum);
   2784 
   2785   switch (i->Subsystem)
   2786     {
   2787     case IMAGE_SUBSYSTEM_UNKNOWN:
   2788       subsystem_name = "unspecified";
   2789       break;
   2790     case IMAGE_SUBSYSTEM_NATIVE:
   2791       subsystem_name = "NT native";
   2792       break;
   2793     case IMAGE_SUBSYSTEM_WINDOWS_GUI:
   2794       subsystem_name = "Windows GUI";
   2795       break;
   2796     case IMAGE_SUBSYSTEM_WINDOWS_CUI:
   2797       subsystem_name = "Windows CUI";
   2798       break;
   2799     case IMAGE_SUBSYSTEM_POSIX_CUI:
   2800       subsystem_name = "POSIX CUI";
   2801       break;
   2802     case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
   2803       subsystem_name = "Wince CUI";
   2804       break;
   2805     // These are from UEFI Platform Initialization Specification 1.1.
   2806     case IMAGE_SUBSYSTEM_EFI_APPLICATION:
   2807       subsystem_name = "EFI application";
   2808       break;
   2809     case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
   2810       subsystem_name = "EFI boot service driver";
   2811       break;
   2812     case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
   2813       subsystem_name = "EFI runtime driver";
   2814       break;
   2815     case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
   2816       subsystem_name = "SAL runtime driver";
   2817       break;
   2818     // This is from revision 8.0 of the MS PE/COFF spec
   2819     case IMAGE_SUBSYSTEM_XBOX:
   2820       subsystem_name = "XBOX";
   2821       break;
   2822     // Added default case for clarity - subsystem_name is NULL anyway.
   2823     default:
   2824       subsystem_name = NULL;
   2825     }
   2826 
   2827   fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
   2828   if (subsystem_name)
   2829     fprintf (file, "\t(%s)", subsystem_name);
   2830   fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
   2831   fprintf (file, "SizeOfStackReserve\t");
   2832   bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
   2833   fprintf (file, "\nSizeOfStackCommit\t");
   2834   bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
   2835   fprintf (file, "\nSizeOfHeapReserve\t");
   2836   bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
   2837   fprintf (file, "\nSizeOfHeapCommit\t");
   2838   bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
   2839   fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
   2840   fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
   2841 	   (unsigned long) i->NumberOfRvaAndSizes);
   2842 
   2843   fprintf (file, "\nThe Data Directory\n");
   2844   for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
   2845     {
   2846       fprintf (file, "Entry %1x ", j);
   2847       bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
   2848       fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
   2849       fprintf (file, "%s\n", dir_names[j]);
   2850     }
   2851 
   2852   pe_print_idata (abfd, vfile);
   2853   pe_print_edata (abfd, vfile);
   2854   if (bfd_coff_have_print_pdata (abfd))
   2855     bfd_coff_print_pdata (abfd, vfile);
   2856   else
   2857     pe_print_pdata (abfd, vfile);
   2858   pe_print_reloc (abfd, vfile);
   2859   pe_print_debugdata (abfd, file);
   2860 
   2861   rsrc_print_section (abfd, vfile);
   2862 
   2863   return TRUE;
   2864 }
   2865 
   2866 static bfd_boolean
   2867 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
   2868 {
   2869   bfd_vma addr = * (bfd_vma *) obj;
   2870   return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
   2871 }
   2872 
   2873 static asection *
   2874 find_section_by_vma (bfd *abfd, bfd_vma addr)
   2875 {
   2876   return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
   2877 }
   2878 
   2879 /* Copy any private info we understand from the input bfd
   2880    to the output bfd.  */
   2881 
   2882 bfd_boolean
   2883 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
   2884 {
   2885   pe_data_type *ipe, *ope;
   2886 
   2887   /* One day we may try to grok other private data.  */
   2888   if (ibfd->xvec->flavour != bfd_target_coff_flavour
   2889       || obfd->xvec->flavour != bfd_target_coff_flavour)
   2890     return TRUE;
   2891 
   2892   ipe = pe_data (ibfd);
   2893   ope = pe_data (obfd);
   2894 
   2895   /* pe_opthdr is copied in copy_object.  */
   2896   ope->dll = ipe->dll;
   2897 
   2898   /* Don't copy input subsystem if output is different from input.  */
   2899   if (obfd->xvec != ibfd->xvec)
   2900     ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
   2901 
   2902   /* For strip: if we removed .reloc, we'll make a real mess of things
   2903      if we don't remove this entry as well.  */
   2904   if (! pe_data (obfd)->has_reloc_section)
   2905     {
   2906       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
   2907       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
   2908     }
   2909 
   2910   /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
   2911      But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
   2912      won't be added.  */
   2913   if (! pe_data (ibfd)->has_reloc_section
   2914       && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
   2915     pe_data (obfd)->dont_strip_reloc = 1;
   2916 
   2917   /* The file offsets contained in the debug directory need rewriting.  */
   2918   if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0)
   2919     {
   2920       bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
   2921 	+ ope->pe_opthdr.ImageBase;
   2922       asection *section = find_section_by_vma (obfd, addr);
   2923       bfd_byte *data;
   2924 
   2925       if (section && bfd_malloc_and_get_section (obfd, section, &data))
   2926         {
   2927           unsigned int i;
   2928           struct external_IMAGE_DEBUG_DIRECTORY *dd =
   2929 	    (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma));
   2930 
   2931           for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
   2932 		 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
   2933             {
   2934               asection *ddsection;
   2935               struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
   2936               struct internal_IMAGE_DEBUG_DIRECTORY idd;
   2937 
   2938               _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
   2939 
   2940               if (idd.AddressOfRawData == 0)
   2941                 continue; /* RVA 0 means only offset is valid, not handled yet.  */
   2942 
   2943               ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase);
   2944               if (!ddsection)
   2945                 continue; /* Not in a section! */
   2946 
   2947               idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData
   2948 							   + ope->pe_opthdr.ImageBase) - ddsection->vma;
   2949 
   2950               _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
   2951             }
   2952 
   2953           if (!bfd_set_section_contents (obfd, section, data, 0, section->size))
   2954             _bfd_error_handler (_("Failed to update file offsets in debug directory"));
   2955         }
   2956     }
   2957 
   2958   return TRUE;
   2959 }
   2960 
   2961 /* Copy private section data.  */
   2962 
   2963 bfd_boolean
   2964 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
   2965 				       asection *isec,
   2966 				       bfd *obfd,
   2967 				       asection *osec)
   2968 {
   2969   if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
   2970       || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
   2971     return TRUE;
   2972 
   2973   if (coff_section_data (ibfd, isec) != NULL
   2974       && pei_section_data (ibfd, isec) != NULL)
   2975     {
   2976       if (coff_section_data (obfd, osec) == NULL)
   2977 	{
   2978 	  bfd_size_type amt = sizeof (struct coff_section_tdata);
   2979 	  osec->used_by_bfd = bfd_zalloc (obfd, amt);
   2980 	  if (osec->used_by_bfd == NULL)
   2981 	    return FALSE;
   2982 	}
   2983 
   2984       if (pei_section_data (obfd, osec) == NULL)
   2985 	{
   2986 	  bfd_size_type amt = sizeof (struct pei_section_tdata);
   2987 	  coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
   2988 	  if (coff_section_data (obfd, osec)->tdata == NULL)
   2989 	    return FALSE;
   2990 	}
   2991 
   2992       pei_section_data (obfd, osec)->virt_size =
   2993 	pei_section_data (ibfd, isec)->virt_size;
   2994       pei_section_data (obfd, osec)->pe_flags =
   2995 	pei_section_data (ibfd, isec)->pe_flags;
   2996     }
   2997 
   2998   return TRUE;
   2999 }
   3000 
   3001 void
   3002 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
   3003 {
   3004   coff_get_symbol_info (abfd, symbol, ret);
   3005 }
   3006 
   3007 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
   3008 static int
   3009 sort_x64_pdata (const void *l, const void *r)
   3010 {
   3011   const char *lp = (const char *) l;
   3012   const char *rp = (const char *) r;
   3013   bfd_vma vl, vr;
   3014   vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
   3015   if (vl != vr)
   3016     return (vl < vr ? -1 : 1);
   3017   /* We compare just begin address.  */
   3018   return 0;
   3019 }
   3020 #endif
   3021 
   3022 /* Functions to process a .rsrc section.  */
   3024 
   3025 static unsigned int sizeof_leaves;
   3026 static unsigned int sizeof_strings;
   3027 static unsigned int sizeof_tables_and_entries;
   3028 
   3029 static bfd_byte *
   3030 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
   3031 
   3032 static bfd_byte *
   3033 rsrc_count_entries (bfd *          abfd,
   3034 		    bfd_boolean    is_name,
   3035 		    bfd_byte *     datastart,
   3036 		    bfd_byte *     data,
   3037 		    bfd_byte *     dataend,
   3038 		    bfd_vma        rva_bias)
   3039 {
   3040   unsigned long entry, addr, size;
   3041 
   3042   if (data + 8 >= dataend)
   3043     return dataend + 1;
   3044 
   3045   if (is_name)
   3046     {
   3047       bfd_byte * name;
   3048 
   3049       entry = (long) bfd_get_32 (abfd, data);
   3050 
   3051       if (HighBitSet (entry))
   3052 	name = datastart + WithoutHighBit (entry);
   3053       else
   3054 	name = datastart + entry - rva_bias;
   3055 
   3056       if (name + 2 >= dataend || name < datastart)
   3057 	return dataend + 1;
   3058 
   3059       unsigned int len = bfd_get_16 (abfd, name);
   3060       if (len == 0 || len > 256)
   3061 	return dataend + 1;
   3062     }
   3063 
   3064   entry = (long) bfd_get_32 (abfd, data + 4);
   3065 
   3066   if (HighBitSet (entry))
   3067     {
   3068       data = datastart + WithoutHighBit (entry);
   3069 
   3070       if (data <= datastart || data >= dataend)
   3071 	return dataend + 1;
   3072 
   3073       return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
   3074     }
   3075 
   3076   if (datastart + entry + 16 >= dataend)
   3077     return dataend + 1;
   3078 
   3079   addr = (long) bfd_get_32 (abfd, datastart + entry);
   3080   size = (long) bfd_get_32 (abfd, datastart + entry + 4);
   3081 
   3082   return datastart + addr - rva_bias + size;
   3083 }
   3084 
   3085 static bfd_byte *
   3086 rsrc_count_directory (bfd *          abfd,
   3087 		      bfd_byte *     datastart,
   3088 		      bfd_byte *     data,
   3089 		      bfd_byte *     dataend,
   3090 		      bfd_vma        rva_bias)
   3091 {
   3092   unsigned int  num_entries, num_ids;
   3093   bfd_byte *    highest_data = data;
   3094 
   3095   if (data + 16 >= dataend)
   3096     return dataend + 1;
   3097 
   3098   num_entries  = (int) bfd_get_16 (abfd, data + 12);
   3099   num_ids      = (int) bfd_get_16 (abfd, data + 14);
   3100 
   3101   num_entries += num_ids;
   3102 
   3103   data += 16;
   3104 
   3105   while (num_entries --)
   3106     {
   3107       bfd_byte * entry_end;
   3108 
   3109       entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
   3110 				      datastart, data, dataend, rva_bias);
   3111       data += 8;
   3112       highest_data = max (highest_data, entry_end);
   3113       if (entry_end >= dataend)
   3114 	break;
   3115     }
   3116 
   3117   return max (highest_data, data);
   3118 }
   3119 
   3120 typedef struct rsrc_dir_chain
   3121 {
   3122   unsigned int         num_entries;
   3123   struct rsrc_entry *  first_entry;
   3124   struct rsrc_entry *  last_entry;
   3125 } rsrc_dir_chain;
   3126 
   3127 typedef struct rsrc_directory
   3128 {
   3129   unsigned int characteristics;
   3130   unsigned int time;
   3131   unsigned int major;
   3132   unsigned int minor;
   3133 
   3134   rsrc_dir_chain names;
   3135   rsrc_dir_chain ids;
   3136 
   3137   struct rsrc_entry * entry;
   3138 } rsrc_directory;
   3139 
   3140 typedef struct rsrc_string
   3141 {
   3142   unsigned int  len;
   3143   bfd_byte *    string;
   3144 } rsrc_string;
   3145 
   3146 typedef struct rsrc_leaf
   3147 {
   3148   unsigned int  size;
   3149   unsigned int  codepage;
   3150   bfd_byte *    data;
   3151 } rsrc_leaf;
   3152 
   3153 typedef struct rsrc_entry
   3154 {
   3155   bfd_boolean is_name;
   3156   union
   3157   {
   3158     unsigned int          id;
   3159     struct rsrc_string    name;
   3160   } name_id;
   3161 
   3162   bfd_boolean is_dir;
   3163   union
   3164   {
   3165     struct rsrc_directory * directory;
   3166     struct rsrc_leaf *      leaf;
   3167   } value;
   3168 
   3169   struct rsrc_entry *     next_entry;
   3170   struct rsrc_directory * parent;
   3171 } rsrc_entry;
   3172 
   3173 static bfd_byte *
   3174 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
   3175 		      bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
   3176 
   3177 static bfd_byte *
   3178 rsrc_parse_entry (bfd *            abfd,
   3179 		  bfd_boolean      is_name,
   3180 		  rsrc_entry *     entry,
   3181 		  bfd_byte *       datastart,
   3182 		  bfd_byte *       data,
   3183 		  bfd_byte *       dataend,
   3184 		  bfd_vma          rva_bias,
   3185 		  rsrc_directory * parent)
   3186 {
   3187   unsigned long val, addr, size;
   3188 
   3189   val = bfd_get_32 (abfd, data);
   3190 
   3191   entry->parent = parent;
   3192   entry->is_name = is_name;
   3193 
   3194   if (is_name)
   3195     {
   3196       bfd_byte * address;
   3197 
   3198       if (HighBitSet (val))
   3199 	{
   3200 	  val = WithoutHighBit (val);
   3201 
   3202 	  address = datastart + val;
   3203 	}
   3204       else
   3205 	{
   3206 	  address = datastart + val - rva_bias;
   3207 	}
   3208 
   3209       if (address + 3 > dataend)
   3210 	return dataend;
   3211 
   3212       entry->name_id.name.len    = bfd_get_16 (abfd, address);
   3213       entry->name_id.name.string = address + 2;
   3214     }
   3215   else
   3216     entry->name_id.id = val;
   3217 
   3218   val = bfd_get_32 (abfd, data + 4);
   3219 
   3220   if (HighBitSet (val))
   3221     {
   3222       entry->is_dir = TRUE;
   3223       entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
   3224       if (entry->value.directory == NULL)
   3225 	return dataend;
   3226 
   3227       return rsrc_parse_directory (abfd, entry->value.directory,
   3228 				   datastart,
   3229 				   datastart + WithoutHighBit (val),
   3230 				   dataend, rva_bias, entry);
   3231     }
   3232 
   3233   entry->is_dir = FALSE;
   3234   entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
   3235   if (entry->value.leaf == NULL)
   3236     return dataend;
   3237 
   3238   addr = bfd_get_32 (abfd, datastart + val);
   3239   size = entry->value.leaf->size = bfd_get_32 (abfd, datastart + val + 4);
   3240   entry->value.leaf->codepage = bfd_get_32 (abfd, datastart + val + 8);
   3241 
   3242   entry->value.leaf->data = bfd_malloc (size);
   3243   if (entry->value.leaf->data == NULL)
   3244     return dataend;
   3245 
   3246   memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
   3247   return datastart + (addr - rva_bias) + size;
   3248 }
   3249 
   3250 static bfd_byte *
   3251 rsrc_parse_entries (bfd *            abfd,
   3252 		    rsrc_dir_chain * chain,
   3253 		    bfd_boolean      is_name,
   3254 		    bfd_byte *       highest_data,
   3255 		    bfd_byte *       datastart,
   3256 		    bfd_byte *       data,
   3257 		    bfd_byte *       dataend,
   3258 		    bfd_vma          rva_bias,
   3259 		    rsrc_directory * parent)
   3260 {
   3261   unsigned int i;
   3262   rsrc_entry * entry;
   3263 
   3264   if (chain->num_entries == 0)
   3265     {
   3266       chain->first_entry = chain->last_entry = NULL;
   3267       return highest_data;
   3268     }
   3269 
   3270   entry = bfd_malloc (sizeof * entry);
   3271   if (entry == NULL)
   3272     return dataend;
   3273 
   3274   chain->first_entry = entry;
   3275 
   3276   for (i = chain->num_entries; i--;)
   3277     {
   3278       bfd_byte * entry_end;
   3279 
   3280       entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
   3281 				    data, dataend, rva_bias, parent);
   3282       data += 8;
   3283       highest_data = max (entry_end, highest_data);
   3284       if (entry_end > dataend)
   3285 	return dataend;
   3286 
   3287       if (i)
   3288 	{
   3289 	  entry->next_entry = bfd_malloc (sizeof * entry);
   3290 	  entry = entry->next_entry;
   3291 	  if (entry == NULL)
   3292 	    return dataend;
   3293 	}
   3294       else
   3295 	entry->next_entry = NULL;
   3296     }
   3297 
   3298   chain->last_entry = entry;
   3299 
   3300   return highest_data;
   3301 }
   3302 
   3303 static bfd_byte *
   3304 rsrc_parse_directory (bfd *            abfd,
   3305 		      rsrc_directory * table,
   3306 		      bfd_byte *       datastart,
   3307 		      bfd_byte *       data,
   3308 		      bfd_byte *       dataend,
   3309 		      bfd_vma          rva_bias,
   3310 		      rsrc_entry *     entry)
   3311 {
   3312   bfd_byte * highest_data = data;
   3313 
   3314   if (table == NULL)
   3315     return dataend;
   3316 
   3317   table->characteristics = bfd_get_32 (abfd, data);
   3318   table->time = bfd_get_32 (abfd, data + 4);
   3319   table->major = bfd_get_16 (abfd, data + 8);
   3320   table->minor = bfd_get_16 (abfd, data + 10);
   3321   table->names.num_entries = bfd_get_16 (abfd, data + 12);
   3322   table->ids.num_entries = bfd_get_16 (abfd, data + 14);
   3323   table->entry = entry;
   3324 
   3325   data += 16;
   3326 
   3327   highest_data = rsrc_parse_entries (abfd, & table->names, TRUE, data,
   3328 				     datastart, data, dataend, rva_bias, table);
   3329   data += table->names.num_entries * 8;
   3330 
   3331   highest_data = rsrc_parse_entries (abfd, & table->ids, FALSE, highest_data,
   3332 				     datastart, data, dataend, rva_bias, table);
   3333   data += table->ids.num_entries * 8;
   3334 
   3335   return max (highest_data, data);
   3336 }
   3337 
   3338 typedef struct rsrc_write_data
   3339 {
   3340   bfd *      abfd;
   3341   bfd_byte * datastart;
   3342   bfd_byte * next_table;
   3343   bfd_byte * next_leaf;
   3344   bfd_byte * next_string;
   3345   bfd_byte * next_data;
   3346   bfd_vma    rva_bias;
   3347 } rsrc_write_data;
   3348 
   3349 static void
   3350 rsrc_write_string (rsrc_write_data * data,
   3351 		   rsrc_string *     string)
   3352 {
   3353   bfd_put_16 (data->abfd, string->len, data->next_string);
   3354   memcpy (data->next_string + 2, string->string, string->len * 2);
   3355   data->next_string += (string->len + 1) * 2;
   3356 }
   3357 
   3358 static inline unsigned int
   3359 rsrc_compute_rva (rsrc_write_data * data,
   3360 		  bfd_byte *        addr)
   3361 {
   3362   return (addr - data->datastart) + data->rva_bias;
   3363 }
   3364 
   3365 static void
   3366 rsrc_write_leaf (rsrc_write_data * data,
   3367 		 rsrc_leaf *       leaf)
   3368 {
   3369   bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
   3370 	      data->next_leaf);
   3371   bfd_put_32 (data->abfd, leaf->size,     data->next_leaf + 4);
   3372   bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
   3373   bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
   3374   data->next_leaf += 16;
   3375 
   3376   memcpy (data->next_data, leaf->data, leaf->size);
   3377   /* An undocumented feature of Windows resources is that each unit
   3378      of raw data is 8-byte aligned...  */
   3379   data->next_data += ((leaf->size + 7) & ~7);
   3380 }
   3381 
   3382 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
   3383 
   3384 static void
   3385 rsrc_write_entry (rsrc_write_data *  data,
   3386 		  bfd_byte *         where,
   3387 		  rsrc_entry *       entry)
   3388 {
   3389   if (entry->is_name)
   3390     {
   3391       bfd_put_32 (data->abfd,
   3392 		  SetHighBit (data->next_string - data->datastart),
   3393 		  where);
   3394       rsrc_write_string (data, & entry->name_id.name);
   3395     }
   3396   else
   3397     bfd_put_32 (data->abfd, entry->name_id.id, where);
   3398 
   3399   if (entry->is_dir)
   3400     {
   3401       bfd_put_32 (data->abfd,
   3402 		  SetHighBit (data->next_table - data->datastart),
   3403 		  where + 4);
   3404       rsrc_write_directory (data, entry->value.directory);
   3405     }
   3406   else
   3407     {
   3408       bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
   3409       rsrc_write_leaf (data, entry->value.leaf);
   3410     }
   3411 }
   3412 
   3413 static void
   3414 rsrc_compute_region_sizes (rsrc_directory * dir)
   3415 {
   3416   struct rsrc_entry * entry;
   3417 
   3418   if (dir == NULL)
   3419     return;
   3420 
   3421   sizeof_tables_and_entries += 16;
   3422 
   3423   for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
   3424     {
   3425       sizeof_tables_and_entries += 8;
   3426 
   3427       sizeof_strings += (entry->name_id.name.len + 1) * 2;
   3428 
   3429       if (entry->is_dir)
   3430 	rsrc_compute_region_sizes (entry->value.directory);
   3431       else
   3432 	sizeof_leaves += 16;
   3433     }
   3434 
   3435   for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
   3436     {
   3437       sizeof_tables_and_entries += 8;
   3438 
   3439       if (entry->is_dir)
   3440 	rsrc_compute_region_sizes (entry->value.directory);
   3441       else
   3442 	sizeof_leaves += 16;
   3443     }
   3444 }
   3445 
   3446 static void
   3447 rsrc_write_directory (rsrc_write_data * data,
   3448 		      rsrc_directory *  dir)
   3449 {
   3450   rsrc_entry * entry;
   3451   unsigned int i;
   3452   bfd_byte * next_entry;
   3453   bfd_byte * nt;
   3454 
   3455   bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
   3456   bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
   3457   bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
   3458   bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
   3459   bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
   3460   bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
   3461 
   3462   /* Compute where the entries and the next table will be placed.  */
   3463   next_entry = data->next_table + 16;
   3464   data->next_table = next_entry + (dir->names.num_entries * 8)
   3465     + (dir->ids.num_entries * 8);
   3466   nt = data->next_table;
   3467 
   3468   /* Write the entries.  */
   3469   for (i = dir->names.num_entries, entry = dir->names.first_entry;
   3470        i > 0 && entry != NULL;
   3471        i--, entry = entry->next_entry)
   3472     {
   3473       BFD_ASSERT (entry->is_name);
   3474       rsrc_write_entry (data, next_entry, entry);
   3475       next_entry += 8;
   3476     }
   3477   BFD_ASSERT (i == 0);
   3478   BFD_ASSERT (entry == NULL);
   3479 
   3480   for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
   3481        i > 0 && entry != NULL;
   3482        i--, entry = entry->next_entry)
   3483     {
   3484       BFD_ASSERT (! entry->is_name);
   3485       rsrc_write_entry (data, next_entry, entry);
   3486       next_entry += 8;
   3487     }
   3488   BFD_ASSERT (i == 0);
   3489   BFD_ASSERT (entry == NULL);
   3490   BFD_ASSERT (nt == next_entry);
   3491 }
   3492 
   3493 #if defined HAVE_WCHAR_H && ! defined __CYGWIN__ && ! defined __MINGW32__
   3494 /* Return the length (number of units) of the first character in S,
   3495    putting its 'ucs4_t' representation in *PUC.  */
   3496 
   3497 static unsigned int
   3498 #if defined HAVE_WCTYPE_H
   3499 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
   3500 #else
   3501 u16_mbtouc (wchar_t * puc, const unsigned short * s, unsigned int n)
   3502 #endif
   3503 {
   3504   unsigned short c = * s;
   3505 
   3506   if (c < 0xd800 || c >= 0xe000)
   3507     {
   3508       *puc = c;
   3509       return 1;
   3510     }
   3511 
   3512   if (c < 0xdc00)
   3513     {
   3514       if (n >= 2)
   3515         {
   3516           if (s[1] >= 0xdc00 && s[1] < 0xe000)
   3517             {
   3518               *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
   3519               return 2;
   3520             }
   3521         }
   3522       else
   3523         {
   3524           /* Incomplete multibyte character.  */
   3525           *puc = 0xfffd;
   3526           return n;
   3527         }
   3528     }
   3529 
   3530   /* Invalid multibyte character.  */
   3531   *puc = 0xfffd;
   3532   return 1;
   3533 }
   3534 #endif /* HAVE_WCHAR_H and not Cygwin/Mingw */
   3535 
   3536 /* Perform a comparison of two entries.  */
   3537 static signed int
   3538 rsrc_cmp (bfd_boolean is_name, rsrc_entry * a, rsrc_entry * b)
   3539 {
   3540   signed int    res;
   3541   bfd_byte *    astring;
   3542   unsigned int  alen;
   3543   bfd_byte *    bstring;
   3544   unsigned int  blen;
   3545 
   3546   if (! is_name)
   3547     return a->name_id.id - b->name_id.id;
   3548 
   3549   /* We have to perform a case insenstive, unicode string comparison...  */
   3550   astring = a->name_id.name.string;
   3551   alen    = a->name_id.name.len;
   3552   bstring = b->name_id.name.string;
   3553   blen    = b->name_id.name.len;
   3554 
   3555 #if defined  __CYGWIN__ || defined __MINGW32__
   3556   /* Under Windows hosts (both Cygwin and Mingw types),
   3557      unicode == UTF-16 == wchar_t.  The case insensitive string comparison
   3558      function however goes by different names in the two environments...  */
   3559 
   3560 #undef rscpcmp
   3561 #ifdef __CYGWIN__
   3562 #define rscpcmp wcsncasecmp
   3563 #endif
   3564 #ifdef __MINGW32__
   3565 #define rscpcmp wcsnicmp
   3566 #endif
   3567 
   3568   res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
   3569 		 min (alen, blen));
   3570 
   3571 #elif defined HAVE_WCHAR_H
   3572   {
   3573     unsigned int  i;
   3574 
   3575     res = 0;
   3576     for (i = min (alen, blen); i--; astring += 2, bstring += 2)
   3577       {
   3578 #if defined HAVE_WCTYPE_H
   3579 	wint_t awc;
   3580 	wint_t bwc;
   3581 #else
   3582 	wchar_t awc;
   3583 	wchar_t bwc;
   3584 #endif
   3585 
   3586 	/* Convert UTF-16 unicode characters into wchar_t characters
   3587 	   so that we can then perform a case insensitive comparison.  */
   3588 	unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
   3589 	unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
   3590 
   3591 	if (Alen != Blen)
   3592 	  return Alen - Blen;
   3593 
   3594 #ifdef HAVE_WCTYPE_H
   3595 	awc = towlower (awc);
   3596 	bwc = towlower (bwc);
   3597 
   3598 	res = awc - bwc;
   3599 #else
   3600 	res = wcsncasecmp (& awc, & bwc, 1);
   3601 #endif
   3602 	if (res)
   3603 	  break;
   3604       }
   3605   }
   3606 #else
   3607   /* Do the best we can - a case sensitive, untranslated comparison.  */
   3608   res = memcmp (astring, bstring, min (alen, blen) * 2);
   3609 #endif
   3610 
   3611   if (res == 0)
   3612     res = alen - blen;
   3613 
   3614   return res;
   3615 }
   3616 
   3617 static void
   3618 rsrc_print_name (char * buffer, rsrc_string string)
   3619 {
   3620   unsigned int  i;
   3621   bfd_byte *    name = string.string;
   3622 
   3623   for (i = string.len; i--; name += 2)
   3624     sprintf (buffer + strlen (buffer), "%.1s", name);
   3625 }
   3626 
   3627 static const char *
   3628 rsrc_resource_name (rsrc_entry * entry, rsrc_directory * dir)
   3629 {
   3630   static char buffer [256];
   3631   bfd_boolean is_string = FALSE;
   3632 
   3633   buffer[0] = 0;
   3634 
   3635   if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
   3636       && dir->entry->parent->entry != NULL)
   3637     {
   3638       strcpy (buffer, "type: ");
   3639       if (dir->entry->parent->entry->is_name)
   3640 	rsrc_print_name (buffer + strlen (buffer),
   3641 			 dir->entry->parent->entry->name_id.name);
   3642       else
   3643 	{
   3644 	  unsigned int id = dir->entry->parent->entry->name_id.id;
   3645 
   3646 	  sprintf (buffer + strlen (buffer), "%x", id);
   3647 	  switch (id)
   3648 	    {
   3649 	    case 1: strcat (buffer, " (CURSOR)"); break;
   3650 	    case 2: strcat (buffer, " (BITMAP)"); break;
   3651 	    case 3: strcat (buffer, " (ICON)"); break;
   3652             case 4: strcat (buffer, " (MENU)"); break;
   3653 	    case 5: strcat (buffer, " (DIALOG)"); break;
   3654 	    case 6: strcat (buffer, " (STRING)"); is_string = TRUE; break;
   3655 	    case 7: strcat (buffer, " (FONTDIR)"); break;
   3656 	    case 8: strcat (buffer, " (FONT)"); break;
   3657 	    case 9: strcat (buffer, " (ACCELERATOR)"); break;
   3658 	    case 10: strcat (buffer, " (RCDATA)"); break;
   3659 	    case 11: strcat (buffer, " (MESSAGETABLE)"); break;
   3660 	    case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
   3661 	    case 14: strcat (buffer, " (GROUP_ICON)"); break;
   3662 	    case 16: strcat (buffer, " (VERSION)"); break;
   3663 	    case 17: strcat (buffer, " (DLGINCLUDE)"); break;
   3664 	    case 19: strcat (buffer, " (PLUGPLAY)"); break;
   3665 	    case 20: strcat (buffer, " (VXD)"); break;
   3666 	    case 21: strcat (buffer, " (ANICURSOR)"); break;
   3667 	    case 22: strcat (buffer, " (ANIICON)"); break;
   3668 	    case 23: strcat (buffer, " (HTML)"); break;
   3669 	    case 24: strcat (buffer, " (MANIFEST)"); break;
   3670 	    case 240: strcat (buffer, " (DLGINIT)"); break;
   3671 	    case 241: strcat (buffer, " (TOOLBAR)"); break;
   3672 	    }
   3673 	}
   3674     }
   3675 
   3676   if (dir != NULL && dir->entry != NULL)
   3677     {
   3678       strcat (buffer, " name: ");
   3679       if (dir->entry->is_name)
   3680 	rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
   3681       else
   3682 	{
   3683 	  unsigned int id = dir->entry->name_id.id;
   3684 
   3685 	  sprintf (buffer + strlen (buffer), "%x", id);
   3686 
   3687 	  if (is_string)
   3688 	    sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
   3689 		     (id - 1) << 4, (id << 4) - 1);
   3690 	}
   3691     }
   3692 
   3693   if (entry != NULL)
   3694     {
   3695       strcat (buffer, " lang: ");
   3696 
   3697       if (entry->is_name)
   3698 	rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
   3699       else
   3700 	sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
   3701     }
   3702 
   3703   return buffer;
   3704 }
   3705 
   3706 /* *sigh* Windows resource strings are special.  Only the top 28-bits of
   3707    their ID is stored in the NAME entry.  The bottom four bits are used as
   3708    an index into unicode string table that makes up the data of the leaf.
   3709    So identical type-name-lang string resources may not actually be
   3710    identical at all.
   3711 
   3712    This function is called when we have detected two string resources with
   3713    match top-28-bit IDs.  We have to scan the string tables inside the leaves
   3714    and discover if there are any real collisions.  If there are then we report
   3715    them and return FALSE.  Otherwise we copy any strings from B into A and
   3716    then return TRUE.  */
   3717 
   3718 static bfd_boolean
   3719 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
   3720 			   rsrc_entry * b ATTRIBUTE_UNUSED)
   3721 {
   3722   unsigned int copy_needed = 0;
   3723   unsigned int i;
   3724   bfd_byte * astring;
   3725   bfd_byte * bstring;
   3726   bfd_byte * new_data;
   3727   bfd_byte * nstring;
   3728 
   3729   /* Step one: Find out what we have to do.  */
   3730   BFD_ASSERT (! a->is_dir);
   3731   astring = a->value.leaf->data;
   3732 
   3733   BFD_ASSERT (! b->is_dir);
   3734   bstring = b->value.leaf->data;
   3735 
   3736   for (i = 0; i < 16; i++)
   3737     {
   3738       unsigned int alen = astring[0] + (astring[1] << 8);
   3739       unsigned int blen = bstring[0] + (bstring[1] << 8);
   3740 
   3741       if (alen == 0)
   3742 	{
   3743 	  copy_needed += blen * 2;
   3744 	}
   3745       else if (blen == 0)
   3746 	;
   3747       else if (alen != blen)
   3748 	/* FIXME: Should we continue the loop in order to report other duplicates ?  */
   3749 	break;
   3750       /* alen == blen != 0.  We might have two identical strings.  If so we
   3751 	 can ignore the second one.  There is no need for wchar_t vs UTF-16
   3752 	 theatrics here - we are only interested in (case sensitive) equality.  */
   3753       else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
   3754 	break;
   3755 
   3756       astring += (alen + 1) * 2;
   3757       bstring += (blen + 1) * 2;
   3758     }
   3759 
   3760   if (i != 16)
   3761     {
   3762       if (a->parent != NULL
   3763 	  && a->parent->entry != NULL
   3764 	  && a->parent->entry->is_name == FALSE)
   3765 	_bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
   3766 			    ((a->parent->entry->name_id.id - 1) << 4) + i);
   3767       return FALSE;
   3768     }
   3769 
   3770   if (copy_needed == 0)
   3771     return TRUE;
   3772 
   3773   /* If we reach here then A and B must both have non-colliding strings.
   3774      (We never get string resources with fully empty string tables).
   3775      We need to allocate an extra COPY_NEEDED bytes in A and then bring
   3776      in B's strings.  */
   3777   new_data = bfd_malloc (a->value.leaf->size + copy_needed);
   3778   if (new_data == NULL)
   3779     return FALSE;
   3780 
   3781   nstring = new_data;
   3782   astring = a->value.leaf->data;
   3783   bstring = b->value.leaf->data;
   3784 
   3785   for (i = 0; i < 16; i++)
   3786     {
   3787       unsigned int alen = astring[0] + (astring[1] << 8);
   3788       unsigned int blen = bstring[0] + (bstring[1] << 8);
   3789 
   3790       if (alen != 0)
   3791 	{
   3792 	  memcpy (nstring, astring, (alen + 1) * 2);
   3793 	  nstring += (alen + 1) * 2;
   3794 	}
   3795       else if (blen != 0)
   3796 	{
   3797 	  memcpy (nstring, bstring, (blen + 1) * 2);
   3798 	  nstring += (blen + 1) * 2;
   3799 	}
   3800       else
   3801 	{
   3802 	  * nstring++ = 0;
   3803 	  * nstring++ = 0;
   3804 	}
   3805 
   3806       astring += (alen + 1) * 2;
   3807       bstring += (blen + 1) * 2;
   3808     }
   3809 
   3810   BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
   3811 
   3812   free (a->value.leaf->data);
   3813   a->value.leaf->data = new_data;
   3814   a->value.leaf->size += copy_needed;
   3815 
   3816   return TRUE;
   3817 }
   3818 
   3819 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
   3820 
   3821 /* Sort the entries in given part of the directory.
   3822    We use an old fashioned bubble sort because we are dealing
   3823    with lists and we want to handle matches specially.  */
   3824 
   3825 static void
   3826 rsrc_sort_entries (rsrc_dir_chain *  chain,
   3827 		   bfd_boolean       is_name,
   3828 		   rsrc_directory *  dir)
   3829 {
   3830   rsrc_entry * entry;
   3831   rsrc_entry * next;
   3832   rsrc_entry ** points_to_entry;
   3833   bfd_boolean swapped;
   3834 
   3835   if (chain->num_entries < 2)
   3836     return;
   3837 
   3838   do
   3839     {
   3840       swapped = FALSE;
   3841       points_to_entry = & chain->first_entry;
   3842       entry = * points_to_entry;
   3843       next  = entry->next_entry;
   3844 
   3845       do
   3846 	{
   3847 	  signed int cmp = rsrc_cmp (is_name, entry, next);
   3848 
   3849 	  if (cmp > 0)
   3850 	    {
   3851 	      entry->next_entry = next->next_entry;
   3852 	      next->next_entry = entry;
   3853 	      * points_to_entry = next;
   3854 	      points_to_entry = & next->next_entry;
   3855 	      next = entry->next_entry;
   3856 	      swapped = TRUE;
   3857 	    }
   3858 	  else if (cmp == 0)
   3859 	    {
   3860 	      if (entry->is_dir && next->is_dir)
   3861 		{
   3862 		  /* When we encounter identical directory entries we have to
   3863 		     merge them together.  The exception to this rule is for
   3864 		     resource manifests - there can only be one of these,
   3865 		     even if they differ in language.  Zero-language manifests
   3866 		     are assumed to be default manifests (provided by the
   3867 		     Cygwin/MinGW build system) and these can be silently dropped,
   3868 		     unless that would reduce the number of manifests to zero.
   3869 		     There should only ever be one non-zero lang manifest -
   3870 		     if there are more it is an error.  A non-zero lang
   3871 		     manifest takes precedence over a default manifest.  */
   3872 		  if (entry->is_name == FALSE
   3873 		      && entry->name_id.id == 1
   3874 		      && dir != NULL
   3875 		      && dir->entry != NULL
   3876 		      && dir->entry->is_name == FALSE
   3877 		      && dir->entry->name_id.id == 0x18)
   3878 		    {
   3879 		      if (next->value.directory->names.num_entries == 0
   3880 			  && next->value.directory->ids.num_entries == 1
   3881 			  && next->value.directory->ids.first_entry->is_name == FALSE
   3882 			  && next->value.directory->ids.first_entry->name_id.id == 0)
   3883 			/* Fall through so that NEXT is dropped.  */
   3884 			;
   3885 		      else if (entry->value.directory->names.num_entries == 0
   3886 			       && entry->value.directory->ids.num_entries == 1
   3887 			       && entry->value.directory->ids.first_entry->is_name == FALSE
   3888 			       && entry->value.directory->ids.first_entry->name_id.id == 0)
   3889 			{
   3890 			  /* Swap ENTRY and NEXT.  Then fall through so that the old ENTRY is dropped.  */
   3891 			  entry->next_entry = next->next_entry;
   3892 			  next->next_entry = entry;
   3893 			  * points_to_entry = next;
   3894 			  points_to_entry = & next->next_entry;
   3895 			  next = entry->next_entry;
   3896 			  swapped = TRUE;
   3897 			}
   3898 		      else
   3899 			{
   3900 			  _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
   3901 			  bfd_set_error (bfd_error_file_truncated);
   3902 			  return;
   3903 			}
   3904 
   3905 		      /* Unhook NEXT from the chain.  */
   3906 		      /* FIXME: memory loss here.  */
   3907 		      entry->next_entry = next->next_entry;
   3908 		      chain->num_entries --;
   3909 		      if (chain->num_entries < 2)
   3910 			return;
   3911 		      next = next->next_entry;
   3912 		    }
   3913 		  else
   3914 		    rsrc_merge (entry, next);
   3915 		}
   3916 	      else if (entry->is_dir != next->is_dir)
   3917 		{
   3918 		  _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
   3919 		  bfd_set_error (bfd_error_file_truncated);
   3920 		  return;
   3921 		}
   3922 	      else
   3923 		{
   3924 		  /* Otherwise with identical leaves we issue an error
   3925 		     message - because there should never be duplicates.
   3926 		     The exception is Type 18/Name 1/Lang 0 which is the
   3927 		     defaul manifest - this can just be dropped.  */
   3928 		  if (entry->is_name == FALSE
   3929 		      && entry->name_id.id == 0
   3930 		      && dir != NULL
   3931 		      && dir->entry != NULL
   3932 		      && dir->entry->is_name == FALSE
   3933 		      && dir->entry->name_id.id == 1
   3934 		      && dir->entry->parent != NULL
   3935 		      && dir->entry->parent->entry != NULL
   3936 		      && dir->entry->parent->entry->is_name == FALSE
   3937 		      && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
   3938 		    ;
   3939 		  else if (dir != NULL
   3940 			   && dir->entry != NULL
   3941 			   && dir->entry->parent != NULL
   3942 			   && dir->entry->parent->entry != NULL
   3943 			   && dir->entry->parent->entry->is_name == FALSE
   3944 			   && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
   3945 		    {
   3946 		      /* Strings need special handling.  */
   3947 		      if (! rsrc_merge_string_entries (entry, next))
   3948 			{
   3949 			  /* _bfd_error_handler should have been called inside merge_strings.  */
   3950 			  bfd_set_error (bfd_error_file_truncated);
   3951 			  return;
   3952 			}
   3953 		    }
   3954 		  else
   3955 		    {
   3956 		      if (dir == NULL
   3957 			  || dir->entry == NULL
   3958 			  || dir->entry->parent == NULL
   3959 			  || dir->entry->parent->entry == NULL)
   3960 			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
   3961 		      else
   3962 			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
   3963 					    rsrc_resource_name (entry, dir));
   3964 		      bfd_set_error (bfd_error_file_truncated);
   3965 		      return;
   3966 		    }
   3967 		}
   3968 
   3969 	      /* Unhook NEXT from the chain.  */
   3970 	      entry->next_entry = next->next_entry;
   3971 	      chain->num_entries --;
   3972 	      if (chain->num_entries < 2)
   3973 		return;
   3974 	      next = next->next_entry;
   3975 	    }
   3976 	  else
   3977 	    {
   3978 	      points_to_entry = & entry->next_entry;
   3979 	      entry = next;
   3980 	      next = next->next_entry;
   3981 	    }
   3982 	}
   3983       while (next);
   3984 
   3985       chain->last_entry = entry;
   3986     }
   3987   while (swapped);
   3988 }
   3989 
   3990 /* Attach B's chain onto A.  */
   3991 static void
   3992 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
   3993 {
   3994   if (bchain->num_entries == 0)
   3995     return;
   3996 
   3997   achain->num_entries += bchain->num_entries;
   3998 
   3999   if (achain->first_entry == NULL)
   4000     {
   4001       achain->first_entry = bchain->first_entry;
   4002       achain->last_entry  = bchain->last_entry;
   4003     }
   4004   else
   4005     {
   4006       achain->last_entry->next_entry = bchain->first_entry;
   4007       achain->last_entry = bchain->last_entry;
   4008     }
   4009 
   4010   bchain->num_entries = 0;
   4011   bchain->first_entry = bchain->last_entry = NULL;
   4012 }
   4013 
   4014 static void
   4015 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
   4016 {
   4017   rsrc_directory * adir;
   4018   rsrc_directory * bdir;
   4019 
   4020   BFD_ASSERT (a->is_dir);
   4021   BFD_ASSERT (b->is_dir);
   4022 
   4023   adir = a->value.directory;
   4024   bdir = b->value.directory;
   4025 
   4026   if (adir->characteristics != bdir->characteristics)
   4027     {
   4028       _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics\n"));
   4029       bfd_set_error (bfd_error_file_truncated);
   4030       return;
   4031     }
   4032 
   4033   if (adir->major != bdir->major || adir->minor != bdir->minor)
   4034     {
   4035       _bfd_error_handler (_(".rsrc merge failure: differing directory versions\n"));
   4036       bfd_set_error (bfd_error_file_truncated);
   4037       return;
   4038     }
   4039 
   4040   /* Attach B's name chain to A.  */
   4041   rsrc_attach_chain (& adir->names, & bdir->names);
   4042 
   4043   /* Attach B's ID chain to A.  */
   4044   rsrc_attach_chain (& adir->ids, & bdir->ids);
   4045 
   4046   /* Now sort A's entries.  */
   4047   rsrc_sort_entries (& adir->names, TRUE, adir);
   4048   rsrc_sort_entries (& adir->ids, FALSE, adir);
   4049 }
   4050 
   4051 /* Check the .rsrc section.  If it contains multiple concatenated
   4052    resources then we must merge them properly.  Otherwise Windows
   4053    will ignore all but the first set.  */
   4054 
   4055 static void
   4056 rsrc_process_section (bfd * abfd,
   4057 		      struct coff_final_link_info * pfinfo)
   4058 {
   4059   rsrc_directory    new_table;
   4060   bfd_size_type     size;
   4061   asection *        sec;
   4062   pe_data_type *    pe;
   4063   bfd_vma           rva_bias;
   4064   bfd_byte *        data;
   4065   bfd_byte *        datastart;
   4066   bfd_byte *        dataend;
   4067   bfd_byte *        new_data;
   4068   unsigned int      num_resource_sets;
   4069   rsrc_directory *  type_tables;
   4070   rsrc_write_data   write_data;
   4071   unsigned int      indx;
   4072   bfd *             input;
   4073   unsigned int      num_input_rsrc = 0;
   4074   unsigned int      max_num_input_rsrc = 4;
   4075   ptrdiff_t *       rsrc_sizes = NULL;
   4076 
   4077   new_table.names.num_entries = 0;
   4078   new_table.ids.num_entries = 0;
   4079 
   4080   sec = bfd_get_section_by_name (abfd, ".rsrc");
   4081   if (sec == NULL || (size = sec->rawsize) == 0)
   4082     return;
   4083 
   4084   pe = pe_data (abfd);
   4085   if (pe == NULL)
   4086     return;
   4087 
   4088   rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
   4089 
   4090   data = bfd_malloc (size);
   4091   if (data == NULL)
   4092     return;
   4093 
   4094   datastart = data;
   4095 
   4096   if (! bfd_get_section_contents (abfd, sec, data, 0, size))
   4097     goto end;
   4098 
   4099   /* Step zero: Scan the input bfds looking for .rsrc sections and record
   4100      their lengths.  Note - we rely upon the fact that the linker script
   4101      does *not* sort the input .rsrc sections, so that the order in the
   4102      linkinfo list matches the order in the output .rsrc section.
   4103 
   4104      We need to know the lengths because each input .rsrc section has padding
   4105      at the end of a variable amount.  (It does not appear to be based upon
   4106      the section alignment or the file alignment).  We need to skip any
   4107      padding bytes when parsing the input .rsrc sections.  */
   4108   rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes);
   4109   if (rsrc_sizes == NULL)
   4110     goto end;
   4111 
   4112   for (input = pfinfo->info->input_bfds;
   4113        input != NULL;
   4114        input = input->link.next)
   4115     {
   4116       asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
   4117 
   4118       if (rsrc_sec != NULL)
   4119 	{
   4120 	  if (num_input_rsrc == max_num_input_rsrc)
   4121 	    {
   4122 	      max_num_input_rsrc += 10;
   4123 	      rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
   4124 					* sizeof * rsrc_sizes);
   4125 	      if (rsrc_sizes == NULL)
   4126 		goto end;
   4127 	    }
   4128 
   4129 	  BFD_ASSERT (rsrc_sec->size > 0);
   4130 	  rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
   4131 	}
   4132     }
   4133 
   4134   if (num_input_rsrc < 2)
   4135     goto end;
   4136 
   4137   /* Step one: Walk the section, computing the size of the tables,
   4138      leaves and data and decide if we need to do anything.  */
   4139   dataend = data + size;
   4140   num_resource_sets = 0;
   4141 
   4142   while (data < dataend)
   4143     {
   4144       bfd_byte * p = data;
   4145 
   4146       data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
   4147 
   4148       if (data > dataend)
   4149 	{
   4150 	  /* Corrupted .rsrc section - cannot merge.  */
   4151 	  _bfd_error_handler (_("%s: .rsrc merge failure: corrupt .rsrc section"),
   4152 			      bfd_get_filename (abfd));
   4153 	  bfd_set_error (bfd_error_file_truncated);
   4154 	  goto end;
   4155 	}
   4156 
   4157       if ((data - p) > rsrc_sizes [num_resource_sets])
   4158 	{
   4159 	  _bfd_error_handler (_("%s: .rsrc merge failure: unexpected .rsrc size"),
   4160 			      bfd_get_filename (abfd));
   4161 	  bfd_set_error (bfd_error_file_truncated);
   4162 	  goto end;
   4163 	}
   4164       /* FIXME: Should we add a check for "data - p" being much smaller
   4165 	 than rsrc_sizes[num_resource_sets] ?  */
   4166 
   4167       data = p + rsrc_sizes[num_resource_sets];
   4168       rva_bias += data - p;
   4169       ++ num_resource_sets;
   4170     }
   4171   BFD_ASSERT (num_resource_sets == num_input_rsrc);
   4172 
   4173   /* Step two: Walk the data again, building trees of the resources.  */
   4174   data = datastart;
   4175   rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
   4176 
   4177   type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
   4178   if (type_tables == NULL)
   4179     goto end;
   4180 
   4181   indx = 0;
   4182   while (data < dataend)
   4183     {
   4184       bfd_byte * p = data;
   4185 
   4186       (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
   4187 				   dataend, rva_bias, NULL);
   4188       data = p + rsrc_sizes[indx];
   4189       rva_bias += data - p;
   4190       ++ indx;
   4191     }
   4192   BFD_ASSERT (indx == num_resource_sets);
   4193 
   4194   /* Step three: Merge the top level tables (there can be only one).
   4195 
   4196      We must ensure that the merged entries are in ascending order.
   4197 
   4198      We also thread the top level table entries from the old tree onto
   4199      the new table, so that they can be pulled off later.  */
   4200 
   4201   /* FIXME: Should we verify that all type tables are the same ?  */
   4202   new_table.characteristics = type_tables[0].characteristics;
   4203   new_table.time            = type_tables[0].time;
   4204   new_table.major           = type_tables[0].major;
   4205   new_table.minor           = type_tables[0].minor;
   4206 
   4207   /* Chain the NAME entries onto the table.  */
   4208   new_table.names.first_entry = NULL;
   4209   new_table.names.last_entry = NULL;
   4210 
   4211   for (indx = 0; indx < num_resource_sets; indx++)
   4212     rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
   4213 
   4214   rsrc_sort_entries (& new_table.names, TRUE, & new_table);
   4215 
   4216   /* Chain the ID entries onto the table.  */
   4217   new_table.ids.first_entry = NULL;
   4218   new_table.ids.last_entry = NULL;
   4219 
   4220   for (indx = 0; indx < num_resource_sets; indx++)
   4221     rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
   4222 
   4223   rsrc_sort_entries (& new_table.ids, FALSE, & new_table);
   4224 
   4225   /* Step four: Create new contents for the .rsrc section.  */
   4226   /* Step four point one: Compute the size of each region of the .rsrc section.
   4227      We do this now, rather than earlier, as the merging above may have dropped
   4228      some entries.  */
   4229   sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
   4230   rsrc_compute_region_sizes (& new_table);
   4231   /* We increment sizeof_strings to make sure that resource data
   4232      starts on an 8-byte boundary.  FIXME: Is this correct ?  */
   4233   sizeof_strings = (sizeof_strings + 7) & ~ 7;
   4234 
   4235   new_data = bfd_zalloc (abfd, size);
   4236   if (new_data == NULL)
   4237     goto end;
   4238 
   4239   write_data.abfd        = abfd;
   4240   write_data.datastart   = new_data;
   4241   write_data.next_table  = new_data;
   4242   write_data.next_leaf   = new_data + sizeof_tables_and_entries;
   4243   write_data.next_string = write_data.next_leaf + sizeof_leaves;
   4244   write_data.next_data   = write_data.next_string + sizeof_strings;
   4245   write_data.rva_bias    = sec->vma - pe->pe_opthdr.ImageBase;
   4246 
   4247   rsrc_write_directory (& write_data, & new_table);
   4248 
   4249   /* Step five: Replace the old contents with the new.
   4250      We recompute the size as we may have lost entries due to mergeing.  */
   4251   size = ((write_data.next_data - new_data) + 3) & ~ 3;
   4252 
   4253   {
   4254     int page_size;
   4255 
   4256     if (coff_data (abfd)->link_info)
   4257       {
   4258 	page_size = pe_data (abfd)->pe_opthdr.FileAlignment;
   4259 
   4260 	/* If no file alignment has been set, default to one.
   4261 	   This repairs 'ld -r' for arm-wince-pe target.  */
   4262 	if (page_size == 0)
   4263 	  page_size = 1;
   4264       }
   4265     else
   4266       page_size = PE_DEF_FILE_ALIGNMENT;
   4267     size = (size + page_size - 1) & - page_size;
   4268   }
   4269 
   4270   bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
   4271   sec->size = sec->rawsize = size;
   4272 
   4273  end:
   4274   /* Step six: Free all the memory that we have used.  */
   4275   /* FIXME: Free the resource tree, if we have one.  */
   4276   free (datastart);
   4277   free (rsrc_sizes);
   4278 }
   4279 
   4280 /* Handle the .idata section and other things that need symbol table
   4281    access.  */
   4282 
   4283 bfd_boolean
   4284 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
   4285 {
   4286   struct coff_link_hash_entry *h1;
   4287   struct bfd_link_info *info = pfinfo->info;
   4288   bfd_boolean result = TRUE;
   4289 
   4290   /* There are a few fields that need to be filled in now while we
   4291      have symbol table access.
   4292 
   4293      The .idata subsections aren't directly available as sections, but
   4294      they are in the symbol table, so get them from there.  */
   4295 
   4296   /* The import directory.  This is the address of .idata$2, with size
   4297      of .idata$2 + .idata$3.  */
   4298   h1 = coff_link_hash_lookup (coff_hash_table (info),
   4299 			      ".idata$2", FALSE, FALSE, TRUE);
   4300   if (h1 != NULL)
   4301     {
   4302       /* PR ld/2729: We cannot rely upon all the output sections having been
   4303 	 created properly, so check before referencing them.  Issue a warning
   4304 	 message for any sections tht could not be found.  */
   4305       if ((h1->root.type == bfd_link_hash_defined
   4306 	   || h1->root.type == bfd_link_hash_defweak)
   4307 	  && h1->root.u.def.section != NULL
   4308 	  && h1->root.u.def.section->output_section != NULL)
   4309 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
   4310 	  (h1->root.u.def.value
   4311 	   + h1->root.u.def.section->output_section->vma
   4312 	   + h1->root.u.def.section->output_offset);
   4313       else
   4314 	{
   4315 	  _bfd_error_handler
   4316 	    (_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"),
   4317 	     abfd);
   4318 	  result = FALSE;
   4319 	}
   4320 
   4321       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4322 				  ".idata$4", FALSE, FALSE, TRUE);
   4323       if (h1 != NULL
   4324 	  && (h1->root.type == bfd_link_hash_defined
   4325 	   || h1->root.type == bfd_link_hash_defweak)
   4326 	  && h1->root.u.def.section != NULL
   4327 	  && h1->root.u.def.section->output_section != NULL)
   4328 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
   4329 	  ((h1->root.u.def.value
   4330 	    + h1->root.u.def.section->output_section->vma
   4331 	    + h1->root.u.def.section->output_offset)
   4332 	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
   4333       else
   4334 	{
   4335 	  _bfd_error_handler
   4336 	    (_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"),
   4337 	     abfd);
   4338 	  result = FALSE;
   4339 	}
   4340 
   4341       /* The import address table.  This is the size/address of
   4342          .idata$5.  */
   4343       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4344 				  ".idata$5", FALSE, FALSE, TRUE);
   4345       if (h1 != NULL
   4346 	  && (h1->root.type == bfd_link_hash_defined
   4347 	   || h1->root.type == bfd_link_hash_defweak)
   4348 	  && h1->root.u.def.section != NULL
   4349 	  && h1->root.u.def.section->output_section != NULL)
   4350 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
   4351 	  (h1->root.u.def.value
   4352 	   + h1->root.u.def.section->output_section->vma
   4353 	   + h1->root.u.def.section->output_offset);
   4354       else
   4355 	{
   4356 	  _bfd_error_handler
   4357 	    (_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"),
   4358 	     abfd);
   4359 	  result = FALSE;
   4360 	}
   4361 
   4362       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4363 				  ".idata$6", FALSE, FALSE, TRUE);
   4364       if (h1 != NULL
   4365 	  && (h1->root.type == bfd_link_hash_defined
   4366 	   || h1->root.type == bfd_link_hash_defweak)
   4367 	  && h1->root.u.def.section != NULL
   4368 	  && h1->root.u.def.section->output_section != NULL)
   4369 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
   4370 	  ((h1->root.u.def.value
   4371 	    + h1->root.u.def.section->output_section->vma
   4372 	    + h1->root.u.def.section->output_offset)
   4373 	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
   4374       else
   4375 	{
   4376 	  _bfd_error_handler
   4377 	    (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
   4378 	     abfd);
   4379 	  result = FALSE;
   4380 	}
   4381     }
   4382   else
   4383     {
   4384       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4385 				  "__IAT_start__", FALSE, FALSE, TRUE);
   4386       if (h1 != NULL
   4387 	  && (h1->root.type == bfd_link_hash_defined
   4388 	   || h1->root.type == bfd_link_hash_defweak)
   4389 	  && h1->root.u.def.section != NULL
   4390 	  && h1->root.u.def.section->output_section != NULL)
   4391 	{
   4392 	  bfd_vma iat_va;
   4393 
   4394 	  iat_va =
   4395 	    (h1->root.u.def.value
   4396 	     + h1->root.u.def.section->output_section->vma
   4397 	     + h1->root.u.def.section->output_offset);
   4398 
   4399 	  h1 = coff_link_hash_lookup (coff_hash_table (info),
   4400 				      "__IAT_end__", FALSE, FALSE, TRUE);
   4401 	  if (h1 != NULL
   4402 	      && (h1->root.type == bfd_link_hash_defined
   4403 	       || h1->root.type == bfd_link_hash_defweak)
   4404 	      && h1->root.u.def.section != NULL
   4405 	      && h1->root.u.def.section->output_section != NULL)
   4406 	    {
   4407 	      pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
   4408 		((h1->root.u.def.value
   4409 		  + h1->root.u.def.section->output_section->vma
   4410 		  + h1->root.u.def.section->output_offset)
   4411 		 - iat_va);
   4412 	      if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
   4413 		pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
   4414 		  iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
   4415 	    }
   4416 	  else
   4417 	    {
   4418 	      _bfd_error_handler
   4419 		(_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
   4420 		   " because .idata$6 is missing"), abfd);
   4421 	      result = FALSE;
   4422 	    }
   4423         }
   4424     }
   4425 
   4426   h1 = coff_link_hash_lookup (coff_hash_table (info),
   4427 			      (bfd_get_symbol_leading_char (abfd) != 0
   4428 			       ? "__tls_used" : "_tls_used"),
   4429 			      FALSE, FALSE, TRUE);
   4430   if (h1 != NULL)
   4431     {
   4432       if ((h1->root.type == bfd_link_hash_defined
   4433 	   || h1->root.type == bfd_link_hash_defweak)
   4434 	  && h1->root.u.def.section != NULL
   4435 	  && h1->root.u.def.section->output_section != NULL)
   4436 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
   4437 	  (h1->root.u.def.value
   4438 	   + h1->root.u.def.section->output_section->vma
   4439 	   + h1->root.u.def.section->output_offset
   4440 	   - pe_data (abfd)->pe_opthdr.ImageBase);
   4441       else
   4442 	{
   4443 	  _bfd_error_handler
   4444 	    (_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"),
   4445 	     abfd);
   4446 	  result = FALSE;
   4447 	}
   4448      /* According to PECOFF sepcifications by Microsoft version 8.2
   4449 	the TLS data directory consists of 4 pointers, followed
   4450 	by two 4-byte integer. This implies that the total size
   4451 	is different for 32-bit and 64-bit executables.  */
   4452 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   4453       pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
   4454 #else
   4455       pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
   4456 #endif
   4457     }
   4458 
   4459 /* If there is a .pdata section and we have linked pdata finally, we
   4460      need to sort the entries ascending.  */
   4461 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
   4462   {
   4463     asection *sec = bfd_get_section_by_name (abfd, ".pdata");
   4464 
   4465     if (sec)
   4466       {
   4467 	bfd_size_type x = sec->rawsize;
   4468 	bfd_byte *tmp_data = NULL;
   4469 
   4470 	if (x)
   4471 	  tmp_data = bfd_malloc (x);
   4472 
   4473 	if (tmp_data != NULL)
   4474 	  {
   4475 	    if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
   4476 	      {
   4477 		qsort (tmp_data,
   4478 		       (size_t) (x / 12),
   4479 		       12, sort_x64_pdata);
   4480 		bfd_set_section_contents (pfinfo->output_bfd, sec,
   4481 					  tmp_data, 0, x);
   4482 	      }
   4483 	    free (tmp_data);
   4484 	  }
   4485       }
   4486   }
   4487 #endif
   4488 
   4489   rsrc_process_section (abfd, pfinfo);
   4490 
   4491   /* If we couldn't find idata$2, we either have an excessively
   4492      trivial program or are in DEEP trouble; we have to assume trivial
   4493      program....  */
   4494   return result;
   4495 }
   4496