Set GDB version number to 13.1.
[binutils-gdb.git] / binutils / dlltool.c
bloba3c5e0f778ef62a31d899cb967872956b21ebf99
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;
359 static bool deterministic = DEFAULT_AR_DETERMINISTIC;
361 /* Types used to implement a linked list of dllnames associated
362 with the specified import lib. Used by the identify_* code.
363 The head entry is acts as a sentinal node and is always empty
364 (head->dllname is NULL). */
365 typedef struct dll_name_list_node_t
367 char * dllname;
368 struct dll_name_list_node_t * next;
369 } dll_name_list_node_type;
371 typedef struct dll_name_list_t
373 dll_name_list_node_type * head;
374 dll_name_list_node_type * tail;
375 } dll_name_list_type;
377 /* Types used to pass data to iterator functions. */
378 typedef struct symname_search_data_t
380 const char *symname;
381 bool found;
382 } symname_search_data_type;
384 typedef struct identify_data_t
386 dll_name_list_type *list;
387 bool ms_style_implib;
388 } identify_data_type;
391 static char *head_label;
392 static char *imp_name_lab;
393 static char *dll_name;
394 static int dll_name_set_by_exp_name;
395 static int add_indirect = 0;
396 static int add_underscore = 0;
397 static int add_stdcall_underscore = 0;
398 /* This variable can hold three different values. The value
399 -1 (default) means that default underscoring should be used,
400 zero means that no underscoring should be done, and one
401 indicates that underscoring should be done. */
402 static int leading_underscore = -1;
403 static int dontdeltemps = 0;
405 /* TRUE if we should export all symbols. Otherwise, we only export
406 symbols listed in .drectve sections or in the def file. */
407 static bool export_all_symbols;
409 /* TRUE if we should exclude the symbols in DEFAULT_EXCLUDES when
410 exporting all symbols. */
411 static bool do_default_excludes = true;
413 static bool use_nul_prefixed_import_tables = false;
415 /* Default symbols to exclude when exporting all the symbols. */
416 static const char *default_excludes = "DllMain@12,DllEntryPoint@0,impure_ptr";
418 /* TRUE if we should add __imp_<SYMBOL> to import libraries for backward
419 compatibility to old Cygwin releases. */
420 static bool create_compat_implib;
422 /* TRUE if we have to write PE+ import libraries. */
423 static bool create_for_pep;
425 static char *def_file;
427 extern char * program_name;
429 static int machine;
430 static int killat;
431 static int add_stdcall_alias;
432 static const char *ext_prefix_alias;
433 static int verbose;
434 static FILE *output_def;
435 static FILE *base_file;
437 #ifdef DLLTOOL_DEFAULT_ARM
438 static const char *mname = "arm";
439 #endif
441 #ifdef DLLTOOL_DEFAULT_ARM_WINCE
442 static const char *mname = "arm-wince";
443 #endif
445 #ifdef DLLTOOL_DEFAULT_I386
446 static const char *mname = "i386";
447 #endif
449 #ifdef DLLTOOL_DEFAULT_MX86_64
450 static const char *mname = "i386:x86-64";
451 #endif
453 #ifdef DLLTOOL_DEFAULT_SH
454 static const char *mname = "sh";
455 #endif
457 #ifdef DLLTOOL_DEFAULT_MIPS
458 static const char *mname = "mips";
459 #endif
461 #ifdef DLLTOOL_DEFAULT_MCORE
462 static const char * mname = "mcore-le";
463 #endif
465 #ifdef DLLTOOL_DEFAULT_MCORE_ELF
466 static const char * mname = "mcore-elf";
467 static char * mcore_elf_out_file = NULL;
468 static char * mcore_elf_linker = NULL;
469 static char * mcore_elf_linker_flags = NULL;
471 #define DRECTVE_SECTION_NAME ((machine == MMCORE_ELF || machine == MMCORE_ELF_LE) ? ".exports" : ".drectve")
472 #endif
474 #ifndef DRECTVE_SECTION_NAME
475 #define DRECTVE_SECTION_NAME ".drectve"
476 #endif
478 /* What's the right name for this ? */
479 #define PATHMAX 250
481 /* External name alias numbering starts here. */
482 #define PREFIX_ALIAS_BASE 20000
484 char *tmp_asm_buf;
485 char *tmp_head_s_buf;
486 char *tmp_head_o_buf;
487 char *tmp_tail_s_buf;
488 char *tmp_tail_o_buf;
489 char *tmp_stub_buf;
491 #define TMP_ASM dlltmp (&tmp_asm_buf, "%sc.s")
492 #define TMP_HEAD_S dlltmp (&tmp_head_s_buf, "%sh.s")
493 #define TMP_HEAD_O dlltmp (&tmp_head_o_buf, "%sh.o")
494 #define TMP_TAIL_S dlltmp (&tmp_tail_s_buf, "%st.s")
495 #define TMP_TAIL_O dlltmp (&tmp_tail_o_buf, "%st.o")
496 #define TMP_STUB dlltmp (&tmp_stub_buf, "%ss")
498 /* This bit of assembly does jmp * .... */
499 static const unsigned char i386_jtab[] =
501 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
504 static const unsigned char i386_dljtab[] =
506 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function */
507 0xB8, 0x00, 0x00, 0x00, 0x00, /* mov eax, offset __imp__function */
508 0xE9, 0x00, 0x00, 0x00, 0x00 /* jmp __tailMerge__dllname */
511 static const unsigned char i386_x64_dljtab[] =
513 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function */
514 0x48, 0x8d, 0x05, /* leaq rax, (__imp__function) */
515 0x00, 0x00, 0x00, 0x00,
516 0xE9, 0x00, 0x00, 0x00, 0x00 /* jmp __tailMerge__dllname */
519 static const unsigned char arm_jtab[] =
521 0x00, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
522 0x00, 0xf0, 0x9c, 0xe5, /* ldr pc, [ip] */
523 0, 0, 0, 0
526 static const unsigned char arm_interwork_jtab[] =
528 0x04, 0xc0, 0x9f, 0xe5, /* ldr ip, [pc] */
529 0x00, 0xc0, 0x9c, 0xe5, /* ldr ip, [ip] */
530 0x1c, 0xff, 0x2f, 0xe1, /* bx ip */
531 0, 0, 0, 0
534 static const unsigned char thumb_jtab[] =
536 0x40, 0xb4, /* push {r6} */
537 0x02, 0x4e, /* ldr r6, [pc, #8] */
538 0x36, 0x68, /* ldr r6, [r6] */
539 0xb4, 0x46, /* mov ip, r6 */
540 0x40, 0xbc, /* pop {r6} */
541 0x60, 0x47, /* bx ip */
542 0, 0, 0, 0
545 static const unsigned char mcore_be_jtab[] =
547 0x71, 0x02, /* lrw r1,2 */
548 0x81, 0x01, /* ld.w r1,(r1,0) */
549 0x00, 0xC1, /* jmp r1 */
550 0x12, 0x00, /* nop */
551 0x00, 0x00, 0x00, 0x00 /* <address> */
554 static const unsigned char mcore_le_jtab[] =
556 0x02, 0x71, /* lrw r1,2 */
557 0x01, 0x81, /* ld.w r1,(r1,0) */
558 0xC1, 0x00, /* jmp r1 */
559 0x00, 0x12, /* nop */
560 0x00, 0x00, 0x00, 0x00 /* <address> */
563 static const char i386_trampoline[] =
564 "\tpushl %%ecx\n"
565 "\tpushl %%edx\n"
566 "\tpushl %%eax\n"
567 "\tpushl $__DELAY_IMPORT_DESCRIPTOR_%s\n"
568 "\tcall ___delayLoadHelper2@8\n"
569 "\tpopl %%edx\n"
570 "\tpopl %%ecx\n"
571 "\tjmp *%%eax\n";
573 static const char i386_x64_trampoline[] =
574 "\tsubq $72, %%rsp\n"
575 "\t.seh_stackalloc 72\n"
576 "\t.seh_endprologue\n"
577 "\tmovq %%rcx, 64(%%rsp)\n"
578 "\tmovq %%rdx, 56(%%rsp)\n"
579 "\tmovq %%r8, 48(%%rsp)\n"
580 "\tmovq %%r9, 40(%%rsp)\n"
581 "\tmovq %%rax, %%rdx\n"
582 "\tleaq __DELAY_IMPORT_DESCRIPTOR_%s(%%rip), %%rcx\n"
583 "\tcall __delayLoadHelper2\n"
584 "\tmovq 40(%%rsp), %%r9\n"
585 "\tmovq 48(%%rsp), %%r8\n"
586 "\tmovq 56(%%rsp), %%rdx\n"
587 "\tmovq 64(%%rsp), %%rcx\n"
588 "\taddq $72, %%rsp\n"
589 "\tjmp *%%rax\n";
591 struct mac
593 const char *type;
594 const char *how_byte;
595 const char *how_short;
596 const char *how_long;
597 const char *how_asciz;
598 const char *how_comment;
599 const char *how_jump;
600 const char *how_global;
601 const char *how_space;
602 const char *how_align_short;
603 const char *how_align_long;
604 const char *how_default_as_switches;
605 const char *how_bfd_target;
606 enum bfd_architecture how_bfd_arch;
607 const unsigned char *how_jtab;
608 int how_jtab_size; /* Size of the jtab entry. */
609 int how_jtab_roff; /* Offset into it for the ind 32 reloc into idata 5. */
610 const unsigned char *how_dljtab;
611 int how_dljtab_size; /* Size of the dljtab entry. */
612 int how_dljtab_roff1; /* Offset for the ind 32 reloc into idata 5. */
613 int how_dljtab_roff2; /* Offset for the ind 32 reloc into idata 5. */
614 int how_dljtab_roff3; /* Offset for the ind 32 reloc into idata 5. */
615 bool how_seh;
616 const char *trampoline;
619 static const struct mac
620 mtable[] =
623 #define MARM 0
624 "arm", ".byte", ".short", ".long", ".asciz", "@",
625 "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
626 ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
627 "pe-arm-little", bfd_arch_arm,
628 arm_jtab, sizeof (arm_jtab), 8,
629 0, 0, 0, 0, 0, false, 0
633 #define M386 1
634 "i386", ".byte", ".short", ".long", ".asciz", "#",
635 "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
636 "pe-i386",bfd_arch_i386,
637 i386_jtab, sizeof (i386_jtab), 2,
638 i386_dljtab, sizeof (i386_dljtab), 2, 7, 12, false, i386_trampoline
642 #define MTHUMB 2
643 "thumb", ".byte", ".short", ".long", ".asciz", "@",
644 "push\t{r6}\n\tldr\tr6, [pc, #8]\n\tldr\tr6, [r6]\n\tmov\tip, r6\n\tpop\t{r6}\n\tbx\tip",
645 ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
646 "pe-arm-little", bfd_arch_arm,
647 thumb_jtab, sizeof (thumb_jtab), 12,
648 0, 0, 0, 0, 0, false, 0
651 #define MARM_INTERWORK 3
653 "arm_interwork", ".byte", ".short", ".long", ".asciz", "@",
654 "ldr\tip,[pc]\n\tldr\tip,[ip]\n\tbx\tip\n\t.long",
655 ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
656 "pe-arm-little", bfd_arch_arm,
657 arm_interwork_jtab, sizeof (arm_interwork_jtab), 12,
658 0, 0, 0, 0, 0, false, 0
662 #define MMCORE_BE 4
663 "mcore-be", ".byte", ".short", ".long", ".asciz", "//",
664 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
665 ".global", ".space", ".align\t2",".align\t4", "",
666 "pe-mcore-big", bfd_arch_mcore,
667 mcore_be_jtab, sizeof (mcore_be_jtab), 8,
668 0, 0, 0, 0, 0, false, 0
672 #define MMCORE_LE 5
673 "mcore-le", ".byte", ".short", ".long", ".asciz", "//",
674 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
675 ".global", ".space", ".align\t2",".align\t4", "-EL",
676 "pe-mcore-little", bfd_arch_mcore,
677 mcore_le_jtab, sizeof (mcore_le_jtab), 8,
678 0, 0, 0, 0, 0, false, 0
682 #define MMCORE_ELF 6
683 "mcore-elf-be", ".byte", ".short", ".long", ".asciz", "//",
684 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
685 ".global", ".space", ".align\t2",".align\t4", "",
686 "elf32-mcore-big", bfd_arch_mcore,
687 mcore_be_jtab, sizeof (mcore_be_jtab), 8,
688 0, 0, 0, 0, 0, false, 0
692 #define MMCORE_ELF_LE 7
693 "mcore-elf-le", ".byte", ".short", ".long", ".asciz", "//",
694 "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
695 ".global", ".space", ".align\t2",".align\t4", "-EL",
696 "elf32-mcore-little", bfd_arch_mcore,
697 mcore_le_jtab, sizeof (mcore_le_jtab), 8,
698 0, 0, 0, 0, 0, false, 0
702 #define MARM_WINCE 8
703 "arm-wince", ".byte", ".short", ".long", ".asciz", "@",
704 "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
705 ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
706 "pe-arm-wince-little", bfd_arch_arm,
707 arm_jtab, sizeof (arm_jtab), 8,
708 0, 0, 0, 0, 0, false, 0
712 #define MX86 9
713 "i386:x86-64", ".byte", ".short", ".long", ".asciz", "#",
714 "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
715 "pe-x86-64",bfd_arch_i386,
716 i386_jtab, sizeof (i386_jtab), 2,
717 i386_x64_dljtab, sizeof (i386_x64_dljtab), 2, 9, 14, true, i386_x64_trampoline
720 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
723 typedef struct dlist
725 char *text;
726 struct dlist *next;
728 dlist_type;
730 typedef struct export
732 const char *name;
733 const char *internal_name;
734 const char *import_name;
735 const char *its_name;
736 int ordinal;
737 int constant;
738 int noname; /* Don't put name in image file. */
739 int private; /* Don't put reference in import lib. */
740 int data;
741 int forward; /* Number of forward label, 0 means no forward. */
742 struct export *next;
744 export_type;
746 /* A list of symbols which we should not export. */
748 struct string_list
750 struct string_list *next;
751 char *string;
754 static struct string_list *excludes;
756 static const char *rvaafter (int);
757 static const char *rvabefore (int);
758 static const char *asm_prefix (int, const char *);
759 static void process_def_file (const char *);
760 static void new_directive (char *);
761 static void append_import (const char *, const char *, int, const char *);
762 static void run (const char *, char *);
763 static void scan_drectve_symbols (bfd *);
764 static void scan_filtered_symbols (bfd *, void *, long, unsigned int);
765 static void add_excludes (const char *);
766 static bool match_exclude (const char *);
767 static void set_default_excludes (void);
768 static long filter_symbols (bfd *, void *, long, unsigned int);
769 static void scan_all_symbols (bfd *);
770 static void scan_open_obj_file (bfd *);
771 static void scan_obj_file (const char *);
772 static void dump_def_info (FILE *);
773 static int sfunc (const void *, const void *);
774 static void flush_page (FILE *, bfd_vma *, bfd_vma, int);
775 static void gen_def_file (void);
776 static void generate_idata_ofile (FILE *);
777 static void assemble_file (const char *, const char *);
778 static void gen_exp_file (void);
779 static const char *xlate (const char *);
780 static char *make_label (const char *, const char *);
781 static char *make_imp_label (const char *, const char *);
782 static bfd *make_one_lib_file (export_type *, int, int);
783 static bfd *make_head (void);
784 static bfd *make_tail (void);
785 static bfd *make_delay_head (void);
786 static void gen_lib_file (int);
787 static void dll_name_list_append (dll_name_list_type *, bfd_byte *);
788 static int dll_name_list_count (dll_name_list_type *);
789 static void dll_name_list_print (dll_name_list_type *);
790 static void dll_name_list_free_contents (dll_name_list_node_type *);
791 static void dll_name_list_free (dll_name_list_type *);
792 static dll_name_list_type * dll_name_list_create (void);
793 static void identify_dll_for_implib (void);
794 static void identify_search_archive
795 (bfd *, void (*) (bfd *, bfd *, void *), void *);
796 static void identify_search_member (bfd *, bfd *, void *);
797 static bool identify_process_section_p (asection *, bool);
798 static void identify_search_section (bfd *, asection *, void *);
799 static void identify_member_contains_symname (bfd *, bfd *, void *);
801 static int pfunc (const void *, const void *);
802 static int nfunc (const void *, const void *);
803 static void remove_null_names (export_type **);
804 static void process_duplicates (export_type **);
805 static void fill_ordinals (export_type **);
806 static void mangle_defs (void);
807 static void usage (FILE *, int);
808 static void inform (const char *, ...) ATTRIBUTE_PRINTF_1;
809 static void set_dll_name_from_def (const char *name, char is_dll);
811 static char *
812 prefix_encode (char *start, unsigned code)
814 static char alpha[26] = "abcdefghijklmnopqrstuvwxyz";
815 static char buf[32];
816 char *p;
817 strcpy (buf, start);
818 p = strchr (buf, '\0');
820 *p++ = alpha[code % sizeof (alpha)];
821 while ((code /= sizeof (alpha)) != 0);
822 *p = '\0';
823 return buf;
826 static char *
827 dlltmp (char **buf, const char *fmt)
829 if (!*buf)
831 *buf = malloc (strlen (tmp_prefix) + 64);
832 sprintf (*buf, fmt, tmp_prefix);
834 return *buf;
837 static void
838 inform (const char * message, ...)
840 va_list args;
842 va_start (args, message);
844 if (!verbose)
845 return;
847 report (message, args);
849 va_end (args);
852 static const char *
853 rvaafter (int mach)
855 switch (mach)
857 case MARM:
858 case M386:
859 case MX86:
860 case MTHUMB:
861 case MARM_INTERWORK:
862 case MMCORE_BE:
863 case MMCORE_LE:
864 case MMCORE_ELF:
865 case MMCORE_ELF_LE:
866 case MARM_WINCE:
867 break;
868 default:
869 /* xgettext:c-format */
870 fatal (_("Internal error: Unknown machine type: %d"), mach);
871 break;
873 return "";
876 static const char *
877 rvabefore (int mach)
879 switch (mach)
881 case MARM:
882 case M386:
883 case MX86:
884 case MTHUMB:
885 case MARM_INTERWORK:
886 case MMCORE_BE:
887 case MMCORE_LE:
888 case MMCORE_ELF:
889 case MMCORE_ELF_LE:
890 case MARM_WINCE:
891 return ".rva\t";
892 default:
893 /* xgettext:c-format */
894 fatal (_("Internal error: Unknown machine type: %d"), mach);
895 break;
897 return "";
900 static const char *
901 asm_prefix (int mach, const char *name)
903 switch (mach)
905 case MARM:
906 case MTHUMB:
907 case MARM_INTERWORK:
908 case MMCORE_BE:
909 case MMCORE_LE:
910 case MMCORE_ELF:
911 case MMCORE_ELF_LE:
912 case MARM_WINCE:
913 break;
914 case M386:
915 case MX86:
916 /* Symbol names starting with ? do not have a leading underscore. */
917 if ((name && *name == '?') || leading_underscore == 0)
918 break;
919 else
920 return "_";
921 default:
922 /* xgettext:c-format */
923 fatal (_("Internal error: Unknown machine type: %d"), mach);
924 break;
926 return "";
929 #define ASM_BYTE mtable[machine].how_byte
930 #define ASM_SHORT mtable[machine].how_short
931 #define ASM_LONG mtable[machine].how_long
932 #define ASM_TEXT mtable[machine].how_asciz
933 #define ASM_C mtable[machine].how_comment
934 #define ASM_JUMP mtable[machine].how_jump
935 #define ASM_GLOBAL mtable[machine].how_global
936 #define ASM_SPACE mtable[machine].how_space
937 #define ASM_ALIGN_SHORT mtable[machine].how_align_short
938 #define ASM_RVA_BEFORE rvabefore (machine)
939 #define ASM_RVA_AFTER rvaafter (machine)
940 #define ASM_PREFIX(NAME) asm_prefix (machine, (NAME))
941 #define ASM_ALIGN_LONG mtable[machine].how_align_long
942 #define HOW_BFD_READ_TARGET 0 /* Always default. */
943 #define HOW_BFD_WRITE_TARGET mtable[machine].how_bfd_target
944 #define HOW_BFD_ARCH mtable[machine].how_bfd_arch
945 #define HOW_JTAB (delay ? mtable[machine].how_dljtab \
946 : mtable[machine].how_jtab)
947 #define HOW_JTAB_SIZE (delay ? mtable[machine].how_dljtab_size \
948 : mtable[machine].how_jtab_size)
949 #define HOW_JTAB_ROFF (delay ? mtable[machine].how_dljtab_roff1 \
950 : mtable[machine].how_jtab_roff)
951 #define HOW_JTAB_ROFF2 (delay ? mtable[machine].how_dljtab_roff2 : 0)
952 #define HOW_JTAB_ROFF3 (delay ? mtable[machine].how_dljtab_roff3 : 0)
953 #define ASM_SWITCHES mtable[machine].how_default_as_switches
954 #define HOW_SEH mtable[machine].how_seh
956 static char **oav;
958 static void
959 process_def_file (const char *name)
961 FILE *f = fopen (name, FOPEN_RT);
963 if (!f)
964 /* xgettext:c-format */
965 fatal (_("Can't open def file: %s"), name);
967 yyin = f;
969 /* xgettext:c-format */
970 inform (_("Processing def file: %s"), name);
972 yyparse ();
974 inform (_("Processed def file"));
977 /**********************************************************************/
979 /* Communications with the parser. */
981 static int d_nfuncs; /* Number of functions exported. */
982 static int d_named_nfuncs; /* Number of named functions exported. */
983 static int d_low_ord; /* Lowest ordinal index. */
984 static int d_high_ord; /* Highest ordinal index. */
985 static export_type *d_exports; /* List of exported functions. */
986 static export_type **d_exports_lexically; /* Vector of exported functions in alpha order. */
987 static dlist_type *d_list; /* Descriptions. */
988 static dlist_type *a_list; /* Stuff to go in directives. */
989 static int d_nforwards = 0; /* Number of forwarded exports. */
991 static int d_is_dll;
992 static int d_is_exe;
994 void
995 yyerror (const char * err ATTRIBUTE_UNUSED)
997 /* xgettext:c-format */
998 non_fatal (_("Syntax error in def file %s:%d"), def_file, linenumber);
1001 void
1002 def_exports (const char *name, const char *internal_name, int ordinal,
1003 int noname, int constant, int data, int private,
1004 const char *its_name)
1006 struct export *p = (struct export *) xmalloc (sizeof (*p));
1008 p->name = name;
1009 p->internal_name = internal_name ? internal_name : name;
1010 p->its_name = its_name;
1011 p->import_name = name;
1012 p->ordinal = ordinal;
1013 p->constant = constant;
1014 p->noname = noname;
1015 p->private = private;
1016 p->data = data;
1017 p->next = d_exports;
1018 d_exports = p;
1019 d_nfuncs++;
1021 if ((internal_name != NULL)
1022 && (strchr (internal_name, '.') != NULL))
1023 p->forward = ++d_nforwards;
1024 else
1025 p->forward = 0; /* no forward */
1028 static void
1029 set_dll_name_from_def (const char *name, char is_dll)
1031 const char *image_basename = lbasename (name);
1032 if (image_basename != name)
1033 non_fatal (_("%s: Path components stripped from image name, '%s'."),
1034 def_file, name);
1035 /* Append the default suffix, if none specified. */
1036 if (strchr (image_basename, '.') == 0)
1038 const char * suffix = is_dll ? ".dll" : ".exe";
1040 dll_name = xmalloc (strlen (image_basename) + strlen (suffix) + 1);
1041 sprintf (dll_name, "%s%s", image_basename, suffix);
1043 else
1044 dll_name = xstrdup (image_basename);
1047 void
1048 def_name (const char *name, int base)
1050 /* xgettext:c-format */
1051 inform (_("NAME: %s base: %x"), name, base);
1053 if (d_is_dll)
1054 non_fatal (_("Can't have LIBRARY and NAME"));
1056 if (dll_name_set_by_exp_name && name && *name != 0)
1058 dll_name = NULL;
1059 dll_name_set_by_exp_name = 0;
1061 /* If --dllname not provided, use the one in the DEF file.
1062 FIXME: Is this appropriate for executables? */
1063 if (!dll_name)
1064 set_dll_name_from_def (name, 0);
1065 d_is_exe = 1;
1068 void
1069 def_library (const char *name, int base)
1071 /* xgettext:c-format */
1072 inform (_("LIBRARY: %s base: %x"), name, base);
1074 if (d_is_exe)
1075 non_fatal (_("Can't have LIBRARY and NAME"));
1077 if (dll_name_set_by_exp_name && name && *name != 0)
1079 dll_name = NULL;
1080 dll_name_set_by_exp_name = 0;
1083 /* If --dllname not provided, use the one in the DEF file. */
1084 if (!dll_name)
1085 set_dll_name_from_def (name, 1);
1086 d_is_dll = 1;
1089 void
1090 def_description (const char *desc)
1092 dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1093 d->text = xstrdup (desc);
1094 d->next = d_list;
1095 d_list = d;
1098 static void
1099 new_directive (char *dir)
1101 dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1102 d->text = xstrdup (dir);
1103 d->next = a_list;
1104 a_list = d;
1107 void
1108 def_heapsize (int reserve, int commit)
1110 char b[200];
1111 if (commit > 0)
1112 sprintf (b, "-heap 0x%x,0x%x ", reserve, commit);
1113 else
1114 sprintf (b, "-heap 0x%x ", reserve);
1115 new_directive (xstrdup (b));
1118 void
1119 def_stacksize (int reserve, int commit)
1121 char b[200];
1122 if (commit > 0)
1123 sprintf (b, "-stack 0x%x,0x%x ", reserve, commit);
1124 else
1125 sprintf (b, "-stack 0x%x ", reserve);
1126 new_directive (xstrdup (b));
1129 /* append_import simply adds the given import definition to the global
1130 import_list. It is used by def_import. */
1132 static void
1133 append_import (const char *symbol_name, const char *dllname, int func_ordinal,
1134 const char *its_name)
1136 iheadtype **pq;
1137 iheadtype *q;
1139 for (pq = &import_list; *pq != NULL; pq = &(*pq)->next)
1141 if (strcmp ((*pq)->dllname, dllname) == 0)
1143 q = *pq;
1144 q->functail->next = xmalloc (sizeof (ifunctype));
1145 q->functail = q->functail->next;
1146 q->functail->ord = func_ordinal;
1147 q->functail->name = xstrdup (symbol_name);
1148 q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1149 q->functail->next = NULL;
1150 q->nfuncs++;
1151 return;
1155 q = xmalloc (sizeof (iheadtype));
1156 q->dllname = xstrdup (dllname);
1157 q->nfuncs = 1;
1158 q->funchead = xmalloc (sizeof (ifunctype));
1159 q->functail = q->funchead;
1160 q->next = NULL;
1161 q->functail->name = xstrdup (symbol_name);
1162 q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1163 q->functail->ord = func_ordinal;
1164 q->functail->next = NULL;
1166 *pq = q;
1169 /* def_import is called from within defparse.y when an IMPORT
1170 declaration is encountered. Depending on the form of the
1171 declaration, the module name may or may not need ".dll" to be
1172 appended to it, the name of the function may be stored in internal
1173 or entry, and there may or may not be an ordinal value associated
1174 with it. */
1176 /* A note regarding the parse modes:
1177 In defparse.y we have to accept import declarations which follow
1178 any one of the following forms:
1179 <func_name_in_app> = <dll_name>.<func_name_in_dll>
1180 <func_name_in_app> = <dll_name>.<number>
1181 <dll_name>.<func_name_in_dll>
1182 <dll_name>.<number>
1183 Furthermore, the dll's name may or may not end with ".dll", which
1184 complicates the parsing a little. Normally the dll's name is
1185 passed to def_import() in the "module" parameter, but when it ends
1186 with ".dll" it gets passed in "module" sans ".dll" and that needs
1187 to be reappended.
1189 def_import gets five parameters:
1190 APP_NAME - the name of the function in the application, if
1191 present, or NULL if not present.
1192 MODULE - the name of the dll, possibly sans extension (ie, '.dll').
1193 DLLEXT - the extension of the dll, if present, NULL if not present.
1194 ENTRY - the name of the function in the dll, if present, or NULL.
1195 ORD_VAL - the numerical tag of the function in the dll, if present,
1196 or NULL. Exactly one of <entry> or <ord_val> must be
1197 present (i.e., not NULL). */
1199 void
1200 def_import (const char *app_name, const char *module, const char *dllext,
1201 const char *entry, int ord_val, const char *its_name)
1203 const char *application_name;
1204 char *buf = NULL;
1206 if (entry != NULL)
1207 application_name = entry;
1208 else
1210 if (app_name != NULL)
1211 application_name = app_name;
1212 else
1213 application_name = "";
1216 if (dllext != NULL)
1217 module = buf = concat (module, ".", dllext, NULL);
1219 append_import (application_name, module, ord_val, its_name);
1221 free (buf);
1224 void
1225 def_version (int major, int minor)
1227 printf (_("VERSION %d.%d\n"), major, minor);
1230 void
1231 def_section (const char *name, int attr)
1233 char buf[200];
1234 char atts[5];
1235 char *d = atts;
1236 if (attr & 1)
1237 *d++ = 'R';
1239 if (attr & 2)
1240 *d++ = 'W';
1241 if (attr & 4)
1242 *d++ = 'X';
1243 if (attr & 8)
1244 *d++ = 'S';
1245 *d++ = 0;
1246 sprintf (buf, "-attr %s %s", name, atts);
1247 new_directive (xstrdup (buf));
1250 void
1251 def_code (int attr)
1254 def_section ("CODE", attr);
1257 void
1258 def_data (int attr)
1260 def_section ("DATA", attr);
1263 /**********************************************************************/
1265 static void
1266 run (const char *what, char *args)
1268 char *s;
1269 int pid, wait_status;
1270 int i;
1271 const char **argv;
1272 char *errmsg_fmt = NULL, *errmsg_arg = NULL;
1273 char *temp_base = make_temp_file ("");
1275 inform (_("run: %s %s"), what, args);
1277 /* Count the args */
1278 i = 0;
1279 for (s = args; *s; s++)
1280 if (*s == ' ')
1281 i++;
1282 i++;
1283 argv = xmalloc (sizeof (char *) * (i + 3));
1284 i = 0;
1285 argv[i++] = what;
1286 s = args;
1287 while (1)
1289 while (*s == ' ')
1290 ++s;
1291 argv[i++] = s;
1292 while (*s != ' ' && *s != 0)
1293 s++;
1294 if (*s == 0)
1295 break;
1296 *s++ = 0;
1298 argv[i++] = NULL;
1300 pid = pexecute (argv[0], (char * const *) argv, program_name, temp_base,
1301 &errmsg_fmt, &errmsg_arg, PEXECUTE_ONE | PEXECUTE_SEARCH);
1302 free (argv);
1304 if (pid == -1)
1306 inform ("%s", strerror (errno));
1308 fatal (errmsg_fmt, errmsg_arg);
1311 pid = pwait (pid, & wait_status, 0);
1313 if (pid == -1)
1315 /* xgettext:c-format */
1316 fatal (_("wait: %s"), strerror (errno));
1318 else if (WIFSIGNALED (wait_status))
1320 /* xgettext:c-format */
1321 fatal (_("subprocess got fatal signal %d"), WTERMSIG (wait_status));
1323 else if (WIFEXITED (wait_status))
1325 if (WEXITSTATUS (wait_status) != 0)
1326 /* xgettext:c-format */
1327 non_fatal (_("%s exited with status %d"),
1328 what, WEXITSTATUS (wait_status));
1330 else
1331 abort ();
1334 /* Look for a list of symbols to export in the .drectve section of
1335 ABFD. Pass each one to def_exports. */
1337 static void
1338 scan_drectve_symbols (bfd *abfd)
1340 asection * s;
1341 int size;
1342 char * buf;
1343 char * p;
1344 char * e;
1346 /* Look for .drectve's */
1347 s = bfd_get_section_by_name (abfd, DRECTVE_SECTION_NAME);
1349 if (s == NULL)
1350 return;
1352 size = bfd_section_size (s);
1353 buf = xmalloc (size);
1355 bfd_get_section_contents (abfd, s, buf, 0, size);
1357 /* xgettext:c-format */
1358 inform (_("Sucking in info from %s section in %s"),
1359 DRECTVE_SECTION_NAME, bfd_get_filename (abfd));
1361 /* Search for -export: strings. The exported symbols can optionally
1362 have type tags (eg., -export:foo,data), so handle those as well.
1363 Currently only data tag is supported. */
1364 p = buf;
1365 e = buf + size;
1366 while (p < e)
1368 if (p[0] == '-'
1369 && startswith (p, "-export:"))
1371 char * name;
1372 char * c;
1373 flagword flags = BSF_FUNCTION;
1375 p += 8;
1376 /* Do we have a quoted export? */
1377 if (*p == '"')
1379 p++;
1380 name = p;
1381 while (p < e && *p != '"')
1382 ++p;
1384 else
1386 name = p;
1387 while (p < e && *p != ',' && *p != ' ' && *p != '-')
1388 p++;
1390 c = xmalloc (p - name + 1);
1391 memcpy (c, name, p - name);
1392 c[p - name] = 0;
1393 /* Advance over trailing quote. */
1394 if (p < e && *p == '"')
1395 ++p;
1396 if (p < e && *p == ',') /* found type tag. */
1398 char *tag_start = ++p;
1399 while (p < e && *p != ' ' && *p != '-')
1400 p++;
1401 if (startswith (tag_start, "data"))
1402 flags &= ~BSF_FUNCTION;
1405 /* FIXME: The 5th arg is for the `constant' field.
1406 What should it be? Not that it matters since it's not
1407 currently useful. */
1408 def_exports (c, 0, -1, 0, 0, ! (flags & BSF_FUNCTION), 0, NULL);
1410 if (add_stdcall_alias && strchr (c, '@'))
1412 int lead_at = (*c == '@') ;
1413 char *exported_name = xstrdup (c + lead_at);
1414 char *atsym = strchr (exported_name, '@');
1415 *atsym = '\0';
1416 /* Note: stdcall alias symbols can never be data. */
1417 def_exports (exported_name, xstrdup (c), -1, 0, 0, 0, 0, NULL);
1420 else
1421 p++;
1423 free (buf);
1426 /* Look through the symbols in MINISYMS, and add each one to list of
1427 symbols to export. */
1429 static void
1430 scan_filtered_symbols (bfd *abfd, void *minisyms, long symcount,
1431 unsigned int size)
1433 asymbol *store;
1434 bfd_byte *from, *fromend;
1436 store = bfd_make_empty_symbol (abfd);
1437 if (store == NULL)
1438 bfd_fatal (bfd_get_filename (abfd));
1440 from = (bfd_byte *) minisyms;
1441 fromend = from + symcount * size;
1442 for (; from < fromend; from += size)
1444 asymbol *sym;
1445 const char *symbol_name;
1447 sym = bfd_minisymbol_to_symbol (abfd, false, from, store);
1448 if (sym == NULL)
1449 bfd_fatal (bfd_get_filename (abfd));
1451 symbol_name = bfd_asymbol_name (sym);
1452 if (bfd_get_symbol_leading_char (abfd) == symbol_name[0])
1453 ++symbol_name;
1455 def_exports (xstrdup (symbol_name) , 0, -1, 0, 0,
1456 ! (sym->flags & BSF_FUNCTION), 0, NULL);
1458 if (add_stdcall_alias && strchr (symbol_name, '@'))
1460 int lead_at = (*symbol_name == '@');
1461 char *exported_name = xstrdup (symbol_name + lead_at);
1462 char *atsym = strchr (exported_name, '@');
1463 *atsym = '\0';
1464 /* Note: stdcall alias symbols can never be data. */
1465 def_exports (exported_name, xstrdup (symbol_name), -1, 0, 0, 0, 0, NULL);
1470 /* Add a list of symbols to exclude. */
1472 static void
1473 add_excludes (const char *new_excludes)
1475 char *local_copy;
1476 char *exclude_string;
1478 local_copy = xstrdup (new_excludes);
1480 exclude_string = strtok (local_copy, ",:");
1481 for (; exclude_string; exclude_string = strtok (NULL, ",:"))
1483 struct string_list *new_exclude;
1485 new_exclude = ((struct string_list *)
1486 xmalloc (sizeof (struct string_list)));
1487 new_exclude->string = (char *) xmalloc (strlen (exclude_string) + 2);
1488 /* Don't add a leading underscore for fastcall symbols. */
1489 if (*exclude_string == '@')
1490 sprintf (new_exclude->string, "%s", exclude_string);
1491 else
1492 sprintf (new_exclude->string, "%s%s", (!leading_underscore ? "" : "_"),
1493 exclude_string);
1494 new_exclude->next = excludes;
1495 excludes = new_exclude;
1497 /* xgettext:c-format */
1498 inform (_("Excluding symbol: %s"), exclude_string);
1501 free (local_copy);
1504 /* See if STRING is on the list of symbols to exclude. */
1506 static bool
1507 match_exclude (const char *string)
1509 struct string_list *excl_item;
1511 for (excl_item = excludes; excl_item; excl_item = excl_item->next)
1512 if (strcmp (string, excl_item->string) == 0)
1513 return true;
1514 return false;
1517 /* Add the default list of symbols to exclude. */
1519 static void
1520 set_default_excludes (void)
1522 add_excludes (default_excludes);
1525 /* Choose which symbols to export. */
1527 static long
1528 filter_symbols (bfd *abfd, void *minisyms, long symcount, unsigned int size)
1530 bfd_byte *from, *fromend, *to;
1531 asymbol *store;
1533 store = bfd_make_empty_symbol (abfd);
1534 if (store == NULL)
1535 bfd_fatal (bfd_get_filename (abfd));
1537 from = (bfd_byte *) minisyms;
1538 fromend = from + symcount * size;
1539 to = (bfd_byte *) minisyms;
1541 for (; from < fromend; from += size)
1543 int keep = 0;
1544 asymbol *sym;
1546 sym = bfd_minisymbol_to_symbol (abfd, false, (const void *) from, store);
1547 if (sym == NULL)
1548 bfd_fatal (bfd_get_filename (abfd));
1550 /* Check for external and defined only symbols. */
1551 keep = (((sym->flags & BSF_GLOBAL) != 0
1552 || (sym->flags & BSF_WEAK) != 0
1553 || bfd_is_com_section (sym->section))
1554 && ! bfd_is_und_section (sym->section));
1556 keep = keep && ! match_exclude (sym->name);
1558 if (keep)
1560 memcpy (to, from, size);
1561 to += size;
1565 return (to - (bfd_byte *) minisyms) / size;
1568 /* Export all symbols in ABFD, except for ones we were told not to
1569 export. */
1571 static void
1572 scan_all_symbols (bfd *abfd)
1574 long symcount;
1575 void *minisyms;
1576 unsigned int size;
1578 /* Ignore bfds with an import descriptor table. We assume that any
1579 such BFD contains symbols which are exported from another DLL,
1580 and we don't want to reexport them from here. */
1581 if (bfd_get_section_by_name (abfd, ".idata$4"))
1582 return;
1584 if (! (bfd_get_file_flags (abfd) & HAS_SYMS))
1586 /* xgettext:c-format */
1587 non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1588 return;
1591 symcount = bfd_read_minisymbols (abfd, false, &minisyms, &size);
1592 if (symcount < 0)
1593 bfd_fatal (bfd_get_filename (abfd));
1595 if (symcount == 0)
1597 /* xgettext:c-format */
1598 non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1599 return;
1602 /* Discard the symbols we don't want to export. It's OK to do this
1603 in place; we'll free the storage anyway. */
1605 symcount = filter_symbols (abfd, minisyms, symcount, size);
1606 scan_filtered_symbols (abfd, minisyms, symcount, size);
1608 free (minisyms);
1611 /* Look at the object file to decide which symbols to export. */
1613 static void
1614 scan_open_obj_file (bfd *abfd)
1616 if (export_all_symbols)
1617 scan_all_symbols (abfd);
1618 else
1619 scan_drectve_symbols (abfd);
1621 /* FIXME: we ought to read in and block out the base relocations. */
1623 /* xgettext:c-format */
1624 inform (_("Done reading %s"), bfd_get_filename (abfd));
1627 static void
1628 scan_obj_file (const char *filename)
1630 bfd * f = bfd_openr (filename, 0);
1632 if (!f)
1633 /* xgettext:c-format */
1634 fatal (_("Unable to open object file: %s: %s"), filename, bfd_get_errmsg ());
1636 /* xgettext:c-format */
1637 inform (_("Scanning object file %s"), filename);
1639 if (bfd_check_format (f, bfd_archive))
1641 bfd *arfile = bfd_openr_next_archived_file (f, 0);
1642 while (arfile)
1644 bfd *next;
1645 if (bfd_check_format (arfile, bfd_object))
1646 scan_open_obj_file (arfile);
1647 next = bfd_openr_next_archived_file (f, arfile);
1648 bfd_close (arfile);
1649 /* PR 17512: file: 58715298. */
1650 if (next == arfile)
1651 break;
1652 arfile = next;
1655 #ifdef DLLTOOL_MCORE_ELF
1656 if (mcore_elf_out_file)
1657 inform (_("Cannot produce mcore-elf dll from archive file: %s"), filename);
1658 #endif
1660 else if (bfd_check_format (f, bfd_object))
1662 scan_open_obj_file (f);
1664 #ifdef DLLTOOL_MCORE_ELF
1665 if (mcore_elf_out_file)
1666 mcore_elf_cache_filename (filename);
1667 #endif
1670 bfd_close (f);
1675 static void
1676 dump_def_info (FILE *f)
1678 int i;
1679 export_type *exp;
1680 fprintf (f, "%s ", ASM_C);
1681 for (i = 0; oav[i]; i++)
1682 fprintf (f, "%s ", oav[i]);
1683 fprintf (f, "\n");
1684 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1686 fprintf (f, "%s %d = %s %s @ %d %s%s%s%s%s%s\n",
1687 ASM_C,
1689 exp->name,
1690 exp->internal_name,
1691 exp->ordinal,
1692 exp->noname ? "NONAME " : "",
1693 exp->private ? "PRIVATE " : "",
1694 exp->constant ? "CONSTANT" : "",
1695 exp->data ? "DATA" : "",
1696 exp->its_name ? " ==" : "",
1697 exp->its_name ? exp->its_name : "");
1701 /* Generate the .exp file. */
1703 static int
1704 sfunc (const void *a, const void *b)
1706 if (*(const bfd_vma *) a == *(const bfd_vma *) b)
1707 return 0;
1709 return ((*(const bfd_vma *) a > *(const bfd_vma *) b) ? 1 : -1);
1712 static void
1713 flush_page (FILE *f, bfd_vma *need, bfd_vma page_addr, int on_page)
1715 int i;
1717 /* Flush this page. */
1718 fprintf (f, "\t%s\t0x%08x\t%s Starting RVA for chunk\n",
1719 ASM_LONG,
1720 (int) page_addr,
1721 ASM_C);
1722 fprintf (f, "\t%s\t0x%x\t%s Size of block\n",
1723 ASM_LONG,
1724 (on_page * 2) + (on_page & 1) * 2 + 8,
1725 ASM_C);
1727 for (i = 0; i < on_page; i++)
1729 bfd_vma needed = need[i];
1731 if (needed)
1733 if (!create_for_pep)
1735 /* Relocation via HIGHLOW. */
1736 needed = ((needed - page_addr) | 0x3000) & 0xffff;
1738 else
1740 /* Relocation via DIR64. */
1741 needed = ((needed - page_addr) | 0xa000) & 0xffff;
1745 fprintf (f, "\t%s\t0x%lx\n", ASM_SHORT, (long) needed);
1748 /* And padding */
1749 if (on_page & 1)
1750 fprintf (f, "\t%s\t0x%x\n", ASM_SHORT, 0 | 0x0000);
1753 static void
1754 gen_def_file (void)
1756 int i;
1757 export_type *exp;
1759 inform (_("Adding exports to output file"));
1761 fprintf (output_def, ";");
1762 for (i = 0; oav[i]; i++)
1763 fprintf (output_def, " %s", oav[i]);
1765 fprintf (output_def, "\nEXPORTS\n");
1767 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1769 char *quote = strchr (exp->name, '.') ? "\"" : "";
1770 char *res = cplus_demangle (exp->internal_name, DMGL_ANSI | DMGL_PARAMS);
1772 if (res)
1774 fprintf (output_def,";\t%s\n", res);
1775 free (res);
1778 if (strcmp (exp->name, exp->internal_name) == 0)
1780 fprintf (output_def, "\t%s%s%s @ %d%s%s%s%s%s\n",
1781 quote,
1782 exp->name,
1783 quote,
1784 exp->ordinal,
1785 exp->noname ? " NONAME" : "",
1786 exp->private ? "PRIVATE " : "",
1787 exp->data ? " DATA" : "",
1788 exp->its_name ? " ==" : "",
1789 exp->its_name ? exp->its_name : "");
1791 else
1793 char * quote1 = strchr (exp->internal_name, '.') ? "\"" : "";
1794 /* char *alias = */
1795 fprintf (output_def, "\t%s%s%s = %s%s%s @ %d%s%s%s%s%s\n",
1796 quote,
1797 exp->name,
1798 quote,
1799 quote1,
1800 exp->internal_name,
1801 quote1,
1802 exp->ordinal,
1803 exp->noname ? " NONAME" : "",
1804 exp->private ? "PRIVATE " : "",
1805 exp->data ? " DATA" : "",
1806 exp->its_name ? " ==" : "",
1807 exp->its_name ? exp->its_name : "");
1811 inform (_("Added exports to output file"));
1814 /* generate_idata_ofile generates the portable assembly source code
1815 for the idata sections. It appends the source code to the end of
1816 the file. */
1818 static void
1819 generate_idata_ofile (FILE *filvar)
1821 iheadtype *headptr;
1822 ifunctype *funcptr;
1823 int headindex;
1824 int funcindex;
1825 int nheads;
1827 if (import_list == NULL)
1828 return;
1830 fprintf (filvar, "%s Import data sections\n", ASM_C);
1831 fprintf (filvar, "\n\t.section\t.idata$2\n");
1832 fprintf (filvar, "\t%s\tdoi_idata\n", ASM_GLOBAL);
1833 fprintf (filvar, "doi_idata:\n");
1835 nheads = 0;
1836 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1838 fprintf (filvar, "\t%slistone%d%s\t%s %s\n",
1839 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER,
1840 ASM_C, headptr->dllname);
1841 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1842 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1843 fprintf (filvar, "\t%sdllname%d%s\n",
1844 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1845 fprintf (filvar, "\t%slisttwo%d%s\n\n",
1846 ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1847 nheads++;
1850 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL record at */
1851 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* end of idata$2 */
1852 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* section */
1853 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1854 fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1856 fprintf (filvar, "\n\t.section\t.idata$4\n");
1857 headindex = 0;
1858 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1860 fprintf (filvar, "listone%d:\n", headindex);
1861 for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1863 if (create_for_pep)
1864 fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1865 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1866 ASM_LONG);
1867 else
1868 fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1869 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1871 if (create_for_pep)
1872 fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1873 else
1874 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
1875 headindex++;
1878 fprintf (filvar, "\n\t.section\t.idata$5\n");
1879 headindex = 0;
1880 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1882 fprintf (filvar, "listtwo%d:\n", headindex);
1883 for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1885 if (create_for_pep)
1886 fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1887 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1888 ASM_LONG);
1889 else
1890 fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1891 ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1893 if (create_for_pep)
1894 fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1895 else
1896 fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
1897 headindex++;
1900 fprintf (filvar, "\n\t.section\t.idata$6\n");
1901 headindex = 0;
1902 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1904 funcindex = 0;
1905 for (funcptr = headptr->funchead; funcptr != NULL;
1906 funcptr = funcptr->next)
1908 fprintf (filvar,"funcptr%d_%d:\n", headindex, funcindex);
1909 fprintf (filvar,"\t%s\t%d\n", ASM_SHORT,
1910 ((funcptr->ord) & 0xFFFF));
1911 fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT,
1912 (funcptr->its_name ? funcptr->its_name : funcptr->name));
1913 fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1914 funcindex++;
1916 headindex++;
1919 fprintf (filvar, "\n\t.section\t.idata$7\n");
1920 headindex = 0;
1921 for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1923 fprintf (filvar,"dllname%d:\n", headindex);
1924 fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT, headptr->dllname);
1925 fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1926 headindex++;
1930 /* Assemble the specified file. */
1931 static void
1932 assemble_file (const char * source, const char * dest)
1934 char * cmd;
1936 cmd = xmalloc (strlen (ASM_SWITCHES) + strlen (as_flags)
1937 + strlen (source) + strlen (dest) + 50);
1939 sprintf (cmd, "%s %s -o %s %s", ASM_SWITCHES, as_flags, dest, source);
1941 run (as_name, cmd);
1942 free (cmd);
1945 static const char * temp_file_to_remove[5];
1946 #define TEMP_EXPORT_FILE 0
1947 #define TEMP_HEAD_FILE 1
1948 #define TEMP_TAIL_FILE 2
1949 #define TEMP_HEAD_O_FILE 3
1950 #define TEMP_TAIL_O_FILE 4
1952 static void
1953 unlink_temp_files (void)
1955 unsigned i;
1957 if (dontdeltemps > 0)
1958 return;
1960 for (i = 0; i < ARRAY_SIZE (temp_file_to_remove); i++)
1962 if (temp_file_to_remove[i])
1964 unlink (temp_file_to_remove[i]);
1965 temp_file_to_remove[i] = NULL;
1970 static void
1971 gen_exp_file (void)
1973 FILE *f;
1974 int i;
1975 export_type *exp;
1976 dlist_type *dl;
1978 /* xgettext:c-format */
1979 inform (_("Generating export file: %s"), exp_name);
1981 f = fopen (TMP_ASM, FOPEN_WT);
1982 if (!f)
1983 /* xgettext:c-format */
1984 fatal (_("Unable to open temporary assembler file: %s"), TMP_ASM);
1986 temp_file_to_remove[TEMP_EXPORT_FILE] = TMP_ASM;
1988 /* xgettext:c-format */
1989 inform (_("Opened temporary file: %s"), TMP_ASM);
1991 dump_def_info (f);
1993 if (d_exports)
1995 fprintf (f, "\t.section .edata\n\n");
1996 fprintf (f, "\t%s 0 %s Allways 0\n", ASM_LONG, ASM_C);
1997 fprintf (f, "\t%s 0x%lx %s Time and date\n", ASM_LONG,
1998 (unsigned long) time(0), ASM_C);
1999 fprintf (f, "\t%s 0 %s Major and Minor version\n", ASM_LONG, ASM_C);
2000 fprintf (f, "\t%sname%s %s Ptr to name of dll\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2001 fprintf (f, "\t%s %d %s Starting ordinal of exports\n", ASM_LONG, d_low_ord, ASM_C);
2004 fprintf (f, "\t%s %d %s Number of functions\n", ASM_LONG, d_high_ord - d_low_ord + 1, ASM_C);
2005 fprintf(f,"\t%s named funcs %d, low ord %d, high ord %d\n",
2006 ASM_C,
2007 d_named_nfuncs, d_low_ord, d_high_ord);
2008 fprintf (f, "\t%s %d %s Number of names\n", ASM_LONG,
2009 show_allnames ? d_high_ord - d_low_ord + 1 : d_named_nfuncs, ASM_C);
2010 fprintf (f, "\t%safuncs%s %s Address of functions\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2012 fprintf (f, "\t%sanames%s %s Address of Name Pointer Table\n",
2013 ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2015 fprintf (f, "\t%sanords%s %s Address of ordinals\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2017 fprintf (f, "name: %s \"%s\"\n", ASM_TEXT, dll_name);
2020 fprintf(f,"%s Export address Table\n", ASM_C);
2021 fprintf(f,"\t%s\n", ASM_ALIGN_LONG);
2022 fprintf (f, "afuncs:\n");
2023 i = d_low_ord;
2025 for (exp = d_exports; exp; exp = exp->next)
2027 if (exp->ordinal != i)
2029 while (i < exp->ordinal)
2031 fprintf(f,"\t%s\t0\n", ASM_LONG);
2032 i++;
2036 if (exp->forward == 0)
2038 if (exp->internal_name[0] == '@')
2039 fprintf (f, "\t%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2040 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2041 else
2042 fprintf (f, "\t%s%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2043 ASM_PREFIX (exp->internal_name),
2044 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2046 else
2047 fprintf (f, "\t%sf%d%s\t%s %d\n", ASM_RVA_BEFORE,
2048 exp->forward, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2049 i++;
2052 fprintf (f,"%s Export Name Pointer Table\n", ASM_C);
2053 fprintf (f, "anames:\n");
2055 for (i = 0; (exp = d_exports_lexically[i]); i++)
2057 if (!exp->noname || show_allnames)
2058 fprintf (f, "\t%sn%d%s\n",
2059 ASM_RVA_BEFORE, exp->ordinal, ASM_RVA_AFTER);
2062 fprintf (f,"%s Export Ordinal Table\n", ASM_C);
2063 fprintf (f, "anords:\n");
2064 for (i = 0; (exp = d_exports_lexically[i]); i++)
2066 if (!exp->noname || show_allnames)
2067 fprintf (f, "\t%s %d\n", ASM_SHORT, exp->ordinal - d_low_ord);
2070 fprintf(f,"%s Export Name Table\n", ASM_C);
2071 for (i = 0; (exp = d_exports_lexically[i]); i++)
2073 if (!exp->noname || show_allnames)
2074 fprintf (f, "n%d: %s \"%s\"\n",
2075 exp->ordinal, ASM_TEXT,
2076 (exp->its_name ? exp->its_name : xlate (exp->name)));
2077 if (exp->forward != 0)
2078 fprintf (f, "f%d: %s \"%s\"\n",
2079 exp->forward, ASM_TEXT, exp->internal_name);
2082 if (a_list)
2084 fprintf (f, "\t.section %s\n", DRECTVE_SECTION_NAME);
2085 for (dl = a_list; dl; dl = dl->next)
2087 fprintf (f, "\t%s\t\"%s\"\n", ASM_TEXT, dl->text);
2091 if (d_list)
2093 fprintf (f, "\t.section .rdata\n");
2094 for (dl = d_list; dl; dl = dl->next)
2096 char *p;
2097 int l;
2099 /* We don't output as ascii because there can
2100 be quote characters in the string. */
2101 l = 0;
2102 for (p = dl->text; *p; p++)
2104 if (l == 0)
2105 fprintf (f, "\t%s\t", ASM_BYTE);
2106 else
2107 fprintf (f, ",");
2108 fprintf (f, "%d", *p);
2109 if (p[1] == 0)
2111 fprintf (f, ",0\n");
2112 break;
2114 if (++l == 10)
2116 fprintf (f, "\n");
2117 l = 0;
2124 /* Add to the output file a way of getting to the exported names
2125 without using the import library. */
2126 if (add_indirect)
2128 fprintf (f, "\t.section\t.rdata\n");
2129 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
2130 if (!exp->noname || show_allnames)
2132 /* We use a single underscore for MS compatibility, and a
2133 double underscore for backward compatibility with old
2134 cygwin releases. */
2135 if (create_compat_implib)
2136 fprintf (f, "\t%s\t__imp_%s\n", ASM_GLOBAL, exp->name);
2137 fprintf (f, "\t%s\t_imp_%s%s\n", ASM_GLOBAL,
2138 (!leading_underscore ? "" : "_"), exp->name);
2139 if (create_compat_implib)
2140 fprintf (f, "__imp_%s:\n", exp->name);
2141 fprintf (f, "_imp_%s%s:\n", (!leading_underscore ? "" : "_"), exp->name);
2142 fprintf (f, "\t%s\t%s\n", ASM_LONG, exp->name);
2146 /* Dump the reloc section if a base file is provided. */
2147 if (base_file)
2149 bfd_vma addr;
2150 bfd_vma need[COFF_PAGE_SIZE];
2151 bfd_vma page_addr;
2152 bfd_size_type numbytes;
2153 int num_entries;
2154 bfd_vma *copy;
2155 int j;
2156 int on_page;
2157 fprintf (f, "\t.section\t.init\n");
2158 fprintf (f, "lab:\n");
2160 fseek (base_file, 0, SEEK_END);
2161 numbytes = ftell (base_file);
2162 fseek (base_file, 0, SEEK_SET);
2163 copy = xmalloc (numbytes);
2164 if (fread (copy, 1, numbytes, base_file) < numbytes)
2165 fatal (_("failed to read the number of entries from base file"));
2166 num_entries = numbytes / sizeof (bfd_vma);
2169 fprintf (f, "\t.section\t.reloc\n");
2170 if (num_entries)
2172 int src;
2173 int dst = 0;
2174 bfd_vma last = (bfd_vma) -1;
2175 qsort (copy, num_entries, sizeof (bfd_vma), sfunc);
2176 /* Delete duplicates */
2177 for (src = 0; src < num_entries; src++)
2179 if (last != copy[src])
2180 last = copy[dst++] = copy[src];
2182 num_entries = dst;
2183 addr = copy[0];
2184 page_addr = addr & PAGE_MASK; /* work out the page addr */
2185 on_page = 0;
2186 for (j = 0; j < num_entries; j++)
2188 addr = copy[j];
2189 if ((addr & PAGE_MASK) != page_addr)
2191 flush_page (f, need, page_addr, on_page);
2192 on_page = 0;
2193 page_addr = addr & PAGE_MASK;
2195 need[on_page++] = addr;
2197 flush_page (f, need, page_addr, on_page);
2199 /* fprintf (f, "\t%s\t0,0\t%s End\n", ASM_LONG, ASM_C);*/
2203 generate_idata_ofile (f);
2205 fclose (f);
2207 /* Assemble the file. */
2208 assemble_file (TMP_ASM, exp_name);
2210 if (dontdeltemps == 0)
2212 temp_file_to_remove[TEMP_EXPORT_FILE] = NULL;
2213 unlink (TMP_ASM);
2216 inform (_("Generated exports file"));
2219 static const char *
2220 xlate (const char *name)
2222 int lead_at = (*name == '@');
2223 int is_stdcall = (!lead_at && strchr (name, '@') != NULL);
2225 if (!lead_at && (add_underscore
2226 || (add_stdcall_underscore && is_stdcall)))
2228 char *copy = xmalloc (strlen (name) + 2);
2230 copy[0] = '_';
2231 strcpy (copy + 1, name);
2232 name = copy;
2235 if (killat)
2237 char *p;
2239 name += lead_at;
2240 /* PR 9766: Look for the last @ sign in the name. */
2241 p = strrchr (name, '@');
2242 if (p && ISDIGIT (p[1]))
2243 *p = 0;
2245 return name;
2248 typedef struct
2250 int id;
2251 const char *name;
2252 int flags;
2253 int align;
2254 asection *sec;
2255 asymbol *sym;
2256 asymbol **sympp;
2257 int size;
2258 unsigned char *data;
2259 } sinfo;
2261 #define INIT_SEC_DATA(id, name, flags, align) \
2262 { id, name, flags, align, NULL, NULL, NULL, 0, NULL }
2264 #define TEXT 0
2265 #define DATA 1
2266 #define BSS 2
2267 #define IDATA7 3
2268 #define IDATA5 4
2269 #define IDATA4 5
2270 #define IDATA6 6
2272 #define NSECS 7
2274 #define TEXT_SEC_FLAGS \
2275 (SEC_ALLOC | SEC_LOAD | SEC_CODE | SEC_READONLY | SEC_HAS_CONTENTS)
2276 #define DATA_SEC_FLAGS (SEC_ALLOC | SEC_LOAD | SEC_DATA)
2277 #define BSS_SEC_FLAGS SEC_ALLOC
2279 static sinfo secdata[NSECS] =
2281 INIT_SEC_DATA (TEXT, ".text", TEXT_SEC_FLAGS, 2),
2282 INIT_SEC_DATA (DATA, ".data", DATA_SEC_FLAGS, 2),
2283 INIT_SEC_DATA (BSS, ".bss", BSS_SEC_FLAGS, 2),
2284 INIT_SEC_DATA (IDATA7, ".idata$7", SEC_HAS_CONTENTS, 2),
2285 INIT_SEC_DATA (IDATA5, ".idata$5", SEC_HAS_CONTENTS, 2),
2286 INIT_SEC_DATA (IDATA4, ".idata$4", SEC_HAS_CONTENTS, 2),
2287 INIT_SEC_DATA (IDATA6, ".idata$6", SEC_HAS_CONTENTS, 1)
2290 /* This is what we're trying to make. We generate the imp symbols with
2291 both single and double underscores, for compatibility.
2293 .text
2294 .global _GetFileVersionInfoSizeW@8
2295 .global __imp_GetFileVersionInfoSizeW@8
2296 _GetFileVersionInfoSizeW@8:
2297 jmp * __imp_GetFileVersionInfoSizeW@8
2298 .section .idata$7 # To force loading of head
2299 .long __version_a_head
2300 # Import Address Table
2301 .section .idata$5
2302 __imp_GetFileVersionInfoSizeW@8:
2303 .rva ID2
2305 # Import Lookup Table
2306 .section .idata$4
2307 .rva ID2
2308 # Hint/Name table
2309 .section .idata$6
2310 ID2: .short 2
2311 .asciz "GetFileVersionInfoSizeW" */
2313 static char *
2314 make_label (const char *prefix, const char *name)
2316 int len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2317 char *copy = xmalloc (len + 1);
2319 strcpy (copy, ASM_PREFIX (name));
2320 strcat (copy, prefix);
2321 strcat (copy, name);
2322 return copy;
2325 static char *
2326 make_imp_label (const char *prefix, const char *name)
2328 int len;
2329 char *copy;
2331 if (name[0] == '@')
2333 len = strlen (prefix) + strlen (name);
2334 copy = xmalloc (len + 1);
2335 strcpy (copy, prefix);
2336 strcat (copy, name);
2338 else
2340 len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2341 copy = xmalloc (len + 1);
2342 strcpy (copy, prefix);
2343 strcat (copy, ASM_PREFIX (name));
2344 strcat (copy, name);
2346 return copy;
2349 static bfd *
2350 make_one_lib_file (export_type *exp, int i, int delay)
2352 bfd * abfd;
2353 asymbol * exp_label;
2354 asymbol * iname = 0;
2355 asymbol * iname2;
2356 asymbol * iname_lab;
2357 asymbol ** iname_lab_pp;
2358 asymbol ** iname_pp;
2359 #ifndef EXTRA
2360 #define EXTRA 0
2361 #endif
2362 asymbol * ptrs[NSECS + 4 + EXTRA + 1];
2363 flagword applicable;
2364 char * outname = xmalloc (strlen (TMP_STUB) + 10);
2365 int oidx = 0;
2368 sprintf (outname, "%s%05d.o", TMP_STUB, i);
2370 abfd = bfd_openw (outname, HOW_BFD_WRITE_TARGET);
2372 if (!abfd)
2373 /* xgettext:c-format */
2374 fatal (_("bfd_open failed open stub file: %s: %s"),
2375 outname, bfd_get_errmsg ());
2377 /* xgettext:c-format */
2378 inform (_("Creating stub file: %s"), outname);
2380 bfd_set_format (abfd, bfd_object);
2381 bfd_set_arch_mach (abfd, HOW_BFD_ARCH, 0);
2383 #ifdef DLLTOOL_ARM
2384 if (machine == MARM_INTERWORK || machine == MTHUMB)
2385 bfd_set_private_flags (abfd, F_INTERWORK);
2386 #endif
2388 applicable = bfd_applicable_section_flags (abfd);
2390 /* First make symbols for the sections. */
2391 for (i = 0; i < NSECS; i++)
2393 sinfo *si = secdata + i;
2395 if (si->id != i)
2396 abort ();
2397 si->sec = bfd_make_section_old_way (abfd, si->name);
2398 bfd_set_section_flags (si->sec, si->flags & applicable);
2400 bfd_set_section_alignment (si->sec, si->align);
2401 si->sec->output_section = si->sec;
2402 si->sym = bfd_make_empty_symbol(abfd);
2403 si->sym->name = si->sec->name;
2404 si->sym->section = si->sec;
2405 si->sym->flags = BSF_LOCAL;
2406 si->sym->value = 0;
2407 ptrs[oidx] = si->sym;
2408 si->sympp = ptrs + oidx;
2409 si->size = 0;
2410 si->data = NULL;
2412 oidx++;
2415 if (! exp->data)
2417 exp_label = bfd_make_empty_symbol (abfd);
2418 exp_label->name = make_imp_label ("", exp->name);
2419 exp_label->section = secdata[TEXT].sec;
2420 exp_label->flags = BSF_GLOBAL;
2421 exp_label->value = 0;
2423 #ifdef DLLTOOL_ARM
2424 if (machine == MTHUMB)
2425 bfd_coff_set_symbol_class (abfd, exp_label, C_THUMBEXTFUNC);
2426 #endif
2427 ptrs[oidx++] = exp_label;
2430 /* Generate imp symbols with one underscore for Microsoft
2431 compatibility, and with two underscores for backward
2432 compatibility with old versions of cygwin. */
2433 if (create_compat_implib)
2435 iname = bfd_make_empty_symbol (abfd);
2436 iname->name = make_imp_label ("___imp", exp->name);
2437 iname->section = secdata[IDATA5].sec;
2438 iname->flags = BSF_GLOBAL;
2439 iname->value = 0;
2442 iname2 = bfd_make_empty_symbol (abfd);
2443 iname2->name = make_imp_label ("__imp_", exp->name);
2444 iname2->section = secdata[IDATA5].sec;
2445 iname2->flags = BSF_GLOBAL;
2446 iname2->value = 0;
2448 iname_lab = bfd_make_empty_symbol (abfd);
2450 iname_lab->name = head_label;
2451 iname_lab->section = bfd_und_section_ptr;
2452 iname_lab->flags = 0;
2453 iname_lab->value = 0;
2455 iname_pp = ptrs + oidx;
2456 if (create_compat_implib)
2457 ptrs[oidx++] = iname;
2458 ptrs[oidx++] = iname2;
2460 iname_lab_pp = ptrs + oidx;
2461 ptrs[oidx++] = iname_lab;
2463 ptrs[oidx] = 0;
2465 for (i = 0; i < NSECS; i++)
2467 sinfo *si = secdata + i;
2468 asection *sec = si->sec;
2469 arelent *rel, *rel2 = 0, *rel3 = 0;
2470 arelent **rpp;
2472 switch (i)
2474 case TEXT:
2475 if (! exp->data)
2477 si->size = HOW_JTAB_SIZE;
2478 si->data = xmalloc (HOW_JTAB_SIZE);
2479 memcpy (si->data, HOW_JTAB, HOW_JTAB_SIZE);
2481 /* Add the reloc into idata$5. */
2482 rel = xmalloc (sizeof (arelent));
2484 rpp = xmalloc (sizeof (arelent *) * (delay ? 4 : 2));
2485 rpp[0] = rel;
2486 rpp[1] = 0;
2488 rel->address = HOW_JTAB_ROFF;
2489 rel->addend = 0;
2491 if (delay)
2493 rel2 = xmalloc (sizeof (arelent));
2494 rpp[1] = rel2;
2495 rel2->address = HOW_JTAB_ROFF2;
2496 rel2->addend = 0;
2497 rel3 = xmalloc (sizeof (arelent));
2498 rpp[2] = rel3;
2499 rel3->address = HOW_JTAB_ROFF3;
2500 rel3->addend = 0;
2501 rpp[3] = 0;
2504 if (machine == MX86)
2506 rel->howto = bfd_reloc_type_lookup (abfd,
2507 BFD_RELOC_32_PCREL);
2508 rel->sym_ptr_ptr = iname_pp;
2510 else
2512 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2513 rel->sym_ptr_ptr = secdata[IDATA5].sympp;
2516 if (delay)
2518 if (machine == MX86)
2519 rel2->howto = bfd_reloc_type_lookup (abfd,
2520 BFD_RELOC_32_PCREL);
2521 else
2522 rel2->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2523 rel2->sym_ptr_ptr = rel->sym_ptr_ptr;
2524 rel3->howto = bfd_reloc_type_lookup (abfd,
2525 BFD_RELOC_32_PCREL);
2526 rel3->sym_ptr_ptr = iname_lab_pp;
2529 sec->orelocation = rpp;
2530 sec->reloc_count = delay ? 3 : 1;
2532 break;
2534 case IDATA5:
2535 if (delay)
2537 si->size = create_for_pep ? 8 : 4;
2538 si->data = xmalloc (si->size);
2539 sec->reloc_count = 1;
2540 memset (si->data, 0, si->size);
2541 /* Point after jmp [__imp_...] instruction. */
2542 si->data[0] = 6;
2543 rel = xmalloc (sizeof (arelent));
2544 rpp = xmalloc (sizeof (arelent *) * 2);
2545 rpp[0] = rel;
2546 rpp[1] = 0;
2547 rel->address = 0;
2548 rel->addend = 0;
2549 if (create_for_pep)
2550 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_64);
2551 else
2552 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2553 rel->sym_ptr_ptr = secdata[TEXT].sympp;
2554 sec->orelocation = rpp;
2555 break;
2557 /* Fall through. */
2559 case IDATA4:
2560 /* An idata$4 or idata$5 is one word long, and has an
2561 rva to idata$6. */
2563 if (create_for_pep)
2565 si->data = xmalloc (8);
2566 si->size = 8;
2567 if (exp->noname)
2569 si->data[0] = exp->ordinal ;
2570 si->data[1] = exp->ordinal >> 8;
2571 si->data[2] = exp->ordinal >> 16;
2572 si->data[3] = exp->ordinal >> 24;
2573 si->data[4] = 0;
2574 si->data[5] = 0;
2575 si->data[6] = 0;
2576 si->data[7] = 0x80;
2578 else
2580 sec->reloc_count = 1;
2581 memset (si->data, 0, si->size);
2582 rel = xmalloc (sizeof (arelent));
2583 rpp = xmalloc (sizeof (arelent *) * 2);
2584 rpp[0] = rel;
2585 rpp[1] = 0;
2586 rel->address = 0;
2587 rel->addend = 0;
2588 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2589 rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2590 sec->orelocation = rpp;
2593 else
2595 si->data = xmalloc (4);
2596 si->size = 4;
2598 if (exp->noname)
2600 si->data[0] = exp->ordinal ;
2601 si->data[1] = exp->ordinal >> 8;
2602 si->data[2] = exp->ordinal >> 16;
2603 si->data[3] = 0x80;
2605 else
2607 sec->reloc_count = 1;
2608 memset (si->data, 0, si->size);
2609 rel = xmalloc (sizeof (arelent));
2610 rpp = xmalloc (sizeof (arelent *) * 2);
2611 rpp[0] = rel;
2612 rpp[1] = 0;
2613 rel->address = 0;
2614 rel->addend = 0;
2615 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2616 rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2617 sec->orelocation = rpp;
2620 break;
2622 case IDATA6:
2623 if (!exp->noname)
2625 int idx = exp->ordinal;
2627 if (exp->its_name)
2628 si->size = strlen (exp->its_name) + 3;
2629 else
2630 si->size = strlen (xlate (exp->import_name)) + 3;
2631 si->data = xmalloc (si->size);
2632 memset (si->data, 0, si->size);
2633 si->data[0] = idx & 0xff;
2634 si->data[1] = idx >> 8;
2635 if (exp->its_name)
2636 strcpy ((char *) si->data + 2, exp->its_name);
2637 else
2638 strcpy ((char *) si->data + 2, xlate (exp->import_name));
2640 break;
2641 case IDATA7:
2642 if (delay)
2643 break;
2644 si->size = 4;
2645 si->data = xmalloc (4);
2646 memset (si->data, 0, si->size);
2647 rel = xmalloc (sizeof (arelent));
2648 rpp = xmalloc (sizeof (arelent *) * 2);
2649 rpp[0] = rel;
2650 rel->address = 0;
2651 rel->addend = 0;
2652 rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2653 rel->sym_ptr_ptr = iname_lab_pp;
2654 sec->orelocation = rpp;
2655 sec->reloc_count = 1;
2656 break;
2661 bfd_vma vma = 0;
2662 /* Size up all the sections. */
2663 for (i = 0; i < NSECS; i++)
2665 sinfo *si = secdata + i;
2667 bfd_set_section_size (si->sec, si->size);
2668 bfd_set_section_vma (si->sec, vma);
2671 /* Write them out. */
2672 for (i = 0; i < NSECS; i++)
2674 sinfo *si = secdata + i;
2676 if (i == IDATA5 && no_idata5)
2677 continue;
2679 if (i == IDATA4 && no_idata4)
2680 continue;
2682 bfd_set_section_contents (abfd, si->sec,
2683 si->data, 0,
2684 si->size);
2687 bfd_set_symtab (abfd, ptrs, oidx);
2688 bfd_close (abfd);
2689 abfd = bfd_openr (outname, HOW_BFD_READ_TARGET);
2690 if (!abfd)
2691 /* xgettext:c-format */
2692 fatal (_("bfd_open failed reopen stub file: %s: %s"),
2693 outname, bfd_get_errmsg ());
2695 return abfd;
2698 static bfd *
2699 make_head (void)
2701 FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2702 bfd *abfd;
2704 if (f == NULL)
2706 fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2707 return NULL;
2710 temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2712 fprintf (f, "%s IMAGE_IMPORT_DESCRIPTOR\n", ASM_C);
2713 fprintf (f, "\t.section\t.idata$2\n");
2715 fprintf (f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2717 fprintf (f, "%s:\n", head_label);
2719 fprintf (f, "\t%shname%s\t%sPtr to image import by name list\n",
2720 ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2722 fprintf (f, "\t%sthis should be the timestamp, but NT sometimes\n", ASM_C);
2723 fprintf (f, "\t%sdoesn't load DLLs when this is set.\n", ASM_C);
2724 fprintf (f, "\t%s\t0\t%s loaded time\n", ASM_LONG, ASM_C);
2725 fprintf (f, "\t%s\t0\t%s Forwarder chain\n", ASM_LONG, ASM_C);
2726 fprintf (f, "\t%s__%s_iname%s\t%s imported dll's name\n",
2727 ASM_RVA_BEFORE,
2728 imp_name_lab,
2729 ASM_RVA_AFTER,
2730 ASM_C);
2731 fprintf (f, "\t%sfthunk%s\t%s pointer to firstthunk\n",
2732 ASM_RVA_BEFORE,
2733 ASM_RVA_AFTER, ASM_C);
2735 fprintf (f, "%sStuff for compatibility\n", ASM_C);
2737 if (!no_idata5)
2739 fprintf (f, "\t.section\t.idata$5\n");
2740 if (use_nul_prefixed_import_tables)
2742 if (create_for_pep)
2743 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2744 else
2745 fprintf (f,"\t%s\t0\n", ASM_LONG);
2747 fprintf (f, "fthunk:\n");
2750 if (!no_idata4)
2752 fprintf (f, "\t.section\t.idata$4\n");
2753 if (use_nul_prefixed_import_tables)
2755 if (create_for_pep)
2756 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2757 else
2758 fprintf (f,"\t%s\t0\n", ASM_LONG);
2760 fprintf (f, "hname:\n");
2763 fclose (f);
2765 assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2767 abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2768 if (abfd == NULL)
2769 /* xgettext:c-format */
2770 fatal (_("failed to open temporary head file: %s: %s"),
2771 TMP_HEAD_O, bfd_get_errmsg ());
2773 temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2774 return abfd;
2777 bfd *
2778 make_delay_head (void)
2780 FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2781 bfd *abfd;
2783 if (f == NULL)
2785 fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2786 return NULL;
2789 temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2791 /* Output the __tailMerge__xxx function */
2792 fprintf (f, "%s Import trampoline\n", ASM_C);
2793 fprintf (f, "\t.section\t.text\n");
2794 fprintf(f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2795 if (HOW_SEH)
2796 fprintf (f, "\t.seh_proc\t%s\n", head_label);
2797 fprintf (f, "%s:\n", head_label);
2798 fprintf (f, mtable[machine].trampoline, imp_name_lab);
2799 if (HOW_SEH)
2800 fprintf (f, "\t.seh_endproc\n");
2802 /* Output the delay import descriptor */
2803 fprintf (f, "\n%s DELAY_IMPORT_DESCRIPTOR\n", ASM_C);
2804 fprintf (f, ".section\t.text$2\n");
2805 fprintf (f,"%s __DELAY_IMPORT_DESCRIPTOR_%s\n", ASM_GLOBAL,imp_name_lab);
2806 fprintf (f, "__DELAY_IMPORT_DESCRIPTOR_%s:\n", imp_name_lab);
2807 fprintf (f, "\t%s 1\t%s grAttrs\n", ASM_LONG, ASM_C);
2808 fprintf (f, "\t%s__%s_iname%s\t%s rvaDLLName\n",
2809 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2810 fprintf (f, "\t%s__DLL_HANDLE_%s%s\t%s rvaHmod\n",
2811 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2812 fprintf (f, "\t%s__IAT_%s%s\t%s rvaIAT\n",
2813 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2814 fprintf (f, "\t%s__INT_%s%s\t%s rvaINT\n",
2815 ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2816 fprintf (f, "\t%s\t0\t%s rvaBoundIAT\n", ASM_LONG, ASM_C);
2817 fprintf (f, "\t%s\t0\t%s rvaUnloadIAT\n", ASM_LONG, ASM_C);
2818 fprintf (f, "\t%s\t0\t%s dwTimeStamp\n", ASM_LONG, ASM_C);
2820 /* Output the dll_handle */
2821 fprintf (f, "\n.section .data\n");
2822 fprintf (f, "__DLL_HANDLE_%s:\n", imp_name_lab);
2823 fprintf (f, "\t%s\t0\t%s Handle\n", ASM_LONG, ASM_C);
2824 if (create_for_pep)
2825 fprintf (f, "\t%s\t0\n", ASM_LONG);
2826 fprintf (f, "\n");
2828 fprintf (f, "%sStuff for compatibility\n", ASM_C);
2830 if (!no_idata5)
2832 fprintf (f, "\t.section\t.idata$5\n");
2833 /* NULL terminating list. */
2834 if (create_for_pep)
2835 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2836 else
2837 fprintf (f,"\t%s\t0\n", ASM_LONG);
2838 fprintf (f, "__IAT_%s:\n", imp_name_lab);
2841 if (!no_idata4)
2843 fprintf (f, "\t.section\t.idata$4\n");
2844 fprintf (f, "\t%s\t0\n", ASM_LONG);
2845 if (create_for_pep)
2846 fprintf (f, "\t%s\t0\n", ASM_LONG);
2847 fprintf (f, "\t.section\t.idata$4\n");
2848 fprintf (f, "__INT_%s:\n", imp_name_lab);
2851 fprintf (f, "\t.section\t.idata$2\n");
2853 fclose (f);
2855 assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2857 abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2858 if (abfd == NULL)
2859 /* xgettext:c-format */
2860 fatal (_("failed to open temporary head file: %s: %s"),
2861 TMP_HEAD_O, bfd_get_errmsg ());
2863 temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2864 return abfd;
2867 static bfd *
2868 make_tail (void)
2870 FILE *f = fopen (TMP_TAIL_S, FOPEN_WT);
2871 bfd *abfd;
2873 if (f == NULL)
2875 fatal (_("failed to open temporary tail file: %s"), TMP_TAIL_S);
2876 return NULL;
2879 temp_file_to_remove[TEMP_TAIL_FILE] = TMP_TAIL_S;
2881 if (!no_idata4)
2883 fprintf (f, "\t.section\t.idata$4\n");
2884 if (create_for_pep)
2885 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2886 else
2887 fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
2890 if (!no_idata5)
2892 fprintf (f, "\t.section\t.idata$5\n");
2893 if (create_for_pep)
2894 fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2895 else
2896 fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list. */
2899 fprintf (f, "\t.section\t.idata$7\n");
2900 fprintf (f, "\t%s\t__%s_iname\n", ASM_GLOBAL, imp_name_lab);
2901 fprintf (f, "__%s_iname:\t%s\t\"%s\"\n",
2902 imp_name_lab, ASM_TEXT, dll_name);
2904 fclose (f);
2906 assemble_file (TMP_TAIL_S, TMP_TAIL_O);
2908 abfd = bfd_openr (TMP_TAIL_O, HOW_BFD_READ_TARGET);
2909 if (abfd == NULL)
2910 /* xgettext:c-format */
2911 fatal (_("failed to open temporary tail file: %s: %s"),
2912 TMP_TAIL_O, bfd_get_errmsg ());
2914 temp_file_to_remove[TEMP_TAIL_O_FILE] = TMP_TAIL_O;
2915 return abfd;
2918 static void
2919 gen_lib_file (int delay)
2921 int i;
2922 export_type *exp;
2923 bfd *ar_head;
2924 bfd *ar_tail;
2925 bfd *outarch;
2926 bfd * head = 0;
2928 unlink (imp_name);
2930 outarch = bfd_openw (imp_name, HOW_BFD_WRITE_TARGET);
2932 if (!outarch)
2933 /* xgettext:c-format */
2934 fatal (_("Can't create .lib file: %s: %s"),
2935 imp_name, bfd_get_errmsg ());
2937 /* xgettext:c-format */
2938 inform (_("Creating library file: %s"), imp_name);
2940 xatexit (unlink_temp_files);
2942 bfd_set_format (outarch, bfd_archive);
2943 outarch->has_armap = 1;
2944 outarch->is_thin_archive = 0;
2946 if (deterministic)
2947 outarch->flags |= BFD_DETERMINISTIC_OUTPUT;
2949 /* Work out a reasonable size of things to put onto one line. */
2950 if (delay)
2952 ar_head = make_delay_head ();
2954 else
2956 ar_head = make_head ();
2958 ar_tail = make_tail();
2960 if (ar_head == NULL || ar_tail == NULL)
2961 return;
2963 for (i = 0; (exp = d_exports_lexically[i]); i++)
2965 bfd *n;
2966 /* Don't add PRIVATE entries to import lib. */
2967 if (exp->private)
2968 continue;
2969 n = make_one_lib_file (exp, i, delay);
2970 n->archive_next = head;
2971 head = n;
2972 if (ext_prefix_alias)
2974 export_type alias_exp;
2976 assert (i < PREFIX_ALIAS_BASE);
2977 alias_exp.name = make_imp_label (ext_prefix_alias, exp->name);
2978 alias_exp.internal_name = exp->internal_name;
2979 alias_exp.its_name = exp->its_name;
2980 alias_exp.import_name = exp->name;
2981 alias_exp.ordinal = exp->ordinal;
2982 alias_exp.constant = exp->constant;
2983 alias_exp.noname = exp->noname;
2984 alias_exp.private = exp->private;
2985 alias_exp.data = exp->data;
2986 alias_exp.forward = exp->forward;
2987 alias_exp.next = exp->next;
2988 n = make_one_lib_file (&alias_exp, i + PREFIX_ALIAS_BASE, delay);
2989 n->archive_next = head;
2990 head = n;
2994 /* Now stick them all into the archive. */
2995 ar_head->archive_next = head;
2996 ar_tail->archive_next = ar_head;
2997 head = ar_tail;
2999 if (! bfd_set_archive_head (outarch, head))
3000 bfd_fatal ("bfd_set_archive_head");
3002 if (! bfd_close (outarch))
3003 bfd_fatal (imp_name);
3005 while (head != NULL)
3007 bfd *n = head->archive_next;
3008 bfd_close (head);
3009 head = n;
3012 /* Delete all the temp files. */
3013 unlink_temp_files ();
3015 if (dontdeltemps < 2)
3017 char *name;
3019 name = xmalloc (strlen (TMP_STUB) + 10);
3020 for (i = 0; (exp = d_exports_lexically[i]); i++)
3022 /* Don't delete non-existent stubs for PRIVATE entries. */
3023 if (exp->private)
3024 continue;
3025 sprintf (name, "%s%05d.o", TMP_STUB, i);
3026 if (unlink (name) < 0)
3027 /* xgettext:c-format */
3028 non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3029 if (ext_prefix_alias)
3031 sprintf (name, "%s%05d.o", TMP_STUB, i + PREFIX_ALIAS_BASE);
3032 if (unlink (name) < 0)
3033 /* xgettext:c-format */
3034 non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3037 free (name);
3040 inform (_("Created lib file"));
3043 /* Append a copy of data (cast to char *) to list. */
3045 static void
3046 dll_name_list_append (dll_name_list_type * list, bfd_byte * data)
3048 dll_name_list_node_type * entry;
3050 /* Error checking. */
3051 if (! list || ! list->tail)
3052 return;
3054 /* Allocate new node. */
3055 entry = ((dll_name_list_node_type *)
3056 xmalloc (sizeof (dll_name_list_node_type)));
3058 /* Initialize its values. */
3059 entry->dllname = xstrdup ((char *) data);
3060 entry->next = NULL;
3062 /* Add to tail, and move tail. */
3063 list->tail->next = entry;
3064 list->tail = entry;
3067 /* Count the number of entries in list. */
3069 static int
3070 dll_name_list_count (dll_name_list_type * list)
3072 dll_name_list_node_type * p;
3073 int count = 0;
3075 /* Error checking. */
3076 if (! list || ! list->head)
3077 return 0;
3079 p = list->head;
3081 while (p && p->next)
3083 count++;
3084 p = p->next;
3086 return count;
3089 /* Print each entry in list to stdout. */
3091 static void
3092 dll_name_list_print (dll_name_list_type * list)
3094 dll_name_list_node_type * p;
3096 /* Error checking. */
3097 if (! list || ! list->head)
3098 return;
3100 p = list->head;
3102 while (p && p->next && p->next->dllname && *(p->next->dllname))
3104 printf ("%s\n", p->next->dllname);
3105 p = p->next;
3109 /* Free all entries in list, and list itself. */
3111 static void
3112 dll_name_list_free (dll_name_list_type * list)
3114 if (list)
3116 dll_name_list_free_contents (list->head);
3117 list->head = NULL;
3118 list->tail = NULL;
3119 free (list);
3123 /* Recursive function to free all nodes entry->next->next...
3124 as well as entry itself. */
3126 static void
3127 dll_name_list_free_contents (dll_name_list_node_type * entry)
3129 if (entry)
3131 if (entry->next)
3132 dll_name_list_free_contents (entry->next);
3133 free (entry->dllname);
3134 free (entry);
3138 /* Allocate and initialize a dll_name_list_type object,
3139 including its sentinel node. Caller is responsible
3140 for calling dll_name_list_free when finished with
3141 the list. */
3143 static dll_name_list_type *
3144 dll_name_list_create (void)
3146 /* Allocate list. */
3147 dll_name_list_type * list = xmalloc (sizeof (dll_name_list_type));
3149 /* Allocate and initialize sentinel node. */
3150 list->head = xmalloc (sizeof (dll_name_list_node_type));
3151 list->head->dllname = NULL;
3152 list->head->next = NULL;
3154 /* Bookkeeping for empty list. */
3155 list->tail = list->head;
3157 return list;
3160 /* Search the symbol table of the suppled BFD for a symbol whose name matches
3161 OBJ (where obj is cast to const char *). If found, set global variable
3162 identify_member_contains_symname_result TRUE. It is the caller's
3163 responsibility to set the result variable FALSE before iterating with
3164 this function. */
3166 static void
3167 identify_member_contains_symname (bfd * abfd,
3168 bfd * archive_bfd ATTRIBUTE_UNUSED,
3169 void * obj)
3171 long storage_needed;
3172 asymbol ** symbol_table;
3173 long number_of_symbols;
3174 long i;
3175 symname_search_data_type * search_data = (symname_search_data_type *) obj;
3177 /* If we already found the symbol in a different member,
3178 short circuit. */
3179 if (search_data->found)
3180 return;
3182 storage_needed = bfd_get_symtab_upper_bound (abfd);
3183 if (storage_needed <= 0)
3184 return;
3186 symbol_table = xmalloc (storage_needed);
3187 number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
3188 if (number_of_symbols < 0)
3190 free (symbol_table);
3191 return;
3194 for (i = 0; i < number_of_symbols; i++)
3196 if (strncmp (symbol_table[i]->name,
3197 search_data->symname,
3198 strlen (search_data->symname)) == 0)
3200 search_data->found = true;
3201 break;
3204 free (symbol_table);
3207 /* This is the main implementation for the --identify option.
3208 Given the name of an import library in identify_imp_name, first
3209 determine if the import library is a GNU binutils-style one (where
3210 the DLL name is stored in an .idata$7 section), or if it is a
3211 MS-style one (where the DLL name, along with much other data, is
3212 stored in the .idata$6 section). We determine the style of import
3213 library by searching for the DLL-structure symbol inserted by MS
3214 tools: __NULL_IMPORT_DESCRIPTOR.
3216 Once we know which section to search, evaluate each section for the
3217 appropriate properties that indicate it may contain the name of the
3218 associated DLL (this differs depending on the style). Add the contents
3219 of all sections which meet the criteria to a linked list of dll names.
3221 Finally, print them all to stdout. (If --identify-strict, an error is
3222 reported if more than one match was found). */
3224 static void
3225 identify_dll_for_implib (void)
3227 bfd * abfd = NULL;
3228 int count = 0;
3229 identify_data_type identify_data;
3230 symname_search_data_type search_data;
3232 /* Initialize identify_data. */
3233 identify_data.list = dll_name_list_create ();
3234 identify_data.ms_style_implib = false;
3236 /* Initialize search_data. */
3237 search_data.symname = "__NULL_IMPORT_DESCRIPTOR";
3238 search_data.found = false;
3240 if (bfd_init () != BFD_INIT_MAGIC)
3241 fatal (_("fatal error: libbfd ABI mismatch"));
3243 abfd = bfd_openr (identify_imp_name, 0);
3244 if (abfd == NULL)
3245 /* xgettext:c-format */
3246 fatal (_("Can't open .lib file: %s: %s"),
3247 identify_imp_name, bfd_get_errmsg ());
3249 if (! bfd_check_format (abfd, bfd_archive))
3251 if (! bfd_close (abfd))
3252 bfd_fatal (identify_imp_name);
3254 fatal (_("%s is not a library"), identify_imp_name);
3257 /* Detect if this a Microsoft import library. */
3258 identify_search_archive (abfd,
3259 identify_member_contains_symname,
3260 (void *)(& search_data));
3261 if (search_data.found)
3262 identify_data.ms_style_implib = true;
3264 /* Rewind the bfd. */
3265 if (! bfd_close (abfd))
3266 bfd_fatal (identify_imp_name);
3267 abfd = bfd_openr (identify_imp_name, 0);
3268 if (abfd == NULL)
3269 bfd_fatal (identify_imp_name);
3271 if (!bfd_check_format (abfd, bfd_archive))
3273 if (!bfd_close (abfd))
3274 bfd_fatal (identify_imp_name);
3276 fatal (_("%s is not a library"), identify_imp_name);
3279 /* Now search for the dll name. */
3280 identify_search_archive (abfd,
3281 identify_search_member,
3282 (void *)(& identify_data));
3284 if (! bfd_close (abfd))
3285 bfd_fatal (identify_imp_name);
3287 count = dll_name_list_count (identify_data.list);
3288 if (count > 0)
3290 if (identify_strict && count > 1)
3292 dll_name_list_free (identify_data.list);
3293 identify_data.list = NULL;
3294 fatal (_("Import library `%s' specifies two or more dlls"),
3295 identify_imp_name);
3297 dll_name_list_print (identify_data.list);
3298 dll_name_list_free (identify_data.list);
3299 identify_data.list = NULL;
3301 else
3303 dll_name_list_free (identify_data.list);
3304 identify_data.list = NULL;
3305 fatal (_("Unable to determine dll name for `%s' (not an import library?)"),
3306 identify_imp_name);
3310 /* Loop over all members of the archive, applying the supplied function to
3311 each member that is a bfd_object. The function will be called as if:
3312 func (member_bfd, abfd, user_storage) */
3314 static void
3315 identify_search_archive (bfd * abfd,
3316 void (* operation) (bfd *, bfd *, void *),
3317 void * user_storage)
3319 bfd * arfile = NULL;
3320 bfd * last_arfile = NULL;
3321 char ** matching;
3323 while (1)
3325 arfile = bfd_openr_next_archived_file (abfd, arfile);
3327 if (arfile == NULL)
3329 if (bfd_get_error () != bfd_error_no_more_archived_files)
3330 bfd_fatal (bfd_get_filename (abfd));
3331 break;
3334 if (bfd_check_format_matches (arfile, bfd_object, &matching))
3335 (*operation) (arfile, abfd, user_storage);
3336 else
3338 bfd_nonfatal (bfd_get_filename (arfile));
3339 free (matching);
3342 if (last_arfile != NULL)
3344 bfd_close (last_arfile);
3345 /* PR 17512: file: 8b2168d4. */
3346 if (last_arfile == arfile)
3348 last_arfile = NULL;
3349 break;
3353 last_arfile = arfile;
3356 if (last_arfile != NULL)
3358 bfd_close (last_arfile);
3362 /* Call the identify_search_section() function for each section of this
3363 archive member. */
3365 static void
3366 identify_search_member (bfd *abfd,
3367 bfd *archive_bfd ATTRIBUTE_UNUSED,
3368 void *obj)
3370 bfd_map_over_sections (abfd, identify_search_section, obj);
3373 /* This predicate returns true if section->name matches the desired value.
3374 By default, this is .idata$7 (.idata$6 if the import library is
3375 ms-style). */
3377 static bool
3378 identify_process_section_p (asection * section, bool ms_style_implib)
3380 static const char * SECTION_NAME = ".idata$7";
3381 static const char * MS_SECTION_NAME = ".idata$6";
3383 const char * section_name =
3384 (ms_style_implib ? MS_SECTION_NAME : SECTION_NAME);
3386 if (strcmp (section_name, section->name) == 0)
3387 return true;
3388 return false;
3391 /* If *section has contents and its name is .idata$7 (.idata$6 if
3392 import lib ms-generated) -- and it satisfies several other constraints
3393 -- then add the contents of the section to obj->list. */
3395 static void
3396 identify_search_section (bfd * abfd, asection * section, void * obj)
3398 bfd_byte *data = 0;
3399 bfd_size_type datasize;
3400 identify_data_type * identify_data = (identify_data_type *)obj;
3401 bool ms_style = identify_data->ms_style_implib;
3403 if ((section->flags & SEC_HAS_CONTENTS) == 0)
3404 return;
3406 if (! identify_process_section_p (section, ms_style))
3407 return;
3409 /* Binutils import libs seem distinguish the .idata$7 section that contains
3410 the DLL name from other .idata$7 sections by the absence of the
3411 SEC_RELOC flag. */
3412 if (!ms_style && ((section->flags & SEC_RELOC) == SEC_RELOC))
3413 return;
3415 /* MS import libs seem to distinguish the .idata$6 section
3416 that contains the DLL name from other .idata$6 sections
3417 by the presence of the SEC_DATA flag. */
3418 if (ms_style && ((section->flags & SEC_DATA) == 0))
3419 return;
3421 if ((datasize = bfd_section_size (section)) == 0)
3422 return;
3424 data = (bfd_byte *) xmalloc (datasize + 1);
3425 data[0] = '\0';
3427 bfd_get_section_contents (abfd, section, data, 0, datasize);
3428 data[datasize] = '\0';
3430 /* Use a heuristic to determine if data is a dll name.
3431 Possible to defeat this if (a) the library has MANY
3432 (more than 0x302f) imports, (b) it is an ms-style
3433 import library, but (c) it is buggy, in that the SEC_DATA
3434 flag is set on the "wrong" sections. This heuristic might
3435 also fail to record a valid dll name if the dllname uses
3436 a multibyte or unicode character set (is that valid?).
3438 This heuristic is based on the fact that symbols names in
3439 the chosen section -- as opposed to the dll name -- begin
3440 at offset 2 in the data. The first two bytes are a 16bit
3441 little-endian count, and start at 0x0000. However, the dll
3442 name begins at offset 0 in the data. We assume that the
3443 dll name does not contain unprintable characters. */
3444 if (data[0] != '\0' && ISPRINT (data[0])
3445 && ((datasize < 2) || ISPRINT (data[1])))
3446 dll_name_list_append (identify_data->list, data);
3448 free (data);
3451 /* Run through the information gathered from the .o files and the
3452 .def file and work out the best stuff. */
3454 static int
3455 pfunc (const void *a, const void *b)
3457 export_type *ap = *(export_type **) a;
3458 export_type *bp = *(export_type **) b;
3460 if (ap->ordinal == bp->ordinal)
3461 return 0;
3463 /* Unset ordinals go to the bottom. */
3464 if (ap->ordinal == -1)
3465 return 1;
3466 if (bp->ordinal == -1)
3467 return -1;
3468 return (ap->ordinal - bp->ordinal);
3471 static int
3472 nfunc (const void *a, const void *b)
3474 export_type *ap = *(export_type **) a;
3475 export_type *bp = *(export_type **) b;
3476 const char *an = ap->name;
3477 const char *bn = bp->name;
3478 if (ap->its_name)
3479 an = ap->its_name;
3480 if (bp->its_name)
3481 an = bp->its_name;
3482 if (killat)
3484 an = (an[0] == '@') ? an + 1 : an;
3485 bn = (bn[0] == '@') ? bn + 1 : bn;
3488 return (strcmp (an, bn));
3491 static void
3492 remove_null_names (export_type **ptr)
3494 int src;
3495 int dst;
3497 for (dst = src = 0; src < d_nfuncs; src++)
3499 if (ptr[src])
3501 ptr[dst] = ptr[src];
3502 dst++;
3505 d_nfuncs = dst;
3508 static void
3509 process_duplicates (export_type **d_export_vec)
3511 int more = 1;
3512 int i;
3514 while (more)
3516 more = 0;
3517 /* Remove duplicates. */
3518 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), nfunc);
3520 for (i = 0; i < d_nfuncs - 1; i++)
3522 if (strcmp (d_export_vec[i]->name,
3523 d_export_vec[i + 1]->name) == 0)
3525 export_type *a = d_export_vec[i];
3526 export_type *b = d_export_vec[i + 1];
3528 more = 1;
3530 /* xgettext:c-format */
3531 inform (_("Warning, ignoring duplicate EXPORT %s %d,%d"),
3532 a->name, a->ordinal, b->ordinal);
3534 if (a->ordinal != -1
3535 && b->ordinal != -1)
3536 /* xgettext:c-format */
3537 fatal (_("Error, duplicate EXPORT with ordinals: %s"),
3538 a->name);
3540 /* Merge attributes. */
3541 b->ordinal = a->ordinal > 0 ? a->ordinal : b->ordinal;
3542 b->constant |= a->constant;
3543 b->noname |= a->noname;
3544 b->data |= a->data;
3545 d_export_vec[i] = 0;
3548 remove_null_names (d_export_vec);
3552 /* Count the names. */
3553 for (i = 0; i < d_nfuncs; i++)
3554 if (!d_export_vec[i]->noname)
3555 d_named_nfuncs++;
3558 static void
3559 fill_ordinals (export_type **d_export_vec)
3561 int lowest = -1;
3562 int i;
3563 char *ptr;
3564 int size = 65536;
3566 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3568 /* Fill in the unset ordinals with ones from our range. */
3569 ptr = (char *) xmalloc (size);
3571 memset (ptr, 0, size);
3573 /* Mark in our large vector all the numbers that are taken. */
3574 for (i = 0; i < d_nfuncs; i++)
3576 if (d_export_vec[i]->ordinal != -1)
3578 ptr[d_export_vec[i]->ordinal] = 1;
3580 if (lowest == -1 || d_export_vec[i]->ordinal < lowest)
3581 lowest = d_export_vec[i]->ordinal;
3585 /* Start at 1 for compatibility with MS toolchain. */
3586 if (lowest == -1)
3587 lowest = 1;
3589 /* Now fill in ordinals where the user wants us to choose. */
3590 for (i = 0; i < d_nfuncs; i++)
3592 if (d_export_vec[i]->ordinal == -1)
3594 int j;
3596 /* First try within or after any user supplied range. */
3597 for (j = lowest; j < size; j++)
3598 if (ptr[j] == 0)
3600 ptr[j] = 1;
3601 d_export_vec[i]->ordinal = j;
3602 goto done;
3605 /* Then try before the range. */
3606 for (j = lowest; j >0; j--)
3607 if (ptr[j] == 0)
3609 ptr[j] = 1;
3610 d_export_vec[i]->ordinal = j;
3611 goto done;
3613 done:;
3617 free (ptr);
3619 /* And resort. */
3620 qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3622 /* Work out the lowest and highest ordinal numbers. */
3623 if (d_nfuncs)
3625 if (d_export_vec[0])
3626 d_low_ord = d_export_vec[0]->ordinal;
3627 if (d_export_vec[d_nfuncs-1])
3628 d_high_ord = d_export_vec[d_nfuncs-1]->ordinal;
3632 static void
3633 mangle_defs (void)
3635 /* First work out the minimum ordinal chosen. */
3636 export_type *exp;
3637 export_type **d_export_vec = xmalloc (sizeof (export_type *) * d_nfuncs);
3638 int i;
3640 inform (_("Processing definitions"));
3642 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3643 d_export_vec[i] = exp;
3645 process_duplicates (d_export_vec);
3646 fill_ordinals (d_export_vec);
3648 /* Put back the list in the new order. */
3649 d_exports = 0;
3650 for (i = d_nfuncs - 1; i >= 0; i--)
3652 d_export_vec[i]->next = d_exports;
3653 d_exports = d_export_vec[i];
3656 /* Build list in alpha order. */
3657 d_exports_lexically = (export_type **)
3658 xmalloc (sizeof (export_type *) * (d_nfuncs + 1));
3660 for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3661 d_exports_lexically[i] = exp;
3663 d_exports_lexically[i] = 0;
3665 qsort (d_exports_lexically, i, sizeof (export_type *), nfunc);
3667 inform (_("Processed definitions"));
3670 static void
3671 usage (FILE *file, int status)
3673 /* xgetext:c-format */
3674 fprintf (file, _("Usage %s <option(s)> <object-file(s)>\n"), program_name);
3675 /* xgetext:c-format */
3676 fprintf (file, _(" -m --machine <machine> Create as DLL for <machine>. [default: %s]\n"), mname);
3677 fprintf (file, _(" possible <machine>: arm[_interwork], i386, mcore[-elf]{-le|-be}, thumb\n"));
3678 fprintf (file, _(" -e --output-exp <outname> Generate an export file.\n"));
3679 fprintf (file, _(" -l --output-lib <outname> Generate an interface library.\n"));
3680 fprintf (file, _(" -y --output-delaylib <outname> Create a delay-import library.\n"));
3681 fprintf (file, _(" --deterministic-libraries\n"));
3682 if (DEFAULT_AR_DETERMINISTIC)
3683 fprintf (file, _(" Use zero for timestamps and uids/gids in output libraries (default)\n"));
3684 else
3685 fprintf (file, _(" Use zero for timestamps and uids/gids in output libraries\n"));
3686 fprintf (file, _(" --non-deterministic-libraries\n"));
3687 if (DEFAULT_AR_DETERMINISTIC)
3688 fprintf (file, _(" Use actual timestamps and uids/gids in output libraries\n"));
3689 else
3690 fprintf (file, _(" Use actual timestamps and uids/gids in output libraries (default)\n"));
3691 fprintf (file, _(" -a --add-indirect Add dll indirects to export file.\n"));
3692 fprintf (file, _(" -D --dllname <name> Name of input dll to put into interface lib.\n"));
3693 fprintf (file, _(" -d --input-def <deffile> Name of .def file to be read in.\n"));
3694 fprintf (file, _(" -z --output-def <deffile> Name of .def file to be created.\n"));
3695 fprintf (file, _(" --export-all-symbols Export all symbols to .def\n"));
3696 fprintf (file, _(" --no-export-all-symbols Only export listed symbols\n"));
3697 fprintf (file, _(" --exclude-symbols <list> Don't export <list>\n"));
3698 fprintf (file, _(" --no-default-excludes Clear default exclude symbols\n"));
3699 fprintf (file, _(" -b --base-file <basefile> Read linker generated base file.\n"));
3700 fprintf (file, _(" -x --no-idata4 Don't generate idata$4 section.\n"));
3701 fprintf (file, _(" -c --no-idata5 Don't generate idata$5 section.\n"));
3702 fprintf (file, _(" --use-nul-prefixed-import-tables Use zero prefixed idata$4 and idata$5.\n"));
3703 fprintf (file, _(" -U --add-underscore Add underscores to all symbols in interface library.\n"));
3704 fprintf (file, _(" --add-stdcall-underscore Add underscores to stdcall symbols in interface library.\n"));
3705 fprintf (file, _(" --no-leading-underscore All symbols shouldn't be prefixed by an underscore.\n"));
3706 fprintf (file, _(" --leading-underscore All symbols should be prefixed by an underscore.\n"));
3707 fprintf (file, _(" -k --kill-at Kill @<n> from exported names.\n"));
3708 fprintf (file, _(" -A --add-stdcall-alias Add aliases without @<n>.\n"));
3709 fprintf (file, _(" -p --ext-prefix-alias <prefix> Add aliases with <prefix>.\n"));
3710 fprintf (file, _(" -S --as <name> Use <name> for assembler.\n"));
3711 fprintf (file, _(" -f --as-flags <flags> Pass <flags> to the assembler.\n"));
3712 fprintf (file, _(" -C --compat-implib Create backward compatible import library.\n"));
3713 fprintf (file, _(" -n --no-delete Keep temp files (repeat for extra preservation).\n"));
3714 fprintf (file, _(" -t --temp-prefix <prefix> Use <prefix> to construct temp file names.\n"));
3715 fprintf (file, _(" -I --identify <implib> Report the name of the DLL associated with <implib>.\n"));
3716 fprintf (file, _(" --identify-strict Causes --identify to report error when multiple DLLs.\n"));
3717 fprintf (file, _(" -v --verbose Be verbose.\n"));
3718 fprintf (file, _(" -V --version Display the program version.\n"));
3719 fprintf (file, _(" -h --help Display this information.\n"));
3720 fprintf (file, _(" @<file> Read options from <file>.\n"));
3721 #ifdef DLLTOOL_MCORE_ELF
3722 fprintf (file, _(" -M --mcore-elf <outname> Process mcore-elf object files into <outname>.\n"));
3723 fprintf (file, _(" -L --linker <name> Use <name> as the linker.\n"));
3724 fprintf (file, _(" -F --linker-flags <flags> Pass <flags> to the linker.\n"));
3725 #endif
3726 if (REPORT_BUGS_TO[0] && status == 0)
3727 fprintf (file, _("Report bugs to %s\n"), REPORT_BUGS_TO);
3728 exit (status);
3731 /* 150 isn't special; it's just an arbitrary non-ASCII char value. */
3732 enum command_line_switch
3734 OPTION_EXPORT_ALL_SYMS = 150,
3735 OPTION_NO_EXPORT_ALL_SYMS,
3736 OPTION_EXCLUDE_SYMS,
3737 OPTION_NO_DEFAULT_EXCLUDES,
3738 OPTION_ADD_STDCALL_UNDERSCORE,
3739 OPTION_USE_NUL_PREFIXED_IMPORT_TABLES,
3740 OPTION_IDENTIFY_STRICT,
3741 OPTION_NO_LEADING_UNDERSCORE,
3742 OPTION_LEADING_UNDERSCORE,
3743 OPTION_DETERMINISTIC_LIBRARIES,
3744 OPTION_NON_DETERMINISTIC_LIBRARIES
3747 static const struct option long_options[] =
3749 {"add-indirect", no_argument, NULL, 'a'},
3750 {"add-stdcall-alias", no_argument, NULL, 'A'},
3751 {"add-stdcall-underscore", no_argument, NULL, OPTION_ADD_STDCALL_UNDERSCORE},
3752 {"add-underscore", no_argument, NULL, 'U'},
3753 {"as", required_argument, NULL, 'S'},
3754 {"as-flags", required_argument, NULL, 'f'},
3755 {"base-file", required_argument, NULL, 'b'},
3756 {"compat-implib", no_argument, NULL, 'C'},
3757 {"def", required_argument, NULL, 'd'}, /* For compatibility with older versions. */
3758 {"deterministic-libraries", no_argument, NULL, OPTION_DETERMINISTIC_LIBRARIES},
3759 {"dllname", required_argument, NULL, 'D'},
3760 {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMS},
3761 {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL_SYMS},
3762 {"ext-prefix-alias", required_argument, NULL, 'p'},
3763 {"help", no_argument, NULL, 'h'},
3764 {"identify", required_argument, NULL, 'I'},
3765 {"identify-strict", no_argument, NULL, OPTION_IDENTIFY_STRICT},
3766 {"input-def", required_argument, NULL, 'd'},
3767 {"kill-at", no_argument, NULL, 'k'},
3768 {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
3769 {"machine", required_argument, NULL, 'm'},
3770 {"mcore-elf", required_argument, NULL, 'M'},
3771 {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
3772 {"no-delete", no_argument, NULL, 'n'},
3773 {"no-export-all-symbols", no_argument, NULL, OPTION_NO_EXPORT_ALL_SYMS},
3774 {"no-idata4", no_argument, NULL, 'x'},
3775 {"no-idata5", no_argument, NULL, 'c'},
3776 {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
3777 {"non-deterministic-libraries", no_argument, NULL, OPTION_NON_DETERMINISTIC_LIBRARIES},
3778 {"output-def", required_argument, NULL, 'z'},
3779 {"output-delaylib", required_argument, NULL, 'y'},
3780 {"output-exp", required_argument, NULL, 'e'},
3781 {"output-lib", required_argument, NULL, 'l'},
3782 {"temp-prefix", required_argument, NULL, 't'},
3783 {"use-nul-prefixed-import-tables", no_argument, NULL, OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
3784 {"verbose", no_argument, NULL, 'v'},
3785 {"version", no_argument, NULL, 'V'},
3786 {NULL,0,NULL,0}
3789 int main (int, char **);
3792 main (int ac, char **av)
3794 int c;
3795 int i;
3796 char *firstarg = 0;
3797 program_name = av[0];
3798 oav = av;
3800 #ifdef HAVE_LC_MESSAGES
3801 setlocale (LC_MESSAGES, "");
3802 #endif
3803 setlocale (LC_CTYPE, "");
3804 bindtextdomain (PACKAGE, LOCALEDIR);
3805 textdomain (PACKAGE);
3807 bfd_set_error_program_name (program_name);
3808 expandargv (&ac, &av);
3810 while ((c = getopt_long (ac, av,
3811 #ifdef DLLTOOL_MCORE_ELF
3812 "m:e:l:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHhM:L:F:",
3813 #else
3814 "m:e:l:y:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHh",
3815 #endif
3816 long_options, 0))
3817 != EOF)
3819 switch (c)
3821 case OPTION_EXPORT_ALL_SYMS:
3822 export_all_symbols = true;
3823 break;
3824 case OPTION_NO_EXPORT_ALL_SYMS:
3825 export_all_symbols = false;
3826 break;
3827 case OPTION_EXCLUDE_SYMS:
3828 add_excludes (optarg);
3829 break;
3830 case OPTION_NO_DEFAULT_EXCLUDES:
3831 do_default_excludes = false;
3832 break;
3833 case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
3834 use_nul_prefixed_import_tables = true;
3835 break;
3836 case OPTION_ADD_STDCALL_UNDERSCORE:
3837 add_stdcall_underscore = 1;
3838 break;
3839 case OPTION_NO_LEADING_UNDERSCORE:
3840 leading_underscore = 0;
3841 break;
3842 case OPTION_LEADING_UNDERSCORE:
3843 leading_underscore = 1;
3844 break;
3845 case OPTION_IDENTIFY_STRICT:
3846 identify_strict = 1;
3847 break;
3848 case 'x':
3849 no_idata4 = 1;
3850 break;
3851 case 'c':
3852 no_idata5 = 1;
3853 break;
3854 case 'S':
3855 as_name = optarg;
3856 break;
3857 case 't':
3858 tmp_prefix = optarg;
3859 break;
3860 case 'f':
3861 as_flags = optarg;
3862 break;
3864 /* Ignored for compatibility. */
3865 case 'u':
3866 break;
3867 case 'a':
3868 add_indirect = 1;
3869 break;
3870 case 'z':
3871 output_def = fopen (optarg, FOPEN_WT);
3872 if (!output_def)
3873 /* xgettext:c-format */
3874 fatal (_("Unable to open def-file: %s"), optarg);
3875 break;
3876 case 'D':
3877 dll_name = (char*) lbasename (optarg);
3878 if (dll_name != optarg)
3879 non_fatal (_("Path components stripped from dllname, '%s'."),
3880 optarg);
3881 break;
3882 case 'l':
3883 imp_name = optarg;
3884 break;
3885 case 'e':
3886 exp_name = optarg;
3887 break;
3888 case 'H':
3889 case 'h':
3890 usage (stdout, 0);
3891 break;
3892 case 'm':
3893 mname = optarg;
3894 break;
3895 case 'I':
3896 identify_imp_name = optarg;
3897 break;
3898 case 'v':
3899 verbose = 1;
3900 break;
3901 case 'V':
3902 print_version (program_name);
3903 break;
3904 case 'U':
3905 add_underscore = 1;
3906 break;
3907 case 'k':
3908 killat = 1;
3909 break;
3910 case 'A':
3911 add_stdcall_alias = 1;
3912 break;
3913 case 'p':
3914 ext_prefix_alias = optarg;
3915 break;
3916 case 'd':
3917 def_file = optarg;
3918 break;
3919 case 'n':
3920 dontdeltemps++;
3921 break;
3922 case 'b':
3923 base_file = fopen (optarg, FOPEN_RB);
3925 if (!base_file)
3926 /* xgettext:c-format */
3927 fatal (_("Unable to open base-file: %s"), optarg);
3929 break;
3930 #ifdef DLLTOOL_MCORE_ELF
3931 case 'M':
3932 mcore_elf_out_file = optarg;
3933 break;
3934 case 'L':
3935 mcore_elf_linker = optarg;
3936 break;
3937 case 'F':
3938 mcore_elf_linker_flags = optarg;
3939 break;
3940 #endif
3941 case 'C':
3942 create_compat_implib = 1;
3943 break;
3944 case 'y':
3945 delayimp_name = optarg;
3946 break;
3947 case OPTION_DETERMINISTIC_LIBRARIES:
3948 deterministic = true;
3949 break;
3950 case OPTION_NON_DETERMINISTIC_LIBRARIES:
3951 deterministic = false;
3952 break;
3953 default:
3954 usage (stderr, 1);
3955 break;
3959 for (i = 0; mtable[i].type; i++)
3960 if (strcmp (mtable[i].type, mname) == 0)
3961 break;
3963 if (!mtable[i].type)
3964 /* xgettext:c-format */
3965 fatal (_("Machine '%s' not supported"), mname);
3967 machine = i;
3969 /* Check if we generated PE+. */
3970 create_for_pep = strcmp (mname, "i386:x86-64") == 0;
3973 /* Check the default underscore */
3974 int u = leading_underscore; /* Underscoring mode. -1 for use default. */
3975 if (u == -1)
3976 bfd_get_target_info (mtable[machine].how_bfd_target, NULL,
3977 NULL, &u, NULL);
3978 if (u != -1)
3979 leading_underscore = u != 0;
3982 if (!dll_name && exp_name)
3984 /* If we are inferring dll_name from exp_name,
3985 strip off any path components, without emitting
3986 a warning. */
3987 const char* exp_basename = lbasename (exp_name);
3988 const int len = strlen (exp_basename) + 5;
3989 dll_name = xmalloc (len);
3990 strcpy (dll_name, exp_basename);
3991 strcat (dll_name, ".dll");
3992 dll_name_set_by_exp_name = 1;
3995 if (as_name == NULL)
3996 as_name = deduce_name ("as");
3998 /* Don't use the default exclude list if we're reading only the
3999 symbols in the .drectve section. The default excludes are meant
4000 to avoid exporting DLL entry point and Cygwin32 impure_ptr. */
4001 if (! export_all_symbols)
4002 do_default_excludes = false;
4004 if (do_default_excludes)
4005 set_default_excludes ();
4007 if (def_file)
4008 process_def_file (def_file);
4010 while (optind < ac)
4012 if (!firstarg)
4013 firstarg = av[optind];
4014 scan_obj_file (av[optind]);
4015 optind++;
4018 if (tmp_prefix == NULL)
4020 /* If possible use a deterministic prefix. */
4021 if (imp_name || delayimp_name)
4023 const char *input = imp_name ? imp_name : delayimp_name;
4024 tmp_prefix = xmalloc (strlen (input) + 2);
4025 sprintf (tmp_prefix, "%s_", input);
4026 for (i = 0; tmp_prefix[i]; i++)
4027 if (!ISALNUM (tmp_prefix[i]))
4028 tmp_prefix[i] = '_';
4030 else
4032 tmp_prefix = prefix_encode ("d", getpid ());
4036 mangle_defs ();
4038 if (exp_name)
4039 gen_exp_file ();
4041 if (imp_name)
4043 /* Make imp_name safe for use as a label. */
4044 char *p;
4046 imp_name_lab = xstrdup (imp_name);
4047 for (p = imp_name_lab; *p; p++)
4049 if (!ISALNUM (*p))
4050 *p = '_';
4052 head_label = make_label("_head_", imp_name_lab);
4053 gen_lib_file (0);
4056 if (delayimp_name)
4058 /* Make delayimp_name safe for use as a label. */
4059 char *p;
4061 if (mtable[machine].how_dljtab == 0)
4063 inform (_("Warning, machine type (%d) not supported for "
4064 "delayimport."), machine);
4066 else
4068 killat = 1;
4069 imp_name = delayimp_name;
4070 imp_name_lab = xstrdup (imp_name);
4071 for (p = imp_name_lab; *p; p++)
4073 if (!ISALNUM (*p))
4074 *p = '_';
4076 head_label = make_label("__tailMerge_", imp_name_lab);
4077 gen_lib_file (1);
4081 if (output_def)
4082 gen_def_file ();
4084 if (identify_imp_name)
4086 identify_dll_for_implib ();
4089 #ifdef DLLTOOL_MCORE_ELF
4090 if (mcore_elf_out_file)
4091 mcore_elf_gen_out_file ();
4092 #endif
4094 return 0;
4097 /* Look for the program formed by concatenating PROG_NAME and the
4098 string running from PREFIX to END_PREFIX. If the concatenated
4099 string contains a '/', try appending EXECUTABLE_SUFFIX if it is
4100 appropriate. */
4102 static char *
4103 look_for_prog (const char *prog_name, const char *prefix, int end_prefix)
4105 struct stat s;
4106 char *cmd;
4108 cmd = xmalloc (strlen (prefix)
4109 + strlen (prog_name)
4110 #ifdef HAVE_EXECUTABLE_SUFFIX
4111 + strlen (EXECUTABLE_SUFFIX)
4112 #endif
4113 + 10);
4114 strcpy (cmd, prefix);
4116 sprintf (cmd + end_prefix, "%s", prog_name);
4118 if (strchr (cmd, '/') != NULL)
4120 int found;
4122 found = (stat (cmd, &s) == 0
4123 #ifdef HAVE_EXECUTABLE_SUFFIX
4124 || stat (strcat (cmd, EXECUTABLE_SUFFIX), &s) == 0
4125 #endif
4128 if (! found)
4130 /* xgettext:c-format */
4131 inform (_("Tried file: %s"), cmd);
4132 free (cmd);
4133 return NULL;
4137 /* xgettext:c-format */
4138 inform (_("Using file: %s"), cmd);
4140 return cmd;
4143 /* Deduce the name of the program we are want to invoke.
4144 PROG_NAME is the basic name of the program we want to run,
4145 eg "as" or "ld". The catch is that we might want actually
4146 run "i386-pe-as".
4148 If argv[0] contains the full path, then try to find the program
4149 in the same place, with and then without a target-like prefix.
4151 Given, argv[0] = /usr/local/bin/i586-cygwin32-dlltool,
4152 deduce_name("as") uses the following search order:
4154 /usr/local/bin/i586-cygwin32-as
4155 /usr/local/bin/as
4158 If there's an EXECUTABLE_SUFFIX, it'll use that as well; for each
4159 name, it'll try without and then with EXECUTABLE_SUFFIX.
4161 Given, argv[0] = i586-cygwin32-dlltool, it will not even try "as"
4162 as the fallback, but rather return i586-cygwin32-as.
4164 Oh, and given, argv[0] = dlltool, it'll return "as".
4166 Returns a dynamically allocated string. */
4168 static char *
4169 deduce_name (const char *prog_name)
4171 char *cmd;
4172 char *dash, *slash, *cp;
4174 dash = NULL;
4175 slash = NULL;
4176 for (cp = program_name; *cp != '\0'; ++cp)
4178 if (*cp == '-')
4179 dash = cp;
4180 if (
4181 #if defined(__DJGPP__) || defined (__CYGWIN__) || defined(__WIN32__)
4182 *cp == ':' || *cp == '\\' ||
4183 #endif
4184 *cp == '/')
4186 slash = cp;
4187 dash = NULL;
4191 cmd = NULL;
4193 if (dash != NULL)
4195 /* First, try looking for a prefixed PROG_NAME in the
4196 PROGRAM_NAME directory, with the same prefix as PROGRAM_NAME. */
4197 cmd = look_for_prog (prog_name, program_name, dash - program_name + 1);
4200 if (slash != NULL && cmd == NULL)
4202 /* Next, try looking for a PROG_NAME in the same directory as
4203 that of this program. */
4204 cmd = look_for_prog (prog_name, program_name, slash - program_name + 1);
4207 if (cmd == NULL)
4209 /* Just return PROG_NAME as is. */
4210 cmd = xstrdup (prog_name);
4213 return cmd;
4216 #ifdef DLLTOOL_MCORE_ELF
4217 typedef struct fname_cache
4219 const char * filename;
4220 struct fname_cache * next;
4222 fname_cache;
4224 static fname_cache fnames;
4226 static void
4227 mcore_elf_cache_filename (const char * filename)
4229 fname_cache * ptr;
4231 ptr = & fnames;
4233 while (ptr->next != NULL)
4234 ptr = ptr->next;
4236 ptr->filename = filename;
4237 ptr->next = (fname_cache *) malloc (sizeof (fname_cache));
4238 if (ptr->next != NULL)
4239 ptr->next->next = NULL;
4242 #define MCORE_ELF_TMP_OBJ "mcoreelf.o"
4243 #define MCORE_ELF_TMP_EXP "mcoreelf.exp"
4244 #define MCORE_ELF_TMP_LIB "mcoreelf.lib"
4246 static void
4247 mcore_elf_gen_out_file (void)
4249 fname_cache * ptr;
4250 dyn_string_t ds;
4252 /* Step one. Run 'ld -r' on the input object files in order to resolve
4253 any internal references and to generate a single .exports section. */
4254 ptr = & fnames;
4256 ds = dyn_string_new (100);
4257 dyn_string_append_cstr (ds, "-r ");
4259 if (mcore_elf_linker_flags != NULL)
4260 dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4262 while (ptr->next != NULL)
4264 dyn_string_append_cstr (ds, ptr->filename);
4265 dyn_string_append_cstr (ds, " ");
4267 ptr = ptr->next;
4270 dyn_string_append_cstr (ds, "-o ");
4271 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4273 if (mcore_elf_linker == NULL)
4274 mcore_elf_linker = deduce_name ("ld");
4276 run (mcore_elf_linker, ds->s);
4278 dyn_string_delete (ds);
4280 /* Step two. Create a .exp file and a .lib file from the temporary file.
4281 Do this by recursively invoking dlltool... */
4282 ds = dyn_string_new (100);
4284 dyn_string_append_cstr (ds, "-S ");
4285 dyn_string_append_cstr (ds, as_name);
4287 dyn_string_append_cstr (ds, " -e ");
4288 dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4289 dyn_string_append_cstr (ds, " -l ");
4290 dyn_string_append_cstr (ds, MCORE_ELF_TMP_LIB);
4291 dyn_string_append_cstr (ds, " " );
4292 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4294 if (verbose)
4295 dyn_string_append_cstr (ds, " -v");
4297 if (dontdeltemps)
4299 dyn_string_append_cstr (ds, " -n");
4301 if (dontdeltemps > 1)
4302 dyn_string_append_cstr (ds, " -n");
4305 /* XXX - FIME: ought to check/copy other command line options as well. */
4306 run (program_name, ds->s);
4308 dyn_string_delete (ds);
4310 /* Step four. Feed the .exp and object files to ld -shared to create the dll. */
4311 ds = dyn_string_new (100);
4313 dyn_string_append_cstr (ds, "-shared ");
4315 if (mcore_elf_linker_flags)
4316 dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4318 dyn_string_append_cstr (ds, " ");
4319 dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4320 dyn_string_append_cstr (ds, " ");
4321 dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4322 dyn_string_append_cstr (ds, " -o ");
4323 dyn_string_append_cstr (ds, mcore_elf_out_file);
4325 run (mcore_elf_linker, ds->s);
4327 dyn_string_delete (ds);
4329 if (dontdeltemps == 0)
4330 unlink (MCORE_ELF_TMP_EXP);
4332 if (dontdeltemps < 2)
4333 unlink (MCORE_ELF_TMP_OBJ);
4335 #endif /* DLLTOOL_MCORE_ELF */