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