struct / union in initializer, RFE #901.
[sdcc.git] / sdcc / support / sdbinutils / binutils / dlltool.c
blobd95bf3f5470b999fa3b30bc887791859f48d81d1
1 /* dlltool.c -- tool to generate stuff for PE style DLLs
2 Copyright (C) 1995-2022 Free Software Foundation, Inc.
4 This file is part of GNU Binutils.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
19 02110-1301, USA. */
22 /* This program allows you to build the files necessary to create
23 DLLs to run on a system which understands PE format image files.
24 (eg, Windows NT)
26 See "Peering Inside the PE: A Tour of the Win32 Portable Executable
27 File Format", MSJ 1994, Volume 9 for more information.
28 Also see "Microsoft Portable Executable and Common Object File Format,
29 Specification 4.1" for more information.
31 A DLL contains an export table which contains the information
32 which the runtime loader needs to tie up references from a
33 referencing program.
35 The export table is generated by this program by reading
36 in a .DEF file or scanning the .a and .o files which will be in the
37 DLL. A .o file can contain information in special ".drectve" sections
38 with export information.
40 A DEF file contains any number of the following commands:
43 NAME <name> [ , <base> ]
44 The result is going to be <name>.EXE
46 LIBRARY <name> [ , <base> ]
47 The result is going to be <name>.DLL
49 EXPORTS ( ( ( <name1> [ = <name2> ] )
50 | ( <name1> = <module-name> . <external-name>))
51 [ @ <integer> ] [ NONAME ] [CONSTANT] [DATA] [PRIVATE] ) *
52 Declares name1 as an exported symbol from the
53 DLL, with optional ordinal number <integer>.
54 Or declares name1 as an alias (forward) of the function <external-name>
55 in the DLL <module-name>.
57 IMPORTS ( ( <internal-name> = <module-name> . <integer> )
58 | ( [ <internal-name> = ] <module-name> . <external-name> )) *
59 Declares that <external-name> or the exported function whose ordinal number
60 is <integer> is to be imported from the file <module-name>. If
61 <internal-name> is specified then this is the name that the imported
62 function will be refereed to in the body of the DLL.
64 DESCRIPTION <string>
65 Puts <string> into output .exp file in the .rdata section
67 [STACKSIZE|HEAPSIZE] <number-reserve> [ , <number-commit> ]
68 Generates --stack|--heap <number-reserve>,<number-commit>
69 in the output .drectve section. The linker will
70 see this and act upon it.
72 [CODE|DATA] <attr>+
73 SECTIONS ( <sectionname> <attr>+ )*
74 <attr> = READ | WRITE | EXECUTE | SHARED
75 Generates --attr <sectionname> <attr> in the output
76 .drectve section. The linker will see this and act
77 upon it.
80 A -export:<name> in a .drectve section in an input .o or .a
81 file to this program is equivalent to a EXPORTS <name>
82 in a .DEF file.
86 The program generates output files with the prefix supplied
87 on the command line, or in the def file, or taken from the first
88 supplied argument.
90 The .exp.s file contains the information necessary to export
91 the routines in the DLL. The .lib.s file contains the information
92 necessary to use the DLL's routines from a referencing program.
96 Example:
98 file1.c:
99 asm (".section .drectve");
100 asm (".ascii \"-export:adef\"");
102 void adef (char * s)
104 printf ("hello from the dll %s\n", s);
107 void bdef (char * s)
109 printf ("hello from the dll and the other entry point %s\n", s);
112 file2.c:
113 asm (".section .drectve");
114 asm (".ascii \"-export:cdef\"");
115 asm (".ascii \"-export:ddef\"");
117 void cdef (char * s)
119 printf ("hello from the dll %s\n", s);
122 void ddef (char * s)
124 printf ("hello from the dll and the other entry point %s\n", s);
127 int printf (void)
129 return 9;
132 themain.c:
133 int main (void)
135 cdef ();
136 return 0;
139 thedll.def
141 LIBRARY thedll
142 HEAPSIZE 0x40000, 0x2000
143 EXPORTS bdef @ 20
144 cdef @ 30 NONAME
146 SECTIONS donkey READ WRITE
147 aardvark EXECUTE
149 # Compile up the parts of the dll and the program
151 gcc -c file1.c file2.c themain.c
153 # Optional: put the dll objects into a library
154 # (you don't have to, you could name all the object
155 # files on the dlltool line)
157 ar qcv thedll.in file1.o file2.o
158 ranlib thedll.in
160 # Run this tool over the DLL's .def file and generate an exports
161 # file (thedll.o) and an imports file (thedll.a).
162 # (You may have to use -S to tell dlltool where to find the assembler).
164 dlltool --def thedll.def --output-exp thedll.o --output-lib thedll.a
166 # Build the dll with the library and the export table
168 ld -o thedll.dll thedll.o thedll.in
170 # Link the executable with the import library
172 gcc -o themain.exe themain.o thedll.a
174 This example can be extended if relocations are needed in the DLL:
176 # Compile up the parts of the dll and the program
178 gcc -c file1.c file2.c themain.c
180 # Run this tool over the DLL's .def file and generate an imports file.
182 dlltool --def thedll.def --output-lib thedll.lib
184 # Link the executable with the import library and generate a base file
185 # at the same time
187 gcc -o themain.exe themain.o thedll.lib -Wl,--base-file -Wl,themain.base
189 # Run this tool over the DLL's .def file and generate an exports file
190 # which includes the relocations from the base file.
192 dlltool --def thedll.def --base-file themain.base --output-exp thedll.exp
194 # Build the dll with file1.o, file2.o and the export table
196 ld -o thedll.dll thedll.exp file1.o file2.o */
198 /* .idata section description
200 The .idata section is the import table. It is a collection of several
201 subsections used to keep the pieces for each dll together: .idata$[234567].
202 IE: Each dll's .idata$2's are catenated together, each .idata$3's, etc.
204 .idata$2 = Import Directory Table
205 = array of IMAGE_IMPORT_DESCRIPTOR's.
207 DWORD Import Lookup Table; - pointer to .idata$4
208 DWORD TimeDateStamp; - currently always 0
209 DWORD ForwarderChain; - currently always 0
210 DWORD Name; - pointer to dll's name
211 PIMAGE_THUNK_DATA FirstThunk; - pointer to .idata$5
213 .idata$3 = null terminating entry for .idata$2.
215 .idata$4 = Import Lookup Table
216 = array of array of pointers to hint name table.
217 There is one for each dll being imported from, and each dll's set is
218 terminated by a trailing NULL.
220 .idata$5 = Import Address Table
221 = array of array of pointers to hint name table.
222 There is one for each dll being imported from, and each dll's set is
223 terminated by a trailing NULL.
224 Initially, this table is identical to the Import Lookup Table. However,
225 at load time, the loader overwrites the entries with the address of the
226 function.
228 .idata$6 = Hint Name Table
229 = Array of { short, asciz } entries, one for each imported function.
230 The `short' is the function's ordinal number.
232 .idata$7 = dll name (eg: "kernel32.dll"). */
234 #include "sysdep.h"
235 #include "bfd.h"
236 #include "libiberty.h"
237 #include "getopt.h"
238 #include "demangle.h"
239 #include "dyn-string.h"
240 #include "bucomm.h"
241 #include "dlltool.h"
242 #include "safe-ctype.h"
243 #include "coff-bfd.h"
245 #include <time.h>
246 #include <assert.h>
248 #ifdef DLLTOOL_ARM
249 #include "coff/arm.h"
250 #include "coff/internal.h"
251 #endif
252 #ifdef DLLTOOL_DEFAULT_MX86_64
253 #include "coff/x86_64.h"
254 #endif
255 #ifdef DLLTOOL_DEFAULT_I386
256 #include "coff/i386.h"
257 #endif
259 #ifndef COFF_PAGE_SIZE
260 #define COFF_PAGE_SIZE ((bfd_vma) 4096)
261 #endif
263 #ifndef PAGE_MASK
264 #define PAGE_MASK ((bfd_vma) (- COFF_PAGE_SIZE))
265 #endif
267 /* Get current BFD error message. */
268 #define bfd_get_errmsg() (bfd_errmsg (bfd_get_error ()))
270 /* Forward references. */
271 static char *look_for_prog (const char *, const char *, int);
272 static char *deduce_name (const char *);
274 #ifdef DLLTOOL_MCORE_ELF
275 static void mcore_elf_cache_filename (const char *);
276 static void mcore_elf_gen_out_file (void);
277 #endif
279 #ifdef HAVE_SYS_WAIT_H
280 #include <sys/wait.h>
281 #else /* ! HAVE_SYS_WAIT_H */
282 #if ! defined (_WIN32) || defined (__CYGWIN32__)
283 #ifndef WIFEXITED
284 #define WIFEXITED(w) (((w) & 0377) == 0)
285 #endif
286 #ifndef WIFSIGNALED
287 #define WIFSIGNALED(w) (((w) & 0377) != 0177 && ((w) & ~0377) == 0)
288 #endif
289 #ifndef WTERMSIG
290 #define WTERMSIG(w) ((w) & 0177)
291 #endif
292 #ifndef WEXITSTATUS
293 #define WEXITSTATUS(w) (((w) >> 8) & 0377)
294 #endif
295 #else /* defined (_WIN32) && ! defined (__CYGWIN32__) */
296 #ifndef WIFEXITED
297 #define WIFEXITED(w) (((w) & 0xff) == 0)
298 #endif
299 #ifndef WIFSIGNALED
300 #define WIFSIGNALED(w) (((w) & 0xff) != 0 && ((w) & 0xff) != 0x7f)
301 #endif
302 #ifndef WTERMSIG
303 #define WTERMSIG(w) ((w) & 0x7f)
304 #endif
305 #ifndef WEXITSTATUS
306 #define WEXITSTATUS(w) (((w) & 0xff00) >> 8)
307 #endif
308 #endif /* defined (_WIN32) && ! defined (__CYGWIN32__) */
309 #endif /* ! HAVE_SYS_WAIT_H */
311 #define show_allnames 0
313 /* ifunc and ihead data structures: ttk@cygnus.com 1997
315 When IMPORT declarations are encountered in a .def file the
316 function import information is stored in a structure referenced by
317 the global variable IMPORT_LIST. The structure is a linked list
318 containing the names of the dll files each function is imported
319 from and a linked list of functions being imported from that dll
320 file. This roughly parallels the structure of the .idata section
321 in the PE object file.
323 The contents of .def file are interpreted from within the
324 process_def_file function. Every time an IMPORT declaration is
325 encountered, it is broken up into its component parts and passed to
326 def_import. IMPORT_LIST is initialized to NULL in function main. */
328 typedef struct ifunct
330 char * name; /* Name of function being imported. */
331 char * its_name; /* Optional import table symbol name. */
332 int ord; /* Two-byte ordinal value associated with function. */
333 struct ifunct *next;
334 } ifunctype;
336 typedef struct iheadt
338 char * dllname; /* Name of dll file imported from. */
339 long nfuncs; /* Number of functions in list. */
340 struct ifunct *funchead; /* First function in list. */
341 struct ifunct *functail; /* Last function in list. */
342 struct iheadt *next; /* Next dll file in list. */
343 } iheadtype;
345 /* Structure containing all import information as defined in .def file
346 (qv "ihead structure"). */
348 static iheadtype *import_list = NULL;
349 static char *as_name = NULL;
350 static char * as_flags = "";
351 static char *tmp_prefix = NULL;
352 static int no_idata4;
353 static int no_idata5;
354 static char *exp_name;
355 static char *imp_name;
356 static char *delayimp_name;
357 static char *identify_imp_name;
358 static bool identify_strict;
360 /* Types used to implement a linked list of dllnames associated
361 with the specified import lib. Used by the identify_* code.
362 The head entry is acts as a sentinal node and is always empty
363 (head->dllname is NULL). */
364 typedef struct dll_name_list_node_t
366 char * dllname;
367 struct dll_name_list_node_t * next;
368 } dll_name_list_node_type;
370 typedef struct dll_name_list_t
372 dll_name_list_node_type * head;
373 dll_name_list_node_type * tail;
374 } dll_name_list_type;
376 /* Types used to pass data to iterator functions. */
377 typedef struct symname_search_data_t
379 const char *symname;
380 bool found;
381 } symname_search_data_type;
383 typedef struct identify_data_t
385 dll_name_list_type *list;
386 bool ms_style_implib;
387 } identify_data_type;
390 static char *head_label;
391 static char *imp_name_lab;
392 static char *dll_name;
393 static int dll_name_set_by_exp_name;
394 static int add_indirect = 0;
395 static int add_underscore = 0;
396 static int add_stdcall_underscore = 0;
397 /* This variable can hold three different values. The value
398 -1 (default) means that default underscoring should be used,
399 zero means that no underscoring should be done, and one
400 indicates that underscoring should be done. */
401 static int leading_underscore = -1;
402 static int dontdeltemps = 0;
404 /* TRUE if we should export all symbols. Otherwise, we only export
405 symbols listed in .drectve sections or in the def file. */
406 static bool export_all_symbols;
408 /* TRUE if we should exclude the symbols in DEFAULT_EXCLUDES when
409 exporting all symbols. */
410 static bool do_default_excludes = true;
412 static bool use_nul_prefixed_import_tables = false;
414 /* Default symbols to exclude when exporting all the symbols. */
415 static const char *default_excludes = "DllMain@12,DllEntryPoint@0,impure_ptr";
417 /* TRUE if we should add __imp_<SYMBOL> to import libraries for backward
418 compatibility to old Cygwin releases. */
419 static bool create_compat_implib;
421 /* TRUE if we have to write PE+ import libraries. */
422 static bool create_for_pep;
424 static char *def_file;
426 extern char * program_name;
428 static int machine;
429 static int killat;
430 static int add_stdcall_alias;
431 static const char *ext_prefix_alias;
432 static int verbose;
433 static FILE *output_def;
434 static FILE *base_file;
436 #ifdef DLLTOOL_DEFAULT_ARM
437 static const char *mname = "arm";
438 #endif
440 #ifdef DLLTOOL_DEFAULT_ARM_WINCE
441 static const char *mname = "arm-wince";
442 #endif
444 #ifdef DLLTOOL_DEFAULT_I386
445 static const char *mname = "i386";
446 #endif
448 #ifdef DLLTOOL_DEFAULT_MX86_64
449 static const char *mname = "i386:x86-64";
450 #endif
452 #ifdef DLLTOOL_DEFAULT_SH
453 static const char *mname = "sh";
454 #endif
456 #ifdef DLLTOOL_DEFAULT_MIPS
457 static const char *mname = "mips";
458 #endif
460 #ifdef DLLTOOL_DEFAULT_MCORE
461 static const char * mname = "mcore-le";
462 #endif
464 #ifdef DLLTOOL_DEFAULT_MCORE_ELF
465 static const char * mname = "mcore-elf";
466 static char * mcore_elf_out_file = NULL;
467 static char * mcore_elf_linker = NULL;
468 static char * mcore_elf_linker_flags = NULL;
470 #define DRECTVE_SECTION_NAME ((machine == MMCORE_ELF || machine == MMCORE_ELF_LE) ? ".exports" : ".drectve")
471 #endif
473 #ifndef DRECTVE_SECTION_NAME
474 #define DRECTVE_SECTION_NAME ".drectve"
475 #endif
477 /* What's the right name for this ? */
478 #define PATHMAX 250
480 /* External name alias numbering starts here. */
481 #define PREFIX_ALIAS_BASE 20000
483 char *tmp_asm_buf;
484 char *tmp_head_s_buf;
485 char *tmp_head_o_buf;
486 char *tmp_tail_s_buf;
487 char *tmp_tail_o_buf;
488 char *tmp_stub_buf;
490 #define TMP_ASM dlltmp (&tmp_asm_buf, "%sc.s")
491 #define TMP_HEAD_S dlltmp (&tmp_head_s_buf, "%sh.s")
492 #define TMP_HEAD_O dlltmp (&tmp_head_o_buf, "%sh.o")
493 #define TMP_TAIL_S dlltmp (&tmp_tail_s_buf, "%st.s")
494 #define TMP_TAIL_O dlltmp (&tmp_tail_o_buf, "%st.o")
495 #define TMP_STUB dlltmp (&tmp_stub_buf, "%ss")
497 /* This bit of assembly does jmp * .... */
498 static const unsigned char i386_jtab[] =
500 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
503 static const unsigned char i386_dljtab[] =
505 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function */
506 0xB8, 0x00, 0x00, 0x00, 0x00, /* mov eax, offset __imp__function */
507 0xE9, 0x00, 0x00, 0x00, 0x00 /* jmp __tailMerge__dllname */
510 static const unsigned char i386_x64_dljtab[] =
512 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function */
513 0x48, 0x8d, 0x05, /* leaq rax, (__imp__function) */
514 0x00, 0x00, 0x00, 0x00,
515 0xE9, 0x00, 0x00, 0x00, 0x00 /* jmp __tailMerge__dllname */
518 static const unsigned char arm_jtab[] =
520 0x00, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
521 0x00, 0xf0, 0x9c, 0xe5, /* ldr pc, [ip] */
522 0, 0, 0, 0
525 static const unsigned char arm_interwork_jtab[] =
527 0x04, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
528 0x00, 0xc0, 0x9c, 0xe5, /* ldr ip, [ip] */
529 0x1c, 0xff, 0x2f, 0xe1, /* bx ip */
530 0, 0, 0, 0
533 static const unsigned char thumb_jtab[] =
535 0x40, 0xb4, /* push {r6} */
536 0x02, 0x4e, /* ldr r6, [pc, #8] */
537 0x36, 0x68, /* ldr r6, [r6] */
538 0xb4, 0x46, /* mov ip, r6 */
539 0x40, 0xbc, /* pop {r6} */
540 0x60, 0x47, /* bx ip */
541 0, 0, 0, 0
544 static const unsigned char mcore_be_jtab[] =
546 0x71, 0x02, /* lrw r1,2 */
547 0x81, 0x01, /* ld.w r1,(r1,0) */
548 0x00, 0xC1, /* jmp r1 */
549 0x12, 0x00, /* nop */
550 0x00, 0x00, 0x00, 0x00 /* <address> */
553 static const unsigned char mcore_le_jtab[] =
555 0x02, 0x71, /* lrw r1,2 */
556 0x01, 0x81, /* ld.w r1,(r1,0) */
557 0xC1, 0x00, /* jmp r1 */
558 0x00, 0x12, /* nop */
559 0x00, 0x00, 0x00, 0x00 /* <address> */
562 static const char i386_trampoline[] =
563 "\tpushl %%ecx\n"
564 "\tpushl %%edx\n"
565 "\tpushl %%eax\n"
566 "\tpushl $__DELAY_IMPORT_DESCRIPTOR_%s\n"
567 "\tcall ___delayLoadHelper2@8\n"
568 "\tpopl %%edx\n"
569 "\tpopl %%ecx\n"
570 "\tjmp *%%eax\n";
572 static const char i386_x64_trampoline[] =
573 "\tsubq $72, %%rsp\n"
574 "\t.seh_stackalloc 72\n"
575 "\t.seh_endprologue\n"
576 "\tmovq %%rcx, 64(%%rsp)\n"
577 "\tmovq %%rdx, 56(%%rsp)\n"
578 "\tmovq %%r8, 48(%%rsp)\n"
579 "\tmovq %%r9, 40(%%rsp)\n"
580 "\tmovq %%rax, %%rdx\n"
581 "\tleaq __DELAY_IMPORT_DESCRIPTOR_%s(%%rip), %%rcx\n"
582 "\tcall __delayLoadHelper2\n"
583 "\tmovq 40(%%rsp), %%r9\n"
584 "\tmovq 48(%%rsp), %%r8\n"
585 "\tmovq 56(%%rsp), %%rdx\n"
586 "\tmovq 64(%%rsp), %%rcx\n"
587 "\taddq $72, %%rsp\n"
588 "\tjmp *%%rax\n";
590 struct mac
592 const char *type;
593 const char *how_byte;
594 const char *how_short;
595 const char *how_long;
596 const char *how_asciz;
597 const char *how_comment;
598 const char *how_jump;
599 const char *how_global;
600 const char *how_space;
601 const char *how_align_short;
602 const char *how_align_long;
603 const char *how_default_as_switches;
604 const char *how_bfd_target;
605 enum bfd_architecture how_bfd_arch;
606 const unsigned char *how_jtab;
607 int how_jtab_size; /* Size of the jtab entry. */
608 int how_jtab_roff; /* Offset into it for the ind 32 reloc into idata 5. */
609 const unsigned char *how_dljtab;
610 int how_dljtab_size; /* Size of the dljtab entry. */
611 int how_dljtab_roff1; /* Offset for the ind 32 reloc into idata 5. */
612 int how_dljtab_roff2; /* Offset for the ind 32 reloc into idata 5. */
613 int how_dljtab_roff3; /* Offset for the ind 32 reloc into idata 5. */
614 bool how_seh;
615 const char *trampoline;
618 static const struct mac
619 mtable[] =
622 #define MARM 0
623 "arm", ".byte", ".short", ".long", ".asciz", "@",
624 "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
625 ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
626 "pe-arm-little", bfd_arch_arm,
627 arm_jtab, sizeof (arm_jtab), 8,
628 0, 0, 0, 0, 0, false, 0
632 #define M386 1
633 "i386", ".byte", ".short", ".long", ".asciz", "#",
634 "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
635 "pe-i386",bfd_arch_i386,
636 i386_jtab, sizeof (i386_jtab), 2,
637 i386_dljtab, sizeof (i386_dljtab), 2, 7, 12, false, i386_trampoline
641 #define MTHUMB 2
642 "thumb", ".byte", ".short", ".long", ".asciz", "@",
643 "push\t{r6}\n\tldr\tr6, [pc, #8]\n\tldr\tr6, [r6]\n\tmov\tip, r6\n\tpop\t{r6}\n\tbx\tip",
644 ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
645 "pe-arm-little", bfd_arch_arm,
646 thumb_jtab, sizeof (thumb_jtab), 12,
647 0, 0, 0, 0, 0, false, 0
650 #define MARM_INTERWORK 3
652 "arm_interwork", ".byte", ".short", ".long", ".asciz", "@",
653 "ldr\tip,[pc]\n\tldr\tip,[ip]\n\tbx\tip\n\t.long",
654 ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
655 "pe-arm-little", bfd_arch_arm,
656 arm_interwork_jtab, sizeof (arm_interwork_jtab), 12,
657 0, 0, 0, 0, 0, false, 0
661 #define MMCORE_BE 4
662 "mcore-be", ".byte", ".short", ".long", ".asciz", "//",
663 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
664 ".global", ".space", ".align\t2",".align\t4", "",
665 "pe-mcore-big", bfd_arch_mcore,
666 mcore_be_jtab, sizeof (mcore_be_jtab), 8,
667 0, 0, 0, 0, 0, false, 0
671 #define MMCORE_LE 5
672 "mcore-le", ".byte", ".short", ".long", ".asciz", "//",
673 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
674 ".global", ".space", ".align\t2",".align\t4", "-EL",
675 "pe-mcore-little", bfd_arch_mcore,
676 mcore_le_jtab, sizeof (mcore_le_jtab), 8,
677 0, 0, 0, 0, 0, false, 0
681 #define MMCORE_ELF 6
682 "mcore-elf-be", ".byte", ".short", ".long", ".asciz", "//",
683 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
684 ".global", ".space", ".align\t2",".align\t4", "",
685 "elf32-mcore-big", bfd_arch_mcore,
686 mcore_be_jtab, sizeof (mcore_be_jtab), 8,
687 0, 0, 0, 0, 0, false, 0
691 #define MMCORE_ELF_LE 7
692 "mcore-elf-le", ".byte", ".short", ".long", ".asciz", "//",
693 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
694 ".global", ".space", ".align\t2",".align\t4", "-EL",
695 "elf32-mcore-little", bfd_arch_mcore,
696 mcore_le_jtab, sizeof (mcore_le_jtab), 8,
697 0, 0, 0, 0, 0, false, 0
701 #define MARM_WINCE 8
702 "arm-wince", ".byte", ".short", ".long", ".asciz", "@",
703 "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
704 ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
705 "pe-arm-wince-little", bfd_arch_arm,
706 arm_jtab, sizeof (arm_jtab), 8,
707 0, 0, 0, 0, 0, false, 0
711 #define MX86 9
712 "i386:x86-64", ".byte", ".short", ".long", ".asciz", "#",
713 "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
714 "pe-x86-64",bfd_arch_i386,
715 i386_jtab, sizeof (i386_jtab), 2,
716 i386_x64_dljtab, sizeof (i386_x64_dljtab), 2, 9, 14, true, i386_x64_trampoline
719 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
722 typedef struct dlist
724 char *text;
725 struct dlist *next;
727 dlist_type;
729 typedef struct export
731 const char *name;
732 const char *internal_name;
733 const char *import_name;
734 const char *its_name;
735 int ordinal;
736 int constant;
737 int noname; /* Don't put name in image file. */
738 int private; /* Don't put reference in import lib. */
739 int data;
740 int forward; /* Number of forward label, 0 means no forward. */
741 struct export *next;
743 export_type;
745 /* A list of symbols which we should not export. */
747 struct string_list
749 struct string_list *next;
750 char *string;
753 static struct string_list *excludes;
755 static const char *rvaafter (int);
756 static const char *rvabefore (int);
757 static const char *asm_prefix (int, const char *);
758 static void process_def_file (const char *);
759 static void new_directive (char *);
760 static void append_import (const char *, const char *, int, const char *);
761 static void run (const char *, char *);
762 static void scan_drectve_symbols (bfd *);
763 static void scan_filtered_symbols (bfd *, void *, long, unsigned int);
764 static void add_excludes (const char *);
765 static bool match_exclude (const char *);
766 static void set_default_excludes (void);
767 static long filter_symbols (bfd *, void *, long, unsigned int);
768 static void scan_all_symbols (bfd *);
769 static void scan_open_obj_file (bfd *);
770 static void scan_obj_file (const char *);
771 static void dump_def_info (FILE *);
772 static int sfunc (const void *, const void *);
773 static void flush_page (FILE *, bfd_vma *, bfd_vma, int);
774 static void gen_def_file (void);
775 static void generate_idata_ofile (FILE *);
776 static void assemble_file (const char *, const char *);
777 static void gen_exp_file (void);
778 static const char *xlate (const char *);
779 static char *make_label (const char *, const char *);
780 static char *make_imp_label (const char *, const char *);
781 static bfd *make_one_lib_file (export_type *, int, int);
782 static bfd *make_head (void);
783 static bfd *make_tail (void);
784 static bfd *make_delay_head (void);
785 static void gen_lib_file (int);
786 static void dll_name_list_append (dll_name_list_type *, bfd_byte *);
787 static int dll_name_list_count (dll_name_list_type *);
788 static void dll_name_list_print (dll_name_list_type *);
789 static void dll_name_list_free_contents (dll_name_list_node_type *);
790 static void dll_name_list_free (dll_name_list_type *);
791 static dll_name_list_type * dll_name_list_create (void);
792 static void identify_dll_for_implib (void);
793 static void identify_search_archive
794 (bfd *, void (*) (bfd *, bfd *, void *), void *);
795 static void identify_search_member (bfd *, bfd *, void *);
796 static bool identify_process_section_p (asection *, bool);
797 static void identify_search_section (bfd *, asection *, void *);
798 static void identify_member_contains_symname (bfd *, bfd *, void *);
800 static int pfunc (const void *, const void *);
801 static int nfunc (const void *, const void *);
802 static void remove_null_names (export_type **);
803 static void process_duplicates (export_type **);
804 static void fill_ordinals (export_type **);
805 static void mangle_defs (void);
806 static void usage (FILE *, int);
807 static void inform (const char *, ...) ATTRIBUTE_PRINTF_1;
808 static void set_dll_name_from_def (const char *name, char is_dll);
810 static char *
811 prefix_encode (char *start, unsigned code)
813 static char alpha[26] = "abcdefghijklmnopqrstuvwxyz";
814 static char buf[32];
815 char *p;
816 strcpy (buf, start);
817 p = strchr (buf, '\0');
819 *p++ = alpha[code % sizeof (alpha)];
820 while ((code /= sizeof (alpha)) != 0);
821 *p = '\0';
822 return buf;
825 static char *
826 dlltmp (char **buf, const char *fmt)
828 if (!*buf)
830 *buf = malloc (strlen (tmp_prefix) + 64);
831 sprintf (*buf, fmt, tmp_prefix);
833 return *buf;
836 static void
837 inform (const char * message, ...)
839 va_list args;
841 va_start (args, message);
843 if (!verbose)
844 return;
846 report (message, args);
848 va_end (args);
851 static const char *
852 rvaafter (int mach)
854 switch (mach)
856 case MARM:
857 case M386:
858 case MX86:
859 case MTHUMB:
860 case MARM_INTERWORK:
861 case MMCORE_BE:
862 case MMCORE_LE:
863 case MMCORE_ELF:
864 case MMCORE_ELF_LE:
865 case MARM_WINCE:
866 break;
867 default:
868 /* xgettext:c-format */
869 fatal (_("Internal error: Unknown machine type: %d"), mach);
870 break;
872 return "";
875 static const char *
876 rvabefore (int mach)
878 switch (mach)
880 case MARM:
881 case M386:
882 case MX86:
883 case MTHUMB:
884 case MARM_INTERWORK:
885 case MMCORE_BE:
886 case MMCORE_LE:
887 case MMCORE_ELF:
888 case MMCORE_ELF_LE:
889 case MARM_WINCE:
890 return ".rva\t";
891 default:
892 /* xgettext:c-format */
893 fatal (_("Internal error: Unknown machine type: %d"), mach);
894 break;
896 return "";
899 static const char *
900 asm_prefix (int mach, const char *name)
902 switch (mach)
904 case MARM:
905 case MTHUMB:
906 case MARM_INTERWORK:
907 case MMCORE_BE:
908 case MMCORE_LE:
909 case MMCORE_ELF:
910 case MMCORE_ELF_LE:
911 case MARM_WINCE:
912 break;
913 case M386:
914 case MX86:
915 /* Symbol names starting with ? do not have a leading underscore. */
916 if ((name && *name == '?') || leading_underscore == 0)
917 break;
918 else
919 return "_";
920 default:
921 /* xgettext:c-format */
922 fatal (_("Internal error: Unknown machine type: %d"), mach);
923 break;
925 return "";
928 #define ASM_BYTE mtable[machine].how_byte
929 #define ASM_SHORT mtable[machine].how_short
930 #define ASM_LONG mtable[machine].how_long
931 #define ASM_TEXT mtable[machine].how_asciz
932 #define ASM_C mtable[machine].how_comment
933 #define ASM_JUMP mtable[machine].how_jump
934 #define ASM_GLOBAL mtable[machine].how_global
935 #define ASM_SPACE mtable[machine].how_space
936 #define ASM_ALIGN_SHORT mtable[machine].how_align_short
937 #define ASM_RVA_BEFORE rvabefore (machine)
938 #define ASM_RVA_AFTER rvaafter (machine)
939 #define ASM_PREFIX(NAME) asm_prefix (machine, (NAME))
940 #define ASM_ALIGN_LONG mtable[machine].how_align_long
941 #define HOW_BFD_READ_TARGET 0 /* Always default. */
942 #define HOW_BFD_WRITE_TARGET mtable[machine].how_bfd_target
943 #define HOW_BFD_ARCH mtable[machine].how_bfd_arch
944 #define HOW_JTAB (delay ? mtable[machine].how_dljtab \
945 : mtable[machine].how_jtab)
946 #define HOW_JTAB_SIZE (delay ? mtable[machine].how_dljtab_size \
947 : mtable[machine].how_jtab_size)
948 #define HOW_JTAB_ROFF (delay ? mtable[machine].how_dljtab_roff1 \
949 : mtable[machine].how_jtab_roff)
950 #define HOW_JTAB_ROFF2 (delay ? mtable[machine].how_dljtab_roff2 : 0)
951 #define HOW_JTAB_ROFF3 (delay ? mtable[machine].how_dljtab_roff3 : 0)
952 #define ASM_SWITCHES mtable[machine].how_default_as_switches
953 #define HOW_SEH mtable[machine].how_seh
955 static char **oav;
957 static void
958 process_def_file (const char *name)
960 FILE *f = fopen (name, FOPEN_RT);
962 if (!f)
963 /* xgettext:c-format */
964 fatal (_("Can't open def file: %s"), name);
966 yyin = f;
968 /* xgettext:c-format */
969 inform (_("Processing def file: %s"), name);
971 yyparse ();
973 inform (_("Processed def file"));
976 /**********************************************************************/
978 /* Communications with the parser. */
980 static int d_nfuncs; /* Number of functions exported. */
981 static int d_named_nfuncs; /* Number of named functions exported. */
982 static int d_low_ord; /* Lowest ordinal index. */
983 static int d_high_ord; /* Highest ordinal index. */
984 static export_type *d_exports; /* List of exported functions. */
985 static export_type **d_exports_lexically; /* Vector of exported functions in alpha order. */
986 static dlist_type *d_list; /* Descriptions. */
987 static dlist_type *a_list; /* Stuff to go in directives. */
988 static int d_nforwards = 0; /* Number of forwarded exports. */
990 static int d_is_dll;
991 static int d_is_exe;
993 void
994 yyerror (const char * err ATTRIBUTE_UNUSED)
996 /* xgettext:c-format */
997 non_fatal (_("Syntax error in def file %s:%d"), def_file, linenumber);
1000 void
1001 def_exports (const char *name, const char *internal_name, int ordinal,
1002 int noname, int constant, int data, int private,
1003 const char *its_name)
1005 struct export *p = (struct export *) xmalloc (sizeof (*p));
1007 p->name = name;
1008 p->internal_name = internal_name ? internal_name : name;
1009 p->its_name = its_name;
1010 p->import_name = name;
1011 p->ordinal = ordinal;
1012 p->constant = constant;
1013 p->noname = noname;
1014 p->private = private;
1015 p->data = data;
1016 p->next = d_exports;
1017 d_exports = p;
1018 d_nfuncs++;
1020 if ((internal_name != NULL)
1021 && (strchr (internal_name, '.') != NULL))
1022 p->forward = ++d_nforwards;
1023 else
1024 p->forward = 0; /* no forward */
1027 static void
1028 set_dll_name_from_def (const char *name, char is_dll)
1030 const char *image_basename = lbasename (name);
1031 if (image_basename != name)
1032 non_fatal (_("%s: Path components stripped from image name, '%s'."),
1033 def_file, name);
1034 /* Append the default suffix, if none specified. */
1035 if (strchr (image_basename, '.') == 0)
1037 const char * suffix = is_dll ? ".dll" : ".exe";
1039 dll_name = xmalloc (strlen (image_basename) + strlen (suffix) + 1);
1040 sprintf (dll_name, "%s%s", image_basename, suffix);
1042 else
1043 dll_name = xstrdup (image_basename);
1046 void
1047 def_name (const char *name, int base)
1049 /* xgettext:c-format */
1050 inform (_("NAME: %s base: %x"), name, base);
1052 if (d_is_dll)
1053 non_fatal (_("Can't have LIBRARY and NAME"));
1055 if (dll_name_set_by_exp_name && name && *name != 0)
1057 dll_name = NULL;
1058 dll_name_set_by_exp_name = 0;
1060 /* If --dllname not provided, use the one in the DEF file.
1061 FIXME: Is this appropriate for executables? */
1062 if (!dll_name)
1063 set_dll_name_from_def (name, 0);
1064 d_is_exe = 1;
1067 void
1068 def_library (const char *name, int base)
1070 /* xgettext:c-format */
1071 inform (_("LIBRARY: %s base: %x"), name, base);
1073 if (d_is_exe)
1074 non_fatal (_("Can't have LIBRARY and NAME"));
1076 if (dll_name_set_by_exp_name && name && *name != 0)
1078 dll_name = NULL;
1079 dll_name_set_by_exp_name = 0;
1082 /* If --dllname not provided, use the one in the DEF file. */
1083 if (!dll_name)
1084 set_dll_name_from_def (name, 1);
1085 d_is_dll = 1;
1088 void
1089 def_description (const char *desc)
1091 dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1092 d->text = xstrdup (desc);
1093 d->next = d_list;
1094 d_list = d;
1097 static void
1098 new_directive (char *dir)
1100 dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1101 d->text = xstrdup (dir);
1102 d->next = a_list;
1103 a_list = d;
1106 void
1107 def_heapsize (int reserve, int commit)
1109 char b[200];
1110 if (commit > 0)
1111 sprintf (b, "-heap 0x%x,0x%x ", reserve, commit);
1112 else
1113 sprintf (b, "-heap 0x%x ", reserve);
1114 new_directive (xstrdup (b));
1117 void
1118 def_stacksize (int reserve, int commit)
1120 char b[200];
1121 if (commit > 0)
1122 sprintf (b, "-stack 0x%x,0x%x ", reserve, commit);
1123 else
1124 sprintf (b, "-stack 0x%x ", reserve);
1125 new_directive (xstrdup (b));
1128 /* append_import simply adds the given import definition to the global
1129 import_list. It is used by def_import. */
1131 static void
1132 append_import (const char *symbol_name, const char *dllname, int func_ordinal,
1133 const char *its_name)
1135 iheadtype **pq;
1136 iheadtype *q;
1138 for (pq = &import_list; *pq != NULL; pq = &(*pq)->next)
1140 if (strcmp ((*pq)->dllname, dllname) == 0)
1142 q = *pq;
1143 q->functail->next = xmalloc (sizeof (ifunctype));
1144 q->functail = q->functail->next;
1145 q->functail->ord = func_ordinal;
1146 q->functail->name = xstrdup (symbol_name);
1147 q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1148 q->functail->next = NULL;
1149 q->nfuncs++;
1150 return;
1154 q = xmalloc (sizeof (iheadtype));
1155 q->dllname = xstrdup (dllname);
1156 q->nfuncs = 1;
1157 q->funchead = xmalloc (sizeof (ifunctype));
1158 q->functail = q->funchead;
1159 q->next = NULL;
1160 q->functail->name = xstrdup (symbol_name);
1161 q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1162 q->functail->ord = func_ordinal;
1163 q->functail->next = NULL;
1165 *pq = q;
1168 /* def_import is called from within defparse.y when an IMPORT
1169 declaration is encountered. Depending on the form of the
1170 declaration, the module name may or may not need ".dll" to be
1171 appended to it, the name of the function may be stored in internal
1172 or entry, and there may or may not be an ordinal value associated
1173 with it. */
1175 /* A note regarding the parse modes:
1176 In defparse.y we have to accept import declarations which follow
1177 any one of the following forms:
1178 <func_name_in_app> = <dll_name>.<func_name_in_dll>
1179 <func_name_in_app> = <dll_name>.<number>
1180 <dll_name>.<func_name_in_dll>
1181 <dll_name>.<number>
1182 Furthermore, the dll's name may or may not end with ".dll", which
1183 complicates the parsing a little. Normally the dll's name is
1184 passed to def_import() in the "module" parameter, but when it ends
1185 with ".dll" it gets passed in "module" sans ".dll" and that needs
1186 to be reappended.
1188 def_import gets five parameters:
1189 APP_NAME - the name of the function in the application, if
1190 present, or NULL if not present.
1191 MODULE - the name of the dll, possibly sans extension (ie, '.dll').
1192 DLLEXT - the extension of the dll, if present, NULL if not present.
1193 ENTRY - the name of the function in the dll, if present, or NULL.
1194 ORD_VAL - the numerical tag of the function in the dll, if present,
1195 or NULL. Exactly one of <entry> or <ord_val> must be
1196 present (i.e., not NULL). */
1198 void
1199 def_import (const char *app_name, const char *module, const char *dllext,
1200 const char *entry, int ord_val, const char *its_name)
1202 const char *application_name;
1203 char *buf = NULL;
1205 if (entry != NULL)
1206 application_name = entry;
1207 else
1209 if (app_name != NULL)
1210 application_name = app_name;
1211 else
1212 application_name = "";
1215 if (dllext != NULL)
1216 module = buf = concat (module, ".", dllext, NULL);
1218 append_import (application_name, module, ord_val, its_name);
1220 free (buf);
1223 void
1224 def_version (int major, int minor)
1226 printf (_("VERSION %d.%d\n"), major, minor);
1229 void
1230 def_section (const char *name, int attr)
1232 char buf[200];
1233 char atts[5];
1234 char *d = atts;
1235 if (attr & 1)
1236 *d++ = 'R';
1238 if (attr & 2)
1239 *d++ = 'W';
1240 if (attr & 4)
1241 *d++ = 'X';
1242 if (attr & 8)
1243 *d++ = 'S';
1244 *d++ = 0;
1245 sprintf (buf, "-attr %s %s", name, atts);
1246 new_directive (xstrdup (buf));
1249 void
1250 def_code (int attr)
1253 def_section ("CODE", attr);
1256 void
1257 def_data (int attr)
1259 def_section ("DATA", attr);
1262 /**********************************************************************/
1264 static void
1265 run (const char *what, char *args)
1267 char *s;
1268 int pid, wait_status;
1269 int i;
1270 const char **argv;
1271 char *errmsg_fmt, *errmsg_arg;
1272 char *temp_base = choose_temp_base ();
1274 inform (_("run: %s %s"), what, args);
1276 /* Count the args */
1277 i = 0;
1278 for (s = args; *s; s++)
1279 if (*s == ' ')
1280 i++;
1281 i++;
1282 argv = xmalloc (sizeof (char *) * (i + 3));
1283 i = 0;
1284 argv[i++] = what;
1285 s = args;
1286 while (1)
1288 while (*s == ' ')
1289 ++s;
1290 argv[i++] = s;
1291 while (*s != ' ' && *s != 0)
1292 s++;
1293 if (*s == 0)
1294 break;
1295 *s++ = 0;
1297 argv[i++] = NULL;
1299 pid = pexecute (argv[0], (char * const *) argv, program_name, temp_base,
1300 &errmsg_fmt, &errmsg_arg, PEXECUTE_ONE | PEXECUTE_SEARCH);
1301 free (argv);
1303 if (pid == -1)
1305 inform ("%s", strerror (errno));
1307 fatal (errmsg_fmt, errmsg_arg);
1310 pid = pwait (pid, & wait_status, 0);
1312 if (pid == -1)
1314 /* xgettext:c-format */
1315 fatal (_("wait: %s"), strerror (errno));
1317 else if (WIFSIGNALED (wait_status))
1319 /* xgettext:c-format */
1320 fatal (_("subprocess got fatal signal %d"), WTERMSIG (wait_status));
1322 else if (WIFEXITED (wait_status))
1324 if (WEXITSTATUS (wait_status) != 0)
1325 /* xgettext:c-format */
1326 non_fatal (_("%s exited with status %d"),
1327 what, WEXITSTATUS (wait_status));
1329 else
1330 abort ();
1333 /* Look for a list of symbols to export in the .drectve section of
1334 ABFD. Pass each one to def_exports. */
1336 static void
1337 scan_drectve_symbols (bfd *abfd)
1339 asection * s;
1340 int size;
1341 char * buf;
1342 char * p;
1343 char * e;
1345 /* Look for .drectve's */
1346 s = bfd_get_section_by_name (abfd, DRECTVE_SECTION_NAME);
1348 if (s == NULL)
1349 return;
1351 size = bfd_section_size (s);
1352 buf = xmalloc (size);
1354 bfd_get_section_contents (abfd, s, buf, 0, size);
1356 /* xgettext:c-format */
1357 inform (_("Sucking in info from %s section in %s"),
1358 DRECTVE_SECTION_NAME, bfd_get_filename (abfd));
1360 /* Search for -export: strings. The exported symbols can optionally
1361 have type tags (eg., -export:foo,data), so handle those as well.
1362 Currently only data tag is supported. */
1363 p = buf;
1364 e = buf + size;
1365 while (p < e)
1367 if (p[0] == '-'
1368 && startswith (p, "-export:"))
1370 char * name;
1371 char * c;
1372 flagword flags = BSF_FUNCTION;
1374 p += 8;
1375 /* Do we have a quoted export? */
1376 if (*p == '"')
1378 p++;
1379 name = p;
1380 while (p < e && *p != '"')
1381 ++p;
1383 else
1385 name = p;
1386 while (p < e && *p != ',' && *p != ' ' && *p != '-')
1387 p++;
1389 c = xmalloc (p - name + 1);
1390 memcpy (c, name, p - name);
1391 c[p - name] = 0;
1392 /* Advance over trailing quote. */
1393 if (p < e && *p == '"')
1394 ++p;
1395 if (p < e && *p == ',') /* found type tag. */
1397 char *tag_start = ++p;
1398 while (p < e && *p != ' ' && *p != '-')
1399 p++;
1400 if (startswith (tag_start, "data"))
1401 flags &= ~BSF_FUNCTION;
1404 /* FIXME: The 5th arg is for the `constant' field.
1405 What should it be? Not that it matters since it's not
1406 currently useful. */
1407 def_exports (c, 0, -1, 0, 0, ! (flags & BSF_FUNCTION), 0, NULL);
1409 if (add_stdcall_alias && strchr (c, '@'))
1411 int lead_at = (*c == '@') ;
1412 char *exported_name = xstrdup (c + lead_at);
1413 char *atsym = strchr (exported_name, '@');
1414 *atsym = '\0';
1415 /* Note: stdcall alias symbols can never be data. */
1416 def_exports (exported_name, xstrdup (c), -1, 0, 0, 0, 0, NULL);
1419 else
1420 p++;
1422 free (buf);
1425 /* Look through the symbols in MINISYMS, and add each one to list of
1426 symbols to export. */
1428 static void
1429 scan_filtered_symbols (bfd *abfd, void *minisyms, long symcount,
1430 unsigned int size)
1432 asymbol *store;
1433 bfd_byte *from, *fromend;
1435 store = bfd_make_empty_symbol (abfd);
1436 if (store == NULL)
1437 bfd_fatal (bfd_get_filename (abfd));
1439 from = (bfd_byte *) minisyms;
1440 fromend = from + symcount * size;
1441 for (; from < fromend; from += size)
1443 asymbol *sym;
1444 const char *symbol_name;
1446 sym = bfd_minisymbol_to_symbol (abfd, false, from, store);
1447 if (sym == NULL)
1448 bfd_fatal (bfd_get_filename (abfd));
1450 symbol_name = bfd_asymbol_name (sym);
1451 if (bfd_get_symbol_leading_char (abfd) == symbol_name[0])
1452 ++symbol_name;
1454 def_exports (xstrdup (symbol_name) , 0, -1, 0, 0,
1455 ! (sym->flags & BSF_FUNCTION), 0, NULL);
1457 if (add_stdcall_alias && strchr (symbol_name, '@'))
1459 int lead_at = (*symbol_name == '@');
1460 char *exported_name = xstrdup (symbol_name + lead_at);
1461 char *atsym = strchr (exported_name, '@');
1462 *atsym = '\0';
1463 /* Note: stdcall alias symbols can never be data. */
1464 def_exports (exported_name, xstrdup (symbol_name), -1, 0, 0, 0, 0, NULL);
1469 /* Add a list of symbols to exclude. */
1471 static void
1472 add_excludes (const char *new_excludes)
1474 char *local_copy;
1475 char *exclude_string;
1477 local_copy = xstrdup (new_excludes);
1479 exclude_string = strtok (local_copy, ",:");
1480 for (; exclude_string; exclude_string = strtok (NULL, ",:"))
1482 struct string_list *new_exclude;
1484 new_exclude = ((struct string_list *)
1485 xmalloc (sizeof (struct string_list)));
1486 new_exclude->string = (char *) xmalloc (strlen (exclude_string) + 2);
1487 /* Don't add a leading underscore for fastcall symbols. */
1488 if (*exclude_string == '@')
1489 sprintf (new_exclude->string, "%s", exclude_string);
1490 else
1491 sprintf (new_exclude->string, "%s%s", (!leading_underscore ? "" : "_"),
1492 exclude_string);
1493 new_exclude->next = excludes;
1494 excludes = new_exclude;
1496 /* xgettext:c-format */
1497 inform (_("Excluding symbol: %s"), exclude_string);
1500 free (local_copy);
1503 /* See if STRING is on the list of symbols to exclude. */
1505 static bool
1506 match_exclude (const char *string)
1508 struct string_list *excl_item;
1510 for (excl_item = excludes; excl_item; excl_item = excl_item->next)
1511 if (strcmp (string, excl_item->string) == 0)
1512 return true;
1513 return false;
1516 /* Add the default list of symbols to exclude. */
1518 static void
1519 set_default_excludes (void)
1521 add_excludes (default_excludes);
1524 /* Choose which symbols to export. */
1526 static long
1527 filter_symbols (bfd *abfd, void *minisyms, long symcount, unsigned int size)
1529 bfd_byte *from, *fromend, *to;
1530 asymbol *store;
1532 store = bfd_make_empty_symbol (abfd);
1533 if (store == NULL)
1534 bfd_fatal (bfd_get_filename (abfd));
1536 from = (bfd_byte *) minisyms;
1537 fromend = from + symcount * size;
1538 to = (bfd_byte *) minisyms;
1540 for (; from < fromend; from += size)
1542 int keep = 0;
1543 asymbol *sym;
1545 sym = bfd_minisymbol_to_symbol (abfd, false, (const void *) from, store);
1546 if (sym == NULL)
1547 bfd_fatal (bfd_get_filename (abfd));
1549 /* Check for external and defined only symbols. */
1550 keep = (((sym->flags & BSF_GLOBAL) != 0
1551 || (sym->flags & BSF_WEAK) != 0
1552 || bfd_is_com_section (sym->section))
1553 && ! bfd_is_und_section (sym->section));
1555 keep = keep && ! match_exclude (sym->name);
1557 if (keep)
1559 memcpy (to, from, size);
1560 to += size;
1564 return (to - (bfd_byte *) minisyms) / size;
1567 /* Export all symbols in ABFD, except for ones we were told not to
1568 export. */
1570 static void
1571 scan_all_symbols (bfd *abfd)
1573 long symcount;
1574 void *minisyms;
1575 unsigned int size;
1577 /* Ignore bfds with an import descriptor table. We assume that any
1578 such BFD contains symbols which are exported from another DLL,
1579 and we don't want to reexport them from here. */
1580 if (bfd_get_section_by_name (abfd, ".idata$4"))
1581 return;
1583 if (! (bfd_get_file_flags (abfd) & HAS_SYMS))
1585 /* xgettext:c-format */
1586 non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1587 return;
1590 symcount = bfd_read_minisymbols (abfd, false, &minisyms, &size);
1591 if (symcount < 0)
1592 bfd_fatal (bfd_get_filename (abfd));
1594 if (symcount == 0)
1596 /* xgettext:c-format */
1597 non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1598 return;
1601 /* Discard the symbols we don't want to export. It's OK to do this
1602 in place; we'll free the storage anyway. */
1604 symcount = filter_symbols (abfd, minisyms, symcount, size);
1605 scan_filtered_symbols (abfd, minisyms, symcount, size);
1607 free (minisyms);
1610 /* Look at the object file to decide which symbols to export. */
1612 static void
1613 scan_open_obj_file (bfd *abfd)
1615 if (export_all_symbols)
1616 scan_all_symbols (abfd);
1617 else
1618 scan_drectve_symbols (abfd);
1620 /* FIXME: we ought to read in and block out the base relocations. */
1622 /* xgettext:c-format */
1623 inform (_("Done reading %s"), bfd_get_filename (abfd));
1626 static void
1627 scan_obj_file (const char *filename)
1629 bfd * f = bfd_openr (filename, 0);
1631 if (!f)
1632 /* xgettext:c-format */
1633 fatal (_("Unable to open object file: %s: %s"), filename, bfd_get_errmsg ());
1635 /* xgettext:c-format */
1636 inform (_("Scanning object file %s"), filename);
1638 if (bfd_check_format (f, bfd_archive))
1640 bfd *arfile = bfd_openr_next_archived_file (f, 0);
1641 while (arfile)
1643 bfd *next;
1644 if (bfd_check_format (arfile, bfd_object))
1645 scan_open_obj_file (arfile);
1646 next = bfd_openr_next_archived_file (f, arfile);
1647 bfd_close (arfile);
1648 /* PR 17512: file: 58715298. */
1649 if (next == arfile)
1650 break;
1651 arfile = next;
1654 #ifdef DLLTOOL_MCORE_ELF
1655 if (mcore_elf_out_file)
1656 inform (_("Cannot produce mcore-elf dll from archive file: %s"), filename);
1657 #endif
1659 else if (bfd_check_format (f, bfd_object))
1661 scan_open_obj_file (f);
1663 #ifdef DLLTOOL_MCORE_ELF
1664 if (mcore_elf_out_file)
1665 mcore_elf_cache_filename (filename);
1666 #endif
1669 bfd_close (f);
1674 static void
1675 dump_def_info (FILE *f)
1677 int i;
1678 export_type *exp;
1679 fprintf (f, "%s ", ASM_C);
1680 for (i = 0; oav[i]; i++)
1681 fprintf (f, "%s ", oav[i]);
1682 fprintf (f, "\n");
1683 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1685 fprintf (f, "%s %d = %s %s @ %d %s%s%s%s%s%s\n",
1686 ASM_C,
1688 exp->name,
1689 exp->internal_name,
1690 exp->ordinal,
1691 exp->noname ? "NONAME " : "",
1692 exp->private ? "PRIVATE " : "",
1693 exp->constant ? "CONSTANT" : "",
1694 exp->data ? "DATA" : "",
1695 exp->its_name ? " ==" : "",
1696 exp->its_name ? exp->its_name : "");
1700 /* Generate the .exp file. */
1702 static int
1703 sfunc (const void *a, const void *b)
1705 if (*(const bfd_vma *) a == *(const bfd_vma *) b)
1706 return 0;
1708 return ((*(const bfd_vma *) a > *(const bfd_vma *) b) ? 1 : -1);
1711 static void
1712 flush_page (FILE *f, bfd_vma *need, bfd_vma page_addr, int on_page)
1714 int i;
1716 /* Flush this page. */
1717 fprintf (f, "\t%s\t0x%08x\t%s Starting RVA for chunk\n",
1718 ASM_LONG,
1719 (int) page_addr,
1720 ASM_C);
1721 fprintf (f, "\t%s\t0x%x\t%s Size of block\n",
1722 ASM_LONG,
1723 (on_page * 2) + (on_page & 1) * 2 + 8,
1724 ASM_C);
1726 for (i = 0; i < on_page; i++)
1728 bfd_vma needed = need[i];
1730 if (needed)
1732 if (!create_for_pep)
1734 /* Relocation via HIGHLOW. */
1735 needed = ((needed - page_addr) | 0x3000) & 0xffff;
1737 else
1739 /* Relocation via DIR64. */
1740 needed = ((needed - page_addr) | 0xa000) & 0xffff;
1744 fprintf (f, "\t%s\t0x%lx\n", ASM_SHORT, (long) needed);
1747 /* And padding */
1748 if (on_page & 1)
1749 fprintf (f, "\t%s\t0x%x\n", ASM_SHORT, 0 | 0x0000);
1752 static void
1753 gen_def_file (void)
1755 int i;
1756 export_type *exp;
1758 inform (_("Adding exports to output file"));
1760 fprintf (output_def, ";");
1761 for (i = 0; oav[i]; i++)
1762 fprintf (output_def, " %s", oav[i]);
1764 fprintf (output_def, "\nEXPORTS\n");
1766 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1768 char *quote = strchr (exp->name, '.') ? "\"" : "";
1769 char *res = cplus_demangle (exp->internal_name, DMGL_ANSI | DMGL_PARAMS);
1771 if (res)
1773 fprintf (output_def,";\t%s\n", res);
1774 free (res);
1777 if (strcmp (exp->name, exp->internal_name) == 0)
1779 fprintf (output_def, "\t%s%s%s @ %d%s%s%s%s%s\n",
1780 quote,
1781 exp->name,
1782 quote,
1783 exp->ordinal,
1784 exp->noname ? " NONAME" : "",
1785 exp->private ? "PRIVATE " : "",
1786 exp->data ? " DATA" : "",
1787 exp->its_name ? " ==" : "",
1788 exp->its_name ? exp->its_name : "");
1790 else
1792 char * quote1 = strchr (exp->internal_name, '.') ? "\"" : "";
1793 /* char *alias = */
1794 fprintf (output_def, "\t%s%s%s = %s%s%s @ %d%s%s%s%s%s\n",
1795 quote,
1796 exp->name,
1797 quote,
1798 quote1,
1799 exp->internal_name,
1800 quote1,
1801 exp->ordinal,
1802 exp->noname ? " NONAME" : "",
1803 exp->private ? "PRIVATE " : "",
1804 exp->data ? " DATA" : "",
1805 exp->its_name ? " ==" : "",
1806 exp->its_name ? exp->its_name : "");
1810 inform (_("Added exports to output file"));
1813 /* generate_idata_ofile generates the portable assembly source code
1814 for the idata sections. It appends the source code to the end of
1815 the file. */
1817 static void
1818 generate_idata_ofile (FILE *filvar)
1820 iheadtype *headptr;
1821 ifunctype *funcptr;
1822 int headindex;
1823 int funcindex;
1824 int nheads;
1826 if (import_list == NULL)
1827 return;
1829 fprintf (filvar, "%s Import data sections\n", ASM_C);
1830 fprintf (filvar, "\n\t.section\t.idata$2\n");
1831 fprintf (filvar, "\t%s\tdoi_idata\n", ASM_GLOBAL);
1832 fprintf (filvar, "doi_idata:\n");
1834 nheads = 0;
1835 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1837 fprintf (filvar, "\t%slistone%d%s\t%s %s\n",
1838 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER,
1839 ASM_C, headptr->dllname);
1840 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1841 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1842 fprintf (filvar, "\t%sdllname%d%s\n",
1843 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1844 fprintf (filvar, "\t%slisttwo%d%s\n\n",
1845 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1846 nheads++;
1849 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL record at */
1850 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* end of idata$2 */
1851 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* section */
1852 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1853 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1855 fprintf (filvar, "\n\t.section\t.idata$4\n");
1856 headindex = 0;
1857 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1859 fprintf (filvar, "listone%d:\n", headindex);
1860 for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1862 if (create_for_pep)
1863 fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1864 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1865 ASM_LONG);
1866 else
1867 fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1868 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1870 if (create_for_pep)
1871 fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1872 else
1873 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
1874 headindex++;
1877 fprintf (filvar, "\n\t.section\t.idata$5\n");
1878 headindex = 0;
1879 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1881 fprintf (filvar, "listtwo%d:\n", headindex);
1882 for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1884 if (create_for_pep)
1885 fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1886 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1887 ASM_LONG);
1888 else
1889 fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1890 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1892 if (create_for_pep)
1893 fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1894 else
1895 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
1896 headindex++;
1899 fprintf (filvar, "\n\t.section\t.idata$6\n");
1900 headindex = 0;
1901 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1903 funcindex = 0;
1904 for (funcptr = headptr->funchead; funcptr != NULL;
1905 funcptr = funcptr->next)
1907 fprintf (filvar,"funcptr%d_%d:\n", headindex, funcindex);
1908 fprintf (filvar,"\t%s\t%d\n", ASM_SHORT,
1909 ((funcptr->ord) & 0xFFFF));
1910 fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT,
1911 (funcptr->its_name ? funcptr->its_name : funcptr->name));
1912 fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1913 funcindex++;
1915 headindex++;
1918 fprintf (filvar, "\n\t.section\t.idata$7\n");
1919 headindex = 0;
1920 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1922 fprintf (filvar,"dllname%d:\n", headindex);
1923 fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT, headptr->dllname);
1924 fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1925 headindex++;
1929 /* Assemble the specified file. */
1930 static void
1931 assemble_file (const char * source, const char * dest)
1933 char * cmd;
1935 cmd = xmalloc (strlen (ASM_SWITCHES) + strlen (as_flags)
1936 + strlen (source) + strlen (dest) + 50);
1938 sprintf (cmd, "%s %s -o %s %s", ASM_SWITCHES, as_flags, dest, source);
1940 run (as_name, cmd);
1941 free (cmd);
1944 static const char * temp_file_to_remove[5];
1945 #define TEMP_EXPORT_FILE 0
1946 #define TEMP_HEAD_FILE 1
1947 #define TEMP_TAIL_FILE 2
1948 #define TEMP_HEAD_O_FILE 3
1949 #define TEMP_TAIL_O_FILE 4
1951 static void
1952 unlink_temp_files (void)
1954 unsigned i;
1956 if (dontdeltemps > 0)
1957 return;
1959 for (i = 0; i < ARRAY_SIZE (temp_file_to_remove); i++)
1961 if (temp_file_to_remove[i])
1963 unlink (temp_file_to_remove[i]);
1964 temp_file_to_remove[i] = NULL;
1969 static void
1970 gen_exp_file (void)
1972 FILE *f;
1973 int i;
1974 export_type *exp;
1975 dlist_type *dl;
1977 /* xgettext:c-format */
1978 inform (_("Generating export file: %s"), exp_name);
1980 f = fopen (TMP_ASM, FOPEN_WT);
1981 if (!f)
1982 /* xgettext:c-format */
1983 fatal (_("Unable to open temporary assembler file: %s"), TMP_ASM);
1985 temp_file_to_remove[TEMP_EXPORT_FILE] = TMP_ASM;
1987 /* xgettext:c-format */
1988 inform (_("Opened temporary file: %s"), TMP_ASM);
1990 dump_def_info (f);
1992 if (d_exports)
1994 fprintf (f, "\t.section .edata\n\n");
1995 fprintf (f, "\t%s 0 %s Allways 0\n", ASM_LONG, ASM_C);
1996 fprintf (f, "\t%s 0x%lx %s Time and date\n", ASM_LONG,
1997 (unsigned long) time(0), ASM_C);
1998 fprintf (f, "\t%s 0 %s Major and Minor version\n", ASM_LONG, ASM_C);
1999 fprintf (f, "\t%sname%s %s Ptr to name of dll\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2000 fprintf (f, "\t%s %d %s Starting ordinal of exports\n", ASM_LONG, d_low_ord, ASM_C);
2003 fprintf (f, "\t%s %d %s Number of functions\n", ASM_LONG, d_high_ord - d_low_ord + 1, ASM_C);
2004 fprintf(f,"\t%s named funcs %d, low ord %d, high ord %d\n",
2005 ASM_C,
2006 d_named_nfuncs, d_low_ord, d_high_ord);
2007 fprintf (f, "\t%s %d %s Number of names\n", ASM_LONG,
2008 show_allnames ? d_high_ord - d_low_ord + 1 : d_named_nfuncs, ASM_C);
2009 fprintf (f, "\t%safuncs%s %s Address of functions\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2011 fprintf (f, "\t%sanames%s %s Address of Name Pointer Table\n",
2012 ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2014 fprintf (f, "\t%sanords%s %s Address of ordinals\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2016 fprintf (f, "name: %s \"%s\"\n", ASM_TEXT, dll_name);
2019 fprintf(f,"%s Export address Table\n", ASM_C);
2020 fprintf(f,"\t%s\n", ASM_ALIGN_LONG);
2021 fprintf (f, "afuncs:\n");
2022 i = d_low_ord;
2024 for (exp = d_exports; exp; exp = exp->next)
2026 if (exp->ordinal != i)
2028 while (i < exp->ordinal)
2030 fprintf(f,"\t%s\t0\n", ASM_LONG);
2031 i++;
2035 if (exp->forward == 0)
2037 if (exp->internal_name[0] == '@')
2038 fprintf (f, "\t%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2039 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2040 else
2041 fprintf (f, "\t%s%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2042 ASM_PREFIX (exp->internal_name),
2043 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2045 else
2046 fprintf (f, "\t%sf%d%s\t%s %d\n", ASM_RVA_BEFORE,
2047 exp->forward, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2048 i++;
2051 fprintf (f,"%s Export Name Pointer Table\n", ASM_C);
2052 fprintf (f, "anames:\n");
2054 for (i = 0; (exp = d_exports_lexically[i]); i++)
2056 if (!exp->noname || show_allnames)
2057 fprintf (f, "\t%sn%d%s\n",
2058 ASM_RVA_BEFORE, exp->ordinal, ASM_RVA_AFTER);
2061 fprintf (f,"%s Export Ordinal Table\n", ASM_C);
2062 fprintf (f, "anords:\n");
2063 for (i = 0; (exp = d_exports_lexically[i]); i++)
2065 if (!exp->noname || show_allnames)
2066 fprintf (f, "\t%s %d\n", ASM_SHORT, exp->ordinal - d_low_ord);
2069 fprintf(f,"%s Export Name Table\n", ASM_C);
2070 for (i = 0; (exp = d_exports_lexically[i]); i++)
2072 if (!exp->noname || show_allnames)
2073 fprintf (f, "n%d: %s \"%s\"\n",
2074 exp->ordinal, ASM_TEXT,
2075 (exp->its_name ? exp->its_name : xlate (exp->name)));
2076 if (exp->forward != 0)
2077 fprintf (f, "f%d: %s \"%s\"\n",
2078 exp->forward, ASM_TEXT, exp->internal_name);
2081 if (a_list)
2083 fprintf (f, "\t.section %s\n", DRECTVE_SECTION_NAME);
2084 for (dl = a_list; dl; dl = dl->next)
2086 fprintf (f, "\t%s\t\"%s\"\n", ASM_TEXT, dl->text);
2090 if (d_list)
2092 fprintf (f, "\t.section .rdata\n");
2093 for (dl = d_list; dl; dl = dl->next)
2095 char *p;
2096 int l;
2098 /* We don't output as ascii because there can
2099 be quote characters in the string. */
2100 l = 0;
2101 for (p = dl->text; *p; p++)
2103 if (l == 0)
2104 fprintf (f, "\t%s\t", ASM_BYTE);
2105 else
2106 fprintf (f, ",");
2107 fprintf (f, "%d", *p);
2108 if (p[1] == 0)
2110 fprintf (f, ",0\n");
2111 break;
2113 if (++l == 10)
2115 fprintf (f, "\n");
2116 l = 0;
2123 /* Add to the output file a way of getting to the exported names
2124 without using the import library. */
2125 if (add_indirect)
2127 fprintf (f, "\t.section\t.rdata\n");
2128 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
2129 if (!exp->noname || show_allnames)
2131 /* We use a single underscore for MS compatibility, and a
2132 double underscore for backward compatibility with old
2133 cygwin releases. */
2134 if (create_compat_implib)
2135 fprintf (f, "\t%s\t__imp_%s\n", ASM_GLOBAL, exp->name);
2136 fprintf (f, "\t%s\t_imp_%s%s\n", ASM_GLOBAL,
2137 (!leading_underscore ? "" : "_"), exp->name);
2138 if (create_compat_implib)
2139 fprintf (f, "__imp_%s:\n", exp->name);
2140 fprintf (f, "_imp_%s%s:\n", (!leading_underscore ? "" : "_"), exp->name);
2141 fprintf (f, "\t%s\t%s\n", ASM_LONG, exp->name);
2145 /* Dump the reloc section if a base file is provided. */
2146 if (base_file)
2148 bfd_vma addr;
2149 bfd_vma need[COFF_PAGE_SIZE];
2150 bfd_vma page_addr;
2151 bfd_size_type numbytes;
2152 int num_entries;
2153 bfd_vma *copy;
2154 int j;
2155 int on_page;
2156 fprintf (f, "\t.section\t.init\n");
2157 fprintf (f, "lab:\n");
2159 fseek (base_file, 0, SEEK_END);
2160 numbytes = ftell (base_file);
2161 fseek (base_file, 0, SEEK_SET);
2162 copy = xmalloc (numbytes);
2163 if (fread (copy, 1, numbytes, base_file) < numbytes)
2164 fatal (_("failed to read the number of entries from base file"));
2165 num_entries = numbytes / sizeof (bfd_vma);
2168 fprintf (f, "\t.section\t.reloc\n");
2169 if (num_entries)
2171 int src;
2172 int dst = 0;
2173 bfd_vma last = (bfd_vma) -1;
2174 qsort (copy, num_entries, sizeof (bfd_vma), sfunc);
2175 /* Delete duplicates */
2176 for (src = 0; src < num_entries; src++)
2178 if (last != copy[src])
2179 last = copy[dst++] = copy[src];
2181 num_entries = dst;
2182 addr = copy[0];
2183 page_addr = addr & PAGE_MASK; /* work out the page addr */
2184 on_page = 0;
2185 for (j = 0; j < num_entries; j++)
2187 addr = copy[j];
2188 if ((addr & PAGE_MASK) != page_addr)
2190 flush_page (f, need, page_addr, on_page);
2191 on_page = 0;
2192 page_addr = addr & PAGE_MASK;
2194 need[on_page++] = addr;
2196 flush_page (f, need, page_addr, on_page);
2198 /* fprintf (f, "\t%s\t0,0\t%s End\n", ASM_LONG, ASM_C);*/
2202 generate_idata_ofile (f);
2204 fclose (f);
2206 /* Assemble the file. */
2207 assemble_file (TMP_ASM, exp_name);
2209 if (dontdeltemps == 0)
2211 temp_file_to_remove[TEMP_EXPORT_FILE] = NULL;
2212 unlink (TMP_ASM);
2215 inform (_("Generated exports file"));
2218 static const char *
2219 xlate (const char *name)
2221 int lead_at = (*name == '@');
2222 int is_stdcall = (!lead_at && strchr (name, '@') != NULL);
2224 if (!lead_at && (add_underscore
2225 || (add_stdcall_underscore && is_stdcall)))
2227 char *copy = xmalloc (strlen (name) + 2);
2229 copy[0] = '_';
2230 strcpy (copy + 1, name);
2231 name = copy;
2234 if (killat)
2236 char *p;
2238 name += lead_at;
2239 /* PR 9766: Look for the last @ sign in the name. */
2240 p = strrchr (name, '@');
2241 if (p && ISDIGIT (p[1]))
2242 *p = 0;
2244 return name;
2247 typedef struct
2249 int id;
2250 const char *name;
2251 int flags;
2252 int align;
2253 asection *sec;
2254 asymbol *sym;
2255 asymbol **sympp;
2256 int size;
2257 unsigned char *data;
2258 } sinfo;
2260 #define INIT_SEC_DATA(id, name, flags, align) \
2261 { id, name, flags, align, NULL, NULL, NULL, 0, NULL }
2263 #define TEXT 0
2264 #define DATA 1
2265 #define BSS 2
2266 #define IDATA7 3
2267 #define IDATA5 4
2268 #define IDATA4 5
2269 #define IDATA6 6
2271 #define NSECS 7
2273 #define TEXT_SEC_FLAGS \
2274 (SEC_ALLOC | SEC_LOAD | SEC_CODE | SEC_READONLY | SEC_HAS_CONTENTS)
2275 #define DATA_SEC_FLAGS (SEC_ALLOC | SEC_LOAD | SEC_DATA)
2276 #define BSS_SEC_FLAGS SEC_ALLOC
2278 static sinfo secdata[NSECS] =
2280 INIT_SEC_DATA (TEXT, ".text", TEXT_SEC_FLAGS, 2),
2281 INIT_SEC_DATA (DATA, ".data", DATA_SEC_FLAGS, 2),
2282 INIT_SEC_DATA (BSS, ".bss", BSS_SEC_FLAGS, 2),
2283 INIT_SEC_DATA (IDATA7, ".idata$7", SEC_HAS_CONTENTS, 2),
2284 INIT_SEC_DATA (IDATA5, ".idata$5", SEC_HAS_CONTENTS, 2),
2285 INIT_SEC_DATA (IDATA4, ".idata$4", SEC_HAS_CONTENTS, 2),
2286 INIT_SEC_DATA (IDATA6, ".idata$6", SEC_HAS_CONTENTS, 1)
2289 /* This is what we're trying to make. We generate the imp symbols with
2290 both single and double underscores, for compatibility.
2292 .text
2293 .global _GetFileVersionInfoSizeW@8
2294 .global __imp_GetFileVersionInfoSizeW@8
2295 _GetFileVersionInfoSizeW@8:
2296 jmp * __imp_GetFileVersionInfoSizeW@8
2297 .section .idata$7 # To force loading of head
2298 .long __version_a_head
2299 # Import Address Table
2300 .section .idata$5
2301 __imp_GetFileVersionInfoSizeW@8:
2302 .rva ID2
2304 # Import Lookup Table
2305 .section .idata$4
2306 .rva ID2
2307 # Hint/Name table
2308 .section .idata$6
2309 ID2: .short 2
2310 .asciz "GetFileVersionInfoSizeW" */
2312 static char *
2313 make_label (const char *prefix, const char *name)
2315 int len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2316 char *copy = xmalloc (len + 1);
2318 strcpy (copy, ASM_PREFIX (name));
2319 strcat (copy, prefix);
2320 strcat (copy, name);
2321 return copy;
2324 static char *
2325 make_imp_label (const char *prefix, const char *name)
2327 int len;
2328 char *copy;
2330 if (name[0] == '@')
2332 len = strlen (prefix) + strlen (name);
2333 copy = xmalloc (len + 1);
2334 strcpy (copy, prefix);
2335 strcat (copy, name);
2337 else
2339 len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2340 copy = xmalloc (len + 1);
2341 strcpy (copy, prefix);
2342 strcat (copy, ASM_PREFIX (name));
2343 strcat (copy, name);
2345 return copy;
2348 static bfd *
2349 make_one_lib_file (export_type *exp, int i, int delay)
2351 bfd * abfd;
2352 asymbol * exp_label;
2353 asymbol * iname = 0;
2354 asymbol * iname2;
2355 asymbol * iname_lab;
2356 asymbol ** iname_lab_pp;
2357 asymbol ** iname_pp;
2358 #ifndef EXTRA
2359 #define EXTRA 0
2360 #endif
2361 asymbol * ptrs[NSECS + 4 + EXTRA + 1];
2362 flagword applicable;
2363 char * outname = xmalloc (strlen (TMP_STUB) + 10);
2364 int oidx = 0;
2367 sprintf (outname, "%s%05d.o", TMP_STUB, i);
2369 abfd = bfd_openw (outname, HOW_BFD_WRITE_TARGET);
2371 if (!abfd)
2372 /* xgettext:c-format */
2373 fatal (_("bfd_open failed open stub file: %s: %s"),
2374 outname, bfd_get_errmsg ());
2376 /* xgettext:c-format */
2377 inform (_("Creating stub file: %s"), outname);
2379 bfd_set_format (abfd, bfd_object);
2380 bfd_set_arch_mach (abfd, HOW_BFD_ARCH, 0);
2382 #ifdef DLLTOOL_ARM
2383 if (machine == MARM_INTERWORK || machine == MTHUMB)
2384 bfd_set_private_flags (abfd, F_INTERWORK);
2385 #endif
2387 applicable = bfd_applicable_section_flags (abfd);
2389 /* First make symbols for the sections. */
2390 for (i = 0; i < NSECS; i++)
2392 sinfo *si = secdata + i;
2394 if (si->id != i)
2395 abort ();
2396 si->sec = bfd_make_section_old_way (abfd, si->name);
2397 bfd_set_section_flags (si->sec, si->flags & applicable);
2399 bfd_set_section_alignment (si->sec, si->align);
2400 si->sec->output_section = si->sec;
2401 si->sym = bfd_make_empty_symbol(abfd);
2402 si->sym->name = si->sec->name;
2403 si->sym->section = si->sec;
2404 si->sym->flags = BSF_LOCAL;
2405 si->sym->value = 0;
2406 ptrs[oidx] = si->sym;
2407 si->sympp = ptrs + oidx;
2408 si->size = 0;
2409 si->data = NULL;
2411 oidx++;
2414 if (! exp->data)
2416 exp_label = bfd_make_empty_symbol (abfd);
2417 exp_label->name = make_imp_label ("", exp->name);
2418 exp_label->section = secdata[TEXT].sec;
2419 exp_label->flags = BSF_GLOBAL;
2420 exp_label->value = 0;
2422 #ifdef DLLTOOL_ARM
2423 if (machine == MTHUMB)
2424 bfd_coff_set_symbol_class (abfd, exp_label, C_THUMBEXTFUNC);
2425 #endif
2426 ptrs[oidx++] = exp_label;
2429 /* Generate imp symbols with one underscore for Microsoft
2430 compatibility, and with two underscores for backward
2431 compatibility with old versions of cygwin. */
2432 if (create_compat_implib)
2434 iname = bfd_make_empty_symbol (abfd);
2435 iname->name = make_imp_label ("___imp", exp->name);
2436 iname->section = secdata[IDATA5].sec;
2437 iname->flags = BSF_GLOBAL;
2438 iname->value = 0;
2441 iname2 = bfd_make_empty_symbol (abfd);
2442 iname2->name = make_imp_label ("__imp_", exp->name);
2443 iname2->section = secdata[IDATA5].sec;
2444 iname2->flags = BSF_GLOBAL;
2445 iname2->value = 0;
2447 iname_lab = bfd_make_empty_symbol (abfd);
2449 iname_lab->name = head_label;
2450 iname_lab->section = bfd_und_section_ptr;
2451 iname_lab->flags = 0;
2452 iname_lab->value = 0;
2454 iname_pp = ptrs + oidx;
2455 if (create_compat_implib)
2456 ptrs[oidx++] = iname;
2457 ptrs[oidx++] = iname2;
2459 iname_lab_pp = ptrs + oidx;
2460 ptrs[oidx++] = iname_lab;
2462 ptrs[oidx] = 0;
2464 for (i = 0; i < NSECS; i++)
2466 sinfo *si = secdata + i;
2467 asection *sec = si->sec;
2468 arelent *rel, *rel2 = 0, *rel3 = 0;
2469 arelent **rpp;
2471 switch (i)
2473 case TEXT:
2474 if (! exp->data)
2476 si->size = HOW_JTAB_SIZE;
2477 si->data = xmalloc (HOW_JTAB_SIZE);
2478 memcpy (si->data, HOW_JTAB, HOW_JTAB_SIZE);
2480 /* Add the reloc into idata$5. */
2481 rel = xmalloc (sizeof (arelent));
2483 rpp = xmalloc (sizeof (arelent *) * (delay ? 4 : 2));
2484 rpp[0] = rel;
2485 rpp[1] = 0;
2487 rel->address = HOW_JTAB_ROFF;
2488 rel->addend = 0;
2490 if (delay)
2492 rel2 = xmalloc (sizeof (arelent));
2493 rpp[1] = rel2;
2494 rel2->address = HOW_JTAB_ROFF2;
2495 rel2->addend = 0;
2496 rel3 = xmalloc (sizeof (arelent));
2497 rpp[2] = rel3;
2498 rel3->address = HOW_JTAB_ROFF3;
2499 rel3->addend = 0;
2500 rpp[3] = 0;
2503 if (machine == MX86)
2505 rel->howto = bfd_reloc_type_lookup (abfd,
2506 BFD_RELOC_32_PCREL);
2507 rel->sym_ptr_ptr = iname_pp;
2509 else
2511 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2512 rel->sym_ptr_ptr = secdata[IDATA5].sympp;
2515 if (delay)
2517 if (machine == MX86)
2518 rel2->howto = bfd_reloc_type_lookup (abfd,
2519 BFD_RELOC_32_PCREL);
2520 else
2521 rel2->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2522 rel2->sym_ptr_ptr = rel->sym_ptr_ptr;
2523 rel3->howto = bfd_reloc_type_lookup (abfd,
2524 BFD_RELOC_32_PCREL);
2525 rel3->sym_ptr_ptr = iname_lab_pp;
2528 sec->orelocation = rpp;
2529 sec->reloc_count = delay ? 3 : 1;
2531 break;
2533 case IDATA5:
2534 if (delay)
2536 si->size = create_for_pep ? 8 : 4;
2537 si->data = xmalloc (si->size);
2538 sec->reloc_count = 1;
2539 memset (si->data, 0, si->size);
2540 /* Point after jmp [__imp_...] instruction. */
2541 si->data[0] = 6;
2542 rel = xmalloc (sizeof (arelent));
2543 rpp = xmalloc (sizeof (arelent *) * 2);
2544 rpp[0] = rel;
2545 rpp[1] = 0;
2546 rel->address = 0;
2547 rel->addend = 0;
2548 if (create_for_pep)
2549 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_64);
2550 else
2551 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2552 rel->sym_ptr_ptr = secdata[TEXT].sympp;
2553 sec->orelocation = rpp;
2554 break;
2556 /* Fall through. */
2558 case IDATA4:
2559 /* An idata$4 or idata$5 is one word long, and has an
2560 rva to idata$6. */
2562 if (create_for_pep)
2564 si->data = xmalloc (8);
2565 si->size = 8;
2566 if (exp->noname)
2568 si->data[0] = exp->ordinal ;
2569 si->data[1] = exp->ordinal >> 8;
2570 si->data[2] = exp->ordinal >> 16;
2571 si->data[3] = exp->ordinal >> 24;
2572 si->data[4] = 0;
2573 si->data[5] = 0;
2574 si->data[6] = 0;
2575 si->data[7] = 0x80;
2577 else
2579 sec->reloc_count = 1;
2580 memset (si->data, 0, si->size);
2581 rel = xmalloc (sizeof (arelent));
2582 rpp = xmalloc (sizeof (arelent *) * 2);
2583 rpp[0] = rel;
2584 rpp[1] = 0;
2585 rel->address = 0;
2586 rel->addend = 0;
2587 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2588 rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2589 sec->orelocation = rpp;
2592 else
2594 si->data = xmalloc (4);
2595 si->size = 4;
2597 if (exp->noname)
2599 si->data[0] = exp->ordinal ;
2600 si->data[1] = exp->ordinal >> 8;
2601 si->data[2] = exp->ordinal >> 16;
2602 si->data[3] = 0x80;
2604 else
2606 sec->reloc_count = 1;
2607 memset (si->data, 0, si->size);
2608 rel = xmalloc (sizeof (arelent));
2609 rpp = xmalloc (sizeof (arelent *) * 2);
2610 rpp[0] = rel;
2611 rpp[1] = 0;
2612 rel->address = 0;
2613 rel->addend = 0;
2614 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2615 rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2616 sec->orelocation = rpp;
2619 break;
2621 case IDATA6:
2622 if (!exp->noname)
2624 int idx = exp->ordinal;
2626 if (exp->its_name)
2627 si->size = strlen (exp->its_name) + 3;
2628 else
2629 si->size = strlen (xlate (exp->import_name)) + 3;
2630 si->data = xmalloc (si->size);
2631 memset (si->data, 0, si->size);
2632 si->data[0] = idx & 0xff;
2633 si->data[1] = idx >> 8;
2634 if (exp->its_name)
2635 strcpy ((char *) si->data + 2, exp->its_name);
2636 else
2637 strcpy ((char *) si->data + 2, xlate (exp->import_name));
2639 break;
2640 case IDATA7:
2641 if (delay)
2642 break;
2643 si->size = 4;
2644 si->data = xmalloc (4);
2645 memset (si->data, 0, si->size);
2646 rel = xmalloc (sizeof (arelent));
2647 rpp = xmalloc (sizeof (arelent *) * 2);
2648 rpp[0] = rel;
2649 rel->address = 0;
2650 rel->addend = 0;
2651 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2652 rel->sym_ptr_ptr = iname_lab_pp;
2653 sec->orelocation = rpp;
2654 sec->reloc_count = 1;
2655 break;
2660 bfd_vma vma = 0;
2661 /* Size up all the sections. */
2662 for (i = 0; i < NSECS; i++)
2664 sinfo *si = secdata + i;
2666 bfd_set_section_size (si->sec, si->size);
2667 bfd_set_section_vma (si->sec, vma);
2670 /* Write them out. */
2671 for (i = 0; i < NSECS; i++)
2673 sinfo *si = secdata + i;
2675 if (i == IDATA5 && no_idata5)
2676 continue;
2678 if (i == IDATA4 && no_idata4)
2679 continue;
2681 bfd_set_section_contents (abfd, si->sec,
2682 si->data, 0,
2683 si->size);
2686 bfd_set_symtab (abfd, ptrs, oidx);
2687 bfd_close (abfd);
2688 abfd = bfd_openr (outname, HOW_BFD_READ_TARGET);
2689 if (!abfd)
2690 /* xgettext:c-format */
2691 fatal (_("bfd_open failed reopen stub file: %s: %s"),
2692 outname, bfd_get_errmsg ());
2694 return abfd;
2697 static bfd *
2698 make_head (void)
2700 FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2701 bfd *abfd;
2703 if (f == NULL)
2705 fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2706 return NULL;
2709 temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2711 fprintf (f, "%s IMAGE_IMPORT_DESCRIPTOR\n", ASM_C);
2712 fprintf (f, "\t.section\t.idata$2\n");
2714 fprintf (f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2716 fprintf (f, "%s:\n", head_label);
2718 fprintf (f, "\t%shname%s\t%sPtr to image import by name list\n",
2719 ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2721 fprintf (f, "\t%sthis should be the timestamp, but NT sometimes\n", ASM_C);
2722 fprintf (f, "\t%sdoesn't load DLLs when this is set.\n", ASM_C);
2723 fprintf (f, "\t%s\t0\t%s loaded time\n", ASM_LONG, ASM_C);
2724 fprintf (f, "\t%s\t0\t%s Forwarder chain\n", ASM_LONG, ASM_C);
2725 fprintf (f, "\t%s__%s_iname%s\t%s imported dll's name\n",
2726 ASM_RVA_BEFORE,
2727 imp_name_lab,
2728 ASM_RVA_AFTER,
2729 ASM_C);
2730 fprintf (f, "\t%sfthunk%s\t%s pointer to firstthunk\n",
2731 ASM_RVA_BEFORE,
2732 ASM_RVA_AFTER, ASM_C);
2734 fprintf (f, "%sStuff for compatibility\n", ASM_C);
2736 if (!no_idata5)
2738 fprintf (f, "\t.section\t.idata$5\n");
2739 if (use_nul_prefixed_import_tables)
2741 if (create_for_pep)
2742 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2743 else
2744 fprintf (f,"\t%s\t0\n", ASM_LONG);
2746 fprintf (f, "fthunk:\n");
2749 if (!no_idata4)
2751 fprintf (f, "\t.section\t.idata$4\n");
2752 if (use_nul_prefixed_import_tables)
2754 if (create_for_pep)
2755 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2756 else
2757 fprintf (f,"\t%s\t0\n", ASM_LONG);
2759 fprintf (f, "hname:\n");
2762 fclose (f);
2764 assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2766 abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2767 if (abfd == NULL)
2768 /* xgettext:c-format */
2769 fatal (_("failed to open temporary head file: %s: %s"),
2770 TMP_HEAD_O, bfd_get_errmsg ());
2772 temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2773 return abfd;
2776 bfd *
2777 make_delay_head (void)
2779 FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2780 bfd *abfd;
2782 if (f == NULL)
2784 fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2785 return NULL;
2788 temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2790 /* Output the __tailMerge__xxx function */
2791 fprintf (f, "%s Import trampoline\n", ASM_C);
2792 fprintf (f, "\t.section\t.text\n");
2793 fprintf(f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2794 if (HOW_SEH)
2795 fprintf (f, "\t.seh_proc\t%s\n", head_label);
2796 fprintf (f, "%s:\n", head_label);
2797 fprintf (f, mtable[machine].trampoline, imp_name_lab);
2798 if (HOW_SEH)
2799 fprintf (f, "\t.seh_endproc\n");
2801 /* Output the delay import descriptor */
2802 fprintf (f, "\n%s DELAY_IMPORT_DESCRIPTOR\n", ASM_C);
2803 fprintf (f, ".section\t.text$2\n");
2804 fprintf (f,"%s __DELAY_IMPORT_DESCRIPTOR_%s\n", ASM_GLOBAL,imp_name_lab);
2805 fprintf (f, "__DELAY_IMPORT_DESCRIPTOR_%s:\n", imp_name_lab);
2806 fprintf (f, "\t%s 1\t%s grAttrs\n", ASM_LONG, ASM_C);
2807 fprintf (f, "\t%s__%s_iname%s\t%s rvaDLLName\n",
2808 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2809 fprintf (f, "\t%s__DLL_HANDLE_%s%s\t%s rvaHmod\n",
2810 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2811 fprintf (f, "\t%s__IAT_%s%s\t%s rvaIAT\n",
2812 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2813 fprintf (f, "\t%s__INT_%s%s\t%s rvaINT\n",
2814 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2815 fprintf (f, "\t%s\t0\t%s rvaBoundIAT\n", ASM_LONG, ASM_C);
2816 fprintf (f, "\t%s\t0\t%s rvaUnloadIAT\n", ASM_LONG, ASM_C);
2817 fprintf (f, "\t%s\t0\t%s dwTimeStamp\n", ASM_LONG, ASM_C);
2819 /* Output the dll_handle */
2820 fprintf (f, "\n.section .data\n");
2821 fprintf (f, "__DLL_HANDLE_%s:\n", imp_name_lab);
2822 fprintf (f, "\t%s\t0\t%s Handle\n", ASM_LONG, ASM_C);
2823 if (create_for_pep)
2824 fprintf (f, "\t%s\t0\n", ASM_LONG);
2825 fprintf (f, "\n");
2827 fprintf (f, "%sStuff for compatibility\n", ASM_C);
2829 if (!no_idata5)
2831 fprintf (f, "\t.section\t.idata$5\n");
2832 /* NULL terminating list. */
2833 if (create_for_pep)
2834 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2835 else
2836 fprintf (f,"\t%s\t0\n", ASM_LONG);
2837 fprintf (f, "__IAT_%s:\n", imp_name_lab);
2840 if (!no_idata4)
2842 fprintf (f, "\t.section\t.idata$4\n");
2843 fprintf (f, "\t%s\t0\n", ASM_LONG);
2844 if (create_for_pep)
2845 fprintf (f, "\t%s\t0\n", ASM_LONG);
2846 fprintf (f, "\t.section\t.idata$4\n");
2847 fprintf (f, "__INT_%s:\n", imp_name_lab);
2850 fprintf (f, "\t.section\t.idata$2\n");
2852 fclose (f);
2854 assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2856 abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2857 if (abfd == NULL)
2858 /* xgettext:c-format */
2859 fatal (_("failed to open temporary head file: %s: %s"),
2860 TMP_HEAD_O, bfd_get_errmsg ());
2862 temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2863 return abfd;
2866 static bfd *
2867 make_tail (void)
2869 FILE *f = fopen (TMP_TAIL_S, FOPEN_WT);
2870 bfd *abfd;
2872 if (f == NULL)
2874 fatal (_("failed to open temporary tail file: %s"), TMP_TAIL_S);
2875 return NULL;
2878 temp_file_to_remove[TEMP_TAIL_FILE] = TMP_TAIL_S;
2880 if (!no_idata4)
2882 fprintf (f, "\t.section\t.idata$4\n");
2883 if (create_for_pep)
2884 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2885 else
2886 fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
2889 if (!no_idata5)
2891 fprintf (f, "\t.section\t.idata$5\n");
2892 if (create_for_pep)
2893 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2894 else
2895 fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
2898 fprintf (f, "\t.section\t.idata$7\n");
2899 fprintf (f, "\t%s\t__%s_iname\n", ASM_GLOBAL, imp_name_lab);
2900 fprintf (f, "__%s_iname:\t%s\t\"%s\"\n",
2901 imp_name_lab, ASM_TEXT, dll_name);
2903 fclose (f);
2905 assemble_file (TMP_TAIL_S, TMP_TAIL_O);
2907 abfd = bfd_openr (TMP_TAIL_O, HOW_BFD_READ_TARGET);
2908 if (abfd == NULL)
2909 /* xgettext:c-format */
2910 fatal (_("failed to open temporary tail file: %s: %s"),
2911 TMP_TAIL_O, bfd_get_errmsg ());
2913 temp_file_to_remove[TEMP_TAIL_O_FILE] = TMP_TAIL_O;
2914 return abfd;
2917 static void
2918 gen_lib_file (int delay)
2920 int i;
2921 export_type *exp;
2922 bfd *ar_head;
2923 bfd *ar_tail;
2924 bfd *outarch;
2925 bfd * head = 0;
2927 unlink (imp_name);
2929 outarch = bfd_openw (imp_name, HOW_BFD_WRITE_TARGET);
2931 if (!outarch)
2932 /* xgettext:c-format */
2933 fatal (_("Can't create .lib file: %s: %s"),
2934 imp_name, bfd_get_errmsg ());
2936 /* xgettext:c-format */
2937 inform (_("Creating library file: %s"), imp_name);
2939 xatexit (unlink_temp_files);
2941 bfd_set_format (outarch, bfd_archive);
2942 outarch->has_armap = 1;
2943 outarch->is_thin_archive = 0;
2945 /* Work out a reasonable size of things to put onto one line. */
2946 if (delay)
2948 ar_head = make_delay_head ();
2950 else
2952 ar_head = make_head ();
2954 ar_tail = make_tail();
2956 if (ar_head == NULL || ar_tail == NULL)
2957 return;
2959 for (i = 0; (exp = d_exports_lexically[i]); i++)
2961 bfd *n;
2962 /* Don't add PRIVATE entries to import lib. */
2963 if (exp->private)
2964 continue;
2965 n = make_one_lib_file (exp, i, delay);
2966 n->archive_next = head;
2967 head = n;
2968 if (ext_prefix_alias)
2970 export_type alias_exp;
2972 assert (i < PREFIX_ALIAS_BASE);
2973 alias_exp.name = make_imp_label (ext_prefix_alias, exp->name);
2974 alias_exp.internal_name = exp->internal_name;
2975 alias_exp.its_name = exp->its_name;
2976 alias_exp.import_name = exp->name;
2977 alias_exp.ordinal = exp->ordinal;
2978 alias_exp.constant = exp->constant;
2979 alias_exp.noname = exp->noname;
2980 alias_exp.private = exp->private;
2981 alias_exp.data = exp->data;
2982 alias_exp.forward = exp->forward;
2983 alias_exp.next = exp->next;
2984 n = make_one_lib_file (&alias_exp, i + PREFIX_ALIAS_BASE, delay);
2985 n->archive_next = head;
2986 head = n;
2990 /* Now stick them all into the archive. */
2991 ar_head->archive_next = head;
2992 ar_tail->archive_next = ar_head;
2993 head = ar_tail;
2995 if (! bfd_set_archive_head (outarch, head))
2996 bfd_fatal ("bfd_set_archive_head");
2998 if (! bfd_close (outarch))
2999 bfd_fatal (imp_name);
3001 while (head != NULL)
3003 bfd *n = head->archive_next;
3004 bfd_close (head);
3005 head = n;
3008 /* Delete all the temp files. */
3009 unlink_temp_files ();
3011 if (dontdeltemps < 2)
3013 char *name;
3015 name = xmalloc (strlen (TMP_STUB) + 10);
3016 for (i = 0; (exp = d_exports_lexically[i]); i++)
3018 /* Don't delete non-existent stubs for PRIVATE entries. */
3019 if (exp->private)
3020 continue;
3021 sprintf (name, "%s%05d.o", TMP_STUB, i);
3022 if (unlink (name) < 0)
3023 /* xgettext:c-format */
3024 non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3025 if (ext_prefix_alias)
3027 sprintf (name, "%s%05d.o", TMP_STUB, i + PREFIX_ALIAS_BASE);
3028 if (unlink (name) < 0)
3029 /* xgettext:c-format */
3030 non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3033 free (name);
3036 inform (_("Created lib file"));
3039 /* Append a copy of data (cast to char *) to list. */
3041 static void
3042 dll_name_list_append (dll_name_list_type * list, bfd_byte * data)
3044 dll_name_list_node_type * entry;
3046 /* Error checking. */
3047 if (! list || ! list->tail)
3048 return;
3050 /* Allocate new node. */
3051 entry = ((dll_name_list_node_type *)
3052 xmalloc (sizeof (dll_name_list_node_type)));
3054 /* Initialize its values. */
3055 entry->dllname = xstrdup ((char *) data);
3056 entry->next = NULL;
3058 /* Add to tail, and move tail. */
3059 list->tail->next = entry;
3060 list->tail = entry;
3063 /* Count the number of entries in list. */
3065 static int
3066 dll_name_list_count (dll_name_list_type * list)
3068 dll_name_list_node_type * p;
3069 int count = 0;
3071 /* Error checking. */
3072 if (! list || ! list->head)
3073 return 0;
3075 p = list->head;
3077 while (p && p->next)
3079 count++;
3080 p = p->next;
3082 return count;
3085 /* Print each entry in list to stdout. */
3087 static void
3088 dll_name_list_print (dll_name_list_type * list)
3090 dll_name_list_node_type * p;
3092 /* Error checking. */
3093 if (! list || ! list->head)
3094 return;
3096 p = list->head;
3098 while (p && p->next && p->next->dllname && *(p->next->dllname))
3100 printf ("%s\n", p->next->dllname);
3101 p = p->next;
3105 /* Free all entries in list, and list itself. */
3107 static void
3108 dll_name_list_free (dll_name_list_type * list)
3110 if (list)
3112 dll_name_list_free_contents (list->head);
3113 list->head = NULL;
3114 list->tail = NULL;
3115 free (list);
3119 /* Recursive function to free all nodes entry->next->next...
3120 as well as entry itself. */
3122 static void
3123 dll_name_list_free_contents (dll_name_list_node_type * entry)
3125 if (entry)
3127 if (entry->next)
3128 dll_name_list_free_contents (entry->next);
3129 free (entry->dllname);
3130 free (entry);
3134 /* Allocate and initialize a dll_name_list_type object,
3135 including its sentinel node. Caller is responsible
3136 for calling dll_name_list_free when finished with
3137 the list. */
3139 static dll_name_list_type *
3140 dll_name_list_create (void)
3142 /* Allocate list. */
3143 dll_name_list_type * list = xmalloc (sizeof (dll_name_list_type));
3145 /* Allocate and initialize sentinel node. */
3146 list->head = xmalloc (sizeof (dll_name_list_node_type));
3147 list->head->dllname = NULL;
3148 list->head->next = NULL;
3150 /* Bookkeeping for empty list. */
3151 list->tail = list->head;
3153 return list;
3156 /* Search the symbol table of the suppled BFD for a symbol whose name matches
3157 OBJ (where obj is cast to const char *). If found, set global variable
3158 identify_member_contains_symname_result TRUE. It is the caller's
3159 responsibility to set the result variable FALSE before iterating with
3160 this function. */
3162 static void
3163 identify_member_contains_symname (bfd * abfd,
3164 bfd * archive_bfd ATTRIBUTE_UNUSED,
3165 void * obj)
3167 long storage_needed;
3168 asymbol ** symbol_table;
3169 long number_of_symbols;
3170 long i;
3171 symname_search_data_type * search_data = (symname_search_data_type *) obj;
3173 /* If we already found the symbol in a different member,
3174 short circuit. */
3175 if (search_data->found)
3176 return;
3178 storage_needed = bfd_get_symtab_upper_bound (abfd);
3179 if (storage_needed <= 0)
3180 return;
3182 symbol_table = xmalloc (storage_needed);
3183 number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
3184 if (number_of_symbols < 0)
3186 free (symbol_table);
3187 return;
3190 for (i = 0; i < number_of_symbols; i++)
3192 if (strncmp (symbol_table[i]->name,
3193 search_data->symname,
3194 strlen (search_data->symname)) == 0)
3196 search_data->found = true;
3197 break;
3200 free (symbol_table);
3203 /* This is the main implementation for the --identify option.
3204 Given the name of an import library in identify_imp_name, first
3205 determine if the import library is a GNU binutils-style one (where
3206 the DLL name is stored in an .idata$7 section), or if it is a
3207 MS-style one (where the DLL name, along with much other data, is
3208 stored in the .idata$6 section). We determine the style of import
3209 library by searching for the DLL-structure symbol inserted by MS
3210 tools: __NULL_IMPORT_DESCRIPTOR.
3212 Once we know which section to search, evaluate each section for the
3213 appropriate properties that indicate it may contain the name of the
3214 associated DLL (this differs depending on the style). Add the contents
3215 of all sections which meet the criteria to a linked list of dll names.
3217 Finally, print them all to stdout. (If --identify-strict, an error is
3218 reported if more than one match was found). */
3220 static void
3221 identify_dll_for_implib (void)
3223 bfd * abfd = NULL;
3224 int count = 0;
3225 identify_data_type identify_data;
3226 symname_search_data_type search_data;
3228 /* Initialize identify_data. */
3229 identify_data.list = dll_name_list_create ();
3230 identify_data.ms_style_implib = false;
3232 /* Initialize search_data. */
3233 search_data.symname = "__NULL_IMPORT_DESCRIPTOR";
3234 search_data.found = false;
3236 if (bfd_init () != BFD_INIT_MAGIC)
3237 fatal (_("fatal error: libbfd ABI mismatch"));
3239 abfd = bfd_openr (identify_imp_name, 0);
3240 if (abfd == NULL)
3241 /* xgettext:c-format */
3242 fatal (_("Can't open .lib file: %s: %s"),
3243 identify_imp_name, bfd_get_errmsg ());
3245 if (! bfd_check_format (abfd, bfd_archive))
3247 if (! bfd_close (abfd))
3248 bfd_fatal (identify_imp_name);
3250 fatal (_("%s is not a library"), identify_imp_name);
3253 /* Detect if this a Microsoft import library. */
3254 identify_search_archive (abfd,
3255 identify_member_contains_symname,
3256 (void *)(& search_data));
3257 if (search_data.found)
3258 identify_data.ms_style_implib = true;
3260 /* Rewind the bfd. */
3261 if (! bfd_close (abfd))
3262 bfd_fatal (identify_imp_name);
3263 abfd = bfd_openr (identify_imp_name, 0);
3264 if (abfd == NULL)
3265 bfd_fatal (identify_imp_name);
3267 if (!bfd_check_format (abfd, bfd_archive))
3269 if (!bfd_close (abfd))
3270 bfd_fatal (identify_imp_name);
3272 fatal (_("%s is not a library"), identify_imp_name);
3275 /* Now search for the dll name. */
3276 identify_search_archive (abfd,
3277 identify_search_member,
3278 (void *)(& identify_data));
3280 if (! bfd_close (abfd))
3281 bfd_fatal (identify_imp_name);
3283 count = dll_name_list_count (identify_data.list);
3284 if (count > 0)
3286 if (identify_strict && count > 1)
3288 dll_name_list_free (identify_data.list);
3289 identify_data.list = NULL;
3290 fatal (_("Import library `%s' specifies two or more dlls"),
3291 identify_imp_name);
3293 dll_name_list_print (identify_data.list);
3294 dll_name_list_free (identify_data.list);
3295 identify_data.list = NULL;
3297 else
3299 dll_name_list_free (identify_data.list);
3300 identify_data.list = NULL;
3301 fatal (_("Unable to determine dll name for `%s' (not an import library?)"),
3302 identify_imp_name);
3306 /* Loop over all members of the archive, applying the supplied function to
3307 each member that is a bfd_object. The function will be called as if:
3308 func (member_bfd, abfd, user_storage) */
3310 static void
3311 identify_search_archive (bfd * abfd,
3312 void (* operation) (bfd *, bfd *, void *),
3313 void * user_storage)
3315 bfd * arfile = NULL;
3316 bfd * last_arfile = NULL;
3317 char ** matching;
3319 while (1)
3321 arfile = bfd_openr_next_archived_file (abfd, arfile);
3323 if (arfile == NULL)
3325 if (bfd_get_error () != bfd_error_no_more_archived_files)
3326 bfd_fatal (bfd_get_filename (abfd));
3327 break;
3330 if (bfd_check_format_matches (arfile, bfd_object, &matching))
3331 (*operation) (arfile, abfd, user_storage);
3332 else
3334 bfd_nonfatal (bfd_get_filename (arfile));
3335 free (matching);
3338 if (last_arfile != NULL)
3340 bfd_close (last_arfile);
3341 /* PR 17512: file: 8b2168d4. */
3342 if (last_arfile == arfile)
3344 last_arfile = NULL;
3345 break;
3349 last_arfile = arfile;
3352 if (last_arfile != NULL)
3354 bfd_close (last_arfile);
3358 /* Call the identify_search_section() function for each section of this
3359 archive member. */
3361 static void
3362 identify_search_member (bfd *abfd,
3363 bfd *archive_bfd ATTRIBUTE_UNUSED,
3364 void *obj)
3366 bfd_map_over_sections (abfd, identify_search_section, obj);
3369 /* This predicate returns true if section->name matches the desired value.
3370 By default, this is .idata$7 (.idata$6 if the import library is
3371 ms-style). */
3373 static bool
3374 identify_process_section_p (asection * section, bool ms_style_implib)
3376 static const char * SECTION_NAME = ".idata$7";
3377 static const char * MS_SECTION_NAME = ".idata$6";
3379 const char * section_name =
3380 (ms_style_implib ? MS_SECTION_NAME : SECTION_NAME);
3382 if (strcmp (section_name, section->name) == 0)
3383 return true;
3384 return false;
3387 /* If *section has contents and its name is .idata$7 (.idata$6 if
3388 import lib ms-generated) -- and it satisfies several other constraints
3389 -- then add the contents of the section to obj->list. */
3391 static void
3392 identify_search_section (bfd * abfd, asection * section, void * obj)
3394 bfd_byte *data = 0;
3395 bfd_size_type datasize;
3396 identify_data_type * identify_data = (identify_data_type *)obj;
3397 bool ms_style = identify_data->ms_style_implib;
3399 if ((section->flags & SEC_HAS_CONTENTS) == 0)
3400 return;
3402 if (! identify_process_section_p (section, ms_style))
3403 return;
3405 /* Binutils import libs seem distinguish the .idata$7 section that contains
3406 the DLL name from other .idata$7 sections by the absence of the
3407 SEC_RELOC flag. */
3408 if (!ms_style && ((section->flags & SEC_RELOC) == SEC_RELOC))
3409 return;
3411 /* MS import libs seem to distinguish the .idata$6 section
3412 that contains the DLL name from other .idata$6 sections
3413 by the presence of the SEC_DATA flag. */
3414 if (ms_style && ((section->flags & SEC_DATA) == 0))
3415 return;
3417 if ((datasize = bfd_section_size (section)) == 0)
3418 return;
3420 data = (bfd_byte *) xmalloc (datasize + 1);
3421 data[0] = '\0';
3423 bfd_get_section_contents (abfd, section, data, 0, datasize);
3424 data[datasize] = '\0';
3426 /* Use a heuristic to determine if data is a dll name.
3427 Possible to defeat this if (a) the library has MANY
3428 (more than 0x302f) imports, (b) it is an ms-style
3429 import library, but (c) it is buggy, in that the SEC_DATA
3430 flag is set on the "wrong" sections. This heuristic might
3431 also fail to record a valid dll name if the dllname uses
3432 a multibyte or unicode character set (is that valid?).
3434 This heuristic is based on the fact that symbols names in
3435 the chosen section -- as opposed to the dll name -- begin
3436 at offset 2 in the data. The first two bytes are a 16bit
3437 little-endian count, and start at 0x0000. However, the dll
3438 name begins at offset 0 in the data. We assume that the
3439 dll name does not contain unprintable characters. */
3440 if (data[0] != '\0' && ISPRINT (data[0])
3441 && ((datasize < 2) || ISPRINT (data[1])))
3442 dll_name_list_append (identify_data->list, data);
3444 free (data);
3447 /* Run through the information gathered from the .o files and the
3448 .def file and work out the best stuff. */
3450 static int
3451 pfunc (const void *a, const void *b)
3453 export_type *ap = *(export_type **) a;
3454 export_type *bp = *(export_type **) b;
3456 if (ap->ordinal == bp->ordinal)
3457 return 0;
3459 /* Unset ordinals go to the bottom. */
3460 if (ap->ordinal == -1)
3461 return 1;
3462 if (bp->ordinal == -1)
3463 return -1;
3464 return (ap->ordinal - bp->ordinal);
3467 static int
3468 nfunc (const void *a, const void *b)
3470 export_type *ap = *(export_type **) a;
3471 export_type *bp = *(export_type **) b;
3472 const char *an = ap->name;
3473 const char *bn = bp->name;
3474 if (ap->its_name)
3475 an = ap->its_name;
3476 if (bp->its_name)
3477 an = bp->its_name;
3478 if (killat)
3480 an = (an[0] == '@') ? an + 1 : an;
3481 bn = (bn[0] == '@') ? bn + 1 : bn;
3484 return (strcmp (an, bn));
3487 static void
3488 remove_null_names (export_type **ptr)
3490 int src;
3491 int dst;
3493 for (dst = src = 0; src < d_nfuncs; src++)
3495 if (ptr[src])
3497 ptr[dst] = ptr[src];
3498 dst++;
3501 d_nfuncs = dst;
3504 static void
3505 process_duplicates (export_type **d_export_vec)
3507 int more = 1;
3508 int i;
3510 while (more)
3512 more = 0;
3513 /* Remove duplicates. */
3514 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), nfunc);
3516 for (i = 0; i < d_nfuncs - 1; i++)
3518 if (strcmp (d_export_vec[i]->name,
3519 d_export_vec[i + 1]->name) == 0)
3521 export_type *a = d_export_vec[i];
3522 export_type *b = d_export_vec[i + 1];
3524 more = 1;
3526 /* xgettext:c-format */
3527 inform (_("Warning, ignoring duplicate EXPORT %s %d,%d"),
3528 a->name, a->ordinal, b->ordinal);
3530 if (a->ordinal != -1
3531 && b->ordinal != -1)
3532 /* xgettext:c-format */
3533 fatal (_("Error, duplicate EXPORT with ordinals: %s"),
3534 a->name);
3536 /* Merge attributes. */
3537 b->ordinal = a->ordinal > 0 ? a->ordinal : b->ordinal;
3538 b->constant |= a->constant;
3539 b->noname |= a->noname;
3540 b->data |= a->data;
3541 d_export_vec[i] = 0;
3544 remove_null_names (d_export_vec);
3548 /* Count the names. */
3549 for (i = 0; i < d_nfuncs; i++)
3550 if (!d_export_vec[i]->noname)
3551 d_named_nfuncs++;
3554 static void
3555 fill_ordinals (export_type **d_export_vec)
3557 int lowest = -1;
3558 int i;
3559 char *ptr;
3560 int size = 65536;
3562 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3564 /* Fill in the unset ordinals with ones from our range. */
3565 ptr = (char *) xmalloc (size);
3567 memset (ptr, 0, size);
3569 /* Mark in our large vector all the numbers that are taken. */
3570 for (i = 0; i < d_nfuncs; i++)
3572 if (d_export_vec[i]->ordinal != -1)
3574 ptr[d_export_vec[i]->ordinal] = 1;
3576 if (lowest == -1 || d_export_vec[i]->ordinal < lowest)
3577 lowest = d_export_vec[i]->ordinal;
3581 /* Start at 1 for compatibility with MS toolchain. */
3582 if (lowest == -1)
3583 lowest = 1;
3585 /* Now fill in ordinals where the user wants us to choose. */
3586 for (i = 0; i < d_nfuncs; i++)
3588 if (d_export_vec[i]->ordinal == -1)
3590 int j;
3592 /* First try within or after any user supplied range. */
3593 for (j = lowest; j < size; j++)
3594 if (ptr[j] == 0)
3596 ptr[j] = 1;
3597 d_export_vec[i]->ordinal = j;
3598 goto done;
3601 /* Then try before the range. */
3602 for (j = lowest; j >0; j--)
3603 if (ptr[j] == 0)
3605 ptr[j] = 1;
3606 d_export_vec[i]->ordinal = j;
3607 goto done;
3609 done:;
3613 free (ptr);
3615 /* And resort. */
3616 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3618 /* Work out the lowest and highest ordinal numbers. */
3619 if (d_nfuncs)
3621 if (d_export_vec[0])
3622 d_low_ord = d_export_vec[0]->ordinal;
3623 if (d_export_vec[d_nfuncs-1])
3624 d_high_ord = d_export_vec[d_nfuncs-1]->ordinal;
3628 static void
3629 mangle_defs (void)
3631 /* First work out the minimum ordinal chosen. */
3632 export_type *exp;
3633 export_type **d_export_vec = xmalloc (sizeof (export_type *) * d_nfuncs);
3634 int i;
3636 inform (_("Processing definitions"));
3638 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3639 d_export_vec[i] = exp;
3641 process_duplicates (d_export_vec);
3642 fill_ordinals (d_export_vec);
3644 /* Put back the list in the new order. */
3645 d_exports = 0;
3646 for (i = d_nfuncs - 1; i >= 0; i--)
3648 d_export_vec[i]->next = d_exports;
3649 d_exports = d_export_vec[i];
3652 /* Build list in alpha order. */
3653 d_exports_lexically = (export_type **)
3654 xmalloc (sizeof (export_type *) * (d_nfuncs + 1));
3656 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3657 d_exports_lexically[i] = exp;
3659 d_exports_lexically[i] = 0;
3661 qsort (d_exports_lexically, i, sizeof (export_type *), nfunc);
3663 inform (_("Processed definitions"));
3666 static void
3667 usage (FILE *file, int status)
3669 /* xgetext:c-format */
3670 fprintf (file, _("Usage %s <option(s)> <object-file(s)>\n"), program_name);
3671 /* xgetext:c-format */
3672 fprintf (file, _(" -m --machine <machine> Create as DLL for <machine>. [default: %s]\n"), mname);
3673 fprintf (file, _(" possible <machine>: arm[_interwork], i386, mcore[-elf]{-le|-be}, thumb\n"));
3674 fprintf (file, _(" -e --output-exp <outname> Generate an export file.\n"));
3675 fprintf (file, _(" -l --output-lib <outname> Generate an interface library.\n"));
3676 fprintf (file, _(" -y --output-delaylib <outname> Create a delay-import library.\n"));
3677 fprintf (file, _(" -a --add-indirect Add dll indirects to export file.\n"));
3678 fprintf (file, _(" -D --dllname <name> Name of input dll to put into interface lib.\n"));
3679 fprintf (file, _(" -d --input-def <deffile> Name of .def file to be read in.\n"));
3680 fprintf (file, _(" -z --output-def <deffile> Name of .def file to be created.\n"));
3681 fprintf (file, _(" --export-all-symbols Export all symbols to .def\n"));
3682 fprintf (file, _(" --no-export-all-symbols Only export listed symbols\n"));
3683 fprintf (file, _(" --exclude-symbols <list> Don't export <list>\n"));
3684 fprintf (file, _(" --no-default-excludes Clear default exclude symbols\n"));
3685 fprintf (file, _(" -b --base-file <basefile> Read linker generated base file.\n"));
3686 fprintf (file, _(" -x --no-idata4 Don't generate idata$4 section.\n"));
3687 fprintf (file, _(" -c --no-idata5 Don't generate idata$5 section.\n"));
3688 fprintf (file, _(" --use-nul-prefixed-import-tables Use zero prefixed idata$4 and idata$5.\n"));
3689 fprintf (file, _(" -U --add-underscore Add underscores to all symbols in interface library.\n"));
3690 fprintf (file, _(" --add-stdcall-underscore Add underscores to stdcall symbols in interface library.\n"));
3691 fprintf (file, _(" --no-leading-underscore All symbols shouldn't be prefixed by an underscore.\n"));
3692 fprintf (file, _(" --leading-underscore All symbols should be prefixed by an underscore.\n"));
3693 fprintf (file, _(" -k --kill-at Kill @<n> from exported names.\n"));
3694 fprintf (file, _(" -A --add-stdcall-alias Add aliases without @<n>.\n"));
3695 fprintf (file, _(" -p --ext-prefix-alias <prefix> Add aliases with <prefix>.\n"));
3696 fprintf (file, _(" -S --as <name> Use <name> for assembler.\n"));
3697 fprintf (file, _(" -f --as-flags <flags> Pass <flags> to the assembler.\n"));
3698 fprintf (file, _(" -C --compat-implib Create backward compatible import library.\n"));
3699 fprintf (file, _(" -n --no-delete Keep temp files (repeat for extra preservation).\n"));
3700 fprintf (file, _(" -t --temp-prefix <prefix> Use <prefix> to construct temp file names.\n"));
3701 fprintf (file, _(" -I --identify <implib> Report the name of the DLL associated with <implib>.\n"));
3702 fprintf (file, _(" --identify-strict Causes --identify to report error when multiple DLLs.\n"));
3703 fprintf (file, _(" -v --verbose Be verbose.\n"));
3704 fprintf (file, _(" -V --version Display the program version.\n"));
3705 fprintf (file, _(" -h --help Display this information.\n"));
3706 fprintf (file, _(" @<file> Read options from <file>.\n"));
3707 #ifdef DLLTOOL_MCORE_ELF
3708 fprintf (file, _(" -M --mcore-elf <outname> Process mcore-elf object files into <outname>.\n"));
3709 fprintf (file, _(" -L --linker <name> Use <name> as the linker.\n"));
3710 fprintf (file, _(" -F --linker-flags <flags> Pass <flags> to the linker.\n"));
3711 #endif
3712 if (REPORT_BUGS_TO[0] && status == 0)
3713 fprintf (file, _("Report bugs to %s\n"), REPORT_BUGS_TO);
3714 exit (status);
3717 #define OPTION_EXPORT_ALL_SYMS 150
3718 #define OPTION_NO_EXPORT_ALL_SYMS (OPTION_EXPORT_ALL_SYMS + 1)
3719 #define OPTION_EXCLUDE_SYMS (OPTION_NO_EXPORT_ALL_SYMS + 1)
3720 #define OPTION_NO_DEFAULT_EXCLUDES (OPTION_EXCLUDE_SYMS + 1)
3721 #define OPTION_ADD_STDCALL_UNDERSCORE (OPTION_NO_DEFAULT_EXCLUDES + 1)
3722 #define OPTION_USE_NUL_PREFIXED_IMPORT_TABLES \
3723 (OPTION_ADD_STDCALL_UNDERSCORE + 1)
3724 #define OPTION_IDENTIFY_STRICT (OPTION_USE_NUL_PREFIXED_IMPORT_TABLES + 1)
3725 #define OPTION_NO_LEADING_UNDERSCORE (OPTION_IDENTIFY_STRICT + 1)
3726 #define OPTION_LEADING_UNDERSCORE (OPTION_NO_LEADING_UNDERSCORE + 1)
3728 static const struct option long_options[] =
3730 {"no-delete", no_argument, NULL, 'n'},
3731 {"dllname", required_argument, NULL, 'D'},
3732 {"no-idata4", no_argument, NULL, 'x'},
3733 {"no-idata5", no_argument, NULL, 'c'},
3734 {"use-nul-prefixed-import-tables", no_argument, NULL,
3735 OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
3736 {"output-exp", required_argument, NULL, 'e'},
3737 {"output-def", required_argument, NULL, 'z'},
3738 {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL_SYMS},
3739 {"no-export-all-symbols", no_argument, NULL, OPTION_NO_EXPORT_ALL_SYMS},
3740 {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMS},
3741 {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
3742 {"output-lib", required_argument, NULL, 'l'},
3743 {"def", required_argument, NULL, 'd'}, /* for compatibility with older versions */
3744 {"input-def", required_argument, NULL, 'd'},
3745 {"add-underscore", no_argument, NULL, 'U'},
3746 {"add-stdcall-underscore", no_argument, NULL, OPTION_ADD_STDCALL_UNDERSCORE},
3747 {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
3748 {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
3749 {"kill-at", no_argument, NULL, 'k'},
3750 {"add-stdcall-alias", no_argument, NULL, 'A'},
3751 {"ext-prefix-alias", required_argument, NULL, 'p'},
3752 {"identify", required_argument, NULL, 'I'},
3753 {"identify-strict", no_argument, NULL, OPTION_IDENTIFY_STRICT},
3754 {"verbose", no_argument, NULL, 'v'},
3755 {"version", no_argument, NULL, 'V'},
3756 {"help", no_argument, NULL, 'h'},
3757 {"machine", required_argument, NULL, 'm'},
3758 {"add-indirect", no_argument, NULL, 'a'},
3759 {"base-file", required_argument, NULL, 'b'},
3760 {"as", required_argument, NULL, 'S'},
3761 {"as-flags", required_argument, NULL, 'f'},
3762 {"mcore-elf", required_argument, NULL, 'M'},
3763 {"compat-implib", no_argument, NULL, 'C'},
3764 {"temp-prefix", required_argument, NULL, 't'},
3765 {"output-delaylib", required_argument, NULL, 'y'},
3766 {NULL,0,NULL,0}
3769 int main (int, char **);
3772 main (int ac, char **av)
3774 int c;
3775 int i;
3776 char *firstarg = 0;
3777 program_name = av[0];
3778 oav = av;
3780 #ifdef HAVE_LC_MESSAGES
3781 setlocale (LC_MESSAGES, "");
3782 #endif
3783 setlocale (LC_CTYPE, "");
3784 bindtextdomain (PACKAGE, LOCALEDIR);
3785 textdomain (PACKAGE);
3787 bfd_set_error_program_name (program_name);
3788 expandargv (&ac, &av);
3790 while ((c = getopt_long (ac, av,
3791 #ifdef DLLTOOL_MCORE_ELF
3792 "m:e:l:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHhM:L:F:",
3793 #else
3794 "m:e:l:y:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHh",
3795 #endif
3796 long_options, 0))
3797 != EOF)
3799 switch (c)
3801 case OPTION_EXPORT_ALL_SYMS:
3802 export_all_symbols = true;
3803 break;
3804 case OPTION_NO_EXPORT_ALL_SYMS:
3805 export_all_symbols = false;
3806 break;
3807 case OPTION_EXCLUDE_SYMS:
3808 add_excludes (optarg);
3809 break;
3810 case OPTION_NO_DEFAULT_EXCLUDES:
3811 do_default_excludes = false;
3812 break;
3813 case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
3814 use_nul_prefixed_import_tables = true;
3815 break;
3816 case OPTION_ADD_STDCALL_UNDERSCORE:
3817 add_stdcall_underscore = 1;
3818 break;
3819 case OPTION_NO_LEADING_UNDERSCORE:
3820 leading_underscore = 0;
3821 break;
3822 case OPTION_LEADING_UNDERSCORE:
3823 leading_underscore = 1;
3824 break;
3825 case OPTION_IDENTIFY_STRICT:
3826 identify_strict = 1;
3827 break;
3828 case 'x':
3829 no_idata4 = 1;
3830 break;
3831 case 'c':
3832 no_idata5 = 1;
3833 break;
3834 case 'S':
3835 as_name = optarg;
3836 break;
3837 case 't':
3838 tmp_prefix = optarg;
3839 break;
3840 case 'f':
3841 as_flags = optarg;
3842 break;
3844 /* Ignored for compatibility. */
3845 case 'u':
3846 break;
3847 case 'a':
3848 add_indirect = 1;
3849 break;
3850 case 'z':
3851 output_def = fopen (optarg, FOPEN_WT);
3852 if (!output_def)
3853 /* xgettext:c-format */
3854 fatal (_("Unable to open def-file: %s"), optarg);
3855 break;
3856 case 'D':
3857 dll_name = (char*) lbasename (optarg);
3858 if (dll_name != optarg)
3859 non_fatal (_("Path components stripped from dllname, '%s'."),
3860 optarg);
3861 break;
3862 case 'l':
3863 imp_name = optarg;
3864 break;
3865 case 'e':
3866 exp_name = optarg;
3867 break;
3868 case 'H':
3869 case 'h':
3870 usage (stdout, 0);
3871 break;
3872 case 'm':
3873 mname = optarg;
3874 break;
3875 case 'I':
3876 identify_imp_name = optarg;
3877 break;
3878 case 'v':
3879 verbose = 1;
3880 break;
3881 case 'V':
3882 print_version (program_name);
3883 break;
3884 case 'U':
3885 add_underscore = 1;
3886 break;
3887 case 'k':
3888 killat = 1;
3889 break;
3890 case 'A':
3891 add_stdcall_alias = 1;
3892 break;
3893 case 'p':
3894 ext_prefix_alias = optarg;
3895 break;
3896 case 'd':
3897 def_file = optarg;
3898 break;
3899 case 'n':
3900 dontdeltemps++;
3901 break;
3902 case 'b':
3903 base_file = fopen (optarg, FOPEN_RB);
3905 if (!base_file)
3906 /* xgettext:c-format */
3907 fatal (_("Unable to open base-file: %s"), optarg);
3909 break;
3910 #ifdef DLLTOOL_MCORE_ELF
3911 case 'M':
3912 mcore_elf_out_file = optarg;
3913 break;
3914 case 'L':
3915 mcore_elf_linker = optarg;
3916 break;
3917 case 'F':
3918 mcore_elf_linker_flags = optarg;
3919 break;
3920 #endif
3921 case 'C':
3922 create_compat_implib = 1;
3923 break;
3924 case 'y':
3925 delayimp_name = optarg;
3926 break;
3927 default:
3928 usage (stderr, 1);
3929 break;
3933 for (i = 0; mtable[i].type; i++)
3934 if (strcmp (mtable[i].type, mname) == 0)
3935 break;
3937 if (!mtable[i].type)
3938 /* xgettext:c-format */
3939 fatal (_("Machine '%s' not supported"), mname);
3941 machine = i;
3943 /* Check if we generated PE+. */
3944 create_for_pep = strcmp (mname, "i386:x86-64") == 0;
3947 /* Check the default underscore */
3948 int u = leading_underscore; /* Underscoring mode. -1 for use default. */
3949 if (u == -1)
3950 bfd_get_target_info (mtable[machine].how_bfd_target, NULL,
3951 NULL, &u, NULL);
3952 if (u != -1)
3953 leading_underscore = u != 0;
3956 if (!dll_name && exp_name)
3958 /* If we are inferring dll_name from exp_name,
3959 strip off any path components, without emitting
3960 a warning. */
3961 const char* exp_basename = lbasename (exp_name);
3962 const int len = strlen (exp_basename) + 5;
3963 dll_name = xmalloc (len);
3964 strcpy (dll_name, exp_basename);
3965 strcat (dll_name, ".dll");
3966 dll_name_set_by_exp_name = 1;
3969 if (as_name == NULL)
3970 as_name = deduce_name ("as");
3972 /* Don't use the default exclude list if we're reading only the
3973 symbols in the .drectve section. The default excludes are meant
3974 to avoid exporting DLL entry point and Cygwin32 impure_ptr. */
3975 if (! export_all_symbols)
3976 do_default_excludes = false;
3978 if (do_default_excludes)
3979 set_default_excludes ();
3981 if (def_file)
3982 process_def_file (def_file);
3984 while (optind < ac)
3986 if (!firstarg)
3987 firstarg = av[optind];
3988 scan_obj_file (av[optind]);
3989 optind++;
3992 if (tmp_prefix == NULL)
3994 /* If possible use a deterministic prefix. */
3995 if (dll_name)
3997 tmp_prefix = xmalloc (strlen (dll_name) + 2);
3998 sprintf (tmp_prefix, "%s_", dll_name);
3999 for (i = 0; tmp_prefix[i]; i++)
4000 if (!ISALNUM (tmp_prefix[i]))
4001 tmp_prefix[i] = '_';
4003 else
4005 tmp_prefix = prefix_encode ("d", getpid ());
4009 mangle_defs ();
4011 if (exp_name)
4012 gen_exp_file ();
4014 if (imp_name)
4016 /* Make imp_name safe for use as a label. */
4017 char *p;
4019 imp_name_lab = xstrdup (imp_name);
4020 for (p = imp_name_lab; *p; p++)
4022 if (!ISALNUM (*p))
4023 *p = '_';
4025 head_label = make_label("_head_", imp_name_lab);
4026 gen_lib_file (0);
4029 if (delayimp_name)
4031 /* Make delayimp_name safe for use as a label. */
4032 char *p;
4034 if (mtable[machine].how_dljtab == 0)
4036 inform (_("Warning, machine type (%d) not supported for "
4037 "delayimport."), machine);
4039 else
4041 killat = 1;
4042 imp_name = delayimp_name;
4043 imp_name_lab = xstrdup (imp_name);
4044 for (p = imp_name_lab; *p; p++)
4046 if (!ISALNUM (*p))
4047 *p = '_';
4049 head_label = make_label("__tailMerge_", imp_name_lab);
4050 gen_lib_file (1);
4054 if (output_def)
4055 gen_def_file ();
4057 if (identify_imp_name)
4059 identify_dll_for_implib ();
4062 #ifdef DLLTOOL_MCORE_ELF
4063 if (mcore_elf_out_file)
4064 mcore_elf_gen_out_file ();
4065 #endif
4067 return 0;
4070 /* Look for the program formed by concatenating PROG_NAME and the
4071 string running from PREFIX to END_PREFIX. If the concatenated
4072 string contains a '/', try appending EXECUTABLE_SUFFIX if it is
4073 appropriate. */
4075 static char *
4076 look_for_prog (const char *prog_name, const char *prefix, int end_prefix)
4078 struct stat s;
4079 char *cmd;
4081 cmd = xmalloc (strlen (prefix)
4082 + strlen (prog_name)
4083 #ifdef HAVE_EXECUTABLE_SUFFIX
4084 + strlen (EXECUTABLE_SUFFIX)
4085 #endif
4086 + 10);
4087 strcpy (cmd, prefix);
4089 sprintf (cmd + end_prefix, "%s", prog_name);
4091 if (strchr (cmd, '/') != NULL)
4093 int found;
4095 found = (stat (cmd, &s) == 0
4096 #ifdef HAVE_EXECUTABLE_SUFFIX
4097 || stat (strcat (cmd, EXECUTABLE_SUFFIX), &s) == 0
4098 #endif
4101 if (! found)
4103 /* xgettext:c-format */
4104 inform (_("Tried file: %s"), cmd);
4105 free (cmd);
4106 return NULL;
4110 /* xgettext:c-format */
4111 inform (_("Using file: %s"), cmd);
4113 return cmd;
4116 /* Deduce the name of the program we are want to invoke.
4117 PROG_NAME is the basic name of the program we want to run,
4118 eg "as" or "ld". The catch is that we might want actually
4119 run "i386-pe-as".
4121 If argv[0] contains the full path, then try to find the program
4122 in the same place, with and then without a target-like prefix.
4124 Given, argv[0] = /usr/local/bin/i586-cygwin32-dlltool,
4125 deduce_name("as") uses the following search order:
4127 /usr/local/bin/i586-cygwin32-as
4128 /usr/local/bin/as
4131 If there's an EXECUTABLE_SUFFIX, it'll use that as well; for each
4132 name, it'll try without and then with EXECUTABLE_SUFFIX.
4134 Given, argv[0] = i586-cygwin32-dlltool, it will not even try "as"
4135 as the fallback, but rather return i586-cygwin32-as.
4137 Oh, and given, argv[0] = dlltool, it'll return "as".
4139 Returns a dynamically allocated string. */
4141 static char *
4142 deduce_name (const char *prog_name)
4144 char *cmd;
4145 char *dash, *slash, *cp;
4147 dash = NULL;
4148 slash = NULL;
4149 for (cp = program_name; *cp != '\0'; ++cp)
4151 if (*cp == '-')
4152 dash = cp;
4153 if (
4154 #if defined(__DJGPP__) || defined (__CYGWIN__) || defined(__WIN32__)
4155 *cp == ':' || *cp == '\\' ||
4156 #endif
4157 *cp == '/')
4159 slash = cp;
4160 dash = NULL;
4164 cmd = NULL;
4166 if (dash != NULL)
4168 /* First, try looking for a prefixed PROG_NAME in the
4169 PROGRAM_NAME directory, with the same prefix as PROGRAM_NAME. */
4170 cmd = look_for_prog (prog_name, program_name, dash - program_name + 1);
4173 if (slash != NULL && cmd == NULL)
4175 /* Next, try looking for a PROG_NAME in the same directory as
4176 that of this program. */
4177 cmd = look_for_prog (prog_name, program_name, slash - program_name + 1);
4180 if (cmd == NULL)
4182 /* Just return PROG_NAME as is. */
4183 cmd = xstrdup (prog_name);
4186 return cmd;
4189 #ifdef DLLTOOL_MCORE_ELF
4190 typedef struct fname_cache
4192 const char * filename;
4193 struct fname_cache * next;
4195 fname_cache;
4197 static fname_cache fnames;
4199 static void
4200 mcore_elf_cache_filename (const char * filename)
4202 fname_cache * ptr;
4204 ptr = & fnames;
4206 while (ptr->next != NULL)
4207 ptr = ptr->next;
4209 ptr->filename = filename;
4210 ptr->next = (fname_cache *) malloc (sizeof (fname_cache));
4211 if (ptr->next != NULL)
4212 ptr->next->next = NULL;
4215 #define MCORE_ELF_TMP_OBJ "mcoreelf.o"
4216 #define MCORE_ELF_TMP_EXP "mcoreelf.exp"
4217 #define MCORE_ELF_TMP_LIB "mcoreelf.lib"
4219 static void
4220 mcore_elf_gen_out_file (void)
4222 fname_cache * ptr;
4223 dyn_string_t ds;
4225 /* Step one. Run 'ld -r' on the input object files in order to resolve
4226 any internal references and to generate a single .exports section. */
4227 ptr = & fnames;
4229 ds = dyn_string_new (100);
4230 dyn_string_append_cstr (ds, "-r ");
4232 if (mcore_elf_linker_flags != NULL)
4233 dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4235 while (ptr->next != NULL)
4237 dyn_string_append_cstr (ds, ptr->filename);
4238 dyn_string_append_cstr (ds, " ");
4240 ptr = ptr->next;
4243 dyn_string_append_cstr (ds, "-o ");
4244 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4246 if (mcore_elf_linker == NULL)
4247 mcore_elf_linker = deduce_name ("ld");
4249 run (mcore_elf_linker, ds->s);
4251 dyn_string_delete (ds);
4253 /* Step two. Create a .exp file and a .lib file from the temporary file.
4254 Do this by recursively invoking dlltool... */
4255 ds = dyn_string_new (100);
4257 dyn_string_append_cstr (ds, "-S ");
4258 dyn_string_append_cstr (ds, as_name);
4260 dyn_string_append_cstr (ds, " -e ");
4261 dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4262 dyn_string_append_cstr (ds, " -l ");
4263 dyn_string_append_cstr (ds, MCORE_ELF_TMP_LIB);
4264 dyn_string_append_cstr (ds, " " );
4265 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4267 if (verbose)
4268 dyn_string_append_cstr (ds, " -v");
4270 if (dontdeltemps)
4272 dyn_string_append_cstr (ds, " -n");
4274 if (dontdeltemps > 1)
4275 dyn_string_append_cstr (ds, " -n");
4278 /* XXX - FIME: ought to check/copy other command line options as well. */
4279 run (program_name, ds->s);
4281 dyn_string_delete (ds);
4283 /* Step four. Feed the .exp and object files to ld -shared to create the dll. */
4284 ds = dyn_string_new (100);
4286 dyn_string_append_cstr (ds, "-shared ");
4288 if (mcore_elf_linker_flags)
4289 dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4291 dyn_string_append_cstr (ds, " ");
4292 dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4293 dyn_string_append_cstr (ds, " ");
4294 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4295 dyn_string_append_cstr (ds, " -o ");
4296 dyn_string_append_cstr (ds, mcore_elf_out_file);
4298 run (mcore_elf_linker, ds->s);
4300 dyn_string_delete (ds);
4302 if (dontdeltemps == 0)
4303 unlink (MCORE_ELF_TMP_EXP);
4305 if (dontdeltemps < 2)
4306 unlink (MCORE_ELF_TMP_OBJ);
4308 #endif /* DLLTOOL_MCORE_ELF */