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