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