Fix typo in symbol.h: s/keywrods/keywords/
[smatch.git] / lib.c
blob42d47f0f1263b455997ae0612ab7a522240412a3
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 = 0;
209 int dbg_dead = 0;
211 int preprocess_only;
212 char *include;
214 #define CMDLINE_INCLUDE 20
215 int cmdline_include_nr = 0;
216 struct cmdline_include cmdline_include[CMDLINE_INCLUDE];
219 void add_pre_buffer(const char *fmt, ...)
221 va_list args;
222 unsigned int size;
224 va_start(args, fmt);
225 size = pre_buffer_size;
226 size += vsnprintf(pre_buffer + size,
227 sizeof(pre_buffer) - size,
228 fmt, args);
229 pre_buffer_size = size;
230 va_end(args);
233 static char **handle_switch_D(char *arg, char **next)
235 const char *name = arg + 1;
236 const char *value = "1";
237 for (;;) {
238 char c;
239 c = *++arg;
240 if (!c)
241 break;
242 if (isspace((unsigned char)c) || c == '=') {
243 *arg = '\0';
244 value = arg + 1;
245 break;
248 add_pre_buffer("#define %s %s\n", name, value);
249 return next;
252 static char **handle_switch_E(char *arg, char **next)
254 preprocess_only = 1;
255 return next;
258 static char **handle_switch_I(char *arg, char **next)
260 char *path = arg+1;
262 switch (arg[1]) {
263 case '-':
264 add_pre_buffer("#split_include\n");
265 break;
267 case '\0': /* Plain "-I" */
268 path = *++next;
269 if (!path)
270 die("missing argument for -I option");
271 /* Fallthrough */
272 default:
273 add_pre_buffer("#add_include \"%s/\"\n", path);
275 return next;
278 static void add_cmdline_include(char *filename)
280 int fd = open(filename, O_RDONLY);
281 if (fd < 0) {
282 perror(filename);
283 return;
285 if (cmdline_include_nr >= CMDLINE_INCLUDE)
286 die("too many include files for %s\n", filename);
287 cmdline_include[cmdline_include_nr].filename = filename;
288 cmdline_include[cmdline_include_nr].fd = fd;
289 cmdline_include_nr++;
292 static char **handle_switch_i(char *arg, char **next)
294 if (*next && !strcmp(arg, "include"))
295 add_cmdline_include(*++next);
296 else if (*next && !strcmp(arg, "imacros"))
297 add_cmdline_include(*++next);
298 else if (*next && !strcmp(arg, "isystem")) {
299 char *path = *++next;
300 if (!path)
301 die("missing argument for -isystem option");
302 add_pre_buffer("#add_isystem \"%s/\"\n", path);
304 return next;
307 static char **handle_switch_M(char *arg, char **next)
309 if (!strcmp(arg, "MF") || !strcmp(arg,"MQ") || !strcmp(arg,"MT")) {
310 if (!*next)
311 die("missing argument for -%s option", arg);
312 return next + 1;
314 return next;
317 static char **handle_switch_m(char *arg, char **next)
319 if (!strcmp(arg, "m64")) {
320 bits_in_long = 64;
321 max_int_alignment = 8;
322 bits_in_pointer = 64;
323 pointer_alignment = 8;
325 return next;
328 static char **handle_switch_o(char *arg, char **next)
330 if (!strcmp (arg, "o") && *next)
331 return next + 1; // "-o foo"
332 else
333 return next; // "-ofoo" or (bogus) terminal "-o"
336 static const struct warning {
337 const char *name;
338 int *flag;
339 } warnings[] = {
340 { "cast-to-as", &Wcast_to_address_space },
341 { "decl", &Wdecl },
342 { "one-bit-signed-bitfield", &Wone_bit_signed_bitfield },
343 { "cast-truncate", &Wcast_truncate },
344 { "ptr-subtraction-blows", &Wptr_subtraction_blows },
345 { "default-bitfield-sign", &Wdefault_bitfield_sign },
346 { "undef", &Wundefined_preprocessor },
347 { "bitwise", &Wbitwise },
348 { "typesign", &Wtypesign },
349 { "context", &Wcontext },
350 { "transparent-union", &Wtransparent_union },
351 { "shadow", &Wshadow },
352 { "address-space", &Waddress_space },
353 { "enum-mismatch", &Wenum_mismatch },
354 { "do-while", &Wdo_while },
355 { "uninitialized", &Wuninitialized },
358 enum {
359 WARNING_OFF,
360 WARNING_ON,
361 WARNING_FORCE_OFF
365 static char **handle_onoff_switch(char *arg, char **next, const struct warning warnings[], int n)
367 int flag = WARNING_ON;
368 char *p = arg + 1;
369 unsigned i;
371 if (!strcmp(p, "all")) {
372 for (i = 0; i < n; i++) {
373 if (*warnings[i].flag != WARNING_FORCE_OFF)
374 *warnings[i].flag = WARNING_ON;
378 // Prefixes "no" and "no-" mean to turn warning off.
379 if (p[0] == 'n' && p[1] == 'o') {
380 p += 2;
381 if (p[0] == '-')
382 p++;
383 flag = WARNING_FORCE_OFF;
386 for (i = 0; i < n; i++) {
387 if (!strcmp(p,warnings[i].name)) {
388 *warnings[i].flag = flag;
389 return next;
393 // Unknown.
394 return NULL;
397 static char **handle_switch_W(char *arg, char **next)
399 char ** ret = handle_onoff_switch(arg, next, warnings, sizeof warnings/sizeof warnings[0]);
400 if (ret)
401 return ret;
403 // Unknown.
404 return next;
407 static struct warning debugs[] = {
408 { "entry", &dbg_entry},
409 { "dead", &dbg_dead},
413 static char **handle_switch_v(char *arg, char **next)
415 char ** ret = handle_onoff_switch(arg, next, debugs, sizeof debugs/sizeof debugs[0]);
416 if (ret)
417 return ret;
419 // Unknown.
420 do {
421 verbose++;
422 } while (*++arg == 'v');
423 return next;
427 static void handle_onoff_switch_finalize(const struct warning warnings[], int n)
429 unsigned i;
431 for (i = 0; i < n; i++) {
432 if (*warnings[i].flag == WARNING_FORCE_OFF)
433 *warnings[i].flag = WARNING_OFF;
437 static void handle_switch_W_finalize(void)
439 handle_onoff_switch_finalize(warnings, sizeof(warnings) / sizeof(warnings[0]));
442 static void handle_switch_v_finalize(void)
444 handle_onoff_switch_finalize(debugs, sizeof(debugs) / sizeof(debugs[0]));
447 static char **handle_switch_U(char *arg, char **next)
449 const char *name = arg + 1;
450 add_pre_buffer ("#undef %s\n", name);
451 return next;
454 static char **handle_switch_O(char *arg, char **next)
456 int level = 1;
457 if (arg[1] >= '0' && arg[1] <= '9')
458 level = arg[1] - '0';
459 optimize = level;
460 optimize_size = arg[1] == 's';
461 return next;
464 static char **handle_switch_f(char *arg, char **next)
466 int flag = 1;
468 arg++;
469 if (!strncmp(arg, "no-", 3)) {
470 flag = 0;
471 arg += 3;
473 /* handle switch here.. */
474 return next;
477 static char **handle_switch_G(char *arg, char **next)
479 if (!strcmp (arg, "G") && *next)
480 return next + 1; // "-G 0"
481 else
482 return next; // "-G0" or (bogus) terminal "-G"
485 static char **handle_nostdinc(char *arg, char **next)
487 add_pre_buffer("#nostdinc\n");
488 return next;
491 static char **handle_dirafter(char *arg, char **next)
493 char *path = *++next;
494 if (!path)
495 die("missing argument for -dirafter option");
496 add_pre_buffer("#add_dirafter \"%s/\"\n", path);
497 return next;
500 struct switches {
501 const char *name;
502 char **(*fn)(char *, char **);
505 char **handle_switch(char *arg, char **next)
507 static struct switches cmd[] = {
508 { "nostdinc", handle_nostdinc },
509 { "dirafter", handle_dirafter },
510 { NULL, NULL }
512 struct switches *s;
514 switch (*arg) {
515 case 'D': return handle_switch_D(arg, next);
516 case 'E': return handle_switch_E(arg, next);
517 case 'I': return handle_switch_I(arg, next);
518 case 'i': return handle_switch_i(arg, next);
519 case 'M': return handle_switch_M(arg, next);
520 case 'm': return handle_switch_m(arg, next);
521 case 'o': return handle_switch_o(arg, next);
522 case 'U': return handle_switch_U(arg, next);
523 case 'v': return handle_switch_v(arg, next);
524 case 'W': return handle_switch_W(arg, next);
525 case 'O': return handle_switch_O(arg, next);
526 case 'f': return handle_switch_f(arg, next);
527 case 'G': return handle_switch_G(arg, next);
528 default:
529 break;
532 s = cmd;
533 while (s->name) {
534 if (!strcmp(s->name, arg))
535 return s->fn(arg, next);
536 s++;
540 * Ignore unknown command line options:
541 * they're probably gcc switches
543 return next;
546 void declare_builtin_functions(void)
548 /* Gaah. gcc knows tons of builtin <string.h> functions */
549 add_pre_buffer("extern void *__builtin_memcpy(void *, const void *, __SIZE_TYPE__);\n");
550 add_pre_buffer("extern void *__builtin_memset(void *, int, __SIZE_TYPE__);\n");
551 add_pre_buffer("extern int __builtin_memcmp(const void *, const void *, __SIZE_TYPE__);\n");
552 add_pre_buffer("extern int __builtin_strcmp(const char *, const char *);\n");
553 add_pre_buffer("extern char *__builtin_strchr(const char *, int);\n");
554 add_pre_buffer("extern char *__builtin_strcpy(char *, const char *);\n");
555 add_pre_buffer("extern char *__builtin_strncpy(char *, const char *, __SIZE_TYPE__);\n");
556 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strspn(const char *, const char *);\n");
557 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strcspn(const char *, const char *);\n");
558 add_pre_buffer("extern char * __builtin_strpbrk(const char *, const char *);\n");
560 /* And some random ones.. */
561 add_pre_buffer("extern void *__builtin_return_address(unsigned int);\n");
562 add_pre_buffer("extern void *__builtin_extract_return_addr(void *);\n");
563 add_pre_buffer("extern void *__builtin_frame_address(unsigned int);\n");
564 add_pre_buffer("extern void __builtin_trap(void);\n");
565 add_pre_buffer("extern int __builtin_ffs(int);\n");
566 add_pre_buffer("extern void *__builtin_alloca(__SIZE_TYPE__);\n");
567 add_pre_buffer("extern int __builtin_popcount(unsigned int);\n");
568 add_pre_buffer("extern int __builtin_popcountl(unsigned long);\n");
569 add_pre_buffer("extern void __builtin_prefetch (const void *, ...);\n");
570 add_pre_buffer("extern long __builtin_alpha_extbl(long, long);\n");
571 add_pre_buffer("extern long __builtin_alpha_extwl(long, long);\n");
572 add_pre_buffer("extern long __builtin_alpha_insbl(long, long);\n");
573 add_pre_buffer("extern long __builtin_alpha_inswl(long, long);\n");
574 add_pre_buffer("extern long __builtin_alpha_insql(long, long);\n");
575 add_pre_buffer("extern long __builtin_alpha_inslh(long, long);\n");
576 add_pre_buffer("extern long __builtin_alpha_cmpbge(long, long);\n");
579 void create_builtin_stream(void)
581 add_pre_buffer("#weak_define __GNUC__ %d\n", gcc_major);
582 add_pre_buffer("#weak_define __GNUC_MINOR__ %d\n", gcc_minor);
583 add_pre_buffer("#weak_define __GNUC_PATCHLEVEL__ %d\n", gcc_patchlevel);
584 add_pre_buffer("#define __extension__\n");
585 add_pre_buffer("#define __pragma__\n");
587 // gcc defines __SIZE_TYPE__ to be size_t. For linux/i86 and
588 // solaris/sparc that is really "unsigned int" and for linux/x86_64
589 // it is "long unsigned int". In either case we can probably
590 // get away with this. We need the #ifndef as cgcc will define
591 // the right __SIZE_TYPE__.
592 add_pre_buffer("#weak_define __SIZE_TYPE__ long unsigned int\n");
593 add_pre_buffer("#weak_define __STDC__ 1\n");
595 add_pre_buffer("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
596 add_pre_buffer("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
597 add_pre_buffer("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n");
598 add_pre_buffer("#define __builtin_va_alist (*(void *)0)\n");
599 add_pre_buffer("#define __builtin_va_arg_incr(x) ((x) + 1)\n");
600 add_pre_buffer("#define __builtin_va_copy(dest, src) ({ dest = src; (void)0; })\n");
601 add_pre_buffer("#define __builtin_va_end(arg)\n");
602 add_pre_buffer("#define __builtin_offsetof(type, name) ((__SIZE_TYPE__)&((type *)(0ul))->name)\n");
604 /* FIXME! We need to do these as special magic macros at expansion time! */
605 add_pre_buffer("#define __BASE_FILE__ \"base_file.c\"\n");
606 add_pre_buffer("#define __DATE__ \"??? ?? ????\"\n");
607 add_pre_buffer("#define __TIME__ \"??:??:??\"\n");
609 if (optimize)
610 add_pre_buffer("#define __OPTIMIZE__ 1\n");
611 if (optimize_size)
612 add_pre_buffer("#define __OPTIMIZE_SIZE__ 1\n");
615 static struct symbol_list *sparse_tokenstream(struct token *token)
617 // Pre-process the stream
618 token = preprocess(token);
620 if (preprocess_only) {
621 while (!eof_token(token)) {
622 int prec = 1;
623 struct token *next = token->next;
624 const char *separator = "";
625 if (next->pos.whitespace)
626 separator = " ";
627 if (next->pos.newline) {
628 separator = "\n\t\t\t\t\t";
629 prec = next->pos.pos;
630 if (prec > 4)
631 prec = 4;
633 printf("%s%.*s", show_token(token), prec, separator);
634 token = next;
636 putchar('\n');
638 return NULL;
641 // Parse the resulting C code
642 while (!eof_token(token))
643 token = external_declaration(token, &translation_unit_used_list);
644 return translation_unit_used_list;
647 static struct symbol_list *sparse_file(const char *filename)
649 int fd;
650 struct token *token;
652 if (strcmp (filename, "-") == 0) {
653 fd = 0;
654 } else {
655 fd = open(filename, O_RDONLY);
656 if (fd < 0)
657 die("No such file: %s", filename);
660 // Tokenize the input stream
661 token = tokenize(filename, fd, NULL, includepath);
662 close(fd);
664 return sparse_tokenstream(token);
668 * This handles the "-include" directive etc: we're in global
669 * scope, and all types/macros etc will affect all the following
670 * files.
672 * NOTE NOTE NOTE! "#undef" of anything in this stage will
673 * affect all subsequent files too, ie we can have non-local
674 * behaviour between files!
676 static struct symbol_list *sparse_initial(void)
678 struct token *token;
679 int i;
681 // Prepend any "include" file to the stream.
682 // We're in global scope, it will affect all files!
683 token = NULL;
684 for (i = cmdline_include_nr - 1; i >= 0; i--)
685 token = tokenize(cmdline_include[i].filename, cmdline_include[i].fd,
686 token, includepath);
688 // Prepend the initial built-in stream
689 token = tokenize_buffer(pre_buffer, pre_buffer_size, token);
690 return sparse_tokenstream(token);
693 struct symbol_list *sparse_initialize(int argc, char **argv, struct string_list **filelist)
695 char **args;
696 struct symbol_list *list;
698 // Initialize symbol stream first, so that we can add defines etc
699 init_symbols();
701 args = argv;
702 for (;;) {
703 char *arg = *++args;
704 if (!arg)
705 break;
707 if (arg[0] == '-' && arg[1]) {
708 args = handle_switch(arg+1, args);
709 continue;
711 add_ptr_list_notag(filelist, arg);
713 handle_switch_W_finalize();
714 handle_switch_v_finalize();
716 list = NULL;
717 if (!ptr_list_empty(filelist)) {
718 // Initialize type system
719 init_ctype();
721 create_builtin_stream();
722 add_pre_buffer("#define __CHECKER__ 1\n");
723 if (!preprocess_only)
724 declare_builtin_functions();
726 list = sparse_initial();
729 * Protect the initial token allocations, since
730 * they need to survive all the others
732 protect_token_alloc();
734 return list;
737 struct symbol_list * __sparse(char *filename)
739 struct symbol_list *res;
741 /* Clear previous symbol list */
742 translation_unit_used_list = NULL;
744 new_file_scope();
745 res = sparse_file(filename);
747 /* Drop the tokens for this file after parsing */
748 clear_token_alloc();
750 /* And return it */
751 return res;
754 struct symbol_list * sparse(char *filename)
756 struct symbol_list *res = __sparse(filename);
758 /* Evaluate the complete symbol list */
759 evaluate_symbol_list(res);
761 return res;