xref: /netbsd-src/external/gpl3/binutils.old/dist/binutils/dlltool.c (revision ccd9df534e375a4366c5b55f23782053c7a98d82)
1 /* dlltool.c -- tool to generate stuff for PE style DLLs
2    Copyright (C) 1995-2022 Free Software Foundation, Inc.
3 
4    This file is part of GNU Binutils.
5 
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.
10 
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.
15 
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.  */
20 
21 
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)
25 
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.
30 
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.
34 
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.
39 
40    A DEF file contains any number of the following commands:
41 
42 
43    NAME <name> [ , <base> ]
44    The result is going to be <name>.EXE
45 
46    LIBRARY <name> [ , <base> ]
47    The result is going to be <name>.DLL
48 
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>.
56 
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.
63 
64    DESCRIPTION <string>
65    Puts <string> into output .exp file in the .rdata section
66 
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.
71 
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.
78 
79 
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.
83 
84 
85 
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.
89 
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.
93 
94 
95 
96    Example:
97 
98  file1.c:
99    asm (".section .drectve");
100    asm (".ascii \"-export:adef\"");
101 
102    void adef (char * s)
103    {
104      printf ("hello from the dll %s\n", s);
105    }
106 
107    void bdef (char * s)
108    {
109      printf ("hello from the dll and the other entry point %s\n", s);
110    }
111 
112  file2.c:
113    asm (".section .drectve");
114    asm (".ascii \"-export:cdef\"");
115    asm (".ascii \"-export:ddef\"");
116 
117    void cdef (char * s)
118    {
119      printf ("hello from the dll %s\n", s);
120    }
121 
122    void ddef (char * s)
123    {
124      printf ("hello from the dll and the other entry point %s\n", s);
125    }
126 
127    int printf (void)
128    {
129      return 9;
130    }
131 
132  themain.c:
133    int main (void)
134    {
135      cdef ();
136      return 0;
137    }
138 
139  thedll.def
140 
141    LIBRARY thedll
142    HEAPSIZE 0x40000, 0x2000
143    EXPORTS bdef @ 20
144            cdef @ 30 NONAME
145 
146    SECTIONS donkey READ WRITE
147    aardvark EXECUTE
148 
149  # Compile up the parts of the dll and the program
150 
151    gcc -c file1.c file2.c themain.c
152 
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)
156 
157    ar  qcv thedll.in file1.o file2.o
158    ranlib thedll.in
159 
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).
163 
164    dlltool --def thedll.def --output-exp thedll.o --output-lib thedll.a
165 
166  # Build the dll with the library and the export table
167 
168    ld -o thedll.dll thedll.o thedll.in
169 
170  # Link the executable with the import library
171 
172    gcc -o themain.exe themain.o thedll.a
173 
174  This example can be extended if relocations are needed in the DLL:
175 
176  # Compile up the parts of the dll and the program
177 
178    gcc -c file1.c file2.c themain.c
179 
180  # Run this tool over the DLL's .def file and generate an imports file.
181 
182    dlltool --def thedll.def --output-lib thedll.lib
183 
184  # Link the executable with the import library and generate a base file
185  # at the same time
186 
187    gcc -o themain.exe themain.o thedll.lib -Wl,--base-file -Wl,themain.base
188 
189  # Run this tool over the DLL's .def file and generate an exports file
190  # which includes the relocations from the base file.
191 
192    dlltool --def thedll.def --base-file themain.base --output-exp thedll.exp
193 
194  # Build the dll with file1.o, file2.o and the export table
195 
196    ld -o thedll.dll thedll.exp file1.o file2.o  */
197 
198 /* .idata section description
199 
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.
203 
204    .idata$2 = Import Directory Table
205    = array of IMAGE_IMPORT_DESCRIPTOR's.
206 
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
212 
213    .idata$3 = null terminating entry for .idata$2.
214 
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.
219 
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.
227 
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.
231 
232    .idata$7 = dll name (eg: "kernel32.dll").  */
233 
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"
244 
245 #include <time.h>
246 #include <assert.h>
247 
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
258 
259 #ifndef COFF_PAGE_SIZE
260 #define COFF_PAGE_SIZE ((bfd_vma) 4096)
261 #endif
262 
263 #ifndef PAGE_MASK
264 #define PAGE_MASK ((bfd_vma) (- COFF_PAGE_SIZE))
265 #endif
266 
267 /* Get current BFD error message.  */
268 #define bfd_get_errmsg() (bfd_errmsg (bfd_get_error ()))
269 
270 /* Forward references.  */
271 static char *look_for_prog (const char *, const char *, int);
272 static char *deduce_name (const char *);
273 
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
278 
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 */
310 
311 #define show_allnames 0
312 
313 /* ifunc and ihead data structures: ttk@cygnus.com 1997
314 
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.
322 
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.  */
327 
328 typedef struct ifunct
329 {
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;
335 
336 typedef struct iheadt
337 {
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;
344 
345 /* Structure containing all import information as defined in .def file
346    (qv "ihead structure").  */
347 
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 
360 /* Types used to implement a linked list of dllnames associated
361    with the specified import lib. Used by the identify_* code.
362    The head entry is acts as a sentinal node and is always empty
363    (head->dllname is NULL).  */
364 typedef struct dll_name_list_node_t
365 {
366   char *                        dllname;
367   struct dll_name_list_node_t * next;
368 } dll_name_list_node_type;
369 
370 typedef struct dll_name_list_t
371 {
372   dll_name_list_node_type * head;
373   dll_name_list_node_type * tail;
374 } dll_name_list_type;
375 
376 /* Types used to pass data to iterator functions.  */
377 typedef struct symname_search_data_t
378 {
379   const char *symname;
380   bool found;
381 } symname_search_data_type;
382 
383 typedef struct identify_data_t
384 {
385    dll_name_list_type *list;
386    bool ms_style_implib;
387 } identify_data_type;
388 
389 
390 static char *head_label;
391 static char *imp_name_lab;
392 static char *dll_name;
393 static int dll_name_set_by_exp_name;
394 static int add_indirect = 0;
395 static int add_underscore = 0;
396 static int add_stdcall_underscore = 0;
397 /* This variable can hold three different values. The value
398    -1 (default) means that default underscoring should be used,
399    zero means that no underscoring should be done, and one
400    indicates that underscoring should be done.  */
401 static int leading_underscore = -1;
402 static int dontdeltemps = 0;
403 
404 /* TRUE if we should export all symbols.  Otherwise, we only export
405    symbols listed in .drectve sections or in the def file.  */
406 static bool export_all_symbols;
407 
408 /* TRUE if we should exclude the symbols in DEFAULT_EXCLUDES when
409    exporting all symbols.  */
410 static bool do_default_excludes = true;
411 
412 static bool use_nul_prefixed_import_tables = false;
413 
414 /* Default symbols to exclude when exporting all the symbols.  */
415 static const char *default_excludes = "DllMain@12,DllEntryPoint@0,impure_ptr";
416 
417 /* TRUE if we should add __imp_<SYMBOL> to import libraries for backward
418    compatibility to old Cygwin releases.  */
419 static bool create_compat_implib;
420 
421 /* TRUE if we have to write PE+ import libraries.  */
422 static bool create_for_pep;
423 
424 static char *def_file;
425 
426 extern char * program_name;
427 
428 static int machine;
429 static int killat;
430 static int add_stdcall_alias;
431 static const char *ext_prefix_alias;
432 static int verbose;
433 static FILE *output_def;
434 static FILE *base_file;
435 
436 #ifdef DLLTOOL_DEFAULT_ARM
437 static const char *mname = "arm";
438 #endif
439 
440 #ifdef DLLTOOL_DEFAULT_ARM_WINCE
441 static const char *mname = "arm-wince";
442 #endif
443 
444 #ifdef DLLTOOL_DEFAULT_I386
445 static const char *mname = "i386";
446 #endif
447 
448 #ifdef DLLTOOL_DEFAULT_MX86_64
449 static const char *mname = "i386:x86-64";
450 #endif
451 
452 #ifdef DLLTOOL_DEFAULT_SH
453 static const char *mname = "sh";
454 #endif
455 
456 #ifdef DLLTOOL_DEFAULT_MIPS
457 static const char *mname = "mips";
458 #endif
459 
460 #ifdef DLLTOOL_DEFAULT_MCORE
461 static const char * mname = "mcore-le";
462 #endif
463 
464 #ifdef DLLTOOL_DEFAULT_MCORE_ELF
465 static const char * mname = "mcore-elf";
466 static char * mcore_elf_out_file = NULL;
467 static char * mcore_elf_linker   = NULL;
468 static char * mcore_elf_linker_flags = NULL;
469 
470 #define DRECTVE_SECTION_NAME ((machine == MMCORE_ELF || machine == MMCORE_ELF_LE) ? ".exports" : ".drectve")
471 #endif
472 
473 #ifndef DRECTVE_SECTION_NAME
474 #define DRECTVE_SECTION_NAME ".drectve"
475 #endif
476 
477 /* What's the right name for this ?  */
478 #define PATHMAX 250
479 
480 /* External name alias numbering starts here.  */
481 #define PREFIX_ALIAS_BASE	20000
482 
483 char *tmp_asm_buf;
484 char *tmp_head_s_buf;
485 char *tmp_head_o_buf;
486 char *tmp_tail_s_buf;
487 char *tmp_tail_o_buf;
488 char *tmp_stub_buf;
489 
490 #define TMP_ASM		dlltmp (&tmp_asm_buf, "%sc.s")
491 #define TMP_HEAD_S	dlltmp (&tmp_head_s_buf, "%sh.s")
492 #define TMP_HEAD_O	dlltmp (&tmp_head_o_buf, "%sh.o")
493 #define TMP_TAIL_S	dlltmp (&tmp_tail_s_buf, "%st.s")
494 #define TMP_TAIL_O	dlltmp (&tmp_tail_o_buf, "%st.o")
495 #define TMP_STUB	dlltmp (&tmp_stub_buf, "%ss")
496 
497 /* This bit of assembly does jmp * ....  */
498 static const unsigned char i386_jtab[] =
499 {
500   0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90
501 };
502 
503 static const unsigned char i386_dljtab[] =
504 {
505   0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function             */
506   0xB8, 0x00, 0x00, 0x00, 0x00,       /* mov eax, offset __imp__function */
507   0xE9, 0x00, 0x00, 0x00, 0x00        /* jmp __tailMerge__dllname        */
508 };
509 
510 static const unsigned char i386_x64_dljtab[] =
511 {
512   0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, /* jmp __imp__function             */
513   0x48, 0x8d, 0x05,		      /* leaq rax, (__imp__function) */
514         0x00, 0x00, 0x00, 0x00,
515   0xE9, 0x00, 0x00, 0x00, 0x00        /* jmp __tailMerge__dllname        */
516 };
517 
518 static const unsigned char arm_jtab[] =
519 {
520   0x00, 0xc0, 0x9f, 0xe5,	/* ldr  ip, [pc] */
521   0x00, 0xf0, 0x9c, 0xe5,	/* ldr  pc, [ip] */
522   0,    0,    0,    0
523 };
524 
525 static const unsigned char arm_interwork_jtab[] =
526 {
527   0x04, 0xc0, 0x9f, 0xe5,	/* ldr  ip, [pc] */
528   0x00, 0xc0, 0x9c, 0xe5,	/* ldr  ip, [ip] */
529   0x1c, 0xff, 0x2f, 0xe1,	/* bx   ip       */
530   0,    0,    0,    0
531 };
532 
533 static const unsigned char thumb_jtab[] =
534 {
535   0x40, 0xb4,           /* push {r6}         */
536   0x02, 0x4e,           /* ldr  r6, [pc, #8] */
537   0x36, 0x68,           /* ldr  r6, [r6]     */
538   0xb4, 0x46,           /* mov  ip, r6       */
539   0x40, 0xbc,           /* pop  {r6}         */
540   0x60, 0x47,           /* bx   ip           */
541   0,    0,    0,    0
542 };
543 
544 static const unsigned char mcore_be_jtab[] =
545 {
546   0x71, 0x02,            /* lrw r1,2       */
547   0x81, 0x01,            /* ld.w r1,(r1,0) */
548   0x00, 0xC1,            /* jmp r1         */
549   0x12, 0x00,            /* nop            */
550   0x00, 0x00, 0x00, 0x00 /* <address>      */
551 };
552 
553 static const unsigned char mcore_le_jtab[] =
554 {
555   0x02, 0x71,            /* lrw r1,2       */
556   0x01, 0x81,            /* ld.w r1,(r1,0) */
557   0xC1, 0x00,            /* jmp r1         */
558   0x00, 0x12,            /* nop            */
559   0x00, 0x00, 0x00, 0x00 /* <address>      */
560 };
561 
562 static const char i386_trampoline[] =
563   "\tpushl %%ecx\n"
564   "\tpushl %%edx\n"
565   "\tpushl %%eax\n"
566   "\tpushl $__DELAY_IMPORT_DESCRIPTOR_%s\n"
567   "\tcall ___delayLoadHelper2@8\n"
568   "\tpopl %%edx\n"
569   "\tpopl %%ecx\n"
570   "\tjmp *%%eax\n";
571 
572 static const char i386_x64_trampoline[] =
573   "\tsubq $72, %%rsp\n"
574   "\t.seh_stackalloc 72\n"
575   "\t.seh_endprologue\n"
576   "\tmovq %%rcx, 64(%%rsp)\n"
577   "\tmovq %%rdx, 56(%%rsp)\n"
578   "\tmovq %%r8, 48(%%rsp)\n"
579   "\tmovq %%r9, 40(%%rsp)\n"
580   "\tmovq  %%rax, %%rdx\n"
581   "\tleaq  __DELAY_IMPORT_DESCRIPTOR_%s(%%rip), %%rcx\n"
582   "\tcall __delayLoadHelper2\n"
583   "\tmovq 40(%%rsp), %%r9\n"
584   "\tmovq 48(%%rsp), %%r8\n"
585   "\tmovq 56(%%rsp), %%rdx\n"
586   "\tmovq 64(%%rsp), %%rcx\n"
587   "\taddq $72, %%rsp\n"
588   "\tjmp *%%rax\n";
589 
590 struct mac
591 {
592   const char *type;
593   const char *how_byte;
594   const char *how_short;
595   const char *how_long;
596   const char *how_asciz;
597   const char *how_comment;
598   const char *how_jump;
599   const char *how_global;
600   const char *how_space;
601   const char *how_align_short;
602   const char *how_align_long;
603   const char *how_default_as_switches;
604   const char *how_bfd_target;
605   enum bfd_architecture how_bfd_arch;
606   const unsigned char *how_jtab;
607   int how_jtab_size; /* Size of the jtab entry.  */
608   int how_jtab_roff; /* Offset into it for the ind 32 reloc into idata 5.  */
609   const unsigned char *how_dljtab;
610   int how_dljtab_size; /* Size of the dljtab entry.  */
611   int how_dljtab_roff1; /* Offset for the ind 32 reloc into idata 5.  */
612   int how_dljtab_roff2; /* Offset for the ind 32 reloc into idata 5.  */
613   int how_dljtab_roff3; /* Offset for the ind 32 reloc into idata 5.  */
614   bool how_seh;
615   const char *trampoline;
616 };
617 
618 static const struct mac
619 mtable[] =
620 {
621   {
622 #define MARM 0
623     "arm", ".byte", ".short", ".long", ".asciz", "@",
624     "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
625     ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
626     "pe-arm-little", bfd_arch_arm,
627     arm_jtab, sizeof (arm_jtab), 8,
628     0, 0, 0, 0, 0, false, 0
629   }
630   ,
631   {
632 #define M386 1
633     "i386", ".byte", ".short", ".long", ".asciz", "#",
634     "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
635     "pe-i386",bfd_arch_i386,
636     i386_jtab, sizeof (i386_jtab), 2,
637     i386_dljtab, sizeof (i386_dljtab), 2, 7, 12, false, i386_trampoline
638   }
639   ,
640   {
641 #define MTHUMB 2
642     "thumb", ".byte", ".short", ".long", ".asciz", "@",
643     "push\t{r6}\n\tldr\tr6, [pc, #8]\n\tldr\tr6, [r6]\n\tmov\tip, r6\n\tpop\t{r6}\n\tbx\tip",
644     ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
645     "pe-arm-little", bfd_arch_arm,
646     thumb_jtab, sizeof (thumb_jtab), 12,
647     0, 0, 0, 0, 0, false, 0
648   }
649   ,
650 #define MARM_INTERWORK 3
651   {
652     "arm_interwork", ".byte", ".short", ".long", ".asciz", "@",
653     "ldr\tip,[pc]\n\tldr\tip,[ip]\n\tbx\tip\n\t.long",
654     ".global", ".space", ".align\t2",".align\t4", "-mthumb-interwork",
655     "pe-arm-little", bfd_arch_arm,
656     arm_interwork_jtab, sizeof (arm_interwork_jtab), 12,
657     0, 0, 0, 0, 0, false, 0
658   }
659   ,
660   {
661 #define MMCORE_BE 4
662     "mcore-be", ".byte", ".short", ".long", ".asciz", "//",
663     "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
664     ".global", ".space", ".align\t2",".align\t4", "",
665     "pe-mcore-big", bfd_arch_mcore,
666     mcore_be_jtab, sizeof (mcore_be_jtab), 8,
667     0, 0, 0, 0, 0, false, 0
668   }
669   ,
670   {
671 #define MMCORE_LE 5
672     "mcore-le", ".byte", ".short", ".long", ".asciz", "//",
673     "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
674     ".global", ".space", ".align\t2",".align\t4", "-EL",
675     "pe-mcore-little", bfd_arch_mcore,
676     mcore_le_jtab, sizeof (mcore_le_jtab), 8,
677     0, 0, 0, 0, 0, false, 0
678   }
679   ,
680   {
681 #define MMCORE_ELF 6
682     "mcore-elf-be", ".byte", ".short", ".long", ".asciz", "//",
683     "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
684     ".global", ".space", ".align\t2",".align\t4", "",
685     "elf32-mcore-big", bfd_arch_mcore,
686     mcore_be_jtab, sizeof (mcore_be_jtab), 8,
687     0, 0, 0, 0, 0, false, 0
688   }
689   ,
690   {
691 #define MMCORE_ELF_LE 7
692     "mcore-elf-le", ".byte", ".short", ".long", ".asciz", "//",
693     "lrw r1,[1f]\n\tld.w r1,(r1,0)\n\tjmp r1\n\tnop\n1:.long",
694     ".global", ".space", ".align\t2",".align\t4", "-EL",
695     "elf32-mcore-little", bfd_arch_mcore,
696     mcore_le_jtab, sizeof (mcore_le_jtab), 8,
697     0, 0, 0, 0, 0, false, 0
698   }
699   ,
700   {
701 #define MARM_WINCE 8
702     "arm-wince", ".byte", ".short", ".long", ".asciz", "@",
703     "ldr\tip,[pc]\n\tldr\tpc,[ip]\n\t.long",
704     ".global", ".space", ".align\t2",".align\t4", "-mapcs-32",
705     "pe-arm-wince-little", bfd_arch_arm,
706     arm_jtab, sizeof (arm_jtab), 8,
707     0, 0, 0, 0, 0, false, 0
708   }
709   ,
710   {
711 #define MX86 9
712     "i386:x86-64", ".byte", ".short", ".long", ".asciz", "#",
713     "jmp *", ".global", ".space", ".align\t2",".align\t4", "",
714     "pe-x86-64",bfd_arch_i386,
715     i386_jtab, sizeof (i386_jtab), 2,
716     i386_x64_dljtab, sizeof (i386_x64_dljtab), 2, 9, 14, true, i386_x64_trampoline
717   }
718   ,
719   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
720 };
721 
722 typedef struct dlist
723 {
724   char *text;
725   struct dlist *next;
726 }
727 dlist_type;
728 
729 typedef struct export
730 {
731   const char *name;
732   const char *internal_name;
733   const char *import_name;
734   const char *its_name;
735   int ordinal;
736   int constant;
737   int noname;		/* Don't put name in image file.  */
738   int private;		/* Don't put reference in import lib.  */
739   int data;
740   int forward;		/* Number of forward label, 0 means no forward.  */
741   struct export *next;
742 }
743 export_type;
744 
745 /* A list of symbols which we should not export.  */
746 
747 struct string_list
748 {
749   struct string_list *next;
750   char *string;
751 };
752 
753 static struct string_list *excludes;
754 
755 static const char *rvaafter (int);
756 static const char *rvabefore (int);
757 static const char *asm_prefix (int, const char *);
758 static void process_def_file (const char *);
759 static void new_directive (char *);
760 static void append_import (const char *, const char *, int, const char *);
761 static void run (const char *, char *);
762 static void scan_drectve_symbols (bfd *);
763 static void scan_filtered_symbols (bfd *, void *, long, unsigned int);
764 static void add_excludes (const char *);
765 static bool match_exclude (const char *);
766 static void set_default_excludes (void);
767 static long filter_symbols (bfd *, void *, long, unsigned int);
768 static void scan_all_symbols (bfd *);
769 static void scan_open_obj_file (bfd *);
770 static void scan_obj_file (const char *);
771 static void dump_def_info (FILE *);
772 static int sfunc (const void *, const void *);
773 static void flush_page (FILE *, bfd_vma *, bfd_vma, int);
774 static void gen_def_file (void);
775 static void generate_idata_ofile (FILE *);
776 static void assemble_file (const char *, const char *);
777 static void gen_exp_file (void);
778 static const char *xlate (const char *);
779 static char *make_label (const char *, const char *);
780 static char *make_imp_label (const char *, const char *);
781 static bfd *make_one_lib_file (export_type *, int, int);
782 static bfd *make_head (void);
783 static bfd *make_tail (void);
784 static bfd *make_delay_head (void);
785 static void gen_lib_file (int);
786 static void dll_name_list_append (dll_name_list_type *, bfd_byte *);
787 static int  dll_name_list_count (dll_name_list_type *);
788 static void dll_name_list_print (dll_name_list_type *);
789 static void dll_name_list_free_contents (dll_name_list_node_type *);
790 static void dll_name_list_free (dll_name_list_type *);
791 static dll_name_list_type * dll_name_list_create (void);
792 static void identify_dll_for_implib (void);
793 static void identify_search_archive
794   (bfd *, void (*) (bfd *, bfd *, void *),  void *);
795 static void identify_search_member (bfd *, bfd *, void *);
796 static bool identify_process_section_p (asection *, bool);
797 static void identify_search_section (bfd *, asection *, void *);
798 static void identify_member_contains_symname (bfd *, bfd  *, void *);
799 
800 static int pfunc (const void *, const void *);
801 static int nfunc (const void *, const void *);
802 static void remove_null_names (export_type **);
803 static void process_duplicates (export_type **);
804 static void fill_ordinals (export_type **);
805 static void mangle_defs (void);
806 static void usage (FILE *, int);
807 static void inform (const char *, ...) ATTRIBUTE_PRINTF_1;
808 static void set_dll_name_from_def (const char *name, char is_dll);
809 
810 static char *
811 prefix_encode (char *start, unsigned code)
812 {
813   static char alpha[26] = "abcdefghijklmnopqrstuvwxyz";
814   static char buf[32];
815   char *p;
816   strcpy (buf, start);
817   p = strchr (buf, '\0');
818   do
819     *p++ = alpha[code % sizeof (alpha)];
820   while ((code /= sizeof (alpha)) != 0);
821   *p = '\0';
822   return buf;
823 }
824 
825 static char *
826 dlltmp (char **buf, const char *fmt)
827 {
828   if (!*buf)
829     {
830       *buf = malloc (strlen (tmp_prefix) + 64);
831       sprintf (*buf, fmt, tmp_prefix);
832     }
833   return *buf;
834 }
835 
836 static void
837 inform (const char * message, ...)
838 {
839   va_list args;
840 
841   va_start (args, message);
842 
843   if (!verbose)
844     return;
845 
846   report (message, args);
847 
848   va_end (args);
849 }
850 
851 static const char *
852 rvaafter (int mach)
853 {
854   switch (mach)
855     {
856     case MARM:
857     case M386:
858     case MX86:
859     case MTHUMB:
860     case MARM_INTERWORK:
861     case MMCORE_BE:
862     case MMCORE_LE:
863     case MMCORE_ELF:
864     case MMCORE_ELF_LE:
865     case MARM_WINCE:
866       break;
867     default:
868       /* xgettext:c-format */
869       fatal (_("Internal error: Unknown machine type: %d"), mach);
870       break;
871     }
872   return "";
873 }
874 
875 static const char *
876 rvabefore (int mach)
877 {
878   switch (mach)
879     {
880     case MARM:
881     case M386:
882     case MX86:
883     case MTHUMB:
884     case MARM_INTERWORK:
885     case MMCORE_BE:
886     case MMCORE_LE:
887     case MMCORE_ELF:
888     case MMCORE_ELF_LE:
889     case MARM_WINCE:
890       return ".rva\t";
891     default:
892       /* xgettext:c-format */
893       fatal (_("Internal error: Unknown machine type: %d"), mach);
894       break;
895     }
896   return "";
897 }
898 
899 static const char *
900 asm_prefix (int mach, const char *name)
901 {
902   switch (mach)
903     {
904     case MARM:
905     case MTHUMB:
906     case MARM_INTERWORK:
907     case MMCORE_BE:
908     case MMCORE_LE:
909     case MMCORE_ELF:
910     case MMCORE_ELF_LE:
911     case MARM_WINCE:
912       break;
913     case M386:
914     case MX86:
915       /* Symbol names starting with ? do not have a leading underscore. */
916       if ((name && *name == '?') || leading_underscore == 0)
917         break;
918       else
919         return "_";
920     default:
921       /* xgettext:c-format */
922       fatal (_("Internal error: Unknown machine type: %d"), mach);
923       break;
924     }
925   return "";
926 }
927 
928 #define ASM_BYTE		mtable[machine].how_byte
929 #define ASM_SHORT		mtable[machine].how_short
930 #define ASM_LONG		mtable[machine].how_long
931 #define ASM_TEXT		mtable[machine].how_asciz
932 #define ASM_C			mtable[machine].how_comment
933 #define ASM_JUMP		mtable[machine].how_jump
934 #define ASM_GLOBAL		mtable[machine].how_global
935 #define ASM_SPACE		mtable[machine].how_space
936 #define ASM_ALIGN_SHORT		mtable[machine].how_align_short
937 #define ASM_RVA_BEFORE		rvabefore (machine)
938 #define ASM_RVA_AFTER		rvaafter (machine)
939 #define ASM_PREFIX(NAME)	asm_prefix (machine, (NAME))
940 #define ASM_ALIGN_LONG  	mtable[machine].how_align_long
941 #define HOW_BFD_READ_TARGET	0  /* Always default.  */
942 #define HOW_BFD_WRITE_TARGET	mtable[machine].how_bfd_target
943 #define HOW_BFD_ARCH		mtable[machine].how_bfd_arch
944 #define HOW_JTAB		(delay ? mtable[machine].how_dljtab \
945 					: mtable[machine].how_jtab)
946 #define HOW_JTAB_SIZE		(delay ? mtable[machine].how_dljtab_size \
947 					: mtable[machine].how_jtab_size)
948 #define HOW_JTAB_ROFF		(delay ? mtable[machine].how_dljtab_roff1 \
949 					: mtable[machine].how_jtab_roff)
950 #define HOW_JTAB_ROFF2		(delay ? mtable[machine].how_dljtab_roff2 : 0)
951 #define HOW_JTAB_ROFF3		(delay ? mtable[machine].how_dljtab_roff3 : 0)
952 #define ASM_SWITCHES		mtable[machine].how_default_as_switches
953 #define HOW_SEH			mtable[machine].how_seh
954 
955 static char **oav;
956 
957 static void
958 process_def_file (const char *name)
959 {
960   FILE *f = fopen (name, FOPEN_RT);
961 
962   if (!f)
963     /* xgettext:c-format */
964     fatal (_("Can't open def file: %s"), name);
965 
966   yyin = f;
967 
968   /* xgettext:c-format */
969   inform (_("Processing def file: %s"), name);
970 
971   yyparse ();
972 
973   inform (_("Processed def file"));
974 }
975 
976 /**********************************************************************/
977 
978 /* Communications with the parser.  */
979 
980 static int d_nfuncs;		/* Number of functions exported.  */
981 static int d_named_nfuncs;	/* Number of named functions exported.  */
982 static int d_low_ord;		/* Lowest ordinal index.  */
983 static int d_high_ord;		/* Highest ordinal index.  */
984 static export_type *d_exports;	/* List of exported functions.  */
985 static export_type **d_exports_lexically;  /* Vector of exported functions in alpha order.  */
986 static dlist_type *d_list;	/* Descriptions.  */
987 static dlist_type *a_list;	/* Stuff to go in directives.  */
988 static int d_nforwards = 0;	/* Number of forwarded exports.  */
989 
990 static int d_is_dll;
991 static int d_is_exe;
992 
993 void
994 yyerror (const char * err ATTRIBUTE_UNUSED)
995 {
996   /* xgettext:c-format */
997   non_fatal (_("Syntax error in def file %s:%d"), def_file, linenumber);
998 }
999 
1000 void
1001 def_exports (const char *name, const char *internal_name, int ordinal,
1002 	     int noname, int constant, int data, int private,
1003 	     const char *its_name)
1004 {
1005   struct export *p = (struct export *) xmalloc (sizeof (*p));
1006 
1007   p->name = name;
1008   p->internal_name = internal_name ? internal_name : name;
1009   p->its_name = its_name;
1010   p->import_name = name;
1011   p->ordinal = ordinal;
1012   p->constant = constant;
1013   p->noname = noname;
1014   p->private = private;
1015   p->data = data;
1016   p->next = d_exports;
1017   d_exports = p;
1018   d_nfuncs++;
1019 
1020   if ((internal_name != NULL)
1021       && (strchr (internal_name, '.') != NULL))
1022     p->forward = ++d_nforwards;
1023   else
1024     p->forward = 0; /* no forward */
1025 }
1026 
1027 static void
1028 set_dll_name_from_def (const char *name, char is_dll)
1029 {
1030   const char *image_basename = lbasename (name);
1031   if (image_basename != name)
1032     non_fatal (_("%s: Path components stripped from image name, '%s'."),
1033 	      def_file, name);
1034   /* Append the default suffix, if none specified.  */
1035   if (strchr (image_basename, '.') == 0)
1036     {
1037       const char * suffix = is_dll ? ".dll" : ".exe";
1038 
1039       dll_name = xmalloc (strlen (image_basename) + strlen (suffix) + 1);
1040       sprintf (dll_name, "%s%s", image_basename, suffix);
1041     }
1042   else
1043     dll_name = xstrdup (image_basename);
1044 }
1045 
1046 void
1047 def_name (const char *name, int base)
1048 {
1049   /* xgettext:c-format */
1050   inform (_("NAME: %s base: %x"), name, base);
1051 
1052   if (d_is_dll)
1053     non_fatal (_("Can't have LIBRARY and NAME"));
1054 
1055   if (dll_name_set_by_exp_name && name && *name != 0)
1056     {
1057       dll_name = NULL;
1058       dll_name_set_by_exp_name = 0;
1059     }
1060   /* If --dllname not provided, use the one in the DEF file.
1061      FIXME: Is this appropriate for executables?  */
1062   if (!dll_name)
1063     set_dll_name_from_def (name, 0);
1064   d_is_exe = 1;
1065 }
1066 
1067 void
1068 def_library (const char *name, int base)
1069 {
1070   /* xgettext:c-format */
1071   inform (_("LIBRARY: %s base: %x"), name, base);
1072 
1073   if (d_is_exe)
1074     non_fatal (_("Can't have LIBRARY and NAME"));
1075 
1076   if (dll_name_set_by_exp_name && name && *name != 0)
1077     {
1078       dll_name = NULL;
1079       dll_name_set_by_exp_name = 0;
1080     }
1081 
1082   /* If --dllname not provided, use the one in the DEF file.  */
1083   if (!dll_name)
1084     set_dll_name_from_def (name, 1);
1085   d_is_dll = 1;
1086 }
1087 
1088 void
1089 def_description (const char *desc)
1090 {
1091   dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1092   d->text = xstrdup (desc);
1093   d->next = d_list;
1094   d_list = d;
1095 }
1096 
1097 static void
1098 new_directive (char *dir)
1099 {
1100   dlist_type *d = (dlist_type *) xmalloc (sizeof (dlist_type));
1101   d->text = xstrdup (dir);
1102   d->next = a_list;
1103   a_list = d;
1104 }
1105 
1106 void
1107 def_heapsize (int reserve, int commit)
1108 {
1109   char b[200];
1110   if (commit > 0)
1111     sprintf (b, "-heap 0x%x,0x%x ", reserve, commit);
1112   else
1113     sprintf (b, "-heap 0x%x ", reserve);
1114   new_directive (xstrdup (b));
1115 }
1116 
1117 void
1118 def_stacksize (int reserve, int commit)
1119 {
1120   char b[200];
1121   if (commit > 0)
1122     sprintf (b, "-stack 0x%x,0x%x ", reserve, commit);
1123   else
1124     sprintf (b, "-stack 0x%x ", reserve);
1125   new_directive (xstrdup (b));
1126 }
1127 
1128 /* append_import simply adds the given import definition to the global
1129    import_list.  It is used by def_import.  */
1130 
1131 static void
1132 append_import (const char *symbol_name, const char *dllname, int func_ordinal,
1133 	       const char *its_name)
1134 {
1135   iheadtype **pq;
1136   iheadtype *q;
1137 
1138   for (pq = &import_list; *pq != NULL; pq = &(*pq)->next)
1139     {
1140       if (strcmp ((*pq)->dllname, dllname) == 0)
1141 	{
1142 	  q = *pq;
1143 	  q->functail->next = xmalloc (sizeof (ifunctype));
1144 	  q->functail = q->functail->next;
1145 	  q->functail->ord  = func_ordinal;
1146 	  q->functail->name = xstrdup (symbol_name);
1147 	  q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1148 	  q->functail->next = NULL;
1149 	  q->nfuncs++;
1150 	  return;
1151 	}
1152     }
1153 
1154   q = xmalloc (sizeof (iheadtype));
1155   q->dllname = xstrdup (dllname);
1156   q->nfuncs = 1;
1157   q->funchead = xmalloc (sizeof (ifunctype));
1158   q->functail = q->funchead;
1159   q->next = NULL;
1160   q->functail->name = xstrdup (symbol_name);
1161   q->functail->its_name = (its_name ? xstrdup (its_name) : NULL);
1162   q->functail->ord  = func_ordinal;
1163   q->functail->next = NULL;
1164 
1165   *pq = q;
1166 }
1167 
1168 /* def_import is called from within defparse.y when an IMPORT
1169    declaration is encountered.  Depending on the form of the
1170    declaration, the module name may or may not need ".dll" to be
1171    appended to it, the name of the function may be stored in internal
1172    or entry, and there may or may not be an ordinal value associated
1173    with it.  */
1174 
1175 /* A note regarding the parse modes:
1176    In defparse.y we have to accept import declarations which follow
1177    any one of the following forms:
1178      <func_name_in_app> = <dll_name>.<func_name_in_dll>
1179      <func_name_in_app> = <dll_name>.<number>
1180      <dll_name>.<func_name_in_dll>
1181      <dll_name>.<number>
1182    Furthermore, the dll's name may or may not end with ".dll", which
1183    complicates the parsing a little.  Normally the dll's name is
1184    passed to def_import() in the "module" parameter, but when it ends
1185    with ".dll" it gets passed in "module" sans ".dll" and that needs
1186    to be reappended.
1187 
1188   def_import gets five parameters:
1189   APP_NAME - the name of the function in the application, if
1190              present, or NULL if not present.
1191   MODULE   - the name of the dll, possibly sans extension (ie, '.dll').
1192   DLLEXT   - the extension of the dll, if present, NULL if not present.
1193   ENTRY    - the name of the function in the dll, if present, or NULL.
1194   ORD_VAL  - the numerical tag of the function in the dll, if present,
1195              or NULL.  Exactly one of <entry> or <ord_val> must be
1196              present (i.e., not NULL).  */
1197 
1198 void
1199 def_import (const char *app_name, const char *module, const char *dllext,
1200 	    const char *entry, int ord_val, const char *its_name)
1201 {
1202   const char *application_name;
1203   char *buf = NULL;
1204 
1205   if (entry != NULL)
1206     application_name = entry;
1207   else
1208     {
1209       if (app_name != NULL)
1210 	application_name = app_name;
1211       else
1212 	application_name = "";
1213     }
1214 
1215   if (dllext != NULL)
1216     module = buf = concat (module, ".", dllext, NULL);
1217 
1218   append_import (application_name, module, ord_val, its_name);
1219 
1220   free (buf);
1221 }
1222 
1223 void
1224 def_version (int major, int minor)
1225 {
1226   printf (_("VERSION %d.%d\n"), major, minor);
1227 }
1228 
1229 void
1230 def_section (const char *name, int attr)
1231 {
1232   char buf[200];
1233   char atts[5];
1234   char *d = atts;
1235   if (attr & 1)
1236     *d++ = 'R';
1237 
1238   if (attr & 2)
1239     *d++ = 'W';
1240   if (attr & 4)
1241     *d++ = 'X';
1242   if (attr & 8)
1243     *d++ = 'S';
1244   *d++ = 0;
1245   sprintf (buf, "-attr %s %s", name, atts);
1246   new_directive (xstrdup (buf));
1247 }
1248 
1249 void
1250 def_code (int attr)
1251 {
1252 
1253   def_section ("CODE", attr);
1254 }
1255 
1256 void
1257 def_data (int attr)
1258 {
1259   def_section ("DATA", attr);
1260 }
1261 
1262 /**********************************************************************/
1263 
1264 static void
1265 run (const char *what, char *args)
1266 {
1267   char *s;
1268   int pid, wait_status;
1269   int i;
1270   const char **argv;
1271   char *errmsg_fmt = NULL, *errmsg_arg = NULL;
1272   char *temp_base = choose_temp_base ();
1273 
1274   inform (_("run: %s %s"), what, args);
1275 
1276   /* Count the args */
1277   i = 0;
1278   for (s = args; *s; s++)
1279     if (*s == ' ')
1280       i++;
1281   i++;
1282   argv = xmalloc (sizeof (char *) * (i + 3));
1283   i = 0;
1284   argv[i++] = what;
1285   s = args;
1286   while (1)
1287     {
1288       while (*s == ' ')
1289 	++s;
1290       argv[i++] = s;
1291       while (*s != ' ' && *s != 0)
1292 	s++;
1293       if (*s == 0)
1294 	break;
1295       *s++ = 0;
1296     }
1297   argv[i++] = NULL;
1298 
1299   pid = pexecute (argv[0], (char * const *) argv, program_name, temp_base,
1300 		  &errmsg_fmt, &errmsg_arg, PEXECUTE_ONE | PEXECUTE_SEARCH);
1301   free (argv);
1302 
1303   if (pid == -1)
1304     {
1305       inform ("%s", strerror (errno));
1306 
1307       fatal (errmsg_fmt, errmsg_arg);
1308     }
1309 
1310   pid = pwait (pid, & wait_status, 0);
1311 
1312   if (pid == -1)
1313     {
1314       /* xgettext:c-format */
1315       fatal (_("wait: %s"), strerror (errno));
1316     }
1317   else if (WIFSIGNALED (wait_status))
1318     {
1319       /* xgettext:c-format */
1320       fatal (_("subprocess got fatal signal %d"), WTERMSIG (wait_status));
1321     }
1322   else if (WIFEXITED (wait_status))
1323     {
1324       if (WEXITSTATUS (wait_status) != 0)
1325 	/* xgettext:c-format */
1326 	non_fatal (_("%s exited with status %d"),
1327 		   what, WEXITSTATUS (wait_status));
1328     }
1329   else
1330     abort ();
1331 }
1332 
1333 /* Look for a list of symbols to export in the .drectve section of
1334    ABFD.  Pass each one to def_exports.  */
1335 
1336 static void
1337 scan_drectve_symbols (bfd *abfd)
1338 {
1339   asection * s;
1340   int        size;
1341   char *     buf;
1342   char *     p;
1343   char *     e;
1344 
1345   /* Look for .drectve's */
1346   s = bfd_get_section_by_name (abfd, DRECTVE_SECTION_NAME);
1347 
1348   if (s == NULL)
1349     return;
1350 
1351   size = bfd_section_size (s);
1352   buf  = xmalloc (size);
1353 
1354   bfd_get_section_contents (abfd, s, buf, 0, size);
1355 
1356   /* xgettext:c-format */
1357   inform (_("Sucking in info from %s section in %s"),
1358 	  DRECTVE_SECTION_NAME, bfd_get_filename (abfd));
1359 
1360   /* Search for -export: strings. The exported symbols can optionally
1361      have type tags (eg., -export:foo,data), so handle those as well.
1362      Currently only data tag is supported.  */
1363   p = buf;
1364   e = buf + size;
1365   while (p < e)
1366     {
1367       if (p[0] == '-'
1368 	  && startswith (p, "-export:"))
1369 	{
1370 	  char * name;
1371 	  char * c;
1372 	  flagword flags = BSF_FUNCTION;
1373 
1374 	  p += 8;
1375 	  /* Do we have a quoted export?  */
1376 	  if (*p == '"')
1377 	    {
1378 	      p++;
1379 	      name = p;
1380 	      while (p < e && *p != '"')
1381 		++p;
1382 	    }
1383 	  else
1384 	    {
1385 	      name = p;
1386 	      while (p < e && *p != ',' && *p != ' ' && *p != '-')
1387 		p++;
1388 	    }
1389 	  c = xmalloc (p - name + 1);
1390 	  memcpy (c, name, p - name);
1391 	  c[p - name] = 0;
1392 	  /* Advance over trailing quote.  */
1393 	  if (p < e && *p == '"')
1394 	    ++p;
1395 	  if (p < e && *p == ',')       /* found type tag.  */
1396 	    {
1397 	      char *tag_start = ++p;
1398 	      while (p < e && *p != ' ' && *p != '-')
1399 		p++;
1400 	      if (startswith (tag_start, "data"))
1401 		flags &= ~BSF_FUNCTION;
1402 	    }
1403 
1404 	  /* FIXME: The 5th arg is for the `constant' field.
1405 	     What should it be?  Not that it matters since it's not
1406 	     currently useful.  */
1407 	  def_exports (c, 0, -1, 0, 0, ! (flags & BSF_FUNCTION), 0, NULL);
1408 
1409 	  if (add_stdcall_alias && strchr (c, '@'))
1410 	    {
1411 	      int lead_at = (*c == '@') ;
1412 	      char *exported_name = xstrdup (c + lead_at);
1413 	      char *atsym = strchr (exported_name, '@');
1414 	      *atsym = '\0';
1415 	      /* Note: stdcall alias symbols can never be data.  */
1416 	      def_exports (exported_name, xstrdup (c), -1, 0, 0, 0, 0, NULL);
1417 	    }
1418 	}
1419       else
1420 	p++;
1421     }
1422   free (buf);
1423 }
1424 
1425 /* Look through the symbols in MINISYMS, and add each one to list of
1426    symbols to export.  */
1427 
1428 static void
1429 scan_filtered_symbols (bfd *abfd, void *minisyms, long symcount,
1430 		       unsigned int size)
1431 {
1432   asymbol *store;
1433   bfd_byte *from, *fromend;
1434 
1435   store = bfd_make_empty_symbol (abfd);
1436   if (store == NULL)
1437     bfd_fatal (bfd_get_filename (abfd));
1438 
1439   from = (bfd_byte *) minisyms;
1440   fromend = from + symcount * size;
1441   for (; from < fromend; from += size)
1442     {
1443       asymbol *sym;
1444       const char *symbol_name;
1445 
1446       sym = bfd_minisymbol_to_symbol (abfd, false, from, store);
1447       if (sym == NULL)
1448 	bfd_fatal (bfd_get_filename (abfd));
1449 
1450       symbol_name = bfd_asymbol_name (sym);
1451       if (bfd_get_symbol_leading_char (abfd) == symbol_name[0])
1452 	++symbol_name;
1453 
1454       def_exports (xstrdup (symbol_name) , 0, -1, 0, 0,
1455 		   ! (sym->flags & BSF_FUNCTION), 0, NULL);
1456 
1457       if (add_stdcall_alias && strchr (symbol_name, '@'))
1458         {
1459 	  int lead_at = (*symbol_name == '@');
1460 	  char *exported_name = xstrdup (symbol_name + lead_at);
1461 	  char *atsym = strchr (exported_name, '@');
1462 	  *atsym = '\0';
1463 	  /* Note: stdcall alias symbols can never be data.  */
1464 	  def_exports (exported_name, xstrdup (symbol_name), -1, 0, 0, 0, 0, NULL);
1465 	}
1466     }
1467 }
1468 
1469 /* Add a list of symbols to exclude.  */
1470 
1471 static void
1472 add_excludes (const char *new_excludes)
1473 {
1474   char *local_copy;
1475   char *exclude_string;
1476 
1477   local_copy = xstrdup (new_excludes);
1478 
1479   exclude_string = strtok (local_copy, ",:");
1480   for (; exclude_string; exclude_string = strtok (NULL, ",:"))
1481     {
1482       struct string_list *new_exclude;
1483 
1484       new_exclude = ((struct string_list *)
1485 		     xmalloc (sizeof (struct string_list)));
1486       new_exclude->string = (char *) xmalloc (strlen (exclude_string) + 2);
1487       /* Don't add a leading underscore for fastcall symbols.  */
1488       if (*exclude_string == '@')
1489 	sprintf (new_exclude->string, "%s", exclude_string);
1490       else
1491 	sprintf (new_exclude->string, "%s%s", (!leading_underscore ? "" : "_"),
1492 		 exclude_string);
1493       new_exclude->next = excludes;
1494       excludes = new_exclude;
1495 
1496       /* xgettext:c-format */
1497       inform (_("Excluding symbol: %s"), exclude_string);
1498     }
1499 
1500   free (local_copy);
1501 }
1502 
1503 /* See if STRING is on the list of symbols to exclude.  */
1504 
1505 static bool
1506 match_exclude (const char *string)
1507 {
1508   struct string_list *excl_item;
1509 
1510   for (excl_item = excludes; excl_item; excl_item = excl_item->next)
1511     if (strcmp (string, excl_item->string) == 0)
1512       return true;
1513   return false;
1514 }
1515 
1516 /* Add the default list of symbols to exclude.  */
1517 
1518 static void
1519 set_default_excludes (void)
1520 {
1521   add_excludes (default_excludes);
1522 }
1523 
1524 /* Choose which symbols to export.  */
1525 
1526 static long
1527 filter_symbols (bfd *abfd, void *minisyms, long symcount, unsigned int size)
1528 {
1529   bfd_byte *from, *fromend, *to;
1530   asymbol *store;
1531 
1532   store = bfd_make_empty_symbol (abfd);
1533   if (store == NULL)
1534     bfd_fatal (bfd_get_filename (abfd));
1535 
1536   from = (bfd_byte *) minisyms;
1537   fromend = from + symcount * size;
1538   to = (bfd_byte *) minisyms;
1539 
1540   for (; from < fromend; from += size)
1541     {
1542       int keep = 0;
1543       asymbol *sym;
1544 
1545       sym = bfd_minisymbol_to_symbol (abfd, false, (const void *) from, store);
1546       if (sym == NULL)
1547 	bfd_fatal (bfd_get_filename (abfd));
1548 
1549       /* Check for external and defined only symbols.  */
1550       keep = (((sym->flags & BSF_GLOBAL) != 0
1551 	       || (sym->flags & BSF_WEAK) != 0
1552 	       || bfd_is_com_section (sym->section))
1553 	      && ! bfd_is_und_section (sym->section));
1554 
1555       keep = keep && ! match_exclude (sym->name);
1556 
1557       if (keep)
1558 	{
1559 	  memcpy (to, from, size);
1560 	  to += size;
1561 	}
1562     }
1563 
1564   return (to - (bfd_byte *) minisyms) / size;
1565 }
1566 
1567 /* Export all symbols in ABFD, except for ones we were told not to
1568    export.  */
1569 
1570 static void
1571 scan_all_symbols (bfd *abfd)
1572 {
1573   long symcount;
1574   void *minisyms;
1575   unsigned int size;
1576 
1577   /* Ignore bfds with an import descriptor table.  We assume that any
1578      such BFD contains symbols which are exported from another DLL,
1579      and we don't want to reexport them from here.  */
1580   if (bfd_get_section_by_name (abfd, ".idata$4"))
1581     return;
1582 
1583   if (! (bfd_get_file_flags (abfd) & HAS_SYMS))
1584     {
1585       /* xgettext:c-format */
1586       non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1587       return;
1588     }
1589 
1590   symcount = bfd_read_minisymbols (abfd, false, &minisyms, &size);
1591   if (symcount < 0)
1592     bfd_fatal (bfd_get_filename (abfd));
1593 
1594   if (symcount == 0)
1595     {
1596       /* xgettext:c-format */
1597       non_fatal (_("%s: no symbols"), bfd_get_filename (abfd));
1598       return;
1599     }
1600 
1601   /* Discard the symbols we don't want to export.  It's OK to do this
1602      in place; we'll free the storage anyway.  */
1603 
1604   symcount = filter_symbols (abfd, minisyms, symcount, size);
1605   scan_filtered_symbols (abfd, minisyms, symcount, size);
1606 
1607   free (minisyms);
1608 }
1609 
1610 /* Look at the object file to decide which symbols to export.  */
1611 
1612 static void
1613 scan_open_obj_file (bfd *abfd)
1614 {
1615   if (export_all_symbols)
1616     scan_all_symbols (abfd);
1617   else
1618     scan_drectve_symbols (abfd);
1619 
1620   /* FIXME: we ought to read in and block out the base relocations.  */
1621 
1622   /* xgettext:c-format */
1623   inform (_("Done reading %s"), bfd_get_filename (abfd));
1624 }
1625 
1626 static void
1627 scan_obj_file (const char *filename)
1628 {
1629   bfd * f = bfd_openr (filename, 0);
1630 
1631   if (!f)
1632     /* xgettext:c-format */
1633     fatal (_("Unable to open object file: %s: %s"), filename, bfd_get_errmsg ());
1634 
1635   /* xgettext:c-format */
1636   inform (_("Scanning object file %s"), filename);
1637 
1638   if (bfd_check_format (f, bfd_archive))
1639     {
1640       bfd *arfile = bfd_openr_next_archived_file (f, 0);
1641       while (arfile)
1642 	{
1643 	  bfd *next;
1644 	  if (bfd_check_format (arfile, bfd_object))
1645 	    scan_open_obj_file (arfile);
1646 	  next = bfd_openr_next_archived_file (f, arfile);
1647 	  bfd_close (arfile);
1648 	  /* PR 17512: file: 58715298.  */
1649 	  if (next == arfile)
1650 	    break;
1651 	  arfile = next;
1652 	}
1653 
1654 #ifdef DLLTOOL_MCORE_ELF
1655       if (mcore_elf_out_file)
1656 	inform (_("Cannot produce mcore-elf dll from archive file: %s"), filename);
1657 #endif
1658     }
1659   else if (bfd_check_format (f, bfd_object))
1660     {
1661       scan_open_obj_file (f);
1662 
1663 #ifdef DLLTOOL_MCORE_ELF
1664       if (mcore_elf_out_file)
1665 	mcore_elf_cache_filename (filename);
1666 #endif
1667     }
1668 
1669   bfd_close (f);
1670 }
1671 
1672 
1673 
1674 static void
1675 dump_def_info (FILE *f)
1676 {
1677   int i;
1678   export_type *exp;
1679   fprintf (f, "%s ", ASM_C);
1680   for (i = 0; oav[i]; i++)
1681     fprintf (f, "%s ", oav[i]);
1682   fprintf (f, "\n");
1683   for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1684     {
1685       fprintf (f, "%s  %d = %s %s @ %d %s%s%s%s%s%s\n",
1686 	       ASM_C,
1687 	       i,
1688 	       exp->name,
1689 	       exp->internal_name,
1690 	       exp->ordinal,
1691 	       exp->noname ? "NONAME " : "",
1692 	       exp->private ? "PRIVATE " : "",
1693 	       exp->constant ? "CONSTANT" : "",
1694 	       exp->data ? "DATA" : "",
1695 	       exp->its_name ? " ==" : "",
1696 	       exp->its_name ? exp->its_name : "");
1697     }
1698 }
1699 
1700 /* Generate the .exp file.  */
1701 
1702 static int
1703 sfunc (const void *a, const void *b)
1704 {
1705   if (*(const bfd_vma *) a == *(const bfd_vma *) b)
1706     return 0;
1707 
1708   return ((*(const bfd_vma *) a > *(const bfd_vma *) b) ? 1 : -1);
1709 }
1710 
1711 static void
1712 flush_page (FILE *f, bfd_vma *need, bfd_vma page_addr, int on_page)
1713 {
1714   int i;
1715 
1716   /* Flush this page.  */
1717   fprintf (f, "\t%s\t0x%08x\t%s Starting RVA for chunk\n",
1718 	   ASM_LONG,
1719 	   (int) page_addr,
1720 	   ASM_C);
1721   fprintf (f, "\t%s\t0x%x\t%s Size of block\n",
1722 	   ASM_LONG,
1723 	   (on_page * 2) + (on_page & 1) * 2 + 8,
1724 	   ASM_C);
1725 
1726   for (i = 0; i < on_page; i++)
1727     {
1728       bfd_vma needed = need[i];
1729 
1730       if (needed)
1731         {
1732 	  if (!create_for_pep)
1733 	    {
1734 	      /* Relocation via HIGHLOW.  */
1735 	      needed = ((needed - page_addr) | 0x3000) & 0xffff;
1736 	    }
1737 	  else
1738 	    {
1739 	      /* Relocation via DIR64.  */
1740 	      needed = ((needed - page_addr) | 0xa000) & 0xffff;
1741 	    }
1742 	}
1743 
1744       fprintf (f, "\t%s\t0x%lx\n", ASM_SHORT, (long) needed);
1745     }
1746 
1747   /* And padding */
1748   if (on_page & 1)
1749     fprintf (f, "\t%s\t0x%x\n", ASM_SHORT, 0 | 0x0000);
1750 }
1751 
1752 static void
1753 gen_def_file (void)
1754 {
1755   int i;
1756   export_type *exp;
1757 
1758   inform (_("Adding exports to output file"));
1759 
1760   fprintf (output_def, ";");
1761   for (i = 0; oav[i]; i++)
1762     fprintf (output_def, " %s", oav[i]);
1763 
1764   fprintf (output_def, "\nEXPORTS\n");
1765 
1766   for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
1767     {
1768       char *quote = strchr (exp->name, '.') ? "\"" : "";
1769       char *res = cplus_demangle (exp->internal_name, DMGL_ANSI | DMGL_PARAMS);
1770 
1771       if (res)
1772 	{
1773 	  fprintf (output_def,";\t%s\n", res);
1774 	  free (res);
1775 	}
1776 
1777       if (strcmp (exp->name, exp->internal_name) == 0)
1778 	{
1779 	  fprintf (output_def, "\t%s%s%s @ %d%s%s%s%s%s\n",
1780 		   quote,
1781 		   exp->name,
1782 		   quote,
1783 		   exp->ordinal,
1784 		   exp->noname ? " NONAME" : "",
1785 		   exp->private ? "PRIVATE " : "",
1786 		   exp->data ? " DATA" : "",
1787 		   exp->its_name ? " ==" : "",
1788 		   exp->its_name ? exp->its_name : "");
1789 	}
1790       else
1791 	{
1792 	  char * quote1 = strchr (exp->internal_name, '.') ? "\"" : "";
1793 	  /* char *alias =  */
1794 	  fprintf (output_def, "\t%s%s%s = %s%s%s @ %d%s%s%s%s%s\n",
1795 		   quote,
1796 		   exp->name,
1797 		   quote,
1798 		   quote1,
1799 		   exp->internal_name,
1800 		   quote1,
1801 		   exp->ordinal,
1802 		   exp->noname ? " NONAME" : "",
1803 		   exp->private ? "PRIVATE " : "",
1804 		   exp->data ? " DATA" : "",
1805 		   exp->its_name ? " ==" : "",
1806 		   exp->its_name ? exp->its_name : "");
1807 	}
1808     }
1809 
1810   inform (_("Added exports to output file"));
1811 }
1812 
1813 /* generate_idata_ofile generates the portable assembly source code
1814    for the idata sections.  It appends the source code to the end of
1815    the file.  */
1816 
1817 static void
1818 generate_idata_ofile (FILE *filvar)
1819 {
1820   iheadtype *headptr;
1821   ifunctype *funcptr;
1822   int        headindex;
1823   int        funcindex;
1824   int	     nheads;
1825 
1826   if (import_list == NULL)
1827     return;
1828 
1829   fprintf (filvar, "%s Import data sections\n", ASM_C);
1830   fprintf (filvar, "\n\t.section\t.idata$2\n");
1831   fprintf (filvar, "\t%s\tdoi_idata\n", ASM_GLOBAL);
1832   fprintf (filvar, "doi_idata:\n");
1833 
1834   nheads = 0;
1835   for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1836     {
1837       fprintf (filvar, "\t%slistone%d%s\t%s %s\n",
1838 	       ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER,
1839 	       ASM_C, headptr->dllname);
1840       fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1841       fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1842       fprintf (filvar, "\t%sdllname%d%s\n",
1843 	       ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1844       fprintf (filvar, "\t%slisttwo%d%s\n\n",
1845 	       ASM_RVA_BEFORE, nheads, ASM_RVA_AFTER);
1846       nheads++;
1847     }
1848 
1849   fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL record at */
1850   fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* end of idata$2 */
1851   fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* section        */
1852   fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1853   fprintf (filvar, "\t%s\t0\n", ASM_LONG);
1854 
1855   fprintf (filvar, "\n\t.section\t.idata$4\n");
1856   headindex = 0;
1857   for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1858     {
1859       fprintf (filvar, "listone%d:\n", headindex);
1860       for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1861         {
1862 	  if (create_for_pep)
1863 	    fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1864 		     ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1865 		     ASM_LONG);
1866 	  else
1867 	    fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1868 		     ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1869         }
1870       if (create_for_pep)
1871 	fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1872       else
1873 	fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list.  */
1874       headindex++;
1875     }
1876 
1877   fprintf (filvar, "\n\t.section\t.idata$5\n");
1878   headindex = 0;
1879   for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1880     {
1881       fprintf (filvar, "listtwo%d:\n", headindex);
1882       for (funcindex = 0; funcindex < headptr->nfuncs; funcindex++)
1883         {
1884 	  if (create_for_pep)
1885 	    fprintf (filvar, "\t%sfuncptr%d_%d%s\n%s\t0\n",
1886 		     ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER,
1887 		     ASM_LONG);
1888 	  else
1889 	    fprintf (filvar, "\t%sfuncptr%d_%d%s\n",
1890 		     ASM_RVA_BEFORE, headindex, funcindex, ASM_RVA_AFTER);
1891         }
1892       if (create_for_pep)
1893 	fprintf (filvar, "\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
1894       else
1895 	fprintf (filvar, "\t%s\t0\n", ASM_LONG); /* NULL terminating list.  */
1896       headindex++;
1897     }
1898 
1899   fprintf (filvar, "\n\t.section\t.idata$6\n");
1900   headindex = 0;
1901   for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1902     {
1903       funcindex = 0;
1904       for (funcptr = headptr->funchead; funcptr != NULL;
1905 	   funcptr = funcptr->next)
1906 	{
1907 	  fprintf (filvar,"funcptr%d_%d:\n", headindex, funcindex);
1908 	  fprintf (filvar,"\t%s\t%d\n", ASM_SHORT,
1909 		   ((funcptr->ord) & 0xFFFF));
1910 	  fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT,
1911 	    (funcptr->its_name ? funcptr->its_name : funcptr->name));
1912 	  fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1913 	  funcindex++;
1914 	}
1915       headindex++;
1916     }
1917 
1918   fprintf (filvar, "\n\t.section\t.idata$7\n");
1919   headindex = 0;
1920   for (headptr = import_list; headptr != NULL; headptr = headptr->next)
1921     {
1922       fprintf (filvar,"dllname%d:\n", headindex);
1923       fprintf (filvar,"\t%s\t\"%s\"\n", ASM_TEXT, headptr->dllname);
1924       fprintf (filvar,"\t%s\t0\n", ASM_BYTE);
1925       headindex++;
1926     }
1927 }
1928 
1929 /* Assemble the specified file.  */
1930 static void
1931 assemble_file (const char * source, const char * dest)
1932 {
1933   char * cmd;
1934 
1935   cmd = xmalloc (strlen (ASM_SWITCHES) + strlen (as_flags)
1936 		 + strlen (source) + strlen (dest) + 50);
1937 
1938   sprintf (cmd, "%s %s -o %s %s", ASM_SWITCHES, as_flags, dest, source);
1939 
1940   run (as_name, cmd);
1941   free (cmd);
1942 }
1943 
1944 static const char * temp_file_to_remove[5];
1945 #define TEMP_EXPORT_FILE 0
1946 #define TEMP_HEAD_FILE   1
1947 #define TEMP_TAIL_FILE   2
1948 #define TEMP_HEAD_O_FILE 3
1949 #define TEMP_TAIL_O_FILE 4
1950 
1951 static void
1952 unlink_temp_files (void)
1953 {
1954   unsigned i;
1955 
1956   if (dontdeltemps > 0)
1957     return;
1958 
1959   for (i = 0; i < ARRAY_SIZE (temp_file_to_remove); i++)
1960     {
1961       if (temp_file_to_remove[i])
1962 	{
1963 	  unlink (temp_file_to_remove[i]);
1964 	  temp_file_to_remove[i] = NULL;
1965 	}
1966     }
1967 }
1968 
1969 static void
1970 gen_exp_file (void)
1971 {
1972   FILE *f;
1973   int i;
1974   export_type *exp;
1975   dlist_type *dl;
1976 
1977   /* xgettext:c-format */
1978   inform (_("Generating export file: %s"), exp_name);
1979 
1980   f = fopen (TMP_ASM, FOPEN_WT);
1981   if (!f)
1982     /* xgettext:c-format */
1983     fatal (_("Unable to open temporary assembler file: %s"), TMP_ASM);
1984 
1985   temp_file_to_remove[TEMP_EXPORT_FILE] = TMP_ASM;
1986 
1987   /* xgettext:c-format */
1988   inform (_("Opened temporary file: %s"), TMP_ASM);
1989 
1990   dump_def_info (f);
1991 
1992   if (d_exports)
1993     {
1994       fprintf (f, "\t.section	.edata\n\n");
1995       fprintf (f, "\t%s	0	%s Allways 0\n", ASM_LONG, ASM_C);
1996       fprintf (f, "\t%s	0x%lx	%s Time and date\n", ASM_LONG,
1997 	       (unsigned long) time(0), ASM_C);
1998       fprintf (f, "\t%s	0	%s Major and Minor version\n", ASM_LONG, ASM_C);
1999       fprintf (f, "\t%sname%s	%s Ptr to name of dll\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2000       fprintf (f, "\t%s	%d	%s Starting ordinal of exports\n", ASM_LONG, d_low_ord, ASM_C);
2001 
2002 
2003       fprintf (f, "\t%s	%d	%s Number of functions\n", ASM_LONG, d_high_ord - d_low_ord + 1, ASM_C);
2004       fprintf(f,"\t%s named funcs %d, low ord %d, high ord %d\n",
2005 	      ASM_C,
2006 	      d_named_nfuncs, d_low_ord, d_high_ord);
2007       fprintf (f, "\t%s	%d	%s Number of names\n", ASM_LONG,
2008 	       show_allnames ? d_high_ord - d_low_ord + 1 : d_named_nfuncs, ASM_C);
2009       fprintf (f, "\t%safuncs%s  %s Address of functions\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2010 
2011       fprintf (f, "\t%sanames%s	%s Address of Name Pointer Table\n",
2012 	       ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2013 
2014       fprintf (f, "\t%sanords%s	%s Address of ordinals\n", ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2015 
2016       fprintf (f, "name:	%s	\"%s\"\n", ASM_TEXT, dll_name);
2017 
2018 
2019       fprintf(f,"%s Export address Table\n", ASM_C);
2020       fprintf(f,"\t%s\n", ASM_ALIGN_LONG);
2021       fprintf (f, "afuncs:\n");
2022       i = d_low_ord;
2023 
2024       for (exp = d_exports; exp; exp = exp->next)
2025 	{
2026 	  if (exp->ordinal != i)
2027 	    {
2028 	      while (i < exp->ordinal)
2029 		{
2030 		  fprintf(f,"\t%s\t0\n", ASM_LONG);
2031 		  i++;
2032 		}
2033 	    }
2034 
2035 	  if (exp->forward == 0)
2036 	    {
2037 	      if (exp->internal_name[0] == '@')
2038 		fprintf (f, "\t%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2039 			 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2040 	      else
2041 		fprintf (f, "\t%s%s%s%s\t%s %d\n", ASM_RVA_BEFORE,
2042 			 ASM_PREFIX (exp->internal_name),
2043 			 exp->internal_name, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2044 	    }
2045 	  else
2046 	    fprintf (f, "\t%sf%d%s\t%s %d\n", ASM_RVA_BEFORE,
2047 		     exp->forward, ASM_RVA_AFTER, ASM_C, exp->ordinal);
2048 	  i++;
2049 	}
2050 
2051       fprintf (f,"%s Export Name Pointer Table\n", ASM_C);
2052       fprintf (f, "anames:\n");
2053 
2054       for (i = 0; (exp = d_exports_lexically[i]); i++)
2055 	{
2056 	  if (!exp->noname || show_allnames)
2057 	    fprintf (f, "\t%sn%d%s\n",
2058 		     ASM_RVA_BEFORE, exp->ordinal, ASM_RVA_AFTER);
2059 	}
2060 
2061       fprintf (f,"%s Export Ordinal Table\n", ASM_C);
2062       fprintf (f, "anords:\n");
2063       for (i = 0; (exp = d_exports_lexically[i]); i++)
2064 	{
2065 	  if (!exp->noname || show_allnames)
2066 	    fprintf (f, "\t%s	%d\n", ASM_SHORT, exp->ordinal - d_low_ord);
2067 	}
2068 
2069       fprintf(f,"%s Export Name Table\n", ASM_C);
2070       for (i = 0; (exp = d_exports_lexically[i]); i++)
2071 	{
2072 	  if (!exp->noname || show_allnames)
2073 	    fprintf (f, "n%d:	%s	\"%s\"\n",
2074 		     exp->ordinal, ASM_TEXT,
2075 		     (exp->its_name ? exp->its_name : xlate (exp->name)));
2076 	  if (exp->forward != 0)
2077 	    fprintf (f, "f%d:	%s	\"%s\"\n",
2078 		     exp->forward, ASM_TEXT, exp->internal_name);
2079 	}
2080 
2081       if (a_list)
2082 	{
2083 	  fprintf (f, "\t.section %s\n", DRECTVE_SECTION_NAME);
2084 	  for (dl = a_list; dl; dl = dl->next)
2085 	    {
2086 	      fprintf (f, "\t%s\t\"%s\"\n", ASM_TEXT, dl->text);
2087 	    }
2088 	}
2089 
2090       if (d_list)
2091 	{
2092 	  fprintf (f, "\t.section .rdata\n");
2093 	  for (dl = d_list; dl; dl = dl->next)
2094 	    {
2095 	      char *p;
2096 	      int l;
2097 
2098 	      /* We don't output as ascii because there can
2099 	         be quote characters in the string.  */
2100 	      l = 0;
2101 	      for (p = dl->text; *p; p++)
2102 		{
2103 		  if (l == 0)
2104 		    fprintf (f, "\t%s\t", ASM_BYTE);
2105 		  else
2106 		    fprintf (f, ",");
2107 		  fprintf (f, "%d", *p);
2108 		  if (p[1] == 0)
2109 		    {
2110 		      fprintf (f, ",0\n");
2111 		      break;
2112 		    }
2113 		  if (++l == 10)
2114 		    {
2115 		      fprintf (f, "\n");
2116 		      l = 0;
2117 		    }
2118 		}
2119 	    }
2120 	}
2121     }
2122 
2123   /* Add to the output file a way of getting to the exported names
2124      without using the import library.  */
2125   if (add_indirect)
2126     {
2127       fprintf (f, "\t.section\t.rdata\n");
2128       for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
2129 	if (!exp->noname || show_allnames)
2130 	  {
2131 	    /* We use a single underscore for MS compatibility, and a
2132                double underscore for backward compatibility with old
2133                cygwin releases.  */
2134 	    if (create_compat_implib)
2135 	      fprintf (f, "\t%s\t__imp_%s\n", ASM_GLOBAL, exp->name);
2136 	    fprintf (f, "\t%s\t_imp_%s%s\n", ASM_GLOBAL,
2137 	    	     (!leading_underscore ? "" : "_"), exp->name);
2138 	    if (create_compat_implib)
2139 	      fprintf (f, "__imp_%s:\n", exp->name);
2140 	    fprintf (f, "_imp_%s%s:\n", (!leading_underscore ? "" : "_"), exp->name);
2141 	    fprintf (f, "\t%s\t%s\n", ASM_LONG, exp->name);
2142 	  }
2143     }
2144 
2145   /* Dump the reloc section if a base file is provided.  */
2146   if (base_file)
2147     {
2148       bfd_vma addr;
2149       bfd_vma need[COFF_PAGE_SIZE];
2150       bfd_vma page_addr;
2151       bfd_size_type numbytes;
2152       int num_entries;
2153       bfd_vma *copy;
2154       int j;
2155       int on_page;
2156       fprintf (f, "\t.section\t.init\n");
2157       fprintf (f, "lab:\n");
2158 
2159       fseek (base_file, 0, SEEK_END);
2160       numbytes = ftell (base_file);
2161       fseek (base_file, 0, SEEK_SET);
2162       copy = xmalloc (numbytes);
2163       if (fread (copy, 1, numbytes, base_file) < numbytes)
2164 	fatal (_("failed to read the number of entries from base file"));
2165       num_entries = numbytes / sizeof (bfd_vma);
2166 
2167 
2168       fprintf (f, "\t.section\t.reloc\n");
2169       if (num_entries)
2170 	{
2171 	  int src;
2172 	  int dst = 0;
2173 	  bfd_vma last = (bfd_vma) -1;
2174 	  qsort (copy, num_entries, sizeof (bfd_vma), sfunc);
2175 	  /* Delete duplicates */
2176 	  for (src = 0; src < num_entries; src++)
2177 	    {
2178 	      if (last != copy[src])
2179 		last = copy[dst++] = copy[src];
2180 	    }
2181 	  num_entries = dst;
2182 	  addr = copy[0];
2183 	  page_addr = addr & PAGE_MASK;		/* work out the page addr */
2184 	  on_page = 0;
2185 	  for (j = 0; j < num_entries; j++)
2186 	    {
2187 	      addr = copy[j];
2188 	      if ((addr & PAGE_MASK) != page_addr)
2189 		{
2190 		  flush_page (f, need, page_addr, on_page);
2191 		  on_page = 0;
2192 		  page_addr = addr & PAGE_MASK;
2193 		}
2194 	      need[on_page++] = addr;
2195 	    }
2196 	  flush_page (f, need, page_addr, on_page);
2197 
2198 /*	  fprintf (f, "\t%s\t0,0\t%s End\n", ASM_LONG, ASM_C);*/
2199 	}
2200     }
2201 
2202   generate_idata_ofile (f);
2203 
2204   fclose (f);
2205 
2206   /* Assemble the file.  */
2207   assemble_file (TMP_ASM, exp_name);
2208 
2209   if (dontdeltemps == 0)
2210     {
2211       temp_file_to_remove[TEMP_EXPORT_FILE] = NULL;
2212       unlink (TMP_ASM);
2213     }
2214 
2215   inform (_("Generated exports file"));
2216 }
2217 
2218 static const char *
2219 xlate (const char *name)
2220 {
2221   int lead_at = (*name == '@');
2222   int is_stdcall = (!lead_at && strchr (name, '@') != NULL);
2223 
2224   if (!lead_at && (add_underscore
2225 		   || (add_stdcall_underscore && is_stdcall)))
2226     {
2227       char *copy = xmalloc (strlen (name) + 2);
2228 
2229       copy[0] = '_';
2230       strcpy (copy + 1, name);
2231       name = copy;
2232     }
2233 
2234   if (killat)
2235     {
2236       char *p;
2237 
2238       name += lead_at;
2239       /* PR 9766: Look for the last @ sign in the name.  */
2240       p = strrchr (name, '@');
2241       if (p && ISDIGIT (p[1]))
2242 	*p = 0;
2243     }
2244   return name;
2245 }
2246 
2247 typedef struct
2248 {
2249   int id;
2250   const char *name;
2251   int flags;
2252   int align;
2253   asection *sec;
2254   asymbol *sym;
2255   asymbol **sympp;
2256   int size;
2257   unsigned char *data;
2258 } sinfo;
2259 
2260 #define INIT_SEC_DATA(id, name, flags, align) \
2261         { id, name, flags, align, NULL, NULL, NULL, 0, NULL }
2262 
2263 #define TEXT 0
2264 #define DATA 1
2265 #define BSS 2
2266 #define IDATA7 3
2267 #define IDATA5 4
2268 #define IDATA4 5
2269 #define IDATA6 6
2270 
2271 #define NSECS 7
2272 
2273 #define TEXT_SEC_FLAGS   \
2274         (SEC_ALLOC | SEC_LOAD | SEC_CODE | SEC_READONLY | SEC_HAS_CONTENTS)
2275 #define DATA_SEC_FLAGS   (SEC_ALLOC | SEC_LOAD | SEC_DATA)
2276 #define BSS_SEC_FLAGS     SEC_ALLOC
2277 
2278 static sinfo secdata[NSECS] =
2279 {
2280   INIT_SEC_DATA (TEXT,   ".text",    TEXT_SEC_FLAGS,   2),
2281   INIT_SEC_DATA (DATA,   ".data",    DATA_SEC_FLAGS,   2),
2282   INIT_SEC_DATA (BSS,    ".bss",     BSS_SEC_FLAGS,    2),
2283   INIT_SEC_DATA (IDATA7, ".idata$7", SEC_HAS_CONTENTS, 2),
2284   INIT_SEC_DATA (IDATA5, ".idata$5", SEC_HAS_CONTENTS, 2),
2285   INIT_SEC_DATA (IDATA4, ".idata$4", SEC_HAS_CONTENTS, 2),
2286   INIT_SEC_DATA (IDATA6, ".idata$6", SEC_HAS_CONTENTS, 1)
2287 };
2288 
2289 /* This is what we're trying to make.  We generate the imp symbols with
2290    both single and double underscores, for compatibility.
2291 
2292 	.text
2293 	.global	_GetFileVersionInfoSizeW@8
2294 	.global	__imp_GetFileVersionInfoSizeW@8
2295 _GetFileVersionInfoSizeW@8:
2296 	jmp *	__imp_GetFileVersionInfoSizeW@8
2297 	.section	.idata$7	# To force loading of head
2298 	.long	__version_a_head
2299 # Import Address Table
2300 	.section	.idata$5
2301 __imp_GetFileVersionInfoSizeW@8:
2302 	.rva	ID2
2303 
2304 # Import Lookup Table
2305 	.section	.idata$4
2306 	.rva	ID2
2307 # Hint/Name table
2308 	.section	.idata$6
2309 ID2:	.short	2
2310 	.asciz	"GetFileVersionInfoSizeW"  */
2311 
2312 static char *
2313 make_label (const char *prefix, const char *name)
2314 {
2315   int len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2316   char *copy = xmalloc (len + 1);
2317 
2318   strcpy (copy, ASM_PREFIX (name));
2319   strcat (copy, prefix);
2320   strcat (copy, name);
2321   return copy;
2322 }
2323 
2324 static char *
2325 make_imp_label (const char *prefix, const char *name)
2326 {
2327   int len;
2328   char *copy;
2329 
2330   if (name[0] == '@')
2331     {
2332       len = strlen (prefix) + strlen (name);
2333       copy = xmalloc (len + 1);
2334       strcpy (copy, prefix);
2335       strcat (copy, name);
2336     }
2337   else
2338     {
2339       len = strlen (ASM_PREFIX (name)) + strlen (prefix) + strlen (name);
2340       copy = xmalloc (len + 1);
2341       strcpy (copy, prefix);
2342       strcat (copy, ASM_PREFIX (name));
2343       strcat (copy, name);
2344     }
2345   return copy;
2346 }
2347 
2348 static bfd *
2349 make_one_lib_file (export_type *exp, int i, int delay)
2350 {
2351   bfd *      abfd;
2352   asymbol *  exp_label;
2353   asymbol *  iname = 0;
2354   asymbol *  iname2;
2355   asymbol *  iname_lab;
2356   asymbol ** iname_lab_pp;
2357   asymbol ** iname_pp;
2358 #ifndef EXTRA
2359 #define EXTRA    0
2360 #endif
2361   asymbol *  ptrs[NSECS + 4 + EXTRA + 1];
2362   flagword   applicable;
2363   char *     outname = xmalloc (strlen (TMP_STUB) + 10);
2364   int        oidx = 0;
2365 
2366 
2367   sprintf (outname, "%s%05d.o", TMP_STUB, i);
2368 
2369   abfd = bfd_openw (outname, HOW_BFD_WRITE_TARGET);
2370 
2371   if (!abfd)
2372     /* xgettext:c-format */
2373     fatal (_("bfd_open failed open stub file: %s: %s"),
2374 	   outname, bfd_get_errmsg ());
2375 
2376   /* xgettext:c-format */
2377   inform (_("Creating stub file: %s"), outname);
2378 
2379   bfd_set_format (abfd, bfd_object);
2380   bfd_set_arch_mach (abfd, HOW_BFD_ARCH, 0);
2381 
2382 #ifdef DLLTOOL_ARM
2383   if (machine == MARM_INTERWORK || machine == MTHUMB)
2384     bfd_set_private_flags (abfd, F_INTERWORK);
2385 #endif
2386 
2387   applicable = bfd_applicable_section_flags (abfd);
2388 
2389   /* First make symbols for the sections.  */
2390   for (i = 0; i < NSECS; i++)
2391     {
2392       sinfo *si = secdata + i;
2393 
2394       if (si->id != i)
2395 	abort ();
2396       si->sec = bfd_make_section_old_way (abfd, si->name);
2397       bfd_set_section_flags (si->sec, si->flags & applicable);
2398 
2399       bfd_set_section_alignment (si->sec, si->align);
2400       si->sec->output_section = si->sec;
2401       si->sym = bfd_make_empty_symbol(abfd);
2402       si->sym->name = si->sec->name;
2403       si->sym->section = si->sec;
2404       si->sym->flags = BSF_LOCAL;
2405       si->sym->value = 0;
2406       ptrs[oidx] = si->sym;
2407       si->sympp = ptrs + oidx;
2408       si->size = 0;
2409       si->data = NULL;
2410 
2411       oidx++;
2412     }
2413 
2414   if (! exp->data)
2415     {
2416       exp_label = bfd_make_empty_symbol (abfd);
2417       exp_label->name = make_imp_label ("", exp->name);
2418       exp_label->section = secdata[TEXT].sec;
2419       exp_label->flags = BSF_GLOBAL;
2420       exp_label->value = 0;
2421 
2422 #ifdef DLLTOOL_ARM
2423       if (machine == MTHUMB)
2424 	bfd_coff_set_symbol_class (abfd, exp_label, C_THUMBEXTFUNC);
2425 #endif
2426       ptrs[oidx++] = exp_label;
2427     }
2428 
2429   /* Generate imp symbols with one underscore for Microsoft
2430      compatibility, and with two underscores for backward
2431      compatibility with old versions of cygwin.  */
2432   if (create_compat_implib)
2433     {
2434       iname = bfd_make_empty_symbol (abfd);
2435       iname->name = make_imp_label ("___imp", exp->name);
2436       iname->section = secdata[IDATA5].sec;
2437       iname->flags = BSF_GLOBAL;
2438       iname->value = 0;
2439     }
2440 
2441   iname2 = bfd_make_empty_symbol (abfd);
2442   iname2->name = make_imp_label ("__imp_", exp->name);
2443   iname2->section = secdata[IDATA5].sec;
2444   iname2->flags = BSF_GLOBAL;
2445   iname2->value = 0;
2446 
2447   iname_lab = bfd_make_empty_symbol (abfd);
2448 
2449   iname_lab->name = head_label;
2450   iname_lab->section = bfd_und_section_ptr;
2451   iname_lab->flags = 0;
2452   iname_lab->value = 0;
2453 
2454   iname_pp = ptrs + oidx;
2455   if (create_compat_implib)
2456     ptrs[oidx++] = iname;
2457   ptrs[oidx++] = iname2;
2458 
2459   iname_lab_pp = ptrs + oidx;
2460   ptrs[oidx++] = iname_lab;
2461 
2462   ptrs[oidx] = 0;
2463 
2464   for (i = 0; i < NSECS; i++)
2465     {
2466       sinfo *si = secdata + i;
2467       asection *sec = si->sec;
2468       arelent *rel, *rel2 = 0, *rel3 = 0;
2469       arelent **rpp;
2470 
2471       switch (i)
2472 	{
2473 	case TEXT:
2474 	  if (! exp->data)
2475 	    {
2476 	      si->size = HOW_JTAB_SIZE;
2477 	      si->data = xmalloc (HOW_JTAB_SIZE);
2478 	      memcpy (si->data, HOW_JTAB, HOW_JTAB_SIZE);
2479 
2480 	      /* Add the reloc into idata$5.  */
2481 	      rel = xmalloc (sizeof (arelent));
2482 
2483 	      rpp = xmalloc (sizeof (arelent *) * (delay ? 4 : 2));
2484 	      rpp[0] = rel;
2485 	      rpp[1] = 0;
2486 
2487 	      rel->address = HOW_JTAB_ROFF;
2488 	      rel->addend = 0;
2489 
2490 	      if (delay)
2491 	        {
2492 	          rel2 = xmalloc (sizeof (arelent));
2493 	          rpp[1] = rel2;
2494 	          rel2->address = HOW_JTAB_ROFF2;
2495 	          rel2->addend = 0;
2496 	          rel3 = xmalloc (sizeof (arelent));
2497 	          rpp[2] = rel3;
2498 	          rel3->address = HOW_JTAB_ROFF3;
2499 	          rel3->addend = 0;
2500 	          rpp[3] = 0;
2501 	        }
2502 
2503 	      if (machine == MX86)
2504 		{
2505 		  rel->howto = bfd_reloc_type_lookup (abfd,
2506 						      BFD_RELOC_32_PCREL);
2507 		  rel->sym_ptr_ptr = iname_pp;
2508 		}
2509 	      else
2510 		{
2511 		  rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2512 		  rel->sym_ptr_ptr = secdata[IDATA5].sympp;
2513 		}
2514 
2515 	      if (delay)
2516 	        {
2517 		  if (machine == MX86)
2518 		   rel2->howto = bfd_reloc_type_lookup (abfd,
2519 							BFD_RELOC_32_PCREL);
2520 	          else
2521 	            rel2->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2522 	          rel2->sym_ptr_ptr = rel->sym_ptr_ptr;
2523 	          rel3->howto = bfd_reloc_type_lookup (abfd,
2524 						       BFD_RELOC_32_PCREL);
2525 	          rel3->sym_ptr_ptr = iname_lab_pp;
2526 	        }
2527 
2528 	      sec->orelocation = rpp;
2529 	      sec->reloc_count = delay ? 3 : 1;
2530 	    }
2531 	  break;
2532 
2533 	case IDATA5:
2534 	  if (delay)
2535 	    {
2536 	      si->size = create_for_pep ? 8 : 4;
2537 	      si->data = xmalloc (si->size);
2538 	      sec->reloc_count = 1;
2539 	      memset (si->data, 0, si->size);
2540 	      /* Point after jmp [__imp_...] instruction.  */
2541 	      si->data[0] = 6;
2542 	      rel = xmalloc (sizeof (arelent));
2543 	      rpp = xmalloc (sizeof (arelent *) * 2);
2544 	      rpp[0] = rel;
2545 	      rpp[1] = 0;
2546 	      rel->address = 0;
2547 	      rel->addend = 0;
2548 	      if (create_for_pep)
2549 	        rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_64);
2550 	      else
2551 	        rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_32);
2552 	      rel->sym_ptr_ptr = secdata[TEXT].sympp;
2553 	      sec->orelocation = rpp;
2554 	      break;
2555 	    }
2556 	  /* Fall through.  */
2557 
2558 	case IDATA4:
2559 	  /* An idata$4 or idata$5 is one word long, and has an
2560 	     rva to idata$6.  */
2561 
2562 	  if (create_for_pep)
2563 	    {
2564 	      si->data = xmalloc (8);
2565 	      si->size = 8;
2566 	      if (exp->noname)
2567 	        {
2568 		  si->data[0] = exp->ordinal ;
2569 		  si->data[1] = exp->ordinal >> 8;
2570 		  si->data[2] = exp->ordinal >> 16;
2571 		  si->data[3] = exp->ordinal >> 24;
2572 		  si->data[4] = 0;
2573 		  si->data[5] = 0;
2574 		  si->data[6] = 0;
2575 		  si->data[7] = 0x80;
2576 	        }
2577 	      else
2578 	        {
2579 		  sec->reloc_count = 1;
2580 		  memset (si->data, 0, si->size);
2581 		  rel = xmalloc (sizeof (arelent));
2582 		  rpp = xmalloc (sizeof (arelent *) * 2);
2583 		  rpp[0] = rel;
2584 		  rpp[1] = 0;
2585 		  rel->address = 0;
2586 		  rel->addend = 0;
2587 		  rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2588 		  rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2589 		  sec->orelocation = rpp;
2590 	        }
2591 	    }
2592 	  else
2593 	    {
2594 	      si->data = xmalloc (4);
2595 	      si->size = 4;
2596 
2597 	      if (exp->noname)
2598 	        {
2599 		  si->data[0] = exp->ordinal ;
2600 		  si->data[1] = exp->ordinal >> 8;
2601 		  si->data[2] = exp->ordinal >> 16;
2602 		  si->data[3] = 0x80;
2603 	        }
2604 	      else
2605 	        {
2606 		  sec->reloc_count = 1;
2607 		  memset (si->data, 0, si->size);
2608 		  rel = xmalloc (sizeof (arelent));
2609 		  rpp = xmalloc (sizeof (arelent *) * 2);
2610 		  rpp[0] = rel;
2611 		  rpp[1] = 0;
2612 		  rel->address = 0;
2613 		  rel->addend = 0;
2614 		  rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2615 		  rel->sym_ptr_ptr = secdata[IDATA6].sympp;
2616 		  sec->orelocation = rpp;
2617 	      }
2618 	    }
2619 	  break;
2620 
2621 	case IDATA6:
2622 	  if (!exp->noname)
2623 	    {
2624 	      int idx = exp->ordinal;
2625 
2626 	      if (exp->its_name)
2627 	        si->size = strlen (exp->its_name) + 3;
2628 	      else
2629 	        si->size = strlen (xlate (exp->import_name)) + 3;
2630 	      si->data = xmalloc (si->size);
2631 	      memset (si->data, 0, si->size);
2632 	      si->data[0] = idx & 0xff;
2633 	      si->data[1] = idx >> 8;
2634 	      if (exp->its_name)
2635 		strcpy ((char *) si->data + 2, exp->its_name);
2636 	      else
2637 		strcpy ((char *) si->data + 2, xlate (exp->import_name));
2638 	    }
2639 	  break;
2640 	case IDATA7:
2641 	  if (delay)
2642 	    break;
2643 	  si->size = 4;
2644 	  si->data = xmalloc (4);
2645 	  memset (si->data, 0, si->size);
2646 	  rel = xmalloc (sizeof (arelent));
2647 	  rpp = xmalloc (sizeof (arelent *) * 2);
2648 	  rpp[0] = rel;
2649 	  rel->address = 0;
2650 	  rel->addend = 0;
2651 	  rel->howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
2652 	  rel->sym_ptr_ptr = iname_lab_pp;
2653 	  sec->orelocation = rpp;
2654 	  sec->reloc_count = 1;
2655 	  break;
2656 	}
2657     }
2658 
2659   {
2660     bfd_vma vma = 0;
2661     /* Size up all the sections.  */
2662     for (i = 0; i < NSECS; i++)
2663       {
2664 	sinfo *si = secdata + i;
2665 
2666 	bfd_set_section_size (si->sec, si->size);
2667 	bfd_set_section_vma (si->sec, vma);
2668       }
2669   }
2670   /* Write them out.  */
2671   for (i = 0; i < NSECS; i++)
2672     {
2673       sinfo *si = secdata + i;
2674 
2675       if (i == IDATA5 && no_idata5)
2676 	continue;
2677 
2678       if (i == IDATA4 && no_idata4)
2679 	continue;
2680 
2681       bfd_set_section_contents (abfd, si->sec,
2682 				si->data, 0,
2683 				si->size);
2684     }
2685 
2686   bfd_set_symtab (abfd, ptrs, oidx);
2687   bfd_close (abfd);
2688   abfd = bfd_openr (outname, HOW_BFD_READ_TARGET);
2689   if (!abfd)
2690     /* xgettext:c-format */
2691     fatal (_("bfd_open failed reopen stub file: %s: %s"),
2692 	   outname, bfd_get_errmsg ());
2693 
2694   return abfd;
2695 }
2696 
2697 static bfd *
2698 make_head (void)
2699 {
2700   FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2701   bfd *abfd;
2702 
2703   if (f == NULL)
2704     {
2705       fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2706       return NULL;
2707     }
2708 
2709   temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2710 
2711   fprintf (f, "%s IMAGE_IMPORT_DESCRIPTOR\n", ASM_C);
2712   fprintf (f, "\t.section\t.idata$2\n");
2713 
2714   fprintf (f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2715 
2716   fprintf (f, "%s:\n", head_label);
2717 
2718   fprintf (f, "\t%shname%s\t%sPtr to image import by name list\n",
2719 	   ASM_RVA_BEFORE, ASM_RVA_AFTER, ASM_C);
2720 
2721   fprintf (f, "\t%sthis should be the timestamp, but NT sometimes\n", ASM_C);
2722   fprintf (f, "\t%sdoesn't load DLLs when this is set.\n", ASM_C);
2723   fprintf (f, "\t%s\t0\t%s loaded time\n", ASM_LONG, ASM_C);
2724   fprintf (f, "\t%s\t0\t%s Forwarder chain\n", ASM_LONG, ASM_C);
2725   fprintf (f, "\t%s__%s_iname%s\t%s imported dll's name\n",
2726 	   ASM_RVA_BEFORE,
2727 	   imp_name_lab,
2728 	   ASM_RVA_AFTER,
2729 	   ASM_C);
2730   fprintf (f, "\t%sfthunk%s\t%s pointer to firstthunk\n",
2731 	   ASM_RVA_BEFORE,
2732 	   ASM_RVA_AFTER, ASM_C);
2733 
2734   fprintf (f, "%sStuff for compatibility\n", ASM_C);
2735 
2736   if (!no_idata5)
2737     {
2738       fprintf (f, "\t.section\t.idata$5\n");
2739       if (use_nul_prefixed_import_tables)
2740         {
2741 	  if (create_for_pep)
2742 	    fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2743 	  else
2744 	    fprintf (f,"\t%s\t0\n", ASM_LONG);
2745         }
2746       fprintf (f, "fthunk:\n");
2747     }
2748 
2749   if (!no_idata4)
2750     {
2751       fprintf (f, "\t.section\t.idata$4\n");
2752       if (use_nul_prefixed_import_tables)
2753         {
2754 	  if (create_for_pep)
2755 	    fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2756 	  else
2757 	    fprintf (f,"\t%s\t0\n", ASM_LONG);
2758         }
2759       fprintf (f, "hname:\n");
2760     }
2761 
2762   fclose (f);
2763 
2764   assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2765 
2766   abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2767   if (abfd == NULL)
2768     /* xgettext:c-format */
2769     fatal (_("failed to open temporary head file: %s: %s"),
2770 	   TMP_HEAD_O, bfd_get_errmsg ());
2771 
2772   temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2773   return abfd;
2774 }
2775 
2776 bfd *
2777 make_delay_head (void)
2778 {
2779   FILE *f = fopen (TMP_HEAD_S, FOPEN_WT);
2780   bfd *abfd;
2781 
2782   if (f == NULL)
2783     {
2784       fatal (_("failed to open temporary head file: %s"), TMP_HEAD_S);
2785       return NULL;
2786     }
2787 
2788   temp_file_to_remove[TEMP_HEAD_FILE] = TMP_HEAD_S;
2789 
2790   /* Output the __tailMerge__xxx function */
2791   fprintf (f, "%s Import trampoline\n", ASM_C);
2792   fprintf (f, "\t.section\t.text\n");
2793   fprintf(f,"\t%s\t%s\n", ASM_GLOBAL, head_label);
2794   if (HOW_SEH)
2795     fprintf (f, "\t.seh_proc\t%s\n", head_label);
2796   fprintf (f, "%s:\n", head_label);
2797   fprintf (f, mtable[machine].trampoline, imp_name_lab);
2798   if (HOW_SEH)
2799     fprintf (f, "\t.seh_endproc\n");
2800 
2801   /* Output the delay import descriptor */
2802   fprintf (f, "\n%s DELAY_IMPORT_DESCRIPTOR\n", ASM_C);
2803   fprintf (f, ".section\t.text$2\n");
2804   fprintf (f,"%s __DELAY_IMPORT_DESCRIPTOR_%s\n", ASM_GLOBAL,imp_name_lab);
2805   fprintf (f, "__DELAY_IMPORT_DESCRIPTOR_%s:\n", imp_name_lab);
2806   fprintf (f, "\t%s 1\t%s grAttrs\n", ASM_LONG, ASM_C);
2807   fprintf (f, "\t%s__%s_iname%s\t%s rvaDLLName\n",
2808 	   ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2809   fprintf (f, "\t%s__DLL_HANDLE_%s%s\t%s rvaHmod\n",
2810 	   ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2811   fprintf (f, "\t%s__IAT_%s%s\t%s rvaIAT\n",
2812 	   ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2813   fprintf (f, "\t%s__INT_%s%s\t%s rvaINT\n",
2814 	   ASM_RVA_BEFORE, imp_name_lab, ASM_RVA_AFTER, ASM_C);
2815   fprintf (f, "\t%s\t0\t%s rvaBoundIAT\n", ASM_LONG, ASM_C);
2816   fprintf (f, "\t%s\t0\t%s rvaUnloadIAT\n", ASM_LONG, ASM_C);
2817   fprintf (f, "\t%s\t0\t%s dwTimeStamp\n", ASM_LONG, ASM_C);
2818 
2819   /* Output the dll_handle */
2820   fprintf (f, "\n.section .data\n");
2821   fprintf (f, "__DLL_HANDLE_%s:\n", imp_name_lab);
2822   fprintf (f, "\t%s\t0\t%s Handle\n", ASM_LONG, ASM_C);
2823   if (create_for_pep)
2824     fprintf (f, "\t%s\t0\n", ASM_LONG);
2825   fprintf (f, "\n");
2826 
2827   fprintf (f, "%sStuff for compatibility\n", ASM_C);
2828 
2829   if (!no_idata5)
2830     {
2831       fprintf (f, "\t.section\t.idata$5\n");
2832       /* NULL terminating list.  */
2833       if (create_for_pep)
2834         fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2835       else
2836         fprintf (f,"\t%s\t0\n", ASM_LONG);
2837       fprintf (f, "__IAT_%s:\n", imp_name_lab);
2838     }
2839 
2840   if (!no_idata4)
2841     {
2842       fprintf (f, "\t.section\t.idata$4\n");
2843       fprintf (f, "\t%s\t0\n", ASM_LONG);
2844       if (create_for_pep)
2845         fprintf (f, "\t%s\t0\n", ASM_LONG);
2846       fprintf (f, "\t.section\t.idata$4\n");
2847       fprintf (f, "__INT_%s:\n", imp_name_lab);
2848     }
2849 
2850   fprintf (f, "\t.section\t.idata$2\n");
2851 
2852   fclose (f);
2853 
2854   assemble_file (TMP_HEAD_S, TMP_HEAD_O);
2855 
2856   abfd = bfd_openr (TMP_HEAD_O, HOW_BFD_READ_TARGET);
2857   if (abfd == NULL)
2858     /* xgettext:c-format */
2859     fatal (_("failed to open temporary head file: %s: %s"),
2860 	   TMP_HEAD_O, bfd_get_errmsg ());
2861 
2862   temp_file_to_remove[TEMP_HEAD_O_FILE] = TMP_HEAD_O;
2863   return abfd;
2864 }
2865 
2866 static bfd *
2867 make_tail (void)
2868 {
2869   FILE *f = fopen (TMP_TAIL_S, FOPEN_WT);
2870   bfd *abfd;
2871 
2872   if (f == NULL)
2873     {
2874       fatal (_("failed to open temporary tail file: %s"), TMP_TAIL_S);
2875       return NULL;
2876     }
2877 
2878   temp_file_to_remove[TEMP_TAIL_FILE] = TMP_TAIL_S;
2879 
2880   if (!no_idata4)
2881     {
2882       fprintf (f, "\t.section\t.idata$4\n");
2883       if (create_for_pep)
2884 	fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2885       else
2886 	fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list.  */
2887     }
2888 
2889   if (!no_idata5)
2890     {
2891       fprintf (f, "\t.section\t.idata$5\n");
2892       if (create_for_pep)
2893 	fprintf (f,"\t%s\t0\n\t%s\t0\n", ASM_LONG, ASM_LONG);
2894       else
2895 	fprintf (f,"\t%s\t0\n", ASM_LONG); /* NULL terminating list.  */
2896     }
2897 
2898   fprintf (f, "\t.section\t.idata$7\n");
2899   fprintf (f, "\t%s\t__%s_iname\n", ASM_GLOBAL, imp_name_lab);
2900   fprintf (f, "__%s_iname:\t%s\t\"%s\"\n",
2901 	   imp_name_lab, ASM_TEXT, dll_name);
2902 
2903   fclose (f);
2904 
2905   assemble_file (TMP_TAIL_S, TMP_TAIL_O);
2906 
2907   abfd = bfd_openr (TMP_TAIL_O, HOW_BFD_READ_TARGET);
2908   if (abfd == NULL)
2909     /* xgettext:c-format */
2910     fatal (_("failed to open temporary tail file: %s: %s"),
2911 	   TMP_TAIL_O, bfd_get_errmsg ());
2912 
2913   temp_file_to_remove[TEMP_TAIL_O_FILE] = TMP_TAIL_O;
2914   return abfd;
2915 }
2916 
2917 static void
2918 gen_lib_file (int delay)
2919 {
2920   int i;
2921   export_type *exp;
2922   bfd *ar_head;
2923   bfd *ar_tail;
2924   bfd *outarch;
2925   bfd * head  = 0;
2926 
2927   unlink (imp_name);
2928 
2929   outarch = bfd_openw (imp_name, HOW_BFD_WRITE_TARGET);
2930 
2931   if (!outarch)
2932     /* xgettext:c-format */
2933     fatal (_("Can't create .lib file: %s: %s"),
2934 	   imp_name, bfd_get_errmsg ());
2935 
2936   /* xgettext:c-format */
2937   inform (_("Creating library file: %s"), imp_name);
2938 
2939   xatexit (unlink_temp_files);
2940 
2941   bfd_set_format (outarch, bfd_archive);
2942   outarch->has_armap = 1;
2943   outarch->is_thin_archive = 0;
2944 
2945   /* Work out a reasonable size of things to put onto one line.  */
2946   if (delay)
2947     {
2948       ar_head = make_delay_head ();
2949     }
2950   else
2951     {
2952       ar_head = make_head ();
2953     }
2954   ar_tail = make_tail();
2955 
2956   if (ar_head == NULL || ar_tail == NULL)
2957     return;
2958 
2959   for (i = 0; (exp = d_exports_lexically[i]); i++)
2960     {
2961       bfd *n;
2962       /* Don't add PRIVATE entries to import lib.  */
2963       if (exp->private)
2964 	continue;
2965       n = make_one_lib_file (exp, i, delay);
2966       n->archive_next = head;
2967       head = n;
2968       if (ext_prefix_alias)
2969 	{
2970 	  export_type alias_exp;
2971 
2972 	  assert (i < PREFIX_ALIAS_BASE);
2973 	  alias_exp.name = make_imp_label (ext_prefix_alias, exp->name);
2974 	  alias_exp.internal_name = exp->internal_name;
2975 	  alias_exp.its_name = exp->its_name;
2976 	  alias_exp.import_name = exp->name;
2977 	  alias_exp.ordinal = exp->ordinal;
2978 	  alias_exp.constant = exp->constant;
2979 	  alias_exp.noname = exp->noname;
2980 	  alias_exp.private = exp->private;
2981 	  alias_exp.data = exp->data;
2982 	  alias_exp.forward = exp->forward;
2983 	  alias_exp.next = exp->next;
2984 	  n = make_one_lib_file (&alias_exp, i + PREFIX_ALIAS_BASE, delay);
2985 	  n->archive_next = head;
2986 	  head = n;
2987 	}
2988     }
2989 
2990   /* Now stick them all into the archive.  */
2991   ar_head->archive_next = head;
2992   ar_tail->archive_next = ar_head;
2993   head = ar_tail;
2994 
2995   if (! bfd_set_archive_head (outarch, head))
2996     bfd_fatal ("bfd_set_archive_head");
2997 
2998   if (! bfd_close (outarch))
2999     bfd_fatal (imp_name);
3000 
3001   while (head != NULL)
3002     {
3003       bfd *n = head->archive_next;
3004       bfd_close (head);
3005       head = n;
3006     }
3007 
3008   /* Delete all the temp files.  */
3009   unlink_temp_files ();
3010 
3011   if (dontdeltemps < 2)
3012     {
3013       char *name;
3014 
3015       name = xmalloc (strlen (TMP_STUB) + 10);
3016       for (i = 0; (exp = d_exports_lexically[i]); i++)
3017 	{
3018 	  /* Don't delete non-existent stubs for PRIVATE entries.  */
3019           if (exp->private)
3020 	    continue;
3021 	  sprintf (name, "%s%05d.o", TMP_STUB, i);
3022 	  if (unlink (name) < 0)
3023 	    /* xgettext:c-format */
3024 	    non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3025 	  if (ext_prefix_alias)
3026 	    {
3027 	      sprintf (name, "%s%05d.o", TMP_STUB, i + PREFIX_ALIAS_BASE);
3028 	      if (unlink (name) < 0)
3029 		/* xgettext:c-format */
3030 		non_fatal (_("cannot delete %s: %s"), name, strerror (errno));
3031 	    }
3032 	}
3033       free (name);
3034     }
3035 
3036   inform (_("Created lib file"));
3037 }
3038 
3039 /* Append a copy of data (cast to char *) to list.  */
3040 
3041 static void
3042 dll_name_list_append (dll_name_list_type * list, bfd_byte * data)
3043 {
3044   dll_name_list_node_type * entry;
3045 
3046   /* Error checking.  */
3047   if (! list || ! list->tail)
3048     return;
3049 
3050   /* Allocate new node.  */
3051   entry = ((dll_name_list_node_type *)
3052 	   xmalloc (sizeof (dll_name_list_node_type)));
3053 
3054   /* Initialize its values.  */
3055   entry->dllname = xstrdup ((char *) data);
3056   entry->next = NULL;
3057 
3058   /* Add to tail, and move tail.  */
3059   list->tail->next = entry;
3060   list->tail = entry;
3061 }
3062 
3063 /* Count the number of entries in list.  */
3064 
3065 static int
3066 dll_name_list_count (dll_name_list_type * list)
3067 {
3068   dll_name_list_node_type * p;
3069   int count = 0;
3070 
3071   /* Error checking.  */
3072   if (! list || ! list->head)
3073     return 0;
3074 
3075   p = list->head;
3076 
3077   while (p && p->next)
3078     {
3079       count++;
3080       p = p->next;
3081     }
3082   return count;
3083 }
3084 
3085 /* Print each entry in list to stdout.  */
3086 
3087 static void
3088 dll_name_list_print (dll_name_list_type * list)
3089 {
3090   dll_name_list_node_type * p;
3091 
3092   /* Error checking.  */
3093   if (! list || ! list->head)
3094     return;
3095 
3096   p = list->head;
3097 
3098   while (p && p->next && p->next->dllname && *(p->next->dllname))
3099     {
3100       printf ("%s\n", p->next->dllname);
3101       p = p->next;
3102     }
3103 }
3104 
3105 /* Free all entries in list, and list itself.  */
3106 
3107 static void
3108 dll_name_list_free (dll_name_list_type * list)
3109 {
3110   if (list)
3111     {
3112       dll_name_list_free_contents (list->head);
3113       list->head = NULL;
3114       list->tail = NULL;
3115       free (list);
3116     }
3117 }
3118 
3119 /* Recursive function to free all nodes entry->next->next...
3120    as well as entry itself.  */
3121 
3122 static void
3123 dll_name_list_free_contents (dll_name_list_node_type * entry)
3124 {
3125   if (entry)
3126     {
3127       if (entry->next)
3128 	dll_name_list_free_contents (entry->next);
3129       free (entry->dllname);
3130       free (entry);
3131     }
3132 }
3133 
3134 /* Allocate and initialize a dll_name_list_type object,
3135    including its sentinel node.  Caller is responsible
3136    for calling dll_name_list_free when finished with
3137    the list.  */
3138 
3139 static dll_name_list_type *
3140 dll_name_list_create (void)
3141 {
3142   /* Allocate list.  */
3143   dll_name_list_type * list = xmalloc (sizeof (dll_name_list_type));
3144 
3145   /* Allocate and initialize sentinel node.  */
3146   list->head = xmalloc (sizeof (dll_name_list_node_type));
3147   list->head->dllname = NULL;
3148   list->head->next = NULL;
3149 
3150   /* Bookkeeping for empty list.  */
3151   list->tail = list->head;
3152 
3153   return list;
3154 }
3155 
3156 /* Search the symbol table of the suppled BFD for a symbol whose name matches
3157    OBJ (where obj is cast to const char *).  If found, set global variable
3158    identify_member_contains_symname_result TRUE.  It is the caller's
3159    responsibility to set the result variable FALSE before iterating with
3160    this function.  */
3161 
3162 static void
3163 identify_member_contains_symname (bfd  * abfd,
3164 				  bfd  * archive_bfd ATTRIBUTE_UNUSED,
3165 				  void * obj)
3166 {
3167   long storage_needed;
3168   asymbol ** symbol_table;
3169   long number_of_symbols;
3170   long i;
3171   symname_search_data_type * search_data = (symname_search_data_type *) obj;
3172 
3173   /* If we already found the symbol in a different member,
3174      short circuit.  */
3175   if (search_data->found)
3176     return;
3177 
3178   storage_needed = bfd_get_symtab_upper_bound (abfd);
3179   if (storage_needed <= 0)
3180     return;
3181 
3182   symbol_table = xmalloc (storage_needed);
3183   number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
3184   if (number_of_symbols < 0)
3185     {
3186       free (symbol_table);
3187       return;
3188     }
3189 
3190   for (i = 0; i < number_of_symbols; i++)
3191     {
3192       if (strncmp (symbol_table[i]->name,
3193                    search_data->symname,
3194                    strlen (search_data->symname)) == 0)
3195 	{
3196 	  search_data->found = true;
3197 	  break;
3198 	}
3199     }
3200   free (symbol_table);
3201 }
3202 
3203 /* This is the main implementation for the --identify option.
3204    Given the name of an import library in identify_imp_name, first
3205    determine if the import library is a GNU binutils-style one (where
3206    the DLL name is stored in an .idata$7 section), or if it is a
3207    MS-style one (where the DLL name, along with much other data, is
3208    stored in the .idata$6 section).  We determine the style of import
3209    library by searching for the DLL-structure symbol inserted by MS
3210    tools: __NULL_IMPORT_DESCRIPTOR.
3211 
3212    Once we know which section to search, evaluate each section for the
3213    appropriate properties that indicate it may contain the name of the
3214    associated DLL (this differs depending on the style).  Add the contents
3215    of all sections which meet the criteria to a linked list of dll names.
3216 
3217    Finally, print them all to stdout. (If --identify-strict, an error is
3218    reported if more than one match was found).  */
3219 
3220 static void
3221 identify_dll_for_implib (void)
3222 {
3223   bfd * abfd = NULL;
3224   int count = 0;
3225   identify_data_type identify_data;
3226   symname_search_data_type search_data;
3227 
3228   /* Initialize identify_data.  */
3229   identify_data.list = dll_name_list_create ();
3230   identify_data.ms_style_implib = false;
3231 
3232   /* Initialize search_data.  */
3233   search_data.symname = "__NULL_IMPORT_DESCRIPTOR";
3234   search_data.found = false;
3235 
3236   if (bfd_init () != BFD_INIT_MAGIC)
3237     fatal (_("fatal error: libbfd ABI mismatch"));
3238 
3239   abfd = bfd_openr (identify_imp_name, 0);
3240   if (abfd == NULL)
3241     /* xgettext:c-format */
3242     fatal (_("Can't open .lib file: %s: %s"),
3243 	   identify_imp_name, bfd_get_errmsg ());
3244 
3245   if (! bfd_check_format (abfd, bfd_archive))
3246     {
3247       if (! bfd_close (abfd))
3248         bfd_fatal (identify_imp_name);
3249 
3250       fatal (_("%s is not a library"), identify_imp_name);
3251     }
3252 
3253   /* Detect if this a Microsoft import library.  */
3254   identify_search_archive (abfd,
3255 			   identify_member_contains_symname,
3256 			   (void *)(& search_data));
3257   if (search_data.found)
3258     identify_data.ms_style_implib = true;
3259 
3260   /* Rewind the bfd.  */
3261   if (! bfd_close (abfd))
3262     bfd_fatal (identify_imp_name);
3263   abfd = bfd_openr (identify_imp_name, 0);
3264   if (abfd == NULL)
3265     bfd_fatal (identify_imp_name);
3266 
3267   if (!bfd_check_format (abfd, bfd_archive))
3268     {
3269       if (!bfd_close (abfd))
3270         bfd_fatal (identify_imp_name);
3271 
3272       fatal (_("%s is not a library"), identify_imp_name);
3273     }
3274 
3275   /* Now search for the dll name.  */
3276   identify_search_archive (abfd,
3277 			   identify_search_member,
3278 			   (void *)(& identify_data));
3279 
3280   if (! bfd_close (abfd))
3281     bfd_fatal (identify_imp_name);
3282 
3283   count = dll_name_list_count (identify_data.list);
3284   if (count > 0)
3285     {
3286       if (identify_strict && count > 1)
3287         {
3288           dll_name_list_free (identify_data.list);
3289           identify_data.list = NULL;
3290           fatal (_("Import library `%s' specifies two or more dlls"),
3291 		 identify_imp_name);
3292         }
3293       dll_name_list_print (identify_data.list);
3294       dll_name_list_free (identify_data.list);
3295       identify_data.list = NULL;
3296     }
3297   else
3298     {
3299       dll_name_list_free (identify_data.list);
3300       identify_data.list = NULL;
3301       fatal (_("Unable to determine dll name for `%s' (not an import library?)"),
3302 	     identify_imp_name);
3303     }
3304 }
3305 
3306 /* Loop over all members of the archive, applying the supplied function to
3307    each member that is a bfd_object.  The function will be called as if:
3308       func (member_bfd, abfd, user_storage)  */
3309 
3310 static void
3311 identify_search_archive (bfd * abfd,
3312 			 void (* operation) (bfd *, bfd *, void *),
3313 			 void * user_storage)
3314 {
3315   bfd *   arfile = NULL;
3316   bfd *   last_arfile = NULL;
3317   char ** matching;
3318 
3319   while (1)
3320     {
3321       arfile = bfd_openr_next_archived_file (abfd, arfile);
3322 
3323       if (arfile == NULL)
3324         {
3325           if (bfd_get_error () != bfd_error_no_more_archived_files)
3326             bfd_fatal (bfd_get_filename (abfd));
3327           break;
3328         }
3329 
3330       if (bfd_check_format_matches (arfile, bfd_object, &matching))
3331 	(*operation) (arfile, abfd, user_storage);
3332       else
3333         {
3334           bfd_nonfatal (bfd_get_filename (arfile));
3335           free (matching);
3336         }
3337 
3338       if (last_arfile != NULL)
3339 	{
3340 	  bfd_close (last_arfile);
3341 	  /* PR 17512: file: 8b2168d4.  */
3342 	  if (last_arfile == arfile)
3343 	    {
3344 	      last_arfile = NULL;
3345 	      break;
3346 	    }
3347 	}
3348 
3349       last_arfile = arfile;
3350     }
3351 
3352   if (last_arfile != NULL)
3353     {
3354       bfd_close (last_arfile);
3355     }
3356 }
3357 
3358 /* Call the identify_search_section() function for each section of this
3359    archive member.  */
3360 
3361 static void
3362 identify_search_member (bfd  *abfd,
3363 			bfd  *archive_bfd ATTRIBUTE_UNUSED,
3364 			void *obj)
3365 {
3366   bfd_map_over_sections (abfd, identify_search_section, obj);
3367 }
3368 
3369 /* This predicate returns true if section->name matches the desired value.
3370    By default, this is .idata$7 (.idata$6 if the import library is
3371    ms-style).  */
3372 
3373 static bool
3374 identify_process_section_p (asection * section, bool ms_style_implib)
3375 {
3376   static const char * SECTION_NAME = ".idata$7";
3377   static const char * MS_SECTION_NAME = ".idata$6";
3378 
3379   const char * section_name =
3380     (ms_style_implib ? MS_SECTION_NAME : SECTION_NAME);
3381 
3382   if (strcmp (section_name, section->name) == 0)
3383     return true;
3384   return false;
3385 }
3386 
3387 /* If *section has contents and its name is .idata$7 (.idata$6 if
3388    import lib ms-generated) -- and it satisfies several other constraints
3389    -- then add the contents of the section to obj->list.  */
3390 
3391 static void
3392 identify_search_section (bfd * abfd, asection * section, void * obj)
3393 {
3394   bfd_byte *data = 0;
3395   bfd_size_type datasize;
3396   identify_data_type * identify_data = (identify_data_type *)obj;
3397   bool ms_style = identify_data->ms_style_implib;
3398 
3399   if ((section->flags & SEC_HAS_CONTENTS) == 0)
3400     return;
3401 
3402   if (! identify_process_section_p (section, ms_style))
3403     return;
3404 
3405   /* Binutils import libs seem distinguish the .idata$7 section that contains
3406      the DLL name from other .idata$7 sections by the absence of the
3407      SEC_RELOC flag.  */
3408   if (!ms_style && ((section->flags & SEC_RELOC) == SEC_RELOC))
3409     return;
3410 
3411   /* MS import libs seem to distinguish the .idata$6 section
3412      that contains the DLL name from other .idata$6 sections
3413      by the presence of the SEC_DATA flag.  */
3414   if (ms_style && ((section->flags & SEC_DATA) == 0))
3415     return;
3416 
3417   if ((datasize = bfd_section_size (section)) == 0)
3418     return;
3419 
3420   data = (bfd_byte *) xmalloc (datasize + 1);
3421   data[0] = '\0';
3422 
3423   bfd_get_section_contents (abfd, section, data, 0, datasize);
3424   data[datasize] = '\0';
3425 
3426   /* Use a heuristic to determine if data is a dll name.
3427      Possible to defeat this if (a) the library has MANY
3428      (more than 0x302f) imports, (b) it is an ms-style
3429      import library, but (c) it is buggy, in that the SEC_DATA
3430      flag is set on the "wrong" sections.  This heuristic might
3431      also fail to record a valid dll name if the dllname uses
3432      a multibyte or unicode character set (is that valid?).
3433 
3434      This heuristic is based on the fact that symbols names in
3435      the chosen section -- as opposed to the dll name -- begin
3436      at offset 2 in the data. The first two bytes are a 16bit
3437      little-endian count, and start at 0x0000. However, the dll
3438      name begins at offset 0 in the data. We assume that the
3439      dll name does not contain unprintable characters.   */
3440   if (data[0] != '\0' && ISPRINT (data[0])
3441       && ((datasize < 2) || ISPRINT (data[1])))
3442     dll_name_list_append (identify_data->list, data);
3443 
3444   free (data);
3445 }
3446 
3447 /* Run through the information gathered from the .o files and the
3448    .def file and work out the best stuff.  */
3449 
3450 static int
3451 pfunc (const void *a, const void *b)
3452 {
3453   export_type *ap = *(export_type **) a;
3454   export_type *bp = *(export_type **) b;
3455 
3456   if (ap->ordinal == bp->ordinal)
3457     return 0;
3458 
3459   /* Unset ordinals go to the bottom.  */
3460   if (ap->ordinal == -1)
3461     return 1;
3462   if (bp->ordinal == -1)
3463     return -1;
3464   return (ap->ordinal - bp->ordinal);
3465 }
3466 
3467 static int
3468 nfunc (const void *a, const void *b)
3469 {
3470   export_type *ap = *(export_type **) a;
3471   export_type *bp = *(export_type **) b;
3472   const char *an = ap->name;
3473   const char *bn = bp->name;
3474   if (ap->its_name)
3475     an = ap->its_name;
3476   if (bp->its_name)
3477     an = bp->its_name;
3478   if (killat)
3479     {
3480       an = (an[0] == '@') ? an + 1 : an;
3481       bn = (bn[0] == '@') ? bn + 1 : bn;
3482     }
3483 
3484   return (strcmp (an, bn));
3485 }
3486 
3487 static void
3488 remove_null_names (export_type **ptr)
3489 {
3490   int src;
3491   int dst;
3492 
3493   for (dst = src = 0; src < d_nfuncs; src++)
3494     {
3495       if (ptr[src])
3496 	{
3497 	  ptr[dst] = ptr[src];
3498 	  dst++;
3499 	}
3500     }
3501   d_nfuncs = dst;
3502 }
3503 
3504 static void
3505 process_duplicates (export_type **d_export_vec)
3506 {
3507   int more = 1;
3508   int i;
3509 
3510   while (more)
3511     {
3512       more = 0;
3513       /* Remove duplicates.  */
3514       qsort (d_export_vec, d_nfuncs, sizeof (export_type *), nfunc);
3515 
3516       for (i = 0; i < d_nfuncs - 1; i++)
3517 	{
3518 	  if (strcmp (d_export_vec[i]->name,
3519 		      d_export_vec[i + 1]->name) == 0)
3520 	    {
3521 	      export_type *a = d_export_vec[i];
3522 	      export_type *b = d_export_vec[i + 1];
3523 
3524 	      more = 1;
3525 
3526 	      /* xgettext:c-format */
3527 	      inform (_("Warning, ignoring duplicate EXPORT %s %d,%d"),
3528 		      a->name, a->ordinal, b->ordinal);
3529 
3530 	      if (a->ordinal != -1
3531 		  && b->ordinal != -1)
3532 		/* xgettext:c-format */
3533 		fatal (_("Error, duplicate EXPORT with ordinals: %s"),
3534 		      a->name);
3535 
3536 	      /* Merge attributes.  */
3537 	      b->ordinal = a->ordinal > 0 ? a->ordinal : b->ordinal;
3538 	      b->constant |= a->constant;
3539 	      b->noname |= a->noname;
3540 	      b->data |= a->data;
3541 	      d_export_vec[i] = 0;
3542 	    }
3543 
3544 	  remove_null_names (d_export_vec);
3545 	}
3546     }
3547 
3548   /* Count the names.  */
3549   for (i = 0; i < d_nfuncs; i++)
3550     if (!d_export_vec[i]->noname)
3551       d_named_nfuncs++;
3552 }
3553 
3554 static void
3555 fill_ordinals (export_type **d_export_vec)
3556 {
3557   int lowest = -1;
3558   int i;
3559   char *ptr;
3560   int size = 65536;
3561 
3562   qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3563 
3564   /* Fill in the unset ordinals with ones from our range.  */
3565   ptr = (char *) xmalloc (size);
3566 
3567   memset (ptr, 0, size);
3568 
3569   /* Mark in our large vector all the numbers that are taken.  */
3570   for (i = 0; i < d_nfuncs; i++)
3571     {
3572       if (d_export_vec[i]->ordinal != -1)
3573 	{
3574 	  ptr[d_export_vec[i]->ordinal] = 1;
3575 
3576 	  if (lowest == -1 || d_export_vec[i]->ordinal < lowest)
3577 	    lowest = d_export_vec[i]->ordinal;
3578 	}
3579     }
3580 
3581   /* Start at 1 for compatibility with MS toolchain.  */
3582   if (lowest == -1)
3583     lowest = 1;
3584 
3585   /* Now fill in ordinals where the user wants us to choose.  */
3586   for (i = 0; i < d_nfuncs; i++)
3587     {
3588       if (d_export_vec[i]->ordinal == -1)
3589 	{
3590 	  int j;
3591 
3592 	  /* First try within or after any user supplied range.  */
3593 	  for (j = lowest; j < size; j++)
3594 	    if (ptr[j] == 0)
3595 	      {
3596 		ptr[j] = 1;
3597 		d_export_vec[i]->ordinal = j;
3598 		goto done;
3599 	      }
3600 
3601 	  /* Then try before the range.  */
3602 	  for (j = lowest; j >0; j--)
3603 	    if (ptr[j] == 0)
3604 	      {
3605 		ptr[j] = 1;
3606 		d_export_vec[i]->ordinal = j;
3607 		goto done;
3608 	      }
3609 	done:;
3610 	}
3611     }
3612 
3613   free (ptr);
3614 
3615   /* And resort.  */
3616   qsort (d_export_vec, d_nfuncs, sizeof (export_type *), pfunc);
3617 
3618   /* Work out the lowest and highest ordinal numbers.  */
3619   if (d_nfuncs)
3620     {
3621       if (d_export_vec[0])
3622 	d_low_ord = d_export_vec[0]->ordinal;
3623       if (d_export_vec[d_nfuncs-1])
3624 	d_high_ord = d_export_vec[d_nfuncs-1]->ordinal;
3625     }
3626 }
3627 
3628 static void
3629 mangle_defs (void)
3630 {
3631   /* First work out the minimum ordinal chosen.  */
3632   export_type *exp;
3633   export_type **d_export_vec = xmalloc (sizeof (export_type *) * d_nfuncs);
3634   int i;
3635 
3636   inform (_("Processing definitions"));
3637 
3638   for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3639     d_export_vec[i] = exp;
3640 
3641   process_duplicates (d_export_vec);
3642   fill_ordinals (d_export_vec);
3643 
3644   /* Put back the list in the new order.  */
3645   d_exports = 0;
3646   for (i = d_nfuncs - 1; i >= 0; i--)
3647     {
3648       d_export_vec[i]->next = d_exports;
3649       d_exports = d_export_vec[i];
3650     }
3651 
3652   /* Build list in alpha order.  */
3653   d_exports_lexically = (export_type **)
3654     xmalloc (sizeof (export_type *) * (d_nfuncs + 1));
3655 
3656   for (i = 0, exp = d_exports; exp; i++, exp = exp->next)
3657     d_exports_lexically[i] = exp;
3658 
3659   d_exports_lexically[i] = 0;
3660 
3661   qsort (d_exports_lexically, i, sizeof (export_type *), nfunc);
3662 
3663   inform (_("Processed definitions"));
3664 }
3665 
3666 static void
3667 usage (FILE *file, int status)
3668 {
3669   /* xgetext:c-format */
3670   fprintf (file, _("Usage %s <option(s)> <object-file(s)>\n"), program_name);
3671   /* xgetext:c-format */
3672   fprintf (file, _("   -m --machine <machine>    Create as DLL for <machine>.  [default: %s]\n"), mname);
3673   fprintf (file, _("        possible <machine>: arm[_interwork], i386, mcore[-elf]{-le|-be}, thumb\n"));
3674   fprintf (file, _("   -e --output-exp <outname> Generate an export file.\n"));
3675   fprintf (file, _("   -l --output-lib <outname> Generate an interface library.\n"));
3676   fprintf (file, _("   -y --output-delaylib <outname> Create a delay-import library.\n"));
3677   fprintf (file, _("   -a --add-indirect         Add dll indirects to export file.\n"));
3678   fprintf (file, _("   -D --dllname <name>       Name of input dll to put into interface lib.\n"));
3679   fprintf (file, _("   -d --input-def <deffile>  Name of .def file to be read in.\n"));
3680   fprintf (file, _("   -z --output-def <deffile> Name of .def file to be created.\n"));
3681   fprintf (file, _("      --export-all-symbols   Export all symbols to .def\n"));
3682   fprintf (file, _("      --no-export-all-symbols  Only export listed symbols\n"));
3683   fprintf (file, _("      --exclude-symbols <list> Don't export <list>\n"));
3684   fprintf (file, _("      --no-default-excludes  Clear default exclude symbols\n"));
3685   fprintf (file, _("   -b --base-file <basefile> Read linker generated base file.\n"));
3686   fprintf (file, _("   -x --no-idata4            Don't generate idata$4 section.\n"));
3687   fprintf (file, _("   -c --no-idata5            Don't generate idata$5 section.\n"));
3688   fprintf (file, _("      --use-nul-prefixed-import-tables Use zero prefixed idata$4 and idata$5.\n"));
3689   fprintf (file, _("   -U --add-underscore       Add underscores to all symbols in interface library.\n"));
3690   fprintf (file, _("      --add-stdcall-underscore Add underscores to stdcall symbols in interface library.\n"));
3691   fprintf (file, _("      --no-leading-underscore All symbols shouldn't be prefixed by an underscore.\n"));
3692   fprintf (file, _("      --leading-underscore   All symbols should be prefixed by an underscore.\n"));
3693   fprintf (file, _("   -k --kill-at              Kill @<n> from exported names.\n"));
3694   fprintf (file, _("   -A --add-stdcall-alias    Add aliases without @<n>.\n"));
3695   fprintf (file, _("   -p --ext-prefix-alias <prefix> Add aliases with <prefix>.\n"));
3696   fprintf (file, _("   -S --as <name>            Use <name> for assembler.\n"));
3697   fprintf (file, _("   -f --as-flags <flags>     Pass <flags> to the assembler.\n"));
3698   fprintf (file, _("   -C --compat-implib        Create backward compatible import library.\n"));
3699   fprintf (file, _("   -n --no-delete            Keep temp files (repeat for extra preservation).\n"));
3700   fprintf (file, _("   -t --temp-prefix <prefix> Use <prefix> to construct temp file names.\n"));
3701   fprintf (file, _("   -I --identify <implib>    Report the name of the DLL associated with <implib>.\n"));
3702   fprintf (file, _("      --identify-strict      Causes --identify to report error when multiple DLLs.\n"));
3703   fprintf (file, _("   -v --verbose              Be verbose.\n"));
3704   fprintf (file, _("   -V --version              Display the program version.\n"));
3705   fprintf (file, _("   -h --help                 Display this information.\n"));
3706   fprintf (file, _("   @<file>                   Read options from <file>.\n"));
3707 #ifdef DLLTOOL_MCORE_ELF
3708   fprintf (file, _("   -M --mcore-elf <outname>  Process mcore-elf object files into <outname>.\n"));
3709   fprintf (file, _("   -L --linker <name>        Use <name> as the linker.\n"));
3710   fprintf (file, _("   -F --linker-flags <flags> Pass <flags> to the linker.\n"));
3711 #endif
3712   if (REPORT_BUGS_TO[0] && status == 0)
3713     fprintf (file, _("Report bugs to %s\n"), REPORT_BUGS_TO);
3714   exit (status);
3715 }
3716 
3717 #define OPTION_EXPORT_ALL_SYMS		150
3718 #define OPTION_NO_EXPORT_ALL_SYMS	(OPTION_EXPORT_ALL_SYMS + 1)
3719 #define OPTION_EXCLUDE_SYMS		(OPTION_NO_EXPORT_ALL_SYMS + 1)
3720 #define OPTION_NO_DEFAULT_EXCLUDES	(OPTION_EXCLUDE_SYMS + 1)
3721 #define OPTION_ADD_STDCALL_UNDERSCORE	(OPTION_NO_DEFAULT_EXCLUDES + 1)
3722 #define OPTION_USE_NUL_PREFIXED_IMPORT_TABLES \
3723   (OPTION_ADD_STDCALL_UNDERSCORE + 1)
3724 #define OPTION_IDENTIFY_STRICT		(OPTION_USE_NUL_PREFIXED_IMPORT_TABLES + 1)
3725 #define OPTION_NO_LEADING_UNDERSCORE	(OPTION_IDENTIFY_STRICT + 1)
3726 #define OPTION_LEADING_UNDERSCORE	(OPTION_NO_LEADING_UNDERSCORE + 1)
3727 
3728 static const struct option long_options[] =
3729 {
3730   {"no-delete", no_argument, NULL, 'n'},
3731   {"dllname", required_argument, NULL, 'D'},
3732   {"no-idata4", no_argument, NULL, 'x'},
3733   {"no-idata5", no_argument, NULL, 'c'},
3734   {"use-nul-prefixed-import-tables", no_argument, NULL,
3735    OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
3736   {"output-exp", required_argument, NULL, 'e'},
3737   {"output-def", required_argument, NULL, 'z'},
3738   {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL_SYMS},
3739   {"no-export-all-symbols", no_argument, NULL, OPTION_NO_EXPORT_ALL_SYMS},
3740   {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMS},
3741   {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
3742   {"output-lib", required_argument, NULL, 'l'},
3743   {"def", required_argument, NULL, 'd'}, /* for compatibility with older versions */
3744   {"input-def", required_argument, NULL, 'd'},
3745   {"add-underscore", no_argument, NULL, 'U'},
3746   {"add-stdcall-underscore", no_argument, NULL, OPTION_ADD_STDCALL_UNDERSCORE},
3747   {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
3748   {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
3749   {"kill-at", no_argument, NULL, 'k'},
3750   {"add-stdcall-alias", no_argument, NULL, 'A'},
3751   {"ext-prefix-alias", required_argument, NULL, 'p'},
3752   {"identify", required_argument, NULL, 'I'},
3753   {"identify-strict", no_argument, NULL, OPTION_IDENTIFY_STRICT},
3754   {"verbose", no_argument, NULL, 'v'},
3755   {"version", no_argument, NULL, 'V'},
3756   {"help", no_argument, NULL, 'h'},
3757   {"machine", required_argument, NULL, 'm'},
3758   {"add-indirect", no_argument, NULL, 'a'},
3759   {"base-file", required_argument, NULL, 'b'},
3760   {"as", required_argument, NULL, 'S'},
3761   {"as-flags", required_argument, NULL, 'f'},
3762   {"mcore-elf", required_argument, NULL, 'M'},
3763   {"compat-implib", no_argument, NULL, 'C'},
3764   {"temp-prefix", required_argument, NULL, 't'},
3765   {"output-delaylib", required_argument, NULL, 'y'},
3766   {NULL,0,NULL,0}
3767 };
3768 
3769 int main (int, char **);
3770 
3771 int
3772 main (int ac, char **av)
3773 {
3774   int c;
3775   int i;
3776   char *firstarg = 0;
3777   program_name = av[0];
3778   oav = av;
3779 
3780 #ifdef HAVE_LC_MESSAGES
3781   setlocale (LC_MESSAGES, "");
3782 #endif
3783   setlocale (LC_CTYPE, "");
3784   bindtextdomain (PACKAGE, LOCALEDIR);
3785   textdomain (PACKAGE);
3786 
3787   bfd_set_error_program_name (program_name);
3788   expandargv (&ac, &av);
3789 
3790   while ((c = getopt_long (ac, av,
3791 #ifdef DLLTOOL_MCORE_ELF
3792                            "m:e:l:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHhM:L:F:",
3793 #else
3794                            "m:e:l:y:aD:d:z:b:xp:cCuUkAS:t:f:nI:vVHh",
3795 #endif
3796 			   long_options, 0))
3797 	 != EOF)
3798     {
3799       switch (c)
3800 	{
3801 	case OPTION_EXPORT_ALL_SYMS:
3802 	  export_all_symbols = true;
3803 	  break;
3804 	case OPTION_NO_EXPORT_ALL_SYMS:
3805 	  export_all_symbols = false;
3806 	  break;
3807 	case OPTION_EXCLUDE_SYMS:
3808 	  add_excludes (optarg);
3809 	  break;
3810 	case OPTION_NO_DEFAULT_EXCLUDES:
3811 	  do_default_excludes = false;
3812 	  break;
3813 	case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
3814 	  use_nul_prefixed_import_tables = true;
3815 	  break;
3816 	case OPTION_ADD_STDCALL_UNDERSCORE:
3817 	  add_stdcall_underscore = 1;
3818 	  break;
3819 	case OPTION_NO_LEADING_UNDERSCORE:
3820 	  leading_underscore = 0;
3821 	  break;
3822 	case OPTION_LEADING_UNDERSCORE:
3823 	  leading_underscore = 1;
3824 	  break;
3825 	case OPTION_IDENTIFY_STRICT:
3826 	  identify_strict = 1;
3827 	  break;
3828 	case 'x':
3829 	  no_idata4 = 1;
3830 	  break;
3831 	case 'c':
3832 	  no_idata5 = 1;
3833 	  break;
3834 	case 'S':
3835 	  as_name = optarg;
3836 	  break;
3837 	case 't':
3838 	  tmp_prefix = optarg;
3839 	  break;
3840 	case 'f':
3841 	  as_flags = optarg;
3842 	  break;
3843 
3844 	  /* Ignored for compatibility.  */
3845 	case 'u':
3846 	  break;
3847 	case 'a':
3848 	  add_indirect = 1;
3849 	  break;
3850 	case 'z':
3851 	  output_def = fopen (optarg, FOPEN_WT);
3852 	  if (!output_def)
3853 	    /* xgettext:c-format */
3854 	    fatal (_("Unable to open def-file: %s"), optarg);
3855 	  break;
3856 	case 'D':
3857 	  dll_name = (char*) lbasename (optarg);
3858 	  if (dll_name != optarg)
3859 	    non_fatal (_("Path components stripped from dllname, '%s'."),
3860 	      		 optarg);
3861 	  break;
3862 	case 'l':
3863 	  imp_name = optarg;
3864 	  break;
3865 	case 'e':
3866 	  exp_name = optarg;
3867 	  break;
3868 	case 'H':
3869 	case 'h':
3870 	  usage (stdout, 0);
3871 	  break;
3872 	case 'm':
3873 	  mname = optarg;
3874 	  break;
3875 	case 'I':
3876 	  identify_imp_name = optarg;
3877 	  break;
3878 	case 'v':
3879 	  verbose = 1;
3880 	  break;
3881 	case 'V':
3882 	  print_version (program_name);
3883 	  break;
3884 	case 'U':
3885 	  add_underscore = 1;
3886 	  break;
3887 	case 'k':
3888 	  killat = 1;
3889 	  break;
3890 	case 'A':
3891 	  add_stdcall_alias = 1;
3892 	  break;
3893 	case 'p':
3894 	  ext_prefix_alias = optarg;
3895 	  break;
3896 	case 'd':
3897 	  def_file = optarg;
3898 	  break;
3899 	case 'n':
3900 	  dontdeltemps++;
3901 	  break;
3902 	case 'b':
3903 	  base_file = fopen (optarg, FOPEN_RB);
3904 
3905 	  if (!base_file)
3906 	    /* xgettext:c-format */
3907 	    fatal (_("Unable to open base-file: %s"), optarg);
3908 
3909 	  break;
3910 #ifdef DLLTOOL_MCORE_ELF
3911 	case 'M':
3912 	  mcore_elf_out_file = optarg;
3913 	  break;
3914 	case 'L':
3915 	  mcore_elf_linker = optarg;
3916 	  break;
3917 	case 'F':
3918 	  mcore_elf_linker_flags = optarg;
3919 	  break;
3920 #endif
3921 	case 'C':
3922 	  create_compat_implib = 1;
3923 	  break;
3924 	case 'y':
3925 	  delayimp_name = optarg;
3926 	  break;
3927 	default:
3928 	  usage (stderr, 1);
3929 	  break;
3930 	}
3931     }
3932 
3933   for (i = 0; mtable[i].type; i++)
3934     if (strcmp (mtable[i].type, mname) == 0)
3935       break;
3936 
3937   if (!mtable[i].type)
3938     /* xgettext:c-format */
3939     fatal (_("Machine '%s' not supported"), mname);
3940 
3941   machine = i;
3942 
3943   /* Check if we generated PE+.  */
3944   create_for_pep = strcmp (mname, "i386:x86-64") == 0;
3945 
3946   {
3947     /* Check the default underscore */
3948     int u = leading_underscore; /* Underscoring mode. -1 for use default.  */
3949     if (u == -1)
3950       bfd_get_target_info (mtable[machine].how_bfd_target, NULL,
3951                            NULL, &u, NULL);
3952     if (u != -1)
3953       leading_underscore = u != 0;
3954   }
3955 
3956   if (!dll_name && exp_name)
3957     {
3958       /* If we are inferring dll_name from exp_name,
3959          strip off any path components, without emitting
3960          a warning.  */
3961       const char* exp_basename = lbasename (exp_name);
3962       const int len = strlen (exp_basename) + 5;
3963       dll_name = xmalloc (len);
3964       strcpy (dll_name, exp_basename);
3965       strcat (dll_name, ".dll");
3966       dll_name_set_by_exp_name = 1;
3967     }
3968 
3969   if (as_name == NULL)
3970     as_name = deduce_name ("as");
3971 
3972   /* Don't use the default exclude list if we're reading only the
3973      symbols in the .drectve section.  The default excludes are meant
3974      to avoid exporting DLL entry point and Cygwin32 impure_ptr.  */
3975   if (! export_all_symbols)
3976     do_default_excludes = false;
3977 
3978   if (do_default_excludes)
3979     set_default_excludes ();
3980 
3981   if (def_file)
3982     process_def_file (def_file);
3983 
3984   while (optind < ac)
3985     {
3986       if (!firstarg)
3987 	firstarg = av[optind];
3988       scan_obj_file (av[optind]);
3989       optind++;
3990     }
3991 
3992   if (tmp_prefix == NULL)
3993     {
3994       /* If possible use a deterministic prefix.  */
3995       if (imp_name || delayimp_name)
3996         {
3997           const char *input = imp_name ? imp_name : delayimp_name;
3998           tmp_prefix = xmalloc (strlen (input) + 2);
3999           sprintf (tmp_prefix, "%s_", input);
4000           for (i = 0; tmp_prefix[i]; i++)
4001             if (!ISALNUM (tmp_prefix[i]))
4002               tmp_prefix[i] = '_';
4003         }
4004       else
4005         {
4006           tmp_prefix = prefix_encode ("d", getpid ());
4007         }
4008     }
4009 
4010   mangle_defs ();
4011 
4012   if (exp_name)
4013     gen_exp_file ();
4014 
4015   if (imp_name)
4016     {
4017       /* Make imp_name safe for use as a label.  */
4018       char *p;
4019 
4020       imp_name_lab = xstrdup (imp_name);
4021       for (p = imp_name_lab; *p; p++)
4022 	{
4023 	  if (!ISALNUM (*p))
4024 	    *p = '_';
4025 	}
4026       head_label = make_label("_head_", imp_name_lab);
4027       gen_lib_file (0);
4028     }
4029 
4030   if (delayimp_name)
4031     {
4032       /* Make delayimp_name safe for use as a label.  */
4033       char *p;
4034 
4035       if (mtable[machine].how_dljtab == 0)
4036         {
4037           inform (_("Warning, machine type (%d) not supported for "
4038 			"delayimport."), machine);
4039         }
4040       else
4041         {
4042           killat = 1;
4043           imp_name = delayimp_name;
4044           imp_name_lab = xstrdup (imp_name);
4045           for (p = imp_name_lab; *p; p++)
4046             {
4047               if (!ISALNUM (*p))
4048                 *p = '_';
4049             }
4050           head_label = make_label("__tailMerge_", imp_name_lab);
4051           gen_lib_file (1);
4052         }
4053     }
4054 
4055   if (output_def)
4056     gen_def_file ();
4057 
4058   if (identify_imp_name)
4059     {
4060       identify_dll_for_implib ();
4061     }
4062 
4063 #ifdef DLLTOOL_MCORE_ELF
4064   if (mcore_elf_out_file)
4065     mcore_elf_gen_out_file ();
4066 #endif
4067 
4068   return 0;
4069 }
4070 
4071 /* Look for the program formed by concatenating PROG_NAME and the
4072    string running from PREFIX to END_PREFIX.  If the concatenated
4073    string contains a '/', try appending EXECUTABLE_SUFFIX if it is
4074    appropriate.  */
4075 
4076 static char *
4077 look_for_prog (const char *prog_name, const char *prefix, int end_prefix)
4078 {
4079   struct stat s;
4080   char *cmd;
4081 
4082   cmd = xmalloc (strlen (prefix)
4083 		 + strlen (prog_name)
4084 #ifdef HAVE_EXECUTABLE_SUFFIX
4085 		 + strlen (EXECUTABLE_SUFFIX)
4086 #endif
4087 		 + 10);
4088   strcpy (cmd, prefix);
4089 
4090   sprintf (cmd + end_prefix, "%s", prog_name);
4091 
4092   if (strchr (cmd, '/') != NULL)
4093     {
4094       int found;
4095 
4096       found = (stat (cmd, &s) == 0
4097 #ifdef HAVE_EXECUTABLE_SUFFIX
4098 	       || stat (strcat (cmd, EXECUTABLE_SUFFIX), &s) == 0
4099 #endif
4100 	       );
4101 
4102       if (! found)
4103 	{
4104 	  /* xgettext:c-format */
4105 	  inform (_("Tried file: %s"), cmd);
4106 	  free (cmd);
4107 	  return NULL;
4108 	}
4109     }
4110 
4111   /* xgettext:c-format */
4112   inform (_("Using file: %s"), cmd);
4113 
4114   return cmd;
4115 }
4116 
4117 /* Deduce the name of the program we are want to invoke.
4118    PROG_NAME is the basic name of the program we want to run,
4119    eg "as" or "ld".  The catch is that we might want actually
4120    run "i386-pe-as".
4121 
4122    If argv[0] contains the full path, then try to find the program
4123    in the same place, with and then without a target-like prefix.
4124 
4125    Given, argv[0] = /usr/local/bin/i586-cygwin32-dlltool,
4126    deduce_name("as") uses the following search order:
4127 
4128      /usr/local/bin/i586-cygwin32-as
4129      /usr/local/bin/as
4130      as
4131 
4132    If there's an EXECUTABLE_SUFFIX, it'll use that as well; for each
4133    name, it'll try without and then with EXECUTABLE_SUFFIX.
4134 
4135    Given, argv[0] = i586-cygwin32-dlltool, it will not even try "as"
4136    as the fallback, but rather return i586-cygwin32-as.
4137 
4138    Oh, and given, argv[0] = dlltool, it'll return "as".
4139 
4140    Returns a dynamically allocated string.  */
4141 
4142 static char *
4143 deduce_name (const char *prog_name)
4144 {
4145   char *cmd;
4146   char *dash, *slash, *cp;
4147 
4148   dash = NULL;
4149   slash = NULL;
4150   for (cp = program_name; *cp != '\0'; ++cp)
4151     {
4152       if (*cp == '-')
4153 	dash = cp;
4154       if (
4155 #if defined(__DJGPP__) || defined (__CYGWIN__) || defined(__WIN32__)
4156 	  *cp == ':' || *cp == '\\' ||
4157 #endif
4158 	  *cp == '/')
4159 	{
4160 	  slash = cp;
4161 	  dash = NULL;
4162 	}
4163     }
4164 
4165   cmd = NULL;
4166 
4167   if (dash != NULL)
4168     {
4169       /* First, try looking for a prefixed PROG_NAME in the
4170          PROGRAM_NAME directory, with the same prefix as PROGRAM_NAME.  */
4171       cmd = look_for_prog (prog_name, program_name, dash - program_name + 1);
4172     }
4173 
4174   if (slash != NULL && cmd == NULL)
4175     {
4176       /* Next, try looking for a PROG_NAME in the same directory as
4177          that of this program.  */
4178       cmd = look_for_prog (prog_name, program_name, slash - program_name + 1);
4179     }
4180 
4181   if (cmd == NULL)
4182     {
4183       /* Just return PROG_NAME as is.  */
4184       cmd = xstrdup (prog_name);
4185     }
4186 
4187   return cmd;
4188 }
4189 
4190 #ifdef DLLTOOL_MCORE_ELF
4191 typedef struct fname_cache
4192 {
4193   const char *         filename;
4194   struct fname_cache * next;
4195 }
4196 fname_cache;
4197 
4198 static fname_cache fnames;
4199 
4200 static void
4201 mcore_elf_cache_filename (const char * filename)
4202 {
4203   fname_cache * ptr;
4204 
4205   ptr = & fnames;
4206 
4207   while (ptr->next != NULL)
4208     ptr = ptr->next;
4209 
4210   ptr->filename = filename;
4211   ptr->next     = (fname_cache *) malloc (sizeof (fname_cache));
4212   if (ptr->next != NULL)
4213     ptr->next->next = NULL;
4214 }
4215 
4216 #define MCORE_ELF_TMP_OBJ "mcoreelf.o"
4217 #define MCORE_ELF_TMP_EXP "mcoreelf.exp"
4218 #define MCORE_ELF_TMP_LIB "mcoreelf.lib"
4219 
4220 static void
4221 mcore_elf_gen_out_file (void)
4222 {
4223   fname_cache * ptr;
4224   dyn_string_t ds;
4225 
4226   /* Step one.  Run 'ld -r' on the input object files in order to resolve
4227      any internal references and to generate a single .exports section.  */
4228   ptr = & fnames;
4229 
4230   ds = dyn_string_new (100);
4231   dyn_string_append_cstr (ds, "-r ");
4232 
4233   if (mcore_elf_linker_flags != NULL)
4234     dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4235 
4236   while (ptr->next != NULL)
4237     {
4238       dyn_string_append_cstr (ds, ptr->filename);
4239       dyn_string_append_cstr (ds, " ");
4240 
4241       ptr = ptr->next;
4242     }
4243 
4244   dyn_string_append_cstr (ds, "-o ");
4245   dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4246 
4247   if (mcore_elf_linker == NULL)
4248     mcore_elf_linker = deduce_name ("ld");
4249 
4250   run (mcore_elf_linker, ds->s);
4251 
4252   dyn_string_delete (ds);
4253 
4254   /* Step two. Create a .exp file and a .lib file from the temporary file.
4255      Do this by recursively invoking dlltool...  */
4256   ds = dyn_string_new (100);
4257 
4258   dyn_string_append_cstr (ds, "-S ");
4259   dyn_string_append_cstr (ds, as_name);
4260 
4261   dyn_string_append_cstr (ds, " -e ");
4262   dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4263   dyn_string_append_cstr (ds, " -l ");
4264   dyn_string_append_cstr (ds, MCORE_ELF_TMP_LIB);
4265   dyn_string_append_cstr (ds, " " );
4266   dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4267 
4268   if (verbose)
4269     dyn_string_append_cstr (ds, " -v");
4270 
4271   if (dontdeltemps)
4272     {
4273       dyn_string_append_cstr (ds, " -n");
4274 
4275       if (dontdeltemps > 1)
4276 	dyn_string_append_cstr (ds, " -n");
4277     }
4278 
4279   /* XXX - FIME: ought to check/copy other command line options as well.  */
4280   run (program_name, ds->s);
4281 
4282   dyn_string_delete (ds);
4283 
4284   /* Step four. Feed the .exp and object files to ld -shared to create the dll.  */
4285   ds = dyn_string_new (100);
4286 
4287   dyn_string_append_cstr (ds, "-shared ");
4288 
4289   if (mcore_elf_linker_flags)
4290     dyn_string_append_cstr (ds, mcore_elf_linker_flags);
4291 
4292   dyn_string_append_cstr (ds, " ");
4293   dyn_string_append_cstr (ds, MCORE_ELF_TMP_EXP);
4294   dyn_string_append_cstr (ds, " ");
4295   dyn_string_append_cstr (ds, MCORE_ELF_TMP_OBJ);
4296   dyn_string_append_cstr (ds, " -o ");
4297   dyn_string_append_cstr (ds, mcore_elf_out_file);
4298 
4299   run (mcore_elf_linker, ds->s);
4300 
4301   dyn_string_delete (ds);
4302 
4303   if (dontdeltemps == 0)
4304     unlink (MCORE_ELF_TMP_EXP);
4305 
4306   if (dontdeltemps < 2)
4307     unlink (MCORE_ELF_TMP_OBJ);
4308 }
4309 #endif /* DLLTOOL_MCORE_ELF */
4310