* emulparams/h8300elf.sh: _tinydata should not be placed in relocatables.
[binutils.git] / ld / pe-dll.c
blob8af1b0639049894bdcdd1e8dae96282eed28e8fd
1 /* Routines to help build PEI-format DLLs (Win32 etc)
2 Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
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$2 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 *name;
149 int len;
151 autofilter_entry_type;
153 typedef struct
155 char *target_name;
156 char *object_target;
157 unsigned int imagebase_reloc;
158 int pe_arch;
159 int bfd_arch;
160 bfd_boolean underscored;
161 autofilter_entry_type* autofilter_symbollist;
163 pe_details_type;
165 static autofilter_entry_type autofilter_symbollist_generic[] =
167 { ".text", 5 },
168 /* Entry point symbols. */
169 { "DllMain", 7 },
170 { "DllMainCRTStartup", 17 },
171 { "_DllMainCRTStartup", 18 },
172 /* Runtime pseudo-reloc. */
173 { "_pei386_runtime_relocator", 25 },
174 { "do_pseudo_reloc", 15 },
175 { NULL, 0 }
178 static autofilter_entry_type autofilter_symbollist_i386[] =
180 { ".text", 5 },
181 /* Entry point symbols, and entry hooks. */
182 { "cygwin_crt0", 11 },
183 { "DllMain@12", 10 },
184 { "DllEntryPoint@0", 15 },
185 { "DllMainCRTStartup@12", 20 },
186 { "_cygwin_dll_entry@12", 20 },
187 { "_cygwin_crt0_common@8", 21 },
188 { "_cygwin_noncygwin_dll_entry@12", 30 },
189 { "cygwin_attach_dll", 17 },
190 { "cygwin_premain0", 15 },
191 { "cygwin_premain1", 15 },
192 { "cygwin_premain2", 15 },
193 { "cygwin_premain3", 15 },
194 /* Runtime pseudo-reloc. */
195 { "_pei386_runtime_relocator", 25 },
196 { "do_pseudo_reloc", 15 },
197 /* Global vars that should not be exported. */
198 { "impure_ptr", 10 },
199 { "_impure_ptr", 11 },
200 { "_fmode", 6 },
201 { "environ", 7 },
202 { NULL, 0 }
205 #define PE_ARCH_i386 1
206 #define PE_ARCH_sh 2
207 #define PE_ARCH_mips 3
208 #define PE_ARCH_arm 4
209 #define PE_ARCH_arm_epoc 5
210 #define PE_ARCH_arm_wince 6
212 static pe_details_type pe_detail_list[] =
215 "pei-i386",
216 "pe-i386",
217 7 /* R_IMAGEBASE */,
218 PE_ARCH_i386,
219 bfd_arch_i386,
220 TRUE,
221 autofilter_symbollist_i386
224 "pei-shl",
225 "pe-shl",
226 16 /* R_SH_IMAGEBASE */,
227 PE_ARCH_sh,
228 bfd_arch_sh,
229 TRUE,
230 autofilter_symbollist_generic
233 "pei-mips",
234 "pe-mips",
235 34 /* MIPS_R_RVA */,
236 PE_ARCH_mips,
237 bfd_arch_mips,
238 FALSE,
239 autofilter_symbollist_generic
242 "pei-arm-little",
243 "pe-arm-little",
244 11 /* ARM_RVA32 */,
245 PE_ARCH_arm,
246 bfd_arch_arm,
247 TRUE,
248 autofilter_symbollist_generic
251 "epoc-pei-arm-little",
252 "epoc-pe-arm-little",
253 11 /* ARM_RVA32 */,
254 PE_ARCH_arm_epoc,
255 bfd_arch_arm,
256 FALSE,
257 autofilter_symbollist_generic
260 "pei-arm-wince-little",
261 "pe-arm-wince-little",
262 2, /* ARM_RVA32 on Windows CE, see bfd/coff-arm.c. */
263 PE_ARCH_arm_wince,
264 bfd_arch_arm,
265 FALSE,
266 autofilter_symbollist_generic
268 { NULL, NULL, 0, 0, 0, FALSE, NULL }
271 static pe_details_type *pe_details;
273 /* Do not specify library suffix explicitly, to allow for dllized versions. */
274 static autofilter_entry_type autofilter_liblist[] =
276 { "libcegcc", 8 },
277 { "libcygwin", 9 },
278 { "libgcc", 6 },
279 { "libstdc++", 9 },
280 { "libmingw32", 10 },
281 { "libmingwex", 10 },
282 { "libg2c", 6 },
283 { "libsupc++", 9 },
284 { "libobjc", 7 },
285 { "libgcj", 6 },
286 { NULL, 0 }
289 static autofilter_entry_type autofilter_objlist[] =
291 { "crt0.o", 6 },
292 { "crt1.o", 6 },
293 { "crt2.o", 6 },
294 { "dllcrt1.o", 9 },
295 { "dllcrt2.o", 9 },
296 { "gcrt0.o", 7 },
297 { "gcrt1.o", 7 },
298 { "gcrt2.o", 7 },
299 { "crtbegin.o", 10 },
300 { "crtend.o", 8 },
301 { NULL, 0 }
304 static autofilter_entry_type autofilter_symbolprefixlist[] =
306 { "__imp_", 6 },
307 /* Do __imp_ explicitly to save time. */
308 { "__rtti_", 7 },
309 /* Don't re-export auto-imported symbols. */
310 { "_nm_", 4 },
311 { "__builtin_", 10 },
312 /* Don't export symbols specifying internal DLL layout. */
313 { "_head_", 6 },
314 { NULL, 0 }
317 static autofilter_entry_type autofilter_symbolsuffixlist[] =
319 { "_iname", 6 },
320 { NULL, 0 }
323 #define U(str) (pe_details->underscored ? "_" str : str)
325 void
326 pe_dll_id_target (const char *target)
328 int i;
330 for (i = 0; pe_detail_list[i].target_name; i++)
331 if (strcmp (pe_detail_list[i].target_name, target) == 0
332 || strcmp (pe_detail_list[i].object_target, target) == 0)
334 pe_details = pe_detail_list + i;
335 return;
337 einfo (_("%XUnsupported PEI architecture: %s\n"), target);
338 exit (1);
341 /* Helper functions for qsort. Relocs must be sorted so that we can write
342 them out by pages. */
344 typedef struct
346 bfd_vma vma;
347 char type;
348 short extra;
350 reloc_data_type;
352 static int
353 reloc_sort (const void *va, const void *vb)
355 bfd_vma a = ((const reloc_data_type *) va)->vma;
356 bfd_vma b = ((const reloc_data_type *) vb)->vma;
358 return (a > b) ? 1 : ((a < b) ? -1 : 0);
361 static int
362 pe_export_sort (const void *va, const void *vb)
364 const def_file_export *a = va;
365 const def_file_export *b = vb;
367 return strcmp (a->name, b->name);
370 /* Read and process the .DEF file. */
372 /* These correspond to the entries in pe_def_file->exports[]. I use
373 exported_symbol_sections[i] to tag whether or not the symbol was
374 defined, since we can't export symbols we don't have. */
376 static bfd_vma *exported_symbol_offsets;
377 static struct bfd_section **exported_symbol_sections;
378 static int export_table_size;
379 static int count_exported;
380 static int count_exported_byname;
381 static int count_with_ordinals;
382 static const char *dll_name;
383 static int min_ordinal, max_ordinal;
384 static int *exported_symbols;
386 typedef struct exclude_list_struct
388 char *string;
389 struct exclude_list_struct *next;
390 int type;
392 exclude_list_struct;
394 static struct exclude_list_struct *excludes = 0;
396 void
397 pe_dll_add_excludes (const char *new_excludes, const int type)
399 char *local_copy;
400 char *exclude_string;
402 local_copy = xstrdup (new_excludes);
404 exclude_string = strtok (local_copy, ",:");
405 for (; exclude_string; exclude_string = strtok (NULL, ",:"))
407 struct exclude_list_struct *new_exclude;
409 new_exclude = xmalloc (sizeof (struct exclude_list_struct));
410 new_exclude->string = xmalloc (strlen (exclude_string) + 1);
411 strcpy (new_exclude->string, exclude_string);
412 new_exclude->type = type;
413 new_exclude->next = excludes;
414 excludes = new_exclude;
417 free (local_copy);
421 /* abfd is a bfd containing n (or NULL)
422 It can be used for contextual checks. */
424 static int
425 auto_export (bfd *abfd, def_file *d, const char *n)
427 int i;
428 struct exclude_list_struct *ex;
429 autofilter_entry_type *afptr;
430 const char * libname = 0;
431 if (abfd && abfd->my_archive)
432 libname = lbasename (abfd->my_archive->filename);
434 /* We should not re-export imported stuff. */
435 if (strncmp (n, "_imp_", 5) == 0)
436 return 0;
438 for (i = 0; i < d->num_exports; i++)
439 if (strcmp (d->exports[i].name, n) == 0)
440 return 0;
442 if (pe_dll_do_default_excludes)
444 const char * p;
445 int len;
447 if (pe_dll_extra_pe_debug)
448 printf ("considering exporting: %s, abfd=%p, abfd->my_arc=%p\n",
449 n, abfd, abfd->my_archive);
451 /* First of all, make context checks:
452 Don't export anything from standard libs. */
453 if (libname)
455 afptr = autofilter_liblist;
457 while (afptr->name)
459 if (strncmp (libname, afptr->name, afptr->len) == 0 )
460 return 0;
461 afptr++;
465 /* Next, exclude symbols from certain startup objects. */
467 if (abfd && (p = lbasename (abfd->filename)))
469 afptr = autofilter_objlist;
470 while (afptr->name)
472 if (strcmp (p, afptr->name) == 0)
473 return 0;
474 afptr++;
478 /* Don't try to blindly exclude all symbols
479 that begin with '__'; this was tried and
480 it is too restrictive. Instead we have
481 a target specific list to use: */
482 afptr = pe_details->autofilter_symbollist;
483 while (afptr->name)
485 if (strcmp (n, afptr->name) == 0)
486 return 0;
488 afptr++;
491 /* Next, exclude symbols starting with ... */
492 afptr = autofilter_symbolprefixlist;
493 while (afptr->name)
495 if (strncmp (n, afptr->name, afptr->len) == 0)
496 return 0;
498 afptr++;
501 /* Finally, exclude symbols ending with ... */
502 len = strlen (n);
503 afptr = autofilter_symbolsuffixlist;
504 while (afptr->name)
506 if ((len >= afptr->len)
507 /* Add 1 to insure match with trailing '\0'. */
508 && strncmp (n + len - afptr->len, afptr->name,
509 afptr->len + 1) == 0)
510 return 0;
512 afptr++;
516 for (ex = excludes; ex; ex = ex->next)
518 if (ex->type == 1) /* exclude-libs */
520 if (libname
521 && ((strcmp (libname, ex->string) == 0)
522 || (strcasecmp ("ALL", ex->string) == 0)))
523 return 0;
525 else if (strcmp (n, ex->string) == 0)
526 return 0;
529 return 1;
532 static void
533 process_def_file (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
535 int i, j;
536 struct bfd_link_hash_entry *blhe;
537 bfd *b;
538 struct bfd_section *s;
539 def_file_export *e = 0;
541 if (!pe_def_file)
542 pe_def_file = def_file_empty ();
544 /* First, run around to all the objects looking for the .drectve
545 sections, and push those into the def file too. */
546 for (b = info->input_bfds; b; b = b->link_next)
548 s = bfd_get_section_by_name (b, ".drectve");
549 if (s)
551 long size = s->size;
552 char *buf = xmalloc (size);
554 bfd_get_section_contents (b, s, buf, 0, size);
555 def_file_add_directive (pe_def_file, buf, size);
556 free (buf);
560 /* If we are not building a DLL, when there are no exports
561 we do not build an export table at all. */
562 if (!pe_dll_export_everything && pe_def_file->num_exports == 0
563 && info->executable)
564 return;
566 /* Now, maybe export everything else the default way. */
567 if (pe_dll_export_everything || pe_def_file->num_exports == 0)
569 for (b = info->input_bfds; b; b = b->link_next)
571 asymbol **symbols;
572 int nsyms, symsize;
574 symsize = bfd_get_symtab_upper_bound (b);
575 symbols = xmalloc (symsize);
576 nsyms = bfd_canonicalize_symtab (b, symbols);
578 for (j = 0; j < nsyms; j++)
580 /* We should export symbols which are either global or not
581 anything at all. (.bss data is the latter)
582 We should not export undefined symbols. */
583 if (symbols[j]->section != &bfd_und_section
584 && ((symbols[j]->flags & BSF_GLOBAL)
585 || (symbols[j]->flags == BFD_FORT_COMM_DEFAULT_VALUE)))
587 const char *sn = symbols[j]->name;
589 /* We should not re-export imported stuff. */
591 char *name = xmalloc (strlen (sn) + 2 + 6);
592 sprintf (name, "%s%s", U("_imp_"), sn);
594 blhe = bfd_link_hash_lookup (info->hash, name,
595 FALSE, FALSE, FALSE);
596 free (name);
598 if (blhe && blhe->type == bfd_link_hash_defined)
599 continue;
602 if (*sn == '_')
603 sn++;
605 if (auto_export (b, pe_def_file, sn))
607 def_file_export *p;
608 p=def_file_add_export (pe_def_file, sn, 0, -1);
609 /* Fill data flag properly, from dlltool.c. */
610 p->flag_data = !(symbols[j]->flags & BSF_FUNCTION);
617 #undef NE
618 #define NE pe_def_file->num_exports
620 /* Canonicalize the export list. */
621 if (pe_dll_kill_ats)
623 for (i = 0; i < NE; i++)
625 if (strchr (pe_def_file->exports[i].name, '@'))
627 /* This will preserve internal_name, which may have been
628 pointing to the same memory as name, or might not
629 have. */
630 int lead_at = (*pe_def_file->exports[i].name == '@');
631 char *tmp = xstrdup (pe_def_file->exports[i].name + lead_at);
632 char *tmp_at = strchr (tmp, '@');
634 if (tmp_at)
635 *tmp_at = 0;
636 else
637 einfo (_("%XCannot export %s: invalid export name\n"),
638 pe_def_file->exports[i].name);
639 pe_def_file->exports[i].name = tmp;
644 if (pe_dll_stdcall_aliases)
646 for (i = 0; i < NE; i++)
648 if (strchr (pe_def_file->exports[i].name, '@'))
650 int lead_at = (*pe_def_file->exports[i].name == '@');
651 char *tmp = xstrdup (pe_def_file->exports[i].name + lead_at);
653 *(strchr (tmp, '@')) = 0;
654 if (auto_export (NULL, pe_def_file, tmp))
655 def_file_add_export (pe_def_file, tmp,
656 pe_def_file->exports[i].internal_name,
657 -1);
658 else
659 free (tmp);
664 /* Convenience, but watch out for it changing. */
665 e = pe_def_file->exports;
667 exported_symbol_offsets = xmalloc (NE * sizeof (bfd_vma));
668 exported_symbol_sections = xmalloc (NE * sizeof (struct bfd_section *));
670 memset (exported_symbol_sections, 0, NE * sizeof (struct bfd_section *));
671 max_ordinal = 0;
672 min_ordinal = 65536;
673 count_exported = 0;
674 count_exported_byname = 0;
675 count_with_ordinals = 0;
677 qsort (pe_def_file->exports, NE, sizeof (pe_def_file->exports[0]),
678 pe_export_sort);
679 for (i = 0, j = 0; i < NE; i++)
681 if (i > 0 && strcmp (e[i].name, e[i - 1].name) == 0)
683 /* This is a duplicate. */
684 if (e[j - 1].ordinal != -1
685 && e[i].ordinal != -1
686 && e[j - 1].ordinal != e[i].ordinal)
688 if (pe_dll_warn_dup_exports)
689 /* xgettext:c-format */
690 einfo (_("%XError, duplicate EXPORT with ordinals: %s (%d vs %d)\n"),
691 e[j - 1].name, e[j - 1].ordinal, e[i].ordinal);
693 else
695 if (pe_dll_warn_dup_exports)
696 /* xgettext:c-format */
697 einfo (_("Warning, duplicate EXPORT: %s\n"),
698 e[j - 1].name);
701 if (e[i].ordinal != -1)
702 e[j - 1].ordinal = e[i].ordinal;
703 e[j - 1].flag_private |= e[i].flag_private;
704 e[j - 1].flag_constant |= e[i].flag_constant;
705 e[j - 1].flag_noname |= e[i].flag_noname;
706 e[j - 1].flag_data |= e[i].flag_data;
708 else
710 if (i != j)
711 e[j] = e[i];
712 j++;
715 pe_def_file->num_exports = j; /* == NE */
717 for (i = 0; i < NE; i++)
719 char *name;
721 /* Check for forward exports */
722 if (strchr (pe_def_file->exports[i].internal_name, '.'))
724 count_exported++;
725 if (!pe_def_file->exports[i].flag_noname)
726 count_exported_byname++;
728 pe_def_file->exports[i].flag_forward = 1;
730 if (pe_def_file->exports[i].ordinal != -1)
732 if (max_ordinal < pe_def_file->exports[i].ordinal)
733 max_ordinal = pe_def_file->exports[i].ordinal;
734 if (min_ordinal > pe_def_file->exports[i].ordinal)
735 min_ordinal = pe_def_file->exports[i].ordinal;
736 count_with_ordinals++;
739 continue;
742 name = xmalloc (strlen (pe_def_file->exports[i].internal_name) + 2);
743 if (pe_details->underscored
744 && (*pe_def_file->exports[i].internal_name != '@'))
746 *name = '_';
747 strcpy (name + 1, pe_def_file->exports[i].internal_name);
749 else
750 strcpy (name, pe_def_file->exports[i].internal_name);
752 blhe = bfd_link_hash_lookup (info->hash,
753 name,
754 FALSE, FALSE, TRUE);
756 if (blhe
757 && (blhe->type == bfd_link_hash_defined
758 || (blhe->type == bfd_link_hash_common)))
760 count_exported++;
761 if (!pe_def_file->exports[i].flag_noname)
762 count_exported_byname++;
764 /* Only fill in the sections. The actual offsets are computed
765 in fill_exported_offsets() after common symbols are laid
766 out. */
767 if (blhe->type == bfd_link_hash_defined)
768 exported_symbol_sections[i] = blhe->u.def.section;
769 else
770 exported_symbol_sections[i] = blhe->u.c.p->section;
772 if (pe_def_file->exports[i].ordinal != -1)
774 if (max_ordinal < pe_def_file->exports[i].ordinal)
775 max_ordinal = pe_def_file->exports[i].ordinal;
776 if (min_ordinal > pe_def_file->exports[i].ordinal)
777 min_ordinal = pe_def_file->exports[i].ordinal;
778 count_with_ordinals++;
781 else if (blhe && blhe->type == bfd_link_hash_undefined)
783 /* xgettext:c-format */
784 einfo (_("%XCannot export %s: symbol not defined\n"),
785 pe_def_file->exports[i].internal_name);
787 else if (blhe)
789 /* xgettext:c-format */
790 einfo (_("%XCannot export %s: symbol wrong type (%d vs %d)\n"),
791 pe_def_file->exports[i].internal_name,
792 blhe->type, bfd_link_hash_defined);
794 else
796 /* xgettext:c-format */
797 einfo (_("%XCannot export %s: symbol not found\n"),
798 pe_def_file->exports[i].internal_name);
800 free (name);
804 /* Build the bfd that will contain .edata and .reloc sections. */
806 static void
807 build_filler_bfd (int include_edata)
809 lang_input_statement_type *filler_file;
810 filler_file = lang_add_input_file ("dll stuff",
811 lang_input_file_is_fake_enum,
812 NULL);
813 filler_file->the_bfd = filler_bfd = bfd_create ("dll stuff", output_bfd);
814 if (filler_bfd == NULL
815 || !bfd_set_arch_mach (filler_bfd,
816 bfd_get_arch (output_bfd),
817 bfd_get_mach (output_bfd)))
819 einfo ("%X%P: can not create BFD: %E\n");
820 return;
823 if (include_edata)
825 edata_s = bfd_make_section_old_way (filler_bfd, ".edata");
826 if (edata_s == NULL
827 || !bfd_set_section_flags (filler_bfd, edata_s,
828 (SEC_HAS_CONTENTS
829 | SEC_ALLOC
830 | SEC_LOAD
831 | SEC_KEEP
832 | SEC_IN_MEMORY)))
834 einfo ("%X%P: can not create .edata section: %E\n");
835 return;
837 bfd_set_section_size (filler_bfd, edata_s, edata_sz);
840 reloc_s = bfd_make_section_old_way (filler_bfd, ".reloc");
841 if (reloc_s == NULL
842 || !bfd_set_section_flags (filler_bfd, reloc_s,
843 (SEC_HAS_CONTENTS
844 | SEC_ALLOC
845 | SEC_LOAD
846 | SEC_KEEP
847 | SEC_IN_MEMORY)))
849 einfo ("%X%P: can not create .reloc section: %E\n");
850 return;
853 bfd_set_section_size (filler_bfd, reloc_s, 0);
855 ldlang_add_file (filler_file);
858 /* Gather all the exported symbols and build the .edata section. */
860 static void
861 generate_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
863 int i, next_ordinal;
864 int name_table_size = 0;
865 const char *dlnp;
867 /* First, we need to know how many exported symbols there are,
868 and what the range of ordinals is. */
869 if (pe_def_file->name)
870 dll_name = pe_def_file->name;
871 else
873 dll_name = abfd->filename;
875 for (dlnp = dll_name; *dlnp; dlnp++)
876 if (*dlnp == '\\' || *dlnp == '/' || *dlnp == ':')
877 dll_name = dlnp + 1;
880 if (count_with_ordinals && max_ordinal > count_exported)
882 if (min_ordinal > max_ordinal - count_exported + 1)
883 min_ordinal = max_ordinal - count_exported + 1;
885 else
887 min_ordinal = 1;
888 max_ordinal = count_exported;
891 export_table_size = max_ordinal - min_ordinal + 1;
892 exported_symbols = xmalloc (export_table_size * sizeof (int));
893 for (i = 0; i < export_table_size; i++)
894 exported_symbols[i] = -1;
896 /* Now we need to assign ordinals to those that don't have them. */
897 for (i = 0; i < NE; i++)
899 if (exported_symbol_sections[i] ||
900 pe_def_file->exports[i].flag_forward)
902 if (pe_def_file->exports[i].ordinal != -1)
904 int ei = pe_def_file->exports[i].ordinal - min_ordinal;
905 int pi = exported_symbols[ei];
907 if (pi != -1)
909 /* xgettext:c-format */
910 einfo (_("%XError, ordinal used twice: %d (%s vs %s)\n"),
911 pe_def_file->exports[i].ordinal,
912 pe_def_file->exports[i].name,
913 pe_def_file->exports[pi].name);
915 exported_symbols[ei] = i;
917 name_table_size += strlen (pe_def_file->exports[i].name) + 1;
920 /* Reserve space for the forward name. */
921 if (pe_def_file->exports[i].flag_forward)
923 name_table_size += strlen (pe_def_file->exports[i].internal_name) + 1;
927 next_ordinal = min_ordinal;
928 for (i = 0; i < NE; i++)
929 if ((exported_symbol_sections[i] ||
930 pe_def_file->exports[i].flag_forward) &&
931 pe_def_file->exports[i].ordinal == -1)
933 while (exported_symbols[next_ordinal - min_ordinal] != -1)
934 next_ordinal++;
936 exported_symbols[next_ordinal - min_ordinal] = i;
937 pe_def_file->exports[i].ordinal = next_ordinal;
940 /* OK, now we can allocate some memory. */
941 edata_sz = (40 /* directory */
942 + 4 * export_table_size /* addresses */
943 + 4 * count_exported_byname /* name ptrs */
944 + 2 * count_exported_byname /* ordinals */
945 + name_table_size + strlen (dll_name) + 1);
948 /* Fill the exported symbol offsets. The preliminary work has already
949 been done in process_def_file(). */
951 static void
952 fill_exported_offsets (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
954 int i;
955 struct bfd_link_hash_entry *blhe;
957 for (i = 0; i < pe_def_file->num_exports; i++)
959 char *name;
961 name = xmalloc (strlen (pe_def_file->exports[i].internal_name) + 2);
962 if (pe_details->underscored
963 && *pe_def_file->exports[i].internal_name != '@')
965 *name = '_';
966 strcpy (name + 1, pe_def_file->exports[i].internal_name);
968 else
969 strcpy (name, pe_def_file->exports[i].internal_name);
971 blhe = bfd_link_hash_lookup (info->hash,
972 name,
973 FALSE, FALSE, TRUE);
975 if (blhe && blhe->type == bfd_link_hash_defined)
976 exported_symbol_offsets[i] = blhe->u.def.value;
978 free (name);
982 static void
983 fill_edata (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
985 int s, hint;
986 unsigned char *edirectory;
987 unsigned char *eaddresses;
988 unsigned char *enameptrs;
989 unsigned char *eordinals;
990 char *enamestr;
991 time_t now;
993 time (&now);
995 edata_d = xmalloc (edata_sz);
997 /* Note use of array pointer math here. */
998 edirectory = edata_d;
999 eaddresses = edata_d + 40;
1000 enameptrs = eaddresses + 4 * export_table_size;
1001 eordinals = enameptrs + 4 * count_exported_byname;
1002 enamestr = (char *) eordinals + 2 * count_exported_byname;
1004 #define ERVA(ptr) (((unsigned char *)(ptr) - edata_d) \
1005 + edata_s->output_section->vma - image_base)
1007 memset (edata_d, 0, edata_sz);
1008 bfd_put_32 (abfd, now, edata_d + 4);
1009 if (pe_def_file->version_major != -1)
1011 bfd_put_16 (abfd, pe_def_file->version_major, edata_d + 8);
1012 bfd_put_16 (abfd, pe_def_file->version_minor, edata_d + 10);
1015 bfd_put_32 (abfd, ERVA (enamestr), edata_d + 12);
1016 strcpy (enamestr, dll_name);
1017 enamestr += strlen (enamestr) + 1;
1018 bfd_put_32 (abfd, min_ordinal, edata_d + 16);
1019 bfd_put_32 (abfd, export_table_size, edata_d + 20);
1020 bfd_put_32 (abfd, count_exported_byname, edata_d + 24);
1021 bfd_put_32 (abfd, ERVA (eaddresses), edata_d + 28);
1022 bfd_put_32 (abfd, ERVA (enameptrs), edata_d + 32);
1023 bfd_put_32 (abfd, ERVA (eordinals), edata_d + 36);
1025 fill_exported_offsets (abfd, info);
1027 /* Ok, now for the filling in part.
1028 Scan alphabetically - ie the ordering in the exports[] table,
1029 rather than by ordinal - the ordering in the exported_symbol[]
1030 table. See dlltool.c and:
1031 http://sources.redhat.com/ml/binutils/2003-04/msg00379.html
1032 for more information. */
1033 hint = 0;
1034 for (s = 0; s < NE; s++)
1036 struct bfd_section *ssec = exported_symbol_sections[s];
1037 if (pe_def_file->exports[s].ordinal != -1 &&
1038 (pe_def_file->exports[s].flag_forward || ssec != NULL))
1040 int ord = pe_def_file->exports[s].ordinal;
1042 if (pe_def_file->exports[s].flag_forward)
1044 bfd_put_32 (abfd, ERVA (enamestr),
1045 eaddresses + 4 * (ord - min_ordinal));
1047 strcpy (enamestr, pe_def_file->exports[s].internal_name);
1048 enamestr += strlen (pe_def_file->exports[s].internal_name) + 1;
1050 else
1052 unsigned long srva = (exported_symbol_offsets[s]
1053 + ssec->output_section->vma
1054 + ssec->output_offset);
1056 bfd_put_32 (abfd, srva - image_base,
1057 eaddresses + 4 * (ord - min_ordinal));
1060 if (!pe_def_file->exports[s].flag_noname)
1062 char *ename = pe_def_file->exports[s].name;
1064 bfd_put_32 (abfd, ERVA (enamestr), enameptrs);
1065 enameptrs += 4;
1066 strcpy (enamestr, ename);
1067 enamestr += strlen (enamestr) + 1;
1068 bfd_put_16 (abfd, ord - min_ordinal, eordinals);
1069 eordinals += 2;
1070 pe_def_file->exports[s].hint = hint++;
1077 static struct bfd_section *current_sec;
1079 void
1080 pe_walk_relocs_of_symbol (struct bfd_link_info *info,
1081 const char *name,
1082 int (*cb) (arelent *, asection *))
1084 bfd *b;
1085 asection *s;
1087 for (b = info->input_bfds; b; b = b->link_next)
1089 asymbol **symbols;
1090 int nsyms, symsize;
1092 symsize = bfd_get_symtab_upper_bound (b);
1093 symbols = xmalloc (symsize);
1094 nsyms = bfd_canonicalize_symtab (b, symbols);
1096 for (s = b->sections; s; s = s->next)
1098 arelent **relocs;
1099 int relsize, nrelocs, i;
1100 int flags = bfd_get_section_flags (b, s);
1102 /* Skip discarded linkonce sections. */
1103 if (flags & SEC_LINK_ONCE
1104 && s->output_section == bfd_abs_section_ptr)
1105 continue;
1107 current_sec = s;
1109 relsize = bfd_get_reloc_upper_bound (b, s);
1110 relocs = xmalloc (relsize);
1111 nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1113 for (i = 0; i < nrelocs; i++)
1115 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1117 if (!strcmp (name, sym->name))
1118 cb (relocs[i], s);
1121 free (relocs);
1123 /* Warning: the allocated symbols are remembered in BFD and reused
1124 later, so don't free them! */
1125 /* free (symbols); */
1130 /* Gather all the relocations and build the .reloc section. */
1132 static void
1133 generate_reloc (bfd *abfd, struct bfd_link_info *info)
1136 /* For .reloc stuff. */
1137 reloc_data_type *reloc_data;
1138 int total_relocs = 0;
1139 int i;
1140 unsigned long sec_page = (unsigned long) -1;
1141 unsigned long page_ptr, page_count;
1142 int bi;
1143 bfd *b;
1144 struct bfd_section *s;
1146 total_relocs = 0;
1147 for (b = info->input_bfds; b; b = b->link_next)
1148 for (s = b->sections; s; s = s->next)
1149 total_relocs += s->reloc_count;
1151 reloc_data = xmalloc (total_relocs * sizeof (reloc_data_type));
1153 total_relocs = 0;
1154 bi = 0;
1155 for (bi = 0, b = info->input_bfds; b; bi++, b = b->link_next)
1157 arelent **relocs;
1158 int relsize, nrelocs, i;
1160 for (s = b->sections; s; s = s->next)
1162 unsigned long sec_vma = s->output_section->vma + s->output_offset;
1163 asymbol **symbols;
1164 int nsyms, symsize;
1166 /* If it's not loaded, we don't need to relocate it this way. */
1167 if (!(s->output_section->flags & SEC_LOAD))
1168 continue;
1170 /* I don't know why there would be a reloc for these, but I've
1171 seen it happen - DJ */
1172 if (s->output_section == &bfd_abs_section)
1173 continue;
1175 if (s->output_section->vma == 0)
1177 /* Huh? Shouldn't happen, but punt if it does. */
1178 einfo ("DJ: zero vma section reloc detected: `%s' #%d f=%d\n",
1179 s->output_section->name, s->output_section->index,
1180 s->output_section->flags);
1181 continue;
1184 symsize = bfd_get_symtab_upper_bound (b);
1185 symbols = xmalloc (symsize);
1186 nsyms = bfd_canonicalize_symtab (b, symbols);
1188 relsize = bfd_get_reloc_upper_bound (b, s);
1189 relocs = xmalloc (relsize);
1190 nrelocs = bfd_canonicalize_reloc (b, s, relocs, symbols);
1192 for (i = 0; i < nrelocs; i++)
1194 if (pe_dll_extra_pe_debug)
1196 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1197 printf ("rel: %s\n", sym->name);
1199 if (!relocs[i]->howto->pc_relative
1200 && relocs[i]->howto->type != pe_details->imagebase_reloc)
1202 bfd_vma sym_vma;
1203 struct bfd_symbol *sym = *relocs[i]->sym_ptr_ptr;
1205 sym_vma = (relocs[i]->addend
1206 + sym->value
1207 + sym->section->vma
1208 + sym->section->output_offset
1209 + sym->section->output_section->vma);
1210 reloc_data[total_relocs].vma = sec_vma + relocs[i]->address;
1212 #define BITS_AND_SHIFT(bits, shift) (bits * 1000 | shift)
1214 switch BITS_AND_SHIFT (relocs[i]->howto->bitsize,
1215 relocs[i]->howto->rightshift)
1217 case BITS_AND_SHIFT (32, 0):
1218 reloc_data[total_relocs].type = 3;
1219 total_relocs++;
1220 break;
1221 case BITS_AND_SHIFT (16, 0):
1222 reloc_data[total_relocs].type = 2;
1223 total_relocs++;
1224 break;
1225 case BITS_AND_SHIFT (16, 16):
1226 reloc_data[total_relocs].type = 4;
1227 /* FIXME: we can't know the symbol's right value
1228 yet, but we probably can safely assume that
1229 CE will relocate us in 64k blocks, so leaving
1230 it zero is safe. */
1231 reloc_data[total_relocs].extra = 0;
1232 total_relocs++;
1233 break;
1234 case BITS_AND_SHIFT (26, 2):
1235 reloc_data[total_relocs].type = 5;
1236 total_relocs++;
1237 break;
1238 case BITS_AND_SHIFT (24, 2):
1239 /* FIXME: 0 is ARM_26D, it is defined in bfd/coff-arm.c
1240 Those ARM_xxx definitions should go in proper
1241 header someday. */
1242 if (relocs[i]->howto->type == 0
1243 /* Older GNU linkers used 5 instead of 0 for this reloc. */
1244 || relocs[i]->howto->type == 5)
1245 /* This is an ARM_26D reloc, which is an ARM_26 reloc
1246 that has already been fully processed during a
1247 previous link stage, so ignore it here. */
1248 break;
1249 /* Fall through. */
1250 default:
1251 /* xgettext:c-format */
1252 einfo (_("%XError: %d-bit reloc in dll\n"),
1253 relocs[i]->howto->bitsize);
1254 break;
1258 free (relocs);
1259 /* Warning: the allocated symbols are remembered in BFD and
1260 reused later, so don't free them! */
1264 /* At this point, we have total_relocs relocation addresses in
1265 reloc_addresses, which are all suitable for the .reloc section.
1266 We must now create the new sections. */
1267 qsort (reloc_data, total_relocs, sizeof (*reloc_data), reloc_sort);
1269 for (i = 0; i < total_relocs; i++)
1271 unsigned long this_page = (reloc_data[i].vma >> 12);
1273 if (this_page != sec_page)
1275 reloc_sz = (reloc_sz + 3) & ~3; /* 4-byte align. */
1276 reloc_sz += 8;
1277 sec_page = this_page;
1280 reloc_sz += 2;
1282 if (reloc_data[i].type == 4)
1283 reloc_sz += 2;
1286 reloc_sz = (reloc_sz + 3) & ~3; /* 4-byte align. */
1287 reloc_d = xmalloc (reloc_sz);
1288 sec_page = (unsigned long) -1;
1289 reloc_sz = 0;
1290 page_ptr = (unsigned long) -1;
1291 page_count = 0;
1293 for (i = 0; i < total_relocs; i++)
1295 unsigned long rva = reloc_data[i].vma - image_base;
1296 unsigned long this_page = (rva & ~0xfff);
1298 if (this_page != sec_page)
1300 while (reloc_sz & 3)
1301 reloc_d[reloc_sz++] = 0;
1303 if (page_ptr != (unsigned long) -1)
1304 bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
1306 bfd_put_32 (abfd, this_page, reloc_d + reloc_sz);
1307 page_ptr = reloc_sz;
1308 reloc_sz += 8;
1309 sec_page = this_page;
1310 page_count = 0;
1313 bfd_put_16 (abfd, (rva & 0xfff) + (reloc_data[i].type << 12),
1314 reloc_d + reloc_sz);
1315 reloc_sz += 2;
1317 if (reloc_data[i].type == 4)
1319 bfd_put_16 (abfd, reloc_data[i].extra, reloc_d + reloc_sz);
1320 reloc_sz += 2;
1323 page_count++;
1326 while (reloc_sz & 3)
1327 reloc_d[reloc_sz++] = 0;
1329 if (page_ptr != (unsigned long) -1)
1330 bfd_put_32 (abfd, reloc_sz - page_ptr, reloc_d + page_ptr + 4);
1332 while (reloc_sz < reloc_s->size)
1333 reloc_d[reloc_sz++] = 0;
1336 /* Given the exiting def_file structure, print out a .DEF file that
1337 corresponds to it. */
1339 static void
1340 quoteput (char *s, FILE *f, int needs_quotes)
1342 char *cp;
1344 for (cp = s; *cp; cp++)
1345 if (*cp == '\''
1346 || *cp == '"'
1347 || *cp == '\\'
1348 || ISSPACE (*cp)
1349 || *cp == ','
1350 || *cp == ';')
1351 needs_quotes = 1;
1353 if (needs_quotes)
1355 putc ('"', f);
1357 while (*s)
1359 if (*s == '"' || *s == '\\')
1360 putc ('\\', f);
1362 putc (*s, f);
1363 s++;
1366 putc ('"', f);
1368 else
1369 fputs (s, f);
1372 void
1373 pe_dll_generate_def_file (const char *pe_out_def_filename)
1375 int i;
1376 FILE *out = fopen (pe_out_def_filename, "w");
1378 if (out == NULL)
1379 /* xgettext:c-format */
1380 einfo (_("%s: Can't open output def file %s\n"),
1381 program_name, pe_out_def_filename);
1383 if (pe_def_file)
1385 if (pe_def_file->name)
1387 if (pe_def_file->is_dll)
1388 fprintf (out, "LIBRARY ");
1389 else
1390 fprintf (out, "NAME ");
1392 quoteput (pe_def_file->name, out, 1);
1394 if (pe_data (output_bfd)->pe_opthdr.ImageBase)
1395 fprintf (out, " BASE=0x%lx",
1396 (unsigned long) pe_data (output_bfd)->pe_opthdr.ImageBase);
1397 fprintf (out, "\n");
1400 if (pe_def_file->description)
1402 fprintf (out, "DESCRIPTION ");
1403 quoteput (pe_def_file->description, out, 1);
1404 fprintf (out, "\n");
1407 if (pe_def_file->version_minor != -1)
1408 fprintf (out, "VERSION %d.%d\n", pe_def_file->version_major,
1409 pe_def_file->version_minor);
1410 else if (pe_def_file->version_major != -1)
1411 fprintf (out, "VERSION %d\n", pe_def_file->version_major);
1413 if (pe_def_file->stack_reserve != -1 || pe_def_file->heap_reserve != -1)
1414 fprintf (out, "\n");
1416 if (pe_def_file->stack_commit != -1)
1417 fprintf (out, "STACKSIZE 0x%x,0x%x\n",
1418 pe_def_file->stack_reserve, pe_def_file->stack_commit);
1419 else if (pe_def_file->stack_reserve != -1)
1420 fprintf (out, "STACKSIZE 0x%x\n", pe_def_file->stack_reserve);
1422 if (pe_def_file->heap_commit != -1)
1423 fprintf (out, "HEAPSIZE 0x%x,0x%x\n",
1424 pe_def_file->heap_reserve, pe_def_file->heap_commit);
1425 else if (pe_def_file->heap_reserve != -1)
1426 fprintf (out, "HEAPSIZE 0x%x\n", pe_def_file->heap_reserve);
1428 if (pe_def_file->num_section_defs > 0)
1430 fprintf (out, "\nSECTIONS\n\n");
1432 for (i = 0; i < pe_def_file->num_section_defs; i++)
1434 fprintf (out, " ");
1435 quoteput (pe_def_file->section_defs[i].name, out, 0);
1437 if (pe_def_file->section_defs[i].class)
1439 fprintf (out, " CLASS ");
1440 quoteput (pe_def_file->section_defs[i].class, out, 0);
1443 if (pe_def_file->section_defs[i].flag_read)
1444 fprintf (out, " READ");
1446 if (pe_def_file->section_defs[i].flag_write)
1447 fprintf (out, " WRITE");
1449 if (pe_def_file->section_defs[i].flag_execute)
1450 fprintf (out, " EXECUTE");
1452 if (pe_def_file->section_defs[i].flag_shared)
1453 fprintf (out, " SHARED");
1455 fprintf (out, "\n");
1459 if (pe_def_file->num_exports > 0)
1461 fprintf (out, "EXPORTS\n");
1463 for (i = 0; i < pe_def_file->num_exports; i++)
1465 def_file_export *e = pe_def_file->exports + i;
1466 fprintf (out, " ");
1467 quoteput (e->name, out, 0);
1469 if (e->internal_name && strcmp (e->internal_name, e->name))
1471 fprintf (out, " = ");
1472 quoteput (e->internal_name, out, 0);
1475 if (e->ordinal != -1)
1476 fprintf (out, " @%d", e->ordinal);
1478 if (e->flag_private)
1479 fprintf (out, " PRIVATE");
1481 if (e->flag_constant)
1482 fprintf (out, " CONSTANT");
1484 if (e->flag_noname)
1485 fprintf (out, " NONAME");
1487 if (e->flag_data)
1488 fprintf (out, " DATA");
1490 fprintf (out, "\n");
1494 if (pe_def_file->num_imports > 0)
1496 fprintf (out, "\nIMPORTS\n\n");
1498 for (i = 0; i < pe_def_file->num_imports; i++)
1500 def_file_import *im = pe_def_file->imports + i;
1501 fprintf (out, " ");
1503 if (im->internal_name
1504 && (!im->name || strcmp (im->internal_name, im->name)))
1506 quoteput (im->internal_name, out, 0);
1507 fprintf (out, " = ");
1510 quoteput (im->module->name, out, 0);
1511 fprintf (out, ".");
1513 if (im->name)
1514 quoteput (im->name, out, 0);
1515 else
1516 fprintf (out, "%d", im->ordinal);
1518 fprintf (out, "\n");
1522 else
1523 fprintf (out, _("; no contents available\n"));
1525 if (fclose (out) == EOF)
1526 /* xgettext:c-format */
1527 einfo (_("%P: Error closing file `%s'\n"), pe_out_def_filename);
1530 /* Generate the import library. */
1532 static asymbol **symtab;
1533 static int symptr;
1534 static int tmp_seq;
1535 static const char *dll_filename;
1536 static char *dll_symname;
1538 #define UNDSEC (asection *) &bfd_und_section
1540 static asection *
1541 quick_section (bfd *abfd, const char *name, int flags, int align)
1543 asection *sec;
1544 asymbol *sym;
1546 sec = bfd_make_section_old_way (abfd, name);
1547 bfd_set_section_flags (abfd, sec, flags | SEC_ALLOC | SEC_LOAD | SEC_KEEP);
1548 bfd_set_section_alignment (abfd, sec, align);
1549 /* Remember to undo this before trying to link internally! */
1550 sec->output_section = sec;
1552 sym = bfd_make_empty_symbol (abfd);
1553 symtab[symptr++] = sym;
1554 sym->name = sec->name;
1555 sym->section = sec;
1556 sym->flags = BSF_LOCAL;
1557 sym->value = 0;
1559 return sec;
1562 static void
1563 quick_symbol (bfd *abfd,
1564 const char *n1,
1565 const char *n2,
1566 const char *n3,
1567 asection *sec,
1568 int flags,
1569 int addr)
1571 asymbol *sym;
1572 char *name = xmalloc (strlen (n1) + strlen (n2) + strlen (n3) + 1);
1574 strcpy (name, n1);
1575 strcat (name, n2);
1576 strcat (name, n3);
1577 sym = bfd_make_empty_symbol (abfd);
1578 sym->name = name;
1579 sym->section = sec;
1580 sym->flags = flags;
1581 sym->value = addr;
1582 symtab[symptr++] = sym;
1585 static arelent *reltab = 0;
1586 static int relcount = 0, relsize = 0;
1588 static void
1589 quick_reloc (bfd *abfd, int address, int which_howto, int symidx)
1591 if (relcount >= relsize - 1)
1593 relsize += 10;
1594 if (reltab)
1595 reltab = xrealloc (reltab, relsize * sizeof (arelent));
1596 else
1597 reltab = xmalloc (relsize * sizeof (arelent));
1599 reltab[relcount].address = address;
1600 reltab[relcount].addend = 0;
1601 reltab[relcount].howto = bfd_reloc_type_lookup (abfd, which_howto);
1602 reltab[relcount].sym_ptr_ptr = symtab + symidx;
1603 relcount++;
1606 static void
1607 save_relocs (asection *sec)
1609 int i;
1611 sec->relocation = reltab;
1612 sec->reloc_count = relcount;
1613 sec->orelocation = xmalloc ((relcount + 1) * sizeof (arelent *));
1614 for (i = 0; i < relcount; i++)
1615 sec->orelocation[i] = sec->relocation + i;
1616 sec->orelocation[relcount] = 0;
1617 sec->flags |= SEC_RELOC;
1618 reltab = 0;
1619 relcount = relsize = 0;
1622 /* .section .idata$2
1623 .global __head_my_dll
1624 __head_my_dll:
1625 .rva hname
1626 .long 0
1627 .long 0
1628 .rva __my_dll_iname
1629 .rva fthunk
1631 .section .idata$5
1632 .long 0
1633 fthunk:
1635 .section .idata$4
1636 .long 0
1637 hname: */
1639 static bfd *
1640 make_head (bfd *parent)
1642 asection *id2, *id5, *id4;
1643 unsigned char *d2, *d5, *d4;
1644 char *oname;
1645 bfd *abfd;
1647 oname = xmalloc (20);
1648 sprintf (oname, "d%06d.o", tmp_seq);
1649 tmp_seq++;
1651 abfd = bfd_create (oname, parent);
1652 bfd_find_target (pe_details->object_target, abfd);
1653 bfd_make_writable (abfd);
1655 bfd_set_format (abfd, bfd_object);
1656 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1658 symptr = 0;
1659 symtab = xmalloc (6 * sizeof (asymbol *));
1660 id2 = quick_section (abfd, ".idata$2", SEC_HAS_CONTENTS, 2);
1661 id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1662 id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1663 quick_symbol (abfd, U ("_head_"), dll_symname, "", id2, BSF_GLOBAL, 0);
1664 quick_symbol (abfd, U (""), dll_symname, "_iname", UNDSEC, BSF_GLOBAL, 0);
1666 /* OK, pay attention here. I got confused myself looking back at
1667 it. We create a four-byte section to mark the beginning of the
1668 list, and we include an offset of 4 in the section, so that the
1669 pointer to the list points to the *end* of this section, which is
1670 the start of the list of sections from other objects. */
1672 bfd_set_section_size (abfd, id2, 20);
1673 d2 = xmalloc (20);
1674 id2->contents = d2;
1675 memset (d2, 0, 20);
1676 d2[0] = d2[16] = 4; /* Reloc addend. */
1677 quick_reloc (abfd, 0, BFD_RELOC_RVA, 2);
1678 quick_reloc (abfd, 12, BFD_RELOC_RVA, 4);
1679 quick_reloc (abfd, 16, BFD_RELOC_RVA, 1);
1680 save_relocs (id2);
1682 bfd_set_section_size (abfd, id5, 4);
1683 d5 = xmalloc (4);
1684 id5->contents = d5;
1685 memset (d5, 0, 4);
1687 bfd_set_section_size (abfd, id4, 4);
1688 d4 = xmalloc (4);
1689 id4->contents = d4;
1690 memset (d4, 0, 4);
1692 bfd_set_symtab (abfd, symtab, symptr);
1694 bfd_set_section_contents (abfd, id2, d2, 0, 20);
1695 bfd_set_section_contents (abfd, id5, d5, 0, 4);
1696 bfd_set_section_contents (abfd, id4, d4, 0, 4);
1698 bfd_make_readable (abfd);
1699 return abfd;
1702 /* .section .idata$4
1703 .long 0
1704 .section .idata$5
1705 .long 0
1706 .section idata$7
1707 .global __my_dll_iname
1708 __my_dll_iname:
1709 .asciz "my.dll" */
1711 static bfd *
1712 make_tail (bfd *parent)
1714 asection *id4, *id5, *id7;
1715 unsigned char *d4, *d5, *d7;
1716 int len;
1717 char *oname;
1718 bfd *abfd;
1720 oname = xmalloc (20);
1721 sprintf (oname, "d%06d.o", tmp_seq);
1722 tmp_seq++;
1724 abfd = bfd_create (oname, parent);
1725 bfd_find_target (pe_details->object_target, abfd);
1726 bfd_make_writable (abfd);
1728 bfd_set_format (abfd, bfd_object);
1729 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1731 symptr = 0;
1732 symtab = xmalloc (5 * sizeof (asymbol *));
1733 id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1734 id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1735 id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1736 quick_symbol (abfd, U (""), dll_symname, "_iname", id7, BSF_GLOBAL, 0);
1738 bfd_set_section_size (abfd, id4, 4);
1739 d4 = xmalloc (4);
1740 id4->contents = d4;
1741 memset (d4, 0, 4);
1743 bfd_set_section_size (abfd, id5, 4);
1744 d5 = xmalloc (4);
1745 id5->contents = d5;
1746 memset (d5, 0, 4);
1748 len = strlen (dll_filename) + 1;
1749 if (len & 1)
1750 len++;
1751 bfd_set_section_size (abfd, id7, len);
1752 d7 = xmalloc (len);
1753 id7->contents = d7;
1754 strcpy ((char *) d7, dll_filename);
1756 bfd_set_symtab (abfd, symtab, symptr);
1758 bfd_set_section_contents (abfd, id4, d4, 0, 4);
1759 bfd_set_section_contents (abfd, id5, d5, 0, 4);
1760 bfd_set_section_contents (abfd, id7, d7, 0, len);
1762 bfd_make_readable (abfd);
1763 return abfd;
1766 /* .text
1767 .global _function
1768 .global ___imp_function
1769 .global __imp__function
1770 _function:
1771 jmp *__imp__function:
1773 .section idata$7
1774 .long __head_my_dll
1776 .section .idata$5
1777 ___imp_function:
1778 __imp__function:
1779 iat?
1780 .section .idata$4
1781 iat?
1782 .section .idata$6
1783 ID<ordinal>:
1784 .short <hint>
1785 .asciz "function" xlate? (add underscore, kill at) */
1787 static unsigned char jmp_ix86_bytes[] =
1789 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
1792 /* _function:
1793 mov.l ip+8,r0
1794 mov.l @r0,r0
1795 jmp @r0
1797 .dw __imp_function */
1799 static unsigned char jmp_sh_bytes[] =
1801 0x01, 0xd0, 0x02, 0x60, 0x2b, 0x40, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00
1804 /* _function:
1805 lui $t0,<high:__imp_function>
1806 lw $t0,<low:__imp_function>
1807 jr $t0
1808 nop */
1810 static unsigned char jmp_mips_bytes[] =
1812 0x00, 0x00, 0x08, 0x3c, 0x00, 0x00, 0x08, 0x8d,
1813 0x08, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
1816 static unsigned char jmp_arm_bytes[] =
1818 0x00, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
1819 0x00, 0xf0, 0x9c, 0xe5, /* ldr pc, [ip] */
1820 0, 0, 0, 0
1824 static bfd *
1825 make_one (def_file_export *exp, bfd *parent)
1827 asection *tx, *id7, *id5, *id4, *id6;
1828 unsigned char *td = NULL, *d7, *d5, *d4, *d6 = NULL;
1829 int len;
1830 char *oname;
1831 bfd *abfd;
1832 unsigned char *jmp_bytes = NULL;
1833 int jmp_byte_count = 0;
1835 switch (pe_details->pe_arch)
1837 case PE_ARCH_i386:
1838 jmp_bytes = jmp_ix86_bytes;
1839 jmp_byte_count = sizeof (jmp_ix86_bytes);
1840 break;
1841 case PE_ARCH_sh:
1842 jmp_bytes = jmp_sh_bytes;
1843 jmp_byte_count = sizeof (jmp_sh_bytes);
1844 break;
1845 case PE_ARCH_mips:
1846 jmp_bytes = jmp_mips_bytes;
1847 jmp_byte_count = sizeof (jmp_mips_bytes);
1848 break;
1849 case PE_ARCH_arm:
1850 case PE_ARCH_arm_epoc:
1851 case PE_ARCH_arm_wince:
1852 jmp_bytes = jmp_arm_bytes;
1853 jmp_byte_count = sizeof (jmp_arm_bytes);
1854 break;
1855 default:
1856 abort ();
1859 oname = xmalloc (20);
1860 sprintf (oname, "d%06d.o", tmp_seq);
1861 tmp_seq++;
1863 abfd = bfd_create (oname, parent);
1864 bfd_find_target (pe_details->object_target, abfd);
1865 bfd_make_writable (abfd);
1867 bfd_set_format (abfd, bfd_object);
1868 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
1870 symptr = 0;
1871 symtab = xmalloc (11 * sizeof (asymbol *));
1872 tx = quick_section (abfd, ".text", SEC_CODE|SEC_HAS_CONTENTS, 2);
1873 id7 = quick_section (abfd, ".idata$7", SEC_HAS_CONTENTS, 2);
1874 id5 = quick_section (abfd, ".idata$5", SEC_HAS_CONTENTS, 2);
1875 id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
1876 id6 = quick_section (abfd, ".idata$6", SEC_HAS_CONTENTS, 2);
1878 if (*exp->internal_name == '@')
1880 quick_symbol (abfd, U ("_head_"), dll_symname, "", UNDSEC,
1881 BSF_GLOBAL, 0);
1882 if (! exp->flag_data)
1883 quick_symbol (abfd, "", exp->internal_name, "", tx, BSF_GLOBAL, 0);
1884 quick_symbol (abfd, U ("_imp_"), exp->internal_name, "", id5,
1885 BSF_GLOBAL, 0);
1886 /* Fastcall applies only to functions,
1887 so no need for auto-import symbol. */
1889 else
1891 quick_symbol (abfd, U ("_head_"), dll_symname, "", UNDSEC,
1892 BSF_GLOBAL, 0);
1893 if (! exp->flag_data)
1894 quick_symbol (abfd, U (""), exp->internal_name, "", tx,
1895 BSF_GLOBAL, 0);
1896 quick_symbol (abfd, U ("_imp__"), exp->internal_name, "", id5,
1897 BSF_GLOBAL, 0);
1898 /* Symbol to reference ord/name of imported
1899 data symbol, used to implement auto-import. */
1900 if (exp->flag_data)
1901 quick_symbol (abfd, U("_nm__"), exp->internal_name, "", id6,
1902 BSF_GLOBAL,0);
1904 if (pe_dll_compat_implib)
1905 quick_symbol (abfd, U ("__imp_"), exp->internal_name, "", id5,
1906 BSF_GLOBAL, 0);
1908 if (! exp->flag_data)
1910 bfd_set_section_size (abfd, tx, jmp_byte_count);
1911 td = xmalloc (jmp_byte_count);
1912 tx->contents = td;
1913 memcpy (td, jmp_bytes, jmp_byte_count);
1915 switch (pe_details->pe_arch)
1917 case PE_ARCH_i386:
1918 quick_reloc (abfd, 2, BFD_RELOC_32, 2);
1919 break;
1920 case PE_ARCH_sh:
1921 quick_reloc (abfd, 8, BFD_RELOC_32, 2);
1922 break;
1923 case PE_ARCH_mips:
1924 quick_reloc (abfd, 0, BFD_RELOC_HI16_S, 2);
1925 quick_reloc (abfd, 0, BFD_RELOC_LO16, 0); /* MIPS_R_PAIR */
1926 quick_reloc (abfd, 4, BFD_RELOC_LO16, 2);
1927 break;
1928 case PE_ARCH_arm:
1929 case PE_ARCH_arm_epoc:
1930 case PE_ARCH_arm_wince:
1931 quick_reloc (abfd, 8, BFD_RELOC_32, 2);
1932 break;
1933 default:
1934 abort ();
1936 save_relocs (tx);
1939 bfd_set_section_size (abfd, id7, 4);
1940 d7 = xmalloc (4);
1941 id7->contents = d7;
1942 memset (d7, 0, 4);
1943 quick_reloc (abfd, 0, BFD_RELOC_RVA, 5);
1944 save_relocs (id7);
1946 bfd_set_section_size (abfd, id5, 4);
1947 d5 = xmalloc (4);
1948 id5->contents = d5;
1949 memset (d5, 0, 4);
1951 if (exp->flag_noname)
1953 d5[0] = exp->ordinal;
1954 d5[1] = exp->ordinal >> 8;
1955 d5[3] = 0x80;
1957 else
1959 quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1960 save_relocs (id5);
1963 bfd_set_section_size (abfd, id4, 4);
1964 d4 = xmalloc (4);
1965 id4->contents = d4;
1966 memset (d4, 0, 4);
1968 if (exp->flag_noname)
1970 d4[0] = exp->ordinal;
1971 d4[1] = exp->ordinal >> 8;
1972 d4[3] = 0x80;
1974 else
1976 quick_reloc (abfd, 0, BFD_RELOC_RVA, 4);
1977 save_relocs (id4);
1980 if (exp->flag_noname)
1982 len = 0;
1983 bfd_set_section_size (abfd, id6, 0);
1985 else
1987 len = strlen (exp->name) + 3;
1988 if (len & 1)
1989 len++;
1990 bfd_set_section_size (abfd, id6, len);
1991 d6 = xmalloc (len);
1992 id6->contents = d6;
1993 memset (d6, 0, len);
1994 d6[0] = exp->hint & 0xff;
1995 d6[1] = exp->hint >> 8;
1996 strcpy ((char *) d6 + 2, exp->name);
1999 bfd_set_symtab (abfd, symtab, symptr);
2001 bfd_set_section_contents (abfd, tx, td, 0, jmp_byte_count);
2002 bfd_set_section_contents (abfd, id7, d7, 0, 4);
2003 bfd_set_section_contents (abfd, id5, d5, 0, 4);
2004 bfd_set_section_contents (abfd, id4, d4, 0, 4);
2005 if (!exp->flag_noname)
2006 bfd_set_section_contents (abfd, id6, d6, 0, len);
2008 bfd_make_readable (abfd);
2009 return abfd;
2012 static bfd *
2013 make_singleton_name_thunk (const char *import, bfd *parent)
2015 /* Name thunks go to idata$4. */
2016 asection *id4;
2017 unsigned char *d4;
2018 char *oname;
2019 bfd *abfd;
2021 oname = xmalloc (20);
2022 sprintf (oname, "nmth%06d.o", tmp_seq);
2023 tmp_seq++;
2025 abfd = bfd_create (oname, parent);
2026 bfd_find_target (pe_details->object_target, abfd);
2027 bfd_make_writable (abfd);
2029 bfd_set_format (abfd, bfd_object);
2030 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2032 symptr = 0;
2033 symtab = xmalloc (3 * sizeof (asymbol *));
2034 id4 = quick_section (abfd, ".idata$4", SEC_HAS_CONTENTS, 2);
2035 quick_symbol (abfd, U ("_nm_thnk_"), import, "", id4, BSF_GLOBAL, 0);
2036 quick_symbol (abfd, U ("_nm_"), import, "", UNDSEC, BSF_GLOBAL, 0);
2038 bfd_set_section_size (abfd, id4, 8);
2039 d4 = xmalloc (4);
2040 id4->contents = d4;
2041 memset (d4, 0, 8);
2042 quick_reloc (abfd, 0, BFD_RELOC_RVA, 2);
2043 save_relocs (id4);
2045 bfd_set_symtab (abfd, symtab, symptr);
2047 bfd_set_section_contents (abfd, id4, d4, 0, 8);
2049 bfd_make_readable (abfd);
2050 return abfd;
2053 static char *
2054 make_import_fixup_mark (arelent *rel)
2056 /* We convert reloc to symbol, for later reference. */
2057 static int counter;
2058 static char *fixup_name = NULL;
2059 static size_t buffer_len = 0;
2061 struct bfd_symbol *sym = *rel->sym_ptr_ptr;
2063 bfd *abfd = bfd_asymbol_bfd (sym);
2064 struct bfd_link_hash_entry *bh;
2066 if (!fixup_name)
2068 fixup_name = xmalloc (384);
2069 buffer_len = 384;
2072 if (strlen (sym->name) + 25 > buffer_len)
2073 /* Assume 25 chars for "__fu" + counter + "_". If counter is
2074 bigger than 20 digits long, we've got worse problems than
2075 overflowing this buffer... */
2077 free (fixup_name);
2078 /* New buffer size is length of symbol, plus 25, but
2079 then rounded up to the nearest multiple of 128. */
2080 buffer_len = ((strlen (sym->name) + 25) + 127) & ~127;
2081 fixup_name = xmalloc (buffer_len);
2084 sprintf (fixup_name, "__fu%d_%s", counter++, sym->name);
2086 bh = NULL;
2087 bfd_coff_link_add_one_symbol (&link_info, abfd, fixup_name, BSF_GLOBAL,
2088 current_sec, /* sym->section, */
2089 rel->address, NULL, TRUE, FALSE, &bh);
2091 if (0)
2093 struct coff_link_hash_entry *myh;
2095 myh = (struct coff_link_hash_entry *) bh;
2096 printf ("type:%d\n", myh->type);
2097 printf ("%s\n", myh->root.u.def.section->name);
2100 return fixup_name;
2103 /* .section .idata$2
2104 .rva __nm_thnk_SYM (singleton thunk with name of func)
2105 .long 0
2106 .long 0
2107 .rva __my_dll_iname (name of dll)
2108 .rva __fuNN_SYM (pointer to reference (address) in text) */
2110 static bfd *
2111 make_import_fixup_entry (const char *name,
2112 const char *fixup_name,
2113 const char *dll_symname,
2114 bfd *parent)
2116 asection *id2;
2117 unsigned char *d2;
2118 char *oname;
2119 bfd *abfd;
2121 oname = xmalloc (20);
2122 sprintf (oname, "fu%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 (6 * sizeof (asymbol *));
2134 id2 = quick_section (abfd, ".idata$2", SEC_HAS_CONTENTS, 2);
2136 quick_symbol (abfd, U ("_nm_thnk_"), name, "", UNDSEC, BSF_GLOBAL, 0);
2137 quick_symbol (abfd, U (""), dll_symname, "_iname", UNDSEC, BSF_GLOBAL, 0);
2138 quick_symbol (abfd, "", fixup_name, "", UNDSEC, BSF_GLOBAL, 0);
2140 bfd_set_section_size (abfd, id2, 20);
2141 d2 = xmalloc (20);
2142 id2->contents = d2;
2143 memset (d2, 0, 20);
2145 quick_reloc (abfd, 0, BFD_RELOC_RVA, 1);
2146 quick_reloc (abfd, 12, BFD_RELOC_RVA, 2);
2147 quick_reloc (abfd, 16, BFD_RELOC_RVA, 3);
2148 save_relocs (id2);
2150 bfd_set_symtab (abfd, symtab, symptr);
2152 bfd_set_section_contents (abfd, id2, d2, 0, 20);
2154 bfd_make_readable (abfd);
2155 return abfd;
2158 /* .section .rdata_runtime_pseudo_reloc
2159 .long addend
2160 .rva __fuNN_SYM (pointer to reference (address) in text) */
2162 static bfd *
2163 make_runtime_pseudo_reloc (const char *name ATTRIBUTE_UNUSED,
2164 const char *fixup_name,
2165 int addend,
2166 bfd *parent)
2168 asection *rt_rel;
2169 unsigned char *rt_rel_d;
2170 char *oname;
2171 bfd *abfd;
2173 oname = xmalloc (20);
2174 sprintf (oname, "rtr%06d.o", tmp_seq);
2175 tmp_seq++;
2177 abfd = bfd_create (oname, parent);
2178 bfd_find_target (pe_details->object_target, abfd);
2179 bfd_make_writable (abfd);
2181 bfd_set_format (abfd, bfd_object);
2182 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2184 symptr = 0;
2185 symtab = xmalloc (2 * sizeof (asymbol *));
2186 rt_rel = quick_section (abfd, ".rdata_runtime_pseudo_reloc",
2187 SEC_HAS_CONTENTS, 2);
2189 quick_symbol (abfd, "", fixup_name, "", UNDSEC, BSF_GLOBAL, 0);
2191 bfd_set_section_size (abfd, rt_rel, 8);
2192 rt_rel_d = xmalloc (8);
2193 rt_rel->contents = rt_rel_d;
2194 memset (rt_rel_d, 0, 8);
2195 bfd_put_32 (abfd, addend, rt_rel_d);
2197 quick_reloc (abfd, 4, BFD_RELOC_RVA, 1);
2198 save_relocs (rt_rel);
2200 bfd_set_symtab (abfd, symtab, symptr);
2202 bfd_set_section_contents (abfd, rt_rel, rt_rel_d, 0, 8);
2204 bfd_make_readable (abfd);
2205 return abfd;
2208 /* .section .rdata
2209 .rva __pei386_runtime_relocator */
2211 static bfd *
2212 pe_create_runtime_relocator_reference (bfd *parent)
2214 asection *extern_rt_rel;
2215 unsigned char *extern_rt_rel_d;
2216 char *oname;
2217 bfd *abfd;
2219 oname = xmalloc (20);
2220 sprintf (oname, "ertr%06d.o", tmp_seq);
2221 tmp_seq++;
2223 abfd = bfd_create (oname, parent);
2224 bfd_find_target (pe_details->object_target, abfd);
2225 bfd_make_writable (abfd);
2227 bfd_set_format (abfd, bfd_object);
2228 bfd_set_arch_mach (abfd, pe_details->bfd_arch, 0);
2230 symptr = 0;
2231 symtab = xmalloc (2 * sizeof (asymbol *));
2232 extern_rt_rel = quick_section (abfd, ".rdata", SEC_HAS_CONTENTS, 2);
2234 quick_symbol (abfd, "", "__pei386_runtime_relocator", "", UNDSEC,
2235 BSF_NO_FLAGS, 0);
2237 bfd_set_section_size (abfd, extern_rt_rel, 4);
2238 extern_rt_rel_d = xmalloc (4);
2239 extern_rt_rel->contents = extern_rt_rel_d;
2241 quick_reloc (abfd, 0, BFD_RELOC_RVA, 1);
2242 save_relocs (extern_rt_rel);
2244 bfd_set_symtab (abfd, symtab, symptr);
2246 bfd_set_section_contents (abfd, extern_rt_rel, extern_rt_rel_d, 0, 4);
2248 bfd_make_readable (abfd);
2249 return abfd;
2252 void
2253 pe_create_import_fixup (arelent *rel, asection *s, int addend)
2255 char buf[300];
2256 struct bfd_symbol *sym = *rel->sym_ptr_ptr;
2257 struct bfd_link_hash_entry *name_thunk_sym;
2258 const char *name = sym->name;
2259 char *fixup_name = make_import_fixup_mark (rel);
2260 bfd *b;
2262 sprintf (buf, U ("_nm_thnk_%s"), name);
2264 name_thunk_sym = bfd_link_hash_lookup (link_info.hash, buf, 0, 0, 1);
2266 if (!name_thunk_sym || name_thunk_sym->type != bfd_link_hash_defined)
2268 bfd *b = make_singleton_name_thunk (name, output_bfd);
2269 add_bfd_to_link (b, b->filename, &link_info);
2271 /* If we ever use autoimport, we have to cast text section writable. */
2272 config.text_read_only = FALSE;
2273 output_bfd->flags &= ~WP_TEXT;
2276 if (addend == 0 || link_info.pei386_runtime_pseudo_reloc)
2278 extern char * pe_data_import_dll;
2279 char * dll_symname = pe_data_import_dll ? pe_data_import_dll : "unknown";
2281 b = make_import_fixup_entry (name, fixup_name, dll_symname, output_bfd);
2282 add_bfd_to_link (b, b->filename, &link_info);
2285 if (addend != 0)
2287 if (link_info.pei386_runtime_pseudo_reloc)
2289 if (pe_dll_extra_pe_debug)
2290 printf ("creating runtime pseudo-reloc entry for %s (addend=%d)\n",
2291 fixup_name, addend);
2292 b = make_runtime_pseudo_reloc (name, fixup_name, addend, output_bfd);
2293 add_bfd_to_link (b, b->filename, &link_info);
2295 if (runtime_pseudo_relocs_created == 0)
2297 b = pe_create_runtime_relocator_reference (output_bfd);
2298 add_bfd_to_link (b, b->filename, &link_info);
2300 runtime_pseudo_relocs_created++;
2302 else
2304 einfo (_("%C: variable '%T' can't be auto-imported. Please read the documentation for ld's --enable-auto-import for details.\n"),
2305 s->owner, s, rel->address, sym->name);
2306 einfo ("%X");
2312 void
2313 pe_dll_generate_implib (def_file *def, const char *impfilename)
2315 int i;
2316 bfd *ar_head;
2317 bfd *ar_tail;
2318 bfd *outarch;
2319 bfd *head = 0;
2321 dll_filename = (def->name) ? def->name : dll_name;
2322 dll_symname = xstrdup (dll_filename);
2323 for (i = 0; dll_symname[i]; i++)
2324 if (!ISALNUM (dll_symname[i]))
2325 dll_symname[i] = '_';
2327 unlink_if_ordinary (impfilename);
2329 outarch = bfd_openw (impfilename, 0);
2331 if (!outarch)
2333 /* xgettext:c-format */
2334 einfo (_("%XCan't open .lib file: %s\n"), impfilename);
2335 return;
2338 /* xgettext:c-format */
2339 info_msg (_("Creating library file: %s\n"), impfilename);
2341 bfd_set_format (outarch, bfd_archive);
2342 outarch->has_armap = 1;
2344 /* Work out a reasonable size of things to put onto one line. */
2345 ar_head = make_head (outarch);
2347 for (i = 0; i < def->num_exports; i++)
2349 /* The import library doesn't know about the internal name. */
2350 char *internal = def->exports[i].internal_name;
2351 bfd *n;
2353 /* Don't add PRIVATE entries to import lib. */
2354 if (pe_def_file->exports[i].flag_private)
2355 continue;
2356 def->exports[i].internal_name = def->exports[i].name;
2357 n = make_one (def->exports + i, outarch);
2358 n->next = head;
2359 head = n;
2360 def->exports[i].internal_name = internal;
2363 ar_tail = make_tail (outarch);
2365 if (ar_head == NULL || ar_tail == NULL)
2366 return;
2368 /* Now stick them all into the archive. */
2369 ar_head->next = head;
2370 ar_tail->next = ar_head;
2371 head = ar_tail;
2373 if (! bfd_set_archive_head (outarch, head))
2374 einfo ("%Xbfd_set_archive_head: %E\n");
2376 if (! bfd_close (outarch))
2377 einfo ("%Xbfd_close %s: %E\n", impfilename);
2379 while (head != NULL)
2381 bfd *n = head->next;
2382 bfd_close (head);
2383 head = n;
2387 static void
2388 add_bfd_to_link (bfd *abfd, const char *name, struct bfd_link_info *link_info)
2390 lang_input_statement_type *fake_file;
2392 fake_file = lang_add_input_file (name,
2393 lang_input_file_is_fake_enum,
2394 NULL);
2395 fake_file->the_bfd = abfd;
2396 ldlang_add_file (fake_file);
2398 if (!bfd_link_add_symbols (abfd, link_info))
2399 einfo ("%Xaddsym %s: %E\n", name);
2402 void
2403 pe_process_import_defs (bfd *output_bfd, struct bfd_link_info *link_info)
2405 def_file_module *module;
2407 pe_dll_id_target (bfd_get_target (output_bfd));
2409 if (!pe_def_file)
2410 return;
2412 for (module = pe_def_file->modules; module; module = module->next)
2414 int i, do_this_dll;
2416 dll_filename = module->name;
2417 dll_symname = xstrdup (module->name);
2418 for (i = 0; dll_symname[i]; i++)
2419 if (!ISALNUM (dll_symname[i]))
2420 dll_symname[i] = '_';
2422 do_this_dll = 0;
2424 for (i = 0; i < pe_def_file->num_imports; i++)
2425 if (pe_def_file->imports[i].module == module)
2427 def_file_export exp;
2428 struct bfd_link_hash_entry *blhe;
2429 int lead_at = (*pe_def_file->imports[i].internal_name == '@');
2430 /* See if we need this import. */
2431 size_t len = strlen (pe_def_file->imports[i].internal_name);
2432 char *name = xmalloc (len + 2 + 6);
2434 if (lead_at)
2435 sprintf (name, "%s%s", "",
2436 pe_def_file->imports[i].internal_name);
2437 else
2438 sprintf (name, "%s%s",U (""),
2439 pe_def_file->imports[i].internal_name);
2441 blhe = bfd_link_hash_lookup (link_info->hash, name,
2442 FALSE, FALSE, FALSE);
2444 if (!blhe || (blhe && blhe->type != bfd_link_hash_undefined))
2446 if (lead_at)
2447 sprintf (name, "%s%s", U ("_imp_"),
2448 pe_def_file->imports[i].internal_name);
2449 else
2450 sprintf (name, "%s%s", U ("_imp__"),
2451 pe_def_file->imports[i].internal_name);
2453 blhe = bfd_link_hash_lookup (link_info->hash, name,
2454 FALSE, FALSE, FALSE);
2456 free (name);
2458 if (blhe && blhe->type == bfd_link_hash_undefined)
2460 bfd *one;
2461 /* We do. */
2462 if (!do_this_dll)
2464 bfd *ar_head = make_head (output_bfd);
2465 add_bfd_to_link (ar_head, ar_head->filename, link_info);
2466 do_this_dll = 1;
2468 exp.internal_name = pe_def_file->imports[i].internal_name;
2469 exp.name = pe_def_file->imports[i].name;
2470 exp.ordinal = pe_def_file->imports[i].ordinal;
2471 exp.hint = exp.ordinal >= 0 ? exp.ordinal : 0;
2472 exp.flag_private = 0;
2473 exp.flag_constant = 0;
2474 exp.flag_data = pe_def_file->imports[i].data;
2475 exp.flag_noname = exp.name ? 0 : 1;
2476 one = make_one (&exp, output_bfd);
2477 add_bfd_to_link (one, one->filename, link_info);
2480 if (do_this_dll)
2482 bfd *ar_tail = make_tail (output_bfd);
2483 add_bfd_to_link (ar_tail, ar_tail->filename, link_info);
2486 free (dll_symname);
2490 /* We were handed a *.DLL file. Parse it and turn it into a set of
2491 IMPORTS directives in the def file. Return TRUE if the file was
2492 handled, FALSE if not. */
2494 static unsigned int
2495 pe_get16 (bfd *abfd, int where)
2497 unsigned char b[2];
2499 bfd_seek (abfd, (file_ptr) where, SEEK_SET);
2500 bfd_bread (b, (bfd_size_type) 2, abfd);
2501 return b[0] + (b[1] << 8);
2504 static unsigned int
2505 pe_get32 (bfd *abfd, int where)
2507 unsigned char b[4];
2509 bfd_seek (abfd, (file_ptr) where, SEEK_SET);
2510 bfd_bread (b, (bfd_size_type) 4, abfd);
2511 return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
2514 static unsigned int
2515 pe_as32 (void *ptr)
2517 unsigned char *b = ptr;
2519 return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
2522 bfd_boolean
2523 pe_implied_import_dll (const char *filename)
2525 bfd *dll;
2526 unsigned long pe_header_offset, opthdr_ofs, num_entries, i;
2527 unsigned long export_rva, export_size, nsections, secptr, expptr;
2528 unsigned long exp_funcbase;
2529 unsigned char *expdata;
2530 char *erva;
2531 unsigned long name_rvas, ordinals, nexp, ordbase;
2532 const char *dll_name;
2533 /* Initialization with start > end guarantees that is_data
2534 will not be set by mistake, and avoids compiler warning. */
2535 unsigned long data_start = 1;
2536 unsigned long data_end = 0;
2537 unsigned long rdata_start = 1;
2538 unsigned long rdata_end = 0;
2539 unsigned long bss_start = 1;
2540 unsigned long bss_end = 0;
2542 /* No, I can't use bfd here. kernel32.dll puts its export table in
2543 the middle of the .rdata section. */
2544 dll = bfd_openr (filename, pe_details->target_name);
2545 if (!dll)
2547 einfo ("%Xopen %s: %E\n", filename);
2548 return FALSE;
2551 /* PEI dlls seem to be bfd_objects. */
2552 if (!bfd_check_format (dll, bfd_object))
2554 einfo ("%X%s: this doesn't appear to be a DLL\n", filename);
2555 return FALSE;
2558 /* Get pe_header, optional header and numbers of export entries. */
2559 pe_header_offset = pe_get32 (dll, 0x3c);
2560 opthdr_ofs = pe_header_offset + 4 + 20;
2561 num_entries = pe_get32 (dll, opthdr_ofs + 92);
2563 if (num_entries < 1) /* No exports. */
2564 return FALSE;
2566 export_rva = pe_get32 (dll, opthdr_ofs + 96);
2567 export_size = pe_get32 (dll, opthdr_ofs + 100);
2568 nsections = pe_get16 (dll, pe_header_offset + 4 + 2);
2569 secptr = (pe_header_offset + 4 + 20 +
2570 pe_get16 (dll, pe_header_offset + 4 + 16));
2571 expptr = 0;
2573 /* Get the rva and size of the export section. */
2574 for (i = 0; i < nsections; i++)
2576 char sname[8];
2577 unsigned long secptr1 = secptr + 40 * i;
2578 unsigned long vaddr = pe_get32 (dll, secptr1 + 12);
2579 unsigned long vsize = pe_get32 (dll, secptr1 + 16);
2580 unsigned long fptr = pe_get32 (dll, secptr1 + 20);
2582 bfd_seek (dll, (file_ptr) secptr1, SEEK_SET);
2583 bfd_bread (sname, (bfd_size_type) 8, dll);
2585 if (vaddr <= export_rva && vaddr + vsize > export_rva)
2587 expptr = fptr + (export_rva - vaddr);
2588 if (export_rva + export_size > vaddr + vsize)
2589 export_size = vsize - (export_rva - vaddr);
2590 break;
2594 /* Scan sections and store the base and size of the
2595 data and bss segments in data/base_start/end. */
2596 for (i = 0; i < nsections; i++)
2598 unsigned long secptr1 = secptr + 40 * i;
2599 unsigned long vsize = pe_get32 (dll, secptr1 + 8);
2600 unsigned long vaddr = pe_get32 (dll, secptr1 + 12);
2601 unsigned long flags = pe_get32 (dll, secptr1 + 36);
2602 char sec_name[9];
2604 sec_name[8] = '\0';
2605 bfd_seek (dll, (file_ptr) secptr1 + 0, SEEK_SET);
2606 bfd_bread (sec_name, (bfd_size_type) 8, dll);
2608 if (strcmp(sec_name,".data") == 0)
2610 data_start = vaddr;
2611 data_end = vaddr + vsize;
2613 if (pe_dll_extra_pe_debug)
2614 printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2615 __FUNCTION__, sec_name, vaddr, vaddr + vsize, flags);
2617 else if (strcmp(sec_name,".rdata") == 0)
2619 rdata_start = vaddr;
2620 rdata_end = vaddr + vsize;
2622 if (pe_dll_extra_pe_debug)
2623 printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2624 __FUNCTION__, sec_name, vaddr, vaddr + vsize, flags);
2626 else if (strcmp (sec_name,".bss") == 0)
2628 bss_start = vaddr;
2629 bss_end = vaddr + vsize;
2631 if (pe_dll_extra_pe_debug)
2632 printf ("%s %s: 0x%08lx-0x%08lx (0x%08lx)\n",
2633 __FUNCTION__, sec_name, vaddr, vaddr + vsize, flags);
2637 expdata = xmalloc (export_size);
2638 bfd_seek (dll, (file_ptr) expptr, SEEK_SET);
2639 bfd_bread (expdata, (bfd_size_type) export_size, dll);
2640 erva = (char *) expdata - export_rva;
2642 if (pe_def_file == 0)
2643 pe_def_file = def_file_empty ();
2645 nexp = pe_as32 (expdata + 24);
2646 name_rvas = pe_as32 (expdata + 32);
2647 ordinals = pe_as32 (expdata + 36);
2648 ordbase = pe_as32 (expdata + 16);
2649 exp_funcbase = pe_as32 (expdata + 28);
2651 /* Use internal dll name instead of filename
2652 to enable symbolic dll linking. */
2653 dll_name = erva + pe_as32 (expdata + 12);
2655 /* Check to see if the dll has already been added to
2656 the definition list and if so return without error.
2657 This avoids multiple symbol definitions. */
2658 if (def_get_module (pe_def_file, dll_name))
2660 if (pe_dll_extra_pe_debug)
2661 printf ("%s is already loaded\n", dll_name);
2662 return TRUE;
2665 /* Iterate through the list of symbols. */
2666 for (i = 0; i < nexp; i++)
2668 /* Pointer to the names vector. */
2669 unsigned long name_rva = pe_as32 (erva + name_rvas + i * 4);
2670 def_file_import *imp;
2671 /* Pointer to the function address vector. */
2672 unsigned long func_rva = pe_as32 (erva + exp_funcbase + i * 4);
2673 int is_data = 0;
2675 /* Skip unwanted symbols, which are
2676 exported in buggy auto-import releases. */
2677 if (strncmp (erva + name_rva, "_nm_", 4) != 0)
2679 /* is_data is true if the address is in the data, rdata or bss
2680 segment. */
2681 is_data =
2682 (func_rva >= data_start && func_rva < data_end)
2683 || (func_rva >= rdata_start && func_rva < rdata_end)
2684 || (func_rva >= bss_start && func_rva < bss_end);
2686 imp = def_file_add_import (pe_def_file, erva + name_rva,
2687 dll_name, i, 0);
2688 /* Mark symbol type. */
2689 imp->data = is_data;
2691 if (pe_dll_extra_pe_debug)
2692 printf ("%s dll-name: %s sym: %s addr: 0x%lx %s\n",
2693 __FUNCTION__, dll_name, erva + name_rva,
2694 func_rva, is_data ? "(data)" : "");
2698 return TRUE;
2701 /* These are the main functions, called from the emulation. The first
2702 is called after the bfds are read, so we can guess at how much space
2703 we need. The second is called after everything is placed, so we
2704 can put the right values in place. */
2706 void
2707 pe_dll_build_sections (bfd *abfd, struct bfd_link_info *info)
2709 pe_dll_id_target (bfd_get_target (abfd));
2710 process_def_file (abfd, info);
2712 if (pe_def_file->num_exports == 0 && !info->shared)
2713 return;
2715 generate_edata (abfd, info);
2716 build_filler_bfd (1);
2719 void
2720 pe_exe_build_sections (bfd *abfd, struct bfd_link_info *info ATTRIBUTE_UNUSED)
2722 pe_dll_id_target (bfd_get_target (abfd));
2723 build_filler_bfd (0);
2726 void
2727 pe_dll_fill_sections (bfd *abfd, struct bfd_link_info *info)
2729 pe_dll_id_target (bfd_get_target (abfd));
2730 image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2732 generate_reloc (abfd, info);
2733 if (reloc_sz > 0)
2735 bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2737 /* Resize the sections. */
2738 lang_reset_memory_regions ();
2739 lang_size_sections (NULL, TRUE);
2741 /* Redo special stuff. */
2742 ldemul_after_allocation ();
2744 /* Do the assignments again. */
2745 lang_do_assignments ();
2748 fill_edata (abfd, info);
2750 if (info->shared && !info->pie)
2751 pe_data (abfd)->dll = 1;
2753 edata_s->contents = edata_d;
2754 reloc_s->contents = reloc_d;
2757 void
2758 pe_exe_fill_sections (bfd *abfd, struct bfd_link_info *info)
2760 pe_dll_id_target (bfd_get_target (abfd));
2761 image_base = pe_data (abfd)->pe_opthdr.ImageBase;
2763 generate_reloc (abfd, info);
2764 if (reloc_sz > 0)
2766 bfd_set_section_size (filler_bfd, reloc_s, reloc_sz);
2768 /* Resize the sections. */
2769 lang_reset_memory_regions ();
2770 lang_size_sections (NULL, TRUE);
2772 /* Redo special stuff. */
2773 ldemul_after_allocation ();
2775 /* Do the assignments again. */
2776 lang_do_assignments ();
2778 reloc_s->contents = reloc_d;