Introduce expression_error
[smatch.git] / lib.c
blobcdc71954a1376b9d0268b4880bfcd45c2d54d1a7
1 /*
2 * 'sparse' library helper routines.
4 * Copyright (C) 2003 Transmeta Corp.
5 * 2003-2004 Linus Torvalds
7 * Licensed under the Open Software License version 1.1
8 */
9 #include <ctype.h>
10 #include <fcntl.h>
11 #include <stdarg.h>
12 #include <stddef.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <assert.h>
19 #include <sys/types.h>
21 #include "lib.h"
22 #include "allocate.h"
23 #include "token.h"
24 #include "parse.h"
25 #include "symbol.h"
26 #include "expression.h"
27 #include "scope.h"
28 #include "linearize.h"
29 #include "target.h"
31 int verbose, optimize, optimize_size, preprocessing;
32 int die_if_error = 0;
34 #ifndef __GNUC__
35 # define __GNUC__ 2
36 # define __GNUC_MINOR__ 95
37 # define __GNUC_PATCHLEVEL__ 0
38 #endif
40 int gcc_major = __GNUC__;
41 int gcc_minor = __GNUC_MINOR__;
42 int gcc_patchlevel = __GNUC_PATCHLEVEL__;
44 struct token *skip_to(struct token *token, int op)
46 while (!match_op(token, op) && !eof_token(token))
47 token = token->next;
48 return token;
51 struct token *expect(struct token *token, int op, const char *where)
53 if (!match_op(token, op)) {
54 static struct token bad_token;
55 if (token != &bad_token) {
56 bad_token.next = token;
57 sparse_error(token->pos, "Expected %s %s", show_special(op), where);
58 sparse_error(token->pos, "got %s", show_token(token));
60 if (op == ';')
61 return skip_to(token, op);
62 return &bad_token;
64 return token->next;
67 unsigned int hexval(unsigned int c)
69 int retval = 256;
70 switch (c) {
71 case '0'...'9':
72 retval = c - '0';
73 break;
74 case 'a'...'f':
75 retval = c - 'a' + 10;
76 break;
77 case 'A'...'F':
78 retval = c - 'A' + 10;
79 break;
81 return retval;
84 static void do_warn(const char *type, struct position pos, const char * fmt, va_list args)
86 static char buffer[512];
87 const char *name;
89 vsprintf(buffer, fmt, args);
90 name = stream_name(pos.stream);
92 fprintf(stderr, "%s:%d:%d: %s%s\n",
93 name, pos.line, pos.pos, type, buffer);
96 static int max_warnings = 100;
97 static int show_info = 1;
99 void info(struct position pos, const char * fmt, ...)
101 va_list args;
103 if (!show_info)
104 return;
105 va_start(args, fmt);
106 do_warn("", pos, fmt, args);
107 va_end(args);
110 void warning(struct position pos, const char * fmt, ...)
112 va_list args;
114 if (!max_warnings) {
115 show_info = 0;
116 return;
119 if (!--max_warnings) {
120 show_info = 0;
121 fmt = "too many warnings";
124 va_start(args, fmt);
125 do_warn("warning: ", pos, fmt, args);
126 va_end(args);
129 void do_error(struct position pos, const char * fmt, va_list args)
131 static int errors = 0;
132 die_if_error = 1;
133 show_info = 1;
134 /* Shut up warnings after an error */
135 max_warnings = 0;
136 if (errors > 100) {
137 static int once = 0;
138 show_info = 0;
139 if (once)
140 return;
141 fmt = "too many errors";
142 once = 1;
145 do_warn("error: ", pos, fmt, args);
146 errors++;
149 void sparse_error(struct position pos, const char * fmt, ...)
151 va_list args;
152 va_start(args, fmt);
153 do_error(pos, fmt, args);
154 va_end(args);
157 void expression_error(struct expression *expr, const char *fmt, ...)
159 va_list args;
160 va_start(args, fmt);
161 do_error(expr->pos, fmt, args);
162 va_end(args);
163 expr->ctype = &bad_ctype;
166 void error_die(struct position pos, const char * fmt, ...)
168 va_list args;
169 va_start(args, fmt);
170 do_warn("error: ", pos, fmt, args);
171 va_end(args);
172 exit(1);
175 void die(const char *fmt, ...)
177 va_list args;
178 static char buffer[512];
180 va_start(args, fmt);
181 vsnprintf(buffer, sizeof(buffer), fmt, args);
182 va_end(args);
184 fprintf(stderr, "%s\n", buffer);
185 exit(1);
188 static unsigned int pre_buffer_size;
189 static char pre_buffer[8192];
191 int Wdefault_bitfield_sign = 0;
192 int Wone_bit_signed_bitfield = 1;
193 int Wcast_truncate = 1;
194 int Wbitwise = 0;
195 int Wtypesign = 0;
196 int Wcontext = 1;
197 int Wundefined_preprocessor = 0;
198 int Wptr_subtraction_blows = 0;
199 int Wcast_to_address_space = 0;
200 int Wdecl = 0;
201 int Wtransparent_union = 1;
202 int Wshadow = 0;
203 int Waddress_space = 1;
204 int Wenum_mismatch = 1;
205 int Wdo_while = 1;
206 int Wuninitialized = 1;
208 int dbg_entry;
210 int preprocess_only;
211 char *include;
213 #define CMDLINE_INCLUDE 20
214 int cmdline_include_nr = 0;
215 struct cmdline_include cmdline_include[CMDLINE_INCLUDE];
218 void add_pre_buffer(const char *fmt, ...)
220 va_list args;
221 unsigned int size;
223 va_start(args, fmt);
224 size = pre_buffer_size;
225 size += vsnprintf(pre_buffer + size,
226 sizeof(pre_buffer) - size,
227 fmt, args);
228 pre_buffer_size = size;
229 va_end(args);
232 static char **handle_switch_D(char *arg, char **next)
234 const char *name = arg + 1;
235 const char *value = "1";
236 for (;;) {
237 char c;
238 c = *++arg;
239 if (!c)
240 break;
241 if (isspace((unsigned char)c) || c == '=') {
242 *arg = '\0';
243 value = arg + 1;
244 break;
247 add_pre_buffer("#define %s %s\n", name, value);
248 return next;
251 static char **handle_switch_E(char *arg, char **next)
253 preprocess_only = 1;
254 return next;
257 static char **handle_switch_I(char *arg, char **next)
259 char *path = arg+1;
261 switch (arg[1]) {
262 case '-':
263 add_pre_buffer("#split_include\n");
264 break;
266 case '\0': /* Plain "-I" */
267 path = *++next;
268 if (!path)
269 die("missing argument for -I option");
270 /* Fallthrough */
271 default:
272 add_pre_buffer("#add_include \"%s/\"\n", path);
274 return next;
277 static void add_cmdline_include(char *filename)
279 int fd = open(filename, O_RDONLY);
280 if (fd < 0) {
281 perror(filename);
282 return;
284 if (cmdline_include_nr >= CMDLINE_INCLUDE)
285 die("too many include files for %s\n", filename);
286 cmdline_include[cmdline_include_nr].filename = filename;
287 cmdline_include[cmdline_include_nr].fd = fd;
288 cmdline_include_nr++;
291 static char **handle_switch_i(char *arg, char **next)
293 if (*next && !strcmp(arg, "include"))
294 add_cmdline_include(*++next);
295 else if (*next && !strcmp(arg, "imacros"))
296 add_cmdline_include(*++next);
297 else if (*next && !strcmp(arg, "isystem")) {
298 char *path = *++next;
299 if (!path)
300 die("missing argument for -isystem option");
301 add_pre_buffer("#add_isystem \"%s/\"\n", path);
303 return next;
306 static char **handle_switch_M(char *arg, char **next)
308 if (!strcmp(arg, "MF") || !strcmp(arg,"MQ") || !strcmp(arg,"MT")) {
309 if (!*next)
310 die("missing argument for -%s option", arg);
311 return next + 1;
313 return next;
316 static char **handle_switch_m(char *arg, char **next)
318 if (!strcmp(arg, "m64")) {
319 bits_in_long = 64;
320 max_int_alignment = 8;
321 bits_in_pointer = 64;
322 pointer_alignment = 8;
324 return next;
327 static char **handle_switch_o(char *arg, char **next)
329 if (!strcmp (arg, "o") && *next)
330 return next + 1; // "-o foo"
331 else
332 return next; // "-ofoo" or (bogus) terminal "-o"
335 static const struct warning {
336 const char *name;
337 int *flag;
338 } warnings[] = {
339 { "cast-to-as", &Wcast_to_address_space },
340 { "decl", &Wdecl },
341 { "one-bit-signed-bitfield", &Wone_bit_signed_bitfield },
342 { "cast-truncate", &Wcast_truncate },
343 { "ptr-subtraction-blows", &Wptr_subtraction_blows },
344 { "default-bitfield-sign", &Wdefault_bitfield_sign },
345 { "undef", &Wundefined_preprocessor },
346 { "bitwise", &Wbitwise },
347 { "typesign", &Wtypesign },
348 { "context", &Wcontext },
349 { "transparent-union", &Wtransparent_union },
350 { "shadow", &Wshadow },
351 { "address-space", &Waddress_space },
352 { "enum-mismatch", &Wenum_mismatch },
353 { "do-while", &Wdo_while },
354 { "uninitialized", &Wuninitialized },
357 enum {
358 WARNING_OFF,
359 WARNING_ON,
360 WARNING_FORCE_OFF
364 static char **handle_onoff_switch(char *arg, char **next, const struct warning warnings[], int n)
366 int flag = WARNING_ON;
367 char *p = arg + 1;
368 unsigned i;
370 if (!strcmp(p, "all")) {
371 for (i = 0; i < n; i++) {
372 if (*warnings[i].flag != WARNING_FORCE_OFF)
373 *warnings[i].flag = WARNING_ON;
377 // Prefixes "no" and "no-" mean to turn warning off.
378 if (p[0] == 'n' && p[1] == 'o') {
379 p += 2;
380 if (p[0] == '-')
381 p++;
382 flag = WARNING_FORCE_OFF;
385 for (i = 0; i < n; i++) {
386 if (!strcmp(p,warnings[i].name)) {
387 *warnings[i].flag = flag;
388 return next;
392 // Unknown.
393 return NULL;
396 static char **handle_switch_W(char *arg, char **next)
398 char ** ret = handle_onoff_switch(arg, next, warnings, sizeof warnings/sizeof warnings[0]);
399 if (ret)
400 return ret;
402 // Unknown.
403 return next;
406 static struct warning debugs[] = {
407 { "entry", &dbg_entry},
411 static char **handle_switch_v(char *arg, char **next)
413 char ** ret = handle_onoff_switch(arg, next, debugs, sizeof debugs/sizeof debugs[0]);
414 if (ret)
415 return ret;
417 // Unknown.
418 do {
419 verbose++;
420 } while (*++arg == 'v');
421 return next;
425 static void handle_onoff_switch_finalize(const struct warning warnings[], int n)
427 unsigned i;
429 for (i = 0; i < n; i++) {
430 if (*warnings[i].flag == WARNING_FORCE_OFF)
431 *warnings[i].flag = WARNING_OFF;
435 static void handle_switch_W_finalize(void)
437 handle_onoff_switch_finalize(warnings, sizeof(warnings) / sizeof(warnings[0]));
440 static void handle_switch_v_finalize(void)
442 handle_onoff_switch_finalize(debugs, sizeof(debugs) / sizeof(debugs[0]));
445 static char **handle_switch_U(char *arg, char **next)
447 const char *name = arg + 1;
448 add_pre_buffer ("#undef %s\n", name);
449 return next;
452 static char **handle_switch_O(char *arg, char **next)
454 int level = 1;
455 if (arg[1] >= '0' && arg[1] <= '9')
456 level = arg[1] - '0';
457 optimize = level;
458 optimize_size = arg[1] == 's';
459 return next;
462 static char **handle_switch_f(char *arg, char **next)
464 int flag = 1;
466 arg++;
467 if (!strncmp(arg, "no-", 3)) {
468 flag = 0;
469 arg += 3;
471 /* handle switch here.. */
472 return next;
475 static char **handle_switch_G(char *arg, char **next)
477 if (!strcmp (arg, "G") && *next)
478 return next + 1; // "-G 0"
479 else
480 return next; // "-G0" or (bogus) terminal "-G"
483 static char **handle_nostdinc(char *arg, char **next)
485 add_pre_buffer("#nostdinc\n");
486 return next;
489 static char **handle_dirafter(char *arg, char **next)
491 char *path = *++next;
492 if (!path)
493 die("missing argument for -dirafter option");
494 add_pre_buffer("#add_dirafter \"%s/\"\n", path);
495 return next;
498 struct switches {
499 const char *name;
500 char **(*fn)(char *, char **);
503 char **handle_switch(char *arg, char **next)
505 static struct switches cmd[] = {
506 { "nostdinc", handle_nostdinc },
507 { "dirafter", handle_dirafter },
508 { NULL, NULL }
510 struct switches *s;
512 switch (*arg) {
513 case 'D': return handle_switch_D(arg, next);
514 case 'E': return handle_switch_E(arg, next);
515 case 'I': return handle_switch_I(arg, next);
516 case 'i': return handle_switch_i(arg, next);
517 case 'M': return handle_switch_M(arg, next);
518 case 'm': return handle_switch_m(arg, next);
519 case 'o': return handle_switch_o(arg, next);
520 case 'U': return handle_switch_U(arg, next);
521 case 'v': return handle_switch_v(arg, next);
522 case 'W': return handle_switch_W(arg, next);
523 case 'O': return handle_switch_O(arg, next);
524 case 'f': return handle_switch_f(arg, next);
525 case 'G': return handle_switch_G(arg, next);
526 default:
527 break;
530 s = cmd;
531 while (s->name) {
532 if (!strcmp(s->name, arg))
533 return s->fn(arg, next);
534 s++;
538 * Ignore unknown command line options:
539 * they're probably gcc switches
541 return next;
544 void declare_builtin_functions(void)
546 /* Gaah. gcc knows tons of builtin <string.h> functions */
547 add_pre_buffer("extern void *__builtin_memcpy(void *, const void *, __SIZE_TYPE__);\n");
548 add_pre_buffer("extern void *__builtin_memset(void *, int, __SIZE_TYPE__);\n");
549 add_pre_buffer("extern int __builtin_memcmp(const void *, const void *, __SIZE_TYPE__);\n");
550 add_pre_buffer("extern int __builtin_strcmp(const char *, const char *);\n");
551 add_pre_buffer("extern char *__builtin_strchr(const char *, int);\n");
552 add_pre_buffer("extern char *__builtin_strcpy(char *, const char *);\n");
553 add_pre_buffer("extern char *__builtin_strncpy(char *, const char *, __SIZE_TYPE__);\n");
554 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strspn(const char *, const char *);\n");
555 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strcspn(const char *, const char *);\n");
556 add_pre_buffer("extern char * __builtin_strpbrk(const char *, const char *);\n");
558 /* And some random ones.. */
559 add_pre_buffer("extern void *__builtin_return_address(unsigned int);\n");
560 add_pre_buffer("extern void *__builtin_extract_return_addr(void *);\n");
561 add_pre_buffer("extern void *__builtin_frame_address(unsigned int);\n");
562 add_pre_buffer("extern void __builtin_trap(void);\n");
563 add_pre_buffer("extern int __builtin_ffs(int);\n");
564 add_pre_buffer("extern void *__builtin_alloca(__SIZE_TYPE__);\n");
565 add_pre_buffer("extern int __builtin_popcount(unsigned int);\n");
566 add_pre_buffer("extern int __builtin_popcountl(unsigned long);\n");
567 add_pre_buffer("extern void __builtin_prefetch (const void *, ...);\n");
568 add_pre_buffer("extern long __builtin_alpha_extbl(long, long);\n");
569 add_pre_buffer("extern long __builtin_alpha_extwl(long, long);\n");
570 add_pre_buffer("extern long __builtin_alpha_insbl(long, long);\n");
571 add_pre_buffer("extern long __builtin_alpha_inswl(long, long);\n");
572 add_pre_buffer("extern long __builtin_alpha_insql(long, long);\n");
573 add_pre_buffer("extern long __builtin_alpha_inslh(long, long);\n");
574 add_pre_buffer("extern long __builtin_alpha_cmpbge(long, long);\n");
577 void create_builtin_stream(void)
579 add_pre_buffer("#weak_define __GNUC__ %d\n", gcc_major);
580 add_pre_buffer("#weak_define __GNUC_MINOR__ %d\n", gcc_minor);
581 add_pre_buffer("#weak_define __GNUC_PATCHLEVEL__ %d\n", gcc_patchlevel);
582 add_pre_buffer("#define __extension__\n");
583 add_pre_buffer("#define __pragma__\n");
585 // gcc defines __SIZE_TYPE__ to be size_t. For linux/i86 and
586 // solaris/sparc that is really "unsigned int" and for linux/x86_64
587 // it is "long unsigned int". In either case we can probably
588 // get away with this. We need the #ifndef as cgcc will define
589 // the right __SIZE_TYPE__.
590 add_pre_buffer("#weak_define __SIZE_TYPE__ long unsigned int\n");
591 add_pre_buffer("#weak_define __STDC__ 1\n");
593 add_pre_buffer("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
594 add_pre_buffer("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
595 add_pre_buffer("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n");
596 add_pre_buffer("#define __builtin_va_alist (*(void *)0)\n");
597 add_pre_buffer("#define __builtin_va_arg_incr(x) ((x) + 1)\n");
598 add_pre_buffer("#define __builtin_va_copy(dest, src) ({ dest = src; (void)0; })\n");
599 add_pre_buffer("#define __builtin_va_end(arg)\n");
600 add_pre_buffer("#define __builtin_offsetof(type, name) ((__SIZE_TYPE__)&((type *)(0ul))->name)\n");
602 /* FIXME! We need to do these as special magic macros at expansion time! */
603 add_pre_buffer("#define __BASE_FILE__ \"base_file.c\"\n");
604 add_pre_buffer("#define __DATE__ \"??? ?? ????\"\n");
605 add_pre_buffer("#define __TIME__ \"??:??:??\"\n");
607 if (optimize)
608 add_pre_buffer("#define __OPTIMIZE__ 1\n");
609 if (optimize_size)
610 add_pre_buffer("#define __OPTIMIZE_SIZE__ 1\n");
613 static struct symbol_list *sparse_tokenstream(struct token *token)
615 // Pre-process the stream
616 token = preprocess(token);
618 if (preprocess_only) {
619 while (!eof_token(token)) {
620 int prec = 1;
621 struct token *next = token->next;
622 const char *separator = "";
623 if (next->pos.whitespace)
624 separator = " ";
625 if (next->pos.newline) {
626 separator = "\n\t\t\t\t\t";
627 prec = next->pos.pos;
628 if (prec > 4)
629 prec = 4;
631 printf("%s%.*s", show_token(token), prec, separator);
632 token = next;
634 putchar('\n');
636 return NULL;
639 // Parse the resulting C code
640 while (!eof_token(token))
641 token = external_declaration(token, &translation_unit_used_list);
642 return translation_unit_used_list;
645 static struct symbol_list *sparse_file(const char *filename)
647 int fd;
648 struct token *token;
650 if (strcmp (filename, "-") == 0) {
651 fd = 0;
652 } else {
653 fd = open(filename, O_RDONLY);
654 if (fd < 0)
655 die("No such file: %s", filename);
658 // Tokenize the input stream
659 token = tokenize(filename, fd, NULL, includepath);
660 close(fd);
662 return sparse_tokenstream(token);
666 * This handles the "-include" directive etc: we're in global
667 * scope, and all types/macros etc will affect all the following
668 * files.
670 * NOTE NOTE NOTE! "#undef" of anything in this stage will
671 * affect all subsequent files too, ie we can have non-local
672 * behaviour between files!
674 static struct symbol_list *sparse_initial(void)
676 struct token *token;
677 int i;
679 // Prepend any "include" file to the stream.
680 // We're in global scope, it will affect all files!
681 token = NULL;
682 for (i = cmdline_include_nr - 1; i >= 0; i--)
683 token = tokenize(cmdline_include[i].filename, cmdline_include[i].fd,
684 token, includepath);
686 // Prepend the initial built-in stream
687 token = tokenize_buffer(pre_buffer, pre_buffer_size, token);
688 return sparse_tokenstream(token);
691 struct symbol_list *sparse_initialize(int argc, char **argv, struct string_list **filelist)
693 char **args;
694 struct symbol_list *list;
696 // Initialize symbol stream first, so that we can add defines etc
697 init_symbols();
699 args = argv;
700 for (;;) {
701 char *arg = *++args;
702 if (!arg)
703 break;
705 if (arg[0] == '-' && arg[1]) {
706 args = handle_switch(arg+1, args);
707 continue;
709 add_ptr_list_notag(filelist, arg);
711 handle_switch_W_finalize();
712 handle_switch_v_finalize();
714 list = NULL;
715 if (!ptr_list_empty(filelist)) {
716 // Initialize type system
717 init_ctype();
719 create_builtin_stream();
720 add_pre_buffer("#define __CHECKER__ 1\n");
721 if (!preprocess_only)
722 declare_builtin_functions();
724 list = sparse_initial();
727 * Protect the initial token allocations, since
728 * they need to survive all the others
730 protect_token_alloc();
732 return list;
735 struct symbol_list * __sparse(char *filename)
737 struct symbol_list *res;
739 /* Clear previous symbol list */
740 translation_unit_used_list = NULL;
742 new_file_scope();
743 res = sparse_file(filename);
745 /* Drop the tokens for this file after parsing */
746 clear_token_alloc();
748 /* And return it */
749 return res;
752 struct symbol_list * sparse(char *filename)
754 struct symbol_list *res = __sparse(filename);
756 /* Evaluate the complete symbol list */
757 evaluate_symbol_list(res);
759 return res;