2008-11-14 Kai Tietz <kai.tietz@onevision.com>
[external/binutils.git] / ld / pe-dll.c
1 /* Routines to help build PEI-format DLLs (Win32 etc)
2    Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3    2008 Free Software Foundation, Inc.
4    Written by DJ Delorie <dj@cygnus.com>
5
6    This file is part of the GNU Binutils.
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 3 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,
21    MA 02110-1301, USA.  */
22
23 #include "sysdep.h"
24 #include "bfd.h"
25 #include "bfdlink.h"
26 #include "libiberty.h"
27 #include "safe-ctype.h"
28
29 #include <time.h>
30
31 #include "ld.h"
32 #include "ldexp.h"
33 #include "ldlang.h"
34 #include "ldwrite.h"
35 #include "ldmisc.h"
36 #include <ldgram.h>
37 #include "ldmain.h"
38 #include "ldfile.h"
39 #include "ldemul.h"
40 #include "coff/internal.h"
41 #include "../bfd/libcoff.h"
42 #include "deffile.h"
43
44 #ifdef pe_use_x86_64
45
46 #define PE_IDATA4_SIZE  8
47 #define PE_IDATA5_SIZE  8
48 #include "pep-dll.h"
49 #undef  AOUTSZ
50 #define AOUTSZ          PEPAOUTSZ
51 #define PEAOUTHDR       PEPAOUTHDR
52
53 #else
54
55 #include "pe-dll.h"
56
57 #endif
58
59 #ifndef PE_IDATA4_SIZE
60 #define PE_IDATA4_SIZE  4
61 #endif
62
63 #ifndef PE_IDATA5_SIZE
64 #define PE_IDATA5_SIZE  4
65 #endif
66
67 /*  This file turns a regular Windows PE image into a DLL.  Because of
68     the complexity of this operation, it has been broken down into a
69     number of separate modules which are all called by the main function
70     at the end of this file.  This function is not re-entrant and is
71     normally only called once, so static variables are used to reduce
72     the number of parameters and return values required.
73
74     See also: ld/emultempl/pe.em and ld/emultempl/pep.em.  */
75
76 /*  Auto-import feature by Paul Sokolovsky
77
78     Quick facts:
79
80     1. With this feature on, DLL clients can import variables from DLL
81     without any concern from their side (for example, without any source
82     code modifications).
83
84     2. This is done completely in bounds of the PE specification (to be fair,
85     there's a place where it pokes nose out of, but in practice it works).
86     So, resulting module can be used with any other PE compiler/linker.
87
88     3. Auto-import is fully compatible with standard import method and they
89     can be mixed together.
90
91     4. Overheads: space: 8 bytes per imported symbol, plus 20 for each
92     reference to it; load time: negligible; virtual/physical memory: should be
93     less than effect of DLL relocation, and I sincerely hope it doesn't affect
94     DLL sharability (too much).
95
96     Idea
97
98     The obvious and only way to get rid of dllimport insanity is to make client
99     access variable directly in the DLL, bypassing extra dereference. I.e.,
100     whenever client contains something like
101
102     mov dll_var,%eax,
103
104     address of dll_var in the command should be relocated to point into loaded
105     DLL. The aim is to make OS loader do so, and than make ld help with that.
106     Import section of PE made following way: there's a vector of structures
107     each describing imports from particular DLL. Each such structure points
108     to two other parallel vectors: one holding imported names, and one which
109     will hold address of corresponding imported name. So, the solution is
110     de-vectorize these structures, making import locations be sparse and
111     pointing directly into code. Before continuing, it is worth a note that,
112     while authors strives to make PE act ELF-like, there're some other people
113     make ELF act PE-like: elfvector, ;-) .
114
115     Implementation
116
117     For each reference of data symbol to be imported from DLL (to set of which
118     belong symbols with name <sym>, if __imp_<sym> is found in implib), the
119     import fixup entry is generated. That entry is of type
120     IMAGE_IMPORT_DESCRIPTOR and stored in .idata$2 subsection. Each
121     fixup entry contains pointer to symbol's address within .text section
122     (marked with __fuN_<sym> symbol, where N is integer), pointer to DLL name
123     (so, DLL name is referenced by multiple entries), and pointer to symbol
124     name thunk. Symbol name thunk is singleton vector (__nm_th_<symbol>)
125     pointing to IMAGE_IMPORT_BY_NAME structure (__nm_<symbol>) directly
126     containing imported name. Here comes that "on the edge" problem mentioned
127     above: PE specification rambles that name vector (OriginalFirstThunk)
128     should run in parallel with addresses vector (FirstThunk), i.e. that they
129     should have same number of elements and terminated with zero. We violate
130     this, since FirstThunk points directly into machine code. But in practice,
131     OS loader implemented the sane way: it goes thru OriginalFirstThunk and
132     puts addresses to FirstThunk, not something else. It once again should be
133     noted that dll and symbol name structures are reused across fixup entries
134     and should be there anyway to support standard import stuff, so sustained
135     overhead is 20 bytes per reference. Other question is whether having several
136     IMAGE_IMPORT_DESCRIPTORS for the same DLL is possible. Answer is yes, it is
137     done even by native compiler/linker (libth32's functions are in fact reside
138     in windows9x kernel32.dll, so if you use it, you have two
139     IMAGE_IMPORT_DESCRIPTORS for kernel32.dll). Yet other question is whether
140     referencing the same PE structures several times is valid. The answer is why
141     not, prohibiting that (detecting violation) would require more work on
142     behalf of loader than not doing it.
143
144     See also: ld/emultempl/pe.em and ld/emultempl/pep.em.  */
145
146 static void add_bfd_to_link (bfd *, const char *, struct bfd_link_info *);
147
148 /* For emultempl/pe.em.  */
149
150 def_file * pe_def_file = 0;
151 int pe_dll_export_everything = 0;
152 int pe_dll_do_default_excludes = 1;
153 int pe_dll_kill_ats = 0;
154 int pe_dll_stdcall_aliases = 0;
155 int pe_dll_warn_dup_exports = 0;
156 int pe_dll_compat_implib = 0;
157 int pe_dll_extra_pe_debug = 0;
158
159 /* Static variables and types.  */
160
161 static bfd_vma image_base;
162 static bfd *filler_bfd;
163 static struct bfd_section *edata_s, *reloc_s;
164 static unsigned char *edata_d, *reloc_d;
165 static size_t edata_sz, reloc_sz;
166 static int runtime_pseudo_relocs_created = 0;
167 static int runtime_pseudp_reloc_v2_init = 0;
168
169 typedef struct
170 {
171   const char *name;
172   int len;
173 }
174 autofilter_entry_type;
175
176 typedef struct
177 {
178   const char *target_name;
179   const char *object_target;
180   unsigned int imagebase_reloc;
181   int pe_arch;
182   int bfd_arch;
183   bfd_boolean underscored;
184   const autofilter_entry_type* autofilter_symbollist; 
185 }
186 pe_details_type;
187
188 static const autofilter_entry_type autofilter_symbollist_generic[] =
189 {
190   { STRING_COMMA_LEN ("_NULL_IMPORT_DESCRIPTOR") },
191   /* Entry point symbols.  */
192   { STRING_COMMA_LEN ("DllMain") },
193   { STRING_COMMA_LEN ("DllMainCRTStartup") },
194   { STRING_COMMA_LEN ("_DllMainCRTStartup") },
195   /* Runtime pseudo-reloc.  */
196   { STRING_COMMA_LEN ("_pei386_runtime_relocator") },
197   { STRING_COMMA_LEN ("do_pseudo_reloc") },
198   { NULL, 0 }
199 };
200
201 static const autofilter_entry_type autofilter_symbollist_i386[] =
202 {
203   { STRING_COMMA_LEN ("_NULL_IMPORT_DESCRIPTOR") },
204   /* Entry point symbols, and entry hooks.  */
205   { STRING_COMMA_LEN ("cygwin_crt0") },
206 #ifdef pe_use_x86_64
207   { STRING_COMMA_LEN ("DllMain") },
208   { STRING_COMMA_LEN ("DllEntryPoint") },
209   { STRING_COMMA_LEN ("DllMainCRTStartup") },
210   { STRING_COMMA_LEN ("_cygwin_dll_entry") },
211   { STRING_COMMA_LEN ("_cygwin_crt0_common") },
212   { STRING_COMMA_LEN ("_cygwin_noncygwin_dll_entry") },
213 #else
214   { STRING_COMMA_LEN ("DllMain@12") },
215   { STRING_COMMA_LEN ("DllEntryPoint@0") },
216   { STRING_COMMA_LEN ("DllMainCRTStartup@12") },
217   { STRING_COMMA_LEN ("_cygwin_dll_entry@12") },
218   { STRING_COMMA_LEN ("_cygwin_crt0_common@8") },
219   { STRING_COMMA_LEN ("_cygwin_noncygwin_dll_entry@12") },
220   { STRING_COMMA_LEN ("cygwin_attach_dll") },
221 #endif  
222   { STRING_COMMA_LEN ("cygwin_premain0") },
223   { STRING_COMMA_LEN ("cygwin_premain1") },
224   { STRING_COMMA_LEN ("cygwin_premain2") },
225   { STRING_COMMA_LEN ("cygwin_premain3") },
226   /* Runtime pseudo-reloc.  */
227   { STRING_COMMA_LEN ("_pei386_runtime_relocator") },
228   { STRING_COMMA_LEN ("do_pseudo_reloc") },
229   /* Global vars that should not be exported.  */
230   { STRING_COMMA_LEN ("impure_ptr") },
231   { STRING_COMMA_LEN ("_impure_ptr") },
232   { STRING_COMMA_LEN ("_fmode") },
233   { STRING_COMMA_LEN ("environ") },
234   { NULL, 0 }
235 };
236
237 #define PE_ARCH_i386     1
238 #define PE_ARCH_sh       2
239 #define PE_ARCH_mips     3
240 #define PE_ARCH_arm      4
241 #define PE_ARCH_arm_epoc 5
242 #define PE_ARCH_arm_wince 6
243
244 static const pe_details_type pe_detail_list[] =
245 {
246   {
247 #ifdef pe_use_x86_64
248     "pei-x86-64",
249     "pe-x86-64",
250     3 /* R_IMAGEBASE */,
251 #else
252     "pei-i386",
253     "pe-i386",
254     7 /* R_IMAGEBASE */,
255 #endif
256     PE_ARCH_i386,
257     bfd_arch_i386,
258     TRUE,
259     autofilter_symbollist_i386
260   },
261   {
262     "pei-shl",
263     "pe-shl",
264     16 /* R_SH_IMAGEBASE */,
265     PE_ARCH_sh,
266     bfd_arch_sh,
267     TRUE,
268     autofilter_symbollist_generic
269   },
270   {
271     "pei-mips",
272     "pe-mips",
273     34 /* MIPS_R_RVA */,
274     PE_ARCH_mips,
275     bfd_arch_mips,
276     FALSE,
277     autofilter_symbollist_generic
278   },
279   {
280     "pei-arm-little",
281     "pe-arm-little",
282     11 /* ARM_RVA32 */,
283     PE_ARCH_arm,
284     bfd_arch_arm,
285     TRUE,
286     autofilter_symbollist_generic
287   },
288   {
289     "epoc-pei-arm-little",
290     "epoc-pe-arm-little",
291     11 /* ARM_RVA32 */,
292     PE_ARCH_arm_epoc,
293     bfd_arch_arm,
294     FALSE,
295     autofilter_symbollist_generic
296   },
297   {
298     "pei-arm-wince-little",
299     "pe-arm-wince-little",
300     2,  /* ARM_RVA32 on Windows CE, see bfd/coff-arm.c.  */
301     PE_ARCH_arm_wince,
302     bfd_arch_arm,
303     FALSE,
304     autofilter_symbollist_generic
305   },
306   { NULL, NULL, 0, 0, 0, FALSE, NULL }
307 };
308
309 static const pe_details_type *pe_details;
310
311 /* Do not specify library suffix explicitly, to allow for dllized versions.  */
312 static const autofilter_entry_type autofilter_liblist[] =
313 {
314   { STRING_COMMA_LEN ("libcegcc") },
315   { STRING_COMMA_LEN ("libcygwin") },
316   { STRING_COMMA_LEN ("libgcc") },
317   { STRING_COMMA_LEN ("libstdc++") },
318   { STRING_COMMA_LEN ("libmingw32") },
319   { STRING_COMMA_LEN ("libmingwex") },
320   { STRING_COMMA_LEN ("libg2c") },
321   { STRING_COMMA_LEN ("libsupc++") },
322   { STRING_COMMA_LEN ("libobjc") },
323   { STRING_COMMA_LEN ("libgcj") },
324   { NULL, 0 }
325 };
326
327 static const autofilter_entry_type autofilter_objlist[] =
328 {
329   { STRING_COMMA_LEN ("crt0.o") },
330   { STRING_COMMA_LEN ("crt1.o") },
331   { STRING_COMMA_LEN ("crt2.o") },
332   { STRING_COMMA_LEN ("dllcrt1.o") },
333   { STRING_COMMA_LEN ("dllcrt2.o") },
334   { STRING_COMMA_LEN ("gcrt0.o") },
335   { STRING_COMMA_LEN ("gcrt1.o") },
336   { STRING_COMMA_LEN ("gcrt2.o") },
337   { STRING_COMMA_LEN ("crtbegin.o") },
338   { STRING_COMMA_LEN ("crtend.o") },
339   { NULL, 0 }
340 };
341
342 static const autofilter_entry_type autofilter_symbolprefixlist[] =
343 {
344   /* _imp_ is treated specially, as it is always underscored.  */
345   /* { STRING_COMMA_LEN ("_imp_") },  */
346   /* Don't export some c++ symbols.  */
347   { STRING_COMMA_LEN ("__rtti_") },
348   { STRING_COMMA_LEN ("__builtin_") },
349   /* Don't re-export auto-imported symbols.  */
350   { STRING_COMMA_LEN ("_nm_") },
351   /* Don't export symbols specifying internal DLL layout.  */
352   { STRING_COMMA_LEN ("_head_") },
353   { STRING_COMMA_LEN ("_IMPORT_DESCRIPTOR_") },
354   /* Don't export section labels or artificial symbols
355   (eg ".weak.foo".  */
356   { STRING_COMMA_LEN (".") },
357   { NULL, 0 }
358 };
359
360 static const autofilter_entry_type autofilter_symbolsuffixlist[] =
361 {
362   { STRING_COMMA_LEN ("_iname") },
363   { STRING_COMMA_LEN ("_NULL_THUNK_DATA") },
364   { NULL, 0 }
365 };
366
367 #define U(str) (pe_details->underscored ? "_" str : str)
368
369 void
370 pe_dll_id_target (const char *target)
371 {
372   int i;
373
374   for (i = 0; pe_detail_list[i].target_name; i++)
375     if (strcmp (pe_detail_list[i].target_name, target) == 0
376         || strcmp (pe_detail_list[i].object_target, target) == 0)
377       {
378         pe_details = pe_detail_list + i;
379         return;
380       }
381   einfo (_("%XUnsupported PEI architecture: %s\n"), target);
382   exit (1);
383 }
384
385 /* Helper functions for qsort.  Relocs must be sorted so that we can write
386    them out by pages.  */
387
388 typedef struct
389   {
390     bfd_vma vma;
391     char type;
392     short extra;
393   }
394 reloc_data_type;
395
396 static int
397 reloc_sort (const void *va, const void *vb)
398 {
399   bfd_vma a = ((const reloc_data_type *) va)->vma;
400   bfd_vma b = ((const reloc_data_type *) vb)->vma;
401
402   return (a > b) ? 1 : ((a < b) ? -1 : 0);
403 }
404
405 static int
406 pe_export_sort (const void *va, const void *vb)
407 {
408   const def_file_export *a = va;
409   const def_file_export *b = vb;
410
411   return strcmp (a->name, b->name);
412 }
413
414 /* Read and process the .DEF file.  */
415
416 /* These correspond to the entries in pe_def_file->exports[].  I use
417    exported_symbol_sections[i] to tag whether or not the symbol was
418    defined, since we can't export symbols we don't have.  */
419
420 static bfd_vma *exported_symbol_offsets;
421 static struct bfd_section **exported_symbol_sections;
422 static int export_table_size;
423 static int count_exported;
424 static int count_exported_byname;
425 static int count_with_ordinals;
426 static const char *dll_name;
427 static int min_ordinal, max_ordinal;
428 static int *exported_symbols;
429
430 typedef struct exclude_list_struct
431   {
432     char *string;
433     struct exclude_list_struct *next;
434     int type;
435   }
436 exclude_list_struct;
437
438 static struct exclude_list_struct *excludes = 0;
439
440 void
441 pe_dll_add_excludes (const char *new_excludes, const int type)
442 {
443   char *local_copy;
444   char *exclude_string;
445
446   local_copy = xstrdup (new_excludes);
447
448   exclude_string = strtok (local_copy, ",:");
449   for (; exclude_string; exclude_string = strtok (NULL, ",:"))
450     {
451       struct exclude_list_struct *new_exclude;
452
453       new_exclude = xmalloc (sizeof (struct exclude_list_struct));
454       new_exclude->string = xmalloc (strlen (exclude_string) + 1);
455       strcpy (new_exclude->string, exclude_string);
456       new_exclude->type = type;
457       new_exclude->next = excludes;
458       excludes = new_exclude;
459     }
460
461   free (local_copy);
462 }
463
464 static bfd_boolean
465 is_import (const char* n)
466 {
467   return (CONST_STRNEQ (n, "__imp_"));
468 }
469
470 /* abfd is a bfd containing n (or NULL)
471    It can be used for contextual checks.  */
472
473 static int
474 auto_export (bfd *abfd, def_file *d, const char *n)
475 {
476   int i;
477   struct exclude_list_struct *ex;
478   const autofilter_entry_type *afptr;
479   const char * libname = 0;
480   if (abfd && abfd->my_archive)
481     libname = lbasename (abfd->my_archive->filename);
482
483   for (i = 0; i < d->num_exports; i++)
484     if (strcmp (d->exports[i].name, n) == 0)
485       return 0;
486
487   if (pe_dll_do_default_excludes)
488     {
489       const char * p;
490       int    len;
491
492       if (pe_dll_extra_pe_debug)
493         printf ("considering exporting: %s, abfd=%p, abfd->my_arc=%p\n",
494                 n, abfd, abfd->my_archive);
495
496       /* First of all, make context checks:
497          Don't export anything from standard libs.  */
498       if (libname)
499         {
500           afptr = autofilter_liblist;
501
502           while (afptr->name)
503             {
504               if (strncmp (libname, afptr->name, afptr->len) == 0 )
505                 return 0;
506               afptr++;
507             }
508         }
509
510       /* Next, exclude symbols from certain startup objects.  */
511
512       if (abfd && (p = lbasename (abfd->filename)))
513         {
514           afptr = autofilter_objlist;
515           while (afptr->name)
516             {
517               if (strcmp (p, afptr->name) == 0)
518                 return 0;
519               afptr++;
520             }
521         }
522
523       /* Don't try to blindly exclude all symbols
524          that begin with '__'; this was tried and
525          it is too restrictive.  Instead we have
526          a target specific list to use:  */
527       afptr = pe_details->autofilter_symbollist; 
528
529       while (afptr->name)
530         {
531           if (strcmp (n, afptr->name) == 0)
532             return 0;
533
534           afptr++;
535         }
536
537       /* Next, exclude symbols starting with ...  */
538       afptr = autofilter_symbolprefixlist;
539       while (afptr->name)
540         {
541           if (strncmp (n, afptr->name, afptr->len) == 0)
542             return 0;
543
544           afptr++;
545         }
546
547       /* Finally, exclude symbols ending with ...  */
548       len = strlen (n);
549       afptr = autofilter_symbolsuffixlist;
550       while (afptr->name)
551         {
552           if ((len >= afptr->len)
553               /* Add 1 to insure match with trailing '\0'.  */
554               && strncmp (n + len - afptr->len, afptr->name,
555                           afptr->len + 1) == 0)
556             return 0;
557
558           afptr++;
559         }
560     }
561
562   for (ex = excludes; ex; ex = ex->next)
563     {
564       if (ex->type == 1) /* exclude-libs */
565         {
566           if (libname
567               && ((strcmp (libname, ex->string) == 0)
568                    || (strcasecmp ("ALL", ex->string) == 0)))
569             return 0;
570         }
571       else if (strcmp (n, ex->string) == 0)
572         return 0;
573     }
574
575   return 1;
576 }
577
578 static void
579 process_def_file (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
580 {
581   int i, j;
582   struct bfd_link_hash_entry *blhe;
583   bfd *b;
584   struct bfd_section *s;
585   def_file_export *e = 0;
586
587   if (!pe_def_file)
588     pe_def_file = def_file_empty ();
589
590   /* First, run around to all the objects looking for the .drectve
591      sections, and push those into the def file too.  */
592   for (b = info->input_bfds; b; b = b->link_next)
593     {
594       s = bfd_get_section_by_name (b, ".drectve");
595       if (s)
596         {
597           long size = s->size;
598           char *buf = xmalloc (size);
599
600           bfd_get_section_contents (b, s, buf, 0, size);
601           def_file_add_directive (pe_def_file, buf, size);
602           free (buf);
603         }
604     }
605
606   /* If we are not building a DLL, when there are no exports
607      we do not build an export table at all.  */
608   if (!pe_dll_export_everything && pe_def_file->num_exports == 0
609       && info->executable)
610     return;
611
612   /* Now, maybe export everything else the default way.  */
613   if (pe_dll_export_everything || pe_def_file->num_exports == 0)
614     {
615       for (b = info->input_bfds; b; b = b->link_next)
616         {
617           asymbol **symbols;
618           int nsyms;
619
620           if (!bfd_generic_link_read_symbols (b))
621             {
622               einfo (_("%B%F: could not read symbols: %E\n"), b);
623               return;
624             }
625
626           symbols = bfd_get_outsymbols (b);
627           nsyms = bfd_get_symcount (b);
628
629           for (j = 0; j < nsyms; j++)
630             {
631               /* We should export symbols which are either global or not
632                  anything at all.  (.bss data is the latter)
633                  We should not export undefined symbols.  */
634               if (symbols[j]->section != &bfd_und_section
635                   && ((symbols[j]->flags & BSF_GLOBAL)
636                       || (symbols[j]->flags == BFD_FORT_COMM_DEFAULT_VALUE)))
637                 {
638                   const char *sn = symbols[j]->name;
639
640                   /* We should not re-export imported stuff.  */
641                   {
642                     char *name;
643                     if (is_import (sn))
644                           continue;
645
646                     name = xmalloc (strlen ("__imp_") + strlen (sn) + 1);
647                     sprintf (name, "%s%s", "__imp_", sn);
648
649                     blhe = bfd_link_hash_lookup (info->hash, name,
650                                                  FALSE, FALSE, FALSE);
651                     free (name);
652
653                     if (blhe && blhe->type == bfd_link_hash_defined)
654                       continue;
655                   }
656
657                   if (pe_details->underscored && *sn == '_')
658                     sn++;
659
660                   if (auto_export (b, pe_def_file, sn))
661                     {
662                       def_file_export *p;
663                       p=def_file_add_export (pe_def_file, sn, 0, -1);
664                       /* Fill data flag properly, from dlltool.c.  */
665                       p->flag_data = !(symbols[j]->flags & BSF_FUNCTION);
666                     }
667                 }
668             }
669         }
670     }
671
672 #undef NE
673 #define NE pe_def_file->num_exports
674
675   /* Canonicalize the export list.  */
676   if (pe_dll_kill_ats)
677     {
678       for (i = 0; i < NE; i++)
679         {
680           if (strchr (pe_def_file->exports[i].name, '@'))
681             {
682               /* This will preserve internal_name, which may have been
683                  pointing to the same memory as name, or might not
684                  have.  */
685               int lead_at = (*pe_def_file->exports[i].name == '@');
686               char *tmp = xstrdup (pe_def_file->exports[i].name + lead_at);
687               char *tmp_at = strchr (tmp, '@');
688
689               if (tmp_at)
690                 *tmp_at = 0;
691               else
692                 einfo (_("%XCannot export %s: invalid export name\n"),
693                        pe_def_file->exports[i].name);
694               pe_def_file->exports[i].name = tmp;
695             }
696         }
697     }
698
699   if (pe_dll_stdcall_aliases)
700     {
701       for (i = 0; i < NE; i++)
702         {
703           if (is_import (pe_def_file->exports[i].name))
704             continue;
705
706           if (strchr (pe_def_file->exports[i].name, '@'))
707             {
708               int lead_at = (*pe_def_file->exports[i].name == '@');
709               char *tmp = xstrdup (pe_def_file->exports[i].name + lead_at);
710
711               *(strchr (tmp, '@')) = 0;
712               if (auto_export (NULL, pe_def_file, tmp))
713                 def_file_add_export (pe_def_file, tmp,
714                                      pe_def_file->exports[i].internal_name,
715                                      -1);
716               else
717                 free (tmp);
718             }
719         }
720     }
721
722   /* Convenience, but watch out for it changing.  */
723   e = pe_def_file->exports;
724
725   exported_symbol_offsets = xmalloc (NE * sizeof (bfd_vma));
726   exported_symbol_sections = xmalloc (NE * sizeof (struct bfd_section *));
727
728   memset (exported_symbol_sections, 0, NE * sizeof (struct bfd_section *));
729   max_ordinal = 0;
730   min_ordinal = 65536;
731   count_exported = 0;
732   count_exported_byname = 0;
733   count_with_ordinals = 0;
734
735   qsort (pe_def_file->exports, NE, sizeof (pe_def_file->exports[0]),
736          pe_export_sort);
737   for (i = 0, j = 0; i < NE; i++)
738     {
739       if (i > 0 && strcmp (e[i].name, e[i - 1].name) == 0)
740         {
741           /* This is a duplicate.  */
742           if (e[j - 1].ordinal != -1
743               && e[i].ordinal != -1
744               && e[j - 1].ordinal != e[i].ordinal)
745             {
746               if (pe_dll_warn_dup_exports)
747                 /* xgettext:c-format */
748                 einfo (_("%XError, duplicate EXPORT with ordinals: %s (%d vs %d)\n"),
749                        e[j - 1].name, e[j - 1].ordinal, e[i].ordinal);
750             }
751           else
752             {
753               if (pe_dll_warn_dup_exports)
754                 /* xgettext:c-format */
755                 einfo (_("Warning, duplicate EXPORT: %s\n"),
756                        e[j - 1].name);
757             }
758
759           if (e[i].ordinal != -1)
760             e[j - 1].ordinal = e[i].ordinal;
761           e[j - 1].flag_private |= e[i].flag_private;
762           e[j - 1].flag_constant |= e[i].flag_constant;
763           e[j - 1].flag_noname |= e[i].flag_noname;
764           e[j - 1].flag_data |= e[i].flag_data;
765         }
766       else
767         {
768           if (i != j)
769             e[j] = e[i];
770           j++;
771         }
772     }
773   pe_def_file->num_exports = j; /* == NE */
774
775   for (i = 0; i < NE; i++)
776     {
777       char *name;
778
779       /* Check for forward exports */
780       if (strchr (pe_def_file->exports[i].internal_name, '.'))
781         {
782           count_exported++;
783           if (!pe_def_file->exports[i].flag_noname)
784             count_exported_byname++;
785
786           pe_def_file->exports[i].flag_forward = 1;
787
788           if (pe_def_file->exports[i].ordinal != -1)
789             {
790               if (max_ordinal < pe_def_file->exports[i].ordinal)
791                 max_ordinal = pe_def_file->exports[i].ordinal;
792               if (min_ordinal > pe_def_file->exports[i].ordinal)
793                 min_ordinal = pe_def_file->exports[i].ordinal;
794               count_with_ordinals++;
795             }
796
797           continue;
798         }
799
800       name = xmalloc (strlen (pe_def_file->exports[i].internal_name) + 2);
801       if (pe_details->underscored
802           && (*pe_def_file->exports[i].internal_name != '@'))
803         {
804           *name = '_';
805           strcpy (name + 1, pe_def_file->exports[i].internal_name);
806         }
807       else
808         strcpy (name, pe_def_file->exports[i].internal_name);
809
810       blhe = bfd_link_hash_lookup (info->hash,
811                                    name,
812                                    FALSE, FALSE, TRUE);
813
814       if (blhe
815           && (blhe->type == bfd_link_hash_defined
816               || (blhe->type == bfd_link_hash_common)))
817         {
818           count_exported++;
819           if (!pe_def_file->exports[i].flag_noname)
820             count_exported_byname++;
821
822           /* Only fill in the sections. The actual offsets are computed
823              in fill_exported_offsets() after common symbols are laid
824              out.  */
825           if (blhe->type == bfd_link_hash_defined)
826             exported_symbol_sections[i] = blhe->u.def.section;
827           else
828             exported_symbol_sections[i] = blhe->u.c.p->section;
829
830           if (pe_def_file->exports[i].ordinal != -1)
831             {
832               if (max_ordinal < pe_def_file->exports[i].ordinal)
833                 max_ordinal = pe_def_file->exports[i].ordinal;
834               if (min_ordinal > pe_def_file->exports[i].ordinal)
835                 min_ordinal = pe_def_file->exports[i].ordinal;
836               count_with_ordinals++;
837             }
838         }
839       else if (blhe && blhe->type == bfd_link_hash_undefined)
840         {
841           /* xgettext:c-format */
842           einfo (_("%XCannot export %s: symbol not defined\n"),
843                  pe_def_file->exports[i].internal_name);
844         }
845       else if (blhe)
846         {
847           /* xgettext:c-format */
848           einfo (_("%XCannot export %s: symbol wrong type (%d vs %d)\n"),
849                  pe_def_file->exports[i].internal_name,
850                  blhe->type, bfd_link_hash_defined);
851         }
852       else
853         {
854           /* xgettext:c-format */
855           einfo (_("%XCannot export %s: symbol not found\n"),
856                  pe_def_file->exports[i].internal_name);
857         }
858       free (name);
859     }
860 }
861
862 /* Build the bfd that will contain .edata and .reloc sections.  */
863
864 static void
865 build_filler_bfd (int include_edata)
866 {
867   lang_input_statement_type *filler_file;
868   filler_file = lang_add_input_file ("dll stuff",
869                                      lang_input_file_is_fake_enum,
870                                      NULL);
871   filler_file->the_bfd = filler_bfd = bfd_create ("dll stuff",
872                                                   link_info.output_bfd);
873   if (filler_bfd == NULL
874       || !bfd_set_arch_mach (filler_bfd,
875                              bfd_get_arch (link_info.output_bfd),
876                              bfd_get_mach (link_info.output_bfd)))
877     {
878       einfo ("%X%P: can not create BFD: %E\n");
879       return;
880     }
881
882   if (include_edata)
883     {
884       edata_s = bfd_make_section_old_way (filler_bfd, ".edata");
885       if (edata_s == NULL
886           || !bfd_set_section_flags (filler_bfd, edata_s,
887                                      (SEC_HAS_CONTENTS
888                                       | SEC_ALLOC
889                                       | SEC_LOAD
890                                       | SEC_KEEP
891                                       | SEC_IN_MEMORY)))
892         {
893           einfo ("%X%P: can not create .edata section: %E\n");
894           return;
895         }
896       bfd_set_section_size (filler_bfd, edata_s, edata_sz);
897     }
898
899   reloc_s = bfd_make_section_old_way (filler_bfd, ".reloc");
900   if (reloc_s == NULL
901       || !bfd_set_section_flags (filler_bfd, reloc_s,
902                                  (SEC_HAS_CONTENTS
903                                   | SEC_ALLOC
904                                   | SEC_LOAD
905                                   | SEC_KEEP
906                                   | SEC_IN_MEMORY)))
907     {
908       einfo ("%X%P: can not create .reloc section: %E\n");
909       return;
910     }
911
912   bfd_set_section_size (filler_bfd, reloc_s, 0);
913
914   ldlang_add_file (filler_file);
915 }
916
917 /* Gather all the exported symbols and build the .edata section.  */
918
919 static void
920 generate_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
921 {
922   int i, next_ordinal;
923   int name_table_size = 0;
924   const char *dlnp;
925
926   /* First, we need to know how many exported symbols there are,
927      and what the range of ordinals is.  */
928   if (pe_def_file->name)
929     dll_name = pe_def_file->name;
930   else
931     {
932       dll_name = abfd->filename;
933
934       for (dlnp = dll_name; *dlnp; dlnp++)
935         if (*dlnp == '\\' || *dlnp == '/' || *dlnp == ':')
936           dll_name = dlnp + 1;
937     }
938
939   if (count_with_ordinals && max_ordinal > count_exported)
940     {
941       if (min_ordinal > max_ordinal - count_exported + 1)
942         min_ordinal = max_ordinal - count_exported + 1;
943     }
944   else
945     {
946       min_ordinal = 1;
947       max_ordinal = count_exported;
948     }
949
950   export_table_size = max_ordinal - min_ordinal + 1;
951   exported_symbols = xmalloc (export_table_size * sizeof (int));
952   for (i = 0; i < export_table_size; i++)
953     exported_symbols[i] = -1;
954
955   /* Now we need to assign ordinals to those that don't have them.  */
956   for (i = 0; i < NE; i++)
957     {
958       if (exported_symbol_sections[i] ||
959           pe_def_file->exports[i].flag_forward)
960         {
961           if (pe_def_file->exports[i].ordinal != -1)
962             {
963               int ei = pe_def_file->exports[i].ordinal - min_ordinal;
964               int pi = exported_symbols[ei];
965
966               if (pi != -1)
967                 {
968                   /* xgettext:c-format */
969                   einfo (_("%XError, ordinal used twice: %d (%s vs %s)\n"),
970                          pe_def_file->exports[i].ordinal,
971                          pe_def_file->exports[i].name,
972                          pe_def_file->exports[pi].name);
973                 }
974               exported_symbols[ei] = i;
975             }
976           name_table_size += strlen (pe_def_file->exports[i].name) + 1;
977         }
978
979       /* Reserve space for the forward name. */
980       if (pe_def_file->exports[i].flag_forward)
981         {
982           name_table_size += strlen (pe_def_file->exports[i].internal_name) + 1;
983         }
984     }
985
986   next_ordinal = min_ordinal;
987   for (i = 0; i < NE; i++)
988     if ((exported_symbol_sections[i] ||
989          pe_def_file->exports[i].flag_forward) &&
990         pe_def_file->exports[i].ordinal == -1)
991       {
992         while (exported_symbols[next_ordinal - min_ordinal] != -1)
993           next_ordinal++;
994
995         exported_symbols[next_ordinal - min_ordinal] = i;
996         pe_def_file->exports[i].ordinal = next_ordinal;
997       }
998
999   /* OK, now we can allocate some memory.  */
1000   edata_sz = (40                                /* directory */
1001               + 4 * export_table_size           /* addresses */
1002               + 4 * count_exported_byname       /* name ptrs */
1003               + 2 * count_exported_byname       /* ordinals */
1004               + name_table_size + strlen (dll_name) + 1);
1005 }
1006
1007 /* Fill the exported symbol offsets. The preliminary work has already
1008    been done in process_def_file().  */
1009
1010 static void
1011 fill_exported_offsets (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
1012 {
1013   int i;
1014   struct bfd_link_hash_entry *blhe;
1015
1016   for (i = 0; i < pe_def_file->num_exports; i++)
1017     {
1018       char *name;
1019
1020       name = xmalloc (strlen (pe_def_file->exports[i].internal_name) + 2);
1021       if (pe_details->underscored
1022           && *pe_def_file->exports[i].internal_name != '@')
1023         {
1024           *name = '_';
1025           strcpy (name + 1, pe_def_file->exports[i].internal_name);
1026         }
1027       else
1028         strcpy (name, pe_def_file->exports[i].internal_name);
1029
1030       blhe = bfd_link_hash_lookup (info->hash,
1031                                    name,
1032                                    FALSE, FALSE, TRUE);
1033
1034       if (blhe && blhe->type == bfd_link_hash_defined)
1035         exported_symbol_offsets[i] = blhe->u.def.value;
1036
1037       free (name);
1038     }
1039 }
1040
1041 static void
1042 fill_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
1043 {
1044   int s, hint;
1045   unsigned char *edirectory;
1046   unsigned char *eaddresses;
1047   unsigned char *enameptrs;
1048   unsigned char *eordinals;
1049   char *enamestr;
1050   time_t now;
1051
1052   time (&now);
1053
1054   edata_d = xmalloc (edata_sz);
1055
1056   /* Note use of array pointer math here.  */
1057   edirectory = edata_d;
1058   eaddresses = edata_d + 40;
1059   enameptrs = eaddresses + 4 * export_table_size;
1060   eordinals = enameptrs + 4 * count_exported_byname;
1061   enamestr = (char *) eordinals + 2 * count_exported_byname;
1062
1063 #define ERVA(ptr) (((unsigned char *)(ptr) - edata_d) \
1064                    + edata_s->output_section->vma - image_base)
1065
1066   memset (edata_d, 0, edata_sz);
1067   bfd_put_32 (abfd, now, edata_d + 4);
1068   if (pe_def_file->version_major != -1)
1069     {
1070       bfd_put_16 (abfd, pe_def_file->version_major, edata_d + 8);
1071       bfd_put_16 (abfd, pe_def_file->version_minor, edata_d + 10);
1072     }
1073
1074   bfd_put_32 (abfd, ERVA (enamestr), edata_d + 12);
1075   strcpy (enamestr, dll_name);
1076   enamestr += strlen (enamestr) + 1;
1077   bfd_put_32 (abfd, min_ordinal, edata_d + 16);
1078   bfd_put_32 (abfd, export_table_size, edata_d + 20);
1079   bfd_put_32 (abfd, count_exported_byname, edata_d + 24);
1080   bfd_put_32 (abfd, ERVA (eaddresses), edata_d + 28);
1081   bfd_put_32 (abfd, ERVA (enameptrs), edata_d + 32);
1082   bfd_put_32 (abfd, ERVA (eordinals), edata_d + 36);
1083
1084   fill_exported_offsets (abfd, info);
1085
1086   /* Ok, now for the filling in part.
1087      Scan alphabetically - ie the ordering in the exports[] table,
1088      rather than by ordinal - the ordering in the exported_symbol[]
1089      table.  See dlltool.c and:
1090         http://sources.redhat.com/ml/binutils/2003-04/msg00379.html
1091      for more information.  */
1092   hint = 0;
1093   for (s = 0; s < NE; s++)
1094     {
1095       struct bfd_section *ssec = exported_symbol_sections[s];
1096       if (pe_def_file->exports[s].ordinal != -1 &&
1097           (pe_def_file->exports[s].flag_forward || ssec != NULL))
1098         {
1099           int ord = pe_def_file->exports[s].ordinal;
1100
1101           if (pe_def_file->exports[s].flag_forward)
1102             {
1103               bfd_put_32 (abfd, ERVA (enamestr),
1104                           eaddresses + 4 * (ord - min_ordinal));
1105
1106               strcpy (enamestr, pe_def_file->exports[s].internal_name);
1107               enamestr += strlen (pe_def_file->exports[s].internal_name) + 1;
1108             }
1109           else
1110             {
1111               bfd_vma srva = (exported_symbol_offsets[s]
1112                                     + ssec->output_section->vma
1113                                     + ssec->output_offset);
1114
1115               bfd_put_32 (abfd, srva - image_base,
1116                           eaddresses + 4 * (ord - min_ordinal));
1117             }
1118
1119           if (!pe_def_file->exports[s].flag_noname)
1120             {
1121               char *ename = pe_def_file->exports[s].name;
1122
1123               bfd_put_32 (abfd, ERVA (enamestr), enameptrs);
1124               enameptrs += 4;
1125               strcpy (enamestr, ename);
1126               enamestr += strlen (enamestr) + 1;
1127               bfd_put_16 (abfd, ord - min_ordinal, eordinals);
1128               eordinals += 2;
1129               pe_def_file->exports[s].hint = hint++;
1130             }
1131         }
1132     }
1133 }
1134
1135
1136 static struct bfd_section *current_sec;
1137
1138 void
1139 pe_walk_relocs_of_symbol (struct bfd_link_info *info,
1140                           const char *name,
1141                           int (*cb) (arelent *, asection *))
1142 {
1143   bfd *b;
1144   asection *s;
1145
1146   for (b = info->input_bfds; b; b = b->link_next)
1147     {
1148       asymbol **symbols;
1149       int nsyms;
1150
1151       if (!bfd_generic_link_read_symbols (b))
1152         {
1153           einfo (_("%B%F: could not read symbols: %E\n"), b);
1154           return;
1155         }
1156
1157       symbols = bfd_get_outsymbols (b);
1158       nsyms = bfd_get_symcount (b);
1159
1160       for (s = b->sections; s; s = s->next)
1161         {
1162           arelent **relocs;
1163           int relsize, nrelocs, i;
1164           int flags = bfd_get_section_flags (b, s);
1165
1166           /* Skip discarded linkonce sections.  */
1167           if (flags & SEC_LINK_ONCE
1168               && s->output_section == bfd_abs_section_ptr)
1169             continue;
1170
1171           current_sec = s;
1172
1173           relsize = bfd_get_reloc_upper_bound (b, s);
1174           relocs = xmalloc (relsize);
1175           nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1176
1177           for (i = 0; i < nrelocs; i++)
1178             {
1179               struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1180
1181               if (!strcmp (name, sym->name))
1182                 cb (relocs[i], s);
1183             }
1184
1185           free (relocs);
1186
1187           /* Warning: the allocated symbols are remembered in BFD and reused
1188              later, so don't free them! */
1189           /* free (symbols); */
1190         }
1191     }
1192 }
1193
1194 /* Gather all the relocations and build the .reloc section.  */
1195
1196 static void
1197 generate_reloc (bfd *abfd, struct bfd_link_info *info)
1198 {
1199
1200   /* For .reloc stuff.  */
1201   reloc_data_type *reloc_data;
1202   int total_relocs = 0;
1203   int i;
1204   bfd_vma sec_page = (bfd_vma) -1;
1205   bfd_vma page_ptr, page_count;
1206   int bi;
1207   bfd *b;
1208   struct bfd_section *s;
1209
1210   total_relocs = 0;
1211   for (b = info->input_bfds; b; b = b->link_next)
1212     for (s = b->sections; s; s = s->next)
1213       total_relocs += s->reloc_count;
1214
1215   reloc_data = xmalloc (total_relocs * sizeof (reloc_data_type));
1216
1217   total_relocs = 0;
1218   bi = 0;
1219   for (bi = 0, b = info->input_bfds; b; bi++, b = b->link_next)
1220     {
1221       arelent **relocs;
1222       int relsize, nrelocs, i;
1223
1224       for (s = b->sections; s; s = s->next)
1225         {
1226           bfd_vma sec_vma = s->output_section->vma + s->output_offset;
1227           asymbol **symbols;
1228           int nsyms;
1229
1230           /* If it's not loaded, we don't need to relocate it this way.  */
1231           if (!(s->output_section->flags & SEC_LOAD))
1232             continue;
1233
1234           /* I don't know why there would be a reloc for these, but I've
1235              seen it happen - DJ  */
1236           if (s->output_section == &bfd_abs_section)
1237             continue;
1238
1239           if (s->output_section->vma == 0)
1240             {
1241               /* Huh?  Shouldn't happen, but punt if it does.  */
1242               einfo ("DJ: zero vma section reloc detected: `%s' #%d f=%d\n",
1243                      s->output_section->name, s->output_section->index,
1244                      s->output_section->flags);
1245               continue;
1246             }
1247
1248           if (!bfd_generic_link_read_symbols (b))
1249             {
1250               einfo (_("%B%F: could not read symbols: %E\n"), b);
1251               return;
1252             }
1253
1254           symbols = bfd_get_outsymbols (b);
1255           nsyms = bfd_get_symcount (b);
1256           relsize = bfd_get_reloc_upper_bound (b, s);
1257           relocs = xmalloc (relsize);
1258           nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1259
1260           for (i = 0; i < nrelocs; i++)
1261             {
1262               if (pe_dll_extra_pe_debug)
1263                 {
1264                   struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1265                   printf ("rel: %s\n", sym->name);
1266                 }
1267               if (!relocs[i]->howto->pc_relative
1268                   && relocs[i]->howto->type != pe_details->imagebase_reloc)
1269                 {
1270                   bfd_vma sym_vma;
1271                   struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1272
1273                   /* Don't create relocs for undefined weak symbols.  */ 
1274                   if (sym->flags == BSF_WEAK)
1275                     {
1276                       struct bfd_link_hash_entry *blhe
1277                         = bfd_link_hash_lookup (info->hash, sym->name,
1278                                                 FALSE, FALSE, FALSE);
1279                       if (!blhe || blhe->type != bfd_link_hash_defined)
1280                         continue;                     
1281                     }
1282
1283                   sym_vma = (relocs[i]->addend
1284                              + sym->value
1285                              + sym->section->vma
1286                              + sym->section->output_offset
1287                              + sym->section->output_section->vma);
1288                   reloc_data[total_relocs].vma = sec_vma + relocs[i]->address;
1289
1290 #define BITS_AND_SHIFT(bits, shift) (bits * 1000 | shift)
1291
1292                   switch BITS_AND_SHIFT (relocs[i]->howto->bitsize,
1293                                          relocs[i]->howto->rightshift)
1294                     {
1295 #ifdef pe_use_x86_64
1296                     case BITS_AND_SHIFT (64, 0):
1297                       reloc_data[total_relocs].type = 10;
1298                       total_relocs++;
1299                       break;
1300 #endif
1301                     case BITS_AND_SHIFT (32, 0):
1302                       reloc_data[total_relocs].type = 3;
1303                       total_relocs++;
1304                       break;
1305                     case BITS_AND_SHIFT (16, 0):
1306                       reloc_data[total_relocs].type = 2;
1307                       total_relocs++;
1308                       break;
1309                     case BITS_AND_SHIFT (16, 16):
1310                       reloc_data[total_relocs].type = 4;
1311                       /* FIXME: we can't know the symbol's right value
1312                          yet, but we probably can safely assume that
1313                          CE will relocate us in 64k blocks, so leaving
1314                          it zero is safe.  */
1315                       reloc_data[total_relocs].extra = 0;
1316                       total_relocs++;
1317                       break;
1318                     case BITS_AND_SHIFT (26, 2):
1319                       reloc_data[total_relocs].type = 5;
1320                       total_relocs++;
1321                       break;
1322                     case BITS_AND_SHIFT (24, 2):
1323                       /* FIXME: 0 is ARM_26D, it is defined in bfd/coff-arm.c
1324                          Those ARM_xxx definitions should go in proper
1325                          header someday.  */
1326                       if (relocs[i]->howto->type == 0
1327                           /* Older GNU linkers used 5 instead of 0 for this reloc.  */
1328                           || relocs[i]->howto->type == 5)
1329                         /* This is an ARM_26D reloc, which is an ARM_26 reloc
1330                            that has already been fully processed during a
1331                            previous link stage, so ignore it here.  */
1332                         break;
1333                       /* Fall through.  */
1334                     default:
1335                       /* xgettext:c-format */
1336                       einfo (_("%XError: %d-bit reloc in dll\n"),
1337                              relocs[i]->howto->bitsize);
1338                       break;
1339                     }
1340                 }
1341             }
1342           free (relocs);
1343           /* Warning: the allocated symbols are remembered in BFD and
1344              reused later, so don't free them!  */
1345         }
1346     }
1347
1348   /* At this point, we have total_relocs relocation addresses in
1349      reloc_addresses, which are all suitable for the .reloc section.
1350      We must now create the new sections.  */
1351   qsort (reloc_data, total_relocs, sizeof (*reloc_data), reloc_sort);
1352
1353   for (i = 0; i < total_relocs; i++)
1354     {
1355       bfd_vma this_page = (reloc_data[i].vma >> 12);
1356
1357       if (this_page != sec_page)
1358         {
1359           reloc_sz = (reloc_sz + 3) & ~3;       /* 4-byte align.  */
1360           reloc_sz += 8;
1361           sec_page = this_page;
1362         }
1363
1364       reloc_sz += 2;
1365
1366       if (reloc_data[i].type == 4)
1367         reloc_sz += 2;
1368     }
1369
1370   reloc_sz = (reloc_sz + 3) & ~3;       /* 4-byte align.  */
1371   reloc_d = xmalloc (reloc_sz);
1372   sec_page = (bfd_vma) -1;
1373   reloc_sz = 0;
1374   page_ptr = (bfd_vma) -1;
1375   page_count = 0;
1376
1377   for (i = 0; i < total_relocs; i++)
1378     {
1379       bfd_vma rva = reloc_data[i].vma - image_base;
1380       bfd_vma this_page = (rva & ~0xfff);
1381
1382       if (this_page != sec_page)
1383         {
1384           while (reloc_sz & 3)
1385             reloc_d[reloc_sz++] = 0;
1386
1387           if (page_ptr != (bfd_vma) -1)
1388             bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
1389
1390           bfd_put_32 (abfd, this_page, reloc_d + reloc_sz);
1391           page_ptr = reloc_sz;
1392           reloc_sz += 8;
1393           sec_page = this_page;
1394           page_count = 0;
1395         }
1396
1397       bfd_put_16 (abfd, (rva & 0xfff) + (reloc_data[i].type << 12),
1398                   reloc_d + reloc_sz);
1399       reloc_sz += 2;
1400
1401       if (reloc_data[i].type == 4)
1402         {
1403           bfd_put_16 (abfd, reloc_data[i].extra, reloc_d + reloc_sz);
1404           reloc_sz += 2;
1405         }
1406
1407       page_count++;
1408     }
1409
1410   while (reloc_sz & 3)
1411     reloc_d[reloc_sz++] = 0;
1412
1413   if (page_ptr != (bfd_vma) -1)
1414     bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
1415
1416   while (reloc_sz < reloc_s->size)
1417     reloc_d[reloc_sz++] = 0;
1418 }
1419
1420 /* Given the exiting def_file structure, print out a .DEF file that
1421    corresponds to it.  */
1422
1423 static void
1424 quoteput (char *s, FILE *f, int needs_quotes)
1425 {
1426   char *cp;
1427
1428   for (cp = s; *cp; cp++)
1429     if (*cp == '\''
1430         || *cp == '"'
1431         || *cp == '\\'
1432         || ISSPACE (*cp)
1433         || *cp == ','
1434         || *cp == ';')
1435       needs_quotes = 1;
1436
1437   if (needs_quotes)
1438     {
1439       putc ('"', f);
1440
1441       while (*s)
1442         {
1443           if (*s == '"' || *s == '\\')
1444             putc ('\\', f);
1445
1446           putc (*s, f);
1447           s++;
1448         }
1449
1450       putc ('"', f);
1451     }
1452   else
1453     fputs (s, f);
1454 }
1455
1456 void
1457 pe_dll_generate_def_file (const char *pe_out_def_filename)
1458 {
1459   int i;
1460   FILE *out = fopen (pe_out_def_filename, "w");
1461
1462   if (out == NULL)
1463     /* xgettext:c-format */
1464     einfo (_("%s: Can't open output def file %s\n"),
1465            program_name, pe_out_def_filename);
1466
1467   if (pe_def_file)
1468     {
1469       if (pe_def_file->name)
1470         {
1471           if (pe_def_file->is_dll)
1472             fprintf (out, "LIBRARY ");
1473           else
1474             fprintf (out, "NAME ");
1475
1476           quoteput (pe_def_file->name, out, 1);
1477
1478           if (pe_data (link_info.output_bfd)->pe_opthdr.ImageBase)
1479             {
1480               fprintf (out, " BASE=0x");
1481               fprintf_vma (out, ((bfd_vma) pe_data (link_info.output_bfd)->pe_opthdr.ImageBase));
1482             }
1483           fprintf (out, "\n");
1484         }
1485
1486       if (pe_def_file->description)
1487         {
1488           fprintf (out, "DESCRIPTION ");
1489           quoteput (pe_def_file->description, out, 1);
1490           fprintf (out, "\n");
1491         }
1492
1493       if (pe_def_file->version_minor != -1)
1494         fprintf (out, "VERSION %d.%d\n", pe_def_file->version_major,
1495                  pe_def_file->version_minor);
1496       else if (pe_def_file->version_major != -1)
1497         fprintf (out, "VERSION %d\n", pe_def_file->version_major);
1498
1499       if (pe_def_file->stack_reserve != -1 || pe_def_file->heap_reserve != -1)
1500         fprintf (out, "\n");
1501
1502       if (pe_def_file->stack_commit != -1)
1503         fprintf (out, "STACKSIZE 0x%x,0x%x\n",
1504                  pe_def_file->stack_reserve, pe_def_file->stack_commit);
1505       else if (pe_def_file->stack_reserve != -1)
1506         fprintf (out, "STACKSIZE 0x%x\n", pe_def_file->stack_reserve);
1507
1508       if (pe_def_file->heap_commit != -1)
1509         fprintf (out, "HEAPSIZE 0x%x,0x%x\n",
1510                  pe_def_file->heap_reserve, pe_def_file->heap_commit);
1511       else if (pe_def_file->heap_reserve != -1)
1512         fprintf (out, "HEAPSIZE 0x%x\n", pe_def_file->heap_reserve);
1513
1514       if (pe_def_file->num_section_defs > 0)
1515         {
1516           fprintf (out, "\nSECTIONS\n\n");
1517
1518           for (i = 0; i < pe_def_file->num_section_defs; i++)
1519             {
1520               fprintf (out, "    ");
1521               quoteput (pe_def_file->section_defs[i].name, out, 0);
1522
1523               if (pe_def_file->section_defs[i].class)
1524                 {
1525                   fprintf (out, " CLASS ");
1526                   quoteput (pe_def_file->section_defs[i].class, out, 0);
1527                 }
1528
1529               if (pe_def_file->section_defs[i].flag_read)
1530                 fprintf (out, " READ");
1531
1532               if (pe_def_file->section_defs[i].flag_write)
1533                 fprintf (out, " WRITE");
1534
1535               if (pe_def_file->section_defs[i].flag_execute)
1536                 fprintf (out, " EXECUTE");
1537
1538               if (pe_def_file->section_defs[i].flag_shared)
1539                 fprintf (out, " SHARED");
1540
1541               fprintf (out, "\n");
1542             }
1543         }
1544
1545       if (pe_def_file->num_exports > 0)
1546         {
1547           fprintf (out, "EXPORTS\n");
1548
1549           for (i = 0; i < pe_def_file->num_exports; i++)
1550             {
1551               def_file_export *e = pe_def_file->exports + i;
1552               fprintf (out, "    ");
1553               quoteput (e->name, out, 0);
1554
1555               if (e->internal_name && strcmp (e->internal_name, e->name))
1556                 {
1557                   fprintf (out, " = ");
1558                   quoteput (e->internal_name, out, 0);
1559                 }
1560
1561               if (e->ordinal != -1)
1562                 fprintf (out, " @%d", e->ordinal);
1563
1564               if (e->flag_private)
1565                 fprintf (out, " PRIVATE");
1566
1567               if (e->flag_constant)
1568                 fprintf (out, " CONSTANT");
1569
1570               if (e->flag_noname)
1571                 fprintf (out, " NONAME");
1572
1573               if (e->flag_data)
1574                 fprintf (out, " DATA");
1575
1576               fprintf (out, "\n");
1577             }
1578         }
1579
1580       if (pe_def_file->num_imports > 0)
1581         {
1582           fprintf (out, "\nIMPORTS\n\n");
1583
1584           for (i = 0; i < pe_def_file->num_imports; i++)
1585             {
1586               def_file_import *im = pe_def_file->imports + i;
1587               fprintf (out, "    ");
1588
1589               if (im->internal_name
1590                   && (!im->name || strcmp (im->internal_name, im->name)))
1591                 {
1592                   quoteput (im->internal_name, out, 0);
1593                   fprintf (out, " = ");
1594                 }
1595
1596               quoteput (im->module->name, out, 0);
1597               fprintf (out, ".");
1598
1599               if (im->name)
1600                 quoteput (im->name, out, 0);
1601               else
1602                 fprintf (out, "%d", im->ordinal);
1603
1604               fprintf (out, "\n");
1605             }
1606         }
1607     }
1608   else
1609     fprintf (out, _("; no contents available\n"));
1610
1611   if (fclose (out) == EOF)
1612     /* xgettext:c-format */
1613     einfo (_("%P: Error closing file `%s'\n"), pe_out_def_filename);
1614 }
1615
1616 /* Generate the import library.  */
1617
1618 static asymbol **symtab;
1619 static int symptr;
1620 static int tmp_seq;
1621 static const char *dll_filename;
1622 static char *dll_symname;
1623
1624 #define UNDSEC (asection *) &bfd_und_section
1625
1626 static asection *
1627 quick_section (bfd *abfd, const char *name, int flags, int align)
1628 {
1629   asection *sec;
1630   asymbol *sym;
1631
1632   sec = bfd_make_section_old_way (abfd, name);
1633   bfd_set_section_flags (abfd, sec, flags | SEC_ALLOC | SEC_LOAD | SEC_KEEP);
1634   bfd_set_section_alignment (abfd, sec, align);
1635   /* Remember to undo this before trying to link internally!  */
1636   sec->output_section = sec;
1637
1638   sym = bfd_make_empty_symbol (abfd);
1639   symtab[symptr++] = sym;
1640   sym->name = sec->name;
1641   sym->section = sec;
1642   sym->flags = BSF_LOCAL;
1643   sym->value = 0;
1644
1645   return sec;
1646 }
1647
1648 static void
1649 quick_symbol (bfd *abfd,
1650               const char *n1,
1651               const char *n2,
1652               const char *n3,
1653               asection *sec,
1654               int flags,
1655               int addr)
1656 {
1657   asymbol *sym;
1658   char *name = xmalloc (strlen (n1) + strlen (n2) + strlen (n3) + 1);
1659
1660   strcpy (name, n1);
1661   strcat (name, n2);
1662   strcat (name, n3);
1663   sym = bfd_make_empty_symbol (abfd);
1664   sym->name = name;
1665   sym->section = sec;
1666   sym->flags = flags;
1667   sym->value = addr;
1668   symtab[symptr++] = sym;
1669 }
1670
1671 static arelent *reltab = 0;
1672 static int relcount = 0, relsize = 0;
1673
1674 static void
1675 quick_reloc (bfd *abfd, bfd_size_type address, int which_howto, int symidx)
1676 {
1677   if (relcount >= relsize - 1)
1678     {
1679       relsize += 10;
1680       if (reltab)
1681         reltab = xrealloc (reltab, relsize * sizeof (arelent));
1682       else
1683         reltab = xmalloc (relsize * sizeof (arelent));
1684     }
1685   reltab[relcount].address = address;
1686   reltab[relcount].addend = 0;
1687   reltab[relcount].howto = bfd_reloc_type_lookup (abfd, which_howto);
1688   reltab[relcount].sym_ptr_ptr = symtab + symidx;
1689   relcount++;
1690 }
1691
1692 static void
1693 save_relocs (asection *sec)
1694 {
1695   int i;
1696
1697   sec->relocation = reltab;
1698   sec->reloc_count = relcount;
1699   sec->orelocation = xmalloc ((relcount + 1) * sizeof (arelent *));
1700   for (i = 0; i < relcount; i++)
1701     sec->orelocation[i] = sec->relocation + i;
1702   sec->orelocation[relcount] = 0;
1703   sec->flags |= SEC_RELOC;
1704   reltab = 0;
1705   relcount = relsize = 0;
1706 }
1707
1708 /*      .section        .idata$2
1709         .global         __head_my_dll
1710    __head_my_dll:
1711         .rva            hname
1712         .long           0
1713         .long           0
1714         .rva            __my_dll_iname
1715         .rva            fthunk
1716
1717         .section        .idata$5
1718         .long           0
1719    fthunk:
1720
1721         .section        .idata$4
1722         .long           0
1723    hname:                              */
1724
1725 static bfd *
1726 make_head (bfd *parent)
1727 {
1728   asection *id2, *id5, *id4;
1729   unsigned char *d2, *d5, *d4;
1730   char *oname;
1731   bfd *abfd;
1732
1733   oname = xmalloc (20);
1734   sprintf (oname, "d%06d.o", tmp_seq);
1735   tmp_seq++;
1736
1737   abfd = bfd_create (oname, parent);
1738   bfd_find_target (pe_details->object_target, abfd);
1739   bfd_make_writable (abfd);
1740
1741   bfd_set_format (abfd, bfd_object);
1742   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1743
1744   symptr = 0;
1745   symtab = xmalloc (6 * sizeof (asymbol *));
1746   id2 = quick_section (abfd, ".idata$2", SEC_HAS_CONTENTS, 2);
1747   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1748   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1749   quick_symbol (abfd, U ("_head_"), dll_symname, "", id2, BSF_GLOBAL, 0);
1750   quick_symbol (abfd, U (""), dll_symname, "_iname", UNDSEC, BSF_GLOBAL, 0);
1751
1752   /* OK, pay attention here.  I got confused myself looking back at
1753      it.  We create a four-byte section to mark the beginning of the
1754      list, and we include an offset of 4 in the section, so that the
1755      pointer to the list points to the *end* of this section, which is
1756      the start of the list of sections from other objects.  */
1757
1758   bfd_set_section_size (abfd, id2, 20);
1759   d2 = xmalloc (20);
1760   id2->contents = d2;
1761   memset (d2, 0, 20);
1762   d2[0] = d2[16] = PE_IDATA5_SIZE; /* Reloc addend.  */
1763   quick_reloc (abfd,  0, BFD_RELOC_RVA, 2);
1764   quick_reloc (abfd, 12, BFD_RELOC_RVA, 4);
1765   quick_reloc (abfd, 16, BFD_RELOC_RVA, 1);
1766   save_relocs (id2);
1767
1768   bfd_set_section_size (abfd, id5, PE_IDATA5_SIZE);
1769   d5 = xmalloc (PE_IDATA5_SIZE);
1770   id5->contents = d5;
1771   memset (d5, 0, PE_IDATA5_SIZE);
1772
1773   bfd_set_section_size (abfd, id4, PE_IDATA4_SIZE);
1774   d4 = xmalloc (PE_IDATA4_SIZE);
1775   id4->contents = d4;
1776   memset (d4, 0, PE_IDATA4_SIZE);
1777
1778   bfd_set_symtab (abfd, symtab, symptr);
1779
1780   bfd_set_section_contents (abfd, id2, d2, 0, 20);
1781   bfd_set_section_contents (abfd, id5, d5, 0, PE_IDATA5_SIZE);
1782   bfd_set_section_contents (abfd, id4, d4, 0, PE_IDATA4_SIZE);
1783
1784   bfd_make_readable (abfd);
1785   return abfd;
1786 }
1787
1788 /*      .section        .idata$4
1789         .long           0
1790         [.long          0] for PE+
1791         .section        .idata$5
1792         .long           0
1793         [.long          0] for PE+
1794         .section        idata$7
1795         .global         __my_dll_iname
1796   __my_dll_iname:
1797         .asciz          "my.dll"       */
1798
1799 static bfd *
1800 make_tail (bfd *parent)
1801 {
1802   asection *id4, *id5, *id7;
1803   unsigned char *d4, *d5, *d7;
1804   int len;
1805   char *oname;
1806   bfd *abfd;
1807
1808   oname = xmalloc (20);
1809   sprintf (oname, "d%06d.o", tmp_seq);
1810   tmp_seq++;
1811
1812   abfd = bfd_create (oname, parent);
1813   bfd_find_target (pe_details->object_target, abfd);
1814   bfd_make_writable (abfd);
1815
1816   bfd_set_format (abfd, bfd_object);
1817   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1818
1819   symptr = 0;
1820   symtab = xmalloc (5 * sizeof (asymbol *));
1821   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1822   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1823   id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1824   quick_symbol (abfd, U (""), dll_symname, "_iname", id7, BSF_GLOBAL, 0);
1825
1826   bfd_set_section_size (abfd, id4, PE_IDATA4_SIZE);
1827   d4 = xmalloc (PE_IDATA4_SIZE);
1828   id4->contents = d4;
1829   memset (d4, 0, PE_IDATA4_SIZE);
1830
1831   bfd_set_section_size (abfd, id5, PE_IDATA5_SIZE);
1832   d5 = xmalloc (PE_IDATA5_SIZE);
1833   id5->contents = d5;
1834   memset (d5, 0, PE_IDATA5_SIZE);
1835
1836   len = strlen (dll_filename) + 1;
1837   if (len & 1)
1838     len++;
1839   bfd_set_section_size (abfd, id7, len);
1840   d7 = xmalloc (len);
1841   id7->contents = d7;
1842   strcpy ((char *) d7, dll_filename);
1843   /* If len was odd, the above
1844      strcpy leaves behind an undefined byte. That is harmless,
1845      but we set it to 0 just so the binary dumps are pretty.  */
1846   d7[len - 1] = 0;
1847
1848   bfd_set_symtab (abfd, symtab, symptr);
1849
1850   bfd_set_section_contents (abfd, id4, d4, 0, PE_IDATA4_SIZE);
1851   bfd_set_section_contents (abfd, id5, d5, 0, PE_IDATA5_SIZE);
1852   bfd_set_section_contents (abfd, id7, d7, 0, len);
1853
1854   bfd_make_readable (abfd);
1855   return abfd;
1856 }
1857
1858 /*      .text
1859         .global         _function
1860         .global         ___imp_function
1861         .global         __imp__function
1862   _function:
1863         jmp             *__imp__function:
1864
1865         .section        idata$7
1866         .long           __head_my_dll
1867
1868         .section        .idata$5
1869   ___imp_function:
1870   __imp__function:
1871   iat?
1872         .section        .idata$4
1873   iat?
1874         .section        .idata$6
1875   ID<ordinal>:
1876         .short          <hint>
1877         .asciz          "function" xlate? (add underscore, kill at)  */
1878
1879 static const unsigned char jmp_ix86_bytes[] =
1880 {
1881   0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
1882 };
1883
1884 /* _function:
1885         mov.l   ip+8,r0
1886         mov.l   @r0,r0
1887         jmp     @r0
1888         nop
1889         .dw     __imp_function   */
1890
1891 static const unsigned char jmp_sh_bytes[] =
1892 {
1893   0x01, 0xd0, 0x02, 0x60, 0x2b, 0x40, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00
1894 };
1895
1896 /* _function:
1897         lui     $t0,<high:__imp_function>
1898         lw      $t0,<low:__imp_function>
1899         jr      $t0
1900         nop                              */
1901
1902 static const unsigned char jmp_mips_bytes[] =
1903 {
1904   0x00, 0x00, 0x08, 0x3c,  0x00, 0x00, 0x08, 0x8d,
1905   0x08, 0x00, 0x00, 0x01,  0x00, 0x00, 0x00, 0x00
1906 };
1907
1908 static const unsigned char jmp_arm_bytes[] =
1909 {
1910   0x00, 0xc0, 0x9f, 0xe5,       /* ldr  ip, [pc] */
1911   0x00, 0xf0, 0x9c, 0xe5,       /* ldr  pc, [ip] */
1912   0,    0,    0,    0
1913 };
1914
1915
1916 static bfd *
1917 make_one (def_file_export *exp, bfd *parent, bfd_boolean include_jmp_stub)
1918 {
1919   asection *tx, *id7, *id5, *id4, *id6;
1920   unsigned char *td = NULL, *d7, *d5, *d4, *d6 = NULL;
1921   int len;
1922   char *oname;
1923   bfd *abfd;
1924   const unsigned char *jmp_bytes = NULL;
1925   int jmp_byte_count = 0;
1926
1927   /* Include the jump stub section only if it is needed. A jump
1928      stub is needed if the symbol being imported <sym> is a function
1929      symbol and there is at least one undefined reference to that
1930      symbol. In other words, if all the import references to <sym> are
1931      explicitly through _declspec(dllimport) then the jump stub is not
1932      needed.  */
1933   if (include_jmp_stub)
1934     {
1935       switch (pe_details->pe_arch)
1936         {
1937         case PE_ARCH_i386:
1938           jmp_bytes = jmp_ix86_bytes;
1939           jmp_byte_count = sizeof (jmp_ix86_bytes);
1940           break;
1941         case PE_ARCH_sh:
1942           jmp_bytes = jmp_sh_bytes;
1943           jmp_byte_count = sizeof (jmp_sh_bytes);
1944           break;
1945         case PE_ARCH_mips:
1946           jmp_bytes = jmp_mips_bytes;
1947           jmp_byte_count = sizeof (jmp_mips_bytes);
1948           break;
1949         case PE_ARCH_arm:
1950         case PE_ARCH_arm_epoc:
1951         case PE_ARCH_arm_wince:
1952           jmp_bytes = jmp_arm_bytes;
1953           jmp_byte_count = sizeof (jmp_arm_bytes);
1954           break;
1955         default:
1956           abort ();
1957         }
1958     }
1959
1960   oname = xmalloc (20);
1961   sprintf (oname, "d%06d.o", tmp_seq);
1962   tmp_seq++;
1963
1964   abfd = bfd_create (oname, parent);
1965   bfd_find_target (pe_details->object_target, abfd);
1966   bfd_make_writable (abfd);
1967
1968   bfd_set_format (abfd, bfd_object);
1969   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1970
1971   symptr = 0;
1972   symtab = xmalloc (11 * sizeof (asymbol *));
1973   tx  = quick_section (abfd, ".text",    SEC_CODE|SEC_HAS_CONTENTS, 2);
1974   id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1975   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1976   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1977   id6 = quick_section (abfd, ".idata$6", SEC_HAS_CONTENTS, 2);
1978
1979   if  (*exp->internal_name == '@')
1980     {
1981       quick_symbol (abfd, U ("_head_"), dll_symname, "", UNDSEC,
1982                     BSF_GLOBAL, 0);
1983       if (include_jmp_stub)
1984         quick_symbol (abfd, "", exp->internal_name, "", tx, BSF_GLOBAL, 0);
1985       quick_symbol (abfd, "__imp_", exp->internal_name, "", id5,
1986                     BSF_GLOBAL, 0);
1987       /* Fastcall applies only to functions,
1988          so no need for auto-import symbol.  */
1989     }
1990   else
1991     {
1992       quick_symbol (abfd, U ("_head_"), dll_symname, "", UNDSEC,
1993                     BSF_GLOBAL, 0);
1994       if (include_jmp_stub)
1995         quick_symbol (abfd, U (""), exp->internal_name, "", tx,
1996                       BSF_GLOBAL, 0);
1997       quick_symbol (abfd, "__imp_", U (""), exp->internal_name, id5,
1998                     BSF_GLOBAL, 0);
1999       /* Symbol to reference ord/name of imported
2000          data symbol, used to implement auto-import.  */
2001       if (exp->flag_data)
2002         quick_symbol (abfd, U ("_nm_"), U (""), exp->internal_name, id6,
2003                       BSF_GLOBAL,0);
2004     }
2005   if (pe_dll_compat_implib)
2006     quick_symbol (abfd, U ("__imp_"), exp->internal_name, "", id5,
2007                   BSF_GLOBAL, 0);
2008
2009   if (include_jmp_stub)
2010     {
2011       bfd_set_section_size (abfd, tx, jmp_byte_count);
2012       td = xmalloc (jmp_byte_count);
2013       tx->contents = td;
2014       memcpy (td, jmp_bytes, jmp_byte_count);
2015
2016       switch (pe_details->pe_arch)
2017         {
2018         case PE_ARCH_i386:
2019 #ifdef pe_use_x86_64
2020           quick_reloc (abfd, 2, BFD_RELOC_32_PCREL, 2);
2021 #else
2022           quick_reloc (abfd, 2, BFD_RELOC_32, 2);
2023 #endif
2024           break;
2025         case PE_ARCH_sh:
2026           quick_reloc (abfd, 8, BFD_RELOC_32, 2);
2027           break;
2028         case PE_ARCH_mips:
2029           quick_reloc (abfd, 0, BFD_RELOC_HI16_S, 2);
2030           quick_reloc (abfd, 0, BFD_RELOC_LO16, 0); /* MIPS_R_PAIR */
2031           quick_reloc (abfd, 4, BFD_RELOC_LO16, 2);
2032           break;
2033         case PE_ARCH_arm:
2034         case PE_ARCH_arm_epoc:
2035         case PE_ARCH_arm_wince:
2036           quick_reloc (abfd, 8, BFD_RELOC_32, 2);
2037           break;
2038         default:
2039           abort ();
2040         }
2041       save_relocs (tx);
2042     }
2043   else
2044     bfd_set_section_size (abfd, tx, 0);
2045
2046   bfd_set_section_size (abfd, id7, 4);
2047   d7 = xmalloc (4);
2048   id7->contents = d7;
2049   memset (d7, 0, 4);
2050   quick_reloc (abfd, 0, BFD_RELOC_RVA, 5);
2051   save_relocs (id7);
2052
2053   bfd_set_section_size (abfd, id5, PE_IDATA5_SIZE);
2054   d5 = xmalloc (PE_IDATA5_SIZE);
2055   id5->contents = d5;
2056   memset (d5, 0, PE_IDATA5_SIZE);
2057
2058   if (exp->flag_noname)
2059     {
2060       d5[0] = exp->ordinal;
2061       d5[1] = exp->ordinal >> 8;
2062       d5[PE_IDATA5_SIZE - 1] = 0x80;
2063     }
2064   else
2065     {
2066       quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
2067       save_relocs (id5);
2068     }
2069
2070   bfd_set_section_size (abfd, id4, PE_IDATA4_SIZE);
2071   d4 = xmalloc (PE_IDATA4_SIZE);
2072   id4->contents = d4;
2073   memset (d4, 0, PE_IDATA4_SIZE);
2074
2075   if (exp->flag_noname)
2076     {
2077       d4[0] = exp->ordinal;
2078       d4[1] = exp->ordinal >> 8;
2079       d4[PE_IDATA4_SIZE - 1] = 0x80;
2080     }
2081   else
2082     {
2083       quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
2084       save_relocs (id4);
2085     }
2086
2087   if (exp->flag_noname)
2088     {
2089       len = 0;
2090       bfd_set_section_size (abfd, id6, 0);
2091     }
2092   else
2093     {
2094       /* { short, asciz }  */
2095       len = 2 + strlen (exp->name) + 1;
2096       if (len & 1)
2097         len++;
2098       bfd_set_section_size (abfd, id6, len);
2099       d6 = xmalloc (len);
2100       id6->contents = d6;
2101       memset (d6, 0, len);
2102       d6[0] = exp->hint & 0xff;
2103       d6[1] = exp->hint >> 8;
2104       strcpy ((char *) d6 + 2, exp->name);
2105     }
2106
2107   bfd_set_symtab (abfd, symtab, symptr);
2108
2109   if (include_jmp_stub)
2110     bfd_set_section_contents (abfd, tx, td, 0, jmp_byte_count);
2111   bfd_set_section_contents (abfd, id7, d7, 0, 4);
2112   bfd_set_section_contents (abfd, id5, d5, 0, PE_IDATA5_SIZE);
2113   bfd_set_section_contents (abfd, id4, d4, 0, PE_IDATA4_SIZE);
2114   if (!exp->flag_noname)
2115     bfd_set_section_contents (abfd, id6, d6, 0, len);
2116
2117   bfd_make_readable (abfd);
2118   return abfd;
2119 }
2120
2121 static bfd *
2122 make_singleton_name_thunk (const char *import, bfd *parent)
2123 {
2124   /* Name thunks go to idata$4.  */
2125   asection *id4;
2126   unsigned char *d4;
2127   char *oname;
2128   bfd *abfd;
2129
2130   oname = xmalloc (20);
2131   sprintf (oname, "nmth%06d.o", tmp_seq);
2132   tmp_seq++;
2133
2134   abfd = bfd_create (oname, parent);
2135   bfd_find_target (pe_details->object_target, abfd);
2136   bfd_make_writable (abfd);
2137
2138   bfd_set_format (abfd, bfd_object);
2139   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2140
2141   symptr = 0;
2142   symtab = xmalloc (3 * sizeof (asymbol *));
2143   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
2144   quick_symbol (abfd, U ("_nm_thnk_"), import, "", id4, BSF_GLOBAL, 0);
2145   quick_symbol (abfd, U ("_nm_"), import, "", UNDSEC, BSF_GLOBAL, 0);
2146
2147   /* We need space for the real thunk and for the null terminator.  */
2148   bfd_set_section_size (abfd, id4, PE_IDATA4_SIZE * 2);
2149   d4 = xmalloc (PE_IDATA4_SIZE * 2);
2150   id4->contents = d4;
2151   memset (d4, 0, PE_IDATA4_SIZE * 2);
2152   quick_reloc (abfd, 0, BFD_RELOC_RVA, 2);
2153   save_relocs (id4);
2154
2155   bfd_set_symtab (abfd, symtab, symptr);
2156
2157   bfd_set_section_contents (abfd, id4, d4, 0, PE_IDATA4_SIZE * 2);
2158
2159   bfd_make_readable (abfd);
2160   return abfd;
2161 }
2162
2163 static char *
2164 make_import_fixup_mark (arelent *rel)
2165 {
2166   /* We convert reloc to symbol, for later reference.  */
2167   static int counter;
2168   static char *fixup_name = NULL;
2169   static size_t buffer_len = 0;
2170
2171   struct bfd_symbol *sym = *rel->sym_ptr_ptr;
2172
2173   bfd *abfd = bfd_asymbol_bfd (sym);
2174   struct bfd_link_hash_entry *bh;
2175
2176   if (!fixup_name)
2177     {
2178       fixup_name = xmalloc (384);
2179       buffer_len = 384;
2180     }
2181
2182   if (strlen (sym->name) + 25 > buffer_len)
2183   /* Assume 25 chars for "__fu" + counter + "_".  If counter is
2184      bigger than 20 digits long, we've got worse problems than
2185      overflowing this buffer...  */
2186     {
2187       free (fixup_name);
2188       /* New buffer size is length of symbol, plus 25, but
2189          then rounded up to the nearest multiple of 128.  */
2190       buffer_len = ((strlen (sym->name) + 25) + 127) & ~127;
2191       fixup_name = xmalloc (buffer_len);
2192     }
2193
2194   sprintf (fixup_name, "__fu%d_%s", counter++, sym->name);
2195
2196   bh = NULL;
2197   bfd_coff_link_add_one_symbol (&link_info, abfd, fixup_name, BSF_GLOBAL,
2198                                 current_sec, /* sym->section, */
2199                                 rel->address, NULL, TRUE, FALSE, &bh);
2200
2201   return fixup_name;
2202 }
2203
2204 /*      .section        .idata$2
2205         .rva            __nm_thnk_SYM (singleton thunk with name of func)
2206         .long           0
2207         .long           0
2208         .rva            __my_dll_iname (name of dll)
2209         .rva            __fuNN_SYM (pointer to reference (address) in text)  */
2210
2211 static bfd *
2212 make_import_fixup_entry (const char *name,
2213                          const char *fixup_name,
2214                          const char *dll_symname,
2215                          bfd *parent)
2216 {
2217   asection *id2;
2218   unsigned char *d2;
2219   char *oname;
2220   bfd *abfd;
2221
2222   oname = xmalloc (20);
2223   sprintf (oname, "fu%06d.o", tmp_seq);
2224   tmp_seq++;
2225
2226   abfd = bfd_create (oname, parent);
2227   bfd_find_target (pe_details->object_target, abfd);
2228   bfd_make_writable (abfd);
2229
2230   bfd_set_format (abfd, bfd_object);
2231   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2232
2233   symptr = 0;
2234   symtab = xmalloc (6 * sizeof (asymbol *));
2235   id2 = quick_section (abfd, ".idata$2", SEC_HAS_CONTENTS, 2);
2236
2237   quick_symbol (abfd, U ("_nm_thnk_"), name, "", UNDSEC, BSF_GLOBAL, 0);
2238   quick_symbol (abfd, U (""), dll_symname, "_iname", UNDSEC, BSF_GLOBAL, 0);
2239   quick_symbol (abfd, "", fixup_name, "", UNDSEC, BSF_GLOBAL, 0);
2240
2241   bfd_set_section_size (abfd, id2, 20);
2242   d2 = xmalloc (20);
2243   id2->contents = d2;
2244   memset (d2, 0, 20);
2245   d2[0] = d2[16] = PE_IDATA5_SIZE; /* Reloc addend.  */
2246
2247   quick_reloc (abfd, 0, BFD_RELOC_RVA, 1);
2248   quick_reloc (abfd, 12, BFD_RELOC_RVA, 2);
2249   quick_reloc (abfd, 16, BFD_RELOC_RVA, 3);
2250   save_relocs (id2);
2251
2252   bfd_set_symtab (abfd, symtab, symptr);
2253
2254   bfd_set_section_contents (abfd, id2, d2, 0, 20);
2255
2256   bfd_make_readable (abfd);
2257   return abfd;
2258 }
2259
2260 /*      .section        .rdata_runtime_pseudo_reloc
2261         .long           addend
2262         .rva            __fuNN_SYM (pointer to reference (address) in text)  */
2263
2264 static bfd *
2265 make_runtime_pseudo_reloc (const char *name ATTRIBUTE_UNUSED,
2266                            const char *fixup_name,
2267                            bfd_vma addend ATTRIBUTE_UNUSED,
2268                            bfd_vma bitsize,
2269                            bfd *parent)
2270 {
2271   asection *rt_rel;
2272   unsigned char *rt_rel_d;
2273   char *oname;
2274   bfd *abfd;
2275   oname = xmalloc (20);
2276   sprintf (oname, "rtr%06d.o", tmp_seq);
2277   tmp_seq++;
2278
2279   abfd = bfd_create (oname, parent);
2280   bfd_find_target (pe_details->object_target, abfd);
2281   bfd_make_writable (abfd);
2282
2283   bfd_set_format (abfd, bfd_object);
2284   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2285
2286   symptr = 0;
2287   symtab = xmalloc (2 * sizeof (asymbol *));
2288   rt_rel = quick_section (abfd, ".rdata_runtime_pseudo_reloc",
2289                           SEC_HAS_CONTENTS, 2);
2290
2291   quick_symbol (abfd, "", fixup_name, "", UNDSEC, BSF_GLOBAL, 0);
2292
2293   if (link_info.pei386_runtime_pseudo_reloc == 2)
2294     {
2295           size_t size = 12;
2296           if (! runtime_pseudp_reloc_v2_init)
2297             {
2298                   size += 12;
2299                   runtime_pseudp_reloc_v2_init = 1;
2300             }
2301       quick_symbol (abfd, U ("_imp_"), name, "", UNDSEC, BSF_GLOBAL, 0);
2302
2303       bfd_set_section_size (abfd, rt_rel, size);
2304       rt_rel_d = xmalloc (size);
2305       rt_rel->contents = rt_rel_d;
2306       memset (rt_rel_d, 0, size);
2307           quick_reloc (abfd, size - 8, BFD_RELOC_RVA, 1);
2308           quick_reloc (abfd, size - 12, BFD_RELOC_RVA, 2);
2309           bfd_put_32 (abfd, bitsize, rt_rel_d + (size - 4));
2310           if (size != 12)
2311             bfd_put_32 (abfd, 1, rt_rel_d + 8);
2312       save_relocs (rt_rel);
2313
2314       bfd_set_symtab (abfd, symtab, symptr);
2315
2316       bfd_set_section_contents (abfd, rt_rel, rt_rel_d, 0, size);
2317    }
2318   else
2319    {
2320       bfd_set_section_size (abfd, rt_rel, 8);
2321       rt_rel_d = xmalloc (8);
2322       rt_rel->contents = rt_rel_d;
2323       memset (rt_rel_d, 0, 8);
2324
2325       bfd_put_32 (abfd, addend, rt_rel_d);
2326       quick_reloc (abfd, 4, BFD_RELOC_RVA, 1);
2327
2328       save_relocs (rt_rel);
2329
2330       bfd_set_symtab (abfd, symtab, symptr);
2331
2332       bfd_set_section_contents (abfd, rt_rel, rt_rel_d, 0, 8);
2333    }
2334   bfd_make_readable (abfd);
2335   return abfd;
2336 }
2337
2338 /*      .section        .rdata
2339         .rva            __pei386_runtime_relocator  */
2340
2341 static bfd *
2342 pe_create_runtime_relocator_reference (bfd *parent)
2343 {
2344   asection *extern_rt_rel;
2345   unsigned char *extern_rt_rel_d;
2346   char *oname;
2347   bfd *abfd;
2348
2349   oname = xmalloc (20);
2350   sprintf (oname, "ertr%06d.o", tmp_seq);
2351   tmp_seq++;
2352
2353   abfd = bfd_create (oname, parent);
2354   bfd_find_target (pe_details->object_target, abfd);
2355   bfd_make_writable (abfd);
2356
2357   bfd_set_format (abfd, bfd_object);
2358   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2359
2360   symptr = 0;
2361   symtab = xmalloc (2 * sizeof (asymbol *));
2362   extern_rt_rel = quick_section (abfd, ".rdata", SEC_HAS_CONTENTS, 2);
2363
2364   quick_symbol (abfd, "", U ("_pei386_runtime_relocator"), "", UNDSEC,
2365                 BSF_NO_FLAGS, 0);
2366
2367   bfd_set_section_size (abfd, extern_rt_rel, 4);
2368   extern_rt_rel_d = xmalloc (4);
2369   extern_rt_rel->contents = extern_rt_rel_d;
2370
2371   quick_reloc (abfd, 0, BFD_RELOC_RVA, 1);
2372   save_relocs (extern_rt_rel);
2373
2374   bfd_set_symtab (abfd, symtab, symptr);
2375
2376   bfd_set_section_contents (abfd, extern_rt_rel, extern_rt_rel_d, 0, 4);
2377
2378   bfd_make_readable (abfd);
2379   return abfd;
2380 }
2381
2382 void
2383 pe_create_import_fixup (arelent *rel, asection *s, bfd_vma addend)
2384 {
2385   char buf[300];
2386   struct bfd_symbol *sym = *rel->sym_ptr_ptr;
2387   struct bfd_link_hash_entry *name_thunk_sym;
2388   const char *name = sym->name;
2389   char *fixup_name = make_import_fixup_mark (rel);
2390   bfd *b;
2391
2392   sprintf (buf, U ("_nm_thnk_%s"), name);
2393
2394   name_thunk_sym = bfd_link_hash_lookup (link_info.hash, buf, 0, 0, 1);
2395
2396   if (!name_thunk_sym || name_thunk_sym->type != bfd_link_hash_defined)
2397     {
2398       bfd *b = make_singleton_name_thunk (name, link_info.output_bfd);
2399       add_bfd_to_link (b, b->filename, &link_info);
2400
2401       /* If we ever use autoimport, we have to cast text section writable.  */
2402       config.text_read_only = FALSE;
2403       link_info.output_bfd->flags &= ~WP_TEXT;   
2404     }
2405
2406   if (addend == 0 || link_info.pei386_runtime_pseudo_reloc)
2407     {
2408       extern char * pe_data_import_dll;
2409       char * dll_symname = pe_data_import_dll ? pe_data_import_dll : "unknown";
2410
2411       b = make_import_fixup_entry (name, fixup_name, dll_symname,
2412                                    link_info.output_bfd);
2413       add_bfd_to_link (b, b->filename, &link_info);
2414     }
2415
2416     if ((link_info.pei386_runtime_pseudo_reloc != 0 && addend != 0)
2417         || link_info.pei386_runtime_pseudo_reloc == 2)
2418       {
2419         if (pe_dll_extra_pe_debug)
2420           printf ("creating runtime pseudo-reloc entry for %s (addend=%d)\n",
2421                   fixup_name, (int) addend);
2422
2423         b = make_runtime_pseudo_reloc (name, fixup_name, addend, rel->howto->bitsize,
2424                                        link_info.output_bfd);
2425         add_bfd_to_link (b, b->filename, &link_info);
2426
2427         if (runtime_pseudo_relocs_created == 0)
2428           {
2429             b = pe_create_runtime_relocator_reference (link_info.output_bfd);
2430             add_bfd_to_link (b, b->filename, &link_info);
2431           }
2432         runtime_pseudo_relocs_created++;
2433       }
2434     else if (addend != 0)
2435       {
2436         einfo (_("%C: variable '%T' can't be auto-imported. Please read the documentation for ld's --enable-auto-import for details.\n"),
2437                s->owner, s, rel->address, sym->name);
2438         einfo ("%X");
2439       }
2440 }
2441
2442
2443 void
2444 pe_dll_generate_implib (def_file *def, const char *impfilename)
2445 {
2446   int i;
2447   bfd *ar_head;
2448   bfd *ar_tail;
2449   bfd *outarch;
2450   bfd *head = 0;
2451
2452   dll_filename = (def->name) ? def->name : dll_name;
2453   dll_symname = xstrdup (dll_filename);
2454   for (i = 0; dll_symname[i]; i++)
2455     if (!ISALNUM (dll_symname[i]))
2456       dll_symname[i] = '_';
2457
2458   unlink_if_ordinary (impfilename);
2459
2460   outarch = bfd_openw (impfilename, 0);
2461
2462   if (!outarch)
2463     {
2464       /* xgettext:c-format */
2465       einfo (_("%XCan't open .lib file: %s\n"), impfilename);
2466       return;
2467     }
2468
2469   /* xgettext:c-format */
2470   info_msg (_("Creating library file: %s\n"), impfilename);
2471  
2472   bfd_set_format (outarch, bfd_archive);
2473   outarch->has_armap = 1;
2474
2475   /* Work out a reasonable size of things to put onto one line.  */
2476   ar_head = make_head (outarch);
2477
2478   for (i = 0; i < def->num_exports; i++)
2479     {
2480       /* The import library doesn't know about the internal name.  */
2481       char *internal = def->exports[i].internal_name;
2482       bfd *n;
2483
2484       /* Don't add PRIVATE entries to import lib.  */   
2485       if (pe_def_file->exports[i].flag_private)
2486         continue;
2487       def->exports[i].internal_name = def->exports[i].name;
2488       n = make_one (def->exports + i, outarch,
2489                     ! (def->exports + i)->flag_data);
2490       n->archive_next = head;
2491       head = n;
2492       def->exports[i].internal_name = internal;
2493     }
2494
2495   ar_tail = make_tail (outarch);
2496
2497   if (ar_head == NULL || ar_tail == NULL)
2498     return;
2499
2500   /* Now stick them all into the archive.  */
2501   ar_head->archive_next = head;
2502   ar_tail->archive_next = ar_head;
2503   head = ar_tail;
2504
2505   if (! bfd_set_archive_head (outarch, head))
2506     einfo ("%Xbfd_set_archive_head: %E\n");
2507
2508   if (! bfd_close (outarch))
2509     einfo ("%Xbfd_close %s: %E\n", impfilename);
2510
2511   while (head != NULL)
2512     {
2513       bfd *n = head->archive_next;
2514       bfd_close (head);
2515       head = n;
2516     }
2517 }
2518
2519 static void
2520 add_bfd_to_link (bfd *abfd, const char *name, struct bfd_link_info *link_info)
2521 {
2522   lang_input_statement_type *fake_file;
2523
2524   fake_file = lang_add_input_file (name,
2525                                    lang_input_file_is_fake_enum,
2526                                    NULL);
2527   fake_file->the_bfd = abfd;
2528   ldlang_add_file (fake_file);
2529
2530   if (!bfd_link_add_symbols (abfd, link_info))
2531     einfo ("%Xaddsym %s: %E\n", name);
2532 }
2533
2534 void
2535 pe_process_import_defs (bfd *output_bfd, struct bfd_link_info *link_info)
2536 {
2537   def_file_module *module;
2538
2539   pe_dll_id_target (bfd_get_target (output_bfd));
2540
2541   if (!pe_def_file)
2542     return;
2543
2544   for (module = pe_def_file->modules; module; module = module->next)
2545     {
2546       int i, do_this_dll;
2547
2548       dll_filename = module->name;
2549       dll_symname = xstrdup (module->name);
2550       for (i = 0; dll_symname[i]; i++)
2551         if (!ISALNUM (dll_symname[i]))
2552           dll_symname[i] = '_';
2553
2554       do_this_dll = 0;
2555
2556       for (i = 0; i < pe_def_file->num_imports; i++)
2557         if (pe_def_file->imports[i].module == module)
2558           {
2559             def_file_export exp;
2560             struct bfd_link_hash_entry *blhe;
2561             int lead_at = (*pe_def_file->imports[i].internal_name == '@');
2562             /* See if we need this import.  */
2563             size_t len = strlen (pe_def_file->imports[i].internal_name);
2564             char *name = xmalloc (len + 2 + 6);
2565             bfd_boolean include_jmp_stub = FALSE;
2566
2567             if (lead_at)
2568               sprintf (name, "%s",
2569                        pe_def_file->imports[i].internal_name);
2570             else
2571               sprintf (name, "%s%s",U (""),
2572                        pe_def_file->imports[i].internal_name);
2573
2574             blhe = bfd_link_hash_lookup (link_info->hash, name,
2575                                          FALSE, FALSE, FALSE);
2576
2577             /* Include the jump stub for <sym> only if the <sym>
2578                is undefined.  */
2579             if (!blhe || (blhe && blhe->type != bfd_link_hash_undefined))
2580               {
2581                 if (lead_at)
2582                   sprintf (name, "%s%s", "__imp_", 
2583                            pe_def_file->imports[i].internal_name);
2584                 else
2585                   sprintf (name, "%s%s%s", "__imp_", U (""),
2586                            pe_def_file->imports[i].internal_name);
2587
2588                 blhe = bfd_link_hash_lookup (link_info->hash, name,
2589                                              FALSE, FALSE, FALSE);
2590               }
2591             else
2592               include_jmp_stub = TRUE;
2593
2594             free (name);
2595
2596             if (blhe && blhe->type == bfd_link_hash_undefined)
2597               {
2598                 bfd *one;
2599                 /* We do.  */
2600                 if (!do_this_dll)
2601                   {
2602                     bfd *ar_head = make_head (output_bfd);
2603                     add_bfd_to_link (ar_head, ar_head->filename, link_info);
2604                     do_this_dll = 1;
2605                   }
2606                 exp.internal_name = pe_def_file->imports[i].internal_name;
2607                 exp.name = pe_def_file->imports[i].name;
2608                 exp.ordinal = pe_def_file->imports[i].ordinal;
2609                 exp.hint = exp.ordinal >= 0 ? exp.ordinal : 0;
2610                 exp.flag_private = 0;
2611                 exp.flag_constant = 0;
2612                 exp.flag_data = pe_def_file->imports[i].data;
2613                 exp.flag_noname = exp.name ? 0 : 1;
2614                 one = make_one (&exp, output_bfd, (! exp.flag_data) && include_jmp_stub);
2615                 add_bfd_to_link (one, one->filename, link_info);
2616               }
2617           }
2618       if (do_this_dll)
2619         {
2620           bfd *ar_tail = make_tail (output_bfd);
2621           add_bfd_to_link (ar_tail, ar_tail->filename, link_info);
2622         }
2623
2624       free (dll_symname);
2625     }
2626 }
2627
2628 /* We were handed a *.DLL file.  Parse it and turn it into a set of
2629    IMPORTS directives in the def file.  Return TRUE if the file was
2630    handled, FALSE if not.  */
2631
2632 static unsigned int
2633 pe_get16 (bfd *abfd, int where)
2634 {
2635   unsigned char b[2];
2636
2637   bfd_seek (abfd, (file_ptr) where, SEEK_SET);
2638   bfd_bread (b, (bfd_size_type) 2, abfd);
2639   return b[0] + (b[1] << 8);
2640 }
2641
2642 static unsigned int
2643 pe_get32 (bfd *abfd, int where)
2644 {
2645   unsigned char b[4];
2646
2647   bfd_seek (abfd, (file_ptr) where, SEEK_SET);
2648   bfd_bread (b, (bfd_size_type) 4, abfd);
2649   return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
2650 }
2651
2652 static unsigned int
2653 pe_as32 (void *ptr)
2654 {
2655   unsigned char *b = ptr;
2656
2657   return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
2658 }
2659
2660 bfd_boolean
2661 pe_implied_import_dll (const char *filename)
2662 {
2663   bfd *dll;
2664   bfd_vma pe_header_offset, opthdr_ofs, num_entries, i;
2665   bfd_vma export_rva, export_size, nsections, secptr, expptr;
2666   bfd_vma exp_funcbase;
2667   unsigned char *expdata;
2668   char *erva;
2669   bfd_vma name_rvas, ordinals, nexp, ordbase;
2670   const char *dll_name;
2671   /* Initialization with start > end guarantees that is_data
2672      will not be set by mistake, and avoids compiler warning.  */
2673   bfd_vma data_start = 1;
2674   bfd_vma data_end = 0;
2675   bfd_vma rdata_start = 1;
2676   bfd_vma rdata_end = 0;
2677   bfd_vma bss_start = 1;
2678   bfd_vma bss_end = 0;
2679
2680   /* No, I can't use bfd here.  kernel32.dll puts its export table in
2681      the middle of the .rdata section.  */
2682   dll = bfd_openr (filename, pe_details->target_name);
2683   if (!dll)
2684     {
2685       einfo ("%Xopen %s: %E\n", filename);
2686       return FALSE;
2687     }
2688
2689   /* PEI dlls seem to be bfd_objects.  */
2690   if (!bfd_check_format (dll, bfd_object))
2691     {
2692       einfo ("%X%s: this doesn't appear to be a DLL\n", filename);
2693       return FALSE;
2694     }
2695
2696   /* Get pe_header, optional header and numbers of export entries.  */
2697   pe_header_offset = pe_get32 (dll, 0x3c);
2698   opthdr_ofs = pe_header_offset + 4 + 20;
2699 #ifdef pe_use_x86_64
2700   num_entries = pe_get32 (dll, opthdr_ofs + 92 + 4 * 4); /*  & NumberOfRvaAndSizes.  */
2701 #else
2702   num_entries = pe_get32 (dll, opthdr_ofs + 92);
2703 #endif
2704
2705   if (num_entries < 1) /* No exports.  */
2706     return FALSE;
2707
2708 #ifdef pe_use_x86_64
2709   export_rva  = pe_get32 (dll, opthdr_ofs + 96 + 4 * 4);
2710   export_size = pe_get32 (dll, opthdr_ofs + 100 + 4 * 4);
2711 #else
2712   export_rva = pe_get32 (dll, opthdr_ofs + 96);
2713   export_size = pe_get32 (dll, opthdr_ofs + 100);
2714 #endif
2715   
2716   nsections = pe_get16 (dll, pe_header_offset + 4 + 2);
2717   secptr = (pe_header_offset + 4 + 20 +
2718             pe_get16 (dll, pe_header_offset + 4 + 16));
2719   expptr = 0;
2720
2721   /* Get the rva and size of the export section.  */
2722   for (i = 0; i < nsections; i++)
2723     {
2724       char sname[8];
2725       bfd_vma secptr1 = secptr + 40 * i;
2726       bfd_vma vaddr = pe_get32 (dll, secptr1 + 12);
2727       bfd_vma vsize = pe_get32 (dll, secptr1 + 16);
2728       bfd_vma fptr = pe_get32 (dll, secptr1 + 20);
2729
2730       bfd_seek (dll, (file_ptr) secptr1, SEEK_SET);
2731       bfd_bread (sname, (bfd_size_type) 8, dll);
2732
2733       if (vaddr <= export_rva && vaddr + vsize > export_rva)
2734         {
2735           expptr = fptr + (export_rva - vaddr);
2736           if (export_rva + export_size > vaddr + vsize)
2737             export_size = vsize - (export_rva - vaddr);
2738           break;
2739         }
2740     }
2741
2742   /* Scan sections and store the base and size of the
2743      data and bss segments in data/base_start/end.  */
2744   for (i = 0; i < nsections; i++)
2745     {
2746       bfd_vma secptr1 = secptr + 40 * i;
2747       bfd_vma vsize = pe_get32 (dll, secptr1 + 8);
2748       bfd_vma vaddr = pe_get32 (dll, secptr1 + 12);
2749       bfd_vma flags = pe_get32 (dll, secptr1 + 36);
2750       char sec_name[9];
2751
2752       sec_name[8] = '\0';
2753       bfd_seek (dll, (file_ptr) secptr1 + 0, SEEK_SET);
2754       bfd_bread (sec_name, (bfd_size_type) 8, dll);
2755
2756       if (strcmp(sec_name,".data") == 0)
2757         {
2758           data_start = vaddr;
2759           data_end = vaddr + vsize;
2760
2761           if (pe_dll_extra_pe_debug)
2762             printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2763                     __FUNCTION__, sec_name, (unsigned long) vaddr,
2764                     (unsigned long) (vaddr + vsize), (unsigned long) flags);
2765         }
2766       else if (strcmp(sec_name,".rdata") == 0)
2767         {
2768           rdata_start = vaddr;
2769           rdata_end = vaddr + vsize;
2770
2771           if (pe_dll_extra_pe_debug)
2772             printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2773                     __FUNCTION__, sec_name, (unsigned long) vaddr,
2774                     (unsigned long) (vaddr + vsize), (unsigned long) flags);
2775         }
2776       else if (strcmp (sec_name,".bss") == 0)
2777         {
2778           bss_start = vaddr;
2779           bss_end = vaddr + vsize;
2780
2781           if (pe_dll_extra_pe_debug)
2782             printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2783                     __FUNCTION__, sec_name, (unsigned long) vaddr,
2784                     (unsigned long) (vaddr + vsize), (unsigned long) flags);
2785         }
2786     }
2787
2788   expdata = xmalloc (export_size);
2789   bfd_seek (dll, (file_ptr) expptr, SEEK_SET);
2790   bfd_bread (expdata, (bfd_size_type) export_size, dll);
2791   erva = (char *) expdata - export_rva;
2792
2793   if (pe_def_file == 0)
2794     pe_def_file = def_file_empty ();
2795
2796   nexp = pe_as32 (expdata + 24);
2797   name_rvas = pe_as32 (expdata + 32);
2798   ordinals = pe_as32 (expdata + 36);
2799   ordbase = pe_as32 (expdata + 16);
2800   exp_funcbase = pe_as32 (expdata + 28);
2801
2802   /* Use internal dll name instead of filename
2803      to enable symbolic dll linking.  */
2804   dll_name = erva + pe_as32 (expdata + 12);
2805
2806   /* Check to see if the dll has already been added to
2807      the definition list and if so return without error.
2808      This avoids multiple symbol definitions.  */
2809   if (def_get_module (pe_def_file, dll_name))
2810     {
2811       if (pe_dll_extra_pe_debug)
2812         printf ("%s is already loaded\n", dll_name);
2813       return TRUE;
2814     }
2815
2816   /* Iterate through the list of symbols.  */
2817   for (i = 0; i < nexp; i++)
2818     {
2819       /* Pointer to the names vector.  */
2820       bfd_vma name_rva = pe_as32 (erva + name_rvas + i * 4);
2821       def_file_import *imp;
2822       /* Pointer to the function address vector.  */
2823       bfd_vma func_rva = pe_as32 (erva + exp_funcbase + i * 4);
2824       int is_data = 0;
2825
2826       /* Skip unwanted symbols, which are
2827          exported in buggy auto-import releases.  */
2828       if (! CONST_STRNEQ (erva + name_rva, "_nm_"))
2829         {
2830           /* is_data is true if the address is in the data, rdata or bss
2831              segment.  */
2832           is_data =
2833             (func_rva >= data_start && func_rva < data_end)
2834             || (func_rva >= rdata_start && func_rva < rdata_end)
2835             || (func_rva >= bss_start && func_rva < bss_end);
2836
2837           imp = def_file_add_import (pe_def_file, erva + name_rva,
2838                                      dll_name, i, 0);
2839           /* Mark symbol type.  */
2840           imp->data = is_data;
2841
2842           if (pe_dll_extra_pe_debug)
2843             printf ("%s dll-name: %s sym: %s addr: 0x%lx %s\n",
2844                     __FUNCTION__, dll_name, erva + name_rva,
2845                     (unsigned long) func_rva, is_data ? "(data)" : "");
2846         }
2847     }
2848
2849   return TRUE;
2850 }
2851
2852 /* These are the main functions, called from the emulation.  The first
2853    is called after the bfds are read, so we can guess at how much space
2854    we need.  The second is called after everything is placed, so we
2855    can put the right values in place.  */
2856
2857 void
2858 pe_dll_build_sections (bfd *abfd, struct bfd_link_info *info)
2859 {
2860   pe_dll_id_target (bfd_get_target (abfd));
2861   process_def_file (abfd, info);
2862
2863   if (pe_def_file->num_exports == 0 && !info->shared)
2864     return;
2865
2866   generate_edata (abfd, info);
2867   build_filler_bfd (1);
2868 }
2869
2870 void
2871 pe_exe_build_sections (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
2872 {
2873   pe_dll_id_target (bfd_get_target (abfd));
2874   build_filler_bfd (0);
2875 }
2876
2877 void
2878 pe_dll_fill_sections (bfd *abfd, struct bfd_link_info *info)
2879 {
2880   pe_dll_id_target (bfd_get_target (abfd));
2881   image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2882
2883   generate_reloc (abfd, info);
2884   if (reloc_sz > 0)
2885     {
2886       bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2887
2888       /* Resize the sections.  */
2889       lang_reset_memory_regions ();
2890       lang_size_sections (NULL, TRUE);
2891
2892       /* Redo special stuff.  */
2893       ldemul_after_allocation ();
2894
2895       /* Do the assignments again.  */
2896       lang_do_assignments ();
2897     }
2898
2899   fill_edata (abfd, info);
2900
2901   if (info->shared && !info->pie)
2902     pe_data (abfd)->dll = 1;
2903
2904   edata_s->contents = edata_d;
2905   reloc_s->contents = reloc_d;
2906 }
2907
2908 void
2909 pe_exe_fill_sections (bfd *abfd, struct bfd_link_info *info)
2910 {
2911   pe_dll_id_target (bfd_get_target (abfd));
2912   image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2913
2914   generate_reloc (abfd, info);
2915   if (reloc_sz > 0)
2916     {
2917       bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2918
2919       /* Resize the sections.  */
2920       lang_reset_memory_regions ();
2921       lang_size_sections (NULL, TRUE);
2922
2923       /* Redo special stuff.  */
2924       ldemul_after_allocation ();
2925
2926       /* Do the assignments again.  */
2927       lang_do_assignments ();
2928     }
2929   reloc_s->contents = reloc_d;
2930 }
2931
2932 bfd_boolean
2933 pe_bfd_is_dll (bfd *abfd)
2934 {
2935   return (bfd_get_format (abfd) == bfd_object
2936           && obj_pe (abfd)
2937           && pe_data (abfd)->dll);
2938 }