include/
[platform/upstream/binutils.git] / bfd / peicode.h
1 /* Support for the generic parts of PE/PEI, for BFD.
2    Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3    2005 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 /* Most of this hacked by  Steve Chamberlain,
23                         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 #include "libpei.h"
57
58 static bfd_boolean (*pe_saved_coff_bfd_print_private_bfd_data)
59     PARAMS ((bfd *, PTR)) =
60 #ifndef coff_bfd_print_private_bfd_data
61      NULL;
62 #else
63      coff_bfd_print_private_bfd_data;
64 #undef coff_bfd_print_private_bfd_data
65 #endif
66
67 static bfd_boolean pe_print_private_bfd_data PARAMS ((bfd *, PTR));
68 #define coff_bfd_print_private_bfd_data pe_print_private_bfd_data
69
70 static bfd_boolean (*pe_saved_coff_bfd_copy_private_bfd_data)
71     PARAMS ((bfd *, bfd *)) =
72 #ifndef coff_bfd_copy_private_bfd_data
73      NULL;
74 #else
75      coff_bfd_copy_private_bfd_data;
76 #undef coff_bfd_copy_private_bfd_data
77 #endif
78
79 static bfd_boolean pe_bfd_copy_private_bfd_data PARAMS ((bfd *, bfd *));
80 #define coff_bfd_copy_private_bfd_data pe_bfd_copy_private_bfd_data
81
82 #define coff_mkobject      pe_mkobject
83 #define coff_mkobject_hook pe_mkobject_hook
84
85 #ifndef NO_COFF_RELOCS
86 static void coff_swap_reloc_in PARAMS ((bfd *, PTR, PTR));
87 static unsigned int coff_swap_reloc_out PARAMS ((bfd *, PTR, PTR));
88 #endif
89 static void coff_swap_filehdr_in PARAMS ((bfd *, PTR, PTR));
90 static void coff_swap_scnhdr_in PARAMS ((bfd *, PTR, PTR));
91 static bfd_boolean pe_mkobject PARAMS ((bfd *));
92 static PTR pe_mkobject_hook PARAMS ((bfd *, PTR, PTR));
93
94 #ifdef COFF_IMAGE_WITH_PE
95 /* This structure contains static variables used by the ILF code.  */
96 typedef asection * asection_ptr;
97
98 typedef struct
99 {
100   bfd *                 abfd;
101   bfd_byte *            data;
102   struct bfd_in_memory * bim;
103   unsigned short        magic;
104
105   arelent *             reltab;
106   unsigned int          relcount;
107
108   coff_symbol_type *    sym_cache;
109   coff_symbol_type *    sym_ptr;
110   unsigned int          sym_index;
111
112   unsigned int *        sym_table;
113   unsigned int *        table_ptr;
114
115   combined_entry_type * native_syms;
116   combined_entry_type * native_ptr;
117
118   coff_symbol_type **   sym_ptr_table;
119   coff_symbol_type **   sym_ptr_ptr;
120
121   unsigned int          sec_index;
122
123   char *                string_table;
124   char *                string_ptr;
125   char *                end_string_ptr;
126
127   SYMENT *              esym_table;
128   SYMENT *              esym_ptr;
129
130   struct internal_reloc * int_reltab;
131 }
132 pe_ILF_vars;
133 #endif /* COFF_IMAGE_WITH_PE */
134
135 /**********************************************************************/
136
137 #ifndef NO_COFF_RELOCS
138 static void
139 coff_swap_reloc_in (abfd, src, dst)
140      bfd *abfd;
141      PTR src;
142      PTR dst;
143 {
144   RELOC *reloc_src = (RELOC *) src;
145   struct internal_reloc *reloc_dst = (struct internal_reloc *) dst;
146
147   reloc_dst->r_vaddr = H_GET_32 (abfd, reloc_src->r_vaddr);
148   reloc_dst->r_symndx = H_GET_S32 (abfd, reloc_src->r_symndx);
149
150   reloc_dst->r_type = H_GET_16 (abfd, reloc_src->r_type);
151
152 #ifdef SWAP_IN_RELOC_OFFSET
153   reloc_dst->r_offset = SWAP_IN_RELOC_OFFSET (abfd, reloc_src->r_offset);
154 #endif
155 }
156
157 static unsigned int
158 coff_swap_reloc_out (abfd, src, dst)
159      bfd       *abfd;
160      PTR        src;
161      PTR        dst;
162 {
163   struct internal_reloc *reloc_src = (struct internal_reloc *)src;
164   struct external_reloc *reloc_dst = (struct external_reloc *)dst;
165   H_PUT_32 (abfd, reloc_src->r_vaddr, reloc_dst->r_vaddr);
166   H_PUT_32 (abfd, reloc_src->r_symndx, reloc_dst->r_symndx);
167
168   H_PUT_16 (abfd, reloc_src->r_type, reloc_dst->r_type);
169
170 #ifdef SWAP_OUT_RELOC_OFFSET
171   SWAP_OUT_RELOC_OFFSET (abfd, reloc_src->r_offset, reloc_dst->r_offset);
172 #endif
173 #ifdef SWAP_OUT_RELOC_EXTRA
174   SWAP_OUT_RELOC_EXTRA(abfd, reloc_src, reloc_dst);
175 #endif
176   return RELSZ;
177 }
178 #endif /* not NO_COFF_RELOCS */
179
180 static void
181 coff_swap_filehdr_in (abfd, src, dst)
182      bfd            *abfd;
183      PTR             src;
184      PTR             dst;
185 {
186   FILHDR *filehdr_src = (FILHDR *) src;
187   struct internal_filehdr *filehdr_dst = (struct internal_filehdr *) dst;
188   filehdr_dst->f_magic = H_GET_16 (abfd, filehdr_src->f_magic);
189   filehdr_dst->f_nscns = H_GET_16 (abfd, filehdr_src-> f_nscns);
190   filehdr_dst->f_timdat = H_GET_32 (abfd, filehdr_src-> f_timdat);
191
192   filehdr_dst->f_nsyms = H_GET_32 (abfd, filehdr_src-> f_nsyms);
193   filehdr_dst->f_flags = H_GET_16 (abfd, filehdr_src-> f_flags);
194   filehdr_dst->f_symptr = H_GET_32 (abfd, filehdr_src->f_symptr);
195
196   /* Other people's tools sometimes generate headers with an nsyms but
197      a zero symptr.  */
198   if (filehdr_dst->f_nsyms != 0 && filehdr_dst->f_symptr == 0)
199     {
200       filehdr_dst->f_nsyms = 0;
201       filehdr_dst->f_flags |= F_LSYMS;
202     }
203
204   filehdr_dst->f_opthdr = H_GET_16 (abfd, filehdr_src-> f_opthdr);
205 }
206
207 #ifdef COFF_IMAGE_WITH_PE
208 # define coff_swap_filehdr_out _bfd_XXi_only_swap_filehdr_out
209 #else
210 # define coff_swap_filehdr_out _bfd_pe_only_swap_filehdr_out
211 #endif
212
213 static void
214 coff_swap_scnhdr_in (abfd, ext, in)
215      bfd            *abfd;
216      PTR             ext;
217      PTR             in;
218 {
219   SCNHDR *scnhdr_ext = (SCNHDR *) ext;
220   struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
221
222   memcpy(scnhdr_int->s_name, scnhdr_ext->s_name, sizeof (scnhdr_int->s_name));
223   scnhdr_int->s_vaddr = GET_SCNHDR_VADDR (abfd, scnhdr_ext->s_vaddr);
224   scnhdr_int->s_paddr = GET_SCNHDR_PADDR (abfd, scnhdr_ext->s_paddr);
225   scnhdr_int->s_size = GET_SCNHDR_SIZE (abfd, scnhdr_ext->s_size);
226   scnhdr_int->s_scnptr = GET_SCNHDR_SCNPTR (abfd, scnhdr_ext->s_scnptr);
227   scnhdr_int->s_relptr = GET_SCNHDR_RELPTR (abfd, scnhdr_ext->s_relptr);
228   scnhdr_int->s_lnnoptr = GET_SCNHDR_LNNOPTR (abfd, scnhdr_ext->s_lnnoptr);
229   scnhdr_int->s_flags = H_GET_32 (abfd, scnhdr_ext->s_flags);
230
231   /* MS handles overflow of line numbers by carrying into the reloc
232      field (it appears).  Since it's supposed to be zero for PE
233      *IMAGE* format, that's safe.  This is still a bit iffy.  */
234 #ifdef COFF_IMAGE_WITH_PE
235   scnhdr_int->s_nlnno = (H_GET_16 (abfd, scnhdr_ext->s_nlnno)
236                          + (H_GET_16 (abfd, scnhdr_ext->s_nreloc) << 16));
237   scnhdr_int->s_nreloc = 0;
238 #else
239   scnhdr_int->s_nreloc = H_GET_16 (abfd, scnhdr_ext->s_nreloc);
240   scnhdr_int->s_nlnno = H_GET_16 (abfd, scnhdr_ext->s_nlnno);
241 #endif
242
243   if (scnhdr_int->s_vaddr != 0)
244     {
245       scnhdr_int->s_vaddr += pe_data (abfd)->pe_opthdr.ImageBase;
246       scnhdr_int->s_vaddr &= 0xffffffff;
247     }
248
249 #ifndef COFF_NO_HACK_SCNHDR_SIZE
250   /* If this section holds uninitialized data and is from an object file
251      or from an executable image that has not initialized the field,
252      or if the image is an executable file and the physical size is padded,
253      use the virtual size (stored in s_paddr) instead.  */
254   if (scnhdr_int->s_paddr > 0
255       && (((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0
256            && (! bfd_pe_executable_p (abfd) || scnhdr_int->s_size == 0))
257           || (bfd_pe_executable_p (abfd) && scnhdr_int->s_size > scnhdr_int->s_paddr)))
258     {
259       scnhdr_int->s_size = scnhdr_int->s_paddr;
260
261       /* This code used to set scnhdr_int->s_paddr to 0.  However,
262          coff_set_alignment_hook stores s_paddr in virt_size, which
263          only works if it correctly holds the virtual size of the
264          section.  */
265     }
266 #endif
267 }
268
269 static bfd_boolean
270 pe_mkobject (abfd)
271      bfd * abfd;
272 {
273   pe_data_type *pe;
274   bfd_size_type amt = sizeof (pe_data_type);
275
276   abfd->tdata.pe_obj_data = (struct pe_tdata *) bfd_zalloc (abfd, amt);
277
278   if (abfd->tdata.pe_obj_data == 0)
279     return FALSE;
280
281   pe = pe_data (abfd);
282
283   pe->coff.pe = 1;
284
285   /* in_reloc_p is architecture dependent.  */
286   pe->in_reloc_p = in_reloc_p;
287
288 #ifdef PEI_FORCE_MINIMUM_ALIGNMENT
289   pe->force_minimum_alignment = 1;
290 #endif
291 #ifdef PEI_TARGET_SUBSYSTEM
292   pe->target_subsystem = PEI_TARGET_SUBSYSTEM;
293 #endif
294
295   return TRUE;
296 }
297
298 /* Create the COFF backend specific information.  */
299 static PTR
300 pe_mkobject_hook (abfd, filehdr, aouthdr)
301      bfd * abfd;
302      PTR filehdr;
303      PTR aouthdr ATTRIBUTE_UNUSED;
304 {
305   struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
306   pe_data_type *pe;
307
308   if (! pe_mkobject (abfd))
309     return NULL;
310
311   pe = pe_data (abfd);
312   pe->coff.sym_filepos = internal_f->f_symptr;
313   /* These members communicate important constants about the symbol
314      table to GDB's symbol-reading code.  These `constants'
315      unfortunately vary among coff implementations...  */
316   pe->coff.local_n_btmask = N_BTMASK;
317   pe->coff.local_n_btshft = N_BTSHFT;
318   pe->coff.local_n_tmask = N_TMASK;
319   pe->coff.local_n_tshift = N_TSHIFT;
320   pe->coff.local_symesz = SYMESZ;
321   pe->coff.local_auxesz = AUXESZ;
322   pe->coff.local_linesz = LINESZ;
323
324   pe->coff.timestamp = internal_f->f_timdat;
325
326   obj_raw_syment_count (abfd) =
327     obj_conv_table_size (abfd) =
328       internal_f->f_nsyms;
329
330   pe->real_flags = internal_f->f_flags;
331
332   if ((internal_f->f_flags & F_DLL) != 0)
333     pe->dll = 1;
334
335   if ((internal_f->f_flags & IMAGE_FILE_DEBUG_STRIPPED) == 0)
336     abfd->flags |= HAS_DEBUG;
337
338 #ifdef COFF_IMAGE_WITH_PE
339   if (aouthdr)
340     pe->pe_opthdr = ((struct internal_aouthdr *)aouthdr)->pe;
341 #endif
342
343 #ifdef ARM
344   if (! _bfd_coff_arm_set_private_flags (abfd, internal_f->f_flags))
345     coff_data (abfd) ->flags = 0;
346 #endif
347
348   return (PTR) pe;
349 }
350
351 static bfd_boolean
352 pe_print_private_bfd_data (abfd, vfile)
353      bfd *abfd;
354      PTR vfile;
355 {
356   FILE *file = (FILE *) vfile;
357
358   if (!_bfd_XX_print_private_bfd_data_common (abfd, vfile))
359     return FALSE;
360
361   if (pe_saved_coff_bfd_print_private_bfd_data != NULL)
362     {
363       fputc ('\n', file);
364
365       return pe_saved_coff_bfd_print_private_bfd_data (abfd, vfile);
366     }
367
368   return TRUE;
369 }
370
371 /* Copy any private info we understand from the input bfd
372    to the output bfd.  */
373
374 static bfd_boolean
375 pe_bfd_copy_private_bfd_data (ibfd, obfd)
376      bfd *ibfd, *obfd;
377 {
378   /* PR binutils/716: Copy the large address aware flag.
379      XXX: Should we be copying other flags or other fields in the pe_data()
380      structure ?  */
381   if (pe_data (obfd) != NULL
382       && pe_data (ibfd) != NULL
383       && pe_data (ibfd)->real_flags & IMAGE_FILE_LARGE_ADDRESS_AWARE)
384     pe_data (obfd)->real_flags |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
385       
386   if (!_bfd_XX_bfd_copy_private_bfd_data_common (ibfd, obfd))
387     return FALSE;
388
389   if (pe_saved_coff_bfd_copy_private_bfd_data)
390     return pe_saved_coff_bfd_copy_private_bfd_data (ibfd, obfd);
391
392   return TRUE;
393 }
394
395 #define coff_bfd_copy_private_section_data \
396   _bfd_XX_bfd_copy_private_section_data
397
398 #define coff_get_symbol_info _bfd_XX_get_symbol_info
399
400 #ifdef COFF_IMAGE_WITH_PE
401 \f
402 /* Code to handle Microsoft's Image Library Format.
403    Also known as LINK6 format.
404    Documentation about this format can be found at:
405
406    http://msdn.microsoft.com/library/specs/pecoff_section8.htm  */
407
408 /* The following constants specify the sizes of the various data
409    structures that we have to create in order to build a bfd describing
410    an ILF object file.  The final "+ 1" in the definitions of SIZEOF_IDATA6
411    and SIZEOF_IDATA7 below is to allow for the possibility that we might
412    need a padding byte in order to ensure 16 bit alignment for the section's
413    contents.
414
415    The value for SIZEOF_ILF_STRINGS is computed as follows:
416
417       There will be NUM_ILF_SECTIONS section symbols.  Allow 9 characters
418       per symbol for their names (longest section name is .idata$x).
419
420       There will be two symbols for the imported value, one the symbol name
421       and one with _imp__ prefixed.  Allowing for the terminating nul's this
422       is strlen (symbol_name) * 2 + 8 + 21 + strlen (source_dll).
423
424       The strings in the string table must start STRING__SIZE_SIZE bytes into
425       the table in order to for the string lookup code in coffgen/coffcode to
426       work.  */
427 #define NUM_ILF_RELOCS          8
428 #define NUM_ILF_SECTIONS        6
429 #define NUM_ILF_SYMS            (2 + NUM_ILF_SECTIONS)
430
431 #define SIZEOF_ILF_SYMS         (NUM_ILF_SYMS * sizeof (* vars.sym_cache))
432 #define SIZEOF_ILF_SYM_TABLE    (NUM_ILF_SYMS * sizeof (* vars.sym_table))
433 #define SIZEOF_ILF_NATIVE_SYMS  (NUM_ILF_SYMS * sizeof (* vars.native_syms))
434 #define SIZEOF_ILF_SYM_PTR_TABLE (NUM_ILF_SYMS * sizeof (* vars.sym_ptr_table))
435 #define SIZEOF_ILF_EXT_SYMS     (NUM_ILF_SYMS * sizeof (* vars.esym_table))
436 #define SIZEOF_ILF_RELOCS       (NUM_ILF_RELOCS * sizeof (* vars.reltab))
437 #define SIZEOF_ILF_INT_RELOCS   (NUM_ILF_RELOCS * sizeof (* vars.int_reltab))
438 #define SIZEOF_ILF_STRINGS      (strlen (symbol_name) * 2 + 8 \
439                                         + 21 + strlen (source_dll) \
440                                         + NUM_ILF_SECTIONS * 9 \
441                                         + STRING_SIZE_SIZE)
442 #define SIZEOF_IDATA2           (5 * 4)
443 #define SIZEOF_IDATA4           (1 * 4)
444 #define SIZEOF_IDATA5           (1 * 4)
445 #define SIZEOF_IDATA6           (2 + strlen (symbol_name) + 1 + 1)
446 #define SIZEOF_IDATA7           (strlen (source_dll) + 1 + 1)
447 #define SIZEOF_ILF_SECTIONS     (NUM_ILF_SECTIONS * sizeof (struct coff_section_tdata))
448
449 #define ILF_DATA_SIZE                           \
450       sizeof (* vars.bim)                       \
451     + SIZEOF_ILF_SYMS                           \
452     + SIZEOF_ILF_SYM_TABLE                      \
453     + SIZEOF_ILF_NATIVE_SYMS                    \
454     + SIZEOF_ILF_SYM_PTR_TABLE                  \
455     + SIZEOF_ILF_EXT_SYMS                       \
456     + SIZEOF_ILF_RELOCS                         \
457     + SIZEOF_ILF_INT_RELOCS                     \
458     + SIZEOF_ILF_STRINGS                        \
459     + SIZEOF_IDATA2                             \
460     + SIZEOF_IDATA4                             \
461     + SIZEOF_IDATA5                             \
462     + SIZEOF_IDATA6                             \
463     + SIZEOF_IDATA7                             \
464     + SIZEOF_ILF_SECTIONS                       \
465     + MAX_TEXT_SECTION_SIZE
466
467 /* Create an empty relocation against the given symbol.  */
468 static void
469 pe_ILF_make_a_symbol_reloc (pe_ILF_vars *                 vars,
470                             bfd_vma                       address,
471                             bfd_reloc_code_real_type      reloc,
472                             struct bfd_symbol **  sym,
473                             unsigned int                  sym_index)
474 {
475   arelent * entry;
476   struct internal_reloc * internal;
477
478   entry = vars->reltab + vars->relcount;
479   internal = vars->int_reltab + vars->relcount;
480
481   entry->address     = address;
482   entry->addend      = 0;
483   entry->howto       = bfd_reloc_type_lookup (vars->abfd, reloc);
484   entry->sym_ptr_ptr = sym;
485
486   internal->r_vaddr  = address;
487   internal->r_symndx = sym_index;
488   internal->r_type   = entry->howto->type;
489
490   vars->relcount ++;
491
492   BFD_ASSERT (vars->relcount <= NUM_ILF_RELOCS);
493 }
494
495 /* Create an empty relocation against the given section.  */
496 static void
497 pe_ILF_make_a_reloc (pe_ILF_vars *             vars,
498                      bfd_vma                   address,
499                      bfd_reloc_code_real_type  reloc,
500                      asection_ptr              sec)
501 {
502   pe_ILF_make_a_symbol_reloc (vars, address, reloc, sec->symbol_ptr_ptr,
503                               coff_section_data (vars->abfd, sec)->i);
504 }
505
506 /* Move the queued relocs into the given section.  */
507 static void
508 pe_ILF_save_relocs (pe_ILF_vars * vars,
509                     asection_ptr  sec)
510 {
511   /* Make sure that there is somewhere to store the internal relocs.  */
512   if (coff_section_data (vars->abfd, sec) == NULL)
513     /* We should probably return an error indication here.  */
514     abort ();
515
516   coff_section_data (vars->abfd, sec)->relocs = vars->int_reltab;
517   coff_section_data (vars->abfd, sec)->keep_relocs = TRUE;
518
519   sec->relocation  = vars->reltab;
520   sec->reloc_count = vars->relcount;
521   sec->flags      |= SEC_RELOC;
522
523   vars->reltab     += vars->relcount;
524   vars->int_reltab += vars->relcount;
525   vars->relcount   = 0;
526
527   BFD_ASSERT ((bfd_byte *) vars->int_reltab < (bfd_byte *) vars->string_table);
528 }
529
530 /* Create a global symbol and add it to the relevant tables.  */
531 static void
532 pe_ILF_make_a_symbol (pe_ILF_vars *  vars,
533                       const char *   prefix,
534                       const char *   symbol_name,
535                       asection_ptr   section,
536                       flagword       extra_flags)
537 {
538   coff_symbol_type * sym;
539   combined_entry_type * ent;
540   SYMENT * esym;
541   unsigned short sclass;
542
543   if (extra_flags & BSF_LOCAL)
544     sclass = C_STAT;
545   else
546     sclass = C_EXT;
547
548 #ifdef THUMBPEMAGIC
549   if (vars->magic == THUMBPEMAGIC)
550     {
551       if (extra_flags & BSF_FUNCTION)
552         sclass = C_THUMBEXTFUNC;
553       else if (extra_flags & BSF_LOCAL)
554         sclass = C_THUMBSTAT;
555       else
556         sclass = C_THUMBEXT;
557     }
558 #endif
559
560   BFD_ASSERT (vars->sym_index < NUM_ILF_SYMS);
561
562   sym = vars->sym_ptr;
563   ent = vars->native_ptr;
564   esym = vars->esym_ptr;
565
566   /* Copy the symbol's name into the string table.  */
567   sprintf (vars->string_ptr, "%s%s", prefix, symbol_name);
568
569   if (section == NULL)
570     section = (asection_ptr) & bfd_und_section;
571
572   /* Initialise the external symbol.  */
573   H_PUT_32 (vars->abfd, vars->string_ptr - vars->string_table,
574             esym->e.e.e_offset);
575   H_PUT_16 (vars->abfd, section->target_index, esym->e_scnum);
576   esym->e_sclass[0] = sclass;
577
578   /* The following initialisations are unnecessary - the memory is
579      zero initialised.  They are just kept here as reminders.  */
580
581   /* Initialise the internal symbol structure.  */
582   ent->u.syment.n_sclass          = sclass;
583   ent->u.syment.n_scnum           = section->target_index;
584   ent->u.syment._n._n_n._n_offset = (long) sym;
585
586   sym->symbol.the_bfd = vars->abfd;
587   sym->symbol.name    = vars->string_ptr;
588   sym->symbol.flags   = BSF_EXPORT | BSF_GLOBAL | extra_flags;
589   sym->symbol.section = section;
590   sym->native         = ent;
591
592   * vars->table_ptr = vars->sym_index;
593   * vars->sym_ptr_ptr = sym;
594
595   /* Adjust pointers for the next symbol.  */
596   vars->sym_index ++;
597   vars->sym_ptr ++;
598   vars->sym_ptr_ptr ++;
599   vars->table_ptr ++;
600   vars->native_ptr ++;
601   vars->esym_ptr ++;
602   vars->string_ptr += strlen (symbol_name) + strlen (prefix) + 1;
603
604   BFD_ASSERT (vars->string_ptr < vars->end_string_ptr);
605 }
606
607 /* Create a section.  */
608 static asection_ptr
609 pe_ILF_make_a_section (pe_ILF_vars * vars,
610                        const char *  name,
611                        unsigned int  size,
612                        flagword      extra_flags)
613 {
614   asection_ptr sec;
615   flagword     flags;
616
617   sec = bfd_make_section_old_way (vars->abfd, name);
618   if (sec == NULL)
619     return NULL;
620
621   flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_IN_MEMORY;
622
623   bfd_set_section_flags (vars->abfd, sec, flags | extra_flags);
624
625   bfd_set_section_alignment (vars->abfd, sec, 2);
626
627   /* Check that we will not run out of space.  */
628   BFD_ASSERT (vars->data + size < vars->bim->buffer + vars->bim->size);
629
630   /* Set the section size and contents.  The actual
631      contents are filled in by our parent.  */
632   bfd_set_section_size (vars->abfd, sec, (bfd_size_type) size);
633   sec->contents = vars->data;
634   sec->target_index = vars->sec_index ++;
635
636   /* Advance data pointer in the vars structure.  */
637   vars->data += size;
638
639   /* Skip the padding byte if it was not needed.
640      The logic here is that if the string length is odd,
641      then the entire string length, including the null byte,
642      is even and so the extra, padding byte, is not needed.  */
643   if (size & 1)
644     vars->data --;
645
646   /* Create a coff_section_tdata structure for our use.  */
647   sec->used_by_bfd = (struct coff_section_tdata *) vars->data;
648   vars->data += sizeof (struct coff_section_tdata);
649
650   BFD_ASSERT (vars->data <= vars->bim->buffer + vars->bim->size);
651
652   /* Create a symbol to refer to this section.  */
653   pe_ILF_make_a_symbol (vars, "", name, sec, BSF_LOCAL);
654
655   /* Cache the index to the symbol in the coff_section_data structure.  */
656   coff_section_data (vars->abfd, sec)->i = vars->sym_index - 1;
657
658   return sec;
659 }
660
661 /* This structure contains the code that goes into the .text section
662    in order to perform a jump into the DLL lookup table.  The entries
663    in the table are index by the magic number used to represent the
664    machine type in the PE file.  The contents of the data[] arrays in
665    these entries are stolen from the jtab[] arrays in ld/pe-dll.c.
666    The SIZE field says how many bytes in the DATA array are actually
667    used.  The OFFSET field says where in the data array the address
668    of the .idata$5 section should be placed.  */
669 #define MAX_TEXT_SECTION_SIZE 32
670
671 typedef struct
672 {
673   unsigned short magic;
674   unsigned char  data[MAX_TEXT_SECTION_SIZE];
675   unsigned int   size;
676   unsigned int   offset;
677 }
678 jump_table;
679
680 static jump_table jtab[] =
681 {
682 #ifdef I386MAGIC
683   { I386MAGIC,
684     { 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90 },
685     8, 2
686   },
687 #endif
688
689 #ifdef  MC68MAGIC
690   { MC68MAGIC, { /* XXX fill me in */ }, 0, 0 },
691 #endif
692 #ifdef  MIPS_ARCH_MAGIC_WINCE
693   { MIPS_ARCH_MAGIC_WINCE,
694     { 0x00, 0x00, 0x08, 0x3c, 0x00, 0x00, 0x08, 0x8d,
695       0x08, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 },
696     16, 0
697   },
698 #endif
699
700 #ifdef  SH_ARCH_MAGIC_WINCE
701   { SH_ARCH_MAGIC_WINCE,
702     { 0x01, 0xd0, 0x02, 0x60, 0x2b, 0x40,
703       0x09, 0x00, 0x00, 0x00, 0x00, 0x00 },
704     12, 8
705   },
706 #endif
707
708 #ifdef  ARMPEMAGIC
709   { ARMPEMAGIC,
710     { 0x00, 0xc0, 0x9f, 0xe5, 0x00, 0xf0,
711       0x9c, 0xe5, 0x00, 0x00, 0x00, 0x00},
712     12, 8
713   },
714 #endif
715
716 #ifdef  THUMBPEMAGIC
717   { THUMBPEMAGIC,
718     { 0x40, 0xb4, 0x02, 0x4e, 0x36, 0x68, 0xb4, 0x46,
719       0x40, 0xbc, 0x60, 0x47, 0x00, 0x00, 0x00, 0x00 },
720     16, 12
721   },
722 #endif
723   { 0, { 0 }, 0, 0 }
724 };
725
726 #ifndef NUM_ENTRIES
727 #define NUM_ENTRIES(a) (sizeof (a) / sizeof (a)[0])
728 #endif
729
730 /* Build a full BFD from the information supplied in a ILF object.  */
731 static bfd_boolean
732 pe_ILF_build_a_bfd (bfd *           abfd,
733                     unsigned int    magic,
734                     char *          symbol_name,
735                     char *          source_dll,
736                     unsigned int    ordinal,
737                     unsigned int    types)
738 {
739   bfd_byte *               ptr;
740   pe_ILF_vars              vars;
741   struct internal_filehdr  internal_f;
742   unsigned int             import_type;
743   unsigned int             import_name_type;
744   asection_ptr             id4, id5, id6 = NULL, text = NULL;
745   coff_symbol_type **      imp_sym;
746   unsigned int             imp_index;
747
748   /* Decode and verify the types field of the ILF structure.  */
749   import_type = types & 0x3;
750   import_name_type = (types & 0x1c) >> 2;
751
752   switch (import_type)
753     {
754     case IMPORT_CODE:
755     case IMPORT_DATA:
756       break;
757
758     case IMPORT_CONST:
759       /* XXX code yet to be written.  */
760       _bfd_error_handler (_("%B: Unhandled import type; %x"),
761                           abfd, import_type);
762       return FALSE;
763
764     default:
765       _bfd_error_handler (_("%B: Unrecognised import type; %x"),
766                           abfd, import_type);
767       return FALSE;
768     }
769
770   switch (import_name_type)
771     {
772     case IMPORT_ORDINAL:
773     case IMPORT_NAME:
774     case IMPORT_NAME_NOPREFIX:
775     case IMPORT_NAME_UNDECORATE:
776       break;
777
778     default:
779       _bfd_error_handler (_("%B: Unrecognised import name type; %x"),
780                           abfd, import_name_type);
781       return FALSE;
782     }
783
784   /* Initialise local variables.
785
786      Note these are kept in a structure rather than being
787      declared as statics since bfd frowns on global variables.
788
789      We are going to construct the contents of the BFD in memory,
790      so allocate all the space that we will need right now.  */
791   ptr = bfd_zalloc (abfd, (bfd_size_type) ILF_DATA_SIZE);
792   if (ptr == NULL)
793     return FALSE;
794
795   /* Create a bfd_in_memory structure.  */
796   vars.bim = (struct bfd_in_memory *) ptr;
797   vars.bim->buffer = ptr;
798   vars.bim->size   = ILF_DATA_SIZE;
799   ptr += sizeof (* vars.bim);
800
801   /* Initialise the pointers to regions of the memory and the
802      other contents of the pe_ILF_vars structure as well.  */
803   vars.sym_cache = (coff_symbol_type *) ptr;
804   vars.sym_ptr   = (coff_symbol_type *) ptr;
805   vars.sym_index = 0;
806   ptr += SIZEOF_ILF_SYMS;
807
808   vars.sym_table = (unsigned int *) ptr;
809   vars.table_ptr = (unsigned int *) ptr;
810   ptr += SIZEOF_ILF_SYM_TABLE;
811
812   vars.native_syms = (combined_entry_type *) ptr;
813   vars.native_ptr  = (combined_entry_type *) ptr;
814   ptr += SIZEOF_ILF_NATIVE_SYMS;
815
816   vars.sym_ptr_table = (coff_symbol_type **) ptr;
817   vars.sym_ptr_ptr   = (coff_symbol_type **) ptr;
818   ptr += SIZEOF_ILF_SYM_PTR_TABLE;
819
820   vars.esym_table = (SYMENT *) ptr;
821   vars.esym_ptr   = (SYMENT *) ptr;
822   ptr += SIZEOF_ILF_EXT_SYMS;
823
824   vars.reltab   = (arelent *) ptr;
825   vars.relcount = 0;
826   ptr += SIZEOF_ILF_RELOCS;
827
828   vars.int_reltab  = (struct internal_reloc *) ptr;
829   ptr += SIZEOF_ILF_INT_RELOCS;
830
831   vars.string_table = (char *) ptr;
832   vars.string_ptr   = (char *) ptr + STRING_SIZE_SIZE;
833   ptr += SIZEOF_ILF_STRINGS;
834   vars.end_string_ptr = (char *) ptr;
835
836   /* The remaining space in bim->buffer is used
837      by the pe_ILF_make_a_section() function.  */
838   vars.data = ptr;
839   vars.abfd = abfd;
840   vars.sec_index = 0;
841   vars.magic = magic;
842
843   /* Create the initial .idata$<n> sections:
844      [.idata$2:  Import Directory Table -- not needed]
845      .idata$4:  Import Lookup Table
846      .idata$5:  Import Address Table
847
848      Note we do not create a .idata$3 section as this is
849      created for us by the linker script.  */
850   id4 = pe_ILF_make_a_section (& vars, ".idata$4", SIZEOF_IDATA4, 0);
851   id5 = pe_ILF_make_a_section (& vars, ".idata$5", SIZEOF_IDATA5, 0);
852   if (id4 == NULL || id5 == NULL)
853     return FALSE;
854
855   /* Fill in the contents of these sections.  */
856   if (import_name_type == IMPORT_ORDINAL)
857     {
858       if (ordinal == 0)
859         /* XXX - treat as IMPORT_NAME ??? */
860         abort ();
861
862       * (unsigned int *) id4->contents = ordinal | 0x80000000;
863       * (unsigned int *) id5->contents = ordinal | 0x80000000;
864     }
865   else
866     {
867       char * symbol;
868
869       /* Create .idata$6 - the Hint Name Table.  */
870       id6 = pe_ILF_make_a_section (& vars, ".idata$6", SIZEOF_IDATA6, 0);
871       if (id6 == NULL)
872         return FALSE;
873
874       /* If necessary, trim the import symbol name.  */
875       symbol = symbol_name;
876
877       if (import_name_type != IMPORT_NAME)
878         {
879           bfd_boolean skipped_leading_underscore = FALSE;
880           bfd_boolean skipped_leading_at = FALSE;
881           bfd_boolean skipped_leading_question_mark = FALSE;
882           bfd_boolean check_again;
883           
884           /* Skip any prefix in symbol_name.  */
885           -- symbol;
886           do
887             {
888               check_again = FALSE;
889               ++ symbol;
890
891               switch (*symbol)
892                 {
893                 case '@':
894                   if (! skipped_leading_at)
895                     check_again = skipped_leading_at = TRUE;
896                   break;
897                 case '?':
898                   if (! skipped_leading_question_mark)
899                     check_again = skipped_leading_question_mark = TRUE;
900                   break;
901                 case '_':
902                   if (! skipped_leading_underscore)
903                     check_again = skipped_leading_underscore = TRUE;
904                   break;
905                 default:
906                   break;
907                 }
908             }
909           while (check_again);
910         }
911       
912       if (import_name_type == IMPORT_NAME_UNDECORATE)
913         {
914           /* Truncate at the first '@'  */
915           while (* symbol != 0 && * symbol != '@')
916             symbol ++;
917
918           * symbol = 0;
919         }
920
921       id6->contents[0] = ordinal & 0xff;
922       id6->contents[1] = ordinal >> 8;
923
924       strcpy ((char *) id6->contents + 2, symbol);
925     }
926
927   if (import_name_type != IMPORT_ORDINAL)
928     {
929       pe_ILF_make_a_reloc (&vars, (bfd_vma) 0, BFD_RELOC_RVA, id6);
930       pe_ILF_save_relocs (&vars, id4);
931
932       pe_ILF_make_a_reloc (&vars, (bfd_vma) 0, BFD_RELOC_RVA, id6);
933       pe_ILF_save_relocs (&vars, id5);
934     }
935
936   /* Create extra sections depending upon the type of import we are dealing with.  */
937   switch (import_type)
938     {
939       int i;
940
941     case IMPORT_CODE:
942       /* Create a .text section.
943          First we need to look up its contents in the jump table.  */
944       for (i = NUM_ENTRIES (jtab); i--;)
945         {
946           if (jtab[i].size == 0)
947             continue;
948           if (jtab[i].magic == magic)
949             break;
950         }
951       /* If we did not find a matching entry something is wrong.  */
952       if (i < 0)
953         abort ();
954
955       /* Create the .text section.  */
956       text = pe_ILF_make_a_section (& vars, ".text", jtab[i].size, SEC_CODE);
957       if (text == NULL)
958         return FALSE;
959
960       /* Copy in the jump code.  */
961       memcpy (text->contents, jtab[i].data, jtab[i].size);
962
963       /* Create an import symbol.  */
964       pe_ILF_make_a_symbol (& vars, "__imp_", symbol_name, id5, 0);
965       imp_sym   = vars.sym_ptr_ptr - 1;
966       imp_index = vars.sym_index - 1;
967
968       /* Create a reloc for the data in the text section.  */
969 #ifdef MIPS_ARCH_MAGIC_WINCE
970       if (magic == MIPS_ARCH_MAGIC_WINCE)
971         {
972           pe_ILF_make_a_symbol_reloc (&vars, (bfd_vma) 0, BFD_RELOC_HI16_S,
973                                       (struct bfd_symbol **) imp_sym,
974                                       imp_index);
975           pe_ILF_make_a_reloc (&vars, (bfd_vma) 0, BFD_RELOC_LO16, text);
976           pe_ILF_make_a_symbol_reloc (&vars, (bfd_vma) 4, BFD_RELOC_LO16,
977                                       (struct bfd_symbol **) imp_sym,
978                                       imp_index);
979         }
980       else
981 #endif
982         pe_ILF_make_a_symbol_reloc (&vars, (bfd_vma) jtab[i].offset,
983                                     BFD_RELOC_32, (asymbol **) imp_sym,
984                                     imp_index);
985
986       pe_ILF_save_relocs (& vars, text);
987       break;
988
989     case IMPORT_DATA:
990       break;
991
992     default:
993       /* XXX code not yet written.  */
994       abort ();
995     }
996
997   /* Initialise the bfd.  */
998   memset (& internal_f, 0, sizeof (internal_f));
999
1000   internal_f.f_magic  = magic;
1001   internal_f.f_symptr = 0;
1002   internal_f.f_nsyms  = 0;
1003   internal_f.f_flags  = F_AR32WR | F_LNNO; /* XXX is this correct ?  */
1004
1005   if (   ! bfd_set_start_address (abfd, (bfd_vma) 0)
1006       || ! bfd_coff_set_arch_mach_hook (abfd, & internal_f))
1007     return FALSE;
1008
1009   if (bfd_coff_mkobject_hook (abfd, (PTR) & internal_f, NULL) == NULL)
1010     return FALSE;
1011
1012   coff_data (abfd)->pe = 1;
1013 #ifdef THUMBPEMAGIC
1014   if (vars.magic == THUMBPEMAGIC)
1015     /* Stop some linker warnings about thumb code not supporting interworking.  */
1016     coff_data (abfd)->flags |= F_INTERWORK | F_INTERWORK_SET;
1017 #endif
1018
1019   /* Switch from file contents to memory contents.  */
1020   bfd_cache_close (abfd);
1021
1022   abfd->iostream = (PTR) vars.bim;
1023   abfd->flags |= BFD_IN_MEMORY /* | HAS_LOCALS */;
1024   abfd->where = 0;
1025   obj_sym_filepos (abfd) = 0;
1026
1027   /* Now create a symbol describing the imported value.  */
1028   switch (import_type)
1029     {
1030     case IMPORT_CODE:
1031       pe_ILF_make_a_symbol (& vars, "", symbol_name, text,
1032                             BSF_NOT_AT_END | BSF_FUNCTION);
1033
1034       /* Create an import symbol for the DLL, without the
1035        .dll suffix.  */
1036       ptr = (bfd_byte *) strrchr (source_dll, '.');
1037       if (ptr)
1038         * ptr = 0;
1039       pe_ILF_make_a_symbol (& vars, "__IMPORT_DESCRIPTOR_", source_dll, NULL, 0);
1040       if (ptr)
1041         * ptr = '.';
1042       break;
1043
1044     case IMPORT_DATA:
1045       /* Nothing to do here.  */
1046       break;
1047
1048     default:
1049       /* XXX code not yet written.  */
1050       abort ();
1051     }
1052
1053   /* Point the bfd at the symbol table.  */
1054   obj_symbols (abfd) = vars.sym_cache;
1055   bfd_get_symcount (abfd) = vars.sym_index;
1056
1057   obj_raw_syments (abfd) = vars.native_syms;
1058   obj_raw_syment_count (abfd) = vars.sym_index;
1059
1060   obj_coff_external_syms (abfd) = (PTR) vars.esym_table;
1061   obj_coff_keep_syms (abfd) = TRUE;
1062
1063   obj_convert (abfd) = vars.sym_table;
1064   obj_conv_table_size (abfd) = vars.sym_index;
1065
1066   obj_coff_strings (abfd) = vars.string_table;
1067   obj_coff_keep_strings (abfd) = TRUE;
1068
1069   abfd->flags |= HAS_SYMS;
1070
1071   return TRUE;
1072 }
1073
1074 /* We have detected a Image Library Format archive element.
1075    Decode the element and return the appropriate target.  */
1076 static const bfd_target *
1077 pe_ILF_object_p (bfd * abfd)
1078 {
1079   bfd_byte        buffer[16];
1080   bfd_byte *      ptr;
1081   char *          symbol_name;
1082   char *          source_dll;
1083   unsigned int    machine;
1084   bfd_size_type   size;
1085   unsigned int    ordinal;
1086   unsigned int    types;
1087   unsigned int    magic;
1088
1089   /* Upon entry the first four buyes of the ILF header have
1090       already been read.  Now read the rest of the header.  */
1091   if (bfd_bread (buffer, (bfd_size_type) 16, abfd) != 16)
1092     return NULL;
1093
1094   ptr = buffer;
1095
1096   /*  We do not bother to check the version number.
1097       version = H_GET_16 (abfd, ptr);  */
1098   ptr += 2;
1099
1100   machine = H_GET_16 (abfd, ptr);
1101   ptr += 2;
1102
1103   /* Check that the machine type is recognised.  */
1104   magic = 0;
1105
1106   switch (machine)
1107     {
1108     case IMAGE_FILE_MACHINE_UNKNOWN:
1109     case IMAGE_FILE_MACHINE_ALPHA:
1110     case IMAGE_FILE_MACHINE_ALPHA64:
1111     case IMAGE_FILE_MACHINE_IA64:
1112       break;
1113
1114     case IMAGE_FILE_MACHINE_I386:
1115 #ifdef I386MAGIC
1116       magic = I386MAGIC;
1117 #endif
1118       break;
1119
1120     case IMAGE_FILE_MACHINE_M68K:
1121 #ifdef MC68AGIC
1122       magic = MC68MAGIC;
1123 #endif
1124       break;
1125
1126     case IMAGE_FILE_MACHINE_R3000:
1127     case IMAGE_FILE_MACHINE_R4000:
1128     case IMAGE_FILE_MACHINE_R10000:
1129
1130     case IMAGE_FILE_MACHINE_MIPS16:
1131     case IMAGE_FILE_MACHINE_MIPSFPU:
1132     case IMAGE_FILE_MACHINE_MIPSFPU16:
1133 #ifdef MIPS_ARCH_MAGIC_WINCE
1134       magic = MIPS_ARCH_MAGIC_WINCE;
1135 #endif
1136       break;
1137
1138     case IMAGE_FILE_MACHINE_SH3:
1139     case IMAGE_FILE_MACHINE_SH4:
1140 #ifdef SH_ARCH_MAGIC_WINCE
1141       magic = SH_ARCH_MAGIC_WINCE;
1142 #endif
1143       break;
1144
1145     case IMAGE_FILE_MACHINE_ARM:
1146 #ifdef ARMPEMAGIC
1147       magic = ARMPEMAGIC;
1148 #endif
1149       break;
1150
1151     case IMAGE_FILE_MACHINE_THUMB:
1152 #ifdef THUMBPEMAGIC
1153       {
1154         extern const bfd_target TARGET_LITTLE_SYM;
1155
1156         if (abfd->xvec == & TARGET_LITTLE_SYM)
1157           magic = THUMBPEMAGIC;
1158       }
1159 #endif
1160       break;
1161
1162     case IMAGE_FILE_MACHINE_POWERPC:
1163       /* We no longer support PowerPC.  */
1164     default:
1165       _bfd_error_handler
1166         (_("%B: Unrecognised machine type (0x%x)"
1167            " in Import Library Format archive"),
1168          abfd, machine);
1169       bfd_set_error (bfd_error_malformed_archive);
1170
1171       return NULL;
1172       break;
1173     }
1174
1175   if (magic == 0)
1176     {
1177       _bfd_error_handler
1178         (_("%B: Recognised but unhandled machine type (0x%x)"
1179            " in Import Library Format archive"),
1180          abfd, machine);
1181       bfd_set_error (bfd_error_wrong_format);
1182
1183       return NULL;
1184     }
1185
1186   /* We do not bother to check the date.
1187      date = H_GET_32 (abfd, ptr);  */
1188   ptr += 4;
1189
1190   size = H_GET_32 (abfd, ptr);
1191   ptr += 4;
1192
1193   if (size == 0)
1194     {
1195       _bfd_error_handler
1196         (_("%B: size field is zero in Import Library Format header"), abfd);
1197       bfd_set_error (bfd_error_malformed_archive);
1198
1199       return NULL;
1200     }
1201
1202   ordinal = H_GET_16 (abfd, ptr);
1203   ptr += 2;
1204
1205   types = H_GET_16 (abfd, ptr);
1206   /* ptr += 2; */
1207
1208   /* Now read in the two strings that follow.  */
1209   ptr = bfd_alloc (abfd, size);
1210   if (ptr == NULL)
1211     return NULL;
1212
1213   if (bfd_bread (ptr, size, abfd) != size)
1214     {
1215       bfd_release (abfd, ptr);
1216       return NULL;
1217     }
1218
1219   symbol_name = (char *) ptr;
1220   source_dll  = symbol_name + strlen (symbol_name) + 1;
1221
1222   /* Verify that the strings are null terminated.  */
1223   if (ptr[size - 1] != 0
1224       || (bfd_size_type) ((bfd_byte *) source_dll - ptr) >= size)
1225     {
1226       _bfd_error_handler
1227         (_("%B: string not null terminated in ILF object file."), abfd);
1228       bfd_set_error (bfd_error_malformed_archive);
1229       bfd_release (abfd, ptr);
1230       return NULL;
1231     }
1232
1233   /* Now construct the bfd.  */
1234   if (! pe_ILF_build_a_bfd (abfd, magic, symbol_name,
1235                             source_dll, ordinal, types))
1236     {
1237       bfd_release (abfd, ptr);
1238       return NULL;
1239     }
1240
1241   return abfd->xvec;
1242 }
1243
1244 static const bfd_target *
1245 pe_bfd_object_p (bfd * abfd)
1246 {
1247   bfd_byte buffer[4];
1248   struct external_PEI_DOS_hdr dos_hdr;
1249   struct external_PEI_IMAGE_hdr image_hdr;
1250   file_ptr offset;
1251
1252   /* Detect if this a Microsoft Import Library Format element.  */
1253   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0
1254       || bfd_bread (buffer, (bfd_size_type) 4, abfd) != 4)
1255     {
1256       if (bfd_get_error () != bfd_error_system_call)
1257         bfd_set_error (bfd_error_wrong_format);
1258       return NULL;
1259     }
1260
1261   if (H_GET_32 (abfd, buffer) == 0xffff0000)
1262     return pe_ILF_object_p (abfd);
1263
1264   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0
1265       || bfd_bread (&dos_hdr, (bfd_size_type) sizeof (dos_hdr), abfd)
1266          != sizeof (dos_hdr))
1267     {
1268       if (bfd_get_error () != bfd_error_system_call)
1269         bfd_set_error (bfd_error_wrong_format);
1270       return NULL;
1271     }
1272
1273   /* There are really two magic numbers involved; the magic number
1274      that says this is a NT executable (PEI) and the magic number that
1275      determines the architecture.  The former is DOSMAGIC, stored in
1276      the e_magic field.  The latter is stored in the f_magic field.
1277      If the NT magic number isn't valid, the architecture magic number
1278      could be mimicked by some other field (specifically, the number
1279      of relocs in section 3).  Since this routine can only be called
1280      correctly for a PEI file, check the e_magic number here, and, if
1281      it doesn't match, clobber the f_magic number so that we don't get
1282      a false match.  */
1283   if (H_GET_16 (abfd, dos_hdr.e_magic) != DOSMAGIC)
1284     {
1285       bfd_set_error (bfd_error_wrong_format);
1286       return NULL;
1287     }
1288
1289   offset = H_GET_32 (abfd, dos_hdr.e_lfanew);
1290   if (bfd_seek (abfd, offset, SEEK_SET) != 0
1291       || (bfd_bread (&image_hdr, (bfd_size_type) sizeof (image_hdr), abfd)
1292           != sizeof (image_hdr)))
1293     {
1294       if (bfd_get_error () != bfd_error_system_call)
1295         bfd_set_error (bfd_error_wrong_format);
1296       return NULL;
1297     }
1298
1299   if (H_GET_32 (abfd, image_hdr.nt_signature) != 0x4550)
1300     {
1301       bfd_set_error (bfd_error_wrong_format);
1302       return NULL;
1303     }
1304
1305   /* Here is the hack.  coff_object_p wants to read filhsz bytes to
1306      pick up the COFF header for PE, see "struct external_PEI_filehdr"
1307      in include/coff/pe.h.  We adjust so that that will work. */
1308   if (bfd_seek (abfd, (file_ptr) (offset - sizeof (dos_hdr)), SEEK_SET) != 0)
1309     {
1310       if (bfd_get_error () != bfd_error_system_call)
1311         bfd_set_error (bfd_error_wrong_format);
1312       return NULL;
1313     }
1314
1315   return coff_object_p (abfd);
1316 }
1317
1318 #define coff_object_p pe_bfd_object_p
1319 #endif /* COFF_IMAGE_WITH_PE */