Applied Mumit Kha's patch to tweak dll production code.
[binutils.git] / ld / emultempl / pe.em
bloba91caa848fdf61988e84a3787e1cdb62bb90fe86
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 rm -f e${EMULATION_NAME}.c
4 (echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
5 cat >>e${EMULATION_NAME}.c <<EOF
6 /* This file is part of GLD, the Gnu Linker.
7    Copyright 1995, 96, 97, 98, 99, 2000 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
23 /* For WINDOWS_NT */
24 /* The original file generated returned different default scripts depending
25    on whether certain switches were set, but these switches pertain to the
26    Linux system and that particular version of coff.  In the NT case, we
27    only determine if the subsystem is console or windows in order to select
28    the correct entry point by default. */ 
29   
30 #include "bfd.h"
31 #include "sysdep.h"
32 #include "bfdlink.h"
33 #include "getopt.h"
34 #include "libiberty.h"
35 #include "ld.h"
36 #include "ldmain.h"
37 #include "ldgram.h"
38 #include "ldexp.h"
39 #include "ldlang.h"
40 #include "ldemul.h"
41 #include "ldlex.h"
42 #include "ldmisc.h"
43 #include "ldctor.h"
44 #include "ldfile.h"
45 #include "coff/internal.h"
47 /* FIXME: This is a BFD internal header file, and we should not be
48    using it here.  */
49 #include "../bfd/libcoff.h"
51 #include "deffile.h"
52 #include "pe-dll.h"
54 #define TARGET_IS_${EMULATION_NAME}
56 /* Permit the emulation parameters to override the default section
57    alignment by setting OVERRIDE_SECTION_ALIGNMENT.  FIXME: This makes
58    it seem that include/coff/internal.h should not define
59    PE_DEF_SECTION_ALIGNMENT.  */
60 #if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
61 #undef PE_DEF_SECTION_ALIGNMENT
62 #define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
63 #endif
65 #if defined(TARGET_IS_i386pe)
66 #define DLL_SUPPORT
67 #endif
69 #define PE_DEF_SUBSYSTEM                3
71 #ifdef TARGET_IS_arm_epoc_pe
72 #define bfd_arm_pe_allocate_interworking_sections \
73         bfd_arm_epoc_pe_allocate_interworking_sections
74 #define bfd_arm_pe_get_bfd_for_interworking \
75         bfd_arm_epoc_pe_get_bfd_for_interworking
76 #define bfd_arm_pe_process_before_allocation \
77         bfd_arm_epoc_pe_process_before_allocation
78 #endif
80 static void gld_${EMULATION_NAME}_set_symbols PARAMS ((void));
81 static void gld_${EMULATION_NAME}_after_open PARAMS ((void));
82 static void gld_${EMULATION_NAME}_before_parse PARAMS ((void));
83 static void gld_${EMULATION_NAME}_after_parse PARAMS ((void));
84 static void gld_${EMULATION_NAME}_before_allocation PARAMS ((void));
85 static boolean gld_${EMULATION_NAME}_place_orphan
86   PARAMS ((lang_input_statement_type *, asection *));
87 static void gld${EMULATION_NAME}_place_section
88   PARAMS ((lang_statement_union_type *));
89 static char *gld_${EMULATION_NAME}_get_script PARAMS ((int *));
90 static int gld_${EMULATION_NAME}_parse_args PARAMS ((int, char **));
91 static void gld_${EMULATION_NAME}_finish PARAMS ((void));
93 static struct internal_extra_pe_aouthdr pe;
94 static int dll;
95 static int support_old_code = 0;
96 static char * thumb_entry_symbol = NULL;
97 static lang_assignment_statement_type *image_base_statement = 0;
99 static char *pe_out_def_filename = 0;
100 static int pe_enable_stdcall_fixup = -1; /* 0=disable 1=enable */
101 static char *pe_implib_filename = 0;
103 extern const char *output_filename;
105 static void
106 gld_${EMULATION_NAME}_before_parse()
108   output_filename = "${EXECUTABLE_NAME:-a.exe}";
109   ldfile_output_architecture = bfd_arch_${ARCH};
110 #ifdef DLL_SUPPORT
111   config.has_shared = 1;
112 #endif
115 /* PE format extra command line options.  */
117 /* Used for setting flags in the PE header. */
118 #define OPTION_BASE_FILE                (300  + 1)
119 #define OPTION_DLL                      (OPTION_BASE_FILE + 1)
120 #define OPTION_FILE_ALIGNMENT           (OPTION_DLL + 1)
121 #define OPTION_IMAGE_BASE               (OPTION_FILE_ALIGNMENT + 1)
122 #define OPTION_MAJOR_IMAGE_VERSION      (OPTION_IMAGE_BASE + 1)
123 #define OPTION_MAJOR_OS_VERSION         (OPTION_MAJOR_IMAGE_VERSION + 1)
124 #define OPTION_MAJOR_SUBSYSTEM_VERSION  (OPTION_MAJOR_OS_VERSION + 1)
125 #define OPTION_MINOR_IMAGE_VERSION      (OPTION_MAJOR_SUBSYSTEM_VERSION + 1)
126 #define OPTION_MINOR_OS_VERSION         (OPTION_MINOR_IMAGE_VERSION + 1)
127 #define OPTION_MINOR_SUBSYSTEM_VERSION  (OPTION_MINOR_OS_VERSION + 1)
128 #define OPTION_SECTION_ALIGNMENT        (OPTION_MINOR_SUBSYSTEM_VERSION + 1)
129 #define OPTION_STACK                    (OPTION_SECTION_ALIGNMENT + 1)
130 #define OPTION_SUBSYSTEM                (OPTION_STACK + 1)
131 #define OPTION_HEAP                     (OPTION_SUBSYSTEM + 1)
132 #define OPTION_SUPPORT_OLD_CODE         (OPTION_HEAP + 1)
133 #define OPTION_OUT_DEF                  (OPTION_SUPPORT_OLD_CODE + 1)
134 #define OPTION_EXPORT_ALL               (OPTION_OUT_DEF + 1)
135 #define OPTION_EXCLUDE_SYMBOLS          (OPTION_EXPORT_ALL + 1)
136 #define OPTION_KILL_ATS                 (OPTION_EXCLUDE_SYMBOLS + 1)
137 #define OPTION_STDCALL_ALIASES          (OPTION_KILL_ATS + 1)
138 #define OPTION_ENABLE_STDCALL_FIXUP     (OPTION_STDCALL_ALIASES + 1)
139 #define OPTION_DISABLE_STDCALL_FIXUP    (OPTION_ENABLE_STDCALL_FIXUP + 1)
140 #define OPTION_IMPLIB_FILENAME          (OPTION_DISABLE_STDCALL_FIXUP + 1)
141 #define OPTION_THUMB_ENTRY              (OPTION_IMPLIB_FILENAME + 1)
142 #define OPTION_WARN_DUPLICATE_EXPORTS   (OPTION_THUMB_ENTRY + 1)
143 #define OPTION_IMP_COMPAT               (OPTION_WARN_DUPLICATE_EXPORTS + 1)
145 static struct option longopts[] =
147   /* PE options */
148   {"base-file", required_argument, NULL, OPTION_BASE_FILE},
149   {"dll", no_argument, NULL, OPTION_DLL},
150   {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
151   {"heap", required_argument, NULL, OPTION_HEAP}, 
152   {"image-base", required_argument, NULL, OPTION_IMAGE_BASE},
153   {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
154   {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
155   {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
156   {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
157   {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
158   {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
159   {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
160   {"stack", required_argument, NULL, OPTION_STACK},
161   {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
162   {"support-old-code", no_argument, NULL, OPTION_SUPPORT_OLD_CODE},
163   {"thumb-entry", required_argument, NULL, OPTION_THUMB_ENTRY},
164 #ifdef DLL_SUPPORT
165   /* getopt allows abbreviations, so we do this to stop it from treating -o
166      as an abbreviation for this option */
167   {"output-def", required_argument, NULL, OPTION_OUT_DEF},
168   {"output-def", required_argument, NULL, OPTION_OUT_DEF},
169   {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL},
170   {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMBOLS},
171   {"kill-at", no_argument, NULL, OPTION_KILL_ATS},
172   {"add-stdcall-alias", no_argument, NULL, OPTION_STDCALL_ALIASES},
173   {"enable-stdcall-fixup", no_argument, NULL, OPTION_ENABLE_STDCALL_FIXUP},
174   {"disable-stdcall-fixup", no_argument, NULL, OPTION_DISABLE_STDCALL_FIXUP},
175   {"out-implib", required_argument, NULL, OPTION_IMPLIB_FILENAME},
176   {"warn-duplicate-exports", no_argument, NULL, OPTION_WARN_DUPLICATE_EXPORTS},
177   {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
178 #endif
179   {NULL, no_argument, NULL, 0}
183 /* PE/WIN32; added routines to get the subsystem type, heap and/or stack
184    parameters which may be input from the command line */
186 typedef struct
188   void *ptr;
189   int size;
190   int value;
191   char *symbol;
192   int inited;
193 } definfo;
195 #define D(field,symbol,def)  {&pe.field,sizeof(pe.field), def, symbol,0}
197 static definfo init[] =
199   /* imagebase must be first */
200 #define IMAGEBASEOFF 0
201   D(ImageBase,"__image_base__", NT_EXE_IMAGE_BASE),
202 #define DLLOFF 1
203   {&dll, sizeof(dll), 0, "__dll__", 0},
204   D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT),
205   D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT),
206   D(MajorOperatingSystemVersion,"__major_os_version__", 4),
207   D(MinorOperatingSystemVersion,"__minor_os_version__", 0),
208   D(MajorImageVersion,"__major_image_version__", 1),
209   D(MinorImageVersion,"__minor_image_version__", 0),
210   D(MajorSubsystemVersion,"__major_subsystem_version__", 4),
211   D(MinorSubsystemVersion,"__minor_subsystem_version__", 0),
212   D(Subsystem,"__subsystem__", ${SUBSYSTEM}),
213   D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x2000000),
214   D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000),
215   D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000),
216   D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000),
217   D(LoaderFlags,"__loader_flags__", 0x0),
218   { NULL, 0, 0, NULL, 0 }
221 static void
222 gld_${EMULATION_NAME}_list_options (file)
223      FILE * file;
225   fprintf (file, _("  --base_file <basefile>             Generate a base file for relocatable DLLs\n"));
226   fprintf (file, _("  --dll                              Set image base to the default for DLLs\n"));
227   fprintf (file, _("  --file-alignment <size>            Set file alignment\n"));
228   fprintf (file, _("  --heap <size>                      Set initial size of the heap\n"));
229   fprintf (file, _("  --image-base <address>             Set start address of the executable\n"));
230   fprintf (file, _("  --major-image-version <number>     Set version number of the executable\n"));
231   fprintf (file, _("  --major-os-version <number>        Set minimum required OS version\n"));
232   fprintf (file, _("  --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
233   fprintf (file, _("  --minor-image-version <number>     Set revision number of the executable\n"));
234   fprintf (file, _("  --minor-os-version <number>        Set minimum required OS revision\n"));
235   fprintf (file, _("  --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
236   fprintf (file, _("  --section-alignment <size>         Set section alignment\n"));
237   fprintf (file, _("  --stack <size>                     Set size of the initial stack\n"));
238   fprintf (file, _("  --subsystem <name>[:<version>]     Set required OS subsystem [& version]\n"));
239   fprintf (file, _("  --support-old-code                 Support interworking with old code\n"));
240   fprintf (file, _("  --thumb-entry=<symbol>             Set the entry point to be Thumb <symbol>\n"));
241 #ifdef DLL_SUPPORT
242   fprintf (file, _("  --add-stdcall-alias                Export symbols with and without @nn\n"));
243   fprintf (file, _("  --disable-stdcall-fixup            Don't link _sym to _sym@nn\n"));
244   fprintf (file, _("  --enable-stdcall-fixup             Link _sym to _sym@nn without warnings\n"));
245   fprintf (file, _("  --exclude-symbols sym,sym,...      Exclude symbols from automatic export\n"));
246   fprintf (file, _("  --export-all-symbols               Automatically export all globals to DLL\n"));
247   fprintf (file, _("  --kill-at                          Remove @nn from exported symbols\n"));
248   fprintf (file, _("  --out-implib <file>                Generate import library\n"));
249   fprintf (file, _("  --output-def <file>                Generate a .DEF file for the built DLL\n"));
250 #endif
253 static void
254 set_pe_name (name, val)
255      char *name;
256      long val;
258   int i;
259   /* Find the name and set it. */
260   for (i = 0; init[i].ptr; i++)
261     {
262       if (strcmp (name, init[i].symbol) == 0)
263         {
264           init[i].value = val;
265           init[i].inited = 1;
266           return;
267         }
268     }
269   abort();
273 static void
274 set_pe_subsystem ()
276   const char *sver;
277   int len;
278   int i;
279   static const struct 
280     {
281       const char *name;
282       const int value;
283       const char *entry;
284     }
285   v[] =
286     {
287       { "native", 1, "NtProcessStartup" },
288       { "windows", 2, "WinMainCRTStartup" },
289       { "console", 3, "mainCRTStartup" },
290 #if 0
291       /* The Microsoft linker does not recognize this.  */
292       { "os2", 5, "" },
293 #endif
294       { "posix", 7, "__PosixProcessStartup"},
295       { 0, 0, 0 }
296     };
298   sver = strchr (optarg, ':');
299   if (sver == NULL)
300     len = strlen (optarg);
301   else
302     {
303       char *end;
305       len = sver - optarg;
306       set_pe_name ("__major_subsystem_version__",
307                    strtoul (sver + 1, &end, 0));
308       if (*end == '.')
309         set_pe_name ("__minor_subsystem_version__",
310                      strtoul (end + 1, &end, 0));
311       if (*end != '\0')
312         einfo (_("%P: warning: bad version number in -subsystem option\n"));
313     }
315   for (i = 0; v[i].name; i++)
316     {
317       if (strncmp (optarg, v[i].name, len) == 0
318           && v[i].name[len] == '\0')
319         {
320           const char *initial_symbol_char;
321           const char *entry;
323           set_pe_name ("__subsystem__", v[i].value);
325           initial_symbol_char = ${INITIAL_SYMBOL_CHAR};
326           if (*initial_symbol_char == '\0')
327             entry = v[i].entry;
328           else
329             {
330               char *alc_entry;
332               /* lang_add_entry expects its argument to be permanently
333                  allocated, so we don't free this string.  */
334               alc_entry = xmalloc (strlen (initial_symbol_char)
335                                    + strlen (v[i].entry)
336                                    + 1);
337               strcpy (alc_entry, initial_symbol_char);
338               strcat (alc_entry, v[i].entry);
339               entry = alc_entry;
340             }
342           lang_add_entry (entry, 1);
344           return;
345         }
346     }
347   
348   einfo (_("%P%F: invalid subsystem type %s\n"), optarg);
353 static void
354 set_pe_value (name)
355      char *name;
356      
358   char *end;
359   
360   set_pe_name (name,  strtoul (optarg, &end, 0));
361   
362   if (end == optarg)
363     einfo (_("%P%F: invalid hex number for PE parameter '%s'\n"), optarg);
365   optarg = end;
368 static void
369 set_pe_stack_heap (resname, comname)
370      char *resname;
371      char *comname;
373   set_pe_value (resname);
374   
375   if (*optarg == ',')
376     {
377       optarg++;
378       set_pe_value (comname);
379     }
380   else if (*optarg)
381     einfo (_("%P%F: strange hex info for PE parameter '%s'\n"), optarg);
386 static int
387 gld_${EMULATION_NAME}_parse_args(argc, argv)
388      int argc;
389      char **argv;
391   int longind;
392   int optc;
393   int prevoptind = optind;
394   int prevopterr = opterr;
395   int wanterror;
396   static int lastoptind = -1;
398   if (lastoptind != optind)
399     opterr = 0;
400   wanterror = opterr;
402   lastoptind = optind;
404   optc = getopt_long_only (argc, argv, "-", longopts, &longind);
405   opterr = prevopterr;
407   switch (optc)
408     {
409     default:
410       if (wanterror)
411         xexit (1);
412       optind =  prevoptind;
413       return 0;
415     case OPTION_BASE_FILE:
416       link_info.base_file = (PTR) fopen (optarg, FOPEN_WB);
417       if (link_info.base_file == NULL)
418         {
419           /* xgettext:c-format */
420           fprintf (stderr, _("%s: Can't open base file %s\n"),
421                    program_name, optarg);
422           xexit (1);
423         }
424       break;
426       /* PE options */
427     case OPTION_HEAP: 
428       set_pe_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
429       break;
430     case OPTION_STACK: 
431       set_pe_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
432       break;
433     case OPTION_SUBSYSTEM:
434       set_pe_subsystem ();
435       break;
436     case OPTION_MAJOR_OS_VERSION:
437       set_pe_value ("__major_os_version__");
438       break;
439     case OPTION_MINOR_OS_VERSION:
440       set_pe_value ("__minor_os_version__");
441       break;
442     case OPTION_MAJOR_SUBSYSTEM_VERSION:
443       set_pe_value ("__major_subsystem_version__");
444       break;
445     case OPTION_MINOR_SUBSYSTEM_VERSION:
446       set_pe_value ("__minor_subsystem_version__");
447       break;
448     case OPTION_MAJOR_IMAGE_VERSION:
449       set_pe_value ("__major_image_version__");
450       break;
451     case OPTION_MINOR_IMAGE_VERSION:
452       set_pe_value ("__minor_image_version__");
453       break;
454     case OPTION_FILE_ALIGNMENT:
455       set_pe_value ("__file_alignment__");
456       break;
457     case OPTION_SECTION_ALIGNMENT:
458       set_pe_value ("__section_alignment__");
459       break;
460     case OPTION_DLL:
461       set_pe_name ("__dll__", 1);
462       break;
463     case OPTION_IMAGE_BASE:
464       set_pe_value ("__image_base__");
465       break;
466     case OPTION_SUPPORT_OLD_CODE:
467       support_old_code = 1;
468       break;
469     case OPTION_THUMB_ENTRY:
470       thumb_entry_symbol = optarg;
471       break;
472 #ifdef DLL_SUPPORT
473     case OPTION_OUT_DEF:
474       pe_out_def_filename = xstrdup (optarg);
475       break;
476     case OPTION_EXPORT_ALL:
477       pe_dll_export_everything = 1;
478       break;
479     case OPTION_EXCLUDE_SYMBOLS:
480       pe_dll_add_excludes (optarg);
481       break;
482     case OPTION_KILL_ATS:
483       pe_dll_kill_ats = 1;
484       break;
485     case OPTION_STDCALL_ALIASES:
486       pe_dll_stdcall_aliases = 1;
487       break;
488     case OPTION_ENABLE_STDCALL_FIXUP:
489       pe_enable_stdcall_fixup = 1;
490       break;
491     case OPTION_DISABLE_STDCALL_FIXUP:
492       pe_enable_stdcall_fixup = 0;
493       break;
494     case OPTION_IMPLIB_FILENAME:
495       pe_implib_filename = xstrdup (optarg);
496       break;
497     case OPTION_WARN_DUPLICATE_EXPORTS:
498       pe_dll_warn_dup_exports = 1;
499       break;
500     case OPTION_IMP_COMPAT:
501       pe_dll_compat_implib = 1;
502       break;
503 #endif
504     }
505   return 1;
508 /* Assign values to the special symbols before the linker script is
509    read.  */
511 static void
512 gld_${EMULATION_NAME}_set_symbols ()
514   /* Run through and invent symbols for all the
515      names and insert the defaults. */
516   int j;
517   lang_statement_list_type *save;
519   if (!init[IMAGEBASEOFF].inited)
520     {
521       if (link_info.relocateable)
522         init[IMAGEBASEOFF].value = 0;
523       else if (init[DLLOFF].value || link_info.shared)
524         init[IMAGEBASEOFF].value = NT_DLL_IMAGE_BASE;
525       else
526         init[IMAGEBASEOFF].value = NT_EXE_IMAGE_BASE;
527     }
529   /* Don't do any symbol assignments if this is a relocateable link.  */
530   if (link_info.relocateable)
531     return;
533   /* Glue the assignments into the abs section */
534   save = stat_ptr;
536   stat_ptr = &(abs_output_section->children);
538   for (j = 0; init[j].ptr; j++)
539     {
540       long val = init[j].value;
541       lang_assignment_statement_type *rv;
542       rv = lang_add_assignment (exp_assop ('=' ,init[j].symbol, exp_intop (val)));
543       if (init[j].size == sizeof(short))
544         *(short *)init[j].ptr = val;
545       else if (init[j].size == sizeof(int))
546         *(int *)init[j].ptr = val;
547       else if (init[j].size == sizeof(long))
548         *(long *)init[j].ptr = val;
549       /* This might be a long long or other special type.  */
550       else if (init[j].size == sizeof(bfd_vma))
551         *(bfd_vma *)init[j].ptr = val;
552       else      abort();
553       if (j == IMAGEBASEOFF)
554         image_base_statement = rv;
555     }
556   /* Restore the pointer. */
557   stat_ptr = save;
558   
559   if (pe.FileAlignment >
560       pe.SectionAlignment)
561     {
562       einfo (_("%P: warning, file alignment > section alignment.\n"));
563     }
566 /* This is called after the linker script and the command line options
567    have been read.  */
569 static void
570 gld_${EMULATION_NAME}_after_parse ()
572   /* The Windows libraries are designed for the linker to treat the
573      entry point as an undefined symbol.  Otherwise, the .obj that
574      defines mainCRTStartup is brought in because it is the first
575      encountered in libc.lib and it has other symbols in it which will
576      be pulled in by the link process.  To avoid this, we act as
577      though the user specified -u with the entry point symbol.
579      This function is called after the linker script and command line
580      options have been read, so at this point we know the right entry
581      point.  This function is called before the input files are
582      opened, so registering the symbol as undefined will make a
583      difference.  */
585   if (! link_info.relocateable && entry_symbol != NULL)
586     ldlang_add_undef (entry_symbol);
589 static struct bfd_link_hash_entry *pe_undef_found_sym;
591 static boolean
592 pe_undef_cdecl_match (h, string)
593   struct bfd_link_hash_entry *h;
594   PTR string;
596   int sl = strlen (string);
597   if (h->type == bfd_link_hash_defined
598       && strncmp (h->root.string, string, sl) == 0
599       && h->root.string[sl] == '@')
600   {
601     pe_undef_found_sym = h;
602     return false;
603   }
604   return true;
607 static void
608 pe_fixup_stdcalls ()
610   static int gave_warning_message = 0;
611   struct bfd_link_hash_entry *undef, *sym;
612   char *at;
613   for (undef = link_info.hash->undefs; undef; undef=undef->next)
614     if (undef->type == bfd_link_hash_undefined)
615     {
616       at = strchr (undef->root.string, '@');
617       if (at)
618       {
619         /* The symbol is a stdcall symbol, so let's look for a cdecl
620            symbol with the same name and resolve to that */
621         char *cname = xstrdup (undef->root.string);
622         at = strchr (cname, '@');
623         *at = 0;
624         sym = bfd_link_hash_lookup (link_info.hash, cname, 0, 0, 1);
625         if (sym && sym->type == bfd_link_hash_defined)
626         {
627           undef->type = bfd_link_hash_defined;
628           undef->u.def.value = sym->u.def.value;
629           undef->u.def.section = sym->u.def.section;
630           if (pe_enable_stdcall_fixup == -1)
631             {
632               einfo (_("Warning: resolving %s by linking to %s\n"),
633                      undef->root.string, cname);
634               if (! gave_warning_message)
635                 {
636                   gave_warning_message = 1;
637                   einfo(_("Use --enable-stdcall-fixup to disable these warnings\n"));
638                   einfo(_("Use --disable-stdcall-fixup to disable these fixups\n"));
639                 }
640             }
641         }
642       }
643       else
644       {
645         /* The symbol is a cdecl symbol, so we look for stdcall
646            symbols - which means scanning the whole symbol table */
647         pe_undef_found_sym = 0;
648         bfd_link_hash_traverse (link_info.hash, pe_undef_cdecl_match,
649                                 (PTR) undef->root.string);
650         sym = pe_undef_found_sym;
651         if (sym)
652         {
653           undef->type = bfd_link_hash_defined;
654           undef->u.def.value = sym->u.def.value;
655           undef->u.def.section = sym->u.def.section;
656           if (pe_enable_stdcall_fixup == -1)
657             {
658               einfo (_("Warning: resolving %s by linking to %s\n"),
659                      undef->root.string, sym->root.string);
660               if (! gave_warning_message)
661                 {
662                   gave_warning_message = 1;
663                   einfo(_("Use --enable-stdcall-fixup to disable these warnings\n"));
664                   einfo(_("Use --disable-stdcall-fixup to disable these fixups\n"));
665                 }
666             }
667         }
668       }
669     }
672 static void
673 gld_${EMULATION_NAME}_after_open ()
675   /* Pass the wacky PE command line options into the output bfd.
676      FIXME: This should be done via a function, rather than by
677      including an internal BFD header.  */
678   
679   if (!coff_data (output_bfd)->pe)
680     einfo (_("%F%P: PE operations on non PE file.\n"));
682   pe_data (output_bfd)->pe_opthdr = pe;
683   pe_data (output_bfd)->dll = init[DLLOFF].value;
685 #ifdef DLL_SUPPORT
686   if (pe_enable_stdcall_fixup) /* -1=warn or 1=disable */
687     pe_fixup_stdcalls ();
689   pe_process_import_defs(output_bfd, &link_info);
690   if (link_info.shared)
691     pe_dll_build_sections (output_bfd, &link_info);
692 #endif
694 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_epoc_pe)
695   if (strstr (bfd_get_target (output_bfd), "arm") == NULL)
696     {
697       /* The arm backend needs special fields in the output hash structure.
698          These will only be created if the output format is an arm format,
699          hence we do not support linking and changing output formats at the
700          same time.  Use a link followed by objcopy to change output formats.  */
701       einfo ("%F%X%P: error: cannot change output format whilst linking ARM binaries\n");
702       return;
703     }
704   {
705     /* Find a BFD that can hold the interworking stubs.  */
706     LANG_FOR_EACH_INPUT_STATEMENT (is)
707       {
708         if (bfd_arm_pe_get_bfd_for_interworking (is->the_bfd, & link_info))
709           break;
710       }
711   }
712 #endif
714   {
715     int is_ms_arch;
716     bfd *cur_arch = 0;
717     lang_input_statement_type *is2;
719     /* Careful - this is a shell script.  Watch those dollar signs! */
720     /* Microsoft import libraries have every member named the same,
721        and not in the right order for us to link them correctly.  We
722        must detect these and rename the members so that they'll link
723        correctly.  There are three types of objects: the head, the
724        thunks, and the sentinel(s).  The head is easy; it's the one
725        with idata2.  We assume that the sentinels won't have relocs,
726        and the thunks will.  It's easier than checking the symbol
727        table for external references.  */
728     LANG_FOR_EACH_INPUT_STATEMENT (is)
729       {
730         if (is->the_bfd->my_archive)
731           {
732             bfd *arch = is->the_bfd->my_archive;
733             if (cur_arch != arch)
734               {
735                 cur_arch = arch;
736                 is_ms_arch = 1;
737                 for (is2 = is;
738                      is2 && is2->the_bfd->my_archive == arch;
739                      is2 = (lang_input_statement_type *)is2->next)
740                   {
741                     if (strcmp (is->the_bfd->filename, is2->the_bfd->filename))
742                       is_ms_arch = 0;
743                   }
744               }
746             if (is_ms_arch)
747               {
748                 int idata2 = 0, reloc_count=0;
749                 asection *sec;
750                 char *new_name, seq;
752                 for (sec = is->the_bfd->sections; sec; sec = sec->next)
753                   {
754                     if (strcmp (sec->name, ".idata\$2") == 0)
755                       idata2 = 1;
756                     reloc_count += sec->reloc_count;
757                   }
759                 if (idata2) /* .idata2 is the TOC */
760                   seq = 'a';
761                 else if (reloc_count > 0) /* thunks */
762                   seq = 'b';
763                 else /* sentinel */
764                   seq = 'c';
766                 new_name = xmalloc (strlen (is->the_bfd->filename) + 3);
767                 sprintf (new_name, "%s.%c", is->the_bfd->filename, seq);
768                 is->the_bfd->filename = new_name;
770                 new_name = xmalloc (strlen(is->filename) + 3);
771                 sprintf (new_name, "%s.%c", is->filename, seq);
772                 is->filename = new_name;
773               }
774           }
775       }
776   }
779 static void  
780 gld_${EMULATION_NAME}_before_allocation()
782 #ifdef TARGET_IS_ppcpe
783   /* Here we rummage through the found bfds to collect toc information */
784   {
785     LANG_FOR_EACH_INPUT_STATEMENT (is)
786       {
787         if (!ppc_process_before_allocation (is->the_bfd, &link_info))
788           {
789             /* xgettext:c-format */
790             einfo (_("Errors encountered processing file %s\n"), is->filename);
791           }
792       }
793   }
795   /* We have seen it all. Allocate it, and carry on */
796   ppc_allocate_toc_section (&link_info);
797 #endif /* TARGET_IS_ppcpe */
799 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_epoc_pe)
800   /* FIXME: we should be able to set the size of the interworking stub
801      section.
803      Here we rummage through the found bfds to collect glue
804      information.  FIXME: should this be based on a command line
805      option?  krk@cygnus.com */
806   {
807     LANG_FOR_EACH_INPUT_STATEMENT (is)
808       {
809         if (! bfd_arm_pe_process_before_allocation
810             (is->the_bfd, & link_info, support_old_code))
811           {
812             /* xgettext:c-format */
813             einfo (_("Errors encountered processing file %s for interworking"),
814                    is->filename);
815           }
816       }
817   }
819   /* We have seen it all. Allocate it, and carry on */
820   bfd_arm_pe_allocate_interworking_sections (& link_info);
821 #endif /* TARGET_IS_armpe */
825 /* This is called when an input file isn't recognized as a BFD.  We
826    check here for .DEF files and pull them in automatically. */
828 static int
829 saw_option(char *option)
831   int i;
832   for (i=0; init[i].ptr; i++)
833     if (strcmp (init[i].symbol, option) == 0)
834       return init[i].inited;
835   return 0;
838 static boolean
839 gld_${EMULATION_NAME}_unrecognized_file(entry)
840   lang_input_statement_type *entry;
842 #ifdef DLL_SUPPORT
843   const char *ext = entry->filename + strlen (entry->filename) - 4;
845   if (strcmp (ext, ".def") == 0 || strcmp (ext, ".DEF") == 0)
846   {
847     if (pe_def_file == 0)
848       pe_def_file = def_file_empty ();
849     def_file_parse (entry->filename, pe_def_file);
850     if (pe_def_file)
851     {
852       int i, buflen=0, len;
853       char *buf;
854       for (i=0; i<pe_def_file->num_exports; i++)
855         {
856           len = strlen(pe_def_file->exports[i].internal_name);
857           if (buflen < len+2)
858             buflen = len+2;
859         }
860       buf = (char *) xmalloc (buflen);
861       for (i=0; i<pe_def_file->num_exports; i++)
862         {
863           struct bfd_link_hash_entry *h;
864           sprintf(buf, "_%s", pe_def_file->exports[i].internal_name);
866           h = bfd_link_hash_lookup (link_info.hash, buf, true, true, true);
867           if (h == (struct bfd_link_hash_entry *) NULL)
868             einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
869           if (h->type == bfd_link_hash_new)
870             {
871               h->type = bfd_link_hash_undefined;
872               h->u.undef.abfd = NULL;
873               bfd_link_add_undef (link_info.hash, h);
874             }
875         }
876       free (buf);
878       /* def_file_print (stdout, pe_def_file); */
879       if (pe_def_file->is_dll == 1)
880         link_info.shared = 1;
882       if (pe_def_file->base_address != (bfd_vma)(-1))
883       {
884         pe.ImageBase =
885         pe_data (output_bfd)->pe_opthdr.ImageBase =
886         init[IMAGEBASEOFF].value = pe_def_file->base_address;
887         init[IMAGEBASEOFF].inited = 1;
888         if (image_base_statement)
889           image_base_statement->exp =
890             exp_assop ('=', "__image_base__", exp_intop (pe.ImageBase));
891       }
893 #if 0
894       /* Not sure if these *should* be set */
895       if (pe_def_file->version_major != -1)
896       {
897         pe.MajorImageVersion = pe_def_file->version_major;
898         pe.MinorImageVersion = pe_def_file->version_minor;
899       }
900 #endif
901       if (pe_def_file->stack_reserve != -1
902           && ! saw_option ("__size_of_stack_reserve__"))
903       {
904         pe.SizeOfStackReserve = pe_def_file->stack_reserve;
905         if (pe_def_file->stack_commit != -1)
906           pe.SizeOfStackCommit = pe_def_file->stack_commit;
907       }
908       if (pe_def_file->heap_reserve != -1
909           && ! saw_option ("__size_of_heap_reserve__"))
910       {
911         pe.SizeOfHeapReserve = pe_def_file->heap_reserve;
912         if (pe_def_file->heap_commit != -1)
913           pe.SizeOfHeapCommit = pe_def_file->heap_commit;
914       }
915       return true;
916     }
917   }
918 #endif
919   return false;
920   
923 static boolean
924 gld_${EMULATION_NAME}_recognized_file(entry)
925   lang_input_statement_type *entry;
927 #ifdef DLL_SUPPORT
928 #ifdef TARGET_IS_i386pe
929   pe_dll_id_target ("pei-i386");
930 #endif
931   if (bfd_get_format (entry->the_bfd) == bfd_object)
932     {
933       const char *ext = entry->filename + strlen (entry->filename) - 4;
934       if (strcmp (ext, ".dll") == 0 || strcmp (ext, ".DLL") == 0)
935         return pe_implied_import_dll (entry->filename);
936     }
937 #endif
938   return false;
941 static void
942 gld_${EMULATION_NAME}_finish ()
944 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_epoc_pe)
945   struct bfd_link_hash_entry * h;
947   if (thumb_entry_symbol != NULL)
948     {
949       h = bfd_link_hash_lookup (link_info.hash, thumb_entry_symbol, false, false, true);
950       
951       if (h != (struct bfd_link_hash_entry *) NULL
952           && (h->type == bfd_link_hash_defined
953               || h->type == bfd_link_hash_defweak)
954           && h->u.def.section->output_section != NULL)
955         {
956           static char buffer[32];
957           bfd_vma val;
958           
959           /* Special procesing is required for a Thumb entry symbol.  The
960              bottom bit of its address must be set.  */
961           val = (h->u.def.value
962                  + bfd_get_section_vma (output_bfd,
963                                         h->u.def.section->output_section)
964                  + h->u.def.section->output_offset);
965           
966           val |= 1;
967           
968           /* Now convert this value into a string and store it in entry_symbol
969              where the lang_finish() function will pick it up.  */
970           buffer[0] = '0';
971           buffer[1] = 'x';
972           
973           sprintf_vma (buffer + 2, val);
974           
975           if (entry_symbol != NULL && entry_from_cmdline)
976             einfo (_("%P: warning: '--thumb-entry %s' is overriding '-e %s'\n"),
977                    thumb_entry_symbol, entry_symbol);
978           entry_symbol = buffer;
979         }
980       else
981         einfo (_("%P: warning: connot find thumb start symbol %s\n"), thumb_entry_symbol);
982     }
983 #endif /* defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_epoc_pe) */
985 #ifdef DLL_SUPPORT
986   if (link_info.shared)
987     {
988       pe_dll_fill_sections (output_bfd, &link_info);
989       if (pe_implib_filename)
990         pe_dll_generate_implib (pe_def_file, pe_implib_filename);
991     }
992   if (pe_out_def_filename)
993     pe_dll_generate_def_file (pe_out_def_filename);
994 #endif
998 /* Place an orphan section.
1000    We use this to put sections in a reasonable place in the file, and
1001    to ensure that they are aligned as required.
1003    We handle grouped sections here as well.  A section named .foo$nn
1004    goes into the output section .foo.  All grouped sections are sorted
1005    by name.
1007    Grouped sections for the default sections are handled by the
1008    default linker script using wildcards, and are sorted by
1009    sort_sections.  */
1011 static asection *hold_section;
1012 static char *hold_section_name;
1013 static lang_output_section_statement_type *hold_use;
1014 static lang_output_section_statement_type *hold_text;
1015 static lang_output_section_statement_type *hold_rdata;
1016 static lang_output_section_statement_type *hold_data;
1017 static lang_output_section_statement_type *hold_bss;
1019 /* Place an orphan section.  We use this to put random SHF_ALLOC
1020    sections in the right segment.  */
1022 /*ARGSUSED*/
1023 static boolean
1024 gld_${EMULATION_NAME}_place_orphan (file, s)
1025      lang_input_statement_type *file;
1026      asection *s;
1028   const char *secname;
1029   char *dollar;
1031   if ((s->flags & SEC_ALLOC) == 0)
1032     return false;
1034   secname = bfd_get_section_name (s->owner, s);
1036   /* Look through the script to see where to place this section.  */
1038   hold_section = s;
1040   hold_section_name = xstrdup (secname);
1041   if (!link_info.relocateable)
1042     {
1043       dollar = strchr (hold_section_name, '$');
1044       if (dollar != NULL)
1045         *dollar = '\0';
1046     }
1048   hold_use = NULL;
1049   lang_for_each_statement (gld${EMULATION_NAME}_place_section);
1051   if (hold_use == NULL)
1052     {
1053       lang_output_section_statement_type *place;
1054       char *outsecname;
1055       asection *snew, **pps;
1056       lang_statement_list_type *old;
1057       lang_statement_list_type add;
1058       etree_type *address;
1060       /* Try to put the new output section in a reasonable place based
1061          on the section name and section flags.  */
1062       place = NULL;
1063       if ((s->flags & SEC_HAS_CONTENTS) == 0
1064           && hold_bss != NULL)
1065         place = hold_bss;
1066       else if ((s->flags & SEC_READONLY) == 0
1067                && hold_data != NULL)
1068         place = hold_data;
1069       else if ((s->flags & SEC_CODE) == 0
1070                && (s->flags & SEC_READONLY) != 0
1071                && hold_rdata != NULL)
1072         place = hold_rdata;
1073       else if ((s->flags & SEC_READONLY) != 0
1074                && hold_text != NULL)
1075         place = hold_text;
1077       /* Choose a unique name for the section.  This will be needed if
1078          the same section name appears in the input file with
1079          different loadable or allocateable characteristics.  */
1080       outsecname = xstrdup (hold_section_name);
1081       if (bfd_get_section_by_name (output_bfd, outsecname) != NULL)
1082         {
1083           unsigned int len;
1084           char *newname;
1085           unsigned int i;
1087           len = strlen (outsecname);
1088           newname = xmalloc (len + 5);
1089           strcpy (newname, outsecname);
1090           i = 0;
1091           do
1092             {
1093               sprintf (newname + len, "%d", i);
1094               ++i;
1095             }
1096           while (bfd_get_section_by_name (output_bfd, newname) != NULL);
1098           free (outsecname);
1099           outsecname = newname;
1100         }
1102       /* We don't want to free OUTSECNAME, as it may get attached to
1103          the output section statement.  */
1105       /* Create the section in the output file, and put it in the
1106          right place.  This shuffling is to make the output file look
1107          neater.  */
1108       snew = bfd_make_section (output_bfd, outsecname);
1109       if (snew == NULL)
1110         einfo ("%P%F: output format %s cannot represent section called %s\n",
1111                output_bfd->xvec->name, outsecname);
1112       if (place != NULL && place->bfd_section != NULL)
1113         {
1114           for (pps = &output_bfd->sections; *pps != snew; pps = &(*pps)->next)
1115             ;
1116           *pps = snew->next;
1117           snew->next = place->bfd_section->next;
1118           place->bfd_section->next = snew;
1119         }
1121       /* Start building a list of statements for this section.  */
1122       old = stat_ptr;
1123       stat_ptr = &add;
1124       lang_list_init (stat_ptr);
1126       if (link_info.relocateable)
1127         address = NULL;
1128       else
1129         {
1130           /* All sections in an executable must be aligned to a page
1131              boundary.  */
1132           address = exp_unop (ALIGN_K,
1133                               exp_nameop (NAME, "__section_alignment__"));
1134         }
1136       lang_enter_output_section_statement (outsecname, address, 0,
1137                                            (bfd_vma) 0,
1138                                            (etree_type *) NULL,
1139                                            (etree_type *) NULL,
1140                                            (etree_type *) NULL);
1142       hold_use = lang_output_section_statement_lookup (outsecname);
1144       lang_leave_output_section_statement
1145         ((bfd_vma) 0, "*default*",
1146          (struct lang_output_section_phdr_list *) NULL);
1148       /* Now stick the new statement list right after PLACE.  */
1149       if (place != NULL)
1150         {
1151           *add.tail = place->header.next;
1152           place->header.next = add.head;
1153         }
1155       stat_ptr = old;
1156     }
1158   if (dollar == NULL)
1159     wild_doit (&hold_use->children, s, hold_use, file);
1160   else
1161     {
1162       lang_statement_union_type **pl;
1163       boolean found_dollar;
1164       lang_statement_list_type list;
1166       /* The section name has a '$'.  Sort it with the other '$'
1167          sections.  */
1169       found_dollar = false;
1170       for (pl = &hold_use->children.head; *pl != NULL; pl = &(*pl)->next)
1171         {
1172           lang_input_section_type *ls;
1173           const char *lname;
1175           if ((*pl)->header.type != lang_input_section_enum)
1176             continue;
1178           ls = &(*pl)->input_section;
1180           lname = bfd_get_section_name (ls->ifile->the_bfd, ls->section);
1181           if (strchr (lname, '$') == NULL)
1182             {
1183               if (found_dollar)
1184                 break;
1185             }
1186           else
1187             {
1188               found_dollar = true;
1189               if (strcmp (secname, lname) < 0)
1190                 break;
1191             }
1192         }
1194       lang_list_init (&list);
1195       wild_doit (&list, s, hold_use, file);
1196       if (list.head != NULL)
1197         {
1198           ASSERT (list.head->next == NULL);
1199           list.head->next = *pl;
1200           *pl = list.head;
1201         }
1202     }
1204   free (hold_section_name);
1206   return true;
1209 static void
1210 gld${EMULATION_NAME}_place_section (s)
1211      lang_statement_union_type *s;
1213   lang_output_section_statement_type *os;
1215   if (s->header.type != lang_output_section_statement_enum)
1216     return;
1218   os = &s->output_section_statement;
1220   if (strcmp (os->name, hold_section_name) == 0
1221       && os->bfd_section != NULL
1222       && ((hold_section->flags & (SEC_LOAD | SEC_ALLOC))
1223           == (os->bfd_section->flags & (SEC_LOAD | SEC_ALLOC))))
1224     hold_use = os;
1226   if (strcmp (os->name, ".text") == 0)
1227     hold_text = os;
1228   else if (strcmp (os->name, ".rdata") == 0)
1229     hold_rdata = os;
1230   else if (strcmp (os->name, ".data") == 0)
1231     hold_data = os;
1232   else if (strcmp (os->name, ".bss") == 0)
1233     hold_bss = os;
1236 static char *
1237 gld_${EMULATION_NAME}_get_script(isfile)
1238      int *isfile;
1240 # Scripts compiled in.
1241 # sed commands to quote an ld script as a C string.
1242 sc="-f stringify.sed"
1244 cat >>e${EMULATION_NAME}.c <<EOF
1245 {                            
1246   *isfile = 0;
1248   if (link_info.relocateable == true && config.build_constructors == true)
1249     return
1251 sed $sc ldscripts/${EMULATION_NAME}.xu                     >> e${EMULATION_NAME}.c
1252 echo '  ; else if (link_info.relocateable == true) return' >> e${EMULATION_NAME}.c
1253 sed $sc ldscripts/${EMULATION_NAME}.xr                     >> e${EMULATION_NAME}.c
1254 echo '  ; else if (!config.text_read_only) return'         >> e${EMULATION_NAME}.c
1255 sed $sc ldscripts/${EMULATION_NAME}.xbn                    >> e${EMULATION_NAME}.c
1256 echo '  ; else if (!config.magic_demand_paged) return'     >> e${EMULATION_NAME}.c
1257 sed $sc ldscripts/${EMULATION_NAME}.xn                     >> e${EMULATION_NAME}.c
1258 echo '  ; else return'                                     >> e${EMULATION_NAME}.c
1259 sed $sc ldscripts/${EMULATION_NAME}.x                      >> e${EMULATION_NAME}.c
1260 echo '; }'                                                 >> e${EMULATION_NAME}.c
1262 cat >>e${EMULATION_NAME}.c <<EOF
1265 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation = 
1267   gld_${EMULATION_NAME}_before_parse,
1268   syslib_default,
1269   hll_default,
1270   gld_${EMULATION_NAME}_after_parse,
1271   gld_${EMULATION_NAME}_after_open,
1272   after_allocation_default,
1273   set_output_arch_default,
1274   ldemul_default_target,
1275   gld_${EMULATION_NAME}_before_allocation,
1276   gld_${EMULATION_NAME}_get_script,
1277   "${EMULATION_NAME}",
1278   "${OUTPUT_FORMAT}",
1279   gld_${EMULATION_NAME}_finish, /* finish */
1280   NULL, /* create output section statements */
1281   NULL, /* open dynamic archive */
1282   gld_${EMULATION_NAME}_place_orphan,
1283   gld_${EMULATION_NAME}_set_symbols,
1284   gld_${EMULATION_NAME}_parse_args,
1285   gld_${EMULATION_NAME}_unrecognized_file,
1286   gld_${EMULATION_NAME}_list_options,
1287   gld_${EMULATION_NAME}_recognized_file