[PATCH] remove long-dead variable in evaluate_ptr_add()
[smatch.git] / lib.c
blob4856b65fef46357200d9a59cb5af809ab21f3061
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 static 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 = 1;
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;
207 int Wold_initializer = 1;
208 int Wnon_pointer_null = 1;
209 int Wparen_string = 0;
211 int dbg_entry = 0;
212 int dbg_dead = 0;
214 int preprocess_only;
216 #define CMDLINE_INCLUDE 20
217 int cmdline_include_nr = 0;
218 struct cmdline_include cmdline_include[CMDLINE_INCLUDE];
221 void add_pre_buffer(const char *fmt, ...)
223 va_list args;
224 unsigned int size;
226 va_start(args, fmt);
227 size = pre_buffer_size;
228 size += vsnprintf(pre_buffer + size,
229 sizeof(pre_buffer) - size,
230 fmt, args);
231 pre_buffer_size = size;
232 va_end(args);
235 static char **handle_switch_D(char *arg, char **next)
237 const char *name = arg + 1;
238 const char *value = "1";
239 for (;;) {
240 char c;
241 c = *++arg;
242 if (!c)
243 break;
244 if (isspace((unsigned char)c) || c == '=') {
245 *arg = '\0';
246 value = arg + 1;
247 break;
250 add_pre_buffer("#define %s %s\n", name, value);
251 return next;
254 static char **handle_switch_E(char *arg, char **next)
256 if (arg[1] == '\0')
257 preprocess_only = 1;
258 return next;
261 static char **handle_switch_I(char *arg, char **next)
263 char *path = arg+1;
265 switch (arg[1]) {
266 case '-':
267 add_pre_buffer("#split_include\n");
268 break;
270 case '\0': /* Plain "-I" */
271 path = *++next;
272 if (!path)
273 die("missing argument for -I option");
274 /* Fall through */
275 default:
276 add_pre_buffer("#add_include \"%s/\"\n", path);
278 return next;
281 static void add_cmdline_include(char *filename)
283 int fd = open(filename, O_RDONLY);
284 if (fd < 0) {
285 perror(filename);
286 return;
288 if (cmdline_include_nr >= CMDLINE_INCLUDE)
289 die("too many include files for %s\n", filename);
290 cmdline_include[cmdline_include_nr].filename = filename;
291 cmdline_include[cmdline_include_nr].fd = fd;
292 cmdline_include_nr++;
295 static char **handle_switch_i(char *arg, char **next)
297 if (*next && !strcmp(arg, "include"))
298 add_cmdline_include(*++next);
299 else if (*next && !strcmp(arg, "imacros"))
300 add_cmdline_include(*++next);
301 else if (*next && !strcmp(arg, "isystem")) {
302 char *path = *++next;
303 if (!path)
304 die("missing argument for -isystem option");
305 add_pre_buffer("#add_isystem \"%s/\"\n", path);
307 return next;
310 static char **handle_switch_M(char *arg, char **next)
312 if (!strcmp(arg, "MF") || !strcmp(arg,"MQ") || !strcmp(arg,"MT")) {
313 if (!*next)
314 die("missing argument for -%s option", arg);
315 return next + 1;
317 return next;
320 static char **handle_switch_m(char *arg, char **next)
322 if (!strcmp(arg, "m64")) {
323 bits_in_long = 64;
324 max_int_alignment = 8;
325 bits_in_pointer = 64;
326 pointer_alignment = 8;
328 return next;
331 static char **handle_switch_o(char *arg, char **next)
333 if (!strcmp (arg, "o") && *next)
334 return next + 1; // "-o foo"
335 else
336 return next; // "-ofoo" or (bogus) terminal "-o"
339 static const struct warning {
340 const char *name;
341 int *flag;
342 } warnings[] = {
343 { "cast-to-as", &Wcast_to_address_space },
344 { "decl", &Wdecl },
345 { "one-bit-signed-bitfield", &Wone_bit_signed_bitfield },
346 { "cast-truncate", &Wcast_truncate },
347 { "ptr-subtraction-blows", &Wptr_subtraction_blows },
348 { "default-bitfield-sign", &Wdefault_bitfield_sign },
349 { "undef", &Wundefined_preprocessor },
350 { "bitwise", &Wbitwise },
351 { "typesign", &Wtypesign },
352 { "context", &Wcontext },
353 { "transparent-union", &Wtransparent_union },
354 { "shadow", &Wshadow },
355 { "address-space", &Waddress_space },
356 { "enum-mismatch", &Wenum_mismatch },
357 { "do-while", &Wdo_while },
358 { "uninitialized", &Wuninitialized },
359 { "old-initializer", &Wold_initializer },
360 { "non-pointer-null", &Wnon_pointer_null },
361 { "paren-string", &Wparen_string },
364 enum {
365 WARNING_OFF,
366 WARNING_ON,
367 WARNING_FORCE_OFF
371 static char **handle_onoff_switch(char *arg, char **next, const struct warning warnings[], int n)
373 int flag = WARNING_ON;
374 char *p = arg + 1;
375 unsigned i;
377 if (!strcmp(p, "all")) {
378 for (i = 0; i < n; i++) {
379 if (*warnings[i].flag != WARNING_FORCE_OFF)
380 *warnings[i].flag = WARNING_ON;
384 // Prefixes "no" and "no-" mean to turn warning off.
385 if (p[0] == 'n' && p[1] == 'o') {
386 p += 2;
387 if (p[0] == '-')
388 p++;
389 flag = WARNING_FORCE_OFF;
392 for (i = 0; i < n; i++) {
393 if (!strcmp(p,warnings[i].name)) {
394 *warnings[i].flag = flag;
395 return next;
399 // Unknown.
400 return NULL;
403 static char **handle_switch_W(char *arg, char **next)
405 char ** ret = handle_onoff_switch(arg, next, warnings, sizeof warnings/sizeof warnings[0]);
406 if (ret)
407 return ret;
409 // Unknown.
410 return next;
413 static struct warning debugs[] = {
414 { "entry", &dbg_entry},
415 { "dead", &dbg_dead},
419 static char **handle_switch_v(char *arg, char **next)
421 char ** ret = handle_onoff_switch(arg, next, debugs, sizeof debugs/sizeof debugs[0]);
422 if (ret)
423 return ret;
425 // Unknown.
426 do {
427 verbose++;
428 } while (*++arg == 'v');
429 return next;
433 static void handle_onoff_switch_finalize(const struct warning warnings[], int n)
435 unsigned i;
437 for (i = 0; i < n; i++) {
438 if (*warnings[i].flag == WARNING_FORCE_OFF)
439 *warnings[i].flag = WARNING_OFF;
443 static void handle_switch_W_finalize(void)
445 handle_onoff_switch_finalize(warnings, sizeof(warnings) / sizeof(warnings[0]));
448 static void handle_switch_v_finalize(void)
450 handle_onoff_switch_finalize(debugs, sizeof(debugs) / sizeof(debugs[0]));
453 static char **handle_switch_U(char *arg, char **next)
455 const char *name = arg + 1;
456 add_pre_buffer ("#undef %s\n", name);
457 return next;
460 static char **handle_switch_O(char *arg, char **next)
462 int level = 1;
463 if (arg[1] >= '0' && arg[1] <= '9')
464 level = arg[1] - '0';
465 optimize = level;
466 optimize_size = arg[1] == 's';
467 return next;
470 static char **handle_switch_f(char *arg, char **next)
472 int flag = 1;
474 arg++;
475 if (!strncmp(arg, "no-", 3)) {
476 flag = 0;
477 arg += 3;
479 /* handle switch here.. */
480 return next;
483 static char **handle_switch_G(char *arg, char **next)
485 if (!strcmp (arg, "G") && *next)
486 return next + 1; // "-G 0"
487 else
488 return next; // "-G0" or (bogus) terminal "-G"
491 static char **handle_nostdinc(char *arg, char **next)
493 add_pre_buffer("#nostdinc\n");
494 return next;
497 static char **handle_dirafter(char *arg, char **next)
499 char *path = *++next;
500 if (!path)
501 die("missing argument for -dirafter option");
502 add_pre_buffer("#add_dirafter \"%s/\"\n", path);
503 return next;
506 struct switches {
507 const char *name;
508 char **(*fn)(char *, char **);
511 char **handle_switch(char *arg, char **next)
513 static struct switches cmd[] = {
514 { "nostdinc", handle_nostdinc },
515 { "dirafter", handle_dirafter },
516 { NULL, NULL }
518 struct switches *s;
520 switch (*arg) {
521 case 'D': return handle_switch_D(arg, next);
522 case 'E': return handle_switch_E(arg, next);
523 case 'I': return handle_switch_I(arg, next);
524 case 'i': return handle_switch_i(arg, next);
525 case 'M': return handle_switch_M(arg, next);
526 case 'm': return handle_switch_m(arg, next);
527 case 'o': return handle_switch_o(arg, next);
528 case 'U': return handle_switch_U(arg, next);
529 case 'v': return handle_switch_v(arg, next);
530 case 'W': return handle_switch_W(arg, next);
531 case 'O': return handle_switch_O(arg, next);
532 case 'f': return handle_switch_f(arg, next);
533 case 'G': return handle_switch_G(arg, next);
534 default:
535 break;
538 s = cmd;
539 while (s->name) {
540 if (!strcmp(s->name, arg))
541 return s->fn(arg, next);
542 s++;
546 * Ignore unknown command line options:
547 * they're probably gcc switches
549 return next;
552 void declare_builtin_functions(void)
554 /* Gaah. gcc knows tons of builtin <string.h> functions */
555 add_pre_buffer("extern void *__builtin_memcpy(void *, const void *, __SIZE_TYPE__);\n");
556 add_pre_buffer("extern void *__builtin_memset(void *, int, __SIZE_TYPE__);\n");
557 add_pre_buffer("extern int __builtin_memcmp(const void *, const void *, __SIZE_TYPE__);\n");
558 add_pre_buffer("extern char *__builtin_strcat(char *, const char *);\n");
559 add_pre_buffer("extern char *__builtin_strncat(char *, const char *, __SIZE_TYPE__);\n");
560 add_pre_buffer("extern int __builtin_strcmp(const char *, const char *);\n");
561 add_pre_buffer("extern char *__builtin_strchr(const char *, int);\n");
562 add_pre_buffer("extern char *__builtin_strcpy(char *, const char *);\n");
563 add_pre_buffer("extern char *__builtin_strncpy(char *, const char *, __SIZE_TYPE__);\n");
564 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strspn(const char *, const char *);\n");
565 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strcspn(const char *, const char *);\n");
566 add_pre_buffer("extern char * __builtin_strpbrk(const char *, const char *);\n");
568 /* And some random ones.. */
569 add_pre_buffer("extern void *__builtin_return_address(unsigned int);\n");
570 add_pre_buffer("extern void *__builtin_extract_return_addr(void *);\n");
571 add_pre_buffer("extern void *__builtin_frame_address(unsigned int);\n");
572 add_pre_buffer("extern void __builtin_trap(void);\n");
573 add_pre_buffer("extern int __builtin_ffs(int);\n");
574 add_pre_buffer("extern void *__builtin_alloca(__SIZE_TYPE__);\n");
575 add_pre_buffer("extern int __builtin_popcount(unsigned int);\n");
576 add_pre_buffer("extern int __builtin_popcountl(unsigned long);\n");
577 add_pre_buffer("extern void __builtin_prefetch (const void *, ...);\n");
578 add_pre_buffer("extern long __builtin_alpha_extbl(long, long);\n");
579 add_pre_buffer("extern long __builtin_alpha_extwl(long, long);\n");
580 add_pre_buffer("extern long __builtin_alpha_insbl(long, long);\n");
581 add_pre_buffer("extern long __builtin_alpha_inswl(long, long);\n");
582 add_pre_buffer("extern long __builtin_alpha_insql(long, long);\n");
583 add_pre_buffer("extern long __builtin_alpha_inslh(long, long);\n");
584 add_pre_buffer("extern long __builtin_alpha_cmpbge(long, long);\n");
587 void create_builtin_stream(void)
589 add_pre_buffer("#weak_define __GNUC__ %d\n", gcc_major);
590 add_pre_buffer("#weak_define __GNUC_MINOR__ %d\n", gcc_minor);
591 add_pre_buffer("#weak_define __GNUC_PATCHLEVEL__ %d\n", gcc_patchlevel);
592 add_pre_buffer("#define __extension__\n");
593 add_pre_buffer("#define __pragma__\n");
595 // gcc defines __SIZE_TYPE__ to be size_t. For linux/i86 and
596 // solaris/sparc that is really "unsigned int" and for linux/x86_64
597 // it is "long unsigned int". In either case we can probably
598 // get away with this. We need the #weak_define as cgcc will define
599 // the right __SIZE_TYPE__.
600 add_pre_buffer("#weak_define __SIZE_TYPE__ long unsigned int\n");
601 add_pre_buffer("#weak_define __STDC__ 1\n");
603 add_pre_buffer("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
604 add_pre_buffer("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
605 add_pre_buffer("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n");
606 add_pre_buffer("#define __builtin_va_alist (*(void *)0)\n");
607 add_pre_buffer("#define __builtin_va_arg_incr(x) ((x) + 1)\n");
608 add_pre_buffer("#define __builtin_va_copy(dest, src) ({ dest = src; (void)0; })\n");
609 add_pre_buffer("#define __builtin_va_end(arg)\n");
610 add_pre_buffer("#define __builtin_offsetof(type, name) ((__SIZE_TYPE__)&((type *)(0ul))->name)\n");
612 /* FIXME! We need to do these as special magic macros at expansion time! */
613 add_pre_buffer("#define __BASE_FILE__ \"base_file.c\"\n");
615 if (optimize)
616 add_pre_buffer("#define __OPTIMIZE__ 1\n");
617 if (optimize_size)
618 add_pre_buffer("#define __OPTIMIZE_SIZE__ 1\n");
621 static struct symbol_list *sparse_tokenstream(struct token *token)
623 // Preprocess the stream
624 token = preprocess(token);
626 if (preprocess_only) {
627 while (!eof_token(token)) {
628 int prec = 1;
629 struct token *next = token->next;
630 const char *separator = "";
631 if (next->pos.whitespace)
632 separator = " ";
633 if (next->pos.newline) {
634 separator = "\n\t\t\t\t\t";
635 prec = next->pos.pos;
636 if (prec > 4)
637 prec = 4;
639 printf("%s%.*s", show_token(token), prec, separator);
640 token = next;
642 putchar('\n');
644 return NULL;
647 // Parse the resulting C code
648 while (!eof_token(token))
649 token = external_declaration(token, &translation_unit_used_list);
650 return translation_unit_used_list;
653 static struct symbol_list *sparse_file(const char *filename)
655 int fd;
656 struct token *token;
658 if (strcmp (filename, "-") == 0) {
659 fd = 0;
660 } else {
661 fd = open(filename, O_RDONLY);
662 if (fd < 0)
663 die("No such file: %s", filename);
666 // Tokenize the input stream
667 token = tokenize(filename, fd, NULL, includepath);
668 close(fd);
670 return sparse_tokenstream(token);
674 * This handles the "-include" directive etc: we're in global
675 * scope, and all types/macros etc will affect all the following
676 * files.
678 * NOTE NOTE NOTE! "#undef" of anything in this stage will
679 * affect all subsequent files too, i.e. we can have non-local
680 * behaviour between files!
682 static struct symbol_list *sparse_initial(void)
684 struct token *token;
685 int i;
687 // Prepend any "include" file to the stream.
688 // We're in global scope, it will affect all files!
689 token = NULL;
690 for (i = cmdline_include_nr - 1; i >= 0; i--)
691 token = tokenize(cmdline_include[i].filename, cmdline_include[i].fd,
692 token, includepath);
694 // Prepend the initial built-in stream
695 token = tokenize_buffer(pre_buffer, pre_buffer_size, token);
696 return sparse_tokenstream(token);
699 struct symbol_list *sparse_initialize(int argc, char **argv, struct string_list **filelist)
701 char **args;
702 struct symbol_list *list;
704 // Initialize symbol stream first, so that we can add defines etc
705 init_symbols();
707 args = argv;
708 for (;;) {
709 char *arg = *++args;
710 if (!arg)
711 break;
713 if (arg[0] == '-' && arg[1]) {
714 args = handle_switch(arg+1, args);
715 continue;
717 add_ptr_list_notag(filelist, arg);
719 handle_switch_W_finalize();
720 handle_switch_v_finalize();
722 list = NULL;
723 if (!ptr_list_empty(filelist)) {
724 // Initialize type system
725 init_ctype();
727 create_builtin_stream();
728 add_pre_buffer("#define __CHECKER__ 1\n");
729 if (!preprocess_only)
730 declare_builtin_functions();
732 list = sparse_initial();
735 * Protect the initial token allocations, since
736 * they need to survive all the others
738 protect_token_alloc();
740 return list;
743 struct symbol_list * __sparse(char *filename)
745 struct symbol_list *res;
747 /* Clear previous symbol list */
748 translation_unit_used_list = NULL;
750 new_file_scope();
751 res = sparse_file(filename);
753 /* Drop the tokens for this file after parsing */
754 clear_token_alloc();
756 /* And return it */
757 return res;
760 struct symbol_list * sparse(char *filename)
762 struct symbol_list *res = __sparse(filename);
764 /* Evaluate the complete symbol list */
765 evaluate_symbol_list(res);
767 return res;