Relicensing TinyCC
[tinycc.git] / tcc.c
1 /*
2  *  TCC - Tiny C Compiler
3  * 
4  *  Copyright (c) 2001-2004 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #ifdef ONE_SOURCE
22 #include "libtcc.c"
23 #else
24 #include "tcc.h"
25 #endif
26
27 static void help(void)
28 {
29     printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
30            "Usage: tcc [options...] [-o outfile] [-c] infile(s)...\n"
31            "       tcc [options...] -run infile [arguments...]\n"
32            "General options:\n"
33            "  -c          compile only - generate an object file\n"
34            "  -o outfile  set output filename\n"
35            "  -run        run compiled source\n"
36            "  -fflag      set or reset (with 'no-' prefix) 'flag' (see man page)\n"
37            "  -Wwarning   set or reset (with 'no-' prefix) 'warning' (see man page)\n"
38            "  -w          disable all warnings\n"
39            "  -v          show version\n"
40            "  -vv         show included files (as sole argument: show search paths)\n"
41            "  -dumpversion\n"
42            "  -bench      show compilation statistics\n"
43            "Preprocessor options:\n"
44            "  -E          preprocess only\n"
45            "  -Idir       add include path 'dir'\n"
46            "  -Dsym[=val] define 'sym' with value 'val'\n"
47            "  -Usym       undefine 'sym'\n"
48            "Linker options:\n"
49            "  -Ldir       add library path 'dir'\n"
50            "  -llib       link with dynamic or static library 'lib'\n"
51            "  -pthread    link with -lpthread and -D_REENTRANT (POSIX Linux)\n"
52            "  -r          generate (relocatable) object file\n"
53            "  -rdynamic   export all global symbols to dynamic linker\n"
54            "  -shared     generate a shared library\n"
55            "  -soname     set name for shared library to be used at runtime\n"
56            "  -static     static linking\n"
57            "  -Wl,-opt[=val]  set linker option (see manual)\n"
58            "Debugger options:\n"
59            "  -g          generate runtime debug info\n"
60 #ifdef CONFIG_TCC_BCHECK
61            "  -b          compile with built-in memory and bounds checker (implies -g)\n"
62 #endif
63 #ifdef CONFIG_TCC_BACKTRACE
64            "  -bt N       show N callers in stack traces\n"
65 #endif
66            "Misc options:\n"
67            "  -nostdinc   do not use standard system include paths\n"
68            "  -nostdlib   do not link with standard crt and libraries\n"
69            "  -Bdir       use 'dir' as tcc internal library and include path\n"
70            "  -MD         generate target dependencies for make\n"
71            "  -MF depfile put generated dependencies here\n"
72            "  -norunsrc   Do not compile the file which is the first argument after -run.\n"
73            );
74 }
75
76 /* re-execute the i386/x86_64 cross-compilers with tcc -m32/-m64: */
77 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
78 #ifdef _WIN32
79 #include <process.h>
80 static int execvp_win32(const char *prog, char **argv)
81 {
82     int ret = spawnvp(P_NOWAIT, prog, (char const*const*)argv);
83     if (-1 == ret)
84         return ret;
85     cwait(&ret, ret, WAIT_CHILD);
86     exit(ret);
87 }
88 #define execvp execvp_win32
89 #endif
90 static void exec_other_tcc(TCCState *s, char **argv, const char *optarg)
91 {
92     char child_path[4096], *child_name; const char *target;
93     switch (atoi(optarg)) {
94 #ifdef TCC_TARGET_I386
95         case 32: break;
96         case 64: target = "x86_64";
97 #else
98         case 64: break;
99         case 32: target = "i386";
100 #endif
101             pstrcpy(child_path, sizeof child_path - 40, argv[0]);
102             child_name = tcc_basename(child_path);
103             strcpy(child_name, target);
104 #ifdef TCC_TARGET_PE
105             strcat(child_name, "-win32");
106 #endif
107             strcat(child_name, "-tcc");
108             if (strcmp(argv[0], child_path)) {
109                 if (s->verbose > 0)
110                     printf("tcc: using '%s'\n", child_name), fflush(stdout);
111                 execvp(argv[0] = child_path, argv);
112             }
113             tcc_error("'%s' not found", child_name);
114         case 0: /* ignore -march etc. */
115             break;
116         default:
117             tcc_warning("unsupported option \"-m%s\"", optarg);
118     }
119 }
120 #else
121 #define exec_other_tcc(s, argv, optarg)
122 #endif
123
124 static void gen_makedeps(TCCState *s, const char *target, const char *filename)
125 {
126     FILE *depout;
127     char buf[1024], *ext;
128     int i;
129
130     if (!filename) {
131         /* compute filename automatically
132          * dir/file.o -> dir/file.d             */
133         pstrcpy(buf, sizeof(buf), target);
134         ext = tcc_fileextension(buf);
135         pstrcpy(ext, sizeof(buf) - (ext-buf), ".d");
136         filename = buf;
137     }
138
139     if (s->verbose)
140         printf("<- %s\n", filename);
141
142     /* XXX return err codes instead of error() ? */
143     depout = fopen(filename, "w");
144     if (!depout)
145         tcc_error("could not open '%s'", filename);
146
147     fprintf(depout, "%s : \\\n", target);
148     for (i=0; i<s->nb_target_deps; ++i)
149         fprintf(depout, " %s \\\n", s->target_deps[i]);
150     fprintf(depout, "\n");
151     fclose(depout);
152 }
153
154 static char *default_outputfile(TCCState *s, const char *first_file)
155 {
156     char buf[1024];
157     char *ext;
158     const char *name = "a";
159
160     if (first_file && strcmp(first_file, "-"))
161         name = tcc_basename(first_file);
162     pstrcpy(buf, sizeof(buf), name);
163     ext = tcc_fileextension(buf);
164 #ifdef TCC_TARGET_PE
165     if (s->output_type == TCC_OUTPUT_DLL)
166         strcpy(ext, ".dll");
167     else
168     if (s->output_type == TCC_OUTPUT_EXE)
169         strcpy(ext, ".exe");
170     else
171 #endif
172     if (( (s->output_type == TCC_OUTPUT_OBJ && !s->option_r) ||
173           (s->output_type == TCC_OUTPUT_PREPROCESS) )
174         && *ext)
175         strcpy(ext, ".o");
176     else
177         strcpy(buf, "a.out");
178
179     return tcc_strdup(buf);
180 }
181
182 static void print_paths(const char *msg, char **paths, int nb_paths)
183 {
184     int i;
185     printf("%s:\n%s", msg, nb_paths ? "" : "  -\n");
186     for(i = 0; i < nb_paths; i++)
187         printf("  %s\n", paths[i]);
188 }
189
190 static void display_info(TCCState *s, int what)
191 {
192     switch (what) {
193     case 0:
194         printf("tcc version %s ("
195 #ifdef TCC_TARGET_I386
196         "i386"
197 # ifdef TCC_TARGET_PE
198         " Win32"
199 # endif
200 #elif defined TCC_TARGET_X86_64
201         "x86-64"
202 # ifdef TCC_TARGET_PE
203         " Win64"
204 # endif
205 #elif defined TCC_TARGET_ARM
206         "ARM"
207 # ifdef TCC_ARM_HARDFLOAT
208         " Hard Float"
209 # endif
210 # ifdef TCC_TARGET_PE
211         " WinCE"
212 # endif
213 #endif
214 #ifndef TCC_TARGET_PE
215 # ifdef __linux
216         " Linux"
217 # endif
218 #endif
219         ")\n", TCC_VERSION);
220         break;
221     case 1:
222         printf("install: %s/\n", s->tcc_lib_path);
223         /* print_paths("programs", NULL, 0); */
224         print_paths("crt", s->crt_paths, s->nb_crt_paths);
225         print_paths("libraries", s->library_paths, s->nb_library_paths);
226         print_paths("include", s->sysinclude_paths, s->nb_sysinclude_paths);
227         printf("elfinterp:\n  %s\n",  CONFIG_TCC_ELFINTERP);
228         break;
229     }
230 }
231
232 static int64_t getclock_us(void)
233 {
234 #ifdef _WIN32
235     struct _timeb tb;
236     _ftime(&tb);
237     return (tb.time * 1000LL + tb.millitm) * 1000LL;
238 #else
239     struct timeval tv;
240     gettimeofday(&tv, NULL);
241     return tv.tv_sec * 1000000LL + tv.tv_usec;
242 #endif
243 }
244
245 int main(int argc, char **argv)
246 {
247     TCCState *s;
248     int ret, optind, i, bench;
249     int64_t start_time = 0;
250     const char *first_file = NULL;
251
252     s = tcc_new();
253     s->output_type = TCC_OUTPUT_EXE;
254
255     optind = tcc_parse_args(s, argc - 1, argv + 1);
256     tcc_set_environment(s);
257
258     if (optind == 0) {
259         help();
260         return 1;
261     }
262
263     if (s->option_m)
264         exec_other_tcc(s, argv, s->option_m);
265
266     if (s->verbose)
267         display_info(s, 0);
268
269     if (s->print_search_dirs || (s->verbose == 2 && optind == 1)) {
270         tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
271         display_info(s, 1);
272         return 0;
273     }
274
275     if (s->verbose && optind == 1)
276         return 0;
277
278     if (s->nb_files == 0)
279         tcc_error("no input files\n");
280
281     /* check -c consistency : only single file handled. XXX: checks file type */
282     if (s->output_type == TCC_OUTPUT_OBJ && !s->option_r) {
283         if (s->nb_libraries != 0)
284             tcc_error("cannot specify libraries with -c");
285         /* accepts only a single input file */
286         if (s->nb_files != 1)
287             tcc_error("cannot specify multiple files with -c");
288     }
289     
290     if (s->output_type == TCC_OUTPUT_PREPROCESS) {
291         if (!s->outfile) {
292             s->ppfp = stdout;
293         } else {
294             s->ppfp = fopen(s->outfile, "w");
295             if (!s->ppfp)
296                 tcc_error("could not write '%s'", s->outfile);
297         }
298     }
299
300     bench = s->do_bench;
301     if (bench)
302         start_time = getclock_us();
303
304     tcc_set_output_type(s, s->output_type);
305
306     /* compile or add each files or library */
307     for(i = ret = 0; i < s->nb_files && ret == 0; i++) {
308         const char *filename;
309
310         filename = s->files[i];
311         if (filename[0] == '-' && filename[1] == 'l') {
312             if (tcc_add_library(s, filename + 2) < 0) {
313                 tcc_error_noabort("cannot find '%s'", filename);
314                 ret = 1;
315             }
316         } else {
317             if (1 == s->verbose)
318                 printf("-> %s\n", filename);
319             if (tcc_add_file(s, filename) < 0)
320                 ret = 1;
321             if (!first_file)
322                 first_file = filename;
323         }
324     }
325
326     if (0 == ret) {
327         if (bench)
328             tcc_print_stats(s, getclock_us() - start_time);
329
330         if (s->output_type == TCC_OUTPUT_MEMORY) {
331 #ifdef TCC_IS_NATIVE
332             ret = tcc_run(s, argc - 1 - optind, argv + 1 + optind);
333 #else
334             tcc_error_noabort("-run is not available in a cross compiler");
335             ret = 1;
336 #endif
337         } else if (s->output_type == TCC_OUTPUT_PREPROCESS) {
338              if (s->outfile)
339                 fclose(s->ppfp);
340         } else {
341             if (!s->outfile)
342                 s->outfile = default_outputfile(s, first_file);
343             ret = !!tcc_output_file(s, s->outfile);
344             /* dump collected dependencies */
345             if (s->gen_deps && !ret)
346                 gen_makedeps(s, s->outfile, s->deps_outfile);
347         }
348     }
349
350     tcc_delete(s);
351     if (bench)
352         tcc_memstats();
353     return ret;
354 }