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