0670375a95b5c884fa26314543855a7a956e66eb
[cparser] / main.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #ifdef _WIN32
13
14 #include <fcntl.h>
15 #include <io.h>
16
17 /* no eXecute on Win32 */
18 #define X_OK 0
19 #define W_OK 2
20 #define R_OK 4
21
22 #define O_RDWR          _O_RDWR
23 #define O_CREAT         _O_CREAT
24 #define O_EXCL          _O_EXCL
25 #define O_BINARY        _O_BINARY
26
27 /* remap some names, we are not in the POSIX world */
28 #define access(fname, mode)      _access(fname, mode)
29 #define mktemp(tmpl)             _mktemp(tmpl)
30 #define open(fname, oflag, mode) _open(fname, oflag, mode)
31 #define fdopen(fd, mode)         _fdopen(fd, mode)
32 #define popen(cmd, mode)         _popen(cmd, mode)
33 #define pclose(file)             _pclose(file)
34
35 #else
36 #include <unistd.h>
37 #define HAVE_MKSTEMP
38 #endif
39
40 #ifndef WITH_LIBCORE
41 #define WITH_LIBCORE
42 #endif
43
44 #include <libfirm/firm.h>
45 #include <libfirm/be.h>
46
47 #include "lexer.h"
48 #include "token_t.h"
49 #include "types.h"
50 #include "type_hash.h"
51 #include "parser.h"
52 #include "ast2firm.h"
53 #include "diagnostic.h"
54 #include "lang_features.h"
55 #include "driver/firm_opt.h"
56 #include "driver/firm_cmdline.h"
57 #include "adt/error.h"
58 #include "write_fluffy.h"
59 #include "revision.h"
60 #include "warning.h"
61
62 #ifndef PREPROCESSOR
63 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int"
64 #endif
65
66 #ifndef LINKER
67 #define LINKER    "gcc -m32"
68 #endif
69
70 #ifndef ASSEMBLER
71 #define ASSEMBLER "as --32"
72 #endif
73
74 /** The current c mode/dialect. */
75 unsigned int c_mode = _C89|_C99|_GNUC;
76
77 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
78 unsigned int machine_size = 32;
79
80 /** true if the char type is signed. */
81 bool char_is_signed = true;
82
83 /** true for strict language checking. */
84 bool strict_mode = false;
85
86 /* to switch off printing of implicit casts */
87 extern bool print_implicit_casts;
88
89 static int            verbose;
90 static struct obstack cppflags_obst, ldflags_obst;
91
92 #if defined(_DEBUG) || defined(FIRM_DEBUG)
93 /**
94  * Debug printf implementation.
95  *
96  * @param fmt  printf style format parameter
97  */
98 void dbg_printf(const char *fmt, ...)
99 {
100         va_list list;
101
102         if (firm_dump.debug_print) {
103                 va_start(list, fmt);
104                 vprintf(fmt, list);
105                 va_end(list);
106         }  /* if */
107 }
108 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
109
110 static void initialize_firm(void)
111 {
112         firm_early_init();
113
114         dump_consts_local(1);
115         dump_keepalive_edges(1);
116 }
117
118 static void get_output_name(char *buf, size_t buflen, const char *inputname,
119                             const char *newext)
120 {
121         size_t last_dot = 0xffffffff;
122         size_t i = 0;
123
124         if(inputname == NULL) {
125                 snprintf(buf, buflen, "a%s", newext);
126                 return;
127         }
128
129         for(const char *c = inputname; *c != 0; ++c) {
130                 if(*c == '.')
131                         last_dot = i;
132                 ++i;
133         }
134         if(last_dot == 0xffffffff)
135                 last_dot = i;
136
137         if(last_dot >= buflen)
138                 panic("filename too long");
139         memcpy(buf, inputname, last_dot);
140
141         size_t extlen = strlen(newext) + 1;
142         if(extlen + last_dot >= buflen)
143                 panic("filename too long");
144         memcpy(buf+last_dot, newext, extlen);
145 }
146
147 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
148 {
149         lexer_open_stream(in, input);
150         translation_unit_t *unit = parse();
151         return unit;
152 }
153
154 static void lextest(FILE *in, const char *fname)
155 {
156         lexer_open_stream(in, fname);
157
158         do {
159                 lexer_next_preprocessing_token();
160                 print_token(stdout, &lexer_token);
161                 puts("");
162         } while(lexer_token.type != T_EOF);
163 }
164
165 static FILE* preprocess(FILE* in, const char *fname)
166 {
167         char buf[4096];
168         const char *flags = obstack_finish(&cppflags_obst);
169
170         if(in != stdin) {
171                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
172         } else {
173                 /* read from stdin */
174                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
175         }
176
177         if(verbose) {
178                 puts(buf);
179         }
180         FILE* f = popen(buf, "r");
181         if (f == NULL) {
182                 fprintf(stderr, "invoking preprocessor failed\n");
183                 exit(1);
184         }
185         return f;
186 }
187
188 static void do_link(const char *out, const char *in)
189 {
190         char buf[4096];
191         const char *flags = obstack_finish(&ldflags_obst);
192
193         snprintf(buf, sizeof(buf), LINKER " %s -o %s %s", flags, out, in);
194         if(verbose) {
195                 puts(buf);
196         }
197         int err = system(buf);
198         if(err != 0) {
199                 fprintf(stderr, "linker reported an error\n");
200                 exit(1);
201         }
202 }
203
204 static void assemble(const char *out, const char *in)
205 {
206         char buf[4096];
207
208         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
209         if(verbose) {
210                 puts(buf);
211         }
212
213         int err = system(buf);
214         if(err != 0) {
215                 fprintf(stderr, "assembler reported an error\n");
216                 exit(1);
217         }
218 }
219
220 static const char *try_dir(const char *dir)
221 {
222         if(dir == NULL)
223                 return dir;
224         if(access(dir, R_OK | W_OK | X_OK) == 0)
225                 return dir;
226         return NULL;
227 }
228
229 static const char *get_tempdir(void)
230 {
231         static const char *tmpdir = NULL;
232
233         if(tmpdir != NULL)
234                 return tmpdir;
235
236         if(tmpdir == NULL)
237                 tmpdir = try_dir(getenv("TMPDIR"));
238         if(tmpdir == NULL)
239                 tmpdir = try_dir(getenv("TMP"));
240         if(tmpdir == NULL)
241                 tmpdir = try_dir(getenv("TEMP"));
242
243 #ifdef P_tmpdir
244         if(tmpdir == NULL)
245                 tmpdir = try_dir(P_tmpdir);
246 #endif
247
248         if(tmpdir == NULL)
249                 tmpdir = try_dir("/var/tmp");
250         if(tmpdir == NULL)
251                 tmpdir = try_dir("/usr/tmp");
252         if(tmpdir == NULL)
253                 tmpdir = try_dir("/tmp");
254
255         if(tmpdir == NULL)
256                 tmpdir = ".";
257
258         return tmpdir;
259 }
260
261 #ifndef HAVE_MKSTEMP
262 /* cheap and nasty mkstemp replacement */
263 static int mkstemp(char *templ)
264 {
265         mktemp(templ);
266         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
267 }
268 #endif
269
270 /**
271  * an own version of tmpnam, which: writes in a buffer, appends a user specified
272  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
273  */
274 static FILE *make_temp_file(char *buffer, size_t buflen,
275                             const char *prefix, const char *suffix)
276 {
277         const char *tempdir = get_tempdir();
278
279         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
280         (void) suffix;
281         suffix = "";
282
283         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
284
285         int fd = mkstemp(buffer);
286         if(fd == -1) {
287                 fprintf(stderr, "couldn't create temporary file: %s\n",
288                         strerror(errno));
289                 exit(1);
290         }
291         FILE *out = fdopen(fd, "w");
292         if(out == NULL) {
293                 fprintf(stderr, "couldn't create temporary file FILE*\n");
294                 exit(1);
295         }
296
297         return out;
298 }
299
300 /**
301  * Do the necessary lowering for compound parameters.
302  */
303 void lower_compound_params(void)
304 {
305         lower_params_t params;
306
307         params.def_ptr_alignment    = 4;
308         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
309         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
310         params.find_pointer_type    = NULL;
311         params.ret_compound_in_regs = NULL;
312         lower_calls_with_compounds(&params);
313 }
314
315 typedef enum compile_mode_t {
316         ParseOnly,
317         Compile,
318         CompileDump,
319         CompileAssemble,
320         CompileAssembleLink,
321         LexTest,
322         PrintAst,
323         PrintFluffy
324 } compile_mode_t;
325
326 static void usage(const char *argv0)
327 {
328         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
329 }
330
331 int main(int argc, char **argv)
332 {
333         initialize_firm();
334
335         const char     *input        = NULL;
336         const char     *outname      = NULL;
337         const char     *dumpfunction = NULL;
338         compile_mode_t  mode         = CompileAssembleLink;
339
340         obstack_init(&cppflags_obst);
341         obstack_init(&ldflags_obst);
342
343 #define GET_ARG_AFTER(def, args)                                             \
344         def = &arg[sizeof(args)-1];                                              \
345         if(def[0] == '\0') {                                                     \
346                 ++i;                                                                 \
347                 if(i >= argc) {                                                      \
348                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
349                         argument_errors = true;                                          \
350                         break;                                                           \
351                 }                                                                    \
352                 def = argv[i];                                                       \
353                 if(def[0] == '-' && def[1] != '\0') {                                \
354                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
355                         argument_errors = true;                                          \
356                         continue;                                                        \
357                 }                                                                    \
358         }
359
360 #define SINGLE_OPTION(ch) (option[0] == (ch) && option[1] == '\0')
361
362         bool help_displayed  = false;
363         bool argument_errors = false;
364         for(int i = 1; i < argc; ++i) {
365                 const char *arg = argv[i];
366                 if(arg[0] == '-') {
367                         /* an option */
368                         const char *option = &arg[1];
369                         if(option[0] == 'o') {
370                                 GET_ARG_AFTER(outname, "-o");
371                         } else if(SINGLE_OPTION('c')) {
372                                 mode = CompileAssemble;
373                         } else if(SINGLE_OPTION('S')) {
374                                 mode = Compile;
375                         } else if(option[0] == 'I') {
376                                 const char *opt;
377                                 GET_ARG_AFTER(opt, "-I");
378                                 obstack_printf(&cppflags_obst, " -I%s", opt);
379                         } else if(option[0] == 'D') {
380                                 const char *opt;
381                                 GET_ARG_AFTER(opt, "-D");
382                                 obstack_printf(&cppflags_obst, " -D%s", opt);
383                         } else if(option[0] == 'U') {
384                                 const char *opt;
385                                 GET_ARG_AFTER(opt, "-U");
386                                 obstack_printf(&cppflags_obst, " -U%s", opt);
387                         } else if(option[0] == 'l') {
388                                 const char *opt;
389                                 GET_ARG_AFTER(opt, "-l");
390                                 obstack_printf(&ldflags_obst, " -l%s", opt);
391                         } else if(option[0] == 'L') {
392                                 const char *opt;
393                                 GET_ARG_AFTER(opt, "-L");
394                                 obstack_printf(&ldflags_obst, " -L%s", opt);
395                         } else if(SINGLE_OPTION('v')) {
396                                 verbose = 1;
397                         } else if(SINGLE_OPTION('w')) {
398                                 inhibit_all_warnings = true;
399                         } else if(option[0] == 'f') {
400                                 const char *opt;
401                                 GET_ARG_AFTER(opt, "-f");
402
403                                 if(strcmp(opt, "syntax-only") == 0) {
404                                         mode = ParseOnly;
405                                 } else if(strcmp(opt, "omit-frame-pointer") == 0) {
406                                         firm_be_option("omitfp");
407                                 } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
408                                         firm_be_option("omitfp=no");
409                                 } else {
410                                         int res = firm_option(opt);
411                                         if (res == 0) {
412                                                 fprintf(stderr, "error: unknown Firm option '-f %s'\n",
413                                                         opt);
414                                                 argument_errors = true;
415                                                 continue;
416                                         } else if (res == -1) {
417                                                 help_displayed = true;
418                                         }
419                                 }
420                         } else if(option[0] == 'b') {
421                                 const char *opt;
422                                 GET_ARG_AFTER(opt, "-b");
423                                 int res = firm_be_option(opt);
424                                 if (res == 0) {
425                                         fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
426                                                 opt);
427                                         argument_errors = true;
428                                 } else if (res == -1) {
429                                         help_displayed = true;
430                                 }
431                         } else if(option[0] == 'W') {
432                                 set_warning_opt(&option[1]);
433                         } else if(option[0] == 'm') {
434                                 const char *opt;
435                                 GET_ARG_AFTER(opt, "-m");
436                                 char *endptr;
437                                 long int value = strtol(opt, &endptr, 10);
438                                 if (*endptr != '\0') {
439                                         fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
440                                         argument_errors = true;
441                                 }
442                                 if (value != 16 && value != 32 && value != 64) {
443                                         fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
444                                         argument_errors = true;
445                                 } else {
446                                         machine_size = (unsigned int)value;
447                                 }
448                         } else if (option[0] == '\0') {
449                                 if(input != NULL) {
450                                         fprintf(stderr, "error: multiple input files specified\n");
451                                         argument_errors = true;
452                                 } else {
453                                         input = arg;
454                                 }
455                         } else if(strcmp(option, "pedantic") == 0) {
456                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
457                         } else if(option[0] == 'O' ||
458                                   option[0] == 'g' ||
459                                   strncmp(option, "std=", 4) == 0) {
460                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
461                         } else if (option[0] == '-') {
462                                 /* double dash option */
463                                 ++option;
464                                 if(strcmp(option, "gcc") == 0) {
465                                         c_mode |= _GNUC;
466                                 } else if(strcmp(option, "no-gcc") == 0) {
467                                         c_mode &= ~_GNUC;
468                                 } else if(strcmp(option, "ms") == 0) {
469                                         c_mode |= _MS;
470                                 } else if(strcmp(option, "no-ms") == 0) {
471                                         c_mode &= ~_MS;
472                                 } else if(strcmp(option, "signed-chars") == 0) {
473                                         char_is_signed = true;
474                                 } else if(strcmp(option, "unsigned-chars") == 0) {
475                                         char_is_signed = false;
476                                 } else if(strcmp(option, "strict") == 0) {
477                                         strict_mode = true;
478                                 } else if(strcmp(option, "lextest") == 0) {
479                                         mode = LexTest;
480                                 } else if(strcmp(option, "print-ast") == 0) {
481                                         mode = PrintAst;
482                                 } else if(strcmp(option, "no-implicit-cast") == 0) {
483                                         print_implicit_casts = false;
484                                 } else if(strcmp(option, "print-fluffy") == 0) {
485                                         mode = PrintFluffy;
486                                 } else if(strcmp(option, "version") == 0) {
487                                         firm_version_t ver;
488                                         firm_get_version(&ver);
489                                         printf("cparser (%d.%d %s) using libFirm (%u.%u", 0, 1, cparser_REVISION, ver.major, ver.minor);
490                                         if(ver.revision[0] != 0) {
491                                                 putchar(' ');
492                                                 fputs(ver.revision, stdout);
493                                         }
494                                         if(ver.build[0] != 0) {
495                                                 putchar(' ');
496                                                 fputs(ver.build, stdout);
497                                         }
498                                         puts(")\n");
499                                         exit(EXIT_SUCCESS);
500                                 } else if(strcmp(option, "dump-function") == 0) {
501                                         ++i;
502                                         if(i >= argc) {
503                                                 fprintf(stderr, "error: "
504                                                         "expected argument after '--dump-function'\n");
505                                                 argument_errors = true;
506                                                 break;
507                                         }
508                                         dumpfunction = argv[i];
509                                         mode         = CompileDump;
510                                 } else {
511                                         fprintf(stderr, "error: unknown argument '%s'\n", arg);
512                                         argument_errors = true;
513                                 }
514                         } else {
515                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
516                                 argument_errors = true;
517                         }
518                 } else {
519                         if(input != NULL) {
520                                 fprintf(stderr, "error: multiple input files specified\n");
521                                 argument_errors = true;
522                         } else {
523                                 input = arg;
524                         }
525                 }
526         }
527
528         /* we do the lowering in ast2firm */
529         firm_opt.lower_bitfields = FALSE;
530
531         if(help_displayed) {
532                 return !argument_errors;
533         }
534         if(argument_errors) {
535                 usage(argv[0]);
536                 return 1;
537         }
538
539         gen_firm_init();
540         init_symbol_table();
541         init_tokens();
542         init_types();
543         init_typehash();
544         init_basic_types();
545         init_lexer();
546         init_ast();
547         init_parser();
548         init_ast2firm();
549
550         FILE *out = NULL;
551         char  outnamebuf[4096];
552         if(outname == NULL) {
553                 switch(mode) {
554                 case PrintAst:
555                 case PrintFluffy:
556                 case LexTest:
557                         if(outname == NULL)
558                                 outname = "-";
559                         break;
560                 case ParseOnly:
561                         break;
562                 case Compile:
563                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
564                         outname = outnamebuf;
565                         break;
566                 case CompileAssemble:
567                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
568                         outname = outnamebuf;
569                         break;
570                 case CompileDump:
571                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
572                                         ".vcg");
573                         outname = outnamebuf;
574                         break;
575                 case CompileAssembleLink:
576                         outname = "a.out";
577                         break;
578                 }
579         }
580
581         if(outname != NULL) {
582                 if(strcmp(outname, "-") == 0) {
583                         out = stdout;
584                 } else {
585                         out = fopen(outname, "w");
586                         if(out == NULL) {
587                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
588                                         strerror(errno));
589                                 return 1;
590                         }
591                 }
592         }
593
594         FILE *in;
595         if(input == NULL) {
596                 fprintf(stderr, "%s: no input files\n", argv[0]);
597                 return 1;
598         } else if(strcmp(input, "-") == 0) {
599                 in    = stdin;
600                 input = "<stdin>";
601         } else {
602                 in = fopen(input, "r");
603                 if(in == NULL) {
604                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
605                         return 1;
606                 }
607         }
608
609         if(mode == LexTest) {
610                 lextest(in, input);
611                 fclose(in);
612                 return 0;
613         }
614
615         FILE *preprocessed_in = preprocess(in, input);
616         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
617         int result = pclose(preprocessed_in);
618         if(result != 0) {
619                 return result;
620         }
621         if(unit == NULL) {
622                 /* parsing failed because of errors */
623                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
624                 return EXIT_FAILURE;
625         }
626         if (warning_count > 0) {
627                 fprintf(stderr, "%u warning(s)\n", warning_count);
628         }
629
630         if(mode == PrintAst) {
631                 type_set_output(out);
632                 ast_set_output(out);
633                 print_ast(unit);
634                 return 0;
635         }
636         if(mode == PrintFluffy) {
637                 type_set_output(out);
638                 ast_set_output(out);
639                 write_fluffy_decls(out, unit);
640         }
641
642         translation_unit_to_firm(unit);
643
644         if(mode == ParseOnly) {
645                 return 0;
646         }
647
648         FILE *asm_out;
649         char  asm_tempfile[1024];
650         if(mode == CompileDump) {
651                 asm_out = NULL;
652                 firm_be_opt.selection = BE_NONE;
653         } else if(mode == Compile) {
654                 asm_out = out;
655         } else {
656                 asm_out
657                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
658         }
659         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
660
661         if(mode == CompileDump) {
662                 /* find irg */
663                 ident    *id     = new_id_from_str(dumpfunction);
664                 ir_graph *irg    = NULL;
665                 int       n_irgs = get_irp_n_irgs();
666                 for(int i = 0; i < n_irgs; ++i) {
667                         ir_graph *tirg   = get_irp_irg(i);
668                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
669                         if(irg_id == id) {
670                                 irg = tirg;
671                                 break;
672                         }
673                 }
674
675                 if(irg == NULL) {
676                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
677                         return 1;
678                 }
679
680                 dump_ir_block_graph_file(irg, out);
681                 fclose(out);
682                 return 0;
683         }
684
685         fclose(asm_out);
686
687         /* assemble assembler and create object file */
688         char obj_tfile[1024];
689         if(mode == CompileAssemble || mode == CompileAssembleLink) {
690                 const char *obj_outfile;
691                 if(mode == CompileAssemble) {
692                         fclose(out);
693                         obj_outfile = outname;
694                 } else {
695                         FILE *tempf
696                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
697                         fclose(tempf);
698                         obj_outfile = obj_tfile;
699                 }
700
701                 assemble(obj_outfile, asm_tempfile);
702         }
703
704         /* link object file */
705         if(mode == CompileAssembleLink) {
706                 do_link(outname, obj_tfile);
707         }
708
709         obstack_free(&cppflags_obst, NULL);
710         obstack_free(&ldflags_obst, NULL);
711
712         exit_ast2firm();
713         exit_parser();
714         exit_ast();
715         exit_lexer();
716         exit_typehash();
717         exit_types();
718         exit_tokens();
719         exit_symbol_table();
720         return 0;
721 }