1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 if [ -z "$MACHINE" ]; then
6 OUTPUT_ARCH=${ARCH}:${MACHINE}
9 /* This file is part of GLD, the Gnu Linker.
10 Copyright (C) 1995-2024 Free Software Foundation, Inc.
12 This file is part of the GNU Binutils.
14 This program is free software; you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation; either version 3 of the License, or
17 (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
24 You should have received a copy of the GNU General Public License
25 along with this program; if not, write to the Free Software
26 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
27 MA 02110-1301, USA. */
31 /* The original file generated returned different default scripts depending
32 on whether certain switches were set, but these switches pertain to the
33 Linux system and that particular version of coff. In the NT case, we
34 only determine if the subsystem is console or windows in order to select
35 the correct entry point by default. */
42 #include "libiberty.h"
43 #include "filenames.h"
54 #include "coff/internal.h"
55 #include "../bfd/libcoff.h"
57 #define TARGET_IS_${EMULATION_NAME}
59 static struct internal_extra_pe_aouthdr pe;
62 extern const char *output_filename;
65 gld${EMULATION_NAME}_before_parse (void)
67 ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
68 output_filename = "a.exe";
71 /* PE format extra command line options. */
74 gld${EMULATION_NAME}_add_options
75 (int ns ATTRIBUTE_UNUSED, char **shortopts ATTRIBUTE_UNUSED, int nl,
76 struct option **longopts, int nrl ATTRIBUTE_UNUSED,
77 struct option **really_longopts ATTRIBUTE_UNUSED)
79 static const struct option xtra_long[] = {
81 {"base-file", required_argument, NULL, OPTION_BASE_FILE},
82 {"dll", no_argument, NULL, OPTION_DLL},
83 {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
84 {"heap", required_argument, NULL, OPTION_HEAP},
85 {"image-base", required_argument, NULL, OPTION_IMAGE_BASE},
86 {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
87 {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
88 {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
89 {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
90 {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
91 {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
92 {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
93 {"stack", required_argument, NULL, OPTION_STACK},
94 {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
95 {NULL, no_argument, NULL, 0}
98 *longopts = (struct option *)
99 xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
100 memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
104 /* PE/WIN32; added routines to get the subsystem type, heap and/or stack
105 parameters which may be input from the command line */
115 #define D(field,symbol,def) {&pe.field,sizeof(pe.field), def, symbol,0}
117 static definfo init[] =
119 /* imagebase must be first */
120 #define IMAGEBASEOFF 0
121 D(ImageBase,"__image_base__", BEOS_EXE_IMAGE_BASE),
123 {&dll, sizeof(dll), 0, "__dll__", 0},
124 D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT),
125 D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT),
126 D(MajorOperatingSystemVersion,"__major_os_version__", 4),
127 D(MinorOperatingSystemVersion,"__minor_os_version__", 0),
128 D(MajorImageVersion,"__major_image_version__", 1),
129 D(MinorImageVersion,"__minor_image_version__", 0),
130 D(MajorSubsystemVersion,"__major_subsystem_version__", 4),
131 D(MinorSubsystemVersion,"__minor_subsystem_version__", 0),
132 D(Subsystem,"__subsystem__", 3),
133 D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x2000000),
134 D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000),
135 D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000),
136 D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000),
137 D(LoaderFlags,"__loader_flags__", 0x0),
138 { NULL, 0, 0, NULL, 0 }
143 set_pe_name (char *name, long val)
146 /* Find the name and set it. */
147 for (i = 0; init[i].ptr; i++)
149 if (strcmp (name, init[i].symbol) == 0)
161 set_pe_subsystem (void)
174 { "native", 1, "_NtProcessStartup" },
175 { "windows", 2, "_WinMainCRTStartup" },
176 { "wwindows", 2, "_wWinMainCRTStartup" },
177 { "console", 3, "_mainCRTStartup" },
178 { "wconsole", 3, "_wmainCRTStartup" },
179 { "posix", 7, "___PosixProcessStartup"},
183 sver = strchr (optarg, ':');
185 len = strlen (optarg);
191 set_pe_name ("__major_subsystem_version__",
192 strtoul (sver + 1, &end, 0));
194 set_pe_name ("__minor_subsystem_version__",
195 strtoul (end + 1, &end, 0));
197 einfo (_("%P: warning: bad version number in -subsystem option\n"));
200 for (i = 0; v[i].name; i++)
202 if (strncmp (optarg, v[i].name, len) == 0
203 && v[i].name[len] == '\0')
205 set_pe_name ("__subsystem__", v[i].value);
207 /* If the subsystem is windows, we use a different entry
209 lang_default_entry (v[i].entry);
214 einfo (_("%F%P: invalid subsystem type %s\n"), optarg);
219 set_pe_value (char *name)
222 set_pe_name (name, strtoul (optarg, &end, 0));
225 einfo (_("%F%P: invalid hex number for PE parameter '%s'\n"), optarg);
232 set_pe_stack_heap (char *resname, char *comname)
234 set_pe_value (resname);
238 set_pe_value (comname);
242 einfo (_("%F%P: strange hex info for PE parameter '%s'\n"), optarg);
248 gld${EMULATION_NAME}_handle_option (int optc)
255 case OPTION_BASE_FILE:
256 link_info.base_file = fopen (optarg, FOPEN_WB);
257 if (link_info.base_file == NULL)
258 einfo (_("%F%P: cannot open base file %s\n"), optarg);
263 set_pe_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
266 set_pe_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
268 case OPTION_SUBSYSTEM:
271 case OPTION_MAJOR_OS_VERSION:
272 set_pe_value ("__major_os_version__");
274 case OPTION_MINOR_OS_VERSION:
275 set_pe_value ("__minor_os_version__");
277 case OPTION_MAJOR_SUBSYSTEM_VERSION:
278 set_pe_value ("__major_subsystem_version__");
280 case OPTION_MINOR_SUBSYSTEM_VERSION:
281 set_pe_value ("__minor_subsystem_version__");
283 case OPTION_MAJOR_IMAGE_VERSION:
284 set_pe_value ("__major_image_version__");
286 case OPTION_MINOR_IMAGE_VERSION:
287 set_pe_value ("__minor_image_version__");
289 case OPTION_FILE_ALIGNMENT:
290 set_pe_value ("__file_alignment__");
292 case OPTION_SECTION_ALIGNMENT:
293 set_pe_value ("__section_alignment__");
296 set_pe_name ("__dll__", 1);
298 case OPTION_IMAGE_BASE:
299 set_pe_value ("__image_base__");
305 /* Assign values to the special symbols before the linker script is
309 gld${EMULATION_NAME}_set_symbols (void)
311 /* Run through and invent symbols for all the
312 names and insert the defaults. */
315 if (!init[IMAGEBASEOFF].inited)
317 if (bfd_link_relocatable (&link_info))
318 init[IMAGEBASEOFF].value = 0;
319 else if (init[DLLOFF].value)
320 init[IMAGEBASEOFF].value = BEOS_DLL_IMAGE_BASE;
322 init[IMAGEBASEOFF].value = BEOS_EXE_IMAGE_BASE;
325 /* Don't do any symbol assignments if this is a relocatable link. */
326 if (bfd_link_relocatable (&link_info))
329 /* Glue the assignments into the abs section */
330 push_stat_ptr (&abs_output_section->children);
332 for (j = 0; init[j].ptr; j++)
334 long val = init[j].value;
335 lang_add_assignment (exp_assign (init[j].symbol, exp_intop (val),
337 if (init[j].size == sizeof(short))
338 *(short *)init[j].ptr = val;
339 else if (init[j].size == sizeof(int))
340 *(int *)init[j].ptr = val;
341 else if (init[j].size == sizeof(long))
342 *(long *)init[j].ptr = val;
343 /* This might be a long long or other special type. */
344 else if (init[j].size == sizeof(bfd_vma))
345 *(bfd_vma *)init[j].ptr = val;
348 /* Restore the pointer. */
351 if (pe.FileAlignment >
354 einfo (_("%P: warning, file alignment > section alignment\n"));
359 gld${EMULATION_NAME}_after_open (void)
361 after_open_default ();
363 /* Pass the wacky PE command line options into the output bfd.
364 FIXME: This should be done via a function, rather than by
365 including an internal BFD header. */
366 if (!obj_pe (link_info.output_bfd))
368 einfo (_("%F%P: PE operations on non PE file\n"));
371 pe_data(link_info.output_bfd)->pe_opthdr = pe;
372 pe_data(link_info.output_bfd)->dll = init[DLLOFF].value;
376 /* Callback functions for qsort in sort_sections. */
379 sort_by_file_name (const void *a, const void *b)
381 const lang_input_section_type *const *ra = a;
382 const lang_input_section_type *const *rb = b;
383 asection *sa = (*ra)->section;
384 asection *sb = (*rb)->section;
387 i = filename_cmp (bfd_get_filename (sa->owner->my_archive),
388 bfd_get_filename (sb->owner->my_archive));
392 i = filename_cmp (bfd_get_filename (sa->owner),
393 bfd_get_filename (sb->owner));
396 /* the tail idata4/5 are the only ones without relocs to an
397 idata$6 section unless we are importing by ordinal,
398 so sort them to last to terminate the IAT
399 and HNT properly. if no reloc this one is import by ordinal
400 so we have to sort by section contents */
402 if (sa->reloc_count + sb->reloc_count != 0)
404 i = sa->reloc_count > sb->reloc_count ? -1 : 0;
408 return sa->reloc_count > sb->reloc_count ? 0 : 1;
412 /* don't sort .idata$6 or .idata$7 FIXME dlltool eliminate .idata$7 */
413 if ((strcmp (sa->name, ".idata$6") == 0))
416 if (!bfd_get_section_contents (sa->owner, sa, &a_sec, (file_ptr) 0,
417 (bfd_size_type) sizeof (a_sec)))
418 einfo (_("%F%P: %pB: can't read contents of section .idata: %E\n"),
421 if (!bfd_get_section_contents (sb->owner, sb, &b_sec, (file_ptr) 0,
422 (bfd_size_type) sizeof (b_sec)))
423 einfo (_("%F%P: %pB: can't read contents of section .idata: %E\n"),
426 i = a_sec < b_sec ? -1 : 0;
429 return a_sec < b_sec ? 0 : 1;
435 sort_by_section_name (const void *a, const void *b)
437 const lang_input_section_type *const *ra = a;
438 const lang_input_section_type *const *rb = b;
439 const char *sna = (*ra)->section->name;
440 const char *snb = (*rb)->section->name;
442 i = strcmp (sna, snb);
443 /* This is a hack to make .stab and .stabstr last, so we don't have
444 to fix strip/objcopy for .reloc sections.
445 FIXME stripping images with a .rsrc section still needs to be fixed. */
448 if ((startswith (sna, ".stab"))
449 && (!startswith (snb, ".stab")))
455 /* Subroutine of sort_sections to a contiguous subset of a list of sections.
456 NEXT_AFTER is the element after the last one to sort.
457 The result is a pointer to the last element's "next" pointer. */
459 static lang_statement_union_type **
460 sort_sections_1 (lang_statement_union_type **startptr,
461 lang_statement_union_type *next_after,
463 int (*sort_func) (const void *, const void *))
465 lang_statement_union_type **vec;
466 lang_statement_union_type *p;
468 lang_statement_union_type **ret;
473 vec = ((lang_statement_union_type **)
474 xmalloc (count * sizeof (lang_statement_union_type *)));
476 for (p = *startptr, i = 0; i < count; i++, p = p->header.next)
479 qsort (vec, count, sizeof (vec[0]), sort_func);
481 /* Fill in the next pointers again. */
483 for (i = 0; i < count - 1; i++)
484 vec[i]->header.next = vec[i + 1];
485 vec[i]->header.next = next_after;
486 ret = &vec[i]->header.next;
491 /* Sort the .idata\$foo input sections of archives into filename order.
492 The reason is so dlltool can arrange to have the pe dll import information
493 generated correctly - the head of the list goes into dh.o, the tail into
494 dt.o, and the guts into ds[nnnn].o. Note that this is only needed for the
496 FIXME: This may no longer be necessary with grouped sections. Instead of
497 sorting on dh.o, ds[nnnn].o, dt.o, one could, for example, have dh.o use
498 .idata\$4h, have ds[nnnn].o use .idata\$4s[nnnn], and have dt.o use .idata\$4t.
499 This would have to be elaborated upon to handle multiple dll's
500 [assuming such an eloboration is possible of course].
502 We also sort sections in '\$' wild statements. These are created by the
503 place_orphans routine to implement grouped sections. */
506 sort_sections (lang_statement_union_type *s)
508 for (; s ; s = s->header.next)
509 switch (s->header.type)
511 case lang_output_section_statement_enum:
512 sort_sections (s->output_section_statement.children.head);
514 case lang_wild_statement_enum:
516 lang_statement_union_type **p = &s->wild_statement.children.head;
517 struct wildcard_list *sec;
519 for (sec = s->wild_statement.section_list; sec; sec = sec->next)
521 /* Is this the .idata section? */
522 if (sec->spec.name != NULL
523 && startswith (sec->spec.name, ".idata"))
525 /* Sort the children. We want to sort any objects in
526 the same archive. In order to handle the case of
527 including a single archive multiple times, we sort
528 all the children by archive name and then by object
529 name. After sorting them, we re-thread the pointer
534 lang_statement_union_type *start = *p;
535 if (start->header.type != lang_input_section_enum
536 || !start->input_section.section->owner->my_archive)
537 p = &(start->header.next);
540 lang_statement_union_type *end;
543 for (end = start, count = 0;
544 end && (end->header.type
545 == lang_input_section_enum);
546 end = end->header.next)
549 p = sort_sections_1 (p, end, count,
556 /* If this is a collection of grouped sections, sort them.
557 The linker script must explicitly mention "*(.foo\$)" or
558 "*(.foo\$*)". Don't sort them if \$ is not the last
559 character (not sure if this is really useful, but it
560 allows explicitly mentioning some \$ sections and letting
561 the linker handle the rest). */
562 if (sec->spec.name != NULL)
564 char *q = strchr (sec->spec.name, '\$');
568 || (q[1] == '*' && q[2] == '\0')))
570 lang_statement_union_type *end;
573 for (end = *p, count = 0; end; end = end->header.next)
575 if (end->header.type != lang_input_section_enum)
579 (void) sort_sections_1 (p, end, count,
580 sort_by_section_name);
593 gld${EMULATION_NAME}_before_allocation (void)
595 #ifdef TARGET_IS_armpe
596 /* FIXME: we should be able to set the size of the interworking stub
599 Here we rummage through the found bfds to collect glue
600 information. FIXME: should this be based on a command line
601 option? krk@cygnus.com */
603 LANG_FOR_EACH_INPUT_STATEMENT (is)
605 if (!arm_process_before_allocation (is->the_bfd, & link_info))
607 einfo (_("%P: errors encountered processing file %s\n"),
613 /* We have seen it all. Allocate it, and carry on */
614 arm_allocate_interworking_sections (& link_info);
615 #endif /* TARGET_IS_armpe */
617 sort_sections (stat_ptr->head);
619 before_allocation_default ();
622 /* Place an orphan section. We use this to put sections with a '\$' in them
623 into the right place. Any section with a '\$' in them (e.g. .text\$foo)
624 gets mapped to the output section with everything from the '\$' on stripped
626 See the Microsoft Portable Executable and Common Object File Format
627 Specification 4.1, section 4.2, Grouped Sections.
629 FIXME: This is now handled by the linker script using wildcards,
630 but I'm leaving this here in case we want to enable it for sections
631 which are not mentioned in the linker script. */
633 static lang_output_section_statement_type *
634 gld${EMULATION_NAME}_place_orphan (asection *s,
638 char *output_secname, *ps;
639 lang_output_section_statement_type *os;
640 lang_statement_union_type *l;
642 if ((s->flags & SEC_ALLOC) == 0)
645 /* Don't process grouped sections unless doing a final link.
646 If they're marked as COMDAT sections, we don't want .text\$foo to
647 end up in .text and then have .text disappear because it's marked
648 link-once-discard. */
649 if (bfd_link_relocatable (&link_info))
652 /* Everything from the '\$' on gets deleted so don't allow '\$' as the
654 if (*secname == '\$')
655 einfo (_("%F%P: section %s has '\$' as first character\n"), secname);
656 if (strchr (secname + 1, '\$') == NULL)
659 /* Look up the output section. The Microsoft specs say sections names in
660 image files never contain a '\$'. Fortunately, lang_..._lookup creates
661 the section if it doesn't exist. */
662 output_secname = xstrdup (secname);
663 ps = strchr (output_secname + 1, '\$');
665 os = lang_output_section_statement_lookup (output_secname, constraint, true);
667 /* Find the '\$' wild statement for this section. We currently require the
668 linker script to explicitly mention "*(.foo\$)". */
672 for (l = os->children.head; l; l = l->header.next)
673 if (l->header.type == lang_wild_statement_enum)
675 struct wildcard_list *sec;
677 for (sec = l->wild_statement.section_list; sec; sec = sec->next)
678 if (sec->spec.name && strcmp (sec->spec.name, output_secname) == 0)
685 einfo (_("%F%P: *(%s\$) missing from linker script\n"), output_secname);
687 /* Link the input section in and we're done for now.
688 The sections still have to be sorted, but that has to wait until
689 all such sections have been processed by us. The sorting is done by
691 lang_add_section (&l->wild_statement.children, s, NULL, NULL, os);
697 gld${EMULATION_NAME}_get_script (int *isfile)
700 if test x"$COMPILE_IN" = xyes
702 # Scripts compiled in.
704 # sed commands to quote an ld script as a C string.
705 sc="-f ${srcdir}/emultempl/stringify.sed"
711 if (bfd_link_relocatable (&link_info) && config.build_constructors)
714 sed $sc ldscripts/${EMULATION_NAME}.xu >> e${EMULATION_NAME}.c
715 echo ' ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
716 sed $sc ldscripts/${EMULATION_NAME}.xr >> e${EMULATION_NAME}.c
717 echo ' ; else if (!config.text_read_only) return' >> e${EMULATION_NAME}.c
718 sed $sc ldscripts/${EMULATION_NAME}.xbn >> e${EMULATION_NAME}.c
719 echo ' ; else if (!config.magic_demand_paged) return' >> e${EMULATION_NAME}.c
720 sed $sc ldscripts/${EMULATION_NAME}.xn >> e${EMULATION_NAME}.c
721 echo ' ; else return' >> e${EMULATION_NAME}.c
722 sed $sc ldscripts/${EMULATION_NAME}.x >> e${EMULATION_NAME}.c
723 echo '; }' >> e${EMULATION_NAME}.c
726 # Scripts read from the filesystem.
732 if (bfd_link_relocatable (&link_info) && config.build_constructors)
733 return "ldscripts/${EMULATION_NAME}.xu";
734 else if (bfd_link_relocatable (&link_info))
735 return "ldscripts/${EMULATION_NAME}.xr";
736 else if (!config.text_read_only)
737 return "ldscripts/${EMULATION_NAME}.xbn";
738 else if (!config.magic_demand_paged)
739 return "ldscripts/${EMULATION_NAME}.xn";
741 return "ldscripts/${EMULATION_NAME}.x";
746 LDEMUL_AFTER_OPEN=gld${EMULATION_NAME}_after_open
747 LDEMUL_BEFORE_ALLOCATION=gld${EMULATION_NAME}_before_allocation
748 LDEMUL_PLACE_ORPHAN=gld${EMULATION_NAME}_place_orphan
749 LDEMUL_SET_SYMBOLS=gld${EMULATION_NAME}_set_symbols
750 LDEMUL_ADD_OPTIONS=gld${EMULATION_NAME}_add_options
751 LDEMUL_HANDLE_OPTION=gld${EMULATION_NAME}_handle_option
753 source_em ${srcdir}/emultempl/emulation.em