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