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 const char *
   1143 _bfd_XXi_get_codeview_pdb_name (bfd * abfd)
   1144 {
   1145   char * filename_ptr = bfd_get_filename(abfd);
   1146   char * last_dir_separator = strrchr(filename_ptr, '/');
   1147   if (last_dir_separator != NULL) {
   1148       filename_ptr = last_dir_separator+1;
   1149   }
   1150   return filename_ptr;
   1151 }
   1152 
   1153 static CODEVIEW_INFO *
   1154 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo)
   1155 {
   1156 
   1157   char buffer [length];
   1158 
   1159   if (!cvinfo)
   1160     return NULL;
   1161 
   1162   if (bfd_seek (abfd, where, SEEK_SET) != 0)
   1163     return NULL;
   1164 
   1165   if (bfd_bread (buffer, length, abfd) < 4)
   1166     return NULL;
   1167 
   1168   cvinfo->CVSignature = H_GET_32(abfd, buffer);
   1169   cvinfo->Age = 0;
   1170 
   1171   if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
   1172       && (length > sizeof (CV_INFO_PDB70)))
   1173     {
   1174       CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
   1175 
   1176       cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
   1177 
   1178       /* A GUID consists of 4,2,2 byte values in little-endian order, followed
   1179          by 8 single bytes.  Byte swap them so we can conveniently treat the GUID
   1180          as 16 bytes in big-endian order.  */
   1181       bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
   1182       bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
   1183       bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
   1184       memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
   1185 
   1186       cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
   1187       strcpy(cvinfo->PdbFileName, cvinfo70->PdbFileName);
   1188 
   1189       return cvinfo;
   1190     }
   1191   else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
   1192            && (length > sizeof (CV_INFO_PDB20)))
   1193     {
   1194       CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
   1195       cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
   1196       memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
   1197       cvinfo->SignatureLength = 4;
   1198       // cvinfo->PdbFileName = cvinfo20->PdbFileName;
   1199 
   1200       return cvinfo;
   1201     }
   1202 
   1203   return NULL;
   1204 }
   1205 
   1206 unsigned int
   1207 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo)
   1208 {
   1209   const char * filename_ptr = _bfd_XXi_get_codeview_pdb_name(abfd);
   1210   unsigned int filename_size = strlen(filename_ptr);
   1211   unsigned int size = sizeof (CV_INFO_PDB70) + filename_size + 1;
   1212   CV_INFO_PDB70 *cvinfo70;
   1213   char buffer[size];
   1214 
   1215   if (bfd_seek (abfd, where, SEEK_SET) != 0)
   1216     return 0;
   1217 
   1218   cvinfo70 = (CV_INFO_PDB70 *) buffer;
   1219   H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
   1220 
   1221   /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
   1222      in little-endian order, followed by 8 single bytes.  */
   1223   bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
   1224   bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
   1225   bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
   1226   memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
   1227 
   1228   H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
   1229   strcpy(cvinfo70->PdbFileName, filename_ptr);
   1230 
   1231   if (bfd_bwrite (buffer, size, abfd) != size)
   1232     return 0;
   1233 
   1234   return size;
   1235 }
   1236 
   1237 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
   1238 {
   1239   N_("Export Directory [.edata (or where ever we found it)]"),
   1240   N_("Import Directory [parts of .idata]"),
   1241   N_("Resource Directory [.rsrc]"),
   1242   N_("Exception Directory [.pdata]"),
   1243   N_("Security Directory"),
   1244   N_("Base Relocation Directory [.reloc]"),
   1245   N_("Debug Directory"),
   1246   N_("Description Directory"),
   1247   N_("Special Directory"),
   1248   N_("Thread Storage Directory [.tls]"),
   1249   N_("Load Configuration Directory"),
   1250   N_("Bound Import Directory"),
   1251   N_("Import Address Table Directory"),
   1252   N_("Delay Import Directory"),
   1253   N_("CLR Runtime Header"),
   1254   N_("Reserved")
   1255 };
   1256 
   1257 #ifdef POWERPC_LE_PE
   1258 /* The code for the PPC really falls in the "architecture dependent"
   1259    category.  However, it's not clear that anyone will ever care, so
   1260    we're ignoring the issue for now; if/when PPC matters, some of this
   1261    may need to go into peicode.h, or arguments passed to enable the
   1262    PPC- specific code.  */
   1263 #endif
   1264 
   1265 static bfd_boolean
   1266 pe_print_idata (bfd * abfd, void * vfile)
   1267 {
   1268   FILE *file = (FILE *) vfile;
   1269   bfd_byte *data;
   1270   asection *section;
   1271   bfd_signed_vma adj;
   1272 
   1273 #ifdef POWERPC_LE_PE
   1274   asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
   1275 #endif
   1276 
   1277   bfd_size_type datasize = 0;
   1278   bfd_size_type dataoff;
   1279   bfd_size_type i;
   1280   int onaline = 20;
   1281 
   1282   pe_data_type *pe = pe_data (abfd);
   1283   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   1284 
   1285   bfd_vma addr;
   1286 
   1287   addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
   1288 
   1289   if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
   1290     {
   1291       /* Maybe the extra header isn't there.  Look for the section.  */
   1292       section = bfd_get_section_by_name (abfd, ".idata");
   1293       if (section == NULL)
   1294 	return TRUE;
   1295 
   1296       addr = section->vma;
   1297       datasize = section->size;
   1298       if (datasize == 0)
   1299 	return TRUE;
   1300     }
   1301   else
   1302     {
   1303       addr += extra->ImageBase;
   1304       for (section = abfd->sections; section != NULL; section = section->next)
   1305 	{
   1306 	  datasize = section->size;
   1307 	  if (addr >= section->vma && addr < section->vma + datasize)
   1308 	    break;
   1309 	}
   1310 
   1311       if (section == NULL)
   1312 	{
   1313 	  fprintf (file,
   1314 		   _("\nThere is an import table, but the section containing it could not be found\n"));
   1315 	  return TRUE;
   1316 	}
   1317       else if (!(section->flags & SEC_HAS_CONTENTS))
   1318         {
   1319 	  fprintf (file,
   1320 		   _("\nThere is an import table in %s, but that section has no contents\n"),
   1321 		   section->name);
   1322 	  return TRUE;
   1323         }
   1324     }
   1325 
   1326   fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
   1327 	   section->name, (unsigned long) addr);
   1328 
   1329   dataoff = addr - section->vma;
   1330 
   1331 #ifdef POWERPC_LE_PE
   1332   if (rel_section != 0 && rel_section->size != 0)
   1333     {
   1334       /* The toc address can be found by taking the starting address,
   1335 	 which on the PPC locates a function descriptor. The
   1336 	 descriptor consists of the function code starting address
   1337 	 followed by the address of the toc. The starting address we
   1338 	 get from the bfd, and the descriptor is supposed to be in the
   1339 	 .reldata section.  */
   1340 
   1341       bfd_vma loadable_toc_address;
   1342       bfd_vma toc_address;
   1343       bfd_vma start_address;
   1344       bfd_byte *data;
   1345       bfd_vma offset;
   1346 
   1347       if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
   1348 	{
   1349 	  if (data != NULL)
   1350 	    free (data);
   1351 	  return FALSE;
   1352 	}
   1353 
   1354       offset = abfd->start_address - rel_section->vma;
   1355 
   1356       if (offset >= rel_section->size || offset + 8 > rel_section->size)
   1357         {
   1358           if (data != NULL)
   1359             free (data);
   1360           return FALSE;
   1361         }
   1362 
   1363       start_address = bfd_get_32 (abfd, data + offset);
   1364       loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
   1365       toc_address = loadable_toc_address - 32768;
   1366 
   1367       fprintf (file,
   1368 	       _("\nFunction descriptor located at the start address: %04lx\n"),
   1369 	       (unsigned long int) (abfd->start_address));
   1370       fprintf (file,
   1371 	       _("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
   1372 	       start_address, loadable_toc_address, toc_address);
   1373       if (data != NULL)
   1374 	free (data);
   1375     }
   1376   else
   1377     {
   1378       fprintf (file,
   1379 	       _("\nNo reldata section! Function descriptor not decoded.\n"));
   1380     }
   1381 #endif
   1382 
   1383   fprintf (file,
   1384 	   _("\nThe Import Tables (interpreted %s section contents)\n"),
   1385 	   section->name);
   1386   fprintf (file,
   1387 	   _("\
   1388  vma:            Hint    Time      Forward  DLL       First\n\
   1389                  Table   Stamp     Chain    Name      Thunk\n"));
   1390 
   1391   /* Read the whole section.  Some of the fields might be before dataoff.  */
   1392   if (!bfd_malloc_and_get_section (abfd, section, &data))
   1393     {
   1394       if (data != NULL)
   1395 	free (data);
   1396       return FALSE;
   1397     }
   1398 
   1399   adj = section->vma - extra->ImageBase;
   1400 
   1401   /* Print all image import descriptors.  */
   1402   for (i = dataoff; i + onaline <= datasize; i += onaline)
   1403     {
   1404       bfd_vma hint_addr;
   1405       bfd_vma time_stamp;
   1406       bfd_vma forward_chain;
   1407       bfd_vma dll_name;
   1408       bfd_vma first_thunk;
   1409       int idx = 0;
   1410       bfd_size_type j;
   1411       char *dll;
   1412 
   1413       /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress).  */
   1414       fprintf (file, " %08lx\t", (unsigned long) (i + adj));
   1415       hint_addr = bfd_get_32 (abfd, data + i);
   1416       time_stamp = bfd_get_32 (abfd, data + i + 4);
   1417       forward_chain = bfd_get_32 (abfd, data + i + 8);
   1418       dll_name = bfd_get_32 (abfd, data + i + 12);
   1419       first_thunk = bfd_get_32 (abfd, data + i + 16);
   1420 
   1421       fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
   1422 	       (unsigned long) hint_addr,
   1423 	       (unsigned long) time_stamp,
   1424 	       (unsigned long) forward_chain,
   1425 	       (unsigned long) dll_name,
   1426 	       (unsigned long) first_thunk);
   1427 
   1428       if (hint_addr == 0 && first_thunk == 0)
   1429 	break;
   1430 
   1431       if (dll_name - adj >= section->size)
   1432         break;
   1433 
   1434       dll = (char *) data + dll_name - adj;
   1435       /* PR 17512 file: 078-12277-0.004.  */
   1436       bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
   1437       fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
   1438 
   1439       if (hint_addr != 0)
   1440 	{
   1441 	  bfd_byte *ft_data;
   1442 	  asection *ft_section;
   1443 	  bfd_vma ft_addr;
   1444 	  bfd_size_type ft_datasize;
   1445 	  int ft_idx;
   1446 	  int ft_allocated;
   1447 
   1448 	  fprintf (file, _("\tvma:  Hint/Ord Member-Name Bound-To\n"));
   1449 
   1450 	  idx = hint_addr - adj;
   1451 
   1452 	  ft_addr = first_thunk + extra->ImageBase;
   1453 	  ft_idx = first_thunk - adj;
   1454 	  ft_data = data + ft_idx;
   1455 	  ft_datasize = datasize - ft_idx;
   1456 	  ft_allocated = 0;
   1457 
   1458 	  if (first_thunk != hint_addr)
   1459 	    {
   1460 	      /* Find the section which contains the first thunk.  */
   1461 	      for (ft_section = abfd->sections;
   1462 		   ft_section != NULL;
   1463 		   ft_section = ft_section->next)
   1464 		{
   1465 		  if (ft_addr >= ft_section->vma
   1466 		      && ft_addr < ft_section->vma + ft_section->size)
   1467 		    break;
   1468 		}
   1469 
   1470 	      if (ft_section == NULL)
   1471 		{
   1472 		  fprintf (file,
   1473 		       _("\nThere is a first thunk, but the section containing it could not be found\n"));
   1474 		  continue;
   1475 		}
   1476 
   1477 	      /* Now check to see if this section is the same as our current
   1478 		 section.  If it is not then we will have to load its data in.  */
   1479 	      if (ft_section != section)
   1480 		{
   1481 		  ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
   1482 		  ft_datasize = ft_section->size - ft_idx;
   1483 		  ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
   1484 		  if (ft_data == NULL)
   1485 		    continue;
   1486 
   1487 		  /* Read ft_datasize bytes starting at offset ft_idx.  */
   1488 		  if (!bfd_get_section_contents (abfd, ft_section, ft_data,
   1489 						 (bfd_vma) ft_idx, ft_datasize))
   1490 		    {
   1491 		      free (ft_data);
   1492 		      continue;
   1493 		    }
   1494 		  ft_allocated = 1;
   1495 		}
   1496 	    }
   1497 
   1498 	  /* Print HintName vector entries.  */
   1499 #ifdef COFF_WITH_pex64
   1500 	  for (j = 0; idx + j + 8 <= datasize; j += 8)
   1501 	    {
   1502 	      bfd_size_type amt;
   1503 	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
   1504 	      unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
   1505 
   1506 	      if (!member && !member_high)
   1507 		break;
   1508 
   1509 	      amt = member - adj;
   1510 
   1511 	      if (HighBitSet (member_high))
   1512 		fprintf (file, "\t%lx%08lx\t %4lx%08lx  <none>",
   1513 			 member_high, member,
   1514 			 WithoutHighBit (member_high), member);
   1515 	      /* PR binutils/17512: Handle corrupt PE data.  */
   1516 	      else if (amt + 2 >= datasize)
   1517 		fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
   1518 	      else
   1519 		{
   1520 		  int ordinal;
   1521 		  char *member_name;
   1522 
   1523 		  ordinal = bfd_get_16 (abfd, data + amt);
   1524 		  member_name = (char *) data + amt + 2;
   1525 		  fprintf (file, "\t%04lx\t %4d  %.*s",member, ordinal,
   1526 			   (int) (datasize - (amt + 2)), member_name);
   1527 		}
   1528 
   1529 	      /* If the time stamp is not zero, the import address
   1530 		 table holds actual addresses.  */
   1531 	      if (time_stamp != 0
   1532 		  && first_thunk != 0
   1533 		  && first_thunk != hint_addr
   1534 		  && j + 4 <= ft_datasize)
   1535 		fprintf (file, "\t%04lx",
   1536 			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
   1537 	      fprintf (file, "\n");
   1538 	    }
   1539 #else
   1540 	  for (j = 0; idx + j + 4 <= datasize; j += 4)
   1541 	    {
   1542 	      bfd_size_type amt;
   1543 	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
   1544 
   1545 	      /* Print single IMAGE_IMPORT_BY_NAME vector.  */
   1546 	      if (member == 0)
   1547 		break;
   1548 
   1549 	      amt = member - adj;
   1550 	      if (HighBitSet (member))
   1551 		fprintf (file, "\t%04lx\t %4lu  <none>",
   1552 			 member, WithoutHighBit (member));
   1553 	      /* PR binutils/17512: Handle corrupt PE data.  */
   1554 	      else if (amt + 2 >= datasize)
   1555 		fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
   1556 	      else
   1557 		{
   1558 		  int ordinal;
   1559 		  char *member_name;
   1560 
   1561 		  ordinal = bfd_get_16 (abfd, data + amt);
   1562 		  member_name = (char *) data + amt + 2;
   1563 		  fprintf (file, "\t%04lx\t %4d  %.*s",
   1564 			   member, ordinal,
   1565 			   (int) (datasize - (amt + 2)), member_name);
   1566 		}
   1567 
   1568 	      /* If the time stamp is not zero, the import address
   1569 		 table holds actual addresses.  */
   1570 	      if (time_stamp != 0
   1571 		  && first_thunk != 0
   1572 		  && first_thunk != hint_addr
   1573 		  && j + 4 <= ft_datasize)
   1574 		fprintf (file, "\t%04lx",
   1575 			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
   1576 
   1577 	      fprintf (file, "\n");
   1578 	    }
   1579 #endif
   1580 	  if (ft_allocated)
   1581 	    free (ft_data);
   1582 	}
   1583 
   1584       fprintf (file, "\n");
   1585     }
   1586 
   1587   free (data);
   1588 
   1589   return TRUE;
   1590 }
   1591 
   1592 static bfd_boolean
   1593 pe_print_edata (bfd * abfd, void * vfile)
   1594 {
   1595   FILE *file = (FILE *) vfile;
   1596   bfd_byte *data;
   1597   asection *section;
   1598   bfd_size_type datasize = 0;
   1599   bfd_size_type dataoff;
   1600   bfd_size_type i;
   1601   bfd_vma       adj;
   1602   struct EDT_type
   1603   {
   1604     long export_flags;          /* Reserved - should be zero.  */
   1605     long time_stamp;
   1606     short major_ver;
   1607     short minor_ver;
   1608     bfd_vma name;               /* RVA - relative to image base.  */
   1609     long base;                  /* Ordinal base.  */
   1610     unsigned long num_functions;/* Number in the export address table.  */
   1611     unsigned long num_names;    /* Number in the name pointer table.  */
   1612     bfd_vma eat_addr;		/* RVA to the export address table.  */
   1613     bfd_vma npt_addr;		/* RVA to the Export Name Pointer Table.  */
   1614     bfd_vma ot_addr;		/* RVA to the Ordinal Table.  */
   1615   } edt;
   1616 
   1617   pe_data_type *pe = pe_data (abfd);
   1618   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   1619 
   1620   bfd_vma addr;
   1621 
   1622   addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
   1623 
   1624   if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
   1625     {
   1626       /* Maybe the extra header isn't there.  Look for the section.  */
   1627       section = bfd_get_section_by_name (abfd, ".edata");
   1628       if (section == NULL)
   1629 	return TRUE;
   1630 
   1631       addr = section->vma;
   1632       dataoff = 0;
   1633       datasize = section->size;
   1634       if (datasize == 0)
   1635 	return TRUE;
   1636     }
   1637   else
   1638     {
   1639       addr += extra->ImageBase;
   1640 
   1641       for (section = abfd->sections; section != NULL; section = section->next)
   1642 	if (addr >= section->vma && addr < section->vma + section->size)
   1643 	  break;
   1644 
   1645       if (section == NULL)
   1646 	{
   1647 	  fprintf (file,
   1648 		   _("\nThere is an export table, but the section containing it could not be found\n"));
   1649 	  return TRUE;
   1650 	}
   1651       else if (!(section->flags & SEC_HAS_CONTENTS))
   1652         {
   1653 	  fprintf (file,
   1654 		   _("\nThere is an export table in %s, but that section has no contents\n"),
   1655 		   section->name);
   1656 	  return TRUE;
   1657         }
   1658 
   1659       dataoff = addr - section->vma;
   1660       datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
   1661       if (datasize > section->size - dataoff)
   1662 	{
   1663 	  fprintf (file,
   1664 		   _("\nThere is an export table in %s, but it does not fit into that section\n"),
   1665 		   section->name);
   1666 	  return TRUE;
   1667 	}
   1668     }
   1669 
   1670   /* PR 17512: Handle corrupt PE binaries.  */
   1671   if (datasize < 36)
   1672     {
   1673       fprintf (file,
   1674 	       _("\nThere is an export table in %s, but it is too small (%d)\n"),
   1675 	       section->name, (int) datasize);
   1676       return TRUE;
   1677     }
   1678 
   1679   fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
   1680 	   section->name, (unsigned long) addr);
   1681 
   1682   data = (bfd_byte *) bfd_malloc (datasize);
   1683   if (data == NULL)
   1684     return FALSE;
   1685 
   1686   if (! bfd_get_section_contents (abfd, section, data,
   1687 				  (file_ptr) dataoff, datasize))
   1688     return FALSE;
   1689 
   1690   /* Go get Export Directory Table.  */
   1691   edt.export_flags   = bfd_get_32 (abfd, data +  0);
   1692   edt.time_stamp     = bfd_get_32 (abfd, data +  4);
   1693   edt.major_ver      = bfd_get_16 (abfd, data +  8);
   1694   edt.minor_ver      = bfd_get_16 (abfd, data + 10);
   1695   edt.name           = bfd_get_32 (abfd, data + 12);
   1696   edt.base           = bfd_get_32 (abfd, data + 16);
   1697   edt.num_functions  = bfd_get_32 (abfd, data + 20);
   1698   edt.num_names      = bfd_get_32 (abfd, data + 24);
   1699   edt.eat_addr       = bfd_get_32 (abfd, data + 28);
   1700   edt.npt_addr       = bfd_get_32 (abfd, data + 32);
   1701   edt.ot_addr        = bfd_get_32 (abfd, data + 36);
   1702 
   1703   adj = section->vma - extra->ImageBase + dataoff;
   1704 
   1705   /* Dump the EDT first.  */
   1706   fprintf (file,
   1707 	   _("\nThe Export Tables (interpreted %s section contents)\n\n"),
   1708 	   section->name);
   1709 
   1710   fprintf (file,
   1711 	   _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
   1712 
   1713   fprintf (file,
   1714 	   _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
   1715 
   1716   fprintf (file,
   1717 	   _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
   1718 
   1719   fprintf (file,
   1720 	   _("Name \t\t\t\t"));
   1721   bfd_fprintf_vma (abfd, file, edt.name);
   1722 
   1723   if ((edt.name >= adj) && (edt.name < adj + datasize))
   1724     fprintf (file, " %.*s\n",
   1725 	     (int) (datasize - (edt.name - adj)),
   1726 	     data + edt.name - adj);
   1727   else
   1728     fprintf (file, "(outside .edata section)\n");
   1729 
   1730   fprintf (file,
   1731 	   _("Ordinal Base \t\t\t%ld\n"), edt.base);
   1732 
   1733   fprintf (file,
   1734 	   _("Number in:\n"));
   1735 
   1736   fprintf (file,
   1737 	   _("\tExport Address Table \t\t%08lx\n"),
   1738 	   edt.num_functions);
   1739 
   1740   fprintf (file,
   1741 	   _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
   1742 
   1743   fprintf (file,
   1744 	   _("Table Addresses\n"));
   1745 
   1746   fprintf (file,
   1747 	   _("\tExport Address Table \t\t"));
   1748   bfd_fprintf_vma (abfd, file, edt.eat_addr);
   1749   fprintf (file, "\n");
   1750 
   1751   fprintf (file,
   1752 	   _("\tName Pointer Table \t\t"));
   1753   bfd_fprintf_vma (abfd, file, edt.npt_addr);
   1754   fprintf (file, "\n");
   1755 
   1756   fprintf (file,
   1757 	   _("\tOrdinal Table \t\t\t"));
   1758   bfd_fprintf_vma (abfd, file, edt.ot_addr);
   1759   fprintf (file, "\n");
   1760 
   1761   /* The next table to find is the Export Address Table. It's basically
   1762      a list of pointers that either locate a function in this dll, or
   1763      forward the call to another dll. Something like:
   1764       typedef union
   1765       {
   1766         long export_rva;
   1767         long forwarder_rva;
   1768       } export_address_table_entry;  */
   1769 
   1770   fprintf (file,
   1771 	  _("\nExport Address Table -- Ordinal Base %ld\n"),
   1772 	  edt.base);
   1773 
   1774   /* PR 17512: Handle corrupt PE binaries.  */
   1775   if (edt.eat_addr + (edt.num_functions * 4) - adj >= datasize
   1776       /* PR 17512 file: 140-165018-0.004.  */
   1777       || data + edt.eat_addr - adj < data)
   1778     fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
   1779 	     (long) edt.eat_addr,
   1780 	     (long) edt.num_functions);
   1781   else for (i = 0; i < edt.num_functions; ++i)
   1782     {
   1783       bfd_vma eat_member = bfd_get_32 (abfd,
   1784 				       data + edt.eat_addr + (i * 4) - adj);
   1785       if (eat_member == 0)
   1786 	continue;
   1787 
   1788       if (eat_member - adj <= datasize)
   1789 	{
   1790 	  /* This rva is to a name (forwarding function) in our section.  */
   1791 	  /* Should locate a function descriptor.  */
   1792 	  fprintf (file,
   1793 		   "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
   1794 		   (long) i,
   1795 		   (long) (i + edt.base),
   1796 		   (unsigned long) eat_member,
   1797 		   _("Forwarder RVA"),
   1798 		   (int)(datasize - (eat_member - adj)),
   1799 		   data + eat_member - adj);
   1800 	}
   1801       else
   1802 	{
   1803 	  /* Should locate a function descriptor in the reldata section.  */
   1804 	  fprintf (file,
   1805 		   "\t[%4ld] +base[%4ld] %04lx %s\n",
   1806 		   (long) i,
   1807 		   (long) (i + edt.base),
   1808 		   (unsigned long) eat_member,
   1809 		   _("Export RVA"));
   1810 	}
   1811     }
   1812 
   1813   /* The Export Name Pointer Table is paired with the Export Ordinal Table.  */
   1814   /* Dump them in parallel for clarity.  */
   1815   fprintf (file,
   1816 	   _("\n[Ordinal/Name Pointer] Table\n"));
   1817 
   1818   /* PR 17512: Handle corrupt PE binaries.  */
   1819   if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
   1820       || (data + edt.npt_addr - adj) < data)
   1821     fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
   1822 	     (long) edt.npt_addr,
   1823 	     (long) edt.num_names);
   1824   /* PR 17512: file: 140-147171-0.004.  */
   1825   else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
   1826 	   || data + edt.ot_addr - adj < data)
   1827     fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
   1828 	     (long) edt.ot_addr,
   1829 	     (long) edt.num_names);
   1830   else for (i = 0; i < edt.num_names; ++i)
   1831     {
   1832       bfd_vma  name_ptr;
   1833       bfd_vma  ord;
   1834 
   1835       ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
   1836       name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
   1837 
   1838       if ((name_ptr - adj) >= datasize)
   1839 	{
   1840 	  fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"),
   1841 		   (long) ord, (long) name_ptr);
   1842 	}
   1843       else
   1844 	{
   1845 	  char * name = (char *) data + name_ptr - adj;
   1846 
   1847 	  fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
   1848 		   (int)((char *)(data + datasize) - name), name);
   1849 	}
   1850     }
   1851 
   1852   free (data);
   1853 
   1854   return TRUE;
   1855 }
   1856 
   1857 /* This really is architecture dependent.  On IA-64, a .pdata entry
   1858    consists of three dwords containing relative virtual addresses that
   1859    specify the start and end address of the code range the entry
   1860    covers and the address of the corresponding unwind info data.
   1861 
   1862    On ARM and SH-4, a compressed PDATA structure is used :
   1863    _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
   1864    _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
   1865    See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
   1866 
   1867    This is the version for uncompressed data.  */
   1868 
   1869 static bfd_boolean
   1870 pe_print_pdata (bfd * abfd, void * vfile)
   1871 {
   1872 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   1873 # define PDATA_ROW_SIZE	(3 * 8)
   1874 #else
   1875 # define PDATA_ROW_SIZE	(5 * 4)
   1876 #endif
   1877   FILE *file = (FILE *) vfile;
   1878   bfd_byte *data = 0;
   1879   asection *section = bfd_get_section_by_name (abfd, ".pdata");
   1880   bfd_size_type datasize = 0;
   1881   bfd_size_type i;
   1882   bfd_size_type start, stop;
   1883   int onaline = PDATA_ROW_SIZE;
   1884 
   1885   if (section == NULL
   1886       || coff_section_data (abfd, section) == NULL
   1887       || pei_section_data (abfd, section) == NULL)
   1888     return TRUE;
   1889 
   1890   stop = pei_section_data (abfd, section)->virt_size;
   1891   if ((stop % onaline) != 0)
   1892     fprintf (file,
   1893 	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
   1894 	     (long) stop, onaline);
   1895 
   1896   fprintf (file,
   1897 	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
   1898 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   1899   fprintf (file,
   1900 	   _(" vma:\t\t\tBegin Address    End Address      Unwind Info\n"));
   1901 #else
   1902   fprintf (file, _("\
   1903  vma:\t\tBegin    End      EH       EH       PrologEnd  Exception\n\
   1904      \t\tAddress  Address  Handler  Data     Address    Mask\n"));
   1905 #endif
   1906 
   1907   datasize = section->size;
   1908   if (datasize == 0)
   1909     return TRUE;
   1910 
   1911   if (! bfd_malloc_and_get_section (abfd, section, &data))
   1912     {
   1913       if (data != NULL)
   1914 	free (data);
   1915       return FALSE;
   1916     }
   1917 
   1918   start = 0;
   1919 
   1920   for (i = start; i < stop; i += onaline)
   1921     {
   1922       bfd_vma begin_addr;
   1923       bfd_vma end_addr;
   1924       bfd_vma eh_handler;
   1925       bfd_vma eh_data;
   1926       bfd_vma prolog_end_addr;
   1927 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1928       int em_data;
   1929 #endif
   1930 
   1931       if (i + PDATA_ROW_SIZE > stop)
   1932 	break;
   1933 
   1934       begin_addr      = GET_PDATA_ENTRY (abfd, data + i     );
   1935       end_addr        = GET_PDATA_ENTRY (abfd, data + i +  4);
   1936       eh_handler      = GET_PDATA_ENTRY (abfd, data + i +  8);
   1937       eh_data         = GET_PDATA_ENTRY (abfd, data + i + 12);
   1938       prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
   1939 
   1940       if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
   1941 	  && eh_data == 0 && prolog_end_addr == 0)
   1942 	/* We are probably into the padding of the section now.  */
   1943 	break;
   1944 
   1945 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1946       em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
   1947 #endif
   1948       eh_handler &= ~(bfd_vma) 0x3;
   1949       prolog_end_addr &= ~(bfd_vma) 0x3;
   1950 
   1951       fputc (' ', file);
   1952       bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
   1953       bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
   1954       bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
   1955       bfd_fprintf_vma (abfd, file, eh_handler);
   1956 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
   1957       fputc (' ', file);
   1958       bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
   1959       bfd_fprintf_vma (abfd, file, prolog_end_addr);
   1960       fprintf (file, "   %x", em_data);
   1961 #endif
   1962 
   1963 #ifdef POWERPC_LE_PE
   1964       if (eh_handler == 0 && eh_data != 0)
   1965 	{
   1966 	  /* Special bits here, although the meaning may be a little
   1967 	     mysterious. The only one I know for sure is 0x03
   1968 	     Code Significance
   1969 	     0x00 None
   1970 	     0x01 Register Save Millicode
   1971 	     0x02 Register Restore Millicode
   1972 	     0x03 Glue Code Sequence.  */
   1973 	  switch (eh_data)
   1974 	    {
   1975 	    case 0x01:
   1976 	      fprintf (file, _(" Register save millicode"));
   1977 	      break;
   1978 	    case 0x02:
   1979 	      fprintf (file, _(" Register restore millicode"));
   1980 	      break;
   1981 	    case 0x03:
   1982 	      fprintf (file, _(" Glue code sequence"));
   1983 	      break;
   1984 	    default:
   1985 	      break;
   1986 	    }
   1987 	}
   1988 #endif
   1989       fprintf (file, "\n");
   1990     }
   1991 
   1992   free (data);
   1993 
   1994   return TRUE;
   1995 #undef PDATA_ROW_SIZE
   1996 }
   1997 
   1998 typedef struct sym_cache
   1999 {
   2000   int        symcount;
   2001   asymbol ** syms;
   2002 } sym_cache;
   2003 
   2004 static asymbol **
   2005 slurp_symtab (bfd *abfd, sym_cache *psc)
   2006 {
   2007   asymbol ** sy = NULL;
   2008   long storage;
   2009 
   2010   if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
   2011     {
   2012       psc->symcount = 0;
   2013       return NULL;
   2014     }
   2015 
   2016   storage = bfd_get_symtab_upper_bound (abfd);
   2017   if (storage < 0)
   2018     return NULL;
   2019   if (storage)
   2020     sy = (asymbol **) bfd_malloc (storage);
   2021 
   2022   psc->symcount = bfd_canonicalize_symtab (abfd, sy);
   2023   if (psc->symcount < 0)
   2024     return NULL;
   2025   return sy;
   2026 }
   2027 
   2028 static const char *
   2029 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
   2030 {
   2031   int i;
   2032 
   2033   if (psc->syms == 0)
   2034     psc->syms = slurp_symtab (abfd, psc);
   2035 
   2036   for (i = 0; i < psc->symcount; i++)
   2037     {
   2038       if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
   2039 	return psc->syms[i]->name;
   2040     }
   2041 
   2042   return NULL;
   2043 }
   2044 
   2045 static void
   2046 cleanup_syms (sym_cache *psc)
   2047 {
   2048   psc->symcount = 0;
   2049   free (psc->syms);
   2050   psc->syms = NULL;
   2051 }
   2052 
   2053 /* This is the version for "compressed" pdata.  */
   2054 
   2055 bfd_boolean
   2056 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
   2057 {
   2058 # define PDATA_ROW_SIZE	(2 * 4)
   2059   FILE *file = (FILE *) vfile;
   2060   bfd_byte *data = NULL;
   2061   asection *section = bfd_get_section_by_name (abfd, ".pdata");
   2062   bfd_size_type datasize = 0;
   2063   bfd_size_type i;
   2064   bfd_size_type start, stop;
   2065   int onaline = PDATA_ROW_SIZE;
   2066   struct sym_cache cache = {0, 0} ;
   2067 
   2068   if (section == NULL
   2069       || coff_section_data (abfd, section) == NULL
   2070       || pei_section_data (abfd, section) == NULL)
   2071     return TRUE;
   2072 
   2073   stop = pei_section_data (abfd, section)->virt_size;
   2074   if ((stop % onaline) != 0)
   2075     fprintf (file,
   2076 	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
   2077 	     (long) stop, onaline);
   2078 
   2079   fprintf (file,
   2080 	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
   2081 
   2082   fprintf (file, _("\
   2083  vma:\t\tBegin    Prolog   Function Flags    Exception EH\n\
   2084      \t\tAddress  Length   Length   32b exc  Handler   Data\n"));
   2085 
   2086   datasize = section->size;
   2087   if (datasize == 0)
   2088     return TRUE;
   2089 
   2090   if (! bfd_malloc_and_get_section (abfd, section, &data))
   2091     {
   2092       if (data != NULL)
   2093 	free (data);
   2094       return FALSE;
   2095     }
   2096 
   2097   start = 0;
   2098 
   2099   for (i = start; i < stop; i += onaline)
   2100     {
   2101       bfd_vma begin_addr;
   2102       bfd_vma other_data;
   2103       bfd_vma prolog_length, function_length;
   2104       int flag32bit, exception_flag;
   2105       asection *tsection;
   2106 
   2107       if (i + PDATA_ROW_SIZE > stop)
   2108 	break;
   2109 
   2110       begin_addr = GET_PDATA_ENTRY (abfd, data + i     );
   2111       other_data = GET_PDATA_ENTRY (abfd, data + i +  4);
   2112 
   2113       if (begin_addr == 0 && other_data == 0)
   2114 	/* We are probably into the padding of the section now.  */
   2115 	break;
   2116 
   2117       prolog_length = (other_data & 0x000000FF);
   2118       function_length = (other_data & 0x3FFFFF00) >> 8;
   2119       flag32bit = (int)((other_data & 0x40000000) >> 30);
   2120       exception_flag = (int)((other_data & 0x80000000) >> 31);
   2121 
   2122       fputc (' ', file);
   2123       bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
   2124       bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
   2125       bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
   2126       bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
   2127       fprintf (file, "%2d  %2d   ", flag32bit, exception_flag);
   2128 
   2129       /* Get the exception handler's address and the data passed from the
   2130          .text section. This is really the data that belongs with the .pdata
   2131          but got "compressed" out for the ARM and SH4 architectures.  */
   2132       tsection = bfd_get_section_by_name (abfd, ".text");
   2133       if (tsection && coff_section_data (abfd, tsection)
   2134 	  && pei_section_data (abfd, tsection))
   2135 	{
   2136 	  bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
   2137 	  bfd_byte *tdata;
   2138 
   2139 	  tdata = (bfd_byte *) bfd_malloc (8);
   2140 	  if (tdata)
   2141 	    {
   2142 	      if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
   2143 		{
   2144 		  bfd_vma eh, eh_data;
   2145 
   2146 		  eh = bfd_get_32 (abfd, tdata);
   2147 		  eh_data = bfd_get_32 (abfd, tdata + 4);
   2148 		  fprintf (file, "%08x  ", (unsigned int) eh);
   2149 		  fprintf (file, "%08x", (unsigned int) eh_data);
   2150 		  if (eh != 0)
   2151 		    {
   2152 		      const char *s = my_symbol_for_address (abfd, eh, &cache);
   2153 
   2154 		      if (s)
   2155 			fprintf (file, " (%s) ", s);
   2156 		    }
   2157 		}
   2158 	      free (tdata);
   2159 	    }
   2160 	}
   2161 
   2162       fprintf (file, "\n");
   2163     }
   2164 
   2165   free (data);
   2166 
   2167   cleanup_syms (& cache);
   2168 
   2169   return TRUE;
   2170 #undef PDATA_ROW_SIZE
   2171 }
   2172 
   2173 
   2174 #define IMAGE_REL_BASED_HIGHADJ 4
   2176 static const char * const tbl[] =
   2177 {
   2178   "ABSOLUTE",
   2179   "HIGH",
   2180   "LOW",
   2181   "HIGHLOW",
   2182   "HIGHADJ",
   2183   "MIPS_JMPADDR",
   2184   "SECTION",
   2185   "REL32",
   2186   "RESERVED1",
   2187   "MIPS_JMPADDR16",
   2188   "DIR64",
   2189   "HIGH3ADJ",
   2190   "UNKNOWN",   /* MUST be last.  */
   2191 };
   2192 
   2193 static bfd_boolean
   2194 pe_print_reloc (bfd * abfd, void * vfile)
   2195 {
   2196   FILE *file = (FILE *) vfile;
   2197   bfd_byte *data = 0;
   2198   asection *section = bfd_get_section_by_name (abfd, ".reloc");
   2199   bfd_byte *p, *end;
   2200 
   2201   if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS))
   2202     return TRUE;
   2203 
   2204   fprintf (file,
   2205 	   _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
   2206 
   2207   if (! bfd_malloc_and_get_section (abfd, section, &data))
   2208     {
   2209       if (data != NULL)
   2210 	free (data);
   2211       return FALSE;
   2212     }
   2213 
   2214   p = data;
   2215   end = data + section->size;
   2216   while (p + 8 <= end)
   2217     {
   2218       int j;
   2219       bfd_vma virtual_address;
   2220       long number, size;
   2221       bfd_byte *chunk_end;
   2222 
   2223       /* The .reloc section is a sequence of blocks, with a header consisting
   2224 	 of two 32 bit quantities, followed by a number of 16 bit entries.  */
   2225       virtual_address = bfd_get_32 (abfd, p);
   2226       size = bfd_get_32 (abfd, p + 4);
   2227       p += 8;
   2228       number = (size - 8) / 2;
   2229 
   2230       if (size == 0)
   2231 	break;
   2232 
   2233       fprintf (file,
   2234 	       _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
   2235 	       (unsigned long) virtual_address, size, (unsigned long) size, number);
   2236 
   2237       chunk_end = p + size;
   2238       if (chunk_end > end)
   2239 	chunk_end = end;
   2240       j = 0;
   2241       while (p + 2 <= chunk_end)
   2242 	{
   2243 	  unsigned short e = bfd_get_16 (abfd, p);
   2244 	  unsigned int t = (e & 0xF000) >> 12;
   2245 	  int off = e & 0x0FFF;
   2246 
   2247 	  if (t >= sizeof (tbl) / sizeof (tbl[0]))
   2248 	    t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
   2249 
   2250 	  fprintf (file,
   2251 		   _("\treloc %4d offset %4x [%4lx] %s"),
   2252 		   j, off, (unsigned long) (off + virtual_address), tbl[t]);
   2253 
   2254 	  p += 2;
   2255 	  j++;
   2256 
   2257 	  /* HIGHADJ takes an argument, - the next record *is* the
   2258 	     low 16 bits of addend.  */
   2259 	  if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
   2260 	    {
   2261 	      fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
   2262 	      p += 2;
   2263 	      j++;
   2264 	    }
   2265 
   2266 	  fprintf (file, "\n");
   2267 	}
   2268     }
   2269 
   2270   free (data);
   2271 
   2272   return TRUE;
   2273 }
   2274 
   2275 /* A data structure describing the regions of a .rsrc section.
   2277    Some fields are filled in as the section is parsed.  */
   2278 
   2279 typedef struct rsrc_regions
   2280 {
   2281   bfd_byte * section_start;
   2282   bfd_byte * section_end;
   2283   bfd_byte * strings_start;
   2284   bfd_byte * resource_start;
   2285 } rsrc_regions;
   2286 
   2287 static bfd_byte *
   2288 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
   2289 			       rsrc_regions *, bfd_vma);
   2290 
   2291 /* Print the resource entry at DATA, with the text indented by INDENT.
   2292    Recusively calls rsrc_print_resource_directory to print the contents
   2293    of directory entries.
   2294    Returns the address of the end of the data associated with the entry
   2295    or section_end + 1 upon failure.  */
   2296 
   2297 static bfd_byte *
   2298 rsrc_print_resource_entries (FILE *         file,
   2299 			     bfd *          abfd,
   2300 			     unsigned int   indent,
   2301 			     bfd_boolean    is_name,
   2302 			     bfd_byte *     data,
   2303 			     rsrc_regions * regions,
   2304 			     bfd_vma        rva_bias)
   2305 {
   2306   unsigned long entry, addr, size;
   2307 
   2308   if (data + 8 >= regions->section_end)
   2309     return regions->section_end + 1;
   2310 
   2311   fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
   2312 
   2313   entry = (unsigned long) bfd_get_32 (abfd, data);
   2314   if (is_name)
   2315     {
   2316       bfd_byte * name;
   2317 
   2318       /* Note - the documentation says that this field is an RVA value
   2319 	 but windres appears to produce a section relative offset with
   2320 	 the top bit set.  Support both styles for now.  */
   2321       if (HighBitSet (entry))
   2322 	name = regions->section_start + WithoutHighBit (entry);
   2323       else
   2324 	name = regions->section_start + entry - rva_bias;
   2325 
   2326       if (name + 2 < regions->section_end && name > regions->section_start)
   2327 	{
   2328 	  unsigned int len;
   2329 
   2330 	  if (regions->strings_start == NULL)
   2331 	    regions->strings_start = name;
   2332 
   2333 	  len = bfd_get_16 (abfd, name);
   2334 
   2335 	  fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
   2336 
   2337 	  if (name + 2 + len * 2 < regions->section_end)
   2338 	    {
   2339 	      /* This strange loop is to cope with multibyte characters.  */
   2340 	      while (len --)
   2341 		{
   2342 		  char c;
   2343 
   2344 		  name += 2;
   2345 		  c = * name;
   2346 		  /* Avoid printing control characters.  */
   2347 		  if (c > 0 && c < 32)
   2348 		    fprintf (file, "^%c", c + 64);
   2349 		  else
   2350 		    fprintf (file, "%.1s", name);
   2351 		}
   2352 	    }
   2353 	  else
   2354 	    {
   2355 	      fprintf (file, _("<corrupt string length: %#x>\n"), len);
   2356 	      /* PR binutils/17512: Do not try to continue decoding a
   2357 		 corrupted resource section.  It is likely to end up with
   2358 		 reams of extraneous output.  FIXME: We could probably
   2359 		 continue if we disable the printing of strings...  */
   2360 	      return regions->section_end + 1;
   2361 	    }
   2362 	}
   2363       else
   2364 	{
   2365 	  fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
   2366 	  return regions->section_end + 1;
   2367 	}
   2368     }
   2369   else
   2370     fprintf (file, _("ID: %#08lx"), entry);
   2371 
   2372   entry = (long) bfd_get_32 (abfd, data + 4);
   2373   fprintf (file, _(", Value: %#08lx\n"), entry);
   2374 
   2375   if (HighBitSet  (entry))
   2376     {
   2377       data = regions->section_start + WithoutHighBit (entry);
   2378       if (data <= regions->section_start || data > regions->section_end)
   2379 	return regions->section_end + 1;
   2380 
   2381       /* FIXME: PR binutils/17512: A corrupt file could contain a loop
   2382 	 in the resource table.  We need some way to detect this.  */
   2383       return rsrc_print_resource_directory (file, abfd, indent + 1, data,
   2384 					    regions, rva_bias);
   2385     }
   2386 
   2387   if (regions->section_start + entry + 16 >= regions->section_end)
   2388     return regions->section_end + 1;
   2389 
   2390   fprintf (file, _("%03x %*.s  Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
   2391 	   (int) (entry),
   2392 	   indent, " ",
   2393 	   addr = (long) bfd_get_32 (abfd, regions->section_start + entry),
   2394 	   size = (long) bfd_get_32 (abfd, regions->section_start + entry + 4),
   2395 	   (int) bfd_get_32 (abfd, regions->section_start + entry + 8));
   2396 
   2397   /* Check that the reserved entry is 0.  */
   2398   if (bfd_get_32 (abfd, regions->section_start + entry + 12) != 0
   2399       /* And that the data address/size is valid too.  */
   2400       || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
   2401     return regions->section_end + 1;
   2402 
   2403   if (regions->resource_start == NULL)
   2404     regions->resource_start = regions->section_start + (addr - rva_bias);
   2405 
   2406   return regions->section_start + (addr - rva_bias) + size;
   2407 }
   2408 
   2409 #define max(a,b) ((a) > (b) ? (a) : (b))
   2410 #define min(a,b) ((a) < (b) ? (a) : (b))
   2411 
   2412 static bfd_byte *
   2413 rsrc_print_resource_directory (FILE *         file,
   2414 			       bfd *          abfd,
   2415 			       unsigned int   indent,
   2416 			       bfd_byte *     data,
   2417 			       rsrc_regions * regions,
   2418 			       bfd_vma        rva_bias)
   2419 {
   2420   unsigned int num_names, num_ids;
   2421   bfd_byte * highest_data = data;
   2422 
   2423   if (data + 16 >= regions->section_end)
   2424     return regions->section_end + 1;
   2425 
   2426   fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
   2427   switch (indent)
   2428     {
   2429     case 0: fprintf (file, "Type"); break;
   2430     case 2: fprintf (file, "Name"); break;
   2431     case 4: fprintf (file, "Language"); break;
   2432     default:
   2433       fprintf (file, _("<unknown directory type: %d>\n"), indent);
   2434       /* FIXME: For now we end the printing here.  If in the
   2435 	 future more directory types are added to the RSRC spec
   2436 	 then we will need to change this.  */
   2437       return regions->section_end + 1;
   2438     }
   2439 
   2440   fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
   2441 	   (int) bfd_get_32 (abfd, data),
   2442 	   (long) bfd_get_32 (abfd, data + 4),
   2443 	   (int)  bfd_get_16 (abfd, data + 8),
   2444 	   (int)  bfd_get_16 (abfd, data + 10),
   2445 	   num_names = (int) bfd_get_16 (abfd, data + 12),
   2446 	   num_ids =   (int) bfd_get_16 (abfd, data + 14));
   2447   data += 16;
   2448 
   2449   while (num_names --)
   2450     {
   2451       bfd_byte * entry_end;
   2452 
   2453       entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, TRUE,
   2454 					       data, regions, rva_bias);
   2455       data += 8;
   2456       highest_data = max (highest_data, entry_end);
   2457       if (entry_end >= regions->section_end)
   2458 	return entry_end;
   2459     }
   2460 
   2461   while (num_ids --)
   2462     {
   2463       bfd_byte * entry_end;
   2464 
   2465       entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, FALSE,
   2466 					       data, regions, rva_bias);
   2467       data += 8;
   2468       highest_data = max (highest_data, entry_end);
   2469       if (entry_end >= regions->section_end)
   2470 	return entry_end;
   2471     }
   2472 
   2473   return max (highest_data, data);
   2474 }
   2475 
   2476 /* Display the contents of a .rsrc section.  We do not try to
   2477    reproduce the resources, windres does that.  Instead we dump
   2478    the tables in a human readable format.  */
   2479 
   2480 static bfd_boolean
   2481 rsrc_print_section (bfd * abfd, void * vfile)
   2482 {
   2483   bfd_vma rva_bias;
   2484   pe_data_type * pe;
   2485   FILE * file = (FILE *) vfile;
   2486   bfd_size_type datasize;
   2487   asection * section;
   2488   bfd_byte * data;
   2489   rsrc_regions regions;
   2490 
   2491   pe = pe_data (abfd);
   2492   if (pe == NULL)
   2493     return TRUE;
   2494 
   2495   section = bfd_get_section_by_name (abfd, ".rsrc");
   2496   if (section == NULL)
   2497     return TRUE;
   2498   if (!(section->flags & SEC_HAS_CONTENTS))
   2499     return TRUE;
   2500 
   2501   datasize = section->size;
   2502   if (datasize == 0)
   2503     return TRUE;
   2504 
   2505   rva_bias = section->vma - pe->pe_opthdr.ImageBase;
   2506 
   2507   if (! bfd_malloc_and_get_section (abfd, section, & data))
   2508     {
   2509       if (data != NULL)
   2510 	free (data);
   2511       return FALSE;
   2512     }
   2513 
   2514   regions.section_start = data;
   2515   regions.section_end = data + datasize;
   2516   regions.strings_start = NULL;
   2517   regions.resource_start = NULL;
   2518 
   2519   fflush (file);
   2520   fprintf (file, "\nThe .rsrc Resource Directory section:\n");
   2521 
   2522   while (data < regions.section_end)
   2523     {
   2524       bfd_byte * p = data;
   2525 
   2526       data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
   2527 
   2528       if (data == regions.section_end + 1)
   2529 	fprintf (file, _("Corrupt .rsrc section detected!\n"));
   2530       else
   2531 	{
   2532 	  /* Align data before continuing.  */
   2533 	  int align = (1 << section->alignment_power) - 1;
   2534 
   2535 	  data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
   2536 	  rva_bias += data - p;
   2537 
   2538 	  /* For reasons that are unclear .rsrc sections are sometimes created
   2539 	     aligned to a 1^3 boundary even when their alignment is set at
   2540 	     1^2.  Catch that case here before we issue a spurious warning
   2541 	     message.  */
   2542 	  if (data == (regions.section_end - 4))
   2543 	    data = regions.section_end;
   2544 	  else if (data < regions.section_end)
   2545 	    {
   2546 	      /* If the extra data is all zeros then do not complain.
   2547 		 This is just padding so that the section meets the
   2548 		 page size requirements.  */
   2549 	      while (data ++ < regions.section_end)
   2550 		if (*data != 0)
   2551 		  break;
   2552 	      if (data < regions.section_end)
   2553 		fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
   2554 	    }
   2555 	}
   2556     }
   2557 
   2558   if (regions.strings_start != NULL)
   2559     fprintf (file, " String table starts at offset: %#03x\n",
   2560 	     (int) (regions.strings_start - regions.section_start));
   2561   if (regions.resource_start != NULL)
   2562     fprintf (file, " Resources start at offset: %#03x\n",
   2563 	     (int) (regions.resource_start - regions.section_start));
   2564 
   2565   free (regions.section_start);
   2566   return TRUE;
   2567 }
   2568 
   2569 #define IMAGE_NUMBEROF_DEBUG_TYPES 12
   2570 
   2571 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
   2572 {
   2573   "Unknown",
   2574   "COFF",
   2575   "CodeView",
   2576   "FPO",
   2577   "Misc",
   2578   "Exception",
   2579   "Fixup",
   2580   "OMAP-to-SRC",
   2581   "OMAP-from-SRC",
   2582   "Borland",
   2583   "Reserved",
   2584   "CLSID",
   2585 };
   2586 
   2587 static bfd_boolean
   2588 pe_print_debugdata (bfd * abfd, void * vfile)
   2589 {
   2590   FILE *file = (FILE *) vfile;
   2591   pe_data_type *pe = pe_data (abfd);
   2592   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
   2593   asection *section;
   2594   bfd_byte *data = 0;
   2595   bfd_size_type dataoff;
   2596   unsigned int i;
   2597 
   2598   bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
   2599   bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
   2600 
   2601   if (size == 0)
   2602     return TRUE;
   2603 
   2604   addr += extra->ImageBase;
   2605   for (section = abfd->sections; section != NULL; section = section->next)
   2606     {
   2607       if ((addr >= section->vma) && (addr < (section->vma + section->size)))
   2608         break;
   2609     }
   2610 
   2611   if (section == NULL)
   2612     {
   2613       fprintf (file,
   2614                _("\nThere is a debug directory, but the section containing it could not be found\n"));
   2615       return TRUE;
   2616     }
   2617   else if (!(section->flags & SEC_HAS_CONTENTS))
   2618     {
   2619       fprintf (file,
   2620                _("\nThere is a debug directory in %s, but that section has no contents\n"),
   2621                section->name);
   2622       return TRUE;
   2623     }
   2624   else if (section->size < size)
   2625     {
   2626       fprintf (file,
   2627                _("\nError: section %s contains the debug data starting address but it is too small\n"),
   2628                section->name);
   2629       return FALSE;
   2630     }
   2631 
   2632   fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
   2633 	   section->name, (unsigned long) addr);
   2634 
   2635   dataoff = addr - section->vma;
   2636 
   2637   if (size > (section->size - dataoff))
   2638     {
   2639       fprintf (file, _("The debug data size field in the data directory is too big for the section"));
   2640       return FALSE;
   2641     }
   2642 
   2643   fprintf (file,
   2644 	   _("Type                Size     Rva      Offset\n"));
   2645 
   2646   /* Read the whole section.  */
   2647   if (!bfd_malloc_and_get_section (abfd, section, &data))
   2648     {
   2649       if (data != NULL)
   2650 	free (data);
   2651       return FALSE;
   2652     }
   2653 
   2654   for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
   2655     {
   2656       const char *type_name;
   2657       struct external_IMAGE_DEBUG_DIRECTORY *ext
   2658 	= &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
   2659       struct internal_IMAGE_DEBUG_DIRECTORY idd;
   2660 
   2661       _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
   2662 
   2663       if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
   2664         type_name = debug_type_names[0];
   2665       else
   2666         type_name = debug_type_names[idd.Type];
   2667 
   2668       fprintf (file, " %2ld  %14s %08lx %08lx %08lx\n",
   2669 	       idd.Type, type_name, idd.SizeOfData,
   2670 	       idd.AddressOfRawData, idd.PointerToRawData);
   2671 
   2672       if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
   2673         {
   2674           char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
   2675           char buffer [idd.SizeOfData];
   2676           CODEVIEW_INFO * cvinfo = (CODEVIEW_INFO *) buffer;
   2677 
   2678           /* The debug entry doesn't have to have to be in a section,
   2679 	     in which case AddressOfRawData is 0, so always use PointerToRawData.  */
   2680           if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
   2681 					       idd.SizeOfData, cvinfo))
   2682             continue;
   2683 
   2684           for (i = 0; i < cvinfo->SignatureLength; i++)
   2685             sprintf (&signature[i*2], "%02x", cvinfo->Signature[i] & 0xff);
   2686 
   2687           fprintf (file, "(format %c%c%c%c signature %s age %ld pdb %s)\n",
   2688 	         buffer[0], buffer[1], buffer[2], buffer[3],
   2689 	         signature, cvinfo->Age, cvinfo->PdbFileName);
   2690         }
   2691     }
   2692 
   2693   if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
   2694     fprintf (file,
   2695             _("The debug directory size is not a multiple of the debug directory entry size\n"));
   2696 
   2697   return TRUE;
   2698 }
   2699 
   2700 /* Print out the program headers.  */
   2701 
   2702 bfd_boolean
   2703 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
   2704 {
   2705   FILE *file = (FILE *) vfile;
   2706   int j;
   2707   pe_data_type *pe = pe_data (abfd);
   2708   struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
   2709   const char *subsystem_name = NULL;
   2710   const char *name;
   2711 
   2712   /* The MS dumpbin program reportedly ands with 0xff0f before
   2713      printing the characteristics field.  Not sure why.  No reason to
   2714      emulate it here.  */
   2715   fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
   2716 #undef PF
   2717 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
   2718   PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
   2719   PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
   2720   PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
   2721   PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
   2722   PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
   2723   PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
   2724   PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
   2725   PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
   2726   PF (IMAGE_FILE_SYSTEM, "system file");
   2727   PF (IMAGE_FILE_DLL, "DLL");
   2728   PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
   2729 #undef PF
   2730 
   2731   /* ctime implies '\n'.  */
   2732   {
   2733     time_t t = pe->coff.timestamp;
   2734     fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
   2735   }
   2736 
   2737 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
   2738 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
   2739 #endif
   2740 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
   2741 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
   2742 #endif
   2743 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
   2744 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
   2745 #endif
   2746 
   2747   switch (i->Magic)
   2748     {
   2749     case IMAGE_NT_OPTIONAL_HDR_MAGIC:
   2750       name = "PE32";
   2751       break;
   2752     case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
   2753       name = "PE32+";
   2754       break;
   2755     case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
   2756       name = "ROM";
   2757       break;
   2758     default:
   2759       name = NULL;
   2760       break;
   2761     }
   2762   fprintf (file, "Magic\t\t\t%04x", i->Magic);
   2763   if (name)
   2764     fprintf (file, "\t(%s)",name);
   2765   fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
   2766   fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
   2767   fprintf (file, "SizeOfCode\t\t%08lx\n", (unsigned long) i->SizeOfCode);
   2768   fprintf (file, "SizeOfInitializedData\t%08lx\n",
   2769 	   (unsigned long) i->SizeOfInitializedData);
   2770   fprintf (file, "SizeOfUninitializedData\t%08lx\n",
   2771 	   (unsigned long) i->SizeOfUninitializedData);
   2772   fprintf (file, "AddressOfEntryPoint\t");
   2773   bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
   2774   fprintf (file, "\nBaseOfCode\t\t");
   2775   bfd_fprintf_vma (abfd, file, i->BaseOfCode);
   2776 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   2777   /* PE32+ does not have BaseOfData member!  */
   2778   fprintf (file, "\nBaseOfData\t\t");
   2779   bfd_fprintf_vma (abfd, file, i->BaseOfData);
   2780 #endif
   2781 
   2782   fprintf (file, "\nImageBase\t\t");
   2783   bfd_fprintf_vma (abfd, file, i->ImageBase);
   2784   fprintf (file, "\nSectionAlignment\t");
   2785   bfd_fprintf_vma (abfd, file, i->SectionAlignment);
   2786   fprintf (file, "\nFileAlignment\t\t");
   2787   bfd_fprintf_vma (abfd, file, i->FileAlignment);
   2788   fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
   2789   fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
   2790   fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
   2791   fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
   2792   fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
   2793   fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
   2794   fprintf (file, "Win32Version\t\t%08lx\n", (unsigned long) i->Reserved1);
   2795   fprintf (file, "SizeOfImage\t\t%08lx\n", (unsigned long) i->SizeOfImage);
   2796   fprintf (file, "SizeOfHeaders\t\t%08lx\n", (unsigned long) i->SizeOfHeaders);
   2797   fprintf (file, "CheckSum\t\t%08lx\n", (unsigned long) i->CheckSum);
   2798 
   2799   switch (i->Subsystem)
   2800     {
   2801     case IMAGE_SUBSYSTEM_UNKNOWN:
   2802       subsystem_name = "unspecified";
   2803       break;
   2804     case IMAGE_SUBSYSTEM_NATIVE:
   2805       subsystem_name = "NT native";
   2806       break;
   2807     case IMAGE_SUBSYSTEM_WINDOWS_GUI:
   2808       subsystem_name = "Windows GUI";
   2809       break;
   2810     case IMAGE_SUBSYSTEM_WINDOWS_CUI:
   2811       subsystem_name = "Windows CUI";
   2812       break;
   2813     case IMAGE_SUBSYSTEM_POSIX_CUI:
   2814       subsystem_name = "POSIX CUI";
   2815       break;
   2816     case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
   2817       subsystem_name = "Wince CUI";
   2818       break;
   2819     // These are from UEFI Platform Initialization Specification 1.1.
   2820     case IMAGE_SUBSYSTEM_EFI_APPLICATION:
   2821       subsystem_name = "EFI application";
   2822       break;
   2823     case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
   2824       subsystem_name = "EFI boot service driver";
   2825       break;
   2826     case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
   2827       subsystem_name = "EFI runtime driver";
   2828       break;
   2829     case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
   2830       subsystem_name = "SAL runtime driver";
   2831       break;
   2832     // This is from revision 8.0 of the MS PE/COFF spec
   2833     case IMAGE_SUBSYSTEM_XBOX:
   2834       subsystem_name = "XBOX";
   2835       break;
   2836     // Added default case for clarity - subsystem_name is NULL anyway.
   2837     default:
   2838       subsystem_name = NULL;
   2839     }
   2840 
   2841   fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
   2842   if (subsystem_name)
   2843     fprintf (file, "\t(%s)", subsystem_name);
   2844   fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
   2845   fprintf (file, "SizeOfStackReserve\t");
   2846   bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
   2847   fprintf (file, "\nSizeOfStackCommit\t");
   2848   bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
   2849   fprintf (file, "\nSizeOfHeapReserve\t");
   2850   bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
   2851   fprintf (file, "\nSizeOfHeapCommit\t");
   2852   bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
   2853   fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
   2854   fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
   2855 	   (unsigned long) i->NumberOfRvaAndSizes);
   2856 
   2857   fprintf (file, "\nThe Data Directory\n");
   2858   for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
   2859     {
   2860       fprintf (file, "Entry %1x ", j);
   2861       bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
   2862       fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
   2863       fprintf (file, "%s\n", dir_names[j]);
   2864     }
   2865 
   2866   pe_print_idata (abfd, vfile);
   2867   pe_print_edata (abfd, vfile);
   2868   if (bfd_coff_have_print_pdata (abfd))
   2869     bfd_coff_print_pdata (abfd, vfile);
   2870   else
   2871     pe_print_pdata (abfd, vfile);
   2872   pe_print_reloc (abfd, vfile);
   2873   pe_print_debugdata (abfd, file);
   2874 
   2875   rsrc_print_section (abfd, vfile);
   2876 
   2877   return TRUE;
   2878 }
   2879 
   2880 static bfd_boolean
   2881 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
   2882 {
   2883   bfd_vma addr = * (bfd_vma *) obj;
   2884   return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
   2885 }
   2886 
   2887 static asection *
   2888 find_section_by_vma (bfd *abfd, bfd_vma addr)
   2889 {
   2890   return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
   2891 }
   2892 
   2893 /* Copy any private info we understand from the input bfd
   2894    to the output bfd.  */
   2895 
   2896 bfd_boolean
   2897 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
   2898 {
   2899   pe_data_type *ipe, *ope;
   2900 
   2901   /* One day we may try to grok other private data.  */
   2902   if (ibfd->xvec->flavour != bfd_target_coff_flavour
   2903       || obfd->xvec->flavour != bfd_target_coff_flavour)
   2904     return TRUE;
   2905 
   2906   ipe = pe_data (ibfd);
   2907   ope = pe_data (obfd);
   2908 
   2909   /* pe_opthdr is copied in copy_object.  */
   2910   ope->dll = ipe->dll;
   2911 
   2912   /* Don't copy input subsystem if output is different from input.  */
   2913   if (obfd->xvec != ibfd->xvec)
   2914     ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
   2915 
   2916   /* For strip: if we removed .reloc, we'll make a real mess of things
   2917      if we don't remove this entry as well.  */
   2918   if (! pe_data (obfd)->has_reloc_section)
   2919     {
   2920       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
   2921       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
   2922     }
   2923 
   2924   /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
   2925      But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
   2926      won't be added.  */
   2927   if (! pe_data (ibfd)->has_reloc_section
   2928       && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
   2929     pe_data (obfd)->dont_strip_reloc = 1;
   2930 
   2931   /* The file offsets contained in the debug directory need rewriting.  */
   2932   if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0)
   2933     {
   2934       bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
   2935 	+ ope->pe_opthdr.ImageBase;
   2936       asection *section = find_section_by_vma (obfd, addr);
   2937       bfd_byte *data;
   2938 
   2939       if (section && bfd_malloc_and_get_section (obfd, section, &data))
   2940         {
   2941           unsigned int i;
   2942           struct external_IMAGE_DEBUG_DIRECTORY *dd =
   2943 	    (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma));
   2944 
   2945           for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
   2946 		 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
   2947             {
   2948               asection *ddsection;
   2949               struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
   2950               struct internal_IMAGE_DEBUG_DIRECTORY idd;
   2951 
   2952               _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
   2953 
   2954               if (idd.AddressOfRawData == 0)
   2955                 continue; /* RVA 0 means only offset is valid, not handled yet.  */
   2956 
   2957               ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase);
   2958               if (!ddsection)
   2959                 continue; /* Not in a section! */
   2960 
   2961               idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData
   2962 							   + ope->pe_opthdr.ImageBase) - ddsection->vma;
   2963 
   2964               _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
   2965             }
   2966 
   2967           if (!bfd_set_section_contents (obfd, section, data, 0, section->size))
   2968             _bfd_error_handler (_("Failed to update file offsets in debug directory"));
   2969         }
   2970     }
   2971 
   2972   return TRUE;
   2973 }
   2974 
   2975 /* Copy private section data.  */
   2976 
   2977 bfd_boolean
   2978 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
   2979 				       asection *isec,
   2980 				       bfd *obfd,
   2981 				       asection *osec)
   2982 {
   2983   if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
   2984       || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
   2985     return TRUE;
   2986 
   2987   if (coff_section_data (ibfd, isec) != NULL
   2988       && pei_section_data (ibfd, isec) != NULL)
   2989     {
   2990       if (coff_section_data (obfd, osec) == NULL)
   2991 	{
   2992 	  bfd_size_type amt = sizeof (struct coff_section_tdata);
   2993 	  osec->used_by_bfd = bfd_zalloc (obfd, amt);
   2994 	  if (osec->used_by_bfd == NULL)
   2995 	    return FALSE;
   2996 	}
   2997 
   2998       if (pei_section_data (obfd, osec) == NULL)
   2999 	{
   3000 	  bfd_size_type amt = sizeof (struct pei_section_tdata);
   3001 	  coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
   3002 	  if (coff_section_data (obfd, osec)->tdata == NULL)
   3003 	    return FALSE;
   3004 	}
   3005 
   3006       pei_section_data (obfd, osec)->virt_size =
   3007 	pei_section_data (ibfd, isec)->virt_size;
   3008       pei_section_data (obfd, osec)->pe_flags =
   3009 	pei_section_data (ibfd, isec)->pe_flags;
   3010     }
   3011 
   3012   return TRUE;
   3013 }
   3014 
   3015 void
   3016 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
   3017 {
   3018   coff_get_symbol_info (abfd, symbol, ret);
   3019 }
   3020 
   3021 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
   3022 static int
   3023 sort_x64_pdata (const void *l, const void *r)
   3024 {
   3025   const char *lp = (const char *) l;
   3026   const char *rp = (const char *) r;
   3027   bfd_vma vl, vr;
   3028   vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
   3029   if (vl != vr)
   3030     return (vl < vr ? -1 : 1);
   3031   /* We compare just begin address.  */
   3032   return 0;
   3033 }
   3034 #endif
   3035 
   3036 /* Functions to process a .rsrc section.  */
   3038 
   3039 static unsigned int sizeof_leaves;
   3040 static unsigned int sizeof_strings;
   3041 static unsigned int sizeof_tables_and_entries;
   3042 
   3043 static bfd_byte *
   3044 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
   3045 
   3046 static bfd_byte *
   3047 rsrc_count_entries (bfd *          abfd,
   3048 		    bfd_boolean    is_name,
   3049 		    bfd_byte *     datastart,
   3050 		    bfd_byte *     data,
   3051 		    bfd_byte *     dataend,
   3052 		    bfd_vma        rva_bias)
   3053 {
   3054   unsigned long entry, addr, size;
   3055 
   3056   if (data + 8 >= dataend)
   3057     return dataend + 1;
   3058 
   3059   if (is_name)
   3060     {
   3061       bfd_byte * name;
   3062 
   3063       entry = (long) bfd_get_32 (abfd, data);
   3064 
   3065       if (HighBitSet (entry))
   3066 	name = datastart + WithoutHighBit (entry);
   3067       else
   3068 	name = datastart + entry - rva_bias;
   3069 
   3070       if (name + 2 >= dataend || name < datastart)
   3071 	return dataend + 1;
   3072 
   3073       unsigned int len = bfd_get_16 (abfd, name);
   3074       if (len == 0 || len > 256)
   3075 	return dataend + 1;
   3076     }
   3077 
   3078   entry = (long) bfd_get_32 (abfd, data + 4);
   3079 
   3080   if (HighBitSet (entry))
   3081     {
   3082       data = datastart + WithoutHighBit (entry);
   3083 
   3084       if (data <= datastart || data >= dataend)
   3085 	return dataend + 1;
   3086 
   3087       return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
   3088     }
   3089 
   3090   if (datastart + entry + 16 >= dataend)
   3091     return dataend + 1;
   3092 
   3093   addr = (long) bfd_get_32 (abfd, datastart + entry);
   3094   size = (long) bfd_get_32 (abfd, datastart + entry + 4);
   3095 
   3096   return datastart + addr - rva_bias + size;
   3097 }
   3098 
   3099 static bfd_byte *
   3100 rsrc_count_directory (bfd *          abfd,
   3101 		      bfd_byte *     datastart,
   3102 		      bfd_byte *     data,
   3103 		      bfd_byte *     dataend,
   3104 		      bfd_vma        rva_bias)
   3105 {
   3106   unsigned int  num_entries, num_ids;
   3107   bfd_byte *    highest_data = data;
   3108 
   3109   if (data + 16 >= dataend)
   3110     return dataend + 1;
   3111 
   3112   num_entries  = (int) bfd_get_16 (abfd, data + 12);
   3113   num_ids      = (int) bfd_get_16 (abfd, data + 14);
   3114 
   3115   num_entries += num_ids;
   3116 
   3117   data += 16;
   3118 
   3119   while (num_entries --)
   3120     {
   3121       bfd_byte * entry_end;
   3122 
   3123       entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
   3124 				      datastart, data, dataend, rva_bias);
   3125       data += 8;
   3126       highest_data = max (highest_data, entry_end);
   3127       if (entry_end >= dataend)
   3128 	break;
   3129     }
   3130 
   3131   return max (highest_data, data);
   3132 }
   3133 
   3134 typedef struct rsrc_dir_chain
   3135 {
   3136   unsigned int         num_entries;
   3137   struct rsrc_entry *  first_entry;
   3138   struct rsrc_entry *  last_entry;
   3139 } rsrc_dir_chain;
   3140 
   3141 typedef struct rsrc_directory
   3142 {
   3143   unsigned int characteristics;
   3144   unsigned int time;
   3145   unsigned int major;
   3146   unsigned int minor;
   3147 
   3148   rsrc_dir_chain names;
   3149   rsrc_dir_chain ids;
   3150 
   3151   struct rsrc_entry * entry;
   3152 } rsrc_directory;
   3153 
   3154 typedef struct rsrc_string
   3155 {
   3156   unsigned int  len;
   3157   bfd_byte *    string;
   3158 } rsrc_string;
   3159 
   3160 typedef struct rsrc_leaf
   3161 {
   3162   unsigned int  size;
   3163   unsigned int  codepage;
   3164   bfd_byte *    data;
   3165 } rsrc_leaf;
   3166 
   3167 typedef struct rsrc_entry
   3168 {
   3169   bfd_boolean is_name;
   3170   union
   3171   {
   3172     unsigned int          id;
   3173     struct rsrc_string    name;
   3174   } name_id;
   3175 
   3176   bfd_boolean is_dir;
   3177   union
   3178   {
   3179     struct rsrc_directory * directory;
   3180     struct rsrc_leaf *      leaf;
   3181   } value;
   3182 
   3183   struct rsrc_entry *     next_entry;
   3184   struct rsrc_directory * parent;
   3185 } rsrc_entry;
   3186 
   3187 static bfd_byte *
   3188 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
   3189 		      bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
   3190 
   3191 static bfd_byte *
   3192 rsrc_parse_entry (bfd *            abfd,
   3193 		  bfd_boolean      is_name,
   3194 		  rsrc_entry *     entry,
   3195 		  bfd_byte *       datastart,
   3196 		  bfd_byte *       data,
   3197 		  bfd_byte *       dataend,
   3198 		  bfd_vma          rva_bias,
   3199 		  rsrc_directory * parent)
   3200 {
   3201   unsigned long val, addr, size;
   3202 
   3203   val = bfd_get_32 (abfd, data);
   3204 
   3205   entry->parent = parent;
   3206   entry->is_name = is_name;
   3207 
   3208   if (is_name)
   3209     {
   3210       bfd_byte * address;
   3211 
   3212       if (HighBitSet (val))
   3213 	{
   3214 	  val = WithoutHighBit (val);
   3215 
   3216 	  address = datastart + val;
   3217 	}
   3218       else
   3219 	{
   3220 	  address = datastart + val - rva_bias;
   3221 	}
   3222 
   3223       if (address + 3 > dataend)
   3224 	return dataend;
   3225 
   3226       entry->name_id.name.len    = bfd_get_16 (abfd, address);
   3227       entry->name_id.name.string = address + 2;
   3228     }
   3229   else
   3230     entry->name_id.id = val;
   3231 
   3232   val = bfd_get_32 (abfd, data + 4);
   3233 
   3234   if (HighBitSet (val))
   3235     {
   3236       entry->is_dir = TRUE;
   3237       entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
   3238       if (entry->value.directory == NULL)
   3239 	return dataend;
   3240 
   3241       return rsrc_parse_directory (abfd, entry->value.directory,
   3242 				   datastart,
   3243 				   datastart + WithoutHighBit (val),
   3244 				   dataend, rva_bias, entry);
   3245     }
   3246 
   3247   entry->is_dir = FALSE;
   3248   entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
   3249   if (entry->value.leaf == NULL)
   3250     return dataend;
   3251 
   3252   addr = bfd_get_32 (abfd, datastart + val);
   3253   size = entry->value.leaf->size = bfd_get_32 (abfd, datastart + val + 4);
   3254   entry->value.leaf->codepage = bfd_get_32 (abfd, datastart + val + 8);
   3255 
   3256   entry->value.leaf->data = bfd_malloc (size);
   3257   if (entry->value.leaf->data == NULL)
   3258     return dataend;
   3259 
   3260   memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
   3261   return datastart + (addr - rva_bias) + size;
   3262 }
   3263 
   3264 static bfd_byte *
   3265 rsrc_parse_entries (bfd *            abfd,
   3266 		    rsrc_dir_chain * chain,
   3267 		    bfd_boolean      is_name,
   3268 		    bfd_byte *       highest_data,
   3269 		    bfd_byte *       datastart,
   3270 		    bfd_byte *       data,
   3271 		    bfd_byte *       dataend,
   3272 		    bfd_vma          rva_bias,
   3273 		    rsrc_directory * parent)
   3274 {
   3275   unsigned int i;
   3276   rsrc_entry * entry;
   3277 
   3278   if (chain->num_entries == 0)
   3279     {
   3280       chain->first_entry = chain->last_entry = NULL;
   3281       return highest_data;
   3282     }
   3283 
   3284   entry = bfd_malloc (sizeof * entry);
   3285   if (entry == NULL)
   3286     return dataend;
   3287 
   3288   chain->first_entry = entry;
   3289 
   3290   for (i = chain->num_entries; i--;)
   3291     {
   3292       bfd_byte * entry_end;
   3293 
   3294       entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
   3295 				    data, dataend, rva_bias, parent);
   3296       data += 8;
   3297       highest_data = max (entry_end, highest_data);
   3298       if (entry_end > dataend)
   3299 	return dataend;
   3300 
   3301       if (i)
   3302 	{
   3303 	  entry->next_entry = bfd_malloc (sizeof * entry);
   3304 	  entry = entry->next_entry;
   3305 	  if (entry == NULL)
   3306 	    return dataend;
   3307 	}
   3308       else
   3309 	entry->next_entry = NULL;
   3310     }
   3311 
   3312   chain->last_entry = entry;
   3313 
   3314   return highest_data;
   3315 }
   3316 
   3317 static bfd_byte *
   3318 rsrc_parse_directory (bfd *            abfd,
   3319 		      rsrc_directory * table,
   3320 		      bfd_byte *       datastart,
   3321 		      bfd_byte *       data,
   3322 		      bfd_byte *       dataend,
   3323 		      bfd_vma          rva_bias,
   3324 		      rsrc_entry *     entry)
   3325 {
   3326   bfd_byte * highest_data = data;
   3327 
   3328   if (table == NULL)
   3329     return dataend;
   3330 
   3331   table->characteristics = bfd_get_32 (abfd, data);
   3332   table->time = bfd_get_32 (abfd, data + 4);
   3333   table->major = bfd_get_16 (abfd, data + 8);
   3334   table->minor = bfd_get_16 (abfd, data + 10);
   3335   table->names.num_entries = bfd_get_16 (abfd, data + 12);
   3336   table->ids.num_entries = bfd_get_16 (abfd, data + 14);
   3337   table->entry = entry;
   3338 
   3339   data += 16;
   3340 
   3341   highest_data = rsrc_parse_entries (abfd, & table->names, TRUE, data,
   3342 				     datastart, data, dataend, rva_bias, table);
   3343   data += table->names.num_entries * 8;
   3344 
   3345   highest_data = rsrc_parse_entries (abfd, & table->ids, FALSE, highest_data,
   3346 				     datastart, data, dataend, rva_bias, table);
   3347   data += table->ids.num_entries * 8;
   3348 
   3349   return max (highest_data, data);
   3350 }
   3351 
   3352 typedef struct rsrc_write_data
   3353 {
   3354   bfd *      abfd;
   3355   bfd_byte * datastart;
   3356   bfd_byte * next_table;
   3357   bfd_byte * next_leaf;
   3358   bfd_byte * next_string;
   3359   bfd_byte * next_data;
   3360   bfd_vma    rva_bias;
   3361 } rsrc_write_data;
   3362 
   3363 static void
   3364 rsrc_write_string (rsrc_write_data * data,
   3365 		   rsrc_string *     string)
   3366 {
   3367   bfd_put_16 (data->abfd, string->len, data->next_string);
   3368   memcpy (data->next_string + 2, string->string, string->len * 2);
   3369   data->next_string += (string->len + 1) * 2;
   3370 }
   3371 
   3372 static inline unsigned int
   3373 rsrc_compute_rva (rsrc_write_data * data,
   3374 		  bfd_byte *        addr)
   3375 {
   3376   return (addr - data->datastart) + data->rva_bias;
   3377 }
   3378 
   3379 static void
   3380 rsrc_write_leaf (rsrc_write_data * data,
   3381 		 rsrc_leaf *       leaf)
   3382 {
   3383   bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
   3384 	      data->next_leaf);
   3385   bfd_put_32 (data->abfd, leaf->size,     data->next_leaf + 4);
   3386   bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
   3387   bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
   3388   data->next_leaf += 16;
   3389 
   3390   memcpy (data->next_data, leaf->data, leaf->size);
   3391   /* An undocumented feature of Windows resources is that each unit
   3392      of raw data is 8-byte aligned...  */
   3393   data->next_data += ((leaf->size + 7) & ~7);
   3394 }
   3395 
   3396 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
   3397 
   3398 static void
   3399 rsrc_write_entry (rsrc_write_data *  data,
   3400 		  bfd_byte *         where,
   3401 		  rsrc_entry *       entry)
   3402 {
   3403   if (entry->is_name)
   3404     {
   3405       bfd_put_32 (data->abfd,
   3406 		  SetHighBit (data->next_string - data->datastart),
   3407 		  where);
   3408       rsrc_write_string (data, & entry->name_id.name);
   3409     }
   3410   else
   3411     bfd_put_32 (data->abfd, entry->name_id.id, where);
   3412 
   3413   if (entry->is_dir)
   3414     {
   3415       bfd_put_32 (data->abfd,
   3416 		  SetHighBit (data->next_table - data->datastart),
   3417 		  where + 4);
   3418       rsrc_write_directory (data, entry->value.directory);
   3419     }
   3420   else
   3421     {
   3422       bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
   3423       rsrc_write_leaf (data, entry->value.leaf);
   3424     }
   3425 }
   3426 
   3427 static void
   3428 rsrc_compute_region_sizes (rsrc_directory * dir)
   3429 {
   3430   struct rsrc_entry * entry;
   3431 
   3432   if (dir == NULL)
   3433     return;
   3434 
   3435   sizeof_tables_and_entries += 16;
   3436 
   3437   for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
   3438     {
   3439       sizeof_tables_and_entries += 8;
   3440 
   3441       sizeof_strings += (entry->name_id.name.len + 1) * 2;
   3442 
   3443       if (entry->is_dir)
   3444 	rsrc_compute_region_sizes (entry->value.directory);
   3445       else
   3446 	sizeof_leaves += 16;
   3447     }
   3448 
   3449   for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
   3450     {
   3451       sizeof_tables_and_entries += 8;
   3452 
   3453       if (entry->is_dir)
   3454 	rsrc_compute_region_sizes (entry->value.directory);
   3455       else
   3456 	sizeof_leaves += 16;
   3457     }
   3458 }
   3459 
   3460 static void
   3461 rsrc_write_directory (rsrc_write_data * data,
   3462 		      rsrc_directory *  dir)
   3463 {
   3464   rsrc_entry * entry;
   3465   unsigned int i;
   3466   bfd_byte * next_entry;
   3467   bfd_byte * nt;
   3468 
   3469   bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
   3470   bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
   3471   bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
   3472   bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
   3473   bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
   3474   bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
   3475 
   3476   /* Compute where the entries and the next table will be placed.  */
   3477   next_entry = data->next_table + 16;
   3478   data->next_table = next_entry + (dir->names.num_entries * 8)
   3479     + (dir->ids.num_entries * 8);
   3480   nt = data->next_table;
   3481 
   3482   /* Write the entries.  */
   3483   for (i = dir->names.num_entries, entry = dir->names.first_entry;
   3484        i > 0 && entry != NULL;
   3485        i--, entry = entry->next_entry)
   3486     {
   3487       BFD_ASSERT (entry->is_name);
   3488       rsrc_write_entry (data, next_entry, entry);
   3489       next_entry += 8;
   3490     }
   3491   BFD_ASSERT (i == 0);
   3492   BFD_ASSERT (entry == NULL);
   3493 
   3494   for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
   3495        i > 0 && entry != NULL;
   3496        i--, entry = entry->next_entry)
   3497     {
   3498       BFD_ASSERT (! entry->is_name);
   3499       rsrc_write_entry (data, next_entry, entry);
   3500       next_entry += 8;
   3501     }
   3502   BFD_ASSERT (i == 0);
   3503   BFD_ASSERT (entry == NULL);
   3504   BFD_ASSERT (nt == next_entry);
   3505 }
   3506 
   3507 #if defined HAVE_WCHAR_H && ! defined __CYGWIN__ && ! defined __MINGW32__
   3508 /* Return the length (number of units) of the first character in S,
   3509    putting its 'ucs4_t' representation in *PUC.  */
   3510 
   3511 static unsigned int
   3512 #if defined HAVE_WCTYPE_H
   3513 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
   3514 #else
   3515 u16_mbtouc (wchar_t * puc, const unsigned short * s, unsigned int n)
   3516 #endif
   3517 {
   3518   unsigned short c = * s;
   3519 
   3520   if (c < 0xd800 || c >= 0xe000)
   3521     {
   3522       *puc = c;
   3523       return 1;
   3524     }
   3525 
   3526   if (c < 0xdc00)
   3527     {
   3528       if (n >= 2)
   3529         {
   3530           if (s[1] >= 0xdc00 && s[1] < 0xe000)
   3531             {
   3532               *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
   3533               return 2;
   3534             }
   3535         }
   3536       else
   3537         {
   3538           /* Incomplete multibyte character.  */
   3539           *puc = 0xfffd;
   3540           return n;
   3541         }
   3542     }
   3543 
   3544   /* Invalid multibyte character.  */
   3545   *puc = 0xfffd;
   3546   return 1;
   3547 }
   3548 #endif /* HAVE_WCHAR_H and not Cygwin/Mingw */
   3549 
   3550 /* Perform a comparison of two entries.  */
   3551 static signed int
   3552 rsrc_cmp (bfd_boolean is_name, rsrc_entry * a, rsrc_entry * b)
   3553 {
   3554   signed int    res;
   3555   bfd_byte *    astring;
   3556   unsigned int  alen;
   3557   bfd_byte *    bstring;
   3558   unsigned int  blen;
   3559 
   3560   if (! is_name)
   3561     return a->name_id.id - b->name_id.id;
   3562 
   3563   /* We have to perform a case insenstive, unicode string comparison...  */
   3564   astring = a->name_id.name.string;
   3565   alen    = a->name_id.name.len;
   3566   bstring = b->name_id.name.string;
   3567   blen    = b->name_id.name.len;
   3568 
   3569 #if defined  __CYGWIN__ || defined __MINGW32__
   3570   /* Under Windows hosts (both Cygwin and Mingw types),
   3571      unicode == UTF-16 == wchar_t.  The case insensitive string comparison
   3572      function however goes by different names in the two environments...  */
   3573 
   3574 #undef rscpcmp
   3575 #ifdef __CYGWIN__
   3576 #define rscpcmp wcsncasecmp
   3577 #endif
   3578 #ifdef __MINGW32__
   3579 #define rscpcmp wcsnicmp
   3580 #endif
   3581 
   3582   res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
   3583 		 min (alen, blen));
   3584 
   3585 #elif defined HAVE_WCHAR_H
   3586   {
   3587     unsigned int  i;
   3588 
   3589     res = 0;
   3590     for (i = min (alen, blen); i--; astring += 2, bstring += 2)
   3591       {
   3592 #if defined HAVE_WCTYPE_H
   3593 	wint_t awc;
   3594 	wint_t bwc;
   3595 #else
   3596 	wchar_t awc;
   3597 	wchar_t bwc;
   3598 #endif
   3599 
   3600 	/* Convert UTF-16 unicode characters into wchar_t characters
   3601 	   so that we can then perform a case insensitive comparison.  */
   3602 	unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
   3603 	unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
   3604 
   3605 	if (Alen != Blen)
   3606 	  return Alen - Blen;
   3607 
   3608 #ifdef HAVE_WCTYPE_H
   3609 	awc = towlower (awc);
   3610 	bwc = towlower (bwc);
   3611 
   3612 	res = awc - bwc;
   3613 #else
   3614 	res = wcsncasecmp (& awc, & bwc, 1);
   3615 #endif
   3616 	if (res)
   3617 	  break;
   3618       }
   3619   }
   3620 #else
   3621   /* Do the best we can - a case sensitive, untranslated comparison.  */
   3622   res = memcmp (astring, bstring, min (alen, blen) * 2);
   3623 #endif
   3624 
   3625   if (res == 0)
   3626     res = alen - blen;
   3627 
   3628   return res;
   3629 }
   3630 
   3631 static void
   3632 rsrc_print_name (char * buffer, rsrc_string string)
   3633 {
   3634   unsigned int  i;
   3635   bfd_byte *    name = string.string;
   3636 
   3637   for (i = string.len; i--; name += 2)
   3638     sprintf (buffer + strlen (buffer), "%.1s", name);
   3639 }
   3640 
   3641 static const char *
   3642 rsrc_resource_name (rsrc_entry * entry, rsrc_directory * dir)
   3643 {
   3644   static char buffer [256];
   3645   bfd_boolean is_string = FALSE;
   3646 
   3647   buffer[0] = 0;
   3648 
   3649   if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
   3650       && dir->entry->parent->entry != NULL)
   3651     {
   3652       strcpy (buffer, "type: ");
   3653       if (dir->entry->parent->entry->is_name)
   3654 	rsrc_print_name (buffer + strlen (buffer),
   3655 			 dir->entry->parent->entry->name_id.name);
   3656       else
   3657 	{
   3658 	  unsigned int id = dir->entry->parent->entry->name_id.id;
   3659 
   3660 	  sprintf (buffer + strlen (buffer), "%x", id);
   3661 	  switch (id)
   3662 	    {
   3663 	    case 1: strcat (buffer, " (CURSOR)"); break;
   3664 	    case 2: strcat (buffer, " (BITMAP)"); break;
   3665 	    case 3: strcat (buffer, " (ICON)"); break;
   3666             case 4: strcat (buffer, " (MENU)"); break;
   3667 	    case 5: strcat (buffer, " (DIALOG)"); break;
   3668 	    case 6: strcat (buffer, " (STRING)"); is_string = TRUE; break;
   3669 	    case 7: strcat (buffer, " (FONTDIR)"); break;
   3670 	    case 8: strcat (buffer, " (FONT)"); break;
   3671 	    case 9: strcat (buffer, " (ACCELERATOR)"); break;
   3672 	    case 10: strcat (buffer, " (RCDATA)"); break;
   3673 	    case 11: strcat (buffer, " (MESSAGETABLE)"); break;
   3674 	    case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
   3675 	    case 14: strcat (buffer, " (GROUP_ICON)"); break;
   3676 	    case 16: strcat (buffer, " (VERSION)"); break;
   3677 	    case 17: strcat (buffer, " (DLGINCLUDE)"); break;
   3678 	    case 19: strcat (buffer, " (PLUGPLAY)"); break;
   3679 	    case 20: strcat (buffer, " (VXD)"); break;
   3680 	    case 21: strcat (buffer, " (ANICURSOR)"); break;
   3681 	    case 22: strcat (buffer, " (ANIICON)"); break;
   3682 	    case 23: strcat (buffer, " (HTML)"); break;
   3683 	    case 24: strcat (buffer, " (MANIFEST)"); break;
   3684 	    case 240: strcat (buffer, " (DLGINIT)"); break;
   3685 	    case 241: strcat (buffer, " (TOOLBAR)"); break;
   3686 	    }
   3687 	}
   3688     }
   3689 
   3690   if (dir != NULL && dir->entry != NULL)
   3691     {
   3692       strcat (buffer, " name: ");
   3693       if (dir->entry->is_name)
   3694 	rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
   3695       else
   3696 	{
   3697 	  unsigned int id = dir->entry->name_id.id;
   3698 
   3699 	  sprintf (buffer + strlen (buffer), "%x", id);
   3700 
   3701 	  if (is_string)
   3702 	    sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
   3703 		     (id - 1) << 4, (id << 4) - 1);
   3704 	}
   3705     }
   3706 
   3707   if (entry != NULL)
   3708     {
   3709       strcat (buffer, " lang: ");
   3710 
   3711       if (entry->is_name)
   3712 	rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
   3713       else
   3714 	sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
   3715     }
   3716 
   3717   return buffer;
   3718 }
   3719 
   3720 /* *sigh* Windows resource strings are special.  Only the top 28-bits of
   3721    their ID is stored in the NAME entry.  The bottom four bits are used as
   3722    an index into unicode string table that makes up the data of the leaf.
   3723    So identical type-name-lang string resources may not actually be
   3724    identical at all.
   3725 
   3726    This function is called when we have detected two string resources with
   3727    match top-28-bit IDs.  We have to scan the string tables inside the leaves
   3728    and discover if there are any real collisions.  If there are then we report
   3729    them and return FALSE.  Otherwise we copy any strings from B into A and
   3730    then return TRUE.  */
   3731 
   3732 static bfd_boolean
   3733 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
   3734 			   rsrc_entry * b ATTRIBUTE_UNUSED)
   3735 {
   3736   unsigned int copy_needed = 0;
   3737   unsigned int i;
   3738   bfd_byte * astring;
   3739   bfd_byte * bstring;
   3740   bfd_byte * new_data;
   3741   bfd_byte * nstring;
   3742 
   3743   /* Step one: Find out what we have to do.  */
   3744   BFD_ASSERT (! a->is_dir);
   3745   astring = a->value.leaf->data;
   3746 
   3747   BFD_ASSERT (! b->is_dir);
   3748   bstring = b->value.leaf->data;
   3749 
   3750   for (i = 0; i < 16; i++)
   3751     {
   3752       unsigned int alen = astring[0] + (astring[1] << 8);
   3753       unsigned int blen = bstring[0] + (bstring[1] << 8);
   3754 
   3755       if (alen == 0)
   3756 	{
   3757 	  copy_needed += blen * 2;
   3758 	}
   3759       else if (blen == 0)
   3760 	;
   3761       else if (alen != blen)
   3762 	/* FIXME: Should we continue the loop in order to report other duplicates ?  */
   3763 	break;
   3764       /* alen == blen != 0.  We might have two identical strings.  If so we
   3765 	 can ignore the second one.  There is no need for wchar_t vs UTF-16
   3766 	 theatrics here - we are only interested in (case sensitive) equality.  */
   3767       else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
   3768 	break;
   3769 
   3770       astring += (alen + 1) * 2;
   3771       bstring += (blen + 1) * 2;
   3772     }
   3773 
   3774   if (i != 16)
   3775     {
   3776       if (a->parent != NULL
   3777 	  && a->parent->entry != NULL
   3778 	  && a->parent->entry->is_name == FALSE)
   3779 	_bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
   3780 			    ((a->parent->entry->name_id.id - 1) << 4) + i);
   3781       return FALSE;
   3782     }
   3783 
   3784   if (copy_needed == 0)
   3785     return TRUE;
   3786 
   3787   /* If we reach here then A and B must both have non-colliding strings.
   3788      (We never get string resources with fully empty string tables).
   3789      We need to allocate an extra COPY_NEEDED bytes in A and then bring
   3790      in B's strings.  */
   3791   new_data = bfd_malloc (a->value.leaf->size + copy_needed);
   3792   if (new_data == NULL)
   3793     return FALSE;
   3794 
   3795   nstring = new_data;
   3796   astring = a->value.leaf->data;
   3797   bstring = b->value.leaf->data;
   3798 
   3799   for (i = 0; i < 16; i++)
   3800     {
   3801       unsigned int alen = astring[0] + (astring[1] << 8);
   3802       unsigned int blen = bstring[0] + (bstring[1] << 8);
   3803 
   3804       if (alen != 0)
   3805 	{
   3806 	  memcpy (nstring, astring, (alen + 1) * 2);
   3807 	  nstring += (alen + 1) * 2;
   3808 	}
   3809       else if (blen != 0)
   3810 	{
   3811 	  memcpy (nstring, bstring, (blen + 1) * 2);
   3812 	  nstring += (blen + 1) * 2;
   3813 	}
   3814       else
   3815 	{
   3816 	  * nstring++ = 0;
   3817 	  * nstring++ = 0;
   3818 	}
   3819 
   3820       astring += (alen + 1) * 2;
   3821       bstring += (blen + 1) * 2;
   3822     }
   3823 
   3824   BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
   3825 
   3826   free (a->value.leaf->data);
   3827   a->value.leaf->data = new_data;
   3828   a->value.leaf->size += copy_needed;
   3829 
   3830   return TRUE;
   3831 }
   3832 
   3833 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
   3834 
   3835 /* Sort the entries in given part of the directory.
   3836    We use an old fashioned bubble sort because we are dealing
   3837    with lists and we want to handle matches specially.  */
   3838 
   3839 static void
   3840 rsrc_sort_entries (rsrc_dir_chain *  chain,
   3841 		   bfd_boolean       is_name,
   3842 		   rsrc_directory *  dir)
   3843 {
   3844   rsrc_entry * entry;
   3845   rsrc_entry * next;
   3846   rsrc_entry ** points_to_entry;
   3847   bfd_boolean swapped;
   3848 
   3849   if (chain->num_entries < 2)
   3850     return;
   3851 
   3852   do
   3853     {
   3854       swapped = FALSE;
   3855       points_to_entry = & chain->first_entry;
   3856       entry = * points_to_entry;
   3857       next  = entry->next_entry;
   3858 
   3859       do
   3860 	{
   3861 	  signed int cmp = rsrc_cmp (is_name, entry, next);
   3862 
   3863 	  if (cmp > 0)
   3864 	    {
   3865 	      entry->next_entry = next->next_entry;
   3866 	      next->next_entry = entry;
   3867 	      * points_to_entry = next;
   3868 	      points_to_entry = & next->next_entry;
   3869 	      next = entry->next_entry;
   3870 	      swapped = TRUE;
   3871 	    }
   3872 	  else if (cmp == 0)
   3873 	    {
   3874 	      if (entry->is_dir && next->is_dir)
   3875 		{
   3876 		  /* When we encounter identical directory entries we have to
   3877 		     merge them together.  The exception to this rule is for
   3878 		     resource manifests - there can only be one of these,
   3879 		     even if they differ in language.  Zero-language manifests
   3880 		     are assumed to be default manifests (provided by the
   3881 		     Cygwin/MinGW build system) and these can be silently dropped,
   3882 		     unless that would reduce the number of manifests to zero.
   3883 		     There should only ever be one non-zero lang manifest -
   3884 		     if there are more it is an error.  A non-zero lang
   3885 		     manifest takes precedence over a default manifest.  */
   3886 		  if (entry->is_name == FALSE
   3887 		      && entry->name_id.id == 1
   3888 		      && dir != NULL
   3889 		      && dir->entry != NULL
   3890 		      && dir->entry->is_name == FALSE
   3891 		      && dir->entry->name_id.id == 0x18)
   3892 		    {
   3893 		      if (next->value.directory->names.num_entries == 0
   3894 			  && next->value.directory->ids.num_entries == 1
   3895 			  && next->value.directory->ids.first_entry->is_name == FALSE
   3896 			  && next->value.directory->ids.first_entry->name_id.id == 0)
   3897 			/* Fall through so that NEXT is dropped.  */
   3898 			;
   3899 		      else if (entry->value.directory->names.num_entries == 0
   3900 			       && entry->value.directory->ids.num_entries == 1
   3901 			       && entry->value.directory->ids.first_entry->is_name == FALSE
   3902 			       && entry->value.directory->ids.first_entry->name_id.id == 0)
   3903 			{
   3904 			  /* Swap ENTRY and NEXT.  Then fall through so that the old ENTRY is dropped.  */
   3905 			  entry->next_entry = next->next_entry;
   3906 			  next->next_entry = entry;
   3907 			  * points_to_entry = next;
   3908 			  points_to_entry = & next->next_entry;
   3909 			  next = entry->next_entry;
   3910 			  swapped = TRUE;
   3911 			}
   3912 		      else
   3913 			{
   3914 			  _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
   3915 			  bfd_set_error (bfd_error_file_truncated);
   3916 			  return;
   3917 			}
   3918 
   3919 		      /* Unhook NEXT from the chain.  */
   3920 		      /* FIXME: memory loss here.  */
   3921 		      entry->next_entry = next->next_entry;
   3922 		      chain->num_entries --;
   3923 		      if (chain->num_entries < 2)
   3924 			return;
   3925 		      next = next->next_entry;
   3926 		    }
   3927 		  else
   3928 		    rsrc_merge (entry, next);
   3929 		}
   3930 	      else if (entry->is_dir != next->is_dir)
   3931 		{
   3932 		  _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
   3933 		  bfd_set_error (bfd_error_file_truncated);
   3934 		  return;
   3935 		}
   3936 	      else
   3937 		{
   3938 		  /* Otherwise with identical leaves we issue an error
   3939 		     message - because there should never be duplicates.
   3940 		     The exception is Type 18/Name 1/Lang 0 which is the
   3941 		     defaul manifest - this can just be dropped.  */
   3942 		  if (entry->is_name == FALSE
   3943 		      && entry->name_id.id == 0
   3944 		      && dir != NULL
   3945 		      && dir->entry != NULL
   3946 		      && dir->entry->is_name == FALSE
   3947 		      && dir->entry->name_id.id == 1
   3948 		      && dir->entry->parent != NULL
   3949 		      && dir->entry->parent->entry != NULL
   3950 		      && dir->entry->parent->entry->is_name == FALSE
   3951 		      && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
   3952 		    ;
   3953 		  else if (dir != NULL
   3954 			   && dir->entry != NULL
   3955 			   && dir->entry->parent != NULL
   3956 			   && dir->entry->parent->entry != NULL
   3957 			   && dir->entry->parent->entry->is_name == FALSE
   3958 			   && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
   3959 		    {
   3960 		      /* Strings need special handling.  */
   3961 		      if (! rsrc_merge_string_entries (entry, next))
   3962 			{
   3963 			  /* _bfd_error_handler should have been called inside merge_strings.  */
   3964 			  bfd_set_error (bfd_error_file_truncated);
   3965 			  return;
   3966 			}
   3967 		    }
   3968 		  else
   3969 		    {
   3970 		      if (dir == NULL
   3971 			  || dir->entry == NULL
   3972 			  || dir->entry->parent == NULL
   3973 			  || dir->entry->parent->entry == NULL)
   3974 			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
   3975 		      else
   3976 			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
   3977 					    rsrc_resource_name (entry, dir));
   3978 		      bfd_set_error (bfd_error_file_truncated);
   3979 		      return;
   3980 		    }
   3981 		}
   3982 
   3983 	      /* Unhook NEXT from the chain.  */
   3984 	      entry->next_entry = next->next_entry;
   3985 	      chain->num_entries --;
   3986 	      if (chain->num_entries < 2)
   3987 		return;
   3988 	      next = next->next_entry;
   3989 	    }
   3990 	  else
   3991 	    {
   3992 	      points_to_entry = & entry->next_entry;
   3993 	      entry = next;
   3994 	      next = next->next_entry;
   3995 	    }
   3996 	}
   3997       while (next);
   3998 
   3999       chain->last_entry = entry;
   4000     }
   4001   while (swapped);
   4002 }
   4003 
   4004 /* Attach B's chain onto A.  */
   4005 static void
   4006 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
   4007 {
   4008   if (bchain->num_entries == 0)
   4009     return;
   4010 
   4011   achain->num_entries += bchain->num_entries;
   4012 
   4013   if (achain->first_entry == NULL)
   4014     {
   4015       achain->first_entry = bchain->first_entry;
   4016       achain->last_entry  = bchain->last_entry;
   4017     }
   4018   else
   4019     {
   4020       achain->last_entry->next_entry = bchain->first_entry;
   4021       achain->last_entry = bchain->last_entry;
   4022     }
   4023 
   4024   bchain->num_entries = 0;
   4025   bchain->first_entry = bchain->last_entry = NULL;
   4026 }
   4027 
   4028 static void
   4029 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
   4030 {
   4031   rsrc_directory * adir;
   4032   rsrc_directory * bdir;
   4033 
   4034   BFD_ASSERT (a->is_dir);
   4035   BFD_ASSERT (b->is_dir);
   4036 
   4037   adir = a->value.directory;
   4038   bdir = b->value.directory;
   4039 
   4040   if (adir->characteristics != bdir->characteristics)
   4041     {
   4042       _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics\n"));
   4043       bfd_set_error (bfd_error_file_truncated);
   4044       return;
   4045     }
   4046 
   4047   if (adir->major != bdir->major || adir->minor != bdir->minor)
   4048     {
   4049       _bfd_error_handler (_(".rsrc merge failure: differing directory versions\n"));
   4050       bfd_set_error (bfd_error_file_truncated);
   4051       return;
   4052     }
   4053 
   4054   /* Attach B's name chain to A.  */
   4055   rsrc_attach_chain (& adir->names, & bdir->names);
   4056 
   4057   /* Attach B's ID chain to A.  */
   4058   rsrc_attach_chain (& adir->ids, & bdir->ids);
   4059 
   4060   /* Now sort A's entries.  */
   4061   rsrc_sort_entries (& adir->names, TRUE, adir);
   4062   rsrc_sort_entries (& adir->ids, FALSE, adir);
   4063 }
   4064 
   4065 /* Check the .rsrc section.  If it contains multiple concatenated
   4066    resources then we must merge them properly.  Otherwise Windows
   4067    will ignore all but the first set.  */
   4068 
   4069 static void
   4070 rsrc_process_section (bfd * abfd,
   4071 		      struct coff_final_link_info * pfinfo)
   4072 {
   4073   rsrc_directory    new_table;
   4074   bfd_size_type     size;
   4075   asection *        sec;
   4076   pe_data_type *    pe;
   4077   bfd_vma           rva_bias;
   4078   bfd_byte *        data;
   4079   bfd_byte *        datastart;
   4080   bfd_byte *        dataend;
   4081   bfd_byte *        new_data;
   4082   unsigned int      num_resource_sets;
   4083   rsrc_directory *  type_tables;
   4084   rsrc_write_data   write_data;
   4085   unsigned int      indx;
   4086   bfd *             input;
   4087   unsigned int      num_input_rsrc = 0;
   4088   unsigned int      max_num_input_rsrc = 4;
   4089   ptrdiff_t *       rsrc_sizes = NULL;
   4090 
   4091   new_table.names.num_entries = 0;
   4092   new_table.ids.num_entries = 0;
   4093 
   4094   sec = bfd_get_section_by_name (abfd, ".rsrc");
   4095   if (sec == NULL || (size = sec->rawsize) == 0)
   4096     return;
   4097 
   4098   pe = pe_data (abfd);
   4099   if (pe == NULL)
   4100     return;
   4101 
   4102   rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
   4103 
   4104   data = bfd_malloc (size);
   4105   if (data == NULL)
   4106     return;
   4107 
   4108   datastart = data;
   4109 
   4110   if (! bfd_get_section_contents (abfd, sec, data, 0, size))
   4111     goto end;
   4112 
   4113   /* Step zero: Scan the input bfds looking for .rsrc sections and record
   4114      their lengths.  Note - we rely upon the fact that the linker script
   4115      does *not* sort the input .rsrc sections, so that the order in the
   4116      linkinfo list matches the order in the output .rsrc section.
   4117 
   4118      We need to know the lengths because each input .rsrc section has padding
   4119      at the end of a variable amount.  (It does not appear to be based upon
   4120      the section alignment or the file alignment).  We need to skip any
   4121      padding bytes when parsing the input .rsrc sections.  */
   4122   rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes);
   4123   if (rsrc_sizes == NULL)
   4124     goto end;
   4125 
   4126   for (input = pfinfo->info->input_bfds;
   4127        input != NULL;
   4128        input = input->link.next)
   4129     {
   4130       asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
   4131 
   4132       if (rsrc_sec != NULL)
   4133 	{
   4134 	  if (num_input_rsrc == max_num_input_rsrc)
   4135 	    {
   4136 	      max_num_input_rsrc += 10;
   4137 	      rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
   4138 					* sizeof * rsrc_sizes);
   4139 	      if (rsrc_sizes == NULL)
   4140 		goto end;
   4141 	    }
   4142 
   4143 	  BFD_ASSERT (rsrc_sec->size > 0);
   4144 	  rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
   4145 	}
   4146     }
   4147 
   4148   if (num_input_rsrc < 2)
   4149     goto end;
   4150 
   4151   /* Step one: Walk the section, computing the size of the tables,
   4152      leaves and data and decide if we need to do anything.  */
   4153   dataend = data + size;
   4154   num_resource_sets = 0;
   4155 
   4156   while (data < dataend)
   4157     {
   4158       bfd_byte * p = data;
   4159 
   4160       data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
   4161 
   4162       if (data > dataend)
   4163 	{
   4164 	  /* Corrupted .rsrc section - cannot merge.  */
   4165 	  _bfd_error_handler (_("%s: .rsrc merge failure: corrupt .rsrc section"),
   4166 			      bfd_get_filename (abfd));
   4167 	  bfd_set_error (bfd_error_file_truncated);
   4168 	  goto end;
   4169 	}
   4170 
   4171       if ((data - p) > rsrc_sizes [num_resource_sets])
   4172 	{
   4173 	  _bfd_error_handler (_("%s: .rsrc merge failure: unexpected .rsrc size"),
   4174 			      bfd_get_filename (abfd));
   4175 	  bfd_set_error (bfd_error_file_truncated);
   4176 	  goto end;
   4177 	}
   4178       /* FIXME: Should we add a check for "data - p" being much smaller
   4179 	 than rsrc_sizes[num_resource_sets] ?  */
   4180 
   4181       data = p + rsrc_sizes[num_resource_sets];
   4182       rva_bias += data - p;
   4183       ++ num_resource_sets;
   4184     }
   4185   BFD_ASSERT (num_resource_sets == num_input_rsrc);
   4186 
   4187   /* Step two: Walk the data again, building trees of the resources.  */
   4188   data = datastart;
   4189   rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
   4190 
   4191   type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
   4192   if (type_tables == NULL)
   4193     goto end;
   4194 
   4195   indx = 0;
   4196   while (data < dataend)
   4197     {
   4198       bfd_byte * p = data;
   4199 
   4200       (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
   4201 				   dataend, rva_bias, NULL);
   4202       data = p + rsrc_sizes[indx];
   4203       rva_bias += data - p;
   4204       ++ indx;
   4205     }
   4206   BFD_ASSERT (indx == num_resource_sets);
   4207 
   4208   /* Step three: Merge the top level tables (there can be only one).
   4209 
   4210      We must ensure that the merged entries are in ascending order.
   4211 
   4212      We also thread the top level table entries from the old tree onto
   4213      the new table, so that they can be pulled off later.  */
   4214 
   4215   /* FIXME: Should we verify that all type tables are the same ?  */
   4216   new_table.characteristics = type_tables[0].characteristics;
   4217   new_table.time            = type_tables[0].time;
   4218   new_table.major           = type_tables[0].major;
   4219   new_table.minor           = type_tables[0].minor;
   4220 
   4221   /* Chain the NAME entries onto the table.  */
   4222   new_table.names.first_entry = NULL;
   4223   new_table.names.last_entry = NULL;
   4224 
   4225   for (indx = 0; indx < num_resource_sets; indx++)
   4226     rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
   4227 
   4228   rsrc_sort_entries (& new_table.names, TRUE, & new_table);
   4229 
   4230   /* Chain the ID entries onto the table.  */
   4231   new_table.ids.first_entry = NULL;
   4232   new_table.ids.last_entry = NULL;
   4233 
   4234   for (indx = 0; indx < num_resource_sets; indx++)
   4235     rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
   4236 
   4237   rsrc_sort_entries (& new_table.ids, FALSE, & new_table);
   4238 
   4239   /* Step four: Create new contents for the .rsrc section.  */
   4240   /* Step four point one: Compute the size of each region of the .rsrc section.
   4241      We do this now, rather than earlier, as the merging above may have dropped
   4242      some entries.  */
   4243   sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
   4244   rsrc_compute_region_sizes (& new_table);
   4245   /* We increment sizeof_strings to make sure that resource data
   4246      starts on an 8-byte boundary.  FIXME: Is this correct ?  */
   4247   sizeof_strings = (sizeof_strings + 7) & ~ 7;
   4248 
   4249   new_data = bfd_zalloc (abfd, size);
   4250   if (new_data == NULL)
   4251     goto end;
   4252 
   4253   write_data.abfd        = abfd;
   4254   write_data.datastart   = new_data;
   4255   write_data.next_table  = new_data;
   4256   write_data.next_leaf   = new_data + sizeof_tables_and_entries;
   4257   write_data.next_string = write_data.next_leaf + sizeof_leaves;
   4258   write_data.next_data   = write_data.next_string + sizeof_strings;
   4259   write_data.rva_bias    = sec->vma - pe->pe_opthdr.ImageBase;
   4260 
   4261   rsrc_write_directory (& write_data, & new_table);
   4262 
   4263   /* Step five: Replace the old contents with the new.
   4264      We recompute the size as we may have lost entries due to mergeing.  */
   4265   size = ((write_data.next_data - new_data) + 3) & ~ 3;
   4266 
   4267   {
   4268     int page_size;
   4269 
   4270     if (coff_data (abfd)->link_info)
   4271       {
   4272 	page_size = pe_data (abfd)->pe_opthdr.FileAlignment;
   4273 
   4274 	/* If no file alignment has been set, default to one.
   4275 	   This repairs 'ld -r' for arm-wince-pe target.  */
   4276 	if (page_size == 0)
   4277 	  page_size = 1;
   4278       }
   4279     else
   4280       page_size = PE_DEF_FILE_ALIGNMENT;
   4281     size = (size + page_size - 1) & - page_size;
   4282   }
   4283 
   4284   bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
   4285   sec->size = sec->rawsize = size;
   4286 
   4287  end:
   4288   /* Step six: Free all the memory that we have used.  */
   4289   /* FIXME: Free the resource tree, if we have one.  */
   4290   free (datastart);
   4291   free (rsrc_sizes);
   4292 }
   4293 
   4294 /* Handle the .idata section and other things that need symbol table
   4295    access.  */
   4296 
   4297 bfd_boolean
   4298 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
   4299 {
   4300   struct coff_link_hash_entry *h1;
   4301   struct bfd_link_info *info = pfinfo->info;
   4302   bfd_boolean result = TRUE;
   4303 
   4304   /* There are a few fields that need to be filled in now while we
   4305      have symbol table access.
   4306 
   4307      The .idata subsections aren't directly available as sections, but
   4308      they are in the symbol table, so get them from there.  */
   4309 
   4310   /* The import directory.  This is the address of .idata$2, with size
   4311      of .idata$2 + .idata$3.  */
   4312   h1 = coff_link_hash_lookup (coff_hash_table (info),
   4313 			      ".idata$2", FALSE, FALSE, TRUE);
   4314   if (h1 != NULL)
   4315     {
   4316       /* PR ld/2729: We cannot rely upon all the output sections having been
   4317 	 created properly, so check before referencing them.  Issue a warning
   4318 	 message for any sections tht could not be found.  */
   4319       if ((h1->root.type == bfd_link_hash_defined
   4320 	   || h1->root.type == bfd_link_hash_defweak)
   4321 	  && h1->root.u.def.section != NULL
   4322 	  && h1->root.u.def.section->output_section != NULL)
   4323 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
   4324 	  (h1->root.u.def.value
   4325 	   + h1->root.u.def.section->output_section->vma
   4326 	   + h1->root.u.def.section->output_offset);
   4327       else
   4328 	{
   4329 	  _bfd_error_handler
   4330 	    (_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"),
   4331 	     abfd);
   4332 	  result = FALSE;
   4333 	}
   4334 
   4335       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4336 				  ".idata$4", FALSE, FALSE, TRUE);
   4337       if (h1 != NULL
   4338 	  && (h1->root.type == bfd_link_hash_defined
   4339 	   || h1->root.type == bfd_link_hash_defweak)
   4340 	  && h1->root.u.def.section != NULL
   4341 	  && h1->root.u.def.section->output_section != NULL)
   4342 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
   4343 	  ((h1->root.u.def.value
   4344 	    + h1->root.u.def.section->output_section->vma
   4345 	    + h1->root.u.def.section->output_offset)
   4346 	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
   4347       else
   4348 	{
   4349 	  _bfd_error_handler
   4350 	    (_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"),
   4351 	     abfd);
   4352 	  result = FALSE;
   4353 	}
   4354 
   4355       /* The import address table.  This is the size/address of
   4356          .idata$5.  */
   4357       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4358 				  ".idata$5", FALSE, FALSE, TRUE);
   4359       if (h1 != NULL
   4360 	  && (h1->root.type == bfd_link_hash_defined
   4361 	   || h1->root.type == bfd_link_hash_defweak)
   4362 	  && h1->root.u.def.section != NULL
   4363 	  && h1->root.u.def.section->output_section != NULL)
   4364 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
   4365 	  (h1->root.u.def.value
   4366 	   + h1->root.u.def.section->output_section->vma
   4367 	   + h1->root.u.def.section->output_offset);
   4368       else
   4369 	{
   4370 	  _bfd_error_handler
   4371 	    (_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"),
   4372 	     abfd);
   4373 	  result = FALSE;
   4374 	}
   4375 
   4376       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4377 				  ".idata$6", FALSE, FALSE, TRUE);
   4378       if (h1 != NULL
   4379 	  && (h1->root.type == bfd_link_hash_defined
   4380 	   || h1->root.type == bfd_link_hash_defweak)
   4381 	  && h1->root.u.def.section != NULL
   4382 	  && h1->root.u.def.section->output_section != NULL)
   4383 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
   4384 	  ((h1->root.u.def.value
   4385 	    + h1->root.u.def.section->output_section->vma
   4386 	    + h1->root.u.def.section->output_offset)
   4387 	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
   4388       else
   4389 	{
   4390 	  _bfd_error_handler
   4391 	    (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
   4392 	     abfd);
   4393 	  result = FALSE;
   4394 	}
   4395     }
   4396   else
   4397     {
   4398       h1 = coff_link_hash_lookup (coff_hash_table (info),
   4399 				  "__IAT_start__", FALSE, FALSE, TRUE);
   4400       if (h1 != NULL
   4401 	  && (h1->root.type == bfd_link_hash_defined
   4402 	   || h1->root.type == bfd_link_hash_defweak)
   4403 	  && h1->root.u.def.section != NULL
   4404 	  && h1->root.u.def.section->output_section != NULL)
   4405 	{
   4406 	  bfd_vma iat_va;
   4407 
   4408 	  iat_va =
   4409 	    (h1->root.u.def.value
   4410 	     + h1->root.u.def.section->output_section->vma
   4411 	     + h1->root.u.def.section->output_offset);
   4412 
   4413 	  h1 = coff_link_hash_lookup (coff_hash_table (info),
   4414 				      "__IAT_end__", FALSE, FALSE, TRUE);
   4415 	  if (h1 != NULL
   4416 	      && (h1->root.type == bfd_link_hash_defined
   4417 	       || h1->root.type == bfd_link_hash_defweak)
   4418 	      && h1->root.u.def.section != NULL
   4419 	      && h1->root.u.def.section->output_section != NULL)
   4420 	    {
   4421 	      pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
   4422 		((h1->root.u.def.value
   4423 		  + h1->root.u.def.section->output_section->vma
   4424 		  + h1->root.u.def.section->output_offset)
   4425 		 - iat_va);
   4426 	      if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
   4427 		pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
   4428 		  iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
   4429 	    }
   4430 	  else
   4431 	    {
   4432 	      _bfd_error_handler
   4433 		(_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
   4434 		   " because .idata$6 is missing"), abfd);
   4435 	      result = FALSE;
   4436 	    }
   4437         }
   4438     }
   4439 
   4440   h1 = coff_link_hash_lookup (coff_hash_table (info),
   4441 			      (bfd_get_symbol_leading_char (abfd) != 0
   4442 			       ? "__tls_used" : "_tls_used"),
   4443 			      FALSE, FALSE, TRUE);
   4444   if (h1 != NULL)
   4445     {
   4446       if ((h1->root.type == bfd_link_hash_defined
   4447 	   || h1->root.type == bfd_link_hash_defweak)
   4448 	  && h1->root.u.def.section != NULL
   4449 	  && h1->root.u.def.section->output_section != NULL)
   4450 	pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
   4451 	  (h1->root.u.def.value
   4452 	   + h1->root.u.def.section->output_section->vma
   4453 	   + h1->root.u.def.section->output_offset
   4454 	   - pe_data (abfd)->pe_opthdr.ImageBase);
   4455       else
   4456 	{
   4457 	  _bfd_error_handler
   4458 	    (_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"),
   4459 	     abfd);
   4460 	  result = FALSE;
   4461 	}
   4462      /* According to PECOFF sepcifications by Microsoft version 8.2
   4463 	the TLS data directory consists of 4 pointers, followed
   4464 	by two 4-byte integer. This implies that the total size
   4465 	is different for 32-bit and 64-bit executables.  */
   4466 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
   4467       pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
   4468 #else
   4469       pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
   4470 #endif
   4471     }
   4472 
   4473 /* If there is a .pdata section and we have linked pdata finally, we
   4474      need to sort the entries ascending.  */
   4475 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
   4476   {
   4477     asection *sec = bfd_get_section_by_name (abfd, ".pdata");
   4478 
   4479     if (sec)
   4480       {
   4481 	bfd_size_type x = sec->rawsize;
   4482 	bfd_byte *tmp_data = NULL;
   4483 
   4484 	if (x)
   4485 	  tmp_data = bfd_malloc (x);
   4486 
   4487 	if (tmp_data != NULL)
   4488 	  {
   4489 	    if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
   4490 	      {
   4491 		qsort (tmp_data,
   4492 		       (size_t) (x / 12),
   4493 		       12, sort_x64_pdata);
   4494 		bfd_set_section_contents (pfinfo->output_bfd, sec,
   4495 					  tmp_data, 0, x);
   4496 	      }
   4497 	    free (tmp_data);
   4498 	  }
   4499       }
   4500   }
   4501 #endif
   4502 
   4503   rsrc_process_section (abfd, pfinfo);
   4504 
   4505   /* If we couldn't find idata$2, we either have an excessively
   4506      trivial program or are in DEEP trouble; we have to assume trivial
   4507      program....  */
   4508   return result;
   4509 }
   4510