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