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