wnaspi32: Make winaspi.dll into a stand-alone 16-bit module.
[wine] / tools / winegcc / winegcc.c
1 /*
2  * MinGW wrapper: makes gcc behave like MinGW.
3  *
4  * Copyright 2000 Manuel Novoa III
5  * Copyright 2000 Francois Gouget
6  * Copyright 2002 Dimitrie O. Paun
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  *
22  * DESCRIPTION
23  *
24  * all options for gcc start with '-' and are for the most part
25  * single options (no parameters as separate argument). 
26  * There are of course exceptions to this rule, so here is an 
27  * exhaustive list of options that do take parameters (potentially)
28  * as a separate argument:
29  *
30  * Compiler:
31  * -x language
32  * -o filename
33  * -aux-info filename
34  *
35  * Preprocessor:
36  * -D name 
37  * -U name
38  * -I dir
39  * -MF file
40  * -MT target
41  * -MQ target
42  * (all -i.* arg)
43  * -include file 
44  * -imacros file
45  * -idirafter dir
46  * -iwithprefix dir
47  * -iwithprefixbefore dir
48  * -isystem dir
49  * -A predicate=answer
50  *
51  * Linking:
52  * -l library
53  * -Xlinker option
54  * -u symbol
55  *
56  * Misc:
57  * -b machine
58  * -V version
59  * -G num  (see NOTES below)
60  *
61  * NOTES
62  * There is -G option for compatibility with System V that
63  * takes no parameters. This makes "-G num" parsing ambiguous.
64  * This option is synonymous to -shared, and as such we will
65  * not support it for now.
66  *
67  * Special interest options 
68  *
69  *      Assembler Option
70  *          -Wa,option
71  *
72  *      Linker Options
73  *          object-file-name  -llibrary -nostartfiles  -nodefaultlibs
74  *          -nostdlib -s  -static  -static-libgcc  -shared  -shared-libgcc
75  *          -symbolic -Wl,option  -Xlinker option -u symbol --image-base
76  *
77  *      Directory Options
78  *          -Bprefix  -Idir  -I-  -Ldir  -specs=file
79  *
80  *      Target Options
81  *          -b machine  -V version
82  *
83  * Please note that the Target Options are relevant to everything:
84  *   compiler, linker, assembler, preprocessor.
85  * 
86  */ 
87
88 #include "config.h"
89 #include "wine/port.h"
90
91 #include <assert.h>
92 #include <stdio.h>
93 #include <stdlib.h>
94 #include <signal.h>
95 #include <stdarg.h>
96 #include <string.h>
97 #include <errno.h>
98
99 #include "utils.h"
100
101 static const char* app_loader_template =
102     "#!/bin/sh\n"
103     "\n"
104     "appname=\"%s\"\n"
105     "# determine the application directory\n"
106     "appdir=''\n"
107     "case \"$0\" in\n"
108     "  */*)\n"
109     "    # $0 contains a path, use it\n"
110     "    appdir=`dirname \"$0\"`\n"
111     "    ;;\n"
112     "  *)\n"
113     "    # no directory in $0, search in PATH\n"
114     "    saved_ifs=$IFS\n"
115     "    IFS=:\n"
116     "    for d in $PATH\n"
117     "    do\n"
118     "      IFS=$saved_ifs\n"
119     "      if [ -x \"$d/$appname\" ]; then appdir=\"$d\"; break; fi\n"
120     "    done\n"
121     "    ;;\n"
122     "esac\n"
123     "\n"
124     "# figure out the full app path\n"
125     "if [ -n \"$appdir\" ]; then\n"
126     "    apppath=\"$appdir/$appname\"\n"
127     "    WINEDLLPATH=\"$appdir:$WINEDLLPATH\"\n"
128     "    export WINEDLLPATH\n"
129     "else\n"
130     "    apppath=\"$appname\"\n"
131     "fi\n"
132     "\n"
133     "# determine the WINELOADER\n"
134     "if [ ! -x \"$WINELOADER\" ]; then WINELOADER=\"wine\"; fi\n"
135     "\n"
136     "# and try to start the app\n"
137     "exec \"$WINELOADER\" \"$apppath\" \"$@\"\n"
138 ;
139
140 static int keep_generated = 0;
141 static strarray* tmp_files;
142 #ifdef HAVE_SIGSET_T
143 static sigset_t signal_mask;
144 #endif
145
146 enum processor { proc_cc, proc_cxx, proc_cpp, proc_as };
147
148 enum target_cpu
149 {
150     CPU_x86, CPU_x86_64, CPU_SPARC, CPU_ALPHA, CPU_POWERPC
151 };
152
153 enum target_platform
154 {
155     PLATFORM_UNSPECIFIED, PLATFORM_APPLE, PLATFORM_SOLARIS, PLATFORM_WINDOWS
156 };
157
158 static const struct
159 {
160     const char *name;
161     enum target_cpu cpu;
162 } cpu_names[] =
163 {
164     { "i386",    CPU_x86 },
165     { "i486",    CPU_x86 },
166     { "i586",    CPU_x86 },
167     { "i686",    CPU_x86 },
168     { "i786",    CPU_x86 },
169     { "x86_64",  CPU_x86_64 },
170     { "sparc",   CPU_SPARC },
171     { "alpha",   CPU_ALPHA },
172     { "powerpc", CPU_POWERPC }
173 };
174
175 static const struct
176 {
177     const char *name;
178     enum target_platform platform;
179 } platform_names[] =
180 {
181     { "macos",   PLATFORM_APPLE },
182     { "darwin",  PLATFORM_APPLE },
183     { "solaris", PLATFORM_SOLARIS },
184     { "mingw32", PLATFORM_WINDOWS },
185     { "windows", PLATFORM_WINDOWS },
186     { "winnt",   PLATFORM_WINDOWS }
187 };
188
189 struct options
190 {
191     enum processor processor;
192     enum target_cpu target_cpu;
193     enum target_platform target_platform;
194     const char *target;
195     int shared;
196     int use_msvcrt;
197     int nostdinc;
198     int nostdlib;
199     int nostartfiles;
200     int nodefaultlibs;
201     int noshortwchar;
202     int gui_app;
203     int unicode_app;
204     int compile_only;
205     int force_pointer_size;
206     const char* wine_objdir;
207     const char* output_name;
208     const char* image_base;
209     const char* section_align;
210     strarray* prefix;
211     strarray* lib_dirs;
212     strarray* linker_args;
213     strarray* compiler_args;
214     strarray* winebuild_args;
215     strarray* files;
216 };
217
218 #ifdef __i386__
219 static const enum target_cpu build_cpu = CPU_x86;
220 #elif defined(__x86_64__)
221 static const enum target_cpu build_cpu = CPU_x86_64;
222 #elif defined(__sparc__)
223 static const enum target_cpu build_cpu = CPU_SPARC;
224 #elif defined(__ALPHA__)
225 static const enum target_cpu build_cpu = CPU_ALPHA;
226 #elif defined(__powerpc__)
227 static const enum target_cpu build_cpu = CPU_POWERPC;
228 #else
229 #error Unsupported CPU
230 #endif
231
232 #ifdef __APPLE__
233 static enum target_platform build_platform = PLATFORM_APPLE;
234 #elif defined(__sun)
235 static enum target_platform build_platform = PLATFORM_SOLARIS;
236 #elif defined(_WINDOWS)
237 static enum target_platform build_platform = PLATFORM_WINDOWS;
238 #else
239 static enum target_platform build_platform = PLATFORM_UNSPECIFIED;
240 #endif
241
242 static void clean_temp_files(void)
243 {
244     unsigned int i;
245
246     if (keep_generated) return;
247
248     for (i = 0; i < tmp_files->size; i++)
249         unlink(tmp_files->base[i]);
250 }
251
252 /* clean things up when aborting on a signal */
253 static void exit_on_signal( int sig )
254 {
255     exit(1);  /* this will call the atexit functions */
256 }
257
258 static char* get_temp_file(const char* prefix, const char* suffix)
259 {
260     int fd;
261     char* tmp = strmake("%s-XXXXXX%s", prefix, suffix);
262
263 #ifdef HAVE_SIGPROCMASK
264     sigset_t old_set;
265     /* block signals while manipulating the temp files list */
266     sigprocmask( SIG_BLOCK, &signal_mask, &old_set );
267 #endif
268     fd = mkstemps( tmp, strlen(suffix) );
269     if (fd == -1)
270     {
271         /* could not create it in current directory, try in /tmp */
272         free(tmp);
273         tmp = strmake("/tmp/%s-XXXXXX%s", prefix, suffix);
274         fd = mkstemps( tmp, strlen(suffix) );
275         if (fd == -1) error( "could not create temp file\n" );
276     }
277     close( fd );
278     strarray_add(tmp_files, tmp);
279 #ifdef HAVE_SIGPROCMASK
280     sigprocmask( SIG_SETMASK, &old_set, NULL );
281 #endif
282     return tmp;
283 }
284
285 static const strarray* get_translator(struct options *opts)
286 {
287     const char *str;
288     strarray *ret;
289
290     switch(opts->processor)
291     {
292     case proc_cpp:
293         if (opts->target) str = strmake( "%s-cpp", opts->target );
294         else str = CPP;
295         break;
296     case proc_cc:
297         if (opts->target) str = strmake( "%s-gcc", opts->target );
298         else str = CC;
299         break;
300     case proc_cxx:
301         if (opts->target) str = strmake( "%s-g++", opts->target );
302         else str = CXX;
303         break;
304     case proc_as:
305         if (opts->target) str = strmake( "%s-as", opts->target );
306         else str = AS;
307         break;
308     default:
309         assert(0);
310     }
311     ret = strarray_fromstring( str, " " );
312     if (opts->force_pointer_size)
313     {
314         if (opts->processor == proc_as)
315             strarray_add( ret, strmake("--%u", 8 * opts->force_pointer_size ));
316         else
317             strarray_add( ret, strmake("-m%u", 8 * opts->force_pointer_size ));
318     }
319     return ret;
320 }
321
322 static void compile(struct options* opts, const char* lang)
323 {
324     strarray* comp_args = strarray_alloc();
325     unsigned int j;
326     int gcc_defs = 0;
327
328     strarray_addall(comp_args, get_translator(opts));
329     switch(opts->processor)
330     {
331         case proc_cpp: gcc_defs = 1; break;
332         case proc_as:  gcc_defs = 0; break;
333         /* Note: if the C compiler is gcc we assume the C++ compiler is too */
334         /* mixing different C and C++ compilers isn't supported in configure anyway */
335         case proc_cc:
336         case proc_cxx:
337             gcc_defs = strendswith(comp_args->base[0], "gcc") || strendswith(comp_args->base[0], "g++");
338             break;
339     }
340
341     if (opts->target_platform == PLATFORM_WINDOWS) goto no_compat_defines;
342
343     if (opts->processor != proc_cpp)
344     {
345         if (gcc_defs && !opts->wine_objdir && !opts->noshortwchar)
346         {
347             strarray_add(comp_args, "-fshort-wchar");
348             strarray_add(comp_args, "-DWINE_UNICODE_NATIVE");
349         }
350         strarray_addall(comp_args, strarray_fromstring(DLLFLAGS, " "));
351     }
352
353     if (opts->target_cpu == CPU_x86_64)
354     {
355         strarray_add(comp_args, "-DWIN64");
356         strarray_add(comp_args, "-D_WIN64");
357         strarray_add(comp_args, "-D__WIN64");
358         strarray_add(comp_args, "-D__WIN64__");
359     }
360
361     strarray_add(comp_args, "-DWIN32");
362     strarray_add(comp_args, "-D_WIN32");
363     strarray_add(comp_args, "-D__WIN32");
364     strarray_add(comp_args, "-D__WIN32__");
365     strarray_add(comp_args, "-D__WINNT");
366     strarray_add(comp_args, "-D__WINNT__");
367
368     if (gcc_defs)
369     {
370         if (opts->target_cpu == CPU_x86_64)
371         {
372             strarray_add(comp_args, "-D__stdcall=__attribute__((ms_abi))");
373             strarray_add(comp_args, "-D__cdecl=__attribute__((ms_abi))");
374             strarray_add(comp_args, "-D_stdcall=__attribute__((ms_abi))");
375             strarray_add(comp_args, "-D_cdecl=__attribute__((ms_abi))");
376             strarray_add(comp_args, "-D__fastcall=__attribute__((ms_abi))");
377             strarray_add(comp_args, "-D_fastcall=__attribute__((ms_abi))");
378         }
379         else if (opts->target_platform == PLATFORM_APPLE)
380         {
381             /* Mac OS X uses a 16-byte aligned stack and not a 4-byte one */
382             strarray_add(comp_args, "-D__stdcall=__attribute__((__stdcall__)) __attribute__((__force_align_arg_pointer__))");
383             strarray_add(comp_args, "-D__cdecl=__attribute__((__cdecl__)) __attribute__((__force_align_arg_pointer__))");
384             strarray_add(comp_args, "-D_stdcall=__attribute__((__stdcall__)) __attribute__((__force_align_arg_pointer__))");
385             strarray_add(comp_args, "-D_cdecl=__attribute__((__cdecl__)) __attribute__((__force_align_arg_pointer__))");
386         }
387         else
388         {
389             strarray_add(comp_args, "-D__stdcall=__attribute__((__stdcall__))");
390             strarray_add(comp_args, "-D__cdecl=__attribute__((__cdecl__))");
391             strarray_add(comp_args, "-D_stdcall=__attribute__((__stdcall__))");
392             strarray_add(comp_args, "-D_cdecl=__attribute__((__cdecl__))");
393         }
394
395         strarray_add(comp_args, "-D__fastcall=__attribute__((__fastcall__))");
396         strarray_add(comp_args, "-D_fastcall=__attribute__((__fastcall__))");
397         strarray_add(comp_args, "-D__declspec(x)=__declspec_##x");
398         strarray_add(comp_args, "-D__declspec_align(x)=__attribute__((aligned(x)))");
399         strarray_add(comp_args, "-D__declspec_allocate(x)=__attribute__((section(x)))");
400         strarray_add(comp_args, "-D__declspec_deprecated=__attribute__((deprecated))");
401         strarray_add(comp_args, "-D__declspec_dllimport=__attribute__((dllimport))");
402         strarray_add(comp_args, "-D__declspec_dllexport=__attribute__((dllexport))");
403         strarray_add(comp_args, "-D__declspec_naked=__attribute__((naked))");
404         strarray_add(comp_args, "-D__declspec_noinline=__attribute__((noinline))");
405         strarray_add(comp_args, "-D__declspec_noreturn=__attribute__((noreturn))");
406         strarray_add(comp_args, "-D__declspec_nothrow=__attribute__((nothrow))");
407         strarray_add(comp_args, "-D__declspec_novtable=__attribute__(())"); /* ignore it */
408         strarray_add(comp_args, "-D__declspec_selectany=__attribute__((weak))");
409         strarray_add(comp_args, "-D__declspec_thread=__thread");
410     }
411
412     strarray_add(comp_args, "-D__int8=char");
413     strarray_add(comp_args, "-D__int16=short");
414     strarray_add(comp_args, "-D__int32=int");
415     if (opts->target_cpu == CPU_x86_64)
416         strarray_add(comp_args, "-D__int64=long");
417     else
418         strarray_add(comp_args, "-D__int64=long long");
419
420 no_compat_defines:
421     strarray_add(comp_args, "-D__WINE__");
422
423     /* options we handle explicitly */
424     if (opts->compile_only)
425         strarray_add(comp_args, "-c");
426     if (opts->output_name)
427     {
428         strarray_add(comp_args, "-o");
429         strarray_add(comp_args, opts->output_name);
430     }
431
432     /* the rest of the pass-through parameters */
433     for ( j = 0 ; j < opts->compiler_args->size ; j++ ) 
434         strarray_add(comp_args, opts->compiler_args->base[j]);
435
436     /* the language option, if any */
437     if (lang && strcmp(lang, "-xnone"))
438         strarray_add(comp_args, lang);
439
440     /* last, but not least, the files */
441     for ( j = 0; j < opts->files->size; j++ )
442     {
443         if (opts->files->base[j][0] != '-')
444             strarray_add(comp_args, opts->files->base[j]);
445     }
446
447     /* standard includes come last in the include search path */
448     if (!opts->wine_objdir && !opts->nostdinc)
449     {
450         if (opts->use_msvcrt)
451         {
452             if (gcc_defs) strarray_add(comp_args, "-isystem" INCLUDEDIR "/msvcrt");
453             else strarray_add(comp_args, "-I" INCLUDEDIR "/msvcrt");
454             strarray_add(comp_args, "-D__MSVCRT__");
455         }
456         strarray_add(comp_args, gcc_defs ? "-isystem" INCLUDEDIR "/windows" : "-I" INCLUDEDIR "/windows" );
457     }
458     else if (opts->wine_objdir)
459         strarray_add(comp_args, strmake("-I%s/include", opts->wine_objdir) );
460
461     spawn(opts->prefix, comp_args, 0);
462     strarray_free(comp_args);
463 }
464
465 static const char* compile_to_object(struct options* opts, const char* file, const char* lang)
466 {
467     struct options copts;
468     char* base_name;
469
470     /* make a copy so we don't change any of the initial stuff */
471     /* a shallow copy is exactly what we want in this case */
472     base_name = get_basename(file);
473     copts = *opts;
474     copts.output_name = get_temp_file(base_name, ".o");
475     copts.compile_only = 1;
476     copts.files = strarray_alloc();
477     strarray_add(copts.files, file);
478     compile(&copts, lang);
479     strarray_free(copts.files);
480     free(base_name);
481
482     return copts.output_name;
483 }
484
485 /* check if there is a static lib associated to a given dll */
486 static char *find_static_lib( const char *dll )
487 {
488     char *lib = strmake("%s.a", dll);
489     if (get_file_type(lib) == file_arh) return lib;
490     free( lib );
491     return NULL;
492 }
493
494 /* add specified library to the list of files */
495 static void add_library( strarray *lib_dirs, strarray *files, const char *library )
496 {
497     char *static_lib, *fullname = 0;
498
499     switch(get_lib_type(lib_dirs, library, &fullname))
500     {
501     case file_arh:
502         strarray_add(files, strmake("-a%s", fullname));
503         break;
504     case file_dll:
505         strarray_add(files, strmake("-d%s", fullname));
506         if ((static_lib = find_static_lib(fullname)))
507         {
508             strarray_add(files, strmake("-a%s",static_lib));
509             free(static_lib);
510         }
511         break;
512     case file_so:
513     default:
514         /* keep it anyway, the linker may know what to do with it */
515         strarray_add(files, strmake("-l%s", library));
516         break;
517     }
518     free(fullname);
519 }
520
521 static void build(struct options* opts)
522 {
523     static const char *stdlibpath[] = { DLLDIR, LIBDIR, "/usr/lib", "/usr/local/lib", "/lib" };
524     strarray *lib_dirs, *files;
525     strarray *spec_args, *link_args;
526     char *output_file;
527     const char *spec_o_name;
528     const char *output_name, *spec_file, *lang;
529     const char* winebuild = getenv("WINEBUILD");
530     int generate_app_loader = 1;
531     unsigned int j;
532
533     /* NOTE: for the files array we'll use the following convention:
534      *    -axxx:  xxx is an archive (.a)
535      *    -dxxx:  xxx is a DLL (.def)
536      *    -lxxx:  xxx is an unsorted library
537      *    -oxxx:  xxx is an object (.o)
538      *    -rxxx:  xxx is a resource (.res)
539      *    -sxxx:  xxx is a shared lib (.so)
540      *    -xlll:  lll is the language (c, c++, etc.)
541      */
542
543     if (!winebuild) winebuild = "winebuild";
544
545     output_file = strdup( opts->output_name ? opts->output_name : "a.out" );
546
547     /* 'winegcc -o app xxx.exe.so' only creates the load script */
548     if (opts->files->size == 1 && strendswith(opts->files->base[0], ".exe.so"))
549     {
550         create_file(output_file, 0755, app_loader_template, opts->files->base[0]);
551         return;
552     }
553
554     /* generate app loader only for .exe */
555     if (opts->shared || strendswith(output_file, ".so"))
556         generate_app_loader = 0;
557
558     /* normalize the filename a bit: strip .so, ensure it has proper ext */
559     if (strendswith(output_file, ".so")) 
560         output_file[strlen(output_file) - 3] = 0;
561     if ((output_name = strrchr(output_file, '/'))) output_name++;
562     else output_name = output_file;
563     if (!strchr(output_name, '.'))
564         output_file = strmake("%s.%s", output_file, opts->shared ? "dll" : "exe");
565
566     /* get the filename from the path */
567     if ((output_name = strrchr(output_file, '/'))) output_name++;
568     else output_name = output_file;
569
570     /* prepare the linking path */
571     if (!opts->wine_objdir)
572     {
573         lib_dirs = strarray_dup(opts->lib_dirs);
574         for ( j = 0; j < sizeof(stdlibpath)/sizeof(stdlibpath[0]); j++ )
575             strarray_add(lib_dirs, stdlibpath[j]);
576     }
577     else
578     {
579         lib_dirs = strarray_alloc();
580         strarray_add(lib_dirs, strmake("%s/dlls", opts->wine_objdir));
581         strarray_add(lib_dirs, strmake("%s/libs/wine", opts->wine_objdir));
582         strarray_addall(lib_dirs, opts->lib_dirs);
583     }
584
585     /* mark the files with their appropriate type */
586     spec_file = lang = 0;
587     files = strarray_alloc();
588     for ( j = 0; j < opts->files->size; j++ )
589     {
590         const char* file = opts->files->base[j];
591         if (file[0] != '-')
592         {
593             switch(get_file_type(file))
594             {
595                 case file_def:
596                 case file_spec:
597                     if (spec_file)
598                         error("Only one spec file can be specified\n");
599                     spec_file = file;
600                     break;
601                 case file_rc:
602                     /* FIXME: invoke wrc to build it */
603                     error("Can't compile .rc file at the moment: %s\n", file);
604                     break;
605                 case file_res:
606                     strarray_add(files, strmake("-r%s", file));
607                     break;
608                 case file_obj:
609                     strarray_add(files, strmake("-o%s", file));
610                     break;
611                 case file_arh:
612                     strarray_add(files, strmake("-a%s", file));
613                     break;
614                 case file_so:
615                     strarray_add(files, strmake("-s%s", file));
616                     break;
617                 case file_na:
618                     error("File does not exist: %s\n", file);
619                     break;
620                 default:
621                     file = compile_to_object(opts, file, lang);
622                     strarray_add(files, strmake("-o%s", file));
623                     break;
624             }
625         }
626         else if (file[1] == 'l')
627             add_library( lib_dirs, files, file + 2 );
628         else if (file[1] == 'x')
629             lang = file;
630     }
631     if (opts->shared && !spec_file)
632         error("A spec file is currently needed in shared mode\n");
633
634     /* add the default libraries, if needed */
635     if (!opts->nostdlib && opts->use_msvcrt) add_library(lib_dirs, files, "msvcrt");
636
637     if (!opts->wine_objdir && !opts->nodefaultlibs) 
638     {
639         if (opts->gui_app) 
640         {
641             add_library(lib_dirs, files, "shell32");
642             add_library(lib_dirs, files, "comdlg32");
643             add_library(lib_dirs, files, "gdi32");
644         }
645         add_library(lib_dirs, files, "advapi32");
646         add_library(lib_dirs, files, "user32");
647         add_library(lib_dirs, files, "kernel32");
648     }
649
650     if (!opts->nostartfiles) add_library(lib_dirs, files, "winecrt0");
651     if (!opts->nostdlib) add_library(lib_dirs, files, "wine");
652
653     /* run winebuild to generate the .spec.o file */
654     spec_args = strarray_alloc();
655     spec_o_name = get_temp_file(output_name, ".spec.o");
656     strarray_add(spec_args, winebuild);
657     if (verbose) strarray_add(spec_args, "-v");
658     if (keep_generated) strarray_add(spec_args, "--save-temps");
659     if (opts->target)
660     {
661         strarray_add(spec_args, "--target");
662         strarray_add(spec_args, opts->target);
663     }
664     if (opts->force_pointer_size)
665         strarray_add(spec_args, strmake("-m%u", 8 * opts->force_pointer_size ));
666     strarray_addall(spec_args, strarray_fromstring(DLLFLAGS, " "));
667     strarray_add(spec_args, opts->shared ? "--dll" : "--exe");
668     strarray_add(spec_args, "-o");
669     strarray_add(spec_args, spec_o_name);
670     if (spec_file)
671     {
672         strarray_add(spec_args, "-E");
673         strarray_add(spec_args, spec_file);
674     }
675
676     if (!opts->shared)
677     {
678         strarray_add(spec_args, "-F");
679         strarray_add(spec_args, output_name);
680         strarray_add(spec_args, "--subsystem");
681         strarray_add(spec_args, opts->gui_app ? "windows" : "console");
682         if (opts->unicode_app)
683         {
684             strarray_add(spec_args, "--entry");
685             strarray_add(spec_args, "__wine_spec_exe_wentry");
686         }
687     }
688
689     for ( j = 0; j < lib_dirs->size; j++ )
690         strarray_add(spec_args, strmake("-L%s", lib_dirs->base[j]));
691
692     for ( j = 0 ; j < opts->winebuild_args->size ; j++ )
693         strarray_add(spec_args, opts->winebuild_args->base[j]);
694
695     for ( j = 0; j < files->size; j++ )
696     {
697         const char* name = files->base[j] + 2;
698         switch(files->base[j][1])
699         {
700             case 'r':
701                 strarray_add(spec_args, files->base[j]);
702                 break;
703             case 'd':
704             case 'a':
705             case 'o':
706                 strarray_add(spec_args, name);
707                 break;
708         }
709     }
710
711     spawn(opts->prefix, spec_args, 0);
712     strarray_free (spec_args);
713
714     /* link everything together now */
715     link_args = strarray_alloc();
716     strarray_addall(link_args, get_translator(opts));
717     strarray_addall(link_args, strarray_fromstring(LDDLLFLAGS, " "));
718
719     strarray_add(link_args, "-o");
720     strarray_add(link_args, strmake("%s.so", output_file));
721
722     for ( j = 0 ; j < opts->linker_args->size ; j++ ) 
723         strarray_add(link_args, opts->linker_args->base[j]);
724
725     switch (opts->target_platform)
726     {
727     case PLATFORM_APPLE:
728         if (opts->image_base)
729         {
730             strarray_add(link_args, "-image_base");
731             strarray_add(link_args, opts->image_base);
732         }
733         break;
734     case PLATFORM_SOLARIS:
735         {
736             char *mapfile = get_temp_file( output_name, ".map" );
737             const char *align = opts->section_align ? opts->section_align : "0x1000";
738
739             create_file( mapfile, 0644, "text = A%s;\ndata = A%s;\n", align, align );
740             strarray_add(link_args, strmake("-Wl,-M,%s", mapfile));
741             strarray_add(tmp_files, mapfile);
742         }
743         break;
744     default:
745         break;
746     }
747
748     for ( j = 0; j < lib_dirs->size; j++ )
749         strarray_add(link_args, strmake("-L%s", lib_dirs->base[j]));
750
751     strarray_add(link_args, spec_o_name);
752
753     for ( j = 0; j < files->size; j++ )
754     {
755         const char* name = files->base[j] + 2;
756         switch(files->base[j][1])
757         {
758             case 'l':
759             case 's':
760                 strarray_add(link_args, strmake("-l%s", name));
761                 break;
762             case 'a':
763             case 'o':
764                 strarray_add(link_args, name);
765                 break;
766         }
767     }
768
769     if (!opts->nostdlib) 
770     {
771         strarray_add(link_args, "-lm");
772         strarray_add(link_args, "-lc");
773     }
774
775     spawn(opts->prefix, link_args, 0);
776     strarray_free (link_args);
777
778     /* set the base address */
779     if (opts->image_base)
780     {
781         const char *prelink = PRELINK;
782         if (prelink[0] && strcmp(prelink,"false"))
783         {
784             strarray *prelink_args = strarray_alloc();
785             strarray_add(prelink_args, prelink);
786             strarray_add(prelink_args, "--reloc-only");
787             strarray_add(prelink_args, opts->image_base);
788             strarray_add(prelink_args, strmake("%s.so", output_file));
789             spawn(opts->prefix, prelink_args, 1);
790             strarray_free(prelink_args);
791         }
792     }
793
794     /* create the loader script */
795     if (generate_app_loader)
796         create_file(output_file, 0755, app_loader_template, strmake("%s.so", output_name));
797 }
798
799
800 static void forward(int argc, char **argv, struct options* opts)
801 {
802     strarray* args = strarray_alloc();
803     int j;
804
805     strarray_addall(args, get_translator(opts));
806
807     for( j = 1; j < argc; j++ ) 
808         strarray_add(args, argv[j]);
809
810     spawn(opts->prefix, args, 0);
811     strarray_free (args);
812 }
813
814 /*
815  *      Linker Options
816  *          object-file-name  -llibrary -nostartfiles  -nodefaultlibs
817  *          -nostdlib -s  -static  -static-libgcc  -shared  -shared-libgcc
818  *          -symbolic -Wl,option  -Xlinker option -u symbol
819  *          -framework name
820  */
821 static int is_linker_arg(const char* arg)
822 {
823     static const char* link_switches[] = 
824     {
825         "-nostartfiles", "-nodefaultlibs", "-nostdlib", "-s", 
826         "-static", "-static-libgcc", "-shared", "-shared-libgcc", "-symbolic",
827         "-framework"
828     };
829     unsigned int j;
830
831     switch (arg[1]) 
832     {
833         case 'R':
834         case 'z':
835         case 'l':
836         case 'u':
837             return 1;
838         case 'W':
839             if (strncmp("-Wl,", arg, 4) == 0) return 1;
840             break;
841         case 'X':
842             if (strcmp("-Xlinker", arg) == 0) return 1;
843             break;
844     }
845
846     for (j = 0; j < sizeof(link_switches)/sizeof(link_switches[0]); j++)
847         if (strcmp(link_switches[j], arg) == 0) return 1;
848
849     return 0;
850 }
851
852 /*
853  *      Target Options
854  *          -b machine  -V version
855  */
856 static int is_target_arg(const char* arg)
857 {
858     return arg[1] == 'b' || arg[2] == 'V';
859 }
860
861
862 /*
863  *      Directory Options
864  *          -Bprefix  -Idir  -I-  -Ldir  -specs=file
865  */
866 static int is_directory_arg(const char* arg)
867 {
868     return arg[1] == 'B' || arg[1] == 'L' || arg[1] == 'I' || strncmp("-specs=", arg, 7) == 0;
869 }
870
871 /*
872  *      MinGW Options
873  *          -mno-cygwin -mwindows -mconsole -mthreads -municode
874  */ 
875 static int is_mingw_arg(const char* arg)
876 {
877     static const char* mingw_switches[] = 
878     {
879         "-mno-cygwin", "-mwindows", "-mconsole", "-mthreads", "-municode"
880     };
881     unsigned int j;
882
883     for (j = 0; j < sizeof(mingw_switches)/sizeof(mingw_switches[0]); j++)
884         if (strcmp(mingw_switches[j], arg) == 0) return 1;
885
886     return 0;
887 }
888
889 static void parse_target_option( struct options *opts, const char *target )
890 {
891     char *p, *platform, *spec = xstrdup( target );
892     unsigned int i;
893
894     /* target specification is in the form CPU-MANUFACTURER-OS or CPU-MANUFACTURER-KERNEL-OS */
895
896     /* get the CPU part */
897
898     if (!(p = strchr( spec, '-' ))) error( "Invalid target specification '%s'\n", target );
899     *p++ = 0;
900     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
901     {
902         if (!strcmp( cpu_names[i].name, spec ))
903         {
904             opts->target_cpu = cpu_names[i].cpu;
905             break;
906         }
907     }
908     if (i == sizeof(cpu_names)/sizeof(cpu_names[0]))
909         error( "Unrecognized CPU '%s'\n", spec );
910     platform = p;
911     if ((p = strrchr( p, '-' ))) platform = p + 1;
912
913     /* get the OS part */
914
915     opts->target_platform = PLATFORM_UNSPECIFIED;  /* default value */
916     for (i = 0; i < sizeof(platform_names)/sizeof(platform_names[0]); i++)
917     {
918         if (!strncmp( platform_names[i].name, platform, strlen(platform_names[i].name) ))
919         {
920             opts->target_platform = platform_names[i].platform;
921             break;
922         }
923     }
924
925     free( spec );
926     opts->target = xstrdup( target );
927 }
928
929 int main(int argc, char **argv)
930 {
931     int i, c, next_is_arg = 0, linking = 1;
932     int raw_compiler_arg, raw_linker_arg;
933     const char* option_arg;
934     struct options opts;
935     char* lang = 0;
936     char* str;
937
938 #ifdef SIGHUP
939     signal( SIGHUP, exit_on_signal );
940 #endif
941     signal( SIGTERM, exit_on_signal );
942     signal( SIGINT, exit_on_signal );
943 #ifdef HAVE_SIGADDSET
944     sigemptyset( &signal_mask );
945     sigaddset( &signal_mask, SIGHUP );
946     sigaddset( &signal_mask, SIGTERM );
947     sigaddset( &signal_mask, SIGINT );
948 #endif
949
950     /* setup tmp file removal at exit */
951     tmp_files = strarray_alloc();
952     atexit(clean_temp_files);
953     
954     /* initialize options */
955     memset(&opts, 0, sizeof(opts));
956     opts.target_cpu = build_cpu;
957     opts.target_platform = build_platform;
958     opts.lib_dirs = strarray_alloc();
959     opts.files = strarray_alloc();
960     opts.linker_args = strarray_alloc();
961     opts.compiler_args = strarray_alloc();
962     opts.winebuild_args = strarray_alloc();
963
964     /* determine the processor type */
965     if (strendswith(argv[0], "winecpp")) opts.processor = proc_cpp;
966     else if (strendswith(argv[0], "++")) opts.processor = proc_cxx;
967     
968     /* parse options */
969     for ( i = 1 ; i < argc ; i++ ) 
970     {
971         if (argv[i][0] == '-')  /* option */
972         {
973             /* determine if tihs switch is followed by a separate argument */
974             next_is_arg = 0;
975             option_arg = 0;
976             switch(argv[i][1])
977             {
978                 case 'x': case 'o': case 'D': case 'U':
979                 case 'I': case 'A': case 'l': case 'u':
980                 case 'b': case 'V': case 'G': case 'L':
981                 case 'B': case 'R': case 'z':
982                     if (argv[i][2]) option_arg = &argv[i][2];
983                     else next_is_arg = 1;
984                     break;
985                 case 'i':
986                     next_is_arg = 1;
987                     break;
988                 case 'a':
989                     if (strcmp("-aux-info", argv[i]) == 0)
990                         next_is_arg = 1;
991                     break;
992                 case 'X':
993                     if (strcmp("-Xlinker", argv[i]) == 0)
994                         next_is_arg = 1;
995                     break;
996                 case 'M':
997                     c = argv[i][2];
998                     if (c == 'F' || c == 'T' || c == 'Q')
999                     {
1000                         if (argv[i][3]) option_arg = &argv[i][3];
1001                         else next_is_arg = 1;
1002                     }
1003                     break;
1004                 case 'f':
1005                     if (strcmp("-framework", argv[i]) == 0)
1006                         next_is_arg = 1;
1007                     break;
1008             }
1009             if (next_is_arg) option_arg = argv[i+1];
1010
1011             /* determine what options go 'as is' to the linker & the compiler */
1012             raw_compiler_arg = raw_linker_arg = 0;
1013             if (is_linker_arg(argv[i])) 
1014             {
1015                 raw_linker_arg = 1;
1016             }
1017             else 
1018             {
1019                 if (is_directory_arg(argv[i]) || is_target_arg(argv[i]))
1020                     raw_linker_arg = 1;
1021                 raw_compiler_arg = !is_mingw_arg(argv[i]);
1022             }
1023
1024             /* these things we handle explicitly so we don't pass them 'as is' */
1025             if (argv[i][1] == 'l' || argv[i][1] == 'I' || argv[i][1] == 'L')
1026                 raw_linker_arg = 0;
1027             if (argv[i][1] == 'c' || argv[i][1] == 'L')
1028                 raw_compiler_arg = 0;
1029             if (argv[i][1] == 'o' || argv[i][1] == 'b')
1030                 raw_compiler_arg = raw_linker_arg = 0;
1031
1032             /* do a bit of semantic analysis */
1033             switch (argv[i][1]) 
1034             {
1035                 case 'B':
1036                     str = strdup(option_arg);
1037                     if (strendswith(str, "/tools/winebuild"))
1038                     {
1039                         char *objdir = strdup(str);
1040                         objdir[strlen(objdir) - sizeof("/tools/winebuild") + 1] = 0;
1041                         opts.wine_objdir = objdir;
1042                         /* don't pass it to the compiler, this generates warnings */
1043                         raw_compiler_arg = raw_linker_arg = 0;
1044                     }
1045                     if (strendswith(str, "/")) str[strlen(str) - 1] = 0;
1046                     if (!opts.prefix) opts.prefix = strarray_alloc();
1047                     strarray_add(opts.prefix, str);
1048                     break;
1049                 case 'b':
1050                     parse_target_option( &opts, option_arg );
1051                     break;
1052                 case 'c':        /* compile or assemble */
1053                     if (argv[i][2] == 0) opts.compile_only = 1;
1054                     /* fall through */
1055                 case 'S':        /* generate assembler code */
1056                 case 'E':        /* preprocess only */
1057                     if (argv[i][2] == 0) linking = 0;
1058                     break;
1059                 case 'f':
1060                     if (strcmp("-fno-short-wchar", argv[i]) == 0)
1061                         opts.noshortwchar = 1;
1062                     break;
1063                 case 'l':
1064                     strarray_add(opts.files, strmake("-l%s", option_arg));
1065                     break;
1066                 case 'L':
1067                     strarray_add(opts.lib_dirs, option_arg);
1068                     break;
1069                 case 'M':        /* map file generation */
1070                     linking = 0;
1071                     break;
1072                 case 'm':
1073                     if (strcmp("-mno-cygwin", argv[i]) == 0)
1074                         opts.use_msvcrt = 1;
1075                     else if (strcmp("-mwindows", argv[i]) == 0)
1076                         opts.gui_app = 1;
1077                     else if (strcmp("-mconsole", argv[i]) == 0)
1078                         opts.gui_app = 0;
1079                     else if (strcmp("-municode", argv[i]) == 0)
1080                         opts.unicode_app = 1;
1081                     else if (strcmp("-m32", argv[i]) == 0)
1082                     {
1083                         opts.force_pointer_size = 4;
1084                         raw_linker_arg = 1;
1085                     }
1086                     else if (strcmp("-m64", argv[i]) == 0)
1087                     {
1088                         opts.force_pointer_size = 8;
1089                         raw_linker_arg = 1;
1090                     }
1091                     break;
1092                 case 'n':
1093                     if (strcmp("-nostdinc", argv[i]) == 0)
1094                         opts.nostdinc = 1;
1095                     else if (strcmp("-nodefaultlibs", argv[i]) == 0)
1096                         opts.nodefaultlibs = 1;
1097                     else if (strcmp("-nostdlib", argv[i]) == 0)
1098                         opts.nostdlib = 1;
1099                     else if (strcmp("-nostartfiles", argv[i]) == 0)
1100                         opts.nostartfiles = 1;
1101                     break;
1102                 case 'o':
1103                     opts.output_name = option_arg;
1104                     break;
1105                 case 's':
1106                     if (strcmp("-static", argv[i]) == 0) 
1107                         linking = -1;
1108                     else if(strcmp("-save-temps", argv[i]) == 0)
1109                         keep_generated = 1;
1110                     else if(strcmp("-shared", argv[i]) == 0)
1111                     {
1112                         opts.shared = 1;
1113                         raw_compiler_arg = raw_linker_arg = 0;
1114                     }
1115                     break;
1116                 case 'v':
1117                     if (argv[i][2] == 0) verbose++;
1118                     break;
1119                 case 'W':
1120                     if (strncmp("-Wl,", argv[i], 4) == 0)
1121                     {
1122                         unsigned int j;
1123                         strarray* Wl = strarray_fromstring(argv[i] + 4, ",");
1124                         for (j = 0; j < Wl->size; j++)
1125                         {
1126                             if (!strcmp(Wl->base[j], "--image-base") && j < Wl->size - 1)
1127                             {
1128                                 opts.image_base = strdup( Wl->base[++j] );
1129                                 continue;
1130                             }
1131                             if (!strcmp(Wl->base[j], "--section-alignment") && j < Wl->size - 1)
1132                             {
1133                                 opts.section_align = strdup( Wl->base[++j] );
1134                                 continue;
1135                             }
1136                             if (!strcmp(Wl->base[j], "-static")) linking = -1;
1137                             strarray_add(opts.linker_args, strmake("-Wl,%s",Wl->base[j]));
1138                         }
1139                         strarray_free(Wl);
1140                         raw_compiler_arg = raw_linker_arg = 0;
1141                     }
1142                     else if (strncmp("-Wb,", argv[i], 4) == 0)
1143                     {
1144                         strarray* Wb = strarray_fromstring(argv[i] + 4, ",");
1145                         strarray_addall(opts.winebuild_args, Wb);
1146                         strarray_free(Wb);
1147                         /* don't pass it to the compiler, it generates errors */
1148                         raw_compiler_arg = raw_linker_arg = 0;
1149                     }
1150                     break;
1151                 case 'x':
1152                     lang = strmake("-x%s", option_arg);
1153                     strarray_add(opts.files, lang);
1154                     /* we'll pass these flags ourselves, explicitly */
1155                     raw_compiler_arg = raw_linker_arg = 0;
1156                     break;
1157                 case '-':
1158                     if (strcmp("-static", argv[i]+1) == 0)
1159                         linking = -1;
1160                     break;
1161             }
1162
1163             /* put the arg into the appropriate bucket */
1164             if (raw_linker_arg) 
1165             {
1166                 strarray_add(opts.linker_args, argv[i]);
1167                 if (next_is_arg && (i + 1 < argc)) 
1168                     strarray_add(opts.linker_args, argv[i + 1]);
1169             }
1170             if (raw_compiler_arg)
1171             {
1172                 strarray_add(opts.compiler_args, argv[i]);
1173                 if (next_is_arg && (i + 1 < argc))
1174                     strarray_add(opts.compiler_args, argv[i + 1]);
1175             }
1176
1177             /* skip the next token if it's an argument */
1178             if (next_is_arg) i++;
1179         }
1180         else
1181         {
1182             strarray_add(opts.files, argv[i]);
1183         } 
1184     }
1185
1186     if (opts.processor == proc_cpp) linking = 0;
1187     if (linking == -1) error("Static linking is not supported\n");
1188
1189     if (opts.files->size == 0) forward(argc, argv, &opts);
1190     else if (linking) build(&opts);
1191     else compile(&opts, lang);
1192
1193     return 0;
1194 }