daily update
[binutils.git] / ld / pe-dll.c
blobd4d42e4d36a2ea8c37d442bde00396500f0a1424
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>
6 This file is part of GLD, the Gnu Linker.
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.
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.
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. */
23 #include "bfd.h"
24 #include "sysdep.h"
25 #include "bfdlink.h"
26 #include "libiberty.h"
27 #include "safe-ctype.h"
29 #include <time.h>
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"
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.
52 See also: ld/emultempl/pe.em. */
54 /* Auto-import feature by Paul Sokolovsky
56 Quick facts:
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).
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.
66 3. Auto-import is fully compatible with standard import method and they
67 can be mixed together.
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).
74 Idea
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
80 mov dll_var,%eax,
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, ;-) .
93 Implementation
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.
122 See also: ld/emultempl/pe.em. */
124 static void add_bfd_to_link (bfd *, const char *, struct bfd_link_info *);
126 /* For emultempl/pe.em. */
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;
137 /* Static variables and types. */
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;
146 typedef struct
148 char *target_name;
149 char *object_target;
150 unsigned int imagebase_reloc;
151 int pe_arch;
152 int bfd_arch;
153 int underscored;
155 pe_details_type;
157 typedef struct
159 char *name;
160 int len;
162 autofilter_entry_type;
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
170 static pe_details_type pe_detail_list[] =
173 "pei-i386",
174 "pe-i386",
175 7 /* R_IMAGEBASE */,
176 PE_ARCH_i386,
177 bfd_arch_i386,
181 "pei-shl",
182 "pe-shl",
183 16 /* R_SH_IMAGEBASE */,
184 PE_ARCH_sh,
185 bfd_arch_sh,
189 "pei-mips",
190 "pe-mips",
191 34 /* MIPS_R_RVA */,
192 PE_ARCH_mips,
193 bfd_arch_mips,
197 "pei-arm-little",
198 "pe-arm-little",
199 11 /* ARM_RVA32 */,
200 PE_ARCH_arm,
201 bfd_arch_arm,
205 "epoc-pei-arm-little",
206 "epoc-pe-arm-little",
207 11 /* ARM_RVA32 */,
208 PE_ARCH_arm_epoc,
209 bfd_arch_arm,
212 { NULL, NULL, 0, 0, 0, 0 }
215 static pe_details_type *pe_details;
217 static autofilter_entry_type autofilter_symbollist[] =
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 }
232 /* Do not specify library suffix explicitly, to allow for dllized versions. */
233 static autofilter_entry_type autofilter_liblist[] =
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 }
247 static autofilter_entry_type autofilter_objlist[] =
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 }
262 static autofilter_entry_type autofilter_symbolprefixlist[] =
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 }
283 static autofilter_entry_type autofilter_symbolsuffixlist[] =
285 { "_iname", 6 },
286 { NULL, 0 }
289 #define U(str) (pe_details->underscored ? "_" str : str)
291 void
292 pe_dll_id_target (const char *target)
294 int i;
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)
300 pe_details = pe_detail_list + i;
301 return;
303 einfo (_("%XUnsupported PEI architecture: %s\n"), target);
304 exit (1);
307 /* Helper functions for qsort. Relocs must be sorted so that we can write
308 them out by pages. */
310 typedef struct
312 bfd_vma vma;
313 char type;
314 short extra;
316 reloc_data_type;
318 static int
319 reloc_sort (const void *va, const void *vb)
321 bfd_vma a = ((const reloc_data_type *) va)->vma;
322 bfd_vma b = ((const reloc_data_type *) vb)->vma;
324 return (a > b) ? 1 : ((a < b) ? -1 : 0);
327 static int
328 pe_export_sort (const void *va, const void *vb)
330 const def_file_export *a = va;
331 const def_file_export *b = vb;
333 return strcmp (a->name, b->name);
336 /* Read and process the .DEF file. */
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. */
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;
352 typedef struct exclude_list_struct
354 char *string;
355 struct exclude_list_struct *next;
356 int type;
358 exclude_list_struct;
360 static struct exclude_list_struct *excludes = 0;
362 void
363 pe_dll_add_excludes (const char *new_excludes, const int type)
365 char *local_copy;
366 char *exclude_string;
368 local_copy = xstrdup (new_excludes);
370 exclude_string = strtok (local_copy, ",:");
371 for (; exclude_string; exclude_string = strtok (NULL, ",:"))
373 struct exclude_list_struct *new_exclude;
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;
383 free (local_copy);
387 /* abfd is a bfd containing n (or NULL)
388 It can be used for contextual checks. */
390 static int
391 auto_export (bfd *abfd, def_file *d, const char *n)
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);
400 /* We should not re-export imported stuff. */
401 if (strncmp (n, "_imp_", 5) == 0)
402 return 0;
404 for (i = 0; i < d->num_exports; i++)
405 if (strcmp (d->exports[i].name, n) == 0)
406 return 0;
408 if (pe_dll_do_default_excludes)
410 const char * p;
411 int len;
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);
417 /* First of all, make context checks:
418 Don't export anything from standard libs. */
419 if (libname)
421 afptr = autofilter_liblist;
423 while (afptr->name)
425 if (strncmp (libname, afptr->name, afptr->len) == 0 )
426 return 0;
427 afptr++;
431 /* Next, exclude symbols from certain startup objects. */
433 if (abfd && (p = lbasename (abfd->filename)))
435 afptr = autofilter_objlist;
436 while (afptr->name)
438 if (strcmp (p, afptr->name) == 0)
439 return 0;
440 afptr++;
444 /* Don't try to blindly exclude all symbols
445 that begin with '__'; this was tried and
446 it is too restrictive. */
448 /* Then, exclude specific symbols. */
449 afptr = autofilter_symbollist;
450 while (afptr->name)
452 if (strcmp (n, afptr->name) == 0)
453 return 0;
455 afptr++;
458 /* Next, exclude symbols starting with ... */
459 afptr = autofilter_symbolprefixlist;
460 while (afptr->name)
462 if (strncmp (n, afptr->name, afptr->len) == 0)
463 return 0;
465 afptr++;
468 /* Finally, exclude symbols ending with ... */
469 len = strlen (n);
470 afptr = autofilter_symbolsuffixlist;
471 while (afptr->name)
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;
479 afptr++;
483 for (ex = excludes; ex; ex = ex->next)
485 if (ex->type == 1) /* exclude-libs */
487 if (libname
488 && ((strcmp (libname, ex->string) == 0)
489 || (strcasecmp ("ALL", ex->string) == 0)))
490 return 0;
492 else if (strcmp (n, ex->string) == 0)
493 return 0;
496 return 1;
499 static void
500 process_def_file (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
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;
508 if (!pe_def_file)
509 pe_def_file = def_file_empty ();
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)
515 s = bfd_get_section_by_name (b, ".drectve");
516 if (s)
518 long size = s->size;
519 char *buf = xmalloc (size);
521 bfd_get_section_contents (b, s, buf, 0, size);
522 def_file_add_directive (pe_def_file, buf, size);
523 free (buf);
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;
533 /* Now, maybe export everything else the default way. */
534 if (pe_dll_export_everything || pe_def_file->num_exports == 0)
536 for (b = info->input_bfds; b; b = b->link_next)
538 asymbol **symbols;
539 int nsyms, symsize;
541 symsize = bfd_get_symtab_upper_bound (b);
542 symbols = xmalloc (symsize);
543 nsyms = bfd_canonicalize_symtab (b, symbols);
545 for (j = 0; j < nsyms; j++)
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)))
554 const char *sn = symbols[j]->name;
556 /* We should not re-export imported stuff. */
558 char *name = xmalloc (strlen (sn) + 2 + 6);
559 sprintf (name, "%s%s", U("_imp_"), sn);
561 blhe = bfd_link_hash_lookup (info->hash, name,
562 FALSE, FALSE, FALSE);
563 free (name);
565 if (blhe && blhe->type == bfd_link_hash_defined)
566 continue;
569 if (*sn == '_')
570 sn++;
572 if (auto_export (b, pe_def_file, sn))
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);
584 #undef NE
585 #define NE pe_def_file->num_exports
587 /* Canonicalize the export list. */
588 if (pe_dll_kill_ats)
590 for (i = 0; i < NE; i++)
592 if (strchr (pe_def_file->exports[i].name, '@'))
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, '@');
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;
611 if (pe_dll_stdcall_aliases)
613 for (i = 0; i < NE; i++)
615 if (strchr (pe_def_file->exports[i].name, '@'))
617 int lead_at = (*pe_def_file->exports[i].name == '@');
618 char *tmp = xstrdup (pe_def_file->exports[i].name + lead_at);
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);
631 /* Convenience, but watch out for it changing. */
632 e = pe_def_file->exports;
634 exported_symbol_offsets = xmalloc (NE * sizeof (bfd_vma));
635 exported_symbol_sections = xmalloc (NE * sizeof (struct bfd_section *));
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;
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++)
648 if (i > 0 && strcmp (e[i].name, e[i - 1].name) == 0)
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)
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);
660 else
662 if (pe_dll_warn_dup_exports)
663 /* xgettext:c-format */
664 einfo (_("Warning, duplicate EXPORT: %s\n"),
665 e[j - 1].name);
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;
675 else
677 if (i != j)
678 e[j] = e[i];
679 j++;
682 pe_def_file->num_exports = j; /* == NE */
684 for (i = 0; i < NE; i++)
686 char *name;
688 /* Check for forward exports */
689 if (strchr (pe_def_file->exports[i].internal_name, '.'))
691 count_exported++;
692 if (!pe_def_file->exports[i].flag_noname)
693 count_exported_byname++;
695 pe_def_file->exports[i].flag_forward = 1;
697 if (pe_def_file->exports[i].ordinal != -1)
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++;
706 continue;
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 != '@'))
713 *name = '_';
714 strcpy (name + 1, pe_def_file->exports[i].internal_name);
716 else
717 strcpy (name, pe_def_file->exports[i].internal_name);
719 blhe = bfd_link_hash_lookup (info->hash,
720 name,
721 FALSE, FALSE, TRUE);
723 if (blhe
724 && (blhe->type == bfd_link_hash_defined
725 || (blhe->type == bfd_link_hash_common)))
727 count_exported++;
728 if (!pe_def_file->exports[i].flag_noname)
729 count_exported_byname++;
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;
739 if (pe_def_file->exports[i].ordinal != -1)
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++;
748 else if (blhe && blhe->type == bfd_link_hash_undefined)
750 /* xgettext:c-format */
751 einfo (_("%XCannot export %s: symbol not defined\n"),
752 pe_def_file->exports[i].internal_name);
754 else if (blhe)
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);
761 else
763 /* xgettext:c-format */
764 einfo (_("%XCannot export %s: symbol not found\n"),
765 pe_def_file->exports[i].internal_name);
767 free (name);
771 /* Build the bfd that will contain .edata and .reloc sections. */
773 static void
774 build_filler_bfd (int include_edata)
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)))
786 einfo ("%X%P: can not create BFD: %E\n");
787 return;
790 if (include_edata)
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)))
801 einfo ("%X%P: can not create .edata section: %E\n");
802 return;
804 bfd_set_section_size (filler_bfd, edata_s, edata_sz);
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)))
816 einfo ("%X%P: can not create .reloc section: %E\n");
817 return;
820 bfd_set_section_size (filler_bfd, reloc_s, 0);
822 ldlang_add_file (filler_file);
825 /* Gather all the exported symbols and build the .edata section. */
827 static void
828 generate_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
830 int i, next_ordinal;
831 int name_table_size = 0;
832 const char *dlnp;
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
840 dll_name = abfd->filename;
842 for (dlnp = dll_name; *dlnp; dlnp++)
843 if (*dlnp == '\\' || *dlnp == '/' || *dlnp == ':')
844 dll_name = dlnp + 1;
847 if (count_with_ordinals && max_ordinal > count_exported)
849 if (min_ordinal > max_ordinal - count_exported + 1)
850 min_ordinal = max_ordinal - count_exported + 1;
852 else
854 min_ordinal = 1;
855 max_ordinal = count_exported;
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;
863 /* Now we need to assign ordinals to those that don't have them. */
864 for (i = 0; i < NE; i++)
866 if (exported_symbol_sections[i] ||
867 pe_def_file->exports[i].flag_forward)
869 if (pe_def_file->exports[i].ordinal != -1)
871 int ei = pe_def_file->exports[i].ordinal - min_ordinal;
872 int pi = exported_symbols[ei];
874 if (pi != -1)
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);
882 exported_symbols[ei] = i;
884 name_table_size += strlen (pe_def_file->exports[i].name) + 1;
887 /* Reserve space for the forward name. */
888 if (pe_def_file->exports[i].flag_forward)
890 name_table_size += strlen (pe_def_file->exports[i].internal_name) + 1;
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)
900 while (exported_symbols[next_ordinal - min_ordinal] != -1)
901 next_ordinal++;
903 exported_symbols[next_ordinal - min_ordinal] = i;
904 pe_def_file->exports[i].ordinal = next_ordinal;
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);
915 /* Fill the exported symbol offsets. The preliminary work has already
916 been done in process_def_file(). */
918 static void
919 fill_exported_offsets (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
921 int i;
922 struct bfd_link_hash_entry *blhe;
924 for (i = 0; i < pe_def_file->num_exports; i++)
926 char *name;
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 != '@')
932 *name = '_';
933 strcpy (name + 1, pe_def_file->exports[i].internal_name);
935 else
936 strcpy (name, pe_def_file->exports[i].internal_name);
938 blhe = bfd_link_hash_lookup (info->hash,
939 name,
940 FALSE, FALSE, TRUE);
942 if (blhe && blhe->type == bfd_link_hash_defined)
943 exported_symbol_offsets[i] = blhe->u.def.value;
945 free (name);
949 static void
950 fill_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
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;
960 time (&now);
962 edata_d = xmalloc (edata_sz);
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;
971 #define ERVA(ptr) (((unsigned char *)(ptr) - edata_d) \
972 + edata_s->output_section->vma - image_base)
974 memset (edata_d, 0, edata_sz);
975 bfd_put_32 (abfd, now, edata_d + 4);
976 if (pe_def_file->version_major != -1)
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);
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);
992 fill_exported_offsets (abfd, info);
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++)
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))
1007 int ord = pe_def_file->exports[s].ordinal;
1009 if (pe_def_file->exports[s].flag_forward)
1011 bfd_put_32 (abfd, ERVA (enamestr),
1012 eaddresses + 4 * (ord - min_ordinal));
1014 strcpy (enamestr, pe_def_file->exports[s].internal_name);
1015 enamestr += strlen (pe_def_file->exports[s].internal_name) + 1;
1017 else
1019 unsigned long srva = (exported_symbol_offsets[s]
1020 + ssec->output_section->vma
1021 + ssec->output_offset);
1023 bfd_put_32 (abfd, srva - image_base,
1024 eaddresses + 4 * (ord - min_ordinal));
1027 if (!pe_def_file->exports[s].flag_noname)
1029 char *ename = pe_def_file->exports[s].name;
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++;
1044 static struct bfd_section *current_sec;
1046 void
1047 pe_walk_relocs_of_symbol (struct bfd_link_info *info,
1048 const char *name,
1049 int (*cb) (arelent *, asection *))
1051 bfd *b;
1052 asection *s;
1054 for (b = info->input_bfds; b; b = b->link_next)
1056 asymbol **symbols;
1057 int nsyms, symsize;
1059 symsize = bfd_get_symtab_upper_bound (b);
1060 symbols = xmalloc (symsize);
1061 nsyms = bfd_canonicalize_symtab (b, symbols);
1063 for (s = b->sections; s; s = s->next)
1065 arelent **relocs;
1066 int relsize, nrelocs, i;
1067 int flags = bfd_get_section_flags (b, s);
1069 /* Skip discarded linkonce sections. */
1070 if (flags & SEC_LINK_ONCE
1071 && s->output_section == bfd_abs_section_ptr)
1072 continue;
1074 current_sec = s;
1076 relsize = bfd_get_reloc_upper_bound (b, s);
1077 relocs = xmalloc (relsize);
1078 nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1080 for (i = 0; i < nrelocs; i++)
1082 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1084 if (!strcmp (name, sym->name))
1085 cb (relocs[i], s);
1088 free (relocs);
1090 /* Warning: the allocated symbols are remembered in BFD and reused
1091 later, so don't free them! */
1092 /* free (symbols); */
1097 /* Gather all the relocations and build the .reloc section. */
1099 static void
1100 generate_reloc (bfd *abfd, struct bfd_link_info *info)
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;
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;
1118 reloc_data = xmalloc (total_relocs * sizeof (reloc_data_type));
1120 total_relocs = 0;
1121 bi = 0;
1122 for (bi = 0, b = info->input_bfds; b; bi++, b = b->link_next)
1124 arelent **relocs;
1125 int relsize, nrelocs, i;
1127 for (s = b->sections; s; s = s->next)
1129 unsigned long sec_vma = s->output_section->vma + s->output_offset;
1130 asymbol **symbols;
1131 int nsyms, symsize;
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;
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;
1142 if (s->output_section->vma == 0)
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;
1151 symsize = bfd_get_symtab_upper_bound (b);
1152 symbols = xmalloc (symsize);
1153 nsyms = bfd_canonicalize_symtab (b, symbols);
1155 relsize = bfd_get_reloc_upper_bound (b, s);
1156 relocs = xmalloc (relsize);
1157 nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1159 for (i = 0; i < nrelocs; i++)
1161 if (pe_dll_extra_pe_debug)
1163 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1164 printf ("rel: %s\n", sym->name);
1166 if (!relocs[i]->howto->pc_relative
1167 && relocs[i]->howto->type != pe_details->imagebase_reloc)
1169 bfd_vma sym_vma;
1170 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
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;
1179 #define BITS_AND_SHIFT(bits, shift) (bits * 1000 | shift)
1181 switch BITS_AND_SHIFT (relocs[i]->howto->bitsize,
1182 relocs[i]->howto->rightshift)
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;
1225 free (relocs);
1226 /* Warning: the allocated symbols are remembered in BFD and
1227 reused later, so don't free them! */
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);
1236 for (i = 0; i < total_relocs; i++)
1238 unsigned long this_page = (reloc_data[i].vma >> 12);
1240 if (this_page != sec_page)
1242 reloc_sz = (reloc_sz + 3) & ~3; /* 4-byte align. */
1243 reloc_sz += 8;
1244 sec_page = this_page;
1247 reloc_sz += 2;
1249 if (reloc_data[i].type == 4)
1250 reloc_sz += 2;
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;
1260 for (i = 0; i < total_relocs; i++)
1262 unsigned long rva = reloc_data[i].vma - image_base;
1263 unsigned long this_page = (rva & ~0xfff);
1265 if (this_page != sec_page)
1267 while (reloc_sz & 3)
1268 reloc_d[reloc_sz++] = 0;
1270 if (page_ptr != (unsigned long) -1)
1271 bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
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;
1280 bfd_put_16 (abfd, (rva & 0xfff) + (reloc_data[i].type << 12),
1281 reloc_d + reloc_sz);
1282 reloc_sz += 2;
1284 if (reloc_data[i].type == 4)
1286 bfd_put_16 (abfd, reloc_data[i].extra, reloc_d + reloc_sz);
1287 reloc_sz += 2;
1290 page_count++;
1293 while (reloc_sz & 3)
1294 reloc_d[reloc_sz++] = 0;
1296 if (page_ptr != (unsigned long) -1)
1297 bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
1299 while (reloc_sz < reloc_s->size)
1300 reloc_d[reloc_sz++] = 0;
1303 /* Given the exiting def_file structure, print out a .DEF file that
1304 corresponds to it. */
1306 static void
1307 quoteput (char *s, FILE *f, int needs_quotes)
1309 char *cp;
1311 for (cp = s; *cp; cp++)
1312 if (*cp == '\''
1313 || *cp == '"'
1314 || *cp == '\\'
1315 || ISSPACE (*cp)
1316 || *cp == ','
1317 || *cp == ';')
1318 needs_quotes = 1;
1320 if (needs_quotes)
1322 putc ('"', f);
1324 while (*s)
1326 if (*s == '"' || *s == '\\')
1327 putc ('\\', f);
1329 putc (*s, f);
1330 s++;
1333 putc ('"', f);
1335 else
1336 fputs (s, f);
1339 void
1340 pe_dll_generate_def_file (const char *pe_out_def_filename)
1342 int i;
1343 FILE *out = fopen (pe_out_def_filename, "w");
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);
1350 if (pe_def_file)
1352 if (pe_def_file->name)
1354 if (pe_def_file->is_dll)
1355 fprintf (out, "LIBRARY ");
1356 else
1357 fprintf (out, "NAME ");
1359 quoteput (pe_def_file->name, out, 1);
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");
1367 if (pe_def_file->description)
1369 fprintf (out, "DESCRIPTION ");
1370 quoteput (pe_def_file->description, out, 1);
1371 fprintf (out, "\n");
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);
1380 if (pe_def_file->stack_reserve != -1 || pe_def_file->heap_reserve != -1)
1381 fprintf (out, "\n");
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);
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);
1395 if (pe_def_file->num_section_defs > 0)
1397 fprintf (out, "\nSECTIONS\n\n");
1399 for (i = 0; i < pe_def_file->num_section_defs; i++)
1401 fprintf (out, " ");
1402 quoteput (pe_def_file->section_defs[i].name, out, 0);
1404 if (pe_def_file->section_defs[i].class)
1406 fprintf (out, " CLASS ");
1407 quoteput (pe_def_file->section_defs[i].class, out, 0);
1410 if (pe_def_file->section_defs[i].flag_read)
1411 fprintf (out, " READ");
1413 if (pe_def_file->section_defs[i].flag_write)
1414 fprintf (out, " WRITE");
1416 if (pe_def_file->section_defs[i].flag_execute)
1417 fprintf (out, " EXECUTE");
1419 if (pe_def_file->section_defs[i].flag_shared)
1420 fprintf (out, " SHARED");
1422 fprintf (out, "\n");
1426 if (pe_def_file->num_exports > 0)
1428 fprintf (out, "EXPORTS\n");
1430 for (i = 0; i < pe_def_file->num_exports; i++)
1432 def_file_export *e = pe_def_file->exports + i;
1433 fprintf (out, " ");
1434 quoteput (e->name, out, 0);
1436 if (e->internal_name && strcmp (e->internal_name, e->name))
1438 fprintf (out, " = ");
1439 quoteput (e->internal_name, out, 0);
1442 if (e->ordinal != -1)
1443 fprintf (out, " @%d", e->ordinal);
1445 if (e->flag_private)
1446 fprintf (out, " PRIVATE");
1448 if (e->flag_constant)
1449 fprintf (out, " CONSTANT");
1451 if (e->flag_noname)
1452 fprintf (out, " NONAME");
1454 if (e->flag_data)
1455 fprintf (out, " DATA");
1457 fprintf (out, "\n");
1461 if (pe_def_file->num_imports > 0)
1463 fprintf (out, "\nIMPORTS\n\n");
1465 for (i = 0; i < pe_def_file->num_imports; i++)
1467 def_file_import *im = pe_def_file->imports + i;
1468 fprintf (out, " ");
1470 if (im->internal_name
1471 && (!im->name || strcmp (im->internal_name, im->name)))
1473 quoteput (im->internal_name, out, 0);
1474 fprintf (out, " = ");
1477 quoteput (im->module->name, out, 0);
1478 fprintf (out, ".");
1480 if (im->name)
1481 quoteput (im->name, out, 0);
1482 else
1483 fprintf (out, "%d", im->ordinal);
1485 fprintf (out, "\n");
1489 else
1490 fprintf (out, _("; no contents available\n"));
1492 if (fclose (out) == EOF)
1493 /* xgettext:c-format */
1494 einfo (_("%P: Error closing file `%s'\n"), pe_out_def_filename);
1497 /* Generate the import library. */
1499 static asymbol **symtab;
1500 static int symptr;
1501 static int tmp_seq;
1502 static const char *dll_filename;
1503 static char *dll_symname;
1505 #define UNDSEC (asection *) &bfd_und_section
1507 static asection *
1508 quick_section (bfd *abfd, const char *name, int flags, int align)
1510 asection *sec;
1511 asymbol *sym;
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;
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;
1526 return sec;
1529 static void
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)
1538 asymbol *sym;
1539 char *name = xmalloc (strlen (n1) + strlen (n2) + strlen (n3) + 1);
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;
1552 static arelent *reltab = 0;
1553 static int relcount = 0, relsize = 0;
1555 static void
1556 quick_reloc (bfd *abfd, int address, int which_howto, int symidx)
1558 if (relcount >= relsize - 1)
1560 relsize += 10;
1561 if (reltab)
1562 reltab = xrealloc (reltab, relsize * sizeof (arelent));
1563 else
1564 reltab = xmalloc (relsize * sizeof (arelent));
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++;
1573 static void
1574 save_relocs (asection *sec)
1576 int i;
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;
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
1598 .section .idata$5
1599 .long 0
1600 fthunk:
1602 .section .idata$4
1603 .long 0
1604 hname: */
1606 static bfd *
1607 make_head (bfd *parent)
1609 asection *id2, *id5, *id4;
1610 unsigned char *d2, *d5, *d4;
1611 char *oname;
1612 bfd *abfd;
1614 oname = xmalloc (20);
1615 sprintf (oname, "d%06d.o", tmp_seq);
1616 tmp_seq++;
1618 abfd = bfd_create (oname, parent);
1619 bfd_find_target (pe_details->object_target, abfd);
1620 bfd_make_writable (abfd);
1622 bfd_set_format (abfd, bfd_object);
1623 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
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);
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. */
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);
1649 bfd_set_section_size (abfd, id5, 4);
1650 d5 = xmalloc (4);
1651 id5->contents = d5;
1652 memset (d5, 0, 4);
1654 bfd_set_section_size (abfd, id4, 4);
1655 d4 = xmalloc (4);
1656 id4->contents = d4;
1657 memset (d4, 0, 4);
1659 bfd_set_symtab (abfd, symtab, symptr);
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);
1665 bfd_make_readable (abfd);
1666 return abfd;
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" */
1678 static bfd *
1679 make_tail (bfd *parent)
1681 asection *id4, *id5, *id7;
1682 unsigned char *d4, *d5, *d7;
1683 int len;
1684 char *oname;
1685 bfd *abfd;
1687 oname = xmalloc (20);
1688 sprintf (oname, "d%06d.o", tmp_seq);
1689 tmp_seq++;
1691 abfd = bfd_create (oname, parent);
1692 bfd_find_target (pe_details->object_target, abfd);
1693 bfd_make_writable (abfd);
1695 bfd_set_format (abfd, bfd_object);
1696 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
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);
1705 bfd_set_section_size (abfd, id4, 4);
1706 d4 = xmalloc (4);
1707 id4->contents = d4;
1708 memset (d4, 0, 4);
1710 bfd_set_section_size (abfd, id5, 4);
1711 d5 = xmalloc (4);
1712 id5->contents = d5;
1713 memset (d5, 0, 4);
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);
1723 bfd_set_symtab (abfd, symtab, symptr);
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);
1729 bfd_make_readable (abfd);
1730 return abfd;
1733 /* .text
1734 .global _function
1735 .global ___imp_function
1736 .global __imp__function
1737 _function:
1738 jmp *__imp__function:
1740 .section idata$7
1741 .long __head_my_dll
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) */
1754 static unsigned char jmp_ix86_bytes[] =
1756 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
1759 /* _function:
1760 mov.l ip+8,r0
1761 mov.l @r0,r0
1762 jmp @r0
1764 .dw __imp_function */
1766 static unsigned char jmp_sh_bytes[] =
1768 0x01, 0xd0, 0x02, 0x60, 0x2b, 0x40, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00
1771 /* _function:
1772 lui $t0,<high:__imp_function>
1773 lw $t0,<low:__imp_function>
1774 jr $t0
1775 nop */
1777 static unsigned char jmp_mips_bytes[] =
1779 0x00, 0x00, 0x08, 0x3c, 0x00, 0x00, 0x08, 0x8d,
1780 0x08, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
1783 static bfd *
1784 make_one (def_file_export *exp, bfd *parent)
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;
1794 switch (pe_details->pe_arch)
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 ();
1812 oname = xmalloc (20);
1813 sprintf (oname, "d%06d.o", tmp_seq);
1814 tmp_seq++;
1816 abfd = bfd_create (oname, parent);
1817 bfd_find_target (pe_details->object_target, abfd);
1818 bfd_make_writable (abfd);
1820 bfd_set_format (abfd, bfd_object);
1821 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
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);
1831 if (*exp->internal_name == '@')
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. */
1842 else
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);
1857 if (pe_dll_compat_implib)
1858 quick_symbol (abfd, U ("__imp_"), exp->internal_name, "", id5,
1859 BSF_GLOBAL, 0);
1861 if (! exp->flag_data)
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);
1868 switch (pe_details->pe_arch)
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 ();
1884 save_relocs (tx);
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);
1894 bfd_set_section_size (abfd, id5, 4);
1895 d5 = xmalloc (4);
1896 id5->contents = d5;
1897 memset (d5, 0, 4);
1899 if (exp->flag_noname)
1901 d5[0] = exp->ordinal;
1902 d5[1] = exp->ordinal >> 8;
1903 d5[3] = 0x80;
1905 else
1907 quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1908 save_relocs (id5);
1911 bfd_set_section_size (abfd, id4, 4);
1912 d4 = xmalloc (4);
1913 id4->contents = d4;
1914 memset (d4, 0, 4);
1916 if (exp->flag_noname)
1918 d4[0] = exp->ordinal;
1919 d4[1] = exp->ordinal >> 8;
1920 d4[3] = 0x80;
1922 else
1924 quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1925 save_relocs (id4);
1928 if (exp->flag_noname)
1930 len = 0;
1931 bfd_set_section_size (abfd, id6, 0);
1933 else
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);
1947 bfd_set_symtab (abfd, symtab, symptr);
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);
1956 bfd_make_readable (abfd);
1957 return abfd;
1960 static bfd *
1961 make_singleton_name_thunk (const char *import, bfd *parent)
1963 /* Name thunks go to idata$4. */
1964 asection *id4;
1965 unsigned char *d4;
1966 char *oname;
1967 bfd *abfd;
1969 oname = xmalloc (20);
1970 sprintf (oname, "nmth%06d.o", tmp_seq);
1971 tmp_seq++;
1973 abfd = bfd_create (oname, parent);
1974 bfd_find_target (pe_details->object_target, abfd);
1975 bfd_make_writable (abfd);
1977 bfd_set_format (abfd, bfd_object);
1978 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
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);
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);
1993 bfd_set_symtab (abfd, symtab, symptr);
1995 bfd_set_section_contents (abfd, id4, d4, 0, 8);
1997 bfd_make_readable (abfd);
1998 return abfd;
2001 static char *
2002 make_import_fixup_mark (arelent *rel)
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;
2009 struct bfd_symbol *sym = *rel->sym_ptr_ptr;
2011 bfd *abfd = bfd_asymbol_bfd (sym);
2012 struct bfd_link_hash_entry *bh;
2014 if (!fixup_name)
2016 fixup_name = xmalloc (384);
2017 buffer_len = 384;
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... */
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);
2032 sprintf (fixup_name, "__fu%d_%s", counter++, sym->name);
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);
2039 if (0)
2041 struct coff_link_hash_entry *myh;
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);
2048 return fixup_name;
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) */
2058 static bfd *
2059 make_import_fixup_entry (const char *name,
2060 const char *fixup_name,
2061 const char *dll_symname,
2062 bfd *parent)
2064 asection *id3;
2065 unsigned char *d3;
2066 char *oname;
2067 bfd *abfd;
2069 oname = xmalloc (20);
2070 sprintf (oname, "fu%06d.o", tmp_seq);
2071 tmp_seq++;
2073 abfd = bfd_create (oname, parent);
2074 bfd_find_target (pe_details->object_target, abfd);
2075 bfd_make_writable (abfd);
2077 bfd_set_format (abfd, bfd_object);
2078 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2080 symptr = 0;
2081 symtab = xmalloc (6 * sizeof (asymbol *));
2082 id3 = quick_section (abfd, ".idata$3", SEC_HAS_CONTENTS, 2);
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);
2088 bfd_set_section_size (abfd, id3, 20);
2089 d3 = xmalloc (20);
2090 id3->contents = d3;
2091 memset (d3, 0, 20);
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);
2098 bfd_set_symtab (abfd, symtab, symptr);
2100 bfd_set_section_contents (abfd, id3, d3, 0, 20);
2102 bfd_make_readable (abfd);
2103 return abfd;
2106 /* .section .rdata_runtime_pseudo_reloc
2107 .long addend
2108 .rva __fuNN_SYM (pointer to reference (address) in text) */
2110 static bfd *
2111 make_runtime_pseudo_reloc (const char *name ATTRIBUTE_UNUSED,
2112 const char *fixup_name,
2113 int addend,
2114 bfd *parent)
2116 asection *rt_rel;
2117 unsigned char *rt_rel_d;
2118 char *oname;
2119 bfd *abfd;
2121 oname = xmalloc (20);
2122 sprintf (oname, "rtr%06d.o", tmp_seq);
2123 tmp_seq++;
2125 abfd = bfd_create (oname, parent);
2126 bfd_find_target (pe_details->object_target, abfd);
2127 bfd_make_writable (abfd);
2129 bfd_set_format (abfd, bfd_object);
2130 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2132 symptr = 0;
2133 symtab = xmalloc (2 * sizeof (asymbol *));
2134 rt_rel = quick_section (abfd, ".rdata_runtime_pseudo_reloc",
2135 SEC_HAS_CONTENTS, 2);
2137 quick_symbol (abfd, "", fixup_name, "", UNDSEC, BSF_GLOBAL, 0);
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);
2145 quick_reloc (abfd, 4, BFD_RELOC_RVA, 1);
2146 save_relocs (rt_rel);
2148 bfd_set_symtab (abfd, symtab, symptr);
2150 bfd_set_section_contents (abfd, rt_rel, rt_rel_d, 0, 8);
2152 bfd_make_readable (abfd);
2153 return abfd;
2156 /* .section .rdata
2157 .rva __pei386_runtime_relocator */
2159 static bfd *
2160 pe_create_runtime_relocator_reference (bfd *parent)
2162 asection *extern_rt_rel;
2163 unsigned char *extern_rt_rel_d;
2164 char *oname;
2165 bfd *abfd;
2167 oname = xmalloc (20);
2168 sprintf (oname, "ertr%06d.o", tmp_seq);
2169 tmp_seq++;
2171 abfd = bfd_create (oname, parent);
2172 bfd_find_target (pe_details->object_target, abfd);
2173 bfd_make_writable (abfd);
2175 bfd_set_format (abfd, bfd_object);
2176 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2178 symptr = 0;
2179 symtab = xmalloc (2 * sizeof (asymbol *));
2180 extern_rt_rel = quick_section (abfd, ".rdata", SEC_HAS_CONTENTS, 2);
2182 quick_symbol (abfd, "", "__pei386_runtime_relocator", "", UNDSEC,
2183 BSF_NO_FLAGS, 0);
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;
2189 quick_reloc (abfd, 0, BFD_RELOC_RVA, 1);
2190 save_relocs (extern_rt_rel);
2192 bfd_set_symtab (abfd, symtab, symptr);
2194 bfd_set_section_contents (abfd, extern_rt_rel, extern_rt_rel_d, 0, 4);
2196 bfd_make_readable (abfd);
2197 return abfd;
2200 void
2201 pe_create_import_fixup (arelent *rel, asection *s, int addend)
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;
2210 sprintf (buf, U ("_nm_thnk_%s"), name);
2212 name_thunk_sym = bfd_link_hash_lookup (link_info.hash, buf, 0, 0, 1);
2214 if (!name_thunk_sym || name_thunk_sym->type != bfd_link_hash_defined)
2216 bfd *b = make_singleton_name_thunk (name, output_bfd);
2217 add_bfd_to_link (b, b->filename, &link_info);
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;
2224 if (addend == 0 || link_info.pei386_runtime_pseudo_reloc)
2226 extern char * pe_data_import_dll;
2227 char * dll_symname = pe_data_import_dll ? pe_data_import_dll : "unknown";
2229 b = make_import_fixup_entry (name, fixup_name, dll_symname, output_bfd);
2230 add_bfd_to_link (b, b->filename, &link_info);
2233 if (addend != 0)
2235 if (link_info.pei386_runtime_pseudo_reloc)
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);
2243 if (runtime_pseudo_relocs_created == 0)
2245 b = pe_create_runtime_relocator_reference (output_bfd);
2246 add_bfd_to_link (b, b->filename, &link_info);
2248 runtime_pseudo_relocs_created++;
2250 else
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");
2260 void
2261 pe_dll_generate_implib (def_file *def, const char *impfilename)
2263 int i;
2264 bfd *ar_head;
2265 bfd *ar_tail;
2266 bfd *outarch;
2267 bfd *head = 0;
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] = '_';
2275 unlink_if_ordinary (impfilename);
2277 outarch = bfd_openw (impfilename, 0);
2279 if (!outarch)
2281 /* xgettext:c-format */
2282 einfo (_("%XCan't open .lib file: %s\n"), impfilename);
2283 return;
2286 /* xgettext:c-format */
2287 info_msg (_("Creating library file: %s\n"), impfilename);
2289 bfd_set_format (outarch, bfd_archive);
2290 outarch->has_armap = 1;
2292 /* Work out a reasonable size of things to put onto one line. */
2293 ar_head = make_head (outarch);
2295 for (i = 0; i < def->num_exports; i++)
2297 /* The import library doesn't know about the internal name. */
2298 char *internal = def->exports[i].internal_name;
2299 bfd *n;
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;
2311 ar_tail = make_tail (outarch);
2313 if (ar_head == NULL || ar_tail == NULL)
2314 return;
2316 /* Now stick them all into the archive. */
2317 ar_head->next = head;
2318 ar_tail->next = ar_head;
2319 head = ar_tail;
2321 if (! bfd_set_archive_head (outarch, head))
2322 einfo ("%Xbfd_set_archive_head: %E\n");
2324 if (! bfd_close (outarch))
2325 einfo ("%Xbfd_close %s: %E\n", impfilename);
2327 while (head != NULL)
2329 bfd *n = head->next;
2330 bfd_close (head);
2331 head = n;
2335 static void
2336 add_bfd_to_link (bfd *abfd, const char *name, struct bfd_link_info *link_info)
2338 lang_input_statement_type *fake_file;
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);
2346 if (!bfd_link_add_symbols (abfd, link_info))
2347 einfo ("%Xaddsym %s: %E\n", name);
2350 void
2351 pe_process_import_defs (bfd *output_bfd, struct bfd_link_info *link_info)
2353 def_file_module *module;
2355 pe_dll_id_target (bfd_get_target (output_bfd));
2357 if (!pe_def_file)
2358 return;
2360 for (module = pe_def_file->modules; module; module = module->next)
2362 int i, do_this_dll;
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] = '_';
2370 do_this_dll = 0;
2372 for (i = 0; i < pe_def_file->num_imports; i++)
2373 if (pe_def_file->imports[i].module == module)
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);
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);
2389 blhe = bfd_link_hash_lookup (link_info->hash, name,
2390 FALSE, FALSE, FALSE);
2392 if (!blhe || (blhe && blhe->type != bfd_link_hash_undefined))
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);
2401 blhe = bfd_link_hash_lookup (link_info->hash, name,
2402 FALSE, FALSE, FALSE);
2404 free (name);
2406 if (blhe && blhe->type == bfd_link_hash_undefined)
2408 bfd *one;
2409 /* We do. */
2410 if (!do_this_dll)
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;
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);
2428 if (do_this_dll)
2430 bfd *ar_tail = make_tail (output_bfd);
2431 add_bfd_to_link (ar_tail, ar_tail->filename, link_info);
2434 free (dll_symname);
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. */
2442 static unsigned int
2443 pe_get16 (bfd *abfd, int where)
2445 unsigned char b[2];
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);
2452 static unsigned int
2453 pe_get32 (bfd *abfd, int where)
2455 unsigned char b[4];
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);
2462 static unsigned int
2463 pe_as32 (void *ptr)
2465 unsigned char *b = ptr;
2467 return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
2470 bfd_boolean
2471 pe_implied_import_dll (const char *filename)
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;
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)
2495 einfo ("%Xopen %s: %E\n", filename);
2496 return FALSE;
2499 /* PEI dlls seem to be bfd_objects. */
2500 if (!bfd_check_format (dll, bfd_object))
2502 einfo ("%X%s: this doesn't appear to be a DLL\n", filename);
2503 return FALSE;
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);
2511 if (num_entries < 1) /* No exports. */
2512 return FALSE;
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;
2521 /* Get the rva and size of the export section. */
2522 for (i = 0; i < nsections; i++)
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);
2530 bfd_seek (dll, (file_ptr) secptr1, SEEK_SET);
2531 bfd_bread (sname, (bfd_size_type) 8, dll);
2533 if (vaddr <= export_rva && vaddr + vsize > export_rva)
2535 expptr = fptr + (export_rva - vaddr);
2536 if (export_rva + export_size > vaddr + vsize)
2537 export_size = vsize - (export_rva - vaddr);
2538 break;
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++)
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];
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);
2556 if (strcmp(sec_name,".data") == 0)
2558 data_start = vaddr;
2559 data_end = vaddr + vsize;
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);
2565 else if (strcmp(sec_name,".rdata") == 0)
2567 rdata_start = vaddr;
2568 rdata_end = vaddr + vsize;
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);
2574 else if (strcmp (sec_name,".bss") == 0)
2576 bss_start = vaddr;
2577 bss_end = vaddr + vsize;
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);
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;
2590 if (pe_def_file == 0)
2591 pe_def_file = def_file_empty ();
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);
2599 /* Use internal dll name instead of filename
2600 to enable symbolic dll linking. */
2601 dll_name = erva + pe_as32 (expdata + 12);
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))
2608 if (pe_dll_extra_pe_debug)
2609 printf ("%s is already loaded\n", dll_name);
2610 return TRUE;
2613 /* Iterate through the list of symbols. */
2614 for (i = 0; i < nexp; i++)
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;
2623 /* Skip unwanted symbols, which are
2624 exported in buggy auto-import releases. */
2625 if (strncmp (erva + name_rva, "_nm_", 4) != 0)
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);
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;
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)" : "");
2646 return TRUE;
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. */
2654 void
2655 pe_dll_build_sections (bfd *abfd, struct bfd_link_info *info)
2657 pe_dll_id_target (bfd_get_target (abfd));
2658 process_def_file (abfd, info);
2660 if (pe_def_file->num_exports == 0 && !info->shared)
2661 return;
2663 generate_edata (abfd, info);
2664 build_filler_bfd (1);
2667 void
2668 pe_exe_build_sections (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
2670 pe_dll_id_target (bfd_get_target (abfd));
2671 build_filler_bfd (0);
2674 void
2675 pe_dll_fill_sections (bfd *abfd, struct bfd_link_info *info)
2677 pe_dll_id_target (bfd_get_target (abfd));
2678 image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2680 generate_reloc (abfd, info);
2681 if (reloc_sz > 0)
2683 bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2685 /* Resize the sections. */
2686 lang_reset_memory_regions ();
2687 lang_size_sections (NULL, TRUE);
2689 /* Redo special stuff. */
2690 ldemul_after_allocation ();
2692 /* Do the assignments again. */
2693 lang_do_assignments ();
2696 fill_edata (abfd, info);
2698 if (info->shared && !info->pie)
2699 pe_data (abfd)->dll = 1;
2701 edata_s->contents = edata_d;
2702 reloc_s->contents = reloc_d;
2705 void
2706 pe_exe_fill_sections (bfd *abfd, struct bfd_link_info *info)
2708 pe_dll_id_target (bfd_get_target (abfd));
2709 image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2711 generate_reloc (abfd, info);
2712 if (reloc_sz > 0)
2714 bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2716 /* Resize the sections. */
2717 lang_reset_memory_regions ();
2718 lang_size_sections (NULL, TRUE);
2720 /* Redo special stuff. */
2721 ldemul_after_allocation ();
2723 /* Do the assignments again. */
2724 lang_do_assignments ();
2726 reloc_s->contents = reloc_d;