* deffilep.y (tokens): Add upper and lower case versions of DATA,
[platform/upstream/binutils.git] / ld / pe-dll.c
1 /* Routines to help build PEI-format DLLs (Win32 etc)
2    Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3    Written by DJ Delorie <dj@cygnus.com>
4
5    This file is part of GLD, the Gnu Linker.
6
7    GLD is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GLD is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GLD; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21
22 #include "bfd.h"
23 #include "sysdep.h"
24 #include "bfdlink.h"
25 #include "libiberty.h"
26
27 #include <time.h>
28 #include <ctype.h>
29
30 #include "ld.h"
31 #include "ldexp.h"
32 #include "ldlang.h"
33 #include "ldwrite.h"
34 #include "ldmisc.h"
35 #include "ldgram.h"
36 #include "ldmain.h"
37 #include "ldemul.h"
38 #include "coff/internal.h"
39 #include "../bfd/libcoff.h"
40 #include "deffile.h"
41 #include "pe-dll.h"
42
43 /************************************************************************
44
45  This file turns a regular Windows PE image into a DLL.  Because of
46  the complexity of this operation, it has been broken down into a
47  number of separate modules which are all called by the main function
48  at the end of this file.  This function is not re-entrant and is
49  normally only called once, so static variables are used to reduce
50  the number of parameters and return values required.
51
52  See also: ld/emultempl/pe.em
53
54  ************************************************************************/
55
56 /* for emultempl/pe.em */
57
58 def_file *pe_def_file = 0;
59 int pe_dll_export_everything = 0;
60 int pe_dll_do_default_excludes = 1;
61 int pe_dll_kill_ats = 0;
62 int pe_dll_stdcall_aliases = 0;
63
64 /************************************************************************
65
66  static variables and types
67
68  ************************************************************************/
69
70 static bfd_vma image_base;
71
72 static bfd *filler_bfd;
73 static struct sec *edata_s, *reloc_s;
74 static unsigned char *edata_d, *reloc_d;
75 static size_t edata_sz, reloc_sz;
76
77 typedef struct {
78   char *target_name;
79   char *object_target;
80   unsigned int imagebase_reloc;
81   int pe_arch;
82   int bfd_arch;
83   int underscored;
84 } pe_details_type;
85
86 #define PE_ARCH_i386    1
87
88 static pe_details_type pe_detail_list[] = {
89   {
90     "pei-i386",
91     "pe-i386",
92     7 /* R_IMAGEBASE */,
93     PE_ARCH_i386,
94     bfd_arch_i386,
95     1
96   },
97   { NULL, NULL, 0, 0, 0, 0 }
98 };
99
100 static pe_details_type *pe_details;
101
102 #define U(str) (pe_details->underscored ? "_" str : str)
103
104 void
105 pe_dll_id_target (target)
106      const char *target;
107 {
108   int i;
109   for (i=0; pe_detail_list[i].target_name; i++)
110     if (strcmp (pe_detail_list[i].target_name, target) == 0)
111       {
112         pe_details = pe_detail_list+i;
113         return;
114       }
115   einfo (_("%XUnsupported PEI architecture: %s\n"), target);
116   exit (1);
117 }
118
119 /************************************************************************
120
121  Helper functions for qsort.  Relocs must be sorted so that we can write
122  them out by pages.
123
124  ************************************************************************/
125
126 typedef struct {
127   bfd_vma vma;
128   char type;
129   short extra;
130 } reloc_data_type;
131
132 static int
133 reloc_sort (va, vb)
134      const void *va, *vb;
135 {
136   bfd_vma a = ((reloc_data_type *) va)->vma;
137   bfd_vma b = ((reloc_data_type *) vb)->vma;
138   return (a > b) ? 1 : ((a < b) ? -1 : 0);
139 }
140
141 static int
142 pe_export_sort (va, vb)
143      const void *va, *vb;
144 {
145   def_file_export *a = (def_file_export *) va;
146   def_file_export *b = (def_file_export *) vb;
147   return strcmp (a->name, b->name);
148 }
149
150 /************************************************************************
151
152  Read and process the .DEF file
153
154  ************************************************************************/
155
156 /* These correspond to the entries in pe_def_file->exports[].  I use
157    exported_symbol_sections[i] to tag whether or not the symbol was
158    defined, since we can't export symbols we don't have. */
159
160 static bfd_vma *exported_symbol_offsets;
161 static struct sec **exported_symbol_sections;
162
163 static int export_table_size;
164 static int count_exported;
165 static int count_exported_byname;
166 static int count_with_ordinals;
167 static const char *dll_name;
168 static int min_ordinal, max_ordinal;
169 static int *exported_symbols;
170
171 typedef struct exclude_list_struct
172   {
173     char *string;
174     struct exclude_list_struct *next;
175   }
176 exclude_list_struct;
177 static struct exclude_list_struct *excludes = 0;
178
179 void
180 pe_dll_add_excludes (new_excludes)
181      const char *new_excludes;
182 {
183   char *local_copy;
184   char *exclude_string;
185
186   local_copy = xstrdup (new_excludes);
187
188   exclude_string = strtok (local_copy, ",:");
189   for (; exclude_string; exclude_string = strtok (NULL, ",:"))
190     {
191       struct exclude_list_struct *new_exclude;
192
193       new_exclude = ((struct exclude_list_struct *)
194                      xmalloc (sizeof (struct exclude_list_struct)));
195       new_exclude->string = (char *) xmalloc (strlen (exclude_string) + 1);
196       strcpy (new_exclude->string, exclude_string);
197       new_exclude->next = excludes;
198       excludes = new_exclude;
199     }
200
201   free (local_copy);
202 }
203
204 static int
205 auto_export (d, n)
206      def_file *d;
207      const char *n;
208 {
209   int i;
210   struct exclude_list_struct *ex;
211   for (i = 0; i < d->num_exports; i++)
212     if (strcmp (d->exports[i].name, n) == 0)
213       return 0;
214   if (pe_dll_do_default_excludes)
215     {
216       if (strcmp (n, "DllMain@12") == 0)
217         return 0;
218       if (strcmp (n, "DllEntryPoint@0") == 0)
219         return 0;
220       if (strcmp (n, "impure_ptr") == 0)
221         return 0;
222     }
223   for (ex = excludes; ex; ex = ex->next)
224     if (strcmp (n, ex->string) == 0)
225       return 0;
226   return 1;
227 }
228
229 static void
230 process_def_file (abfd, info)
231      bfd *abfd ATTRIBUTE_UNUSED;
232      struct bfd_link_info *info;
233 {
234   int i, j;
235   struct bfd_link_hash_entry *blhe;
236   bfd *b;
237   struct sec *s;
238   def_file_export *e=0;
239
240   if (!pe_def_file)
241     pe_def_file = def_file_empty ();
242
243   /* First, run around to all the objects looking for the .drectve
244      sections, and push those into the def file too */
245
246   for (b = info->input_bfds; b; b = b->link_next)
247     {
248       s = bfd_get_section_by_name (b, ".drectve");
249       if (s)
250         {
251           int size = bfd_get_section_size_before_reloc (s);
252           char *buf = xmalloc (size);
253           bfd_get_section_contents (b, s, buf, 0, size);
254           def_file_add_directive (pe_def_file, buf, size);
255           free (buf);
256         }
257     }
258
259   /* Now, maybe export everything else the default way */
260
261   if (pe_dll_export_everything || pe_def_file->num_exports == 0)
262     {
263       for (b = info->input_bfds; b; b = b->link_next)
264         {
265           asymbol **symbols;
266           int nsyms, symsize;
267
268           symsize = bfd_get_symtab_upper_bound (b);
269           symbols = (asymbol **) xmalloc (symsize);
270           nsyms = bfd_canonicalize_symtab (b, symbols);
271
272           for (j = 0; j < nsyms; j++)
273             {
274               if ((symbols[j]->flags & (BSF_FUNCTION | BSF_GLOBAL))
275                   == (BSF_FUNCTION | BSF_GLOBAL))
276                 {
277                   const char *sn = symbols[j]->name;
278                   if (*sn == '_')
279                     sn++;
280                   if (auto_export (pe_def_file, sn))
281                     def_file_add_export (pe_def_file, sn, 0, -1);
282                 }
283             }
284         }
285     }
286
287 #undef NE
288 #define NE pe_def_file->num_exports
289
290   /* Canonicalize the export list */
291
292   if (pe_dll_kill_ats)
293     {
294       for (i = 0; i < NE; i++)
295         {
296           if (strchr (pe_def_file->exports[i].name, '@'))
297             {
298               /* This will preserve internal_name, which may have been pointing
299                  to the same memory as name, or might not have */
300               char *tmp = xstrdup (pe_def_file->exports[i].name);
301               *(strchr (tmp, '@')) = 0;
302               pe_def_file->exports[i].name = tmp;
303             }
304         }
305     }
306
307   if (pe_dll_stdcall_aliases)
308     {
309       for (i = 0; i < NE; i++)
310         {
311           if (strchr (pe_def_file->exports[i].name, '@'))
312             {
313               char *tmp = xstrdup (pe_def_file->exports[i].name);
314               *(strchr (tmp, '@')) = 0;
315               if (auto_export (pe_def_file, tmp))
316                 def_file_add_export (pe_def_file, tmp,
317                                      pe_def_file->exports[i].internal_name, -1);
318               else
319                 free (tmp);
320             }
321         }
322     }
323
324   e = pe_def_file->exports; /* convenience, but watch out for it changing */
325
326   exported_symbol_offsets = (bfd_vma *) xmalloc (NE * sizeof (bfd_vma));
327   exported_symbol_sections = (struct sec **) xmalloc (NE * sizeof (struct sec *));
328
329   memset (exported_symbol_sections, 0, NE * sizeof (struct sec *));
330   max_ordinal = 0;
331   min_ordinal = 65536;
332   count_exported = 0;
333   count_exported_byname = 0;
334   count_with_ordinals = 0;
335
336   qsort (pe_def_file->exports, NE, sizeof (pe_def_file->exports[0]), pe_export_sort);
337   for (i = 0, j = 0; i < NE; i++)
338     {
339       if (i > 0 && strcmp (e[i].name, e[i - 1].name) == 0)
340         {
341           /* This is a duplicate */
342           if (e[j - 1].ordinal != -1
343               && e[i].ordinal != -1
344               && e[j - 1].ordinal != e[i].ordinal)
345             {
346               /* xgettext:c-format */
347               einfo (_("%XError, duplicate EXPORT with oridinals: %s (%d vs %d)\n"),
348                      e[j - 1].name, e[j - 1].ordinal, e[i].ordinal);
349             }
350           else
351             {
352               /* xgettext:c-format */
353               einfo (_("Warning, duplicate EXPORT: %s\n"),
354                      e[j - 1].name);
355             }
356           if (e[i].ordinal)
357             e[j - 1].ordinal = e[i].ordinal;
358           e[j - 1].flag_private |= e[i].flag_private;
359           e[j - 1].flag_constant |= e[i].flag_constant;
360           e[j - 1].flag_noname |= e[i].flag_noname;
361           e[j - 1].flag_data |= e[i].flag_data;
362         }
363       else
364         {
365           if (i != j)
366             e[j] = e[i];
367           j++;
368         }
369     }
370   pe_def_file->num_exports = j; /* == NE */
371
372   for (i = 0; i < NE; i++)
373     {
374       char *name = (char *) xmalloc (strlen (pe_def_file->exports[i].internal_name) + 2);
375       if (pe_details->underscored)
376         {
377           *name = '_';
378           strcpy (name + 1, pe_def_file->exports[i].internal_name);
379         }
380       else
381         strcpy (name, pe_def_file->exports[i].internal_name);
382
383       blhe = bfd_link_hash_lookup (info->hash,
384                                    name,
385                                    false, false, true);
386
387       if (blhe && (blhe->type == bfd_link_hash_defined))
388         {
389           count_exported++;
390           if (!pe_def_file->exports[i].flag_noname)
391             count_exported_byname++;
392           exported_symbol_offsets[i] = blhe->u.def.value;
393           exported_symbol_sections[i] = blhe->u.def.section;
394           if (pe_def_file->exports[i].ordinal != -1)
395             {
396               if (max_ordinal < pe_def_file->exports[i].ordinal)
397                 max_ordinal = pe_def_file->exports[i].ordinal;
398               if (min_ordinal > pe_def_file->exports[i].ordinal)
399                 min_ordinal = pe_def_file->exports[i].ordinal;
400               count_with_ordinals++;
401             }
402         }
403       else if (blhe && blhe->type == bfd_link_hash_undefined)
404         {
405           /* xgettext:c-format */
406           einfo (_("%XCannot export %s: symbol not defined\n"),
407                  pe_def_file->exports[i].internal_name);
408         }
409       else if (blhe)
410         {
411           /* xgettext:c-format */
412           einfo (_("%XCannot export %s: symbol wrong type (%d vs %d)\n"),
413                  pe_def_file->exports[i].internal_name,
414                  blhe->type, bfd_link_hash_defined);
415         }
416       else
417         {
418           /* xgettext:c-format */
419           einfo (_("%XCannot export %s: symbol not found\n"),
420                  pe_def_file->exports[i].internal_name);
421         }
422       free (name);
423     }
424 }
425
426 /************************************************************************
427
428  Build the bfd that will contain .edata and .reloc sections
429
430  ************************************************************************/
431
432 static void
433 build_filler_bfd (include_edata)
434      int include_edata;
435 {
436   lang_input_statement_type *filler_file;
437   filler_file = lang_add_input_file ("dll stuff",
438                                      lang_input_file_is_fake_enum,
439                                      NULL);
440   filler_file->the_bfd = filler_bfd = bfd_create ("dll stuff", output_bfd);
441   if (filler_bfd == NULL
442       || !bfd_set_arch_mach (filler_bfd,
443                              bfd_get_arch (output_bfd),
444                              bfd_get_mach (output_bfd)))
445     {
446       einfo ("%X%P: can not create BFD %E\n");
447       return;
448     }
449
450   if (include_edata)
451     {
452       edata_s = bfd_make_section_old_way (filler_bfd, ".edata");
453       if (edata_s == NULL
454           || !bfd_set_section_flags (filler_bfd, edata_s,
455                                      (SEC_HAS_CONTENTS
456                                       | SEC_ALLOC
457                                       | SEC_LOAD
458                                       | SEC_KEEP
459                                       | SEC_IN_MEMORY)))
460         {
461           einfo ("%X%P: can not create .edata section: %E\n");
462           return;
463         }
464       bfd_set_section_size (filler_bfd, edata_s, edata_sz);
465     }
466
467   reloc_s = bfd_make_section_old_way (filler_bfd, ".reloc");
468   if (reloc_s == NULL
469       || !bfd_set_section_flags (filler_bfd, reloc_s,
470                                  (SEC_HAS_CONTENTS
471                                   | SEC_ALLOC
472                                   | SEC_LOAD
473                                   | SEC_KEEP
474                                   | SEC_IN_MEMORY)))
475     {
476       einfo ("%X%P: can not create .reloc section: %E\n");
477       return;
478     }
479   bfd_set_section_size (filler_bfd, reloc_s, 0);
480
481   ldlang_add_file (filler_file);
482 }
483
484 /************************************************************************
485
486  Gather all the exported symbols and build the .edata section
487
488  ************************************************************************/
489
490 static void
491 generate_edata (abfd, info)
492      bfd *abfd;
493      struct bfd_link_info *info ATTRIBUTE_UNUSED;
494 {
495   int i, next_ordinal;
496   int name_table_size = 0;
497   const char *dlnp;
498
499   /* First, we need to know how many exported symbols there are,
500      and what the range of ordinals is. */
501
502   if (pe_def_file->name)
503     {
504       dll_name = pe_def_file->name;
505     }
506   else
507     {
508       dll_name = abfd->filename;
509       for (dlnp = dll_name; *dlnp; dlnp++)
510         {
511           if (*dlnp == '\\' || *dlnp == '/' || *dlnp == ':')
512             dll_name = dlnp + 1;
513         }
514     }
515
516   if (count_with_ordinals && max_ordinal > count_exported)
517     {
518       if (min_ordinal > max_ordinal - count_exported + 1)
519         min_ordinal = max_ordinal - count_exported + 1;
520     }
521   else
522     {
523       min_ordinal = 1;
524       max_ordinal = count_exported;
525     }
526   export_table_size = max_ordinal - min_ordinal + 1;
527
528   exported_symbols = (int *) xmalloc (export_table_size * sizeof (int));
529   for (i = 0; i < export_table_size; i++)
530     exported_symbols[i] = -1;
531
532   /* Now we need to assign ordinals to those that don't have them */
533   for (i = 0; i < NE; i++)
534     {
535       if (exported_symbol_sections[i])
536         {
537           if (pe_def_file->exports[i].ordinal != -1)
538             {
539               int ei = pe_def_file->exports[i].ordinal - min_ordinal;
540               int pi = exported_symbols[ei];
541               if (pi != -1)
542                 {
543                   /* xgettext:c-format */
544                   einfo (_("%XError, oridinal used twice: %d (%s vs %s)\n"),
545                          pe_def_file->exports[i].ordinal,
546                          pe_def_file->exports[i].name,
547                          pe_def_file->exports[pi].name);
548                 }
549               exported_symbols[ei] = i;
550             }
551           name_table_size += strlen (pe_def_file->exports[i].name) + 1;
552         }
553     }
554
555   next_ordinal = min_ordinal;
556   for (i = 0; i < NE; i++)
557     if (exported_symbol_sections[i])
558       if (pe_def_file->exports[i].ordinal == -1)
559         {
560           while (exported_symbols[next_ordinal - min_ordinal] != -1)
561             next_ordinal++;
562           exported_symbols[next_ordinal - min_ordinal] = i;
563           pe_def_file->exports[i].ordinal = next_ordinal;
564         }
565
566   /* OK, now we can allocate some memory */
567
568   edata_sz = (40                /* directory */
569               + 4 * export_table_size   /* addresses */
570               + 4 * count_exported_byname       /* name ptrs */
571               + 2 * count_exported_byname       /* ordinals */
572               + name_table_size + strlen (dll_name) + 1);
573 }
574
575 static void
576 fill_edata (abfd, info)
577      bfd *abfd;
578      struct bfd_link_info *info ATTRIBUTE_UNUSED;
579 {
580   int i, hint;
581   unsigned char *edirectory;
582   unsigned long *eaddresses;
583   unsigned long *enameptrs;
584   unsigned short *eordinals;
585   unsigned char *enamestr;
586   time_t now;
587
588   time (&now);
589
590   edata_d = (unsigned char *) xmalloc (edata_sz);
591
592   /* Note use of array pointer math here */
593   edirectory = edata_d;
594   eaddresses = (unsigned long *) (edata_d + 40);
595   enameptrs = eaddresses + export_table_size;
596   eordinals = (unsigned short *) (enameptrs + count_exported_byname);
597   enamestr = (char *) (eordinals + count_exported_byname);
598
599 #define ERVA(ptr) (((unsigned char *)(ptr) - edata_d) + edata_s->output_section->vma - image_base)
600
601   memset (edata_d, 0, 40);
602   bfd_put_32 (abfd, now, edata_d + 4);
603   if (pe_def_file->version_major != -1)
604     {
605       bfd_put_16 (abfd, pe_def_file->version_major, edata_d + 8);
606       bfd_put_16 (abfd, pe_def_file->version_minor, edata_d + 10);
607     }
608   bfd_put_32 (abfd, ERVA (enamestr), edata_d + 12);
609   strcpy (enamestr, dll_name);
610   enamestr += strlen (enamestr) + 1;
611   bfd_put_32 (abfd, min_ordinal, edata_d + 16);
612   bfd_put_32 (abfd, export_table_size, edata_d + 20);
613   bfd_put_32 (abfd, count_exported_byname, edata_d + 24);
614   bfd_put_32 (abfd, ERVA (eaddresses), edata_d + 28);
615   bfd_put_32 (abfd, ERVA (enameptrs), edata_d + 32);
616   bfd_put_32 (abfd, ERVA (eordinals), edata_d + 36);
617
618   /* Ok, now for the filling in part */
619   hint = 0;
620   for (i = 0; i < export_table_size; i++)
621     {
622       int s = exported_symbols[i];
623       if (s != -1)
624         {
625           struct sec *ssec = exported_symbol_sections[s];
626           unsigned long srva = (exported_symbol_offsets[s]
627                                 + ssec->output_section->vma
628                                 + ssec->output_offset);
629
630           bfd_put_32 (abfd, srva - image_base, (void *) (eaddresses + i));
631           if (!pe_def_file->exports[s].flag_noname)
632             {
633               char *ename = pe_def_file->exports[s].name;
634               bfd_put_32 (abfd, ERVA (enamestr), (void *) enameptrs);
635               strcpy (enamestr, ename);
636               enamestr += strlen (enamestr) + 1;
637               bfd_put_16 (abfd, i, (void *) eordinals);
638               enameptrs++;
639               pe_def_file->exports[s].hint = hint++;
640             }
641           eordinals++;
642         }
643     }
644 }
645
646 /************************************************************************
647
648  Gather all the relocations and build the .reloc section
649
650  ************************************************************************/
651
652 static void
653 generate_reloc (abfd, info)
654      bfd *abfd;
655      struct bfd_link_info *info;
656 {
657
658   /* for .reloc stuff */
659   reloc_data_type *reloc_data;
660   int total_relocs = 0;
661   int i;
662   unsigned long sec_page = (unsigned long) (-1);
663   unsigned long page_ptr, page_count;
664   int bi;
665   bfd *b;
666   struct sec *s;
667
668   total_relocs = 0;
669   for (b = info->input_bfds; b; b = b->link_next)
670     for (s = b->sections; s; s = s->next)
671       total_relocs += s->reloc_count;
672
673   reloc_data = (reloc_data_type *) xmalloc (total_relocs * sizeof (reloc_data_type));
674
675   total_relocs = 0;
676   bi = 0;
677   for (bi = 0, b = info->input_bfds; b; bi++, b = b->link_next)
678     {
679       arelent **relocs;
680       int relsize, nrelocs, i;
681
682       for (s = b->sections; s; s = s->next)
683         {
684           unsigned long sec_vma = s->output_section->vma + s->output_offset;
685           asymbol **symbols;
686           int nsyms, symsize;
687
688           /* if it's not loaded, we don't need to relocate it this way */
689           if (!(s->output_section->flags & SEC_LOAD))
690             continue;
691
692           /* I don't know why there would be a reloc for these, but I've
693              seen it happen - DJ */
694           if (s->output_section == &bfd_abs_section)
695             continue;
696
697           if (s->output_section->vma == 0)
698             {
699               /* Huh?  Shouldn't happen, but punt if it does */
700               einfo ("DJ: zero vma section reloc detected: `%s' #%d f=%d\n",
701                      s->output_section->name, s->output_section->index,
702                      s->output_section->flags);
703               continue;
704             }
705
706           symsize = bfd_get_symtab_upper_bound (b);
707           symbols = (asymbol **) xmalloc (symsize);
708           nsyms = bfd_canonicalize_symtab (b, symbols);
709
710           relsize = bfd_get_reloc_upper_bound (b, s);
711           relocs = (arelent **) xmalloc ((size_t) relsize);
712           nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
713
714           for (i = 0; i < nrelocs; i++)
715             {
716               if (!relocs[i]->howto->pc_relative
717                   && relocs[i]->howto->type != pe_details->imagebase_reloc)
718                 {
719                   bfd_vma sym_vma;
720                   struct symbol_cache_entry *sym = *relocs[i]->sym_ptr_ptr;
721                   sym_vma = (relocs[i]->addend
722                              + sym->value
723                              + sym->section->vma
724                              + sym->section->output_offset
725                              + sym->section->output_section->vma);
726                   reloc_data[total_relocs].vma = sec_vma + relocs[i]->address;
727                   switch (relocs[i]->howto->bitsize*1000
728                           + relocs[i]->howto->rightshift)
729                     {
730                     case 32000:
731                       reloc_data[total_relocs].type = 3;
732                       total_relocs++;
733                       break;
734                     default:
735                       /* xgettext:c-format */
736                       einfo (_("%XError: %d-bit reloc in dll\n"),
737                              relocs[i]->howto->bitsize);
738                       break;
739                     }
740                 }
741             }
742           free (relocs);
743           /* Warning: the allocated symbols are remembered in BFD and reused
744              later, so don't free them! */
745           /* free (symbols); */
746         }
747     }
748
749   /* At this point, we have total_relocs relocation addresses in
750      reloc_addresses, which are all suitable for the .reloc section.
751      We must now create the new sections. */
752
753   qsort (reloc_data, total_relocs, sizeof (*reloc_data), reloc_sort);
754
755   for (i = 0; i < total_relocs; i++)
756     {
757       unsigned long this_page = (reloc_data[i].vma >> 12);
758       if (this_page != sec_page)
759         {
760           reloc_sz = (reloc_sz + 3) & ~3;       /* 4-byte align */
761           reloc_sz += 8;
762           sec_page = this_page;
763         }
764       reloc_sz += 2;
765     }
766   reloc_sz = (reloc_sz + 3) & ~3;       /* 4-byte align */
767
768   reloc_d = (unsigned char *) xmalloc (reloc_sz);
769
770   sec_page = (unsigned long) (-1);
771   reloc_sz = 0;
772   page_ptr = (unsigned long) (-1);
773   page_count = 0;
774   for (i = 0; i < total_relocs; i++)
775     {
776       unsigned long rva = reloc_data[i].vma - image_base;
777       unsigned long this_page = (rva & ~0xfff);
778       if (this_page != sec_page)
779         {
780           while (reloc_sz & 3)
781             reloc_d[reloc_sz++] = 0;
782           if (page_ptr != (unsigned long) (-1))
783             bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
784           bfd_put_32 (abfd, this_page, reloc_d + reloc_sz);
785           page_ptr = reloc_sz;
786           reloc_sz += 8;
787           sec_page = this_page;
788           page_count = 0;
789         }
790       bfd_put_16 (abfd, (rva & 0xfff) + (reloc_data[i].type<<12),
791                   reloc_d + reloc_sz);
792       reloc_sz += 2;
793       if (reloc_data[i].type == 4)
794         {
795           bfd_put_16 (abfd, reloc_data[i].extra, reloc_d + reloc_sz);
796           reloc_sz += 2;
797         }
798       page_count++;
799     }
800   while (reloc_sz & 3)
801     reloc_d[reloc_sz++] = 0;
802   if (page_ptr != (unsigned long) (-1))
803     bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
804   while (reloc_sz < reloc_s->_raw_size)
805     reloc_d[reloc_sz++] = 0;
806 }
807
808 /************************************************************************
809
810  Given the exiting def_file structure, print out a .DEF file that
811  corresponds to it.
812
813  ************************************************************************/
814
815 static void
816 quoteput (s, f, needs_quotes)
817      char *s;
818      FILE * f;
819      int needs_quotes;
820 {
821   char *cp;
822   for (cp = s; *cp; cp++)
823     if (*cp == '\''
824         || *cp == '"'
825         || *cp == '\\'
826         || isspace ((unsigned char) *cp)
827         || *cp == ','
828         || *cp == ';')
829       needs_quotes = 1;
830   if (needs_quotes)
831     {
832       putc ('"', f);
833       while (*s)
834         {
835           if (*s == '"' || *s == '\\')
836             putc ('\\', f);
837           putc (*s, f);
838           s++;
839         }
840       putc ('"', f);
841     }
842   else
843     fputs (s, f);
844 }
845
846 void
847 pe_dll_generate_def_file (pe_out_def_filename)
848      const char *pe_out_def_filename;
849 {
850   int i;
851   FILE *out = fopen (pe_out_def_filename, "w");
852   if (out == NULL)
853     {
854       /* xgettext:c-format */
855       einfo (_("%s: Can't open output def file %s\n"),
856              program_name, pe_out_def_filename);
857     }
858
859   if (pe_def_file)
860     {
861       if (pe_def_file->name)
862         {
863           if (pe_def_file->is_dll)
864             fprintf (out, "LIBRARY ");
865           else
866             fprintf (out, "NAME ");
867           quoteput (pe_def_file->name, out, 1);
868           if (pe_data (output_bfd)->pe_opthdr.ImageBase)
869             fprintf (out, " BASE=0x%lx",
870                      (unsigned long) pe_data (output_bfd)->pe_opthdr.ImageBase);
871           fprintf (out, "\n");
872         }
873
874       if (pe_def_file->description)
875         {
876           fprintf (out, "DESCRIPTION ");
877           quoteput (pe_def_file->description, out, 1);
878           fprintf (out, "\n");
879         }
880
881       if (pe_def_file->version_minor != -1)
882         fprintf (out, "VERSION %d.%d\n", pe_def_file->version_major,
883                  pe_def_file->version_minor);
884       else if (pe_def_file->version_major != -1)
885         fprintf (out, "VERSION %d\n", pe_def_file->version_major);
886
887       if (pe_def_file->stack_reserve != -1 || pe_def_file->heap_reserve != -1)
888         fprintf (out, "\n");
889
890       if (pe_def_file->stack_commit != -1)
891         fprintf (out, "STACKSIZE 0x%x,0x%x\n",
892                  pe_def_file->stack_reserve, pe_def_file->stack_commit);
893       else if (pe_def_file->stack_reserve != -1)
894         fprintf (out, "STACKSIZE 0x%x\n", pe_def_file->stack_reserve);
895       if (pe_def_file->heap_commit != -1)
896         fprintf (out, "HEAPSIZE 0x%x,0x%x\n",
897                  pe_def_file->heap_reserve, pe_def_file->heap_commit);
898       else if (pe_def_file->heap_reserve != -1)
899         fprintf (out, "HEAPSIZE 0x%x\n", pe_def_file->heap_reserve);
900
901       if (pe_def_file->num_section_defs > 0)
902         {
903           fprintf (out, "\nSECTIONS\n\n");
904           for (i = 0; i < pe_def_file->num_section_defs; i++)
905             {
906               fprintf (out, "    ");
907               quoteput (pe_def_file->section_defs[i].name, out, 0);
908               if (pe_def_file->section_defs[i].class)
909                 {
910                   fprintf (out, " CLASS ");
911                   quoteput (pe_def_file->section_defs[i].class, out, 0);
912                 }
913               if (pe_def_file->section_defs[i].flag_read)
914                 fprintf (out, " READ");
915               if (pe_def_file->section_defs[i].flag_write)
916                 fprintf (out, " WRITE");
917               if (pe_def_file->section_defs[i].flag_execute)
918                 fprintf (out, " EXECUTE");
919               if (pe_def_file->section_defs[i].flag_shared)
920                 fprintf (out, " SHARED");
921               fprintf (out, "\n");
922             }
923         }
924
925       if (pe_def_file->num_exports > 0)
926         {
927           fprintf (out, "\nEXPORTS\n\n");
928           for (i = 0; i < pe_def_file->num_exports; i++)
929             {
930               def_file_export *e = pe_def_file->exports + i;
931               fprintf (out, "    ");
932               quoteput (e->name, out, 0);
933               if (e->internal_name && strcmp (e->internal_name, e->name))
934                 {
935                   fprintf (out, " = ");
936                   quoteput (e->internal_name, out, 0);
937                 }
938               if (e->ordinal != -1)
939                 fprintf (out, " @%d", e->ordinal);
940               if (e->flag_private)
941                 fprintf (out, " PRIVATE");
942               if (e->flag_constant)
943                 fprintf (out, " CONSTANT");
944               if (e->flag_noname)
945                 fprintf (out, " NONAME");
946               if (e->flag_data)
947                 fprintf (out, " DATA");
948
949               fprintf (out, "\n");
950             }
951         }
952
953       if (pe_def_file->num_imports > 0)
954         {
955           fprintf (out, "\nIMPORTS\n\n");
956           for (i = 0; i < pe_def_file->num_imports; i++)
957             {
958               def_file_import *im = pe_def_file->imports + i;
959               fprintf (out, "    ");
960               if (im->internal_name
961                   && (!im->name || strcmp (im->internal_name, im->name)))
962                 {
963                   quoteput (im->internal_name, out, 0);
964                   fprintf (out, " = ");
965                 }
966               quoteput (im->module->name, out, 0);
967               fprintf (out, ".");
968               if (im->name)
969                 quoteput (im->name, out, 0);
970               else
971                 fprintf (out, "%d", im->ordinal);
972               fprintf (out, "\n");
973             }
974         }
975     }
976   else
977     fprintf (out, _("; no contents available\n"));
978
979   if (fclose (out) == EOF)
980     {
981       /* xgettext:c-format */
982       einfo (_("%P: Error closing file `%s'\n"), pe_out_def_filename);
983     }
984 }
985
986 /************************************************************************
987
988  Generate the import library
989
990  ************************************************************************/
991
992 static asymbol **symtab;
993 static int symptr;
994 static int tmp_seq;
995 static const char *dll_filename;
996 static char *dll_symname;
997
998 #define UNDSEC (asection *) &bfd_und_section
999
1000 static asection *
1001 quick_section(abfd, name, flags, align)
1002      bfd *abfd;
1003      const char *name;
1004      int flags;
1005      int align;
1006 {
1007   asection *sec;
1008   asymbol *sym;
1009
1010   sec = bfd_make_section_old_way (abfd, name);
1011   bfd_set_section_flags (abfd, sec, flags
1012                                   | SEC_ALLOC
1013                                   | SEC_LOAD
1014                                   | SEC_KEEP
1015                          );
1016   bfd_set_section_alignment (abfd, sec, align);
1017   /* remember to undo this before trying to link internally! */
1018   sec->output_section = sec;
1019
1020   sym = bfd_make_empty_symbol (abfd);
1021   symtab[symptr++] = sym;
1022   sym->name = sec->name;
1023   sym->section = sec;
1024   sym->flags = BSF_LOCAL;
1025   sym->value = 0;
1026
1027   return sec;
1028 }
1029
1030 static void
1031 quick_symbol (abfd, n1, n2, n3, sec, flags, addr)
1032      bfd *abfd;
1033      char *n1;
1034      char *n2;
1035      char *n3;
1036      asection *sec;
1037      int flags;
1038      int addr;
1039 {
1040   asymbol *sym;
1041   char *name = (char *) xmalloc (strlen (n1) + strlen (n2) + strlen (n3) + 1);
1042   strcpy (name, n1);
1043   strcat (name, n2);
1044   strcat (name, n3);
1045   sym = bfd_make_empty_symbol (abfd);
1046   sym->name = name;
1047   sym->section = sec;
1048   sym->flags = flags;
1049   sym->value = addr;
1050   symtab[symptr++] = sym;
1051 }
1052
1053 static arelent *reltab = 0;
1054 static int relcount = 0, relsize = 0;
1055
1056 static void
1057 quick_reloc (abfd, address, which_howto, symidx)
1058      bfd *abfd;
1059      int address;
1060      int which_howto;
1061      int symidx;
1062 {
1063   if (relcount >= (relsize-1))
1064     {
1065       relsize += 10;
1066       if (reltab)
1067         reltab = (arelent *) xrealloc (reltab, relsize * sizeof (arelent));
1068       else
1069         reltab = (arelent *) xmalloc (relsize * sizeof (arelent));
1070     }
1071   reltab[relcount].address = address;
1072   reltab[relcount].addend = 0;
1073   reltab[relcount].howto = bfd_reloc_type_lookup (abfd, which_howto);
1074   reltab[relcount].sym_ptr_ptr = symtab + symidx;
1075   relcount++;
1076 }
1077
1078 static void
1079 save_relocs (asection *sec)
1080 {
1081   int i;
1082   sec->relocation = reltab;
1083   sec->reloc_count = relcount;
1084   sec->orelocation = (arelent **) xmalloc ((relcount+1) * sizeof (arelent *));
1085   for (i=0; i<relcount; i++)
1086     sec->orelocation[i] = sec->relocation + i;
1087   sec->orelocation[relcount] = 0;
1088   sec->flags |= SEC_RELOC;
1089   reltab = 0;
1090   relcount = relsize = 0;
1091 }
1092
1093 /*
1094  *      .section        .idata$2
1095  *      .global         __head_my_dll
1096  * __head_my_dll:
1097  *      .rva            hname
1098  *      .long           0
1099  *      .long           0
1100  *      .rva            __my_dll_iname
1101  *      .rva            fthunk
1102  *
1103  *      .section        .idata$5
1104  *      .long           0
1105  * fthunk:
1106  *
1107  *      .section        .idata$4
1108  *      .long           0
1109  * hname:
1110  */
1111
1112 static bfd *
1113 make_head (parent)
1114      bfd *parent;
1115 {
1116   asection *id2, *id5, *id4;
1117   unsigned char *d2, *d5, *d4;
1118   char *oname;
1119   bfd *abfd;
1120
1121   oname = (char *) xmalloc (20);
1122   sprintf (oname, "d%06d.o", tmp_seq);
1123   tmp_seq++;
1124
1125   abfd = bfd_create (oname, parent);
1126   bfd_find_target (pe_details->object_target, abfd);
1127   bfd_make_writable (abfd);
1128
1129   bfd_set_format (abfd, bfd_object);
1130   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1131
1132   symptr = 0;
1133   symtab = (asymbol **) xmalloc (6 * sizeof (asymbol *));
1134   id2 = quick_section (abfd, ".idata$2", SEC_HAS_CONTENTS, 2);
1135   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1136   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1137   quick_symbol (abfd, U("_head_"), dll_symname, "", id2, BSF_GLOBAL, 0);
1138   quick_symbol (abfd, U(""), dll_symname, "_iname", UNDSEC, BSF_GLOBAL, 0);
1139
1140   /* OK, pay attention here.  I got confused myself looking back at
1141      it.  We create a four-byte section to mark the beginning of the
1142      list, and we include an offset of 4 in the section, so that the
1143      pointer to the list points to the *end* of this section, which is
1144      the start of the list of sections from other objects. */
1145
1146   bfd_set_section_size (abfd, id2, 20);
1147   d2 = (unsigned char *) xmalloc (20);
1148   id2->contents = d2;
1149   memset (d2, 0, 20);
1150   d2[0] = d2[16] = 4; /* reloc addend */
1151   quick_reloc (abfd,  0, BFD_RELOC_RVA, 2);
1152   quick_reloc (abfd, 12, BFD_RELOC_RVA, 4);
1153   quick_reloc (abfd, 16, BFD_RELOC_RVA, 1);
1154   save_relocs (id2);
1155
1156   bfd_set_section_size (abfd, id5, 4);
1157   d5 = (unsigned char *) xmalloc (4);
1158   id5->contents = d5;
1159   memset (d5, 0, 4);
1160
1161   bfd_set_section_size (abfd, id4, 4);
1162   d4 = (unsigned char *) xmalloc (4);
1163   id4->contents = d4;
1164   memset (d4, 0, 4);
1165
1166   bfd_set_symtab (abfd, symtab, symptr);
1167
1168   bfd_set_section_contents (abfd, id2, d2, 0, 20);
1169   bfd_set_section_contents (abfd, id5, d5, 0, 4);
1170   bfd_set_section_contents (abfd, id4, d4, 0, 4);
1171   
1172   bfd_make_readable (abfd);
1173   return abfd;
1174 }
1175
1176 /*
1177  *      .section        .idata$4
1178  *      .long           0
1179  *      .section        .idata$5
1180  *      .long           0
1181  *      .section        idata$7
1182  *      .global         __my_dll_iname
1183  *__my_dll_iname:
1184  *      .asciz          "my.dll"
1185  */
1186
1187 static bfd *
1188 make_tail (parent)
1189      bfd *parent;
1190 {
1191   asection *id4, *id5, *id7;
1192   unsigned char *d4, *d5, *d7;
1193   int len;
1194   char *oname;
1195   bfd *abfd;
1196
1197   oname = (char *) xmalloc (20);
1198   sprintf (oname, "d%06d.o", tmp_seq);
1199   tmp_seq++;
1200
1201   abfd = bfd_create (oname, parent);
1202   bfd_find_target (pe_details->object_target, abfd);
1203   bfd_make_writable (abfd);
1204
1205   bfd_set_format (abfd, bfd_object);
1206   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1207
1208   symptr = 0;
1209   symtab = (asymbol **) xmalloc (5 * sizeof (asymbol *));
1210   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1211   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1212   id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1213   quick_symbol (abfd, U(""), dll_symname, "_iname", id7, BSF_GLOBAL, 0);
1214
1215   bfd_set_section_size (abfd, id4, 4);
1216   d4 = (unsigned char *) xmalloc (4);
1217   id4->contents = d4;
1218   memset (d4, 0, 4);
1219
1220   bfd_set_section_size (abfd, id5, 4);
1221   d5 = (unsigned char *) xmalloc (4);
1222   id5->contents = d5;
1223   memset (d5, 0, 4);
1224
1225   len = strlen (dll_filename)+1;
1226   if (len & 1)
1227     len ++;
1228   bfd_set_section_size (abfd, id7, len);
1229   d7 = (unsigned char *) xmalloc (len);
1230   id7->contents = d7;
1231   strcpy (d7, dll_filename);
1232
1233   bfd_set_symtab (abfd, symtab, symptr);
1234
1235   bfd_set_section_contents (abfd, id4, d4, 0, 4);
1236   bfd_set_section_contents (abfd, id5, d5, 0, 4);
1237   bfd_set_section_contents (abfd, id7, d7, 0, len);
1238
1239   bfd_make_readable (abfd);
1240   return abfd;
1241 }
1242
1243 /*
1244  *      .text
1245  *      .global         _function
1246  *      .global         ___imp_function
1247  *      .global         __imp__function
1248  *_function:
1249  *      jmp             *__imp__function:
1250  *
1251  *      .section        idata$7
1252  *      .long           __head_my_dll
1253  *
1254  *      .section        .idata$5
1255  *___imp_function:
1256  *__imp__function:
1257  *iat?
1258  *      .section        .idata$4
1259  *iat?
1260  *      .section        .idata$6
1261  *ID<ordinal>:
1262  *      .short          <hint>
1263  *      .asciz          "function" xlate? (add underscore, kill at)
1264  */
1265
1266 static unsigned char jmp_ix86_bytes[] = {
1267   0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
1268 };
1269
1270
1271 static bfd *
1272 make_one (exp, parent)
1273      def_file_export *exp;
1274      bfd *parent;
1275 {
1276   asection *tx, *id7, *id5, *id4, *id6;
1277   unsigned char *td, *d7, *d5, *d4, *d6;
1278   int len;
1279   char *oname;
1280   bfd *abfd;
1281   unsigned char *jmp_bytes;
1282   int jmp_byte_count;
1283
1284   switch (pe_details->pe_arch)
1285     {
1286     case PE_ARCH_i386:
1287       jmp_bytes = jmp_ix86_bytes;
1288       jmp_byte_count = sizeof (jmp_ix86_bytes);
1289       break;
1290     }
1291
1292   oname = (char *) xmalloc (20);
1293   sprintf (oname, "d%06d.o", tmp_seq);
1294   tmp_seq++;
1295
1296   abfd = bfd_create (oname, parent);
1297   bfd_find_target (pe_details->object_target, abfd);
1298   bfd_make_writable (abfd);
1299
1300   bfd_set_format (abfd, bfd_object);
1301   bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1302
1303   symptr = 0;
1304   symtab = (asymbol **) xmalloc (10 * sizeof (asymbol *));
1305   tx  = quick_section (abfd, ".text",    SEC_CODE|SEC_HAS_CONTENTS, 2);
1306   id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1307   id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1308   id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1309   id6 = quick_section (abfd, ".idata$6", SEC_HAS_CONTENTS, 2);
1310   if (! exp->flag_data)
1311     quick_symbol (abfd, U(""), exp->internal_name, "", tx, BSF_GLOBAL, 0);
1312   quick_symbol (abfd, U("_head_"), dll_symname, "", UNDSEC, BSF_GLOBAL, 0);
1313   quick_symbol (abfd, U("__imp_"), exp->internal_name, "", id5, BSF_GLOBAL, 0);
1314   quick_symbol (abfd, U("_imp__"), exp->internal_name, "", id5, BSF_GLOBAL, 0);
1315
1316   bfd_set_section_size (abfd, tx, jmp_byte_count);
1317   td = (unsigned char *) xmalloc (jmp_byte_count);
1318   tx->contents = td;
1319   memcpy (td, jmp_bytes, jmp_byte_count);
1320   switch (pe_details->pe_arch)
1321     {
1322     case PE_ARCH_i386:
1323       quick_reloc (abfd, 2, BFD_RELOC_32, 2);
1324       break;
1325     }
1326   save_relocs (tx);
1327
1328   bfd_set_section_size (abfd, id7, 4);
1329   d7 = (unsigned char *) xmalloc (4);
1330   id7->contents = d7;
1331   memset (d7, 0, 4);
1332   quick_reloc (abfd, 0, BFD_RELOC_RVA, 6);
1333   save_relocs (id7);
1334
1335   bfd_set_section_size (abfd, id5, 4);
1336   d5 = (unsigned char *) xmalloc (4);
1337   id5->contents = d5;
1338   memset (d5, 0, 4);
1339   if (exp->flag_noname)
1340     {
1341       d5[0] = exp->ordinal;
1342       d5[1] = exp->ordinal >> 8;
1343       d5[3] = 0x80;
1344     }
1345   else
1346     {
1347       quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1348       save_relocs (id5);
1349     }
1350
1351   bfd_set_section_size (abfd, id4, 4);
1352   d4 = (unsigned char *) xmalloc (4);
1353   id4->contents = d4;
1354   memset (d4, 0, 4);
1355   if (exp->flag_noname)
1356     {
1357       d5[0] = exp->ordinal;
1358       d5[1] = exp->ordinal >> 8;
1359       d5[3] = 0x80;
1360     }
1361   else
1362     {
1363       quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1364       save_relocs (id4);
1365     }
1366
1367   if (exp->flag_noname)
1368     {
1369       len = 0;
1370       bfd_set_section_size (abfd, id6, 0);
1371     }
1372   else
1373     {
1374       len = strlen (exp->name) + 3;
1375       if (len & 1)
1376         len++;
1377       bfd_set_section_size (abfd, id6, len);
1378       d6 = (unsigned char *) xmalloc (len);
1379       id6->contents = d6;
1380       memset (d6, 0, len);
1381       d6[0] = exp->hint & 0xff;
1382       d6[1] = exp->hint >> 8;
1383       strcpy (d6+2, exp->name);
1384     }
1385
1386   bfd_set_symtab (abfd, symtab, symptr);
1387
1388   bfd_set_section_contents (abfd, tx, td, 0, jmp_byte_count);
1389   bfd_set_section_contents (abfd, id7, d7, 0, 4);
1390   bfd_set_section_contents (abfd, id5, d5, 0, 4);
1391   bfd_set_section_contents (abfd, id4, d4, 0, 4);
1392   if (!exp->flag_noname)
1393     bfd_set_section_contents (abfd, id6, d6, 0, len);
1394
1395   bfd_make_readable (abfd);
1396   return abfd;
1397 }
1398
1399 void
1400 pe_dll_generate_implib (def, impfilename)
1401      def_file *def;
1402      const char *impfilename;
1403 {
1404   int i;
1405   bfd *ar_head;
1406   bfd *ar_tail;
1407   bfd *outarch;
1408   bfd *head = 0;
1409
1410   dll_filename = def->name;
1411   if (dll_filename == 0)
1412     {
1413       dll_filename = dll_name;
1414       for (i=0; impfilename[i]; i++)
1415         if (impfilename[i] == '/' || impfilename[i] == '\\')
1416           dll_filename = impfilename+1;
1417     }
1418   dll_symname = xstrdup (dll_filename);
1419   for (i=0; dll_symname[i]; i++)
1420     if (!isalnum ((unsigned char) dll_symname[i]))
1421       dll_symname[i] = '_';
1422
1423   unlink (impfilename);
1424
1425   outarch = bfd_openw (impfilename, 0);
1426
1427   if (!outarch)
1428     {
1429       /* xgettext:c-format */
1430       einfo (_("%XCan't open .lib file: %s\n"), impfilename);
1431       return;
1432     }
1433
1434   /* xgettext:c-format */
1435   einfo (_("Creating library file: %s\n"), impfilename);
1436   
1437   bfd_set_format (outarch, bfd_archive);
1438   outarch->has_armap = 1;
1439
1440   /* Work out a reasonable size of things to put onto one line. */
1441
1442   ar_head = make_head (outarch);
1443
1444   for (i = 0; i<def->num_exports; i++)
1445     {
1446       /* The import library doesn't know about the internal name */
1447       char *internal = def->exports[i].internal_name;
1448       bfd *n;
1449       def->exports[i].internal_name = def->exports[i].name;
1450       n = make_one (def->exports+i, outarch);
1451       n->next = head;
1452       head = n;
1453       def->exports[i].internal_name = internal;
1454     }
1455
1456   ar_tail = make_tail (outarch);
1457
1458   if (ar_head == NULL || ar_tail == NULL)
1459     return;
1460
1461   /* Now stick them all into the archive */
1462
1463   ar_head->next = head;
1464   ar_tail->next = ar_head;
1465   head = ar_tail;
1466
1467   if (! bfd_set_archive_head (outarch, head))
1468     einfo ("%Xbfd_set_archive_head: %s\n", bfd_errmsg (bfd_get_error ()));
1469   
1470   if (! bfd_close (outarch))
1471     einfo ("%Xbfd_close %s: %s\n", impfilename, bfd_errmsg (bfd_get_error ()));
1472
1473   while (head != NULL)
1474     {
1475       bfd *n = head->next;
1476       bfd_close (head);
1477       head = n;
1478     }
1479 }
1480
1481 static void
1482 add_bfd_to_link (abfd, name, link_info)
1483      bfd *abfd;
1484      char *name;
1485      struct bfd_link_info *link_info;
1486 {
1487   lang_input_statement_type *fake_file;
1488   fake_file = lang_add_input_file (name,
1489                                    lang_input_file_is_fake_enum,
1490                                    NULL);
1491   fake_file->the_bfd = abfd;
1492   ldlang_add_file (fake_file);
1493   if (!bfd_link_add_symbols (abfd, link_info))
1494     einfo ("%Xaddsym %s: %s\n", name, bfd_errmsg (bfd_get_error ()));
1495 }
1496
1497 void
1498 pe_process_import_defs (output_bfd, link_info)
1499      bfd *output_bfd;
1500      struct bfd_link_info *link_info;
1501 {
1502   def_file_module *module;
1503   pe_dll_id_target(bfd_get_target (output_bfd));
1504
1505   if (!pe_def_file)
1506     return;
1507
1508   for (module = pe_def_file->modules; module; module = module->next)
1509     {
1510       int i, do_this_dll;
1511
1512       dll_filename = module->name;
1513       dll_symname = xstrdup (module->name);
1514       for (i=0; dll_symname[i]; i++)
1515         if (!isalnum (dll_symname[i]))
1516           dll_symname[i] = '_';
1517
1518       do_this_dll = 0;
1519
1520       for (i=0; i<pe_def_file->num_imports; i++)
1521         if (pe_def_file->imports[i].module == module)
1522           {
1523             def_file_export exp;
1524             struct bfd_link_hash_entry *blhe;
1525
1526             /* see if we need this import */
1527             char *name = (char *) xmalloc (strlen (pe_def_file->imports[i].internal_name) + 2);
1528             sprintf (name, "%s%s", U(""), pe_def_file->imports[i].internal_name);
1529             blhe = bfd_link_hash_lookup (link_info->hash, name,
1530                                          false, false, false);
1531             free (name);
1532             if (blhe && blhe->type == bfd_link_hash_undefined)
1533               {
1534                 bfd *one;
1535                 /* we do */
1536                 if (!do_this_dll)
1537                   {
1538                     bfd *ar_head = make_head (output_bfd);
1539                     add_bfd_to_link (ar_head, ar_head->filename, link_info);
1540                     do_this_dll = 1;
1541                   }
1542                 exp.internal_name = pe_def_file->imports[i].internal_name;
1543                 exp.name = pe_def_file->imports[i].name;
1544                 exp.ordinal = pe_def_file->imports[i].ordinal;
1545                 exp.hint = exp.ordinal >= 0 ? exp.ordinal : 0;
1546                 exp.flag_private = 0;
1547                 exp.flag_constant = 0;
1548                 exp.flag_data = 0;
1549                 exp.flag_noname = exp.name ? 0 : 1;
1550                 one = make_one (&exp, output_bfd);
1551                 add_bfd_to_link (one, one->filename, link_info);
1552               }
1553           }
1554       if (do_this_dll)
1555         {
1556           bfd *ar_tail = make_tail (output_bfd);
1557           add_bfd_to_link (ar_tail, ar_tail->filename, link_info);
1558         }
1559
1560       free (dll_symname);
1561     }
1562 }
1563
1564 /************************************************************************
1565
1566  We were handed a *.DLL file.  Parse it and turn it into a set of
1567  IMPORTS directives in the def file.  Return true if the file was
1568  handled, false if not.
1569
1570  ************************************************************************/
1571
1572 static unsigned int
1573 pe_get16 (abfd, where)
1574      bfd *abfd;
1575      int where;
1576 {
1577   unsigned char b[2];
1578   bfd_seek (abfd, where, SEEK_SET);
1579   bfd_read (b, 1, 2, abfd);
1580   return b[0] + (b[1]<<8);
1581 }
1582
1583 static unsigned int
1584 pe_get32 (abfd, where)
1585      bfd *abfd;
1586      int where;
1587 {
1588   unsigned char b[4];
1589   bfd_seek (abfd, where, SEEK_SET);
1590   bfd_read (b, 1, 4, abfd);
1591   return b[0] + (b[1]<<8) + (b[2]<<16) + (b[3]<<24);
1592 }
1593
1594 #if 0 /* This is not currently used.  */
1595
1596 static unsigned int
1597 pe_as16 (ptr)
1598      void *ptr;
1599 {
1600   unsigned char *b = ptr;
1601   return b[0] + (b[1]<<8);
1602 }
1603
1604 #endif
1605
1606 static unsigned int
1607 pe_as32 (ptr)
1608      void *ptr;
1609 {
1610   unsigned char *b = ptr;
1611   return b[0] + (b[1]<<8) + (b[2]<<16) + (b[3]<<24);
1612 }
1613
1614 boolean
1615 pe_implied_import_dll (filename)
1616      const char *filename;
1617 {
1618   bfd *dll;
1619   unsigned long pe_header_offset, opthdr_ofs, num_entries, i;
1620   unsigned long export_rva, export_size, nsections, secptr, expptr;
1621   unsigned char *expdata, *erva;
1622   unsigned long name_rvas, ordinals, nexp, ordbase;
1623   const char *dll_name;
1624
1625   /* No, I can't use bfd here.  kernel32.dll puts its export table in
1626      the middle of the .rdata section. */
1627
1628   dll = bfd_openr (filename, pe_details->target_name);
1629   if (!dll)
1630     {
1631       einfo ("%Xopen %s: %s\n", filename, bfd_errmsg (bfd_get_error ()));
1632       return false;
1633     }
1634   /* PEI dlls seem to be bfd_objects */
1635   if (!bfd_check_format (dll, bfd_object))
1636     {
1637       einfo ("%X%s: this doesn't appear to be a DLL\n", filename);
1638       return false;
1639     }
1640
1641   dll_name = filename;
1642   for (i=0; filename[i]; i++)
1643     if (filename[i] == '/' || filename[i] == '\\' || filename[i] == ':')
1644       dll_name = filename + i + 1;
1645
1646   pe_header_offset = pe_get32 (dll, 0x3c);
1647   opthdr_ofs = pe_header_offset + 4 + 20;
1648   num_entries = pe_get32 (dll, opthdr_ofs + 92);
1649   if (num_entries < 1) /* no exports */
1650     return false;
1651   export_rva = pe_get32 (dll, opthdr_ofs + 96);
1652   export_size = pe_get32 (dll, opthdr_ofs + 100);
1653   nsections = pe_get16 (dll, pe_header_offset + 4 + 2);
1654   secptr = (pe_header_offset + 4 + 20 +
1655             pe_get16 (dll, pe_header_offset + 4 + 16));
1656   expptr = 0;
1657   for (i=0; i<nsections; i++)
1658     {
1659       char sname[8];
1660       unsigned long secptr1 = secptr + 40 * i;
1661       unsigned long vaddr = pe_get32 (dll, secptr1 + 12);
1662       unsigned long vsize = pe_get32 (dll, secptr1 + 16);
1663       unsigned long fptr = pe_get32 (dll, secptr1 + 20);
1664       bfd_seek(dll, secptr1, SEEK_SET);
1665       bfd_read(sname, 1, 8, dll);
1666       if (vaddr <= export_rva && vaddr+vsize > export_rva)
1667         {
1668           expptr = fptr + (export_rva - vaddr);
1669           if (export_rva + export_size > vaddr + vsize)
1670             export_size = vsize - (export_rva - vaddr);
1671           break;
1672         }
1673     }
1674
1675   expdata = (unsigned char *) xmalloc (export_size);
1676   bfd_seek (dll, expptr, SEEK_SET);
1677   bfd_read (expdata, 1, export_size, dll);
1678   erva = expdata - export_rva;
1679
1680   if (pe_def_file == 0)
1681     pe_def_file = def_file_empty();
1682
1683   nexp = pe_as32 (expdata+24);
1684   name_rvas = pe_as32 (expdata+32);
1685   ordinals = pe_as32 (expdata+36);
1686   ordbase = pe_as32 (expdata+16);
1687   for (i=0; i<nexp; i++)
1688     {
1689       unsigned long name_rva = pe_as32 (erva+name_rvas+i*4);
1690       def_file_import *imp;
1691       imp = def_file_add_import (pe_def_file, erva+name_rva, dll_name,
1692                                  i, 0);
1693     }
1694
1695   return true;
1696 }
1697
1698 /************************************************************************
1699
1700  These are the main functions, called from the emulation.  The first
1701  is called after the bfds are read, so we can guess at how much space
1702  we need.  The second is called after everything is placed, so we
1703  can put the right values in place.
1704
1705  ************************************************************************/
1706
1707 void
1708 pe_dll_build_sections (abfd, info)
1709      bfd *abfd;
1710      struct bfd_link_info *info;
1711 {
1712   pe_dll_id_target (bfd_get_target (abfd));
1713   process_def_file (abfd, info);
1714
1715   generate_edata (abfd, info);
1716   build_filler_bfd (1);
1717 }
1718
1719 void
1720 pe_exe_build_sections (abfd, info)
1721      bfd *abfd;
1722      struct bfd_link_info *info ATTRIBUTE_UNUSED;
1723 {
1724   pe_dll_id_target (bfd_get_target (abfd));
1725   build_filler_bfd (0);
1726 }
1727
1728 void
1729 pe_dll_fill_sections (abfd, info)
1730      bfd *abfd;
1731      struct bfd_link_info *info;
1732 {
1733   pe_dll_id_target (bfd_get_target (abfd));
1734   image_base = pe_data (abfd)->pe_opthdr.ImageBase;
1735
1736   generate_reloc (abfd, info);
1737   if (reloc_sz > 0)
1738     {
1739       bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
1740
1741       /* Resize the sections.  */
1742       lang_size_sections (stat_ptr->head, abs_output_section,
1743                           &stat_ptr->head, 0, (bfd_vma) 0, false);
1744
1745       /* Redo special stuff.  */
1746       ldemul_after_allocation ();
1747
1748       /* Do the assignments again.  */
1749       lang_do_assignments (stat_ptr->head,
1750                            abs_output_section,
1751                            (fill_type) 0, (bfd_vma) 0);
1752     }
1753
1754   fill_edata (abfd, info);
1755
1756   pe_data (abfd)->dll = 1;
1757
1758   edata_s->contents = edata_d;
1759   reloc_s->contents = reloc_d;
1760 }
1761
1762 void
1763 pe_exe_fill_sections (abfd, info)
1764      bfd *abfd;
1765      struct bfd_link_info *info;
1766 {
1767   pe_dll_id_target (bfd_get_target (abfd));
1768   image_base = pe_data (abfd)->pe_opthdr.ImageBase;
1769
1770   generate_reloc (abfd, info);
1771   if (reloc_sz > 0)
1772     {
1773       bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
1774
1775       /* Resize the sections.  */
1776       lang_size_sections (stat_ptr->head, abs_output_section,
1777                           &stat_ptr->head, 0, (bfd_vma) 0, false);
1778
1779       /* Redo special stuff.  */
1780       ldemul_after_allocation ();
1781
1782       /* Do the assignments again.  */
1783       lang_do_assignments (stat_ptr->head,
1784                            abs_output_section,
1785                            (fill_type) 0, (bfd_vma) 0);
1786     }
1787   reloc_s->contents = reloc_d;
1788 }