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