Subversion Repositories Kolibri OS

Rev

Rev 5197 | Blame | Compare with Previous | Last modification | View Log | RSS feed

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