]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/binutils/bfd/peXXigen.c
src.conf.5: regen after r368667, GDB retirement
[FreeBSD/FreeBSD.git] / contrib / binutils / bfd / peXXigen.c
1 /* Support for the generic parts of PE/PEI; the common executable parts.
2    Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007 Free Software Foundation, Inc.
4    Written by Cygnus Solutions.
5
6    This file is part of BFD, the Binary File Descriptor library.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
21
22 /* Most of this hacked by Steve Chamberlain <sac@cygnus.com>.
23
24    PE/PEI rearrangement (and code added): Donn Terry
25                                           Softway Systems, Inc.  */
26
27 /* Hey look, some documentation [and in a place you expect to find it]!
28
29    The main reference for the pei format is "Microsoft Portable Executable
30    and Common Object File Format Specification 4.1".  Get it if you need to
31    do some serious hacking on this code.
32
33    Another reference:
34    "Peering Inside the PE: A Tour of the Win32 Portable Executable
35    File Format", MSJ 1994, Volume 9.
36
37    The *sole* difference between the pe format and the pei format is that the
38    latter has an MSDOS 2.0 .exe header on the front that prints the message
39    "This app must be run under Windows." (or some such).
40    (FIXME: Whether that statement is *really* true or not is unknown.
41    Are there more subtle differences between pe and pei formats?
42    For now assume there aren't.  If you find one, then for God sakes
43    document it here!)
44
45    The Microsoft docs use the word "image" instead of "executable" because
46    the former can also refer to a DLL (shared library).  Confusion can arise
47    because the `i' in `pei' also refers to "image".  The `pe' format can
48    also create images (i.e. executables), it's just that to run on a win32
49    system you need to use the pei format.
50
51    FIXME: Please add more docs here so the next poor fool that has to hack
52    on this code has a chance of getting something accomplished without
53    wasting too much time.  */
54
55 /* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64
56    depending on whether we're compiling for straight PE or PE+.  */
57 #define COFF_WITH_XX
58
59 #include "sysdep.h"
60 #include "bfd.h"
61 #include "libbfd.h"
62 #include "coff/internal.h"
63
64 /* NOTE: it's strange to be including an architecture specific header
65    in what's supposed to be general (to PE/PEI) code.  However, that's
66    where the definitions are, and they don't vary per architecture
67    within PE/PEI, so we get them from there.  FIXME: The lack of
68    variance is an assumption which may prove to be incorrect if new
69    PE/PEI targets are created.  */
70 #if defined COFF_WITH_pex64
71 # include "coff/x86_64.h"
72 #elif defined COFF_WITH_pep
73 # include "coff/ia64.h"
74 #else
75 # include "coff/i386.h"
76 #endif
77
78 #include "coff/pe.h"
79 #include "libcoff.h"
80 #include "libpei.h"
81
82 #if defined COFF_WITH_pep || defined COFF_WITH_pex64
83 # undef AOUTSZ
84 # define AOUTSZ         PEPAOUTSZ
85 # define PEAOUTHDR      PEPAOUTHDR
86 #endif
87
88 /* FIXME: This file has various tests of POWERPC_LE_PE.  Those tests
89    worked when the code was in peicode.h, but no longer work now that
90    the code is in peigen.c.  PowerPC NT is said to be dead.  If
91    anybody wants to revive the code, you will have to figure out how
92    to handle those issues.  */
93 \f
94 void
95 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
96 {
97   SYMENT *ext = (SYMENT *) ext1;
98   struct internal_syment *in = (struct internal_syment *) in1;
99
100   if (ext->e.e_name[0] == 0)
101     {
102       in->_n._n_n._n_zeroes = 0;
103       in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
104     }
105   else
106     memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
107
108   in->n_value = H_GET_32 (abfd, ext->e_value);
109   in->n_scnum = H_GET_16 (abfd, ext->e_scnum);
110
111   if (sizeof (ext->e_type) == 2)
112     in->n_type = H_GET_16 (abfd, ext->e_type);
113   else
114     in->n_type = H_GET_32 (abfd, ext->e_type);
115
116   in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
117   in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
118
119 #ifndef STRICT_PE_FORMAT
120   /* This is for Gnu-created DLLs.  */
121
122   /* The section symbols for the .idata$ sections have class 0x68
123      (C_SECTION), which MS documentation indicates is a section
124      symbol.  Unfortunately, the value field in the symbol is simply a
125      copy of the .idata section's flags rather than something useful.
126      When these symbols are encountered, change the value to 0 so that
127      they will be handled somewhat correctly in the bfd code.  */
128   if (in->n_sclass == C_SECTION)
129     {
130       in->n_value = 0x0;
131
132       /* Create synthetic empty sections as needed.  DJ */
133       if (in->n_scnum == 0)
134         {
135           asection *sec;
136
137           for (sec = abfd->sections; sec; sec = sec->next)
138             {
139               if (strcmp (sec->name, in->n_name) == 0)
140                 {
141                   in->n_scnum = sec->target_index;
142                   break;
143                 }
144             }
145         }
146
147       if (in->n_scnum == 0)
148         {
149           int unused_section_number = 0;
150           asection *sec;
151           char *name;
152           flagword flags;
153
154           for (sec = abfd->sections; sec; sec = sec->next)
155             if (unused_section_number <= sec->target_index)
156               unused_section_number = sec->target_index + 1;
157
158           name = bfd_alloc (abfd, (bfd_size_type) strlen (in->n_name) + 10);
159           if (name == NULL)
160             return;
161           strcpy (name, in->n_name);
162           flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
163           sec = bfd_make_section_anyway_with_flags (abfd, name, flags);
164
165           sec->vma = 0;
166           sec->lma = 0;
167           sec->size = 0;
168           sec->filepos = 0;
169           sec->rel_filepos = 0;
170           sec->reloc_count = 0;
171           sec->line_filepos = 0;
172           sec->lineno_count = 0;
173           sec->userdata = NULL;
174           sec->next = NULL;
175           sec->alignment_power = 2;
176
177           sec->target_index = unused_section_number;
178
179           in->n_scnum = unused_section_number;
180         }
181       in->n_sclass = C_STAT;
182     }
183 #endif
184
185 #ifdef coff_swap_sym_in_hook
186   /* This won't work in peigen.c, but since it's for PPC PE, it's not
187      worth fixing.  */
188   coff_swap_sym_in_hook (abfd, ext1, in1);
189 #endif
190 }
191
192 unsigned int
193 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
194 {
195   struct internal_syment *in = (struct internal_syment *) inp;
196   SYMENT *ext = (SYMENT *) extp;
197
198   if (in->_n._n_name[0] == 0)
199     {
200       H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
201       H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
202     }
203   else
204     memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
205
206   H_PUT_32 (abfd, in->n_value, ext->e_value);
207   H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
208
209   if (sizeof (ext->e_type) == 2)
210     H_PUT_16 (abfd, in->n_type, ext->e_type);
211   else
212     H_PUT_32 (abfd, in->n_type, ext->e_type);
213
214   H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
215   H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
216
217   return SYMESZ;
218 }
219
220 void
221 _bfd_XXi_swap_aux_in (bfd *     abfd,
222                       void *    ext1,
223                       int       type,
224                       int       class,
225                       int       indx ATTRIBUTE_UNUSED,
226                       int       numaux ATTRIBUTE_UNUSED,
227                       void *    in1)
228 {
229   AUXENT *ext = (AUXENT *) ext1;
230   union internal_auxent *in = (union internal_auxent *) in1;
231
232   switch (class)
233     {
234     case C_FILE:
235       if (ext->x_file.x_fname[0] == 0)
236         {
237           in->x_file.x_n.x_zeroes = 0;
238           in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
239         }
240       else
241         memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
242       return;
243
244     case C_STAT:
245     case C_LEAFSTAT:
246     case C_HIDDEN:
247       if (type == T_NULL)
248         {
249           in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
250           in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
251           in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
252           in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
253           in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
254           in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
255           return;
256         }
257       break;
258     }
259
260   in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
261   in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
262
263   if (class == C_BLOCK || class == C_FCN || ISFCN (type) || ISTAG (class))
264     {
265       in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
266       in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
267     }
268   else
269     {
270       in->x_sym.x_fcnary.x_ary.x_dimen[0] =
271         H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
272       in->x_sym.x_fcnary.x_ary.x_dimen[1] =
273         H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
274       in->x_sym.x_fcnary.x_ary.x_dimen[2] =
275         H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
276       in->x_sym.x_fcnary.x_ary.x_dimen[3] =
277         H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
278     }
279
280   if (ISFCN (type))
281     {
282       in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
283     }
284   else
285     {
286       in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
287       in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
288     }
289 }
290
291 unsigned int
292 _bfd_XXi_swap_aux_out (bfd *  abfd,
293                        void * inp,
294                        int    type,
295                        int    class,
296                        int    indx ATTRIBUTE_UNUSED,
297                        int    numaux ATTRIBUTE_UNUSED,
298                        void * extp)
299 {
300   union internal_auxent *in = (union internal_auxent *) inp;
301   AUXENT *ext = (AUXENT *) extp;
302
303   memset (ext, 0, AUXESZ);
304
305   switch (class)
306     {
307     case C_FILE:
308       if (in->x_file.x_fname[0] == 0)
309         {
310           H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
311           H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
312         }
313       else
314         memcpy (ext->x_file.x_fname, in->x_file.x_fname, FILNMLEN);
315
316       return AUXESZ;
317
318     case C_STAT:
319     case C_LEAFSTAT:
320     case C_HIDDEN:
321       if (type == T_NULL)
322         {
323           PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
324           PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
325           PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
326           H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
327           H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
328           H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
329           return AUXESZ;
330         }
331       break;
332     }
333
334   H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
335   H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
336
337   if (class == C_BLOCK || class == C_FCN || ISFCN (type) || ISTAG (class))
338     {
339       PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr,  ext);
340       PUT_FCN_ENDNDX  (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
341     }
342   else
343     {
344       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
345                 ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
346       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
347                 ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
348       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
349                 ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
350       H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
351                 ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
352     }
353
354   if (ISFCN (type))
355     H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
356   else
357     {
358       PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
359       PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
360     }
361
362   return AUXESZ;
363 }
364
365 void
366 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
367 {
368   LINENO *ext = (LINENO *) ext1;
369   struct internal_lineno *in = (struct internal_lineno *) in1;
370
371   in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
372   in->l_lnno = GET_LINENO_LNNO (abfd, ext);
373 }
374
375 unsigned int
376 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
377 {
378   struct internal_lineno *in = (struct internal_lineno *) inp;
379   struct external_lineno *ext = (struct external_lineno *) outp;
380   H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
381
382   PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
383   return LINESZ;
384 }
385
386 void
387 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
388                           void * aouthdr_ext1,
389                           void * aouthdr_int1)
390 {
391   PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
392   AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
393   struct internal_aouthdr *aouthdr_int
394     = (struct internal_aouthdr *) aouthdr_int1;
395   struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
396
397   aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
398   aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
399   aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
400   aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
401   aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
402   aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
403   aouthdr_int->text_start =
404     GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
405 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
406   /* PE32+ does not have data_start member!  */
407   aouthdr_int->data_start =
408     GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
409   a->BaseOfData = aouthdr_int->data_start;
410 #endif
411
412   a->Magic = aouthdr_int->magic;
413   a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
414   a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
415   a->SizeOfCode = aouthdr_int->tsize ;
416   a->SizeOfInitializedData = aouthdr_int->dsize ;
417   a->SizeOfUninitializedData = aouthdr_int->bsize ;
418   a->AddressOfEntryPoint = aouthdr_int->entry;
419   a->BaseOfCode = aouthdr_int->text_start;
420   a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
421   a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
422   a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
423   a->MajorOperatingSystemVersion =
424     H_GET_16 (abfd, src->MajorOperatingSystemVersion);
425   a->MinorOperatingSystemVersion =
426     H_GET_16 (abfd, src->MinorOperatingSystemVersion);
427   a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
428   a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
429   a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
430   a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
431   a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
432   a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
433   a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
434   a->CheckSum = H_GET_32 (abfd, src->CheckSum);
435   a->Subsystem = H_GET_16 (abfd, src->Subsystem);
436   a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
437   a->SizeOfStackReserve =
438     GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
439   a->SizeOfStackCommit =
440     GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
441   a->SizeOfHeapReserve =
442     GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
443   a->SizeOfHeapCommit =
444     GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
445   a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
446   a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
447
448   {
449     int idx;
450
451     /* PR 17512: Corrupt PE binaries can cause seg-faults.  */
452     if (a->NumberOfRvaAndSizes > 16)
453       {
454        (*_bfd_error_handler)
455           (_("%B: aout header specifies an invalid number of data-directory entries: %d"),
456            abfd, a->NumberOfRvaAndSizes);
457         /* Paranoia: If the number is corrupt, then assume that the
458            actual entries themselves might be corrupt as well.  */
459         a->NumberOfRvaAndSizes = 0;
460       }
461
462     for (idx = 0; idx < 16; idx++)
463       {
464         /* If data directory is empty, rva also should be 0.  */
465         int size =
466           H_GET_32 (abfd, src->DataDirectory[idx][1]);
467
468         a->DataDirectory[idx].Size = size;
469
470         if (size)
471           a->DataDirectory[idx].VirtualAddress =
472             H_GET_32 (abfd, src->DataDirectory[idx][0]);
473         else
474           a->DataDirectory[idx].VirtualAddress = 0;
475       }
476   }
477
478   if (aouthdr_int->entry)
479     {
480       aouthdr_int->entry += a->ImageBase;
481 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
482       aouthdr_int->entry &= 0xffffffff;
483 #endif
484     }
485
486   if (aouthdr_int->tsize)
487     {
488       aouthdr_int->text_start += a->ImageBase;
489 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
490       aouthdr_int->text_start &= 0xffffffff;
491 #endif
492     }
493
494 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
495   /* PE32+ does not have data_start member!  */
496   if (aouthdr_int->dsize)
497     {
498       aouthdr_int->data_start += a->ImageBase;
499       aouthdr_int->data_start &= 0xffffffff;
500     }
501 #endif
502
503 #ifdef POWERPC_LE_PE
504   /* These three fields are normally set up by ppc_relocate_section.
505      In the case of reading a file in, we can pick them up from the
506      DataDirectory.  */
507   first_thunk_address = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress;
508   thunk_size = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size;
509   import_table_size = a->DataDirectory[PE_IMPORT_TABLE].Size;
510 #endif
511 }
512
513 /* A support function for below.  */
514
515 static void
516 add_data_entry (bfd * abfd,
517                 struct internal_extra_pe_aouthdr *aout,
518                 int idx,
519                 char *name,
520                 bfd_vma base)
521 {
522   asection *sec = bfd_get_section_by_name (abfd, name);
523
524   /* Add import directory information if it exists.  */
525   if ((sec != NULL)
526       && (coff_section_data (abfd, sec) != NULL)
527       && (pei_section_data (abfd, sec) != NULL))
528     {
529       /* If data directory is empty, rva also should be 0.  */
530       int size = pei_section_data (abfd, sec)->virt_size;
531       aout->DataDirectory[idx].Size = size;
532
533       if (size)
534         {
535           aout->DataDirectory[idx].VirtualAddress =
536             (sec->vma - base) & 0xffffffff;
537           sec->flags |= SEC_DATA;
538         }
539     }
540 }
541
542 unsigned int
543 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
544 {
545   struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
546   pe_data_type *pe = pe_data (abfd);
547   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
548   PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
549   bfd_vma sa, fa, ib;
550   IMAGE_DATA_DIRECTORY idata2, idata5, tls;
551   
552   if (pe->force_minimum_alignment)
553     {
554       if (!extra->FileAlignment)
555         extra->FileAlignment = PE_DEF_FILE_ALIGNMENT;
556       if (!extra->SectionAlignment)
557         extra->SectionAlignment = PE_DEF_SECTION_ALIGNMENT;
558     }
559
560   if (extra->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
561     extra->Subsystem = pe->target_subsystem;
562
563   sa = extra->SectionAlignment;
564   fa = extra->FileAlignment;
565   ib = extra->ImageBase;
566
567   idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
568   idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
569   tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
570   
571   if (aouthdr_in->tsize)
572     {
573       aouthdr_in->text_start -= ib;
574 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
575       aouthdr_in->text_start &= 0xffffffff;
576 #endif
577     }
578
579   if (aouthdr_in->dsize)
580     {
581       aouthdr_in->data_start -= ib;
582 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
583       aouthdr_in->data_start &= 0xffffffff;
584 #endif
585     }
586
587   if (aouthdr_in->entry)
588     {
589       aouthdr_in->entry -= ib;
590 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
591       aouthdr_in->entry &= 0xffffffff;
592 #endif
593     }
594
595 #define FA(x) (((x) + fa -1 ) & (- fa))
596 #define SA(x) (((x) + sa -1 ) & (- sa))
597
598   /* We like to have the sizes aligned.  */
599   aouthdr_in->bsize = FA (aouthdr_in->bsize);
600
601   extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
602
603   /* First null out all data directory entries.  */
604   memset (extra->DataDirectory, 0, sizeof (extra->DataDirectory));
605
606   add_data_entry (abfd, extra, 0, ".edata", ib);
607   add_data_entry (abfd, extra, 2, ".rsrc", ib);
608   add_data_entry (abfd, extra, 3, ".pdata", ib);
609
610   /* In theory we do not need to call add_data_entry for .idata$2 or
611      .idata$5.  It will be done in bfd_coff_final_link where all the
612      required information is available.  If however, we are not going
613      to perform a final link, eg because we have been invoked by objcopy
614      or strip, then we need to make sure that these Data Directory
615      entries are initialised properly.
616
617      So - we copy the input values into the output values, and then, if
618      a final link is going to be performed, it can overwrite them.  */
619   extra->DataDirectory[PE_IMPORT_TABLE]  = idata2;
620   extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
621   extra->DataDirectory[PE_TLS_TABLE] = tls;
622
623   if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
624     /* Until other .idata fixes are made (pending patch), the entry for
625        .idata is needed for backwards compatibility.  FIXME.  */
626     add_data_entry (abfd, extra, 1, ".idata", ib);
627     
628   /* For some reason, the virtual size (which is what's set by
629      add_data_entry) for .reloc is not the same as the size recorded
630      in this slot by MSVC; it doesn't seem to cause problems (so far),
631      but since it's the best we've got, use it.  It does do the right
632      thing for .pdata.  */
633   if (pe->has_reloc_section)
634     add_data_entry (abfd, extra, 5, ".reloc", ib);
635
636   {
637     asection *sec;
638     bfd_vma hsize = 0;
639     bfd_vma dsize = 0;
640     bfd_vma isize = 0;
641     bfd_vma tsize = 0;
642
643     for (sec = abfd->sections; sec; sec = sec->next)
644       {
645         int rounded = FA (sec->size);
646
647         /* The first non-zero section filepos is the header size.
648            Sections without contents will have a filepos of 0.  */
649         if (hsize == 0)
650           hsize = sec->filepos;
651         if (sec->flags & SEC_DATA)
652           dsize += rounded;
653         if (sec->flags & SEC_CODE)
654           tsize += rounded;
655         /* The image size is the total VIRTUAL size (which is what is
656            in the virt_size field).  Files have been seen (from MSVC
657            5.0 link.exe) where the file size of the .data segment is
658            quite small compared to the virtual size.  Without this
659            fix, strip munges the file.
660
661            FIXME: We need to handle holes between sections, which may
662            happpen when we covert from another format.  We just use
663            the virtual address and virtual size of the last section
664            for the image size.  */
665         if (coff_section_data (abfd, sec) != NULL
666             && pei_section_data (abfd, sec) != NULL)
667           isize = (sec->vma - extra->ImageBase
668                    + SA (FA (pei_section_data (abfd, sec)->virt_size)));
669       }
670
671     aouthdr_in->dsize = dsize;
672     aouthdr_in->tsize = tsize;
673     extra->SizeOfHeaders = hsize;
674     extra->SizeOfImage = isize;
675   }
676
677   H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
678
679 #define LINKER_VERSION 256 /* That is, 2.56 */
680
681   /* This piece of magic sets the "linker version" field to
682      LINKER_VERSION.  */
683   H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
684             aouthdr_out->standard.vstamp);
685
686   PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
687   PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
688   PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
689   PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
690   PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
691                           aouthdr_out->standard.text_start);
692
693 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
694   /* PE32+ does not have data_start member!  */
695   PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
696                           aouthdr_out->standard.data_start);
697 #endif
698
699   PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
700   H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
701   H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
702   H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
703             aouthdr_out->MajorOperatingSystemVersion);
704   H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
705             aouthdr_out->MinorOperatingSystemVersion);
706   H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
707   H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
708   H_PUT_16 (abfd, extra->MajorSubsystemVersion,
709             aouthdr_out->MajorSubsystemVersion);
710   H_PUT_16 (abfd, extra->MinorSubsystemVersion,
711             aouthdr_out->MinorSubsystemVersion);
712   H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
713   H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
714   H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
715   H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
716   H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
717   H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
718   PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
719                                     aouthdr_out->SizeOfStackReserve);
720   PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
721                                    aouthdr_out->SizeOfStackCommit);
722   PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
723                                    aouthdr_out->SizeOfHeapReserve);
724   PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
725                                   aouthdr_out->SizeOfHeapCommit);
726   H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
727   H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
728             aouthdr_out->NumberOfRvaAndSizes);
729   {
730     int idx;
731
732     for (idx = 0; idx < 16; idx++)
733       {
734         H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
735                   aouthdr_out->DataDirectory[idx][0]);
736         H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
737                   aouthdr_out->DataDirectory[idx][1]);
738       }
739   }
740
741   return AOUTSZ;
742 }
743
744 unsigned int
745 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
746 {
747   int idx;
748   struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
749   struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
750
751   if (pe_data (abfd)->has_reloc_section)
752     filehdr_in->f_flags &= ~F_RELFLG;
753
754   if (pe_data (abfd)->dll)
755     filehdr_in->f_flags |= F_DLL;
756
757   filehdr_in->pe.e_magic    = DOSMAGIC;
758   filehdr_in->pe.e_cblp     = 0x90;
759   filehdr_in->pe.e_cp       = 0x3;
760   filehdr_in->pe.e_crlc     = 0x0;
761   filehdr_in->pe.e_cparhdr  = 0x4;
762   filehdr_in->pe.e_minalloc = 0x0;
763   filehdr_in->pe.e_maxalloc = 0xffff;
764   filehdr_in->pe.e_ss       = 0x0;
765   filehdr_in->pe.e_sp       = 0xb8;
766   filehdr_in->pe.e_csum     = 0x0;
767   filehdr_in->pe.e_ip       = 0x0;
768   filehdr_in->pe.e_cs       = 0x0;
769   filehdr_in->pe.e_lfarlc   = 0x40;
770   filehdr_in->pe.e_ovno     = 0x0;
771
772   for (idx = 0; idx < 4; idx++)
773     filehdr_in->pe.e_res[idx] = 0x0;
774
775   filehdr_in->pe.e_oemid   = 0x0;
776   filehdr_in->pe.e_oeminfo = 0x0;
777
778   for (idx = 0; idx < 10; idx++)
779     filehdr_in->pe.e_res2[idx] = 0x0;
780
781   filehdr_in->pe.e_lfanew = 0x80;
782
783   /* This next collection of data are mostly just characters.  It
784      appears to be constant within the headers put on NT exes.  */
785   filehdr_in->pe.dos_message[0]  = 0x0eba1f0e;
786   filehdr_in->pe.dos_message[1]  = 0xcd09b400;
787   filehdr_in->pe.dos_message[2]  = 0x4c01b821;
788   filehdr_in->pe.dos_message[3]  = 0x685421cd;
789   filehdr_in->pe.dos_message[4]  = 0x70207369;
790   filehdr_in->pe.dos_message[5]  = 0x72676f72;
791   filehdr_in->pe.dos_message[6]  = 0x63206d61;
792   filehdr_in->pe.dos_message[7]  = 0x6f6e6e61;
793   filehdr_in->pe.dos_message[8]  = 0x65622074;
794   filehdr_in->pe.dos_message[9]  = 0x6e757220;
795   filehdr_in->pe.dos_message[10] = 0x206e6920;
796   filehdr_in->pe.dos_message[11] = 0x20534f44;
797   filehdr_in->pe.dos_message[12] = 0x65646f6d;
798   filehdr_in->pe.dos_message[13] = 0x0a0d0d2e;
799   filehdr_in->pe.dos_message[14] = 0x24;
800   filehdr_in->pe.dos_message[15] = 0x0;
801   filehdr_in->pe.nt_signature = NT_SIGNATURE;
802
803   H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
804   H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
805
806   H_PUT_32 (abfd, time (0), filehdr_out->f_timdat);
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_pe_executable_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_pe_executable_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 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1035 {
1036   N_("Export Directory [.edata (or where ever we found it)]"),
1037   N_("Import Directory [parts of .idata]"),
1038   N_("Resource Directory [.rsrc]"),
1039   N_("Exception Directory [.pdata]"),
1040   N_("Security Directory"),
1041   N_("Base Relocation Directory [.reloc]"),
1042   N_("Debug Directory"),
1043   N_("Description Directory"),
1044   N_("Special Directory"),
1045   N_("Thread Storage Directory [.tls]"),
1046   N_("Load Configuration Directory"),
1047   N_("Bound Import Directory"),
1048   N_("Import Address Table Directory"),
1049   N_("Delay Import Directory"),
1050   N_("CLR Runtime Header"),
1051   N_("Reserved")
1052 };
1053
1054 #ifdef POWERPC_LE_PE
1055 /* The code for the PPC really falls in the "architecture dependent"
1056    category.  However, it's not clear that anyone will ever care, so
1057    we're ignoring the issue for now; if/when PPC matters, some of this
1058    may need to go into peicode.h, or arguments passed to enable the
1059    PPC- specific code.  */
1060 #endif
1061
1062 static bfd_boolean
1063 pe_print_idata (bfd * abfd, void * vfile)
1064 {
1065   FILE *file = (FILE *) vfile;
1066   bfd_byte *data;
1067   asection *section;
1068   bfd_signed_vma adj;
1069
1070 #ifdef POWERPC_LE_PE
1071   asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
1072 #endif
1073
1074   bfd_size_type datasize = 0;
1075   bfd_size_type dataoff;
1076   bfd_size_type i;
1077   int onaline = 20;
1078
1079   pe_data_type *pe = pe_data (abfd);
1080   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1081
1082   bfd_vma addr;
1083
1084   addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1085
1086   if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1087     {
1088       /* Maybe the extra header isn't there.  Look for the section.  */
1089       section = bfd_get_section_by_name (abfd, ".idata");
1090       if (section == NULL)
1091         return TRUE;
1092
1093       addr = section->vma;
1094       datasize = section->size;
1095       if (datasize == 0)
1096         return TRUE;
1097     }
1098   else
1099     {
1100       addr += extra->ImageBase;
1101       for (section = abfd->sections; section != NULL; section = section->next)
1102         {
1103           datasize = section->size;
1104           if (addr >= section->vma && addr < section->vma + datasize)
1105             break;
1106         }
1107
1108       if (section == NULL)
1109         {
1110           fprintf (file,
1111                    _("\nThere is an import table, but the section containing it could not be found\n"));
1112           return TRUE;
1113         }
1114     }
1115
1116   fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1117            section->name, (unsigned long) addr);
1118
1119   dataoff = addr - section->vma;
1120   datasize -= dataoff;
1121
1122 #ifdef POWERPC_LE_PE
1123   if (rel_section != 0 && rel_section->size != 0)
1124     {
1125       /* The toc address can be found by taking the starting address,
1126          which on the PPC locates a function descriptor. The
1127          descriptor consists of the function code starting address
1128          followed by the address of the toc. The starting address we
1129          get from the bfd, and the descriptor is supposed to be in the
1130          .reldata section.  */
1131
1132       bfd_vma loadable_toc_address;
1133       bfd_vma toc_address;
1134       bfd_vma start_address;
1135       bfd_byte *data;
1136       bfd_vma offset;
1137
1138       if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
1139         {
1140           if (data != NULL)
1141             free (data);
1142           return FALSE;
1143         }
1144
1145       offset = abfd->start_address - rel_section->vma;
1146
1147       if (offset >= rel_section->size || offset + 8 > rel_section->size)
1148         {
1149           if (data != NULL)
1150             free (data);
1151           return FALSE;
1152         }
1153
1154       start_address = bfd_get_32 (abfd, data + offset);
1155       loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
1156       toc_address = loadable_toc_address - 32768;
1157
1158       fprintf (file,
1159                _("\nFunction descriptor located at the start address: %04lx\n"),
1160                (unsigned long int) (abfd->start_address));
1161       fprintf (file,
1162                _("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
1163                start_address, loadable_toc_address, toc_address);
1164       if (data != NULL)
1165         free (data);
1166     }
1167   else
1168     {
1169       fprintf (file,
1170                _("\nNo reldata section! Function descriptor not decoded.\n"));
1171     }
1172 #endif
1173
1174   fprintf (file,
1175            _("\nThe Import Tables (interpreted %s section contents)\n"),
1176            section->name);
1177   fprintf (file,
1178            _("\
1179  vma:            Hint    Time      Forward  DLL       First\n\
1180                  Table   Stamp     Chain    Name      Thunk\n"));
1181
1182   /* Read the whole section.  Some of the fields might be before dataoff.  */
1183   if (!bfd_malloc_and_get_section (abfd, section, &data))
1184     {
1185       if (data != NULL)
1186         free (data);
1187       return FALSE;
1188     }
1189
1190   adj = section->vma - extra->ImageBase;
1191
1192   /* Print all image import descriptors.  */
1193   for (i = 0; i < datasize; i += onaline)
1194     {
1195       bfd_vma hint_addr;
1196       bfd_vma time_stamp;
1197       bfd_vma forward_chain;
1198       bfd_vma dll_name;
1199       bfd_vma first_thunk;
1200       int idx = 0;
1201       bfd_size_type j;
1202       char *dll;
1203
1204       /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress).  */
1205       fprintf (file, " %08lx\t", (unsigned long) (i + adj + dataoff));
1206       hint_addr = bfd_get_32 (abfd, data + i + dataoff);
1207       time_stamp = bfd_get_32 (abfd, data + i + 4 + dataoff);
1208       forward_chain = bfd_get_32 (abfd, data + i + 8 + dataoff);
1209       dll_name = bfd_get_32 (abfd, data + i + 12 + dataoff);
1210       first_thunk = bfd_get_32 (abfd, data + i + 16 + dataoff);
1211
1212       fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1213                (unsigned long) hint_addr,
1214                (unsigned long) time_stamp,
1215                (unsigned long) forward_chain,
1216                (unsigned long) dll_name,
1217                (unsigned long) first_thunk);
1218
1219       if (hint_addr == 0 && first_thunk == 0)
1220         break;
1221
1222       if (dll_name - adj >= section->size)
1223         break;
1224
1225       dll = (char *) data + dll_name - adj;
1226       fprintf (file, _("\n\tDLL Name: %s\n"), dll);
1227
1228       if (hint_addr != 0)
1229         {
1230           bfd_byte *ft_data;
1231           asection *ft_section;
1232           bfd_vma ft_addr;
1233           bfd_size_type ft_datasize;
1234           int ft_idx;
1235           int ft_allocated = 0;
1236
1237           fprintf (file, _("\tvma:  Hint/Ord Member-Name Bound-To\n"));
1238
1239           idx = hint_addr - adj;
1240           
1241           ft_addr = first_thunk + extra->ImageBase;
1242           ft_data = data;
1243           ft_idx = first_thunk - adj;
1244           ft_allocated = 0; 
1245
1246           if (first_thunk != hint_addr)
1247             {
1248               /* Find the section which contains the first thunk.  */
1249               for (ft_section = abfd->sections;
1250                    ft_section != NULL;
1251                    ft_section = ft_section->next)
1252                 {
1253                   ft_datasize = ft_section->size;
1254                   if (ft_addr >= ft_section->vma
1255                       && ft_addr < ft_section->vma + ft_datasize)
1256                     break;
1257                 }
1258
1259               if (ft_section == NULL)
1260                 {
1261                   fprintf (file,
1262                        _("\nThere is a first thunk, but the section containing it could not be found\n"));
1263                   continue;
1264                 }
1265
1266               /* Now check to see if this section is the same as our current
1267                  section.  If it is not then we will have to load its data in.  */
1268               if (ft_section == section)
1269                 {
1270                   ft_data = data;
1271                   ft_idx = first_thunk - adj;
1272                 }
1273               else
1274                 {
1275                   ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1276                   ft_data = bfd_malloc (datasize);
1277                   if (ft_data == NULL)
1278                     continue;
1279
1280                   /* Read datasize bfd_bytes starting at offset ft_idx.  */
1281                   if (! bfd_get_section_contents
1282                       (abfd, ft_section, ft_data, (bfd_vma) ft_idx, datasize))
1283                     {
1284                       free (ft_data);
1285                       continue;
1286                     }
1287
1288                   ft_idx = 0;
1289                   ft_allocated = 1;
1290                 }
1291             }
1292
1293           /* Print HintName vector entries.  */
1294 #ifdef COFF_WITH_pex64
1295           for (j = 0; j < datasize; j += 8)
1296             {
1297               unsigned long member = bfd_get_32 (abfd, data + idx + j);
1298               unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1299
1300               if (!member && !member_high)
1301                 break;
1302
1303               if (member_high & 0x80000000)
1304                 fprintf (file, "\t%lx%08lx\t %4lx%08lx  <none>",
1305                          member_high,member, member_high & 0x7fffffff, member);
1306               else
1307                 {
1308                   int ordinal;
1309                   char *member_name;
1310
1311                   ordinal = bfd_get_16 (abfd, data + member - adj);
1312                   member_name = (char *) data + member - adj + 2;
1313                   fprintf (file, "\t%04lx\t %4d  %s",member, ordinal, member_name);
1314                 }
1315
1316               /* If the time stamp is not zero, the import address
1317                  table holds actual addresses.  */
1318               if (time_stamp != 0
1319                   && first_thunk != 0
1320                   && first_thunk != hint_addr)
1321                 fprintf (file, "\t%04lx",
1322                          (long) bfd_get_32 (abfd, ft_data + ft_idx + j));
1323               fprintf (file, "\n");
1324             }
1325 #else
1326           for (j = 0; j < datasize; j += 4)
1327             {
1328               unsigned long member = bfd_get_32 (abfd, data + idx + j);
1329
1330               /* Print single IMAGE_IMPORT_BY_NAME vector.  */ 
1331               if (member == 0)
1332                 break;
1333
1334               if (member & 0x80000000)
1335                 fprintf (file, "\t%04lx\t %4lu  <none>",
1336                          member, member & 0x7fffffff);
1337               else
1338                 {
1339                   int ordinal;
1340                   char *member_name;
1341
1342                   ordinal = bfd_get_16 (abfd, data + member - adj);
1343                   member_name = (char *) data + member - adj + 2;
1344                   fprintf (file, "\t%04lx\t %4d  %s",
1345                            member, ordinal, member_name);
1346                 }
1347
1348               /* If the time stamp is not zero, the import address
1349                  table holds actual addresses.  */
1350               if (time_stamp != 0
1351                   && first_thunk != 0
1352                   && first_thunk != hint_addr)
1353                 fprintf (file, "\t%04lx",
1354                          (long) bfd_get_32 (abfd, ft_data + ft_idx + j));
1355
1356               fprintf (file, "\n");
1357             }
1358 #endif
1359           if (ft_allocated)
1360             free (ft_data);
1361         }
1362
1363       fprintf (file, "\n");
1364     }
1365
1366   free (data);
1367
1368   return TRUE;
1369 }
1370
1371 static bfd_boolean
1372 pe_print_edata (bfd * abfd, void * vfile)
1373 {
1374   FILE *file = (FILE *) vfile;
1375   bfd_byte *data;
1376   asection *section;
1377   bfd_size_type datasize = 0;
1378   bfd_size_type dataoff;
1379   bfd_size_type i;
1380   bfd_signed_vma adj;
1381   struct EDT_type
1382   {
1383     long export_flags;          /* Reserved - should be zero.  */
1384     long time_stamp;
1385     short major_ver;
1386     short minor_ver;
1387     bfd_vma name;               /* RVA - relative to image base.  */
1388     long base;                  /* Ordinal base.  */
1389     unsigned long num_functions;/* Number in the export address table.  */
1390     unsigned long num_names;    /* Number in the name pointer table.  */
1391     bfd_vma eat_addr;           /* RVA to the export address table.  */
1392     bfd_vma npt_addr;           /* RVA to the Export Name Pointer Table.  */
1393     bfd_vma ot_addr;            /* RVA to the Ordinal Table.  */
1394   } edt;
1395
1396   pe_data_type *pe = pe_data (abfd);
1397   struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1398
1399   bfd_vma addr;
1400
1401   addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1402
1403   if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1404     {
1405       /* Maybe the extra header isn't there.  Look for the section.  */
1406       section = bfd_get_section_by_name (abfd, ".edata");
1407       if (section == NULL)
1408         return TRUE;
1409
1410       addr = section->vma;
1411       dataoff = 0;
1412       datasize = section->size;
1413       if (datasize == 0)
1414         return TRUE;
1415     }
1416   else
1417     {
1418       addr += extra->ImageBase;
1419
1420       for (section = abfd->sections; section != NULL; section = section->next)
1421         if (addr >= section->vma && addr < section->vma + section->size)
1422           break;
1423
1424       if (section == NULL)
1425         {
1426           fprintf (file,
1427                    _("\nThere is an export table, but the section containing it could not be found\n"));
1428           return TRUE;
1429         }
1430
1431       dataoff = addr - section->vma;
1432       datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1433       if (datasize > section->size - dataoff)
1434         {
1435           fprintf (file,
1436                    _("\nThere is an export table in %s, but it does not fit into that section\n"),
1437                    section->name);
1438           return TRUE;
1439         }
1440     }
1441
1442   /* PR 17512: Handle corrupt PE binaries.  */
1443   if (datasize < 36)
1444     {
1445       fprintf (file,
1446                _("\nThere is an export table in %s, but it is too small (%d)\n"),
1447                section->name, (int) datasize);
1448       return TRUE;
1449     }
1450
1451   fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1452            section->name, (unsigned long) addr);
1453
1454   data = bfd_malloc (datasize);
1455   if (data == NULL)
1456     return FALSE;
1457
1458   if (! bfd_get_section_contents (abfd, section, data,
1459                                   (file_ptr) dataoff, datasize))
1460     return FALSE;
1461
1462   /* Go get Export Directory Table.  */
1463   edt.export_flags   = bfd_get_32 (abfd, data +  0);
1464   edt.time_stamp     = bfd_get_32 (abfd, data +  4);
1465   edt.major_ver      = bfd_get_16 (abfd, data +  8);
1466   edt.minor_ver      = bfd_get_16 (abfd, data + 10);
1467   edt.name           = bfd_get_32 (abfd, data + 12);
1468   edt.base           = bfd_get_32 (abfd, data + 16);
1469   edt.num_functions  = bfd_get_32 (abfd, data + 20);
1470   edt.num_names      = bfd_get_32 (abfd, data + 24);
1471   edt.eat_addr       = bfd_get_32 (abfd, data + 28);
1472   edt.npt_addr       = bfd_get_32 (abfd, data + 32);
1473   edt.ot_addr        = bfd_get_32 (abfd, data + 36);
1474
1475   adj = section->vma - extra->ImageBase + dataoff;
1476
1477   /* Dump the EDT first.  */
1478   fprintf (file,
1479            _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1480            section->name);
1481
1482   fprintf (file,
1483            _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1484
1485   fprintf (file,
1486            _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1487
1488   fprintf (file,
1489            _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1490
1491   fprintf (file,
1492            _("Name \t\t\t\t"));
1493   fprintf_vma (file, edt.name);
1494   fprintf (file,
1495            " %s\n", data + edt.name - adj);
1496
1497   fprintf (file,
1498            _("Ordinal Base \t\t\t%ld\n"), edt.base);
1499
1500   fprintf (file,
1501            _("Number in:\n"));
1502
1503   fprintf (file,
1504            _("\tExport Address Table \t\t%08lx\n"),
1505            edt.num_functions);
1506
1507   fprintf (file,
1508            _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1509
1510   fprintf (file,
1511            _("Table Addresses\n"));
1512
1513   fprintf (file,
1514            _("\tExport Address Table \t\t"));
1515   fprintf_vma (file, edt.eat_addr);
1516   fprintf (file, "\n");
1517
1518   fprintf (file,
1519            _("\tName Pointer Table \t\t"));
1520   fprintf_vma (file, edt.npt_addr);
1521   fprintf (file, "\n");
1522
1523   fprintf (file,
1524            _("\tOrdinal Table \t\t\t"));
1525   fprintf_vma (file, edt.ot_addr);
1526   fprintf (file, "\n");
1527
1528   /* The next table to find is the Export Address Table. It's basically
1529      a list of pointers that either locate a function in this dll, or
1530      forward the call to another dll. Something like:
1531       typedef union
1532       {
1533         long export_rva;
1534         long forwarder_rva;
1535       } export_address_table_entry;  */
1536
1537   fprintf (file,
1538           _("\nExport Address Table -- Ordinal Base %ld\n"),
1539           edt.base);
1540
1541   for (i = 0; i < edt.num_functions; ++i)
1542     {
1543       bfd_vma eat_member = bfd_get_32 (abfd,
1544                                        data + edt.eat_addr + (i * 4) - adj);
1545       if (eat_member == 0)
1546         continue;
1547
1548       if (eat_member - adj <= datasize)
1549         {
1550           /* This rva is to a name (forwarding function) in our section.  */
1551           /* Should locate a function descriptor.  */
1552           fprintf (file,
1553                    "\t[%4ld] +base[%4ld] %04lx %s -- %s\n",
1554                    (long) i,
1555                    (long) (i + edt.base),
1556                    (unsigned long) eat_member,
1557                    _("Forwarder RVA"),
1558                    data + eat_member - adj);
1559         }
1560       else
1561         {
1562           /* Should locate a function descriptor in the reldata section.  */
1563           fprintf (file,
1564                    "\t[%4ld] +base[%4ld] %04lx %s\n",
1565                    (long) i,
1566                    (long) (i + edt.base),
1567                    (unsigned long) eat_member,
1568                    _("Export RVA"));
1569         }
1570     }
1571
1572   /* The Export Name Pointer Table is paired with the Export Ordinal Table.  */
1573   /* Dump them in parallel for clarity.  */
1574   fprintf (file,
1575            _("\n[Ordinal/Name Pointer] Table\n"));
1576
1577   for (i = 0; i < edt.num_names; ++i)
1578     {
1579       bfd_vma name_ptr = bfd_get_32 (abfd,
1580                                     data +
1581                                     edt.npt_addr
1582                                     + (i*4) - adj);
1583
1584       char *name = (char *) data + name_ptr - adj;
1585
1586       bfd_vma ord = bfd_get_16 (abfd,
1587                                     data +
1588                                     edt.ot_addr
1589                                     + (i*2) - adj);
1590       fprintf (file,
1591               "\t[%4ld] %s\n", (long) ord, name);
1592     }
1593
1594   free (data);
1595
1596   return TRUE;
1597 }
1598
1599 /* This really is architecture dependent.  On IA-64, a .pdata entry
1600    consists of three dwords containing relative virtual addresses that
1601    specify the start and end address of the code range the entry
1602    covers and the address of the corresponding unwind info data.  */
1603
1604 static bfd_boolean
1605 pe_print_pdata (bfd * abfd, void * vfile)
1606 {
1607 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1608 # define PDATA_ROW_SIZE (3 * 8)
1609 #else
1610 # define PDATA_ROW_SIZE (5 * 4)
1611 #endif
1612   FILE *file = (FILE *) vfile;
1613   bfd_byte *data = 0;
1614   asection *section = bfd_get_section_by_name (abfd, ".pdata");
1615   bfd_size_type datasize = 0;
1616   bfd_size_type i;
1617   bfd_size_type start, stop;
1618   int onaline = PDATA_ROW_SIZE;
1619
1620   if (section == NULL
1621       || coff_section_data (abfd, section) == NULL
1622       || pei_section_data (abfd, section) == NULL)
1623     return TRUE;
1624
1625   stop = pei_section_data (abfd, section)->virt_size;
1626   if ((stop % onaline) != 0)
1627     fprintf (file,
1628              _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
1629              (long) stop, onaline);
1630
1631   fprintf (file,
1632            _("\nThe Function Table (interpreted .pdata section contents)\n"));
1633 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1634   fprintf (file,
1635            _(" vma:\t\t\tBegin Address    End Address      Unwind Info\n"));
1636 #else
1637   fprintf (file, _("\
1638  vma:\t\tBegin    End      EH       EH       PrologEnd  Exception\n\
1639      \t\tAddress  Address  Handler  Data     Address    Mask\n"));
1640 #endif
1641
1642   datasize = section->size;
1643   if (datasize == 0)
1644     return TRUE;
1645
1646   if (! bfd_malloc_and_get_section (abfd, section, &data))
1647     {
1648       if (data != NULL)
1649         free (data);
1650       return FALSE;
1651     }
1652
1653   start = 0;
1654
1655   for (i = start; i < stop; i += onaline)
1656     {
1657       bfd_vma begin_addr;
1658       bfd_vma end_addr;
1659       bfd_vma eh_handler;
1660       bfd_vma eh_data;
1661       bfd_vma prolog_end_addr;
1662       int em_data;
1663
1664       if (i + PDATA_ROW_SIZE > stop)
1665         break;
1666
1667       begin_addr      = GET_PDATA_ENTRY (abfd, data + i     );
1668       end_addr        = GET_PDATA_ENTRY (abfd, data + i +  4);
1669       eh_handler      = GET_PDATA_ENTRY (abfd, data + i +  8);
1670       eh_data         = GET_PDATA_ENTRY (abfd, data + i + 12);
1671       prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1672
1673       if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1674           && eh_data == 0 && prolog_end_addr == 0)
1675         /* We are probably into the padding of the section now.  */
1676         break;
1677
1678       em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1679       eh_handler &= ~(bfd_vma) 0x3;
1680       prolog_end_addr &= ~(bfd_vma) 0x3;
1681
1682       fputc (' ', file);
1683       fprintf_vma (file, i + section->vma); fputc ('\t', file);
1684       fprintf_vma (file, begin_addr); fputc (' ', file);
1685       fprintf_vma (file, end_addr); fputc (' ', file);
1686       fprintf_vma (file, eh_handler);
1687 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1688       fputc (' ', file);
1689       fprintf_vma (file, eh_data); fputc (' ', file);
1690       fprintf_vma (file, prolog_end_addr);
1691       fprintf (file, "   %x", em_data);
1692 #endif
1693
1694 #ifdef POWERPC_LE_PE
1695       if (eh_handler == 0 && eh_data != 0)
1696         {
1697           /* Special bits here, although the meaning may be a little
1698              mysterious. The only one I know for sure is 0x03
1699              Code Significance
1700              0x00 None
1701              0x01 Register Save Millicode
1702              0x02 Register Restore Millicode
1703              0x03 Glue Code Sequence.  */
1704           switch (eh_data)
1705             {
1706             case 0x01:
1707               fprintf (file, _(" Register save millicode"));
1708               break;
1709             case 0x02:
1710               fprintf (file, _(" Register restore millicode"));
1711               break;
1712             case 0x03:
1713               fprintf (file, _(" Glue code sequence"));
1714               break;
1715             default:
1716               break;
1717             }
1718         }
1719 #endif
1720       fprintf (file, "\n");
1721     }
1722
1723   free (data);
1724
1725   return TRUE;
1726 }
1727
1728 #define IMAGE_REL_BASED_HIGHADJ 4
1729 static const char * const tbl[] =
1730 {
1731   "ABSOLUTE",
1732   "HIGH",
1733   "LOW",
1734   "HIGHLOW",
1735   "HIGHADJ",
1736   "MIPS_JMPADDR",
1737   "SECTION",
1738   "REL32",
1739   "RESERVED1",
1740   "MIPS_JMPADDR16",
1741   "DIR64",
1742   "HIGH3ADJ",
1743   "UNKNOWN",   /* MUST be last.  */
1744 };
1745
1746 static bfd_boolean
1747 pe_print_reloc (bfd * abfd, void * vfile)
1748 {
1749   FILE *file = (FILE *) vfile;
1750   bfd_byte *data = 0;
1751   asection *section = bfd_get_section_by_name (abfd, ".reloc");
1752   bfd_size_type datasize;
1753   bfd_size_type i;
1754   bfd_size_type start, stop;
1755
1756   if (section == NULL)
1757     return TRUE;
1758
1759   if (section->size == 0)
1760     return TRUE;
1761
1762   fprintf (file,
1763            _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
1764
1765   datasize = section->size;
1766   if (! bfd_malloc_and_get_section (abfd, section, &data))
1767     {
1768       if (data != NULL)
1769         free (data);
1770       return FALSE;
1771     }
1772
1773   start = 0;
1774
1775   stop = section->size;
1776
1777   for (i = start; i < stop;)
1778     {
1779       int j;
1780       bfd_vma virtual_address;
1781       long number, size;
1782
1783       /* The .reloc section is a sequence of blocks, with a header consisting
1784          of two 32 bit quantities, followed by a number of 16 bit entries.  */
1785       virtual_address = bfd_get_32 (abfd, data+i);
1786       size = bfd_get_32 (abfd, data+i+4);
1787       number = (size - 8) / 2;
1788
1789       if (size == 0)
1790         break;
1791
1792       fprintf (file,
1793                _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
1794                (unsigned long) virtual_address, size, size, number);
1795
1796       for (j = 0; j < number; ++j)
1797         {
1798           unsigned short e = bfd_get_16 (abfd, data + i + 8 + j * 2);
1799           unsigned int t = (e & 0xF000) >> 12;
1800           int off = e & 0x0FFF;
1801
1802           if (t >= sizeof (tbl) / sizeof (tbl[0]))
1803             t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
1804
1805           fprintf (file,
1806                    _("\treloc %4d offset %4x [%4lx] %s"),
1807                    j, off, (long) (off + virtual_address), tbl[t]);
1808
1809           /* HIGHADJ takes an argument, - the next record *is* the
1810              low 16 bits of addend.  */
1811           if (t == IMAGE_REL_BASED_HIGHADJ)
1812             {
1813               fprintf (file, " (%4x)",
1814                        ((unsigned int)
1815                         bfd_get_16 (abfd, data + i + 8 + j * 2 + 2)));
1816               j++;
1817             }
1818
1819           fprintf (file, "\n");
1820         }
1821
1822       i += size;
1823     }
1824
1825   free (data);
1826
1827   return TRUE;
1828 }
1829
1830 /* Print out the program headers.  */
1831
1832 bfd_boolean
1833 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
1834 {
1835   FILE *file = (FILE *) vfile;
1836   int j;
1837   pe_data_type *pe = pe_data (abfd);
1838   struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
1839   const char *subsystem_name = NULL;
1840   const char *name;
1841
1842   /* The MS dumpbin program reportedly ands with 0xff0f before
1843      printing the characteristics field.  Not sure why.  No reason to
1844      emulate it here.  */
1845   fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
1846 #undef PF
1847 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
1848   PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
1849   PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
1850   PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
1851   PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
1852   PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
1853   PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
1854   PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
1855   PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
1856   PF (IMAGE_FILE_SYSTEM, "system file");
1857   PF (IMAGE_FILE_DLL, "DLL");
1858   PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
1859 #undef PF
1860
1861   /* ctime implies '\n'.  */
1862   {
1863     time_t t = pe->coff.timestamp;
1864     fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
1865   }
1866
1867 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
1868 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
1869 #endif
1870 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
1871 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
1872 #endif
1873 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
1874 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
1875 #endif
1876
1877   switch (i->Magic)
1878     {
1879     case IMAGE_NT_OPTIONAL_HDR_MAGIC:
1880       name = "PE32";
1881       break;
1882     case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
1883       name = "PE32+";
1884       break;
1885     case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
1886       name = "ROM";
1887       break;
1888     default:
1889       name = NULL;
1890       break;
1891     }
1892   fprintf (file, "Magic\t\t\t%04x", i->Magic);
1893   if (name)
1894     fprintf (file, "\t(%s)",name);
1895   fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
1896   fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
1897   fprintf (file, "SizeOfCode\t\t%08lx\n", i->SizeOfCode);
1898   fprintf (file, "SizeOfInitializedData\t%08lx\n",
1899            i->SizeOfInitializedData);
1900   fprintf (file, "SizeOfUninitializedData\t%08lx\n",
1901            i->SizeOfUninitializedData);
1902   fprintf (file, "AddressOfEntryPoint\t");
1903   fprintf_vma (file, i->AddressOfEntryPoint);
1904   fprintf (file, "\nBaseOfCode\t\t");
1905   fprintf_vma (file, i->BaseOfCode);
1906 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1907   /* PE32+ does not have BaseOfData member!  */
1908   fprintf (file, "\nBaseOfData\t\t");
1909   fprintf_vma (file, i->BaseOfData);
1910 #endif
1911
1912   fprintf (file, "\nImageBase\t\t");
1913   fprintf_vma (file, i->ImageBase);
1914   fprintf (file, "\nSectionAlignment\t");
1915   fprintf_vma (file, i->SectionAlignment);
1916   fprintf (file, "\nFileAlignment\t\t");
1917   fprintf_vma (file, i->FileAlignment);
1918   fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
1919   fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
1920   fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
1921   fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
1922   fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
1923   fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
1924   fprintf (file, "Win32Version\t\t%08lx\n", i->Reserved1);
1925   fprintf (file, "SizeOfImage\t\t%08lx\n", i->SizeOfImage);
1926   fprintf (file, "SizeOfHeaders\t\t%08lx\n", i->SizeOfHeaders);
1927   fprintf (file, "CheckSum\t\t%08lx\n", i->CheckSum);
1928
1929   switch (i->Subsystem)
1930     {
1931     case IMAGE_SUBSYSTEM_UNKNOWN:
1932       subsystem_name = "unspecified";
1933       break;
1934     case IMAGE_SUBSYSTEM_NATIVE:
1935       subsystem_name = "NT native";
1936       break;
1937     case IMAGE_SUBSYSTEM_WINDOWS_GUI:
1938       subsystem_name = "Windows GUI";
1939       break;
1940     case IMAGE_SUBSYSTEM_WINDOWS_CUI:
1941       subsystem_name = "Windows CUI";
1942       break;
1943     case IMAGE_SUBSYSTEM_POSIX_CUI:
1944       subsystem_name = "POSIX CUI";
1945       break;
1946     case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1947       subsystem_name = "Wince CUI";
1948       break;
1949     case IMAGE_SUBSYSTEM_EFI_APPLICATION:
1950       subsystem_name = "EFI application";
1951       break;
1952     case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
1953       subsystem_name = "EFI boot service driver";
1954       break;
1955     case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
1956       subsystem_name = "EFI runtime driver";
1957       break;
1958     // These are from revision 8.0 of the MS PE/COFF spec
1959     case IMAGE_SUBSYSTEM_EFI_ROM:
1960       subsystem_name = "EFI ROM";
1961       break;
1962     case IMAGE_SUBSYSTEM_XBOX:
1963       subsystem_name = "XBOX";
1964       break;
1965     // Added default case for clarity - subsystem_name is NULL anyway.
1966     default:
1967       subsystem_name = NULL;
1968     }
1969
1970   fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
1971   if (subsystem_name)
1972     fprintf (file, "\t(%s)", subsystem_name);
1973   fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
1974   fprintf (file, "SizeOfStackReserve\t");
1975   fprintf_vma (file, i->SizeOfStackReserve);
1976   fprintf (file, "\nSizeOfStackCommit\t");
1977   fprintf_vma (file, i->SizeOfStackCommit);
1978   fprintf (file, "\nSizeOfHeapReserve\t");
1979   fprintf_vma (file, i->SizeOfHeapReserve);
1980   fprintf (file, "\nSizeOfHeapCommit\t");
1981   fprintf_vma (file, i->SizeOfHeapCommit);
1982   fprintf (file, "\nLoaderFlags\t\t%08lx\n", i->LoaderFlags);
1983   fprintf (file, "NumberOfRvaAndSizes\t%08lx\n", i->NumberOfRvaAndSizes);
1984
1985   fprintf (file, "\nThe Data Directory\n");
1986   for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
1987     {
1988       fprintf (file, "Entry %1x ", j);
1989       fprintf_vma (file, i->DataDirectory[j].VirtualAddress);
1990       fprintf (file, " %08lx ", i->DataDirectory[j].Size);
1991       fprintf (file, "%s\n", dir_names[j]);
1992     }
1993
1994   pe_print_idata (abfd, vfile);
1995   pe_print_edata (abfd, vfile);
1996   pe_print_pdata (abfd, vfile);
1997   pe_print_reloc (abfd, vfile);
1998
1999   return TRUE;
2000 }
2001
2002 /* Copy any private info we understand from the input bfd
2003    to the output bfd.  */
2004
2005 bfd_boolean
2006 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2007 {
2008   /* One day we may try to grok other private data.  */
2009   if (ibfd->xvec->flavour != bfd_target_coff_flavour
2010       || obfd->xvec->flavour != bfd_target_coff_flavour)
2011     return TRUE;
2012
2013   pe_data (obfd)->pe_opthdr = pe_data (ibfd)->pe_opthdr;
2014   pe_data (obfd)->dll = pe_data (ibfd)->dll;
2015
2016   /* For strip: if we removed .reloc, we'll make a real mess of things
2017      if we don't remove this entry as well.  */
2018   if (! pe_data (obfd)->has_reloc_section)
2019     {
2020       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
2021       pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
2022     }
2023   return TRUE;
2024 }
2025
2026 /* Copy private section data.  */
2027
2028 bfd_boolean
2029 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
2030                                        asection *isec,
2031                                        bfd *obfd,
2032                                        asection *osec)
2033 {
2034   if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
2035       || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
2036     return TRUE;
2037
2038   if (coff_section_data (ibfd, isec) != NULL
2039       && pei_section_data (ibfd, isec) != NULL)
2040     {
2041       if (coff_section_data (obfd, osec) == NULL)
2042         {
2043           bfd_size_type amt = sizeof (struct coff_section_tdata);
2044           osec->used_by_bfd = bfd_zalloc (obfd, amt);
2045           if (osec->used_by_bfd == NULL)
2046             return FALSE;
2047         }
2048
2049       if (pei_section_data (obfd, osec) == NULL)
2050         {
2051           bfd_size_type amt = sizeof (struct pei_section_tdata);
2052           coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
2053           if (coff_section_data (obfd, osec)->tdata == NULL)
2054             return FALSE;
2055         }
2056
2057       pei_section_data (obfd, osec)->virt_size =
2058         pei_section_data (ibfd, isec)->virt_size;
2059       pei_section_data (obfd, osec)->pe_flags =
2060         pei_section_data (ibfd, isec)->pe_flags;
2061     }
2062
2063   return TRUE;
2064 }
2065
2066 void
2067 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
2068 {
2069   coff_get_symbol_info (abfd, symbol, ret);
2070 }
2071
2072 /* Handle the .idata section and other things that need symbol table
2073    access.  */
2074
2075 bfd_boolean
2076 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
2077 {
2078   struct coff_link_hash_entry *h1;
2079   struct bfd_link_info *info = pfinfo->info;
2080   bfd_boolean result = TRUE;
2081
2082   /* There are a few fields that need to be filled in now while we
2083      have symbol table access.
2084
2085      The .idata subsections aren't directly available as sections, but
2086      they are in the symbol table, so get them from there.  */
2087
2088   /* The import directory.  This is the address of .idata$2, with size
2089      of .idata$2 + .idata$3.  */
2090   h1 = coff_link_hash_lookup (coff_hash_table (info),
2091                               ".idata$2", FALSE, FALSE, TRUE);
2092   if (h1 != NULL)
2093     {
2094       /* PR ld/2729: We cannot rely upon all the output sections having been 
2095          created properly, so check before referencing them.  Issue a warning
2096          message for any sections tht could not be found.  */
2097       if (h1->root.u.def.section != NULL
2098           && h1->root.u.def.section->output_section != NULL)
2099         pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
2100           (h1->root.u.def.value
2101            + h1->root.u.def.section->output_section->vma
2102            + h1->root.u.def.section->output_offset);
2103       else
2104         {
2105           _bfd_error_handler
2106             (_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"), 
2107              abfd);
2108           result = FALSE;
2109         }
2110
2111       h1 = coff_link_hash_lookup (coff_hash_table (info),
2112                                   ".idata$4", FALSE, FALSE, TRUE);
2113       if (h1 != NULL
2114           && h1->root.u.def.section != NULL
2115           && h1->root.u.def.section->output_section != NULL)
2116         pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
2117           ((h1->root.u.def.value
2118             + h1->root.u.def.section->output_section->vma
2119             + h1->root.u.def.section->output_offset)
2120            - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
2121       else
2122         {
2123           _bfd_error_handler
2124             (_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"), 
2125              abfd);
2126           result = FALSE;
2127         }
2128
2129       /* The import address table.  This is the size/address of
2130          .idata$5.  */
2131       h1 = coff_link_hash_lookup (coff_hash_table (info),
2132                                   ".idata$5", FALSE, FALSE, TRUE);
2133       if (h1 != NULL
2134           && h1->root.u.def.section != NULL
2135           && h1->root.u.def.section->output_section != NULL)
2136         pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
2137           (h1->root.u.def.value
2138            + h1->root.u.def.section->output_section->vma
2139            + h1->root.u.def.section->output_offset);
2140       else
2141         {
2142           _bfd_error_handler
2143             (_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"), 
2144              abfd);
2145           result = FALSE;
2146         }
2147
2148       h1 = coff_link_hash_lookup (coff_hash_table (info),
2149                                   ".idata$6", FALSE, FALSE, TRUE);
2150       if (h1 != NULL
2151           && h1->root.u.def.section != NULL
2152           && h1->root.u.def.section->output_section != NULL)
2153         pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
2154           ((h1->root.u.def.value
2155             + h1->root.u.def.section->output_section->vma
2156             + h1->root.u.def.section->output_offset)
2157            - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);      
2158       else
2159         {
2160           _bfd_error_handler
2161             (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"), 
2162              abfd);
2163           result = FALSE;
2164         }
2165     }
2166
2167   h1 = coff_link_hash_lookup (coff_hash_table (info),
2168                               "__tls_used", FALSE, FALSE, TRUE);
2169   if (h1 != NULL)
2170     {
2171       if (h1->root.u.def.section != NULL
2172           && h1->root.u.def.section->output_section != NULL)
2173         pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
2174           (h1->root.u.def.value
2175            + h1->root.u.def.section->output_section->vma
2176            + h1->root.u.def.section->output_offset
2177            - pe_data (abfd)->pe_opthdr.ImageBase);
2178       else
2179         {
2180           _bfd_error_handler
2181             (_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"), 
2182              abfd);
2183           result = FALSE;
2184         }
2185
2186       pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
2187     }
2188
2189   /* If we couldn't find idata$2, we either have an excessively
2190      trivial program or are in DEEP trouble; we have to assume trivial
2191      program....  */
2192   return result;
2193 }