Fixed a few prototypes in the USER driver.
[wine] / tools / winebuild / spec32.c
1 /*
2  * 32-bit spec files
3  *
4  * Copyright 1993 Robert J. Amstadt
5  * Copyright 1995 Martin von Loewis
6  * Copyright 1995, 1996, 1997 Alexandre Julliard
7  * Copyright 1997 Eric Youngdale
8  * Copyright 1999 Ulrich Weigand
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <ctype.h>
30 #include <stdarg.h>
31 #include <string.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "wine/exception.h"
36 #include "build.h"
37
38
39 static int string_compare( const void *ptr1, const void *ptr2 )
40 {
41     const char * const *str1 = ptr1;
42     const char * const *str2 = ptr2;
43     return strcmp( *str1, *str2 );
44 }
45
46
47 /*******************************************************************
48  *         make_internal_name
49  *
50  * Generate an internal name for an entry point. Used for stubs etc.
51  */
52 static const char *make_internal_name( const ORDDEF *odp, DLLSPEC *spec, const char *prefix )
53 {
54     static char buffer[256];
55     if (odp->name || odp->export_name)
56     {
57         char *p;
58         sprintf( buffer, "__wine_%s_%s_%s", prefix, spec->file_name,
59                  odp->name ? odp->name : odp->export_name );
60         /* make sure name is a legal C identifier */
61         for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
62         if (!*p) return buffer;
63     }
64     sprintf( buffer, "__wine_%s_%s_%d", prefix, make_c_identifier(spec->file_name), odp->ordinal );
65     return buffer;
66 }
67
68 /*******************************************************************
69  *         declare_weak_function
70  *
71  * Output a prototype for a weak function.
72  */
73 static void declare_weak_function( FILE *outfile, const char *ret_type, const char *name, const char *params)
74 {
75     fprintf( outfile, "#ifdef __GNUC__\n" );
76     if (target_platform == PLATFORM_APPLE)
77     {
78         fprintf( outfile, "extern %s %s(%s) __attribute__((weak_import));\n", ret_type, name, params );
79         fprintf( outfile, "static %s (*__wine_spec_weak_%s)(%s) = %s;\n", ret_type, name, params, name );
80         fprintf( outfile, "#define %s __wine_spec_weak_%s\n", name, name );
81         fprintf( outfile, "asm(\".weak_reference %s\");\n", asm_name(name) );
82     }
83     else fprintf( outfile, "extern %s %s(%s) __attribute__((weak));\n", ret_type, name, params );
84
85     fprintf( outfile, "#else\n" );
86     fprintf( outfile, "extern %s %s(%s);\n", ret_type, name, params );
87     fprintf( outfile, "static void __asm__dummy_%s(void)", name );
88     fprintf( outfile, " { asm(\".weak %s\"); }\n", asm_name(name) );
89     fprintf( outfile, "#endif\n\n" );
90 }
91
92
93 /*******************************************************************
94  *         output_debug
95  *
96  * Output the debug channels.
97  */
98 static int output_debug( FILE *outfile )
99 {
100     int i;
101
102     if (!nb_debug_channels) return 0;
103     qsort( debug_channels, nb_debug_channels, sizeof(debug_channels[0]), string_compare );
104
105     for (i = 0; i < nb_debug_channels; i++)
106         fprintf( outfile, "char __wine_dbch_%s[] = \"\\003%s\";\n",
107                  debug_channels[i], debug_channels[i] );
108
109     fprintf( outfile, "\nstatic char * const debug_channels[%d] =\n{\n", nb_debug_channels );
110     for (i = 0; i < nb_debug_channels; i++)
111     {
112         fprintf( outfile, "    __wine_dbch_%s", debug_channels[i] );
113         if (i < nb_debug_channels - 1) fprintf( outfile, ",\n" );
114     }
115     fprintf( outfile, "\n};\n\n" );
116     fprintf( outfile, "static void *debug_registration;\n\n" );
117
118     return nb_debug_channels;
119 }
120
121
122 /*******************************************************************
123  *         get_exports_size
124  *
125  * Compute the size of the export table.
126  */
127 static int get_exports_size( DLLSPEC *spec )
128 {
129     int nr_exports = spec->base <= spec->limit ? spec->limit - spec->base + 1 : 0;
130     int i, fwd_size = 0, total_size;
131
132     if (!nr_exports) return 0;
133
134     /* export directory header */
135     total_size = 10 * sizeof(int);
136
137     /* function pointers */
138     total_size += nr_exports * sizeof(int);
139
140     /* function name pointers */
141     total_size += spec->nb_names * sizeof(int);
142
143     /* function ordinals */
144     total_size += spec->nb_names * sizeof(short);
145     if (spec->nb_names % 2) total_size += sizeof(short);
146
147     /* forward strings */
148     for (i = spec->base; i <= spec->limit; i++)
149     {
150         ORDDEF *odp = spec->ordinals[i];
151         if (odp && odp->flags & FLAG_FORWARD) fwd_size += strlen(odp->link_name) + 1;
152     }
153     total_size += (fwd_size + 3) & ~3;
154
155     return total_size;
156 }
157
158
159 /*******************************************************************
160  *         output_export_names
161  *
162  * Output all the exported names for a Win32 module.
163  */
164 static void output_export_names( FILE *outfile, DLLSPEC *spec )
165 {
166     int i, nr_exports = spec->base <= spec->limit ? spec->limit - spec->base + 1 : 0;
167
168     if (!nr_exports) return;
169
170     fprintf( outfile, "\nconst char __wine_spec_exp_names[] =" );
171     fprintf( outfile, "\n    \"%s\\0\"", spec->file_name );
172     for (i = 0; i < spec->nb_names; i++)
173         fprintf( outfile, "\n    \"%s\\0\"", spec->names[i]->name );
174     fprintf( outfile, ";\n" );
175 }
176
177
178 /*******************************************************************
179  *         output_exports
180  *
181  * Output the export table for a Win32 module.
182  */
183 static void output_exports( FILE *outfile, DLLSPEC *spec )
184 {
185     int i, fwd_size = 0;
186     int nr_exports = spec->base <= spec->limit ? spec->limit - spec->base + 1 : 0;
187
188     if (!nr_exports) return;
189
190     fprintf( outfile, "/* export table */\n" );
191     fprintf( outfile, "asm(\".data\\n\"\n" );
192     fprintf( outfile, "    \"\\t.align %d\\n\"\n", get_alignment(4) );
193     fprintf( outfile, "    \"%s:\\n\"\n", asm_name("__wine_spec_exports") );
194
195     /* export directory header */
196
197     fprintf( outfile, "    \"\\t.long 0\\n\"\n" );                 /* Characteristics */
198     fprintf( outfile, "    \"\\t.long 0\\n\"\n" );                 /* TimeDateStamp */
199     fprintf( outfile, "    \"\\t.long 0\\n\"\n" );                 /* MajorVersion/MinorVersion */
200     fprintf( outfile, "    \"\\t.long %s\\n\"\n", asm_name("__wine_spec_exp_names") ); /* Name */
201     fprintf( outfile, "    \"\\t.long %d\\n\"\n", spec->base );        /* Base */
202     fprintf( outfile, "    \"\\t.long %d\\n\"\n", nr_exports );        /* NumberOfFunctions */
203     fprintf( outfile, "    \"\\t.long %d\\n\"\n", spec->nb_names );    /* NumberOfNames */
204     fprintf( outfile, "    \"\\t.long __wine_spec_exports_funcs\\n\"\n" ); /* AddressOfFunctions */
205     if (spec->nb_names)
206     {
207         fprintf( outfile, "    \"\\t.long __wine_spec_exp_name_ptrs\\n\"\n" );     /* AddressOfNames */
208         fprintf( outfile, "    \"\\t.long __wine_spec_exp_ordinals\\n\"\n" );  /* AddressOfNameOrdinals */
209     }
210     else
211     {
212         fprintf( outfile, "    \"\\t.long 0\\n\"\n" );  /* AddressOfNames */
213         fprintf( outfile, "    \"\\t.long 0\\n\"\n" );  /* AddressOfNameOrdinals */
214     }
215
216     /* output the function pointers */
217
218     fprintf( outfile, "    \"__wine_spec_exports_funcs:\\n\"\n" );
219     for (i = spec->base; i <= spec->limit; i++)
220     {
221         ORDDEF *odp = spec->ordinals[i];
222         if (!odp) fprintf( outfile, "    \"\\t.long 0\\n\"\n" );
223         else switch(odp->type)
224         {
225         case TYPE_EXTERN:
226         case TYPE_STDCALL:
227         case TYPE_VARARGS:
228         case TYPE_CDECL:
229             if (!(odp->flags & FLAG_FORWARD))
230             {
231                 fprintf( outfile, "    \"\\t.long %s\\n\"\n", asm_name(odp->link_name) );
232             }
233             else
234             {
235                 fprintf( outfile, "    \"\\t.long __wine_spec_forwards+%d\\n\"\n", fwd_size );
236                 fwd_size += strlen(odp->link_name) + 1;
237             }
238             break;
239         case TYPE_STUB:
240             fprintf( outfile, "    \"\\t.long %s\\n\"\n",
241                      asm_name( make_internal_name( odp, spec, "stub" )) );
242             break;
243         default:
244             assert(0);
245         }
246     }
247
248     if (spec->nb_names)
249     {
250         /* output the function name pointers */
251
252         int namepos = strlen(spec->file_name) + 1;
253
254         fprintf( outfile, "    \"__wine_spec_exp_name_ptrs:\\n\"\n" );
255         for (i = 0; i < spec->nb_names; i++)
256         {
257             fprintf( outfile, "    \"\\t.long %s+%d\\n\"\n", asm_name("__wine_spec_exp_names"), namepos );
258             namepos += strlen(spec->names[i]->name) + 1;
259         }
260     }
261
262     if (spec->nb_names)
263     {
264         /* output the function ordinals */
265
266         fprintf( outfile, "    \"__wine_spec_exp_ordinals:\\n\"\n" );
267         for (i = 0; i < spec->nb_names; i++)
268         {
269             fprintf( outfile, "    \"\\t%s %d\\n\"\n",
270                      get_asm_short_keyword(), spec->names[i]->ordinal - spec->base );
271         }
272         if (spec->nb_names % 2)
273         {
274             fprintf( outfile, "    \"\\t%s 0\\n\"\n", get_asm_short_keyword() );
275         }
276     }
277
278     /* output forward strings */
279
280     if (fwd_size)
281     {
282         fprintf( outfile, "    \"__wine_spec_forwards:\\n\"\n" );
283         for (i = spec->base; i <= spec->limit; i++)
284         {
285             ORDDEF *odp = spec->ordinals[i];
286             if (odp && (odp->flags & FLAG_FORWARD))
287                 fprintf( outfile, "    \"\\t%s \\\"%s\\\"\\n\"\n", get_asm_string_keyword(), odp->link_name );
288         }
289         fprintf( outfile, "    \"\\t.align %d\\n\"\n", get_alignment(4) );
290     }
291
292     /* output relays */
293
294     /* we only support relay debugging on i386 */
295     if (target_cpu == CPU_x86)
296     {
297         for (i = spec->base; i <= spec->limit; i++)
298         {
299             ORDDEF *odp = spec->ordinals[i];
300             unsigned int j, args, mask = 0;
301
302             /* skip nonexistent entry points */
303             if (!odp) goto ignore;
304             /* skip non-functions */
305             if ((odp->type != TYPE_STDCALL) && (odp->type != TYPE_CDECL)) goto ignore;
306             /* skip norelay and forward entry points */
307             if (odp->flags & (FLAG_NORELAY|FLAG_FORWARD)) goto ignore;
308
309             for (j = 0; odp->u.func.arg_types[j]; j++)
310             {
311                 if (odp->u.func.arg_types[j] == 't') mask |= 1<< (j*2);
312                 if (odp->u.func.arg_types[j] == 'W') mask |= 2<< (j*2);
313             }
314             if ((odp->flags & FLAG_RET64) && (j < 16)) mask |= 0x80000000;
315
316             args = strlen(odp->u.func.arg_types) * sizeof(int);
317
318             switch(odp->type)
319             {
320             case TYPE_STDCALL:
321                 fprintf( outfile, "    \"\\tjmp %s\\n\"\n", asm_name(odp->link_name) );
322                 fprintf( outfile, "    \"\\tret $%d\\n\"\n", args );
323                 fprintf( outfile, "    \"\\t.long %s,0x%08x\\n\"\n", asm_name(odp->link_name), mask );
324                 break;
325             case TYPE_CDECL:
326                 fprintf( outfile, "    \"\\tjmp %s\\n\"\n", asm_name(odp->link_name) );
327                 fprintf( outfile, "    \"\\tret\\n\"\n" );
328                 fprintf( outfile, "    \"\\t%s %d\\n\"\n", get_asm_short_keyword(), args );
329                 fprintf( outfile, "    \"\\t.long %s,0x%08x\\n\"\n", asm_name(odp->link_name), mask );
330                 break;
331             default:
332                 assert(0);
333             }
334             continue;
335
336         ignore:
337             fprintf( outfile, "    \"\\t.long 0,0,0,0\\n\"\n" );
338         }
339     }
340     fprintf( outfile, ");\n" );
341 }
342
343
344 /*******************************************************************
345  *         output_stub_funcs
346  *
347  * Output the functions for stub entry points
348 */
349 static void output_stub_funcs( FILE *outfile, DLLSPEC *spec )
350 {
351     int i;
352
353     for (i = 0; i < spec->nb_entry_points; i++)
354     {
355         ORDDEF *odp = &spec->entry_points[i];
356         if (odp->type != TYPE_STUB) continue;
357         fprintf( outfile, "#ifdef __GNUC__\n" );
358         fprintf( outfile, "static void __wine_unimplemented( const char *func ) __attribute__((noreturn));\n" );
359         fprintf( outfile, "#endif\n\n" );
360         fprintf( outfile, "struct exc_record {\n" );
361         fprintf( outfile, "  unsigned int code, flags;\n" );
362         fprintf( outfile, "  void *rec, *addr;\n" );
363         fprintf( outfile, "  unsigned int params;\n" );
364         fprintf( outfile, "  const void *info[15];\n" );
365         fprintf( outfile, "};\n\n" );
366         fprintf( outfile, "extern void __stdcall RtlRaiseException( struct exc_record * );\n\n" );
367         fprintf( outfile, "static void __wine_unimplemented( const char *func )\n{\n" );
368         fprintf( outfile, "  struct exc_record rec;\n" );
369         fprintf( outfile, "  rec.code    = 0x%08x;\n", EXCEPTION_WINE_STUB );
370         fprintf( outfile, "  rec.flags   = %d;\n", EH_NONCONTINUABLE );
371         fprintf( outfile, "  rec.rec     = 0;\n" );
372         fprintf( outfile, "  rec.params  = 2;\n" );
373         fprintf( outfile, "  rec.info[0] = \"%s\";\n", spec->file_name );
374         fprintf( outfile, "  rec.info[1] = func;\n" );
375         fprintf( outfile, "#ifdef __GNUC__\n" );
376         fprintf( outfile, "  rec.addr = __builtin_return_address(1);\n" );
377         fprintf( outfile, "#else\n" );
378         fprintf( outfile, "  rec.addr = 0;\n" );
379         fprintf( outfile, "#endif\n" );
380         fprintf( outfile, "  for (;;) RtlRaiseException( &rec );\n}\n\n" );
381         break;
382     }
383
384     for (i = 0; i < spec->nb_entry_points; i++)
385     {
386         const ORDDEF *odp = &spec->entry_points[i];
387         if (odp->type != TYPE_STUB) continue;
388         fprintf( outfile, "void %s(void) ", make_internal_name( odp, spec, "stub" ) );
389         if (odp->name)
390             fprintf( outfile, "{ __wine_unimplemented(\"%s\"); }\n", odp->name );
391         else if (odp->export_name)
392             fprintf( outfile, "{ __wine_unimplemented(\"%s\"); }\n", odp->export_name );
393         else
394             fprintf( outfile, "{ __wine_unimplemented(\"%d\"); }\n", odp->ordinal );
395     }
396 }
397
398
399 /*******************************************************************
400  *         output_dll_init
401  *
402  * Output code for calling a dll constructor and destructor.
403  */
404 void output_dll_init( FILE *outfile, const char *constructor, const char *destructor )
405 {
406     if (target_platform == PLATFORM_APPLE)
407     {
408         /* Mach-O doesn't have an init section */
409         if (constructor)
410         {
411             fprintf( outfile, "asm(\"\\t.mod_init_func\\n\"\n" );
412             fprintf( outfile, "    \"\\t.align 2\\n\"\n" );
413             fprintf( outfile, "    \"\\t.long %s\\n\"\n", asm_name(constructor) );
414             fprintf( outfile, "    \"\\t.text\\n\");\n" );
415         }
416         if (destructor)
417         {
418             fprintf( outfile, "asm(\"\\t.mod_term_func\\n\"\n" );
419             fprintf( outfile, "    \"\\t.align 2\\n\"\n" );
420             fprintf( outfile, "    \"\\t.long %s\\n\"\n", asm_name(destructor) );
421             fprintf( outfile, "    \"\\t.text\\n\");\n" );
422         }
423     }
424     else switch(target_cpu)
425     {
426     case CPU_x86:
427         if (constructor)
428         {
429             fprintf( outfile, "asm(\"\\t.section\\t\\\".init\\\" ,\\\"ax\\\"\\n\"\n" );
430             fprintf( outfile, "    \"\\tcall %s\\n\"\n", asm_name(constructor) );
431             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
432         }
433         if (destructor)
434         {
435             fprintf( outfile, "asm(\"\\t.section\\t\\\".fini\\\" ,\\\"ax\\\"\\n\"\n" );
436             fprintf( outfile, "    \"\\tcall %s\\n\"\n", asm_name(destructor) );
437             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
438         }
439         break;
440     case CPU_SPARC:
441         if (constructor)
442         {
443             fprintf( outfile, "asm(\"\\t.section\\t\\\".init\\\" ,\\\"ax\\\"\\n\"\n" );
444             fprintf( outfile, "    \"\\tcall %s\\n\"\n", asm_name(constructor) );
445             fprintf( outfile, "    \"\\tnop\\n\"\n" );
446             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
447         }
448         if (destructor)
449         {
450             fprintf( outfile, "asm(\"\\t.section\\t\\\".fini\\\" ,\\\"ax\\\"\\n\"\n" );
451             fprintf( outfile, "    \"\\tcall %s\\n\"\n", asm_name(destructor) );
452             fprintf( outfile, "    \"\\tnop\\n\"\n" );
453             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
454         }
455         break;
456     case CPU_ALPHA:
457         if (constructor)
458         {
459             fprintf( outfile, "asm(\"\\t.section\\t\\\".init\\\" ,\\\"ax\\\"\\n\"\n" );
460             fprintf( outfile, "    \"\\tjsr $26,%s\\n\"\n", asm_name(constructor) );
461             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
462         }
463         if (destructor)
464         {
465             fprintf( outfile, "asm(\"\\t.section\\t\\\".fini\\\" ,\\\"ax\\\"\\n\"\n" );
466             fprintf( outfile, "    \"\\tjsr $26,%s\\n\"\n", asm_name(destructor) );
467             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
468         }
469         break;
470     case CPU_POWERPC:
471         if (constructor)
472         {
473             fprintf( outfile, "asm(\"\\t.section\\t\\\".init\\\" ,\\\"ax\\\"\\n\"\n" );
474             fprintf( outfile, "    \"\\tbl %s\\n\"\n", asm_name(constructor) );
475             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
476         }
477         if (destructor)
478         {
479             fprintf( outfile, "asm(\"\\t.section\\t\\\".fini\\\" ,\\\"ax\\\"\\n\"\n" );
480             fprintf( outfile, "    \"\\tbl %s\\n\"\n", asm_name(destructor) );
481             fprintf( outfile, "    \"\\t.section\\t\\\".text\\\"\\n\");\n" );
482         }
483         break;
484     }
485 }
486
487
488 /*******************************************************************
489  *         BuildSpec32File
490  *
491  * Build a Win32 C file from a spec file.
492  */
493 void BuildSpec32File( FILE *outfile, DLLSPEC *spec )
494 {
495     int exports_size = 0;
496     int nr_exports, nr_imports, nr_delayed;
497     unsigned int page_size = get_page_size();
498     const char *init_func = spec->init_func;
499
500     nr_exports = spec->base <= spec->limit ? spec->limit - spec->base + 1 : 0;
501     resolve_imports( spec );
502     exports_size = get_exports_size( spec );
503     output_standard_file_header( outfile );
504
505     /* Reserve some space for the PE header */
506
507     fprintf( outfile, "extern char __wine_spec_pe_header[];\n" );
508     fprintf( outfile, "#ifndef __GNUC__\n" );
509     fprintf( outfile, "static void __asm__dummy_header(void) {\n" );
510     fprintf( outfile, "#endif\n" );
511     fprintf( outfile, "asm(\".text\\n\\t\"\n" );
512     fprintf( outfile, "    \".align %d\\n\"\n", get_alignment(page_size) );
513     fprintf( outfile, "    \"%s:\\t\"\n", asm_name("__wine_spec_pe_header") );
514     if (target_platform == PLATFORM_APPLE)
515         fprintf( outfile, "    \".space 65536\\n\\t\"\n" );
516     else
517         fprintf( outfile, "    \".skip 65536\\n\\t\"\n" );
518     fprintf( outfile, "    \".data\\n\\t\"\n" );
519     fprintf( outfile, "    \".align %d\\n\"\n", get_alignment(4) );
520     fprintf( outfile, "    \"%s:\\t.long 1\");\n", asm_name("__wine_spec_data_start") );
521     fprintf( outfile, "#ifndef __GNUC__\n" );
522     fprintf( outfile, "}\n" );
523     fprintf( outfile, "#endif\n" );
524
525     if (target_platform == PLATFORM_APPLE)
526         fprintf( outfile, "static char _end[4];\n" );
527     else
528         fprintf( outfile, "extern char _end[];\n" );
529
530     fprintf( outfile, "extern int __wine_spec_data_start[], __wine_spec_exports[];\n\n" );
531
532     if (target_cpu == CPU_x86)
533         fprintf( outfile, "#define __stdcall __attribute__((__stdcall__))\n\n" );
534     else
535         fprintf( outfile, "#define __stdcall\n\n" );
536
537     output_stub_funcs( outfile, spec );
538     output_export_names( outfile, spec );
539
540     /* Output the DLL imports */
541
542     nr_imports = output_imports( outfile, spec, &nr_delayed );
543
544     /* Output the resources */
545
546     output_resources( outfile, spec );
547
548     /* Output the entry point function */
549
550     fprintf( outfile, "static int __wine_spec_init_state;\n" );
551     fprintf( outfile, "extern int __wine_main_argc;\n" );
552     fprintf( outfile, "extern char **__wine_main_argv;\n" );
553     fprintf( outfile, "extern char **__wine_main_environ;\n" );
554     fprintf( outfile, "extern unsigned short **__wine_main_wargv;\n" );
555     if (target_platform == PLATFORM_APPLE)
556     {
557         fprintf( outfile, "extern _dyld_func_lookup(char *, void *);" );
558         fprintf( outfile, "static void __wine_spec_hidden_init(int argc, char** argv, char** envp)\n" );
559         fprintf( outfile, "{\n" );
560         fprintf( outfile, "    void (*init)(void);\n" );
561         fprintf( outfile, "    _dyld_func_lookup(\"__dyld_make_delayed_module_initializer_calls\", (unsigned long *)&init);\n" );
562         fprintf( outfile, "    init();\n" );
563         fprintf( outfile, "}\n" );
564         fprintf( outfile, "static void __wine_spec_hidden_fini()\n" );
565         fprintf( outfile, "{\n" );
566         fprintf( outfile, "    void (*fini)(void);\n" );
567         fprintf( outfile, "    _dyld_func_lookup(\"__dyld_mod_term_funcs\", (unsigned long *)&fini);\n" );
568         fprintf( outfile, "    fini();\n" );
569         fprintf( outfile, "}\n" );
570         fprintf( outfile, "#define _init __wine_spec_hidden_init\n" );
571         fprintf( outfile, "#define _fini __wine_spec_hidden_fini\n" );
572     }
573     else
574     {
575         fprintf( outfile, "extern void _init(int, char**, char**);\n" );
576         fprintf( outfile, "extern void _fini();\n" );
577     }
578
579     if (spec->characteristics & IMAGE_FILE_DLL)
580     {
581         if (init_func)
582             fprintf( outfile, "extern int __stdcall %s( void*, unsigned int, void* );\n\n", init_func );
583         else
584         {
585             declare_weak_function( outfile, "int __stdcall", "DllMain", "void*, unsigned int, void*" );
586             init_func = "DllMain";
587         }
588         fprintf( outfile,
589                  "static int __stdcall __wine_dll_main( void *inst, unsigned int reason, void *reserved )\n"
590                  "{\n"
591                  "    int ret;\n"
592                  "    if (reason == %d && __wine_spec_init_state == 1)\n"
593                  "        _init( __wine_main_argc, __wine_main_argv, __wine_main_environ );\n"
594                  "    ret = %s ? %s( inst, reason, reserved ) : 1;\n"
595                  "    if (reason == %d && __wine_spec_init_state == 1)\n",
596                  DLL_PROCESS_ATTACH, init_func, init_func, DLL_PROCESS_DETACH );
597         if (!nr_delayed)
598             fprintf( outfile, "        _fini();\n" );
599         else
600             fprintf( outfile,
601                      "    {\n"
602                      "        extern int __stdcall FreeLibrary(void *);\n"
603                      "        unsigned int i;\n"
604                      "        _fini();\n"
605                      "        for (i = 0; i < sizeof(__wine_delay_imp_hmod)/sizeof(__wine_delay_imp_hmod[0]); i++)\n"
606                      "            if (__wine_delay_imp_hmod[i]) FreeLibrary( __wine_delay_imp_hmod[i] );\n"
607                      "    }\n" );
608         fprintf( outfile, "    return ret;\n}\n" );
609         init_func = "__wine_dll_main";
610     }
611     else switch(spec->subsystem)
612     {
613     case IMAGE_SUBSYSTEM_NATIVE:
614         if (init_func)
615             fprintf( outfile, "extern int __stdcall %s( void*, void* );\n\n", init_func );
616         else
617         {
618             declare_weak_function( outfile, "int __stdcall", "DriverEntry", "void*, void*");
619             init_func = "DriverEntry";
620         }
621         fprintf( outfile,
622                  "static int __stdcall __wine_driver_entry( void *obj, void *path )\n"
623                  "{\n"
624                  "    int ret;\n"
625                  "    if (__wine_spec_init_state == 1)\n"
626                  "        _init( __wine_main_argc, __wine_main_argv, __wine_main_environ );\n"
627                  "    ret = %s ? %s( obj, path ) : 0;\n"
628                  "    if (__wine_spec_init_state == 1) _fini();\n"
629                  "    return ret;\n"
630                  "}\n",
631                  init_func, init_func );
632         init_func = "__wine_driver_entry";
633         break;
634     case IMAGE_SUBSYSTEM_WINDOWS_GUI:
635     case IMAGE_SUBSYSTEM_WINDOWS_CUI:
636         if (init_func)
637             fprintf( outfile, "extern int %s( int argc, char *argv[] );\n", init_func );
638         else
639         {
640             declare_weak_function( outfile, "int", "main", "int argc, char *argv[]" );
641             declare_weak_function( outfile, "int", "wmain", "int argc, unsigned short *argv[]" );
642             declare_weak_function( outfile, "int __stdcall", "WinMain", "void *,void *,char *,int" );
643         }
644         fprintf( outfile,
645                  "\ntypedef struct {\n"
646                  "    unsigned int cb;\n"
647                  "    char *lpReserved, *lpDesktop, *lpTitle;\n"
648                  "    unsigned int dwX, dwY, dwXSize, dwYSize;\n"
649                  "    unsigned int dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;\n"
650                  "    unsigned short wShowWindow, cbReserved2;\n"
651                  "    char *lpReserved2;\n"
652                  "    void *hStdInput, *hStdOutput, *hStdError;\n"
653                  "} STARTUPINFOA;\n"
654                  "extern char * __stdcall GetCommandLineA(void);\n"
655                  "extern void * __stdcall GetModuleHandleA(char *);\n"
656                  "extern void __stdcall GetStartupInfoA(STARTUPINFOA *);\n"
657                  "extern void __stdcall ExitProcess(unsigned int);\n"
658                  "static void __wine_exe_main(void)\n"
659                  "{\n"
660                  "    int ret;\n"
661                  "    if (__wine_spec_init_state == 1)\n"
662                  "        _init( __wine_main_argc, __wine_main_argv, __wine_main_environ );\n" );
663         if (init_func)
664             fprintf( outfile,
665                      "    ret = %s( __wine_main_argc, __wine_main_argv );\n", init_func );
666         else
667             fprintf( outfile,
668                      "    if (WinMain) {\n"
669                      "        STARTUPINFOA info;\n"
670                      "        char *cmdline = GetCommandLineA();\n"
671                      "        int bcount=0, in_quotes=0;\n"
672                      "        while (*cmdline) {\n"
673                      "            if ((*cmdline=='\\t' || *cmdline==' ') && !in_quotes) break;\n"
674                      "            else if (*cmdline=='\\\\') bcount++;\n"
675                      "            else if (*cmdline=='\\\"') {\n"
676                      "                if ((bcount & 1)==0) in_quotes=!in_quotes;\n"
677                      "                bcount=0;\n"
678                      "            }\n"
679                      "            else bcount=0;\n"
680                      "            cmdline++;\n"
681                      "        }\n"
682                      "        while (*cmdline=='\\t' || *cmdline==' ') cmdline++;\n"
683                      "        GetStartupInfoA( &info );\n"
684                      "        if (!(info.dwFlags & 1)) info.wShowWindow = 1;\n"
685                      "        ret = WinMain( GetModuleHandleA(0), 0, cmdline, info.wShowWindow );\n"
686                      "    }\n"
687                      "    else if (wmain) ret = wmain( __wine_main_argc, __wine_main_wargv );\n"
688                      "    else ret = main( __wine_main_argc, __wine_main_argv );\n" );
689         fprintf( outfile,
690                  "    if (__wine_spec_init_state == 1) _fini();\n"
691                  "    ExitProcess( ret );\n"
692                  "}\n\n" );
693         init_func = "__wine_exe_main";
694         break;
695     }
696
697     /* Output the NT header */
698
699     /* this is the IMAGE_NT_HEADERS structure, but we cannot include winnt.h here */
700     fprintf( outfile, "static const struct image_nt_headers\n{\n" );
701     fprintf( outfile, "  int Signature;\n" );
702     fprintf( outfile, "  struct file_header {\n" );
703     fprintf( outfile, "    short Machine;\n" );
704     fprintf( outfile, "    short NumberOfSections;\n" );
705     fprintf( outfile, "    int   TimeDateStamp;\n" );
706     fprintf( outfile, "    void *PointerToSymbolTable;\n" );
707     fprintf( outfile, "    int   NumberOfSymbols;\n" );
708     fprintf( outfile, "    short SizeOfOptionalHeader;\n" );
709     fprintf( outfile, "    short Characteristics;\n" );
710     fprintf( outfile, "  } FileHeader;\n" );
711     fprintf( outfile, "  struct opt_header {\n" );
712     fprintf( outfile, "    short Magic;\n" );
713     fprintf( outfile, "    char  MajorLinkerVersion, MinorLinkerVersion;\n" );
714     fprintf( outfile, "    int   SizeOfCode;\n" );
715     fprintf( outfile, "    int   SizeOfInitializedData;\n" );
716     fprintf( outfile, "    int   SizeOfUninitializedData;\n" );
717     fprintf( outfile, "    void *AddressOfEntryPoint;\n" );
718     fprintf( outfile, "    void *BaseOfCode;\n" );
719     fprintf( outfile, "    void *BaseOfData;\n" );
720     fprintf( outfile, "    void *ImageBase;\n" );
721     fprintf( outfile, "    int   SectionAlignment;\n" );
722     fprintf( outfile, "    int   FileAlignment;\n" );
723     fprintf( outfile, "    short MajorOperatingSystemVersion;\n" );
724     fprintf( outfile, "    short MinorOperatingSystemVersion;\n" );
725     fprintf( outfile, "    short MajorImageVersion;\n" );
726     fprintf( outfile, "    short MinorImageVersion;\n" );
727     fprintf( outfile, "    short MajorSubsystemVersion;\n" );
728     fprintf( outfile, "    short MinorSubsystemVersion;\n" );
729     fprintf( outfile, "    int   Win32VersionValue;\n" );
730     fprintf( outfile, "    void *SizeOfImage;\n" );
731     fprintf( outfile, "    int   SizeOfHeaders;\n" );
732     fprintf( outfile, "    int   CheckSum;\n" );
733     fprintf( outfile, "    short Subsystem;\n" );
734     fprintf( outfile, "    short DllCharacteristics;\n" );
735     fprintf( outfile, "    int   SizeOfStackReserve;\n" );
736     fprintf( outfile, "    int   SizeOfStackCommit;\n" );
737     fprintf( outfile, "    int   SizeOfHeapReserve;\n" );
738     fprintf( outfile, "    int   SizeOfHeapCommit;\n" );
739     fprintf( outfile, "    int   LoaderFlags;\n" );
740     fprintf( outfile, "    int   NumberOfRvaAndSizes;\n" );
741     fprintf( outfile, "    struct { const void *VirtualAddress; int Size; } DataDirectory[%d];\n",
742              IMAGE_NUMBEROF_DIRECTORY_ENTRIES );
743     fprintf( outfile, "  } OptionalHeader;\n" );
744     fprintf( outfile, "} nt_header = {\n" );
745     fprintf( outfile, "  0x%04x,\n", IMAGE_NT_SIGNATURE );   /* Signature */
746     switch(target_cpu)
747     {
748     case CPU_x86:
749         fprintf( outfile, "  { 0x%04x,\n", IMAGE_FILE_MACHINE_I386 );  /* Machine */
750         break;
751     case CPU_POWERPC:
752         fprintf( outfile, "  { 0x%04x,\n", IMAGE_FILE_MACHINE_POWERPC ); /* Machine */
753         break;
754     case CPU_ALPHA:
755         fprintf( outfile, "  { 0x%04x,\n", IMAGE_FILE_MACHINE_ALPHA ); /* Machine */
756         break;
757     case CPU_SPARC:
758         fprintf( outfile, "  { 0x%04x,\n", IMAGE_FILE_MACHINE_UNKNOWN );  /* Machine */
759         break;
760     }
761     fprintf( outfile, "    0, 0, 0, 0,\n" );
762     fprintf( outfile, "    sizeof(nt_header.OptionalHeader),\n" ); /* SizeOfOptionalHeader */
763     fprintf( outfile, "    0x%04x },\n", spec->characteristics );  /* Characteristics */
764
765     fprintf( outfile, "  { 0x%04x,\n", IMAGE_NT_OPTIONAL_HDR_MAGIC );  /* Magic */
766     fprintf( outfile, "    0, 0,\n" );                   /* Major/MinorLinkerVersion */
767     fprintf( outfile, "    0, 0, 0,\n" );                /* SizeOfCode/Data */
768     fprintf( outfile, "    %s,\n", init_func );          /* AddressOfEntryPoint */
769     fprintf( outfile, "    0, __wine_spec_data_start,\n" );              /* BaseOfCode/Data */
770     fprintf( outfile, "    __wine_spec_pe_header,\n" );  /* ImageBase */
771     fprintf( outfile, "    %u,\n", page_size );          /* SectionAlignment */
772     fprintf( outfile, "    %u,\n", page_size );          /* FileAlignment */
773     fprintf( outfile, "    1, 0,\n" );                   /* Major/MinorOperatingSystemVersion */
774     fprintf( outfile, "    0, 0,\n" );                   /* Major/MinorImageVersion */
775     fprintf( outfile, "    %d,\n", spec->subsystem_major );             /* MajorSubsystemVersion */
776     fprintf( outfile, "    %d,\n", spec->subsystem_minor );             /* MinorSubsystemVersion */
777     fprintf( outfile, "    0,\n" );                      /* Win32VersionValue */
778     fprintf( outfile, "    _end,\n" );                   /* SizeOfImage */
779     fprintf( outfile, "    %u,\n", page_size );          /* SizeOfHeaders */
780     fprintf( outfile, "    0,\n" );                      /* CheckSum */
781     fprintf( outfile, "    0x%04x,\n", spec->subsystem );/* Subsystem */
782     fprintf( outfile, "    0,\n" );                      /* DllCharacteristics */
783     fprintf( outfile, "    %u, %u,\n",                   /* SizeOfStackReserve/Commit */
784              (spec->stack_size ? spec->stack_size : 1024) * 1024, page_size );
785     fprintf( outfile, "    %u, %u,\n",                   /* SizeOfHeapReserve/Commit */
786              (spec->heap_size ? spec->heap_size : 1024) * 1024, page_size );
787     fprintf( outfile, "    0,\n" );                      /* LoaderFlags */
788     fprintf( outfile, "    %d,\n", IMAGE_NUMBEROF_DIRECTORY_ENTRIES );  /* NumberOfRvaAndSizes */
789     fprintf( outfile, "    {\n" );
790     fprintf( outfile, "      { %s, %d },\n",  /* IMAGE_DIRECTORY_ENTRY_EXPORT */
791              exports_size ? "__wine_spec_exports" : "0", exports_size );
792     fprintf( outfile, "      { %s, %s },\n",  /* IMAGE_DIRECTORY_ENTRY_IMPORT */
793              nr_imports ? "&imports" : "0", nr_imports ? "sizeof(imports)" : "0" );
794     fprintf( outfile, "      { %s, %s },\n",   /* IMAGE_DIRECTORY_ENTRY_RESOURCE */
795              spec->nb_resources ? "&__wine_spec_resources" : "0",
796              spec->nb_resources ? "sizeof(__wine_spec_resources)" : "0" );
797     fprintf( outfile, "    }\n  }\n};\n\n" );
798
799     /* Output the DLL constructor */
800
801     fprintf( outfile,
802              "void __wine_spec_init(void)\n"
803              "{\n"
804              "    extern void __wine_dll_register( const struct image_nt_headers *, const char * );\n"
805              "    __wine_spec_init_state = 1;\n"
806              "    __wine_dll_register( &nt_header, \"%s\" );\n"
807              "}\n\n",
808              spec->file_name );
809
810     fprintf( outfile,
811              "void __wine_spec_init_ctor(void)\n"
812              "{\n"
813              "    if (__wine_spec_init_state) return;\n"
814              "    __wine_spec_init();\n"
815              "    __wine_spec_init_state = 2;\n"
816              "}\n" );
817
818     fprintf( outfile, "#ifndef __GNUC__\n" );
819     fprintf( outfile, "static void __asm__dummy(void) {\n" );
820     fprintf( outfile, "#endif\n" );
821
822     output_exports( outfile, spec );
823     output_import_thunks( outfile, spec );
824     output_dll_init( outfile, "__wine_spec_init_ctor", NULL );
825
826     fprintf( outfile, "#ifndef __GNUC__\n" );
827     fprintf( outfile, "}\n" );
828     fprintf( outfile, "#endif\n" );
829 }
830
831
832 /*******************************************************************
833  *         BuildDef32File
834  *
835  * Build a Win32 def file from a spec file.
836  */
837 void BuildDef32File( FILE *outfile, DLLSPEC *spec )
838 {
839     const char *name;
840     int i;
841
842     if (spec_file_name)
843         fprintf( outfile, "; File generated automatically from %s; do not edit!\n\n",
844                  spec_file_name );
845     else
846         fprintf( outfile, "; File generated automatically; do not edit!\n\n" );
847
848     fprintf(outfile, "LIBRARY %s\n\n", spec->file_name);
849
850     fprintf(outfile, "EXPORTS\n");
851
852     /* Output the exports and relay entry points */
853
854     for(i = 0; i < spec->nb_entry_points; i++)
855     {
856         const ORDDEF *odp = &spec->entry_points[i];
857         int is_data = 0;
858
859         if (!odp) continue;
860         if (odp->type == TYPE_STUB) continue;
861
862         if (odp->name) name = odp->name;
863         else if (odp->export_name) name = odp->export_name;
864         else continue;
865
866         fprintf(outfile, "  %s", name);
867
868         switch(odp->type)
869         {
870         case TYPE_EXTERN:
871             is_data = 1;
872             /* fall through */
873         case TYPE_VARARGS:
874         case TYPE_CDECL:
875             /* try to reduce output */
876             if(strcmp(name, odp->link_name) || (odp->flags & FLAG_FORWARD))
877                 fprintf(outfile, "=%s", odp->link_name);
878             break;
879         case TYPE_STDCALL:
880         {
881             int at_param = strlen(odp->u.func.arg_types) * sizeof(int);
882             if (!kill_at) fprintf(outfile, "@%d", at_param);
883             if  (odp->flags & FLAG_FORWARD)
884             {
885                 fprintf(outfile, "=%s", odp->link_name);
886             }
887             else if (strcmp(name, odp->link_name)) /* try to reduce output */
888             {
889                 fprintf(outfile, "=%s", odp->link_name);
890                 if (!kill_at) fprintf(outfile, "@%d", at_param);
891             }
892             break;
893         }
894         default:
895             assert(0);
896         }
897         fprintf( outfile, " @%d", odp->ordinal );
898         if (!odp->name) fprintf( outfile, " NONAME" );
899         if (is_data) fprintf( outfile, " DATA" );
900         if (odp->flags & FLAG_PRIVATE) fprintf( outfile, " PRIVATE" );
901         fprintf( outfile, "\n" );
902     }
903 }
904
905
906 /*******************************************************************
907  *         BuildDebugFile
908  *
909  * Build the debugging channels source file.
910  */
911 void BuildDebugFile( FILE *outfile, const char *srcdir, char **argv )
912 {
913     int nr_debug;
914     char *prefix, *p, *constructor, *destructor;
915
916     while (*argv)
917     {
918         if (!parse_debug_channels( srcdir, *argv++ )) exit(1);
919     }
920
921     output_standard_file_header( outfile );
922     nr_debug = output_debug( outfile );
923     if (!nr_debug)
924     {
925         fprintf( outfile, "/* no debug channels found for this module */\n" );
926         return;
927     }
928
929     if (output_file_name)
930     {
931         if ((p = strrchr( output_file_name, '/' ))) p++;
932         prefix = xstrdup( p ? p : output_file_name );
933         if ((p = strchr( prefix, '.' ))) *p = 0;
934         strcpy( p, make_c_identifier(p) );
935     }
936     else prefix = xstrdup( "_" );
937
938     /* Output the DLL constructor */
939
940     constructor = xmalloc( strlen(prefix) + 17 );
941     destructor = xmalloc( strlen(prefix) + 17 );
942     sprintf( constructor, "__wine_dbg_%s_init", prefix );
943     sprintf( destructor, "__wine_dbg_%s_fini", prefix );
944     fprintf( outfile,
945              "#ifdef __GNUC__\n"
946              "void %s(void) __attribute__((constructor));\n"
947              "void %s(void) __attribute__((destructor));\n"
948              "#else\n"
949              "static void __asm__dummy_dll_init(void) {\n",
950              constructor, destructor );
951     output_dll_init( outfile, constructor, destructor );
952     fprintf( outfile, "}\n#endif /* defined(__GNUC__) */\n\n" );
953
954     fprintf( outfile,
955              "void %s(void)\n"
956              "{\n"
957              "    extern void *__wine_dbg_register( char * const *, int );\n"
958              "    if (!debug_registration) debug_registration = __wine_dbg_register( debug_channels, %d );\n"
959              "}\n\n", constructor, nr_debug );
960     fprintf( outfile,
961              "void %s(void)\n"
962              "{\n"
963              "    extern void __wine_dbg_unregister( void* );\n"
964              "    __wine_dbg_unregister( debug_registration );\n"
965              "}\n", destructor );
966
967     free( constructor );
968     free( destructor );
969     free( prefix );
970 }