dinput: Move SetEventNotification and associated event into base class.
[wine] / tools / winebuild / main.c
1 /*
2  * Main function
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <stdio.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <stdarg.h>
34 #include <ctype.h>
35 #ifdef HAVE_GETOPT_H
36 # include <getopt.h>
37 #endif
38
39 #include "windef.h"
40 #include "winbase.h"
41 #include "build.h"
42
43 int UsePIC = 0;
44 int nb_lib_paths = 0;
45 int nb_errors = 0;
46 int display_warnings = 0;
47 int kill_at = 0;
48 int verbose = 0;
49 int save_temps = 0;
50 int link_ext_symbols = 0;
51
52 #ifdef __i386__
53 enum target_cpu target_cpu = CPU_x86;
54 #elif defined(__x86_64__)
55 enum target_cpu target_cpu = CPU_x86_64;
56 #elif defined(__sparc__)
57 enum target_cpu target_cpu = CPU_SPARC;
58 #elif defined(__ALPHA__)
59 enum target_cpu target_cpu = CPU_ALPHA;
60 #elif defined(__powerpc__)
61 enum target_cpu target_cpu = CPU_POWERPC;
62 #else
63 #error Unsupported CPU
64 #endif
65
66 #ifdef __APPLE__
67 enum target_platform target_platform = PLATFORM_APPLE;
68 #elif defined(_WINDOWS)
69 enum target_platform target_platform = PLATFORM_WINDOWS;
70 #else
71 enum target_platform target_platform = PLATFORM_UNSPECIFIED;
72 #endif
73
74 char **lib_path = NULL;
75
76 char *input_file_name = NULL;
77 char *spec_file_name = NULL;
78 FILE *output_file = NULL;
79 const char *output_file_name = NULL;
80 static const char *output_file_source_name;
81
82 char *as_command = NULL;
83 char *ld_command = NULL;
84 char *nm_command = NULL;
85
86 static int nb_res_files;
87 static char **res_files;
88
89 /* execution mode */
90 enum exec_mode_values
91 {
92     MODE_NONE,
93     MODE_DLL,
94     MODE_EXE,
95     MODE_DEF,
96     MODE_RELAY16,
97     MODE_RELAY32
98 };
99
100 static enum exec_mode_values exec_mode = MODE_NONE;
101
102 static const struct
103 {
104     const char *name;
105     enum target_cpu cpu;
106 } cpu_names[] =
107 {
108     { "i386",    CPU_x86 },
109     { "i486",    CPU_x86 },
110     { "i586",    CPU_x86 },
111     { "i686",    CPU_x86 },
112     { "i786",    CPU_x86 },
113     { "x86_64",  CPU_x86_64 },
114     { "sparc",   CPU_SPARC },
115     { "alpha",   CPU_ALPHA },
116     { "powerpc", CPU_POWERPC }
117 };
118
119 static const struct
120 {
121     const char *name;
122     enum target_platform platform;
123 } platform_names[] =
124 {
125     { "macos",   PLATFORM_APPLE },
126     { "darwin",  PLATFORM_APPLE },
127     { "windows", PLATFORM_WINDOWS },
128     { "winnt",   PLATFORM_WINDOWS }
129 };
130
131 /* set the dll file name from the input file name */
132 static void set_dll_file_name( const char *name, DLLSPEC *spec )
133 {
134     char *p;
135
136     if (spec->file_name) return;
137
138     if ((p = strrchr( name, '\\' ))) name = p + 1;
139     if ((p = strrchr( name, '/' ))) name = p + 1;
140     spec->file_name = xmalloc( strlen(name) + 5 );
141     strcpy( spec->file_name, name );
142     if ((p = strrchr( spec->file_name, '.' )))
143     {
144         if (!strcmp( p, ".spec" ) || !strcmp( p, ".def" )) *p = 0;
145     }
146 }
147
148 /* set the dll subsystem */
149 static void set_subsystem( const char *subsystem, DLLSPEC *spec )
150 {
151     char *major, *minor, *str = xstrdup( subsystem );
152
153     if ((major = strchr( str, ':' ))) *major++ = 0;
154     if (!strcmp( str, "native" )) spec->subsystem = IMAGE_SUBSYSTEM_NATIVE;
155     else if (!strcmp( str, "windows" )) spec->subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
156     else if (!strcmp( str, "console" )) spec->subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
157     else fatal_error( "Invalid subsystem name '%s'\n", subsystem );
158     if (major)
159     {
160         if ((minor = strchr( major, '.' )))
161         {
162             *minor++ = 0;
163             spec->subsystem_minor = atoi( minor );
164         }
165         spec->subsystem_major = atoi( major );
166     }
167     free( str );
168 }
169
170 /* set the target CPU and platform */
171 static void set_target( const char *target )
172 {
173     unsigned int i;
174     char *p, *platform, *spec = xstrdup( target );
175
176     /* target specification is in the form CPU-MANUFACTURER-OS or CPU-MANUFACTURER-KERNEL-OS */
177
178     /* get the CPU part */
179
180     if (!(p = strchr( spec, '-' ))) fatal_error( "Invalid target specification '%s'\n", target );
181     *p++ = 0;
182     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
183     {
184         if (!strcmp( cpu_names[i].name, spec )) break;
185     }
186     if (i < sizeof(cpu_names)/sizeof(cpu_names[0])) target_cpu = cpu_names[i].cpu;
187     else fatal_error( "Unrecognized CPU '%s'\n", spec );
188
189     platform = p;
190     if ((p = strrchr( p, '-' ))) platform = p + 1;
191
192     /* get the OS part */
193
194     target_platform = PLATFORM_UNSPECIFIED;  /* default value */
195     for (i = 0; i < sizeof(platform_names)/sizeof(platform_names[0]); i++)
196     {
197         if (!strncmp( platform_names[i].name, platform, strlen(platform_names[i].name) ))
198         {
199             target_platform = platform_names[i].platform;
200             break;
201         }
202     }
203
204     free( spec );
205
206     if (!as_command)
207     {
208         as_command = xmalloc( strlen(target) + sizeof("-as") );
209         strcpy( as_command, target );
210         strcat( as_command, "-as" );
211     }
212     if (!ld_command)
213     {
214         ld_command = xmalloc( strlen(target) + sizeof("-ld") );
215         strcpy( ld_command, target );
216         strcat( ld_command, "-ld" );
217     }
218     if (!nm_command)
219     {
220         nm_command = xmalloc( strlen(target) + sizeof("-nm") );
221         strcpy( nm_command, target );
222         strcat( nm_command, "-nm" );
223     }
224 }
225
226 /* cleanup on program exit */
227 static void cleanup(void)
228 {
229     if (output_file_name) unlink( output_file_name );
230 }
231
232 /* clean things up when aborting on a signal */
233 static void exit_on_signal( int sig )
234 {
235     exit(1);  /* this will call atexit functions */
236 }
237
238 /*******************************************************************
239  *         command-line option handling
240  */
241 static const char usage_str[] =
242 "Usage: winebuild [OPTIONS] [FILES]\n\n"
243 "Options:\n"
244 "       --as-cmd=AS          Command to use for assembling (default: as)\n"
245 "   -d, --delay-lib=LIB      Import the specified library in delayed mode\n"
246 "   -D SYM                   Ignored for C flags compatibility\n"
247 "   -e, --entry=FUNC         Set the DLL entry point function (default: DllMain)\n"
248 "   -E, --export=FILE        Export the symbols defined in the .spec or .def file\n"
249 "       --external-symbols   Allow linking to external symbols\n"
250 "   -f FLAGS                 Compiler flags (only -fPIC is supported)\n"
251 "   -F, --filename=DLLFILE   Set the DLL filename (default: from input file name)\n"
252 "   -h, --help               Display this help message\n"
253 "   -H, --heap=SIZE          Set the heap size for a Win16 dll\n"
254 "   -i, --ignore=SYM[,SYM]   Ignore specified symbols when resolving imports\n"
255 "   -I DIR                   Ignored for C flags compatibility\n"
256 "   -k, --kill-at            Kill stdcall decorations in generated .def files\n"
257 "   -K, FLAGS                Compiler flags (only -KPIC is supported)\n"
258 "       --ld-cmd=LD          Command to use for linking (default: ld)\n"
259 "   -l, --library=LIB        Import the specified library\n"
260 "   -L, --library-path=DIR   Look for imports libraries in DIR\n"
261 "   -M, --main-module=MODULE Set the name of the main module for a Win16 dll\n"
262 "       --nm-cmd=NM          Command to use to get undefined symbols (default: nm)\n"
263 "   -N, --dll-name=DLLNAME   Set the DLL name (default: from input file name)\n"
264 "   -o, --output=NAME        Set the output file name (default: stdout)\n"
265 "   -r, --res=RSRC.RES       Load resources from RSRC.RES\n"
266 "       --save-temps         Do not delete the generated intermediate files\n"
267 "       --subsystem=SUBSYS   Set the subsystem (one of native, windows, console)\n"
268 "       --target=TARGET      Specify target CPU and platform for cross-compiling\n"
269 "   -u, --undefined=SYMBOL   Add an undefined reference to SYMBOL when linking\n"
270 "   -v, --verbose            Display the programs invoked\n"
271 "       --version            Print the version and exit\n"
272 "   -w, --warnings           Turn on warnings\n"
273 "\nMode options:\n"
274 "       --dll                Build a .c file from a .spec or .def file\n"
275 "       --def                Build a .def file from a .spec file\n"
276 "       --exe                Build a .c file for an executable\n"
277 "       --relay16            Build the 16-bit relay assembly routines\n"
278 "       --relay32            Build the 32-bit relay assembly routines\n\n"
279 "The mode options are mutually exclusive; you must specify one and only one.\n\n";
280
281 enum long_options_values
282 {
283     LONG_OPT_DLL = 1,
284     LONG_OPT_DEF,
285     LONG_OPT_EXE,
286     LONG_OPT_ASCMD,
287     LONG_OPT_EXTERNAL_SYMS,
288     LONG_OPT_LDCMD,
289     LONG_OPT_NMCMD,
290     LONG_OPT_RELAY16,
291     LONG_OPT_RELAY32,
292     LONG_OPT_SAVE_TEMPS,
293     LONG_OPT_SUBSYSTEM,
294     LONG_OPT_TARGET,
295     LONG_OPT_VERSION
296 };
297
298 static const char short_options[] = "C:D:E:F:H:I:K:L:M:N:d:e:f:hi:kl:m:o:r:u:vw";
299
300 static const struct option long_options[] =
301 {
302     { "dll",           0, 0, LONG_OPT_DLL },
303     { "def",           0, 0, LONG_OPT_DEF },
304     { "exe",           0, 0, LONG_OPT_EXE },
305     { "as-cmd",        1, 0, LONG_OPT_ASCMD },
306     { "external-symbols", 0, 0, LONG_OPT_EXTERNAL_SYMS },
307     { "ld-cmd",        1, 0, LONG_OPT_LDCMD },
308     { "nm-cmd",        1, 0, LONG_OPT_NMCMD },
309     { "relay16",       0, 0, LONG_OPT_RELAY16 },
310     { "relay32",       0, 0, LONG_OPT_RELAY32 },
311     { "save-temps",    0, 0, LONG_OPT_SAVE_TEMPS },
312     { "subsystem",     1, 0, LONG_OPT_SUBSYSTEM },
313     { "target",        1, 0, LONG_OPT_TARGET },
314     { "version",       0, 0, LONG_OPT_VERSION },
315     /* aliases for short options */
316     { "delay-lib",     1, 0, 'd' },
317     { "export",        1, 0, 'E' },
318     { "entry",         1, 0, 'e' },
319     { "filename",      1, 0, 'F' },
320     { "help",          0, 0, 'h' },
321     { "heap",          1, 0, 'H' },
322     { "ignore",        1, 0, 'i' },
323     { "kill-at",       0, 0, 'k' },
324     { "library",       1, 0, 'l' },
325     { "library-path",  1, 0, 'L' },
326     { "main-module",   1, 0, 'M' },
327     { "dll-name",      1, 0, 'N' },
328     { "output",        1, 0, 'o' },
329     { "res",           1, 0, 'r' },
330     { "undefined",     1, 0, 'u' },
331     { "verbose",       0, 0, 'v' },
332     { "warnings",      0, 0, 'w' },
333     { NULL,            0, 0, 0 }
334 };
335
336 static void usage( int exit_code )
337 {
338     fprintf( stderr, "%s", usage_str );
339     exit( exit_code );
340 }
341
342 static void set_exec_mode( enum exec_mode_values mode )
343 {
344     if (exec_mode != MODE_NONE) usage(1);
345     exec_mode = mode;
346 }
347
348 /* parse options from the argv array and remove all the recognized ones */
349 static char **parse_options( int argc, char **argv, DLLSPEC *spec )
350 {
351     char *p;
352     int optc;
353
354     while ((optc = getopt_long( argc, argv, short_options, long_options, NULL )) != -1)
355     {
356         switch(optc)
357         {
358         case 'D':
359             /* ignored */
360             break;
361         case 'E':
362             spec_file_name = xstrdup( optarg );
363             set_dll_file_name( optarg, spec );
364             break;
365         case 'F':
366             spec->file_name = xstrdup( optarg );
367             break;
368         case 'H':
369             if (!isdigit(optarg[0]))
370                 fatal_error( "Expected number argument with -H option instead of '%s'\n", optarg );
371             spec->heap_size = atoi(optarg);
372             if (spec->heap_size > 65535)
373                 fatal_error( "Invalid heap size %d, maximum is 65535\n", spec->heap_size );
374             break;
375         case 'I':
376             /* ignored */
377             break;
378         case 'K':
379             /* ignored, because cc generates correct code. */
380             break;
381         case 'L':
382             lib_path = xrealloc( lib_path, (nb_lib_paths+1) * sizeof(*lib_path) );
383             lib_path[nb_lib_paths++] = xstrdup( optarg );
384             break;
385         case 'M':
386             spec->type = SPEC_WIN16;
387             break;
388         case 'N':
389             spec->dll_name = xstrdup( optarg );
390             break;
391         case 'd':
392             add_delayed_import( optarg );
393             break;
394         case 'e':
395             spec->init_func = xstrdup( optarg );
396             if ((p = strchr( spec->init_func, '@' ))) *p = 0;  /* kill stdcall decoration */
397             break;
398         case 'f':
399             if (!strcmp( optarg, "PIC") || !strcmp( optarg, "pic")) UsePIC = 1;
400             /* ignore all other flags */
401             break;
402         case 'h':
403             usage(0);
404             break;
405         case 'i':
406             {
407                 char *str = xstrdup( optarg );
408                 char *token = strtok( str, "," );
409                 while (token)
410                 {
411                     add_ignore_symbol( token );
412                     token = strtok( NULL, "," );
413                 }
414                 free( str );
415             }
416             break;
417         case 'k':
418             kill_at = 1;
419             break;
420         case 'l':
421             add_import_dll( optarg, NULL );
422             break;
423         case 'o':
424             {
425                 char *ext = strrchr( optarg, '.' );
426
427                 if (unlink( optarg ) == -1 && errno != ENOENT)
428                     fatal_error( "Unable to create output file '%s'\n", optarg );
429                 if (ext && !strcmp( ext, ".o" ))
430                 {
431                     output_file_source_name = get_temp_file_name( optarg, ".s" );
432                     if (!(output_file = fopen( output_file_source_name, "w" )))
433                         fatal_error( "Unable to create output file '%s'\n", optarg );
434                 }
435                 else
436                 {
437                     if (!(output_file = fopen( optarg, "w" )))
438                         fatal_error( "Unable to create output file '%s'\n", optarg );
439                 }
440                 output_file_name = xstrdup(optarg);
441                 atexit( cleanup );  /* make sure we remove the output file on exit */
442             }
443             break;
444         case 'r':
445             res_files = xrealloc( res_files, (nb_res_files+1) * sizeof(*res_files) );
446             res_files[nb_res_files++] = xstrdup( optarg );
447             break;
448         case 'u':
449             add_extra_ld_symbol( optarg );
450             break;
451         case 'v':
452             verbose++;
453             break;
454         case 'w':
455             display_warnings = 1;
456             break;
457         case LONG_OPT_DLL:
458             set_exec_mode( MODE_DLL );
459             break;
460         case LONG_OPT_DEF:
461             set_exec_mode( MODE_DEF );
462             break;
463         case LONG_OPT_EXE:
464             set_exec_mode( MODE_EXE );
465             if (!spec->subsystem) spec->subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
466             break;
467         case LONG_OPT_ASCMD:
468             as_command = xstrdup( optarg );
469             break;
470         case LONG_OPT_EXTERNAL_SYMS:
471             link_ext_symbols = 1;
472             break;
473         case LONG_OPT_LDCMD:
474             ld_command = xstrdup( optarg );
475             break;
476         case LONG_OPT_NMCMD:
477             nm_command = xstrdup( optarg );
478             break;
479         case LONG_OPT_RELAY16:
480             set_exec_mode( MODE_RELAY16 );
481             break;
482         case LONG_OPT_RELAY32:
483             set_exec_mode( MODE_RELAY32 );
484             break;
485         case LONG_OPT_SAVE_TEMPS:
486             save_temps = 1;
487             break;
488         case LONG_OPT_SUBSYSTEM:
489             set_subsystem( optarg, spec );
490             break;
491         case LONG_OPT_TARGET:
492             set_target( optarg );
493             break;
494         case LONG_OPT_VERSION:
495             printf( "winebuild version " PACKAGE_VERSION "\n" );
496             exit(0);
497         case '?':
498             usage(1);
499             break;
500         }
501     }
502
503     if (spec->file_name && !strchr( spec->file_name, '.' ))
504         strcat( spec->file_name, exec_mode == MODE_EXE ? ".exe" : ".dll" );
505
506     return &argv[optind];
507 }
508
509
510 /* load all specified resource files */
511 static void load_resources( char *argv[], DLLSPEC *spec )
512 {
513     int i;
514     char **ptr, **last;
515
516     switch (spec->type)
517     {
518     case SPEC_WIN16:
519         for (i = 0; i < nb_res_files; i++) load_res16_file( res_files[i], spec );
520         break;
521
522     case SPEC_WIN32:
523         for (i = 0; i < nb_res_files; i++)
524         {
525             if (!load_res32_file( res_files[i], spec ))
526                 fatal_error( "%s is not a valid Win32 resource file\n", res_files[i] );
527         }
528
529         /* load any resource file found in the remaining arguments */
530         for (ptr = last = argv; *ptr; ptr++)
531         {
532             if (!load_res32_file( *ptr, spec ))
533                 *last++ = *ptr; /* not a resource file, keep it in the list */
534         }
535         *last = NULL;
536         break;
537     }
538 }
539
540 /* add input files that look like import libs to the import list */
541 static void load_import_libs( char *argv[] )
542 {
543     char **ptr, **last;
544
545     for (ptr = last = argv; *ptr; ptr++)
546     {
547         if (strendswith( *ptr, ".def" ))
548             add_import_dll( NULL, *ptr );
549         else
550             *last++ = *ptr; /* not an import dll, keep it in the list */
551     }
552     *last = NULL;
553 }
554
555 static int parse_input_file( DLLSPEC *spec )
556 {
557     FILE *input_file = open_input_file( NULL, spec_file_name );
558     char *extension = strrchr( spec_file_name, '.' );
559     int result;
560
561     spec->src_name = xstrdup( input_file_name );
562     if (extension && !strcmp( extension, ".def" ))
563         result = parse_def_file( input_file, spec );
564     else
565         result = parse_spec_file( input_file, spec );
566     close_input_file( input_file );
567     return result;
568 }
569
570
571 /*******************************************************************
572  *         main
573  */
574 int main(int argc, char **argv)
575 {
576     DLLSPEC *spec = alloc_dll_spec();
577
578 #ifdef SIGHUP
579     signal( SIGHUP, exit_on_signal );
580 #endif
581     signal( SIGTERM, exit_on_signal );
582     signal( SIGINT, exit_on_signal );
583
584     output_file = stdout;
585     argv = parse_options( argc, argv, spec );
586
587     switch(exec_mode)
588     {
589     case MODE_DLL:
590         spec->characteristics |= IMAGE_FILE_DLL;
591         load_resources( argv, spec );
592         load_import_libs( argv );
593         if (!spec_file_name) fatal_error( "missing .spec file\n" );
594         if (!parse_input_file( spec )) break;
595         switch (spec->type)
596         {
597             case SPEC_WIN16:
598                 if (argv[0])
599                     fatal_error( "file argument '%s' not allowed in this mode\n", argv[0] );
600                 BuildSpec16File( spec );
601                 break;
602             case SPEC_WIN32:
603                 read_undef_symbols( spec, argv );
604                 BuildSpec32File( spec );
605                 break;
606             default: assert(0);
607         }
608         break;
609     case MODE_EXE:
610         if (spec->type == SPEC_WIN16) fatal_error( "Cannot build 16-bit exe files\n" );
611         if (!spec->file_name) fatal_error( "executable must be named via the -F option\n" );
612         load_resources( argv, spec );
613         load_import_libs( argv );
614         if (spec_file_name && !parse_input_file( spec )) break;
615         read_undef_symbols( spec, argv );
616         BuildSpec32File( spec );
617         break;
618     case MODE_DEF:
619         if (argv[0]) fatal_error( "file argument '%s' not allowed in this mode\n", argv[0] );
620         if (spec->type == SPEC_WIN16) fatal_error( "Cannot yet build .def file for 16-bit dlls\n" );
621         if (!spec_file_name) fatal_error( "missing .spec file\n" );
622         if (!parse_input_file( spec )) break;
623         BuildDef32File( spec );
624         break;
625     case MODE_RELAY16:
626         if (argv[0]) fatal_error( "file argument '%s' not allowed in this mode\n", argv[0] );
627         BuildRelays16();
628         break;
629     case MODE_RELAY32:
630         if (argv[0]) fatal_error( "file argument '%s' not allowed in this mode\n", argv[0] );
631         BuildRelays32();
632         break;
633     default:
634         usage(1);
635         break;
636     }
637     if (nb_errors) exit(1);
638     if (output_file_name)
639     {
640         if (fclose( output_file ) < 0) fatal_perror( "fclose" );
641         if (output_file_source_name) assemble_file( output_file_source_name, output_file_name );
642         output_file_name = NULL;
643     }
644     return 0;
645 }