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