Make sparse warn about initializers that initialize the same member twice
[smatch.git] / lib.c
blobcd46e03ecca68e44bc173b841e2016eff71b5fe0
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 sparse_error(struct position pos, const char * fmt, ...)
131 static int errors = 0;
132 va_list args;
133 die_if_error = 1;
134 show_info = 1;
135 /* Shut up warnings after an error */
136 max_warnings = 0;
137 if (errors > 100) {
138 static int once = 0;
139 show_info = 0;
140 if (once)
141 return;
142 fmt = "too many errors";
143 once = 1;
146 va_start(args, fmt);
147 do_warn("error: ", pos, fmt, args);
148 va_end(args);
149 errors++;
152 void error_die(struct position pos, const char * fmt, ...)
154 va_list args;
155 va_start(args, fmt);
156 do_warn("error: ", pos, fmt, args);
157 va_end(args);
158 exit(1);
161 void die(const char *fmt, ...)
163 va_list args;
164 static char buffer[512];
166 va_start(args, fmt);
167 vsnprintf(buffer, sizeof(buffer), fmt, args);
168 va_end(args);
170 fprintf(stderr, "%s\n", buffer);
171 exit(1);
174 static unsigned int pre_buffer_size;
175 static char pre_buffer[8192];
177 int Wdefault_bitfield_sign = 0;
178 int Wone_bit_signed_bitfield = 1;
179 int Wcast_truncate = 1;
180 int Wbitwise = 0;
181 int Wtypesign = 0;
182 int Wcontext = 0;
183 int Wundefined_preprocessor = 0;
184 int Wptr_subtraction_blows = 0;
185 int Wcast_to_address_space = 0;
186 int Wdecl = 0;
187 int Wtransparent_union = 1;
188 int Wshadow = 0;
189 int Waddress_space = 1;
190 int Wenum_mismatch = 1;
191 int preprocess_only;
192 char *include;
193 int include_fd = -1;
196 void add_pre_buffer(const char *fmt, ...)
198 va_list args;
199 unsigned int size;
201 va_start(args, fmt);
202 size = pre_buffer_size;
203 size += vsnprintf(pre_buffer + size,
204 sizeof(pre_buffer) - size,
205 fmt, args);
206 pre_buffer_size = size;
207 va_end(args);
210 static char **handle_switch_D(char *arg, char **next)
212 const char *name = arg + 1;
213 const char *value = "1";
214 for (;;) {
215 char c;
216 c = *++arg;
217 if (!c)
218 break;
219 if (isspace((unsigned char)c) || c == '=') {
220 *arg = '\0';
221 value = arg + 1;
222 break;
225 add_pre_buffer("#define %s %s\n", name, value);
226 return next;
229 static char **handle_switch_E(char *arg, char **next)
231 preprocess_only = 1;
232 return next;
235 static char **handle_switch_v(char *arg, char **next)
237 do {
238 verbose++;
239 } while (*++arg == 'v');
240 return next;
243 static char **handle_switch_I(char *arg, char **next)
245 char *path = arg+1;
247 switch (arg[1]) {
248 case '-':
249 add_pre_buffer("#split_include\n");
250 break;
252 case '\0': /* Plain "-I" */
253 path = *++next;
254 if (!path)
255 die("missing argument for -I option");
256 /* Fallthrough */
257 default:
258 add_pre_buffer("#add_include \"%s/\"\n", path);
260 return next;
263 static char **handle_switch_i(char *arg, char **next)
265 if (*next && !strcmp(arg, "include")) {
266 char *name = *++next;
267 int fd = open(name, O_RDONLY);
269 include_fd = fd;
270 include = name;
271 if (fd < 0)
272 perror(name);
274 if (*next && !strcmp(arg, "imacros")) {
275 char *name = *++next;
276 int fd = open(name, O_RDONLY);
278 include_fd = fd;
279 include = name;
280 if (fd < 0)
281 perror(name);
283 else if (*next && !strcmp(arg, "isystem")) {
284 char *path = *++next;
285 if (!path)
286 die("missing argument for -isystem option");
287 add_pre_buffer("#add_isystem \"%s/\"\n", path);
289 return next;
292 static char **handle_switch_M(char *arg, char **next)
294 if (!strcmp(arg, "MF") || !strcmp(arg,"MQ") || !strcmp(arg,"MT")) {
295 if (!*next)
296 die("missing argument for -%s option", arg);
297 return next + 1;
299 return next;
302 static char **handle_switch_m(char *arg, char **next)
304 if (!strcmp(arg, "m64")) {
305 bits_in_long = 64;
306 max_int_alignment = 8;
307 bits_in_pointer = 64;
308 pointer_alignment = 8;
310 return next;
313 static char **handle_switch_o(char *arg, char **next)
315 if (!strcmp (arg, "o") && *next)
316 return next + 1; // "-o foo"
317 else
318 return next; // "-ofoo" or (bogus) terminal "-o"
321 static const struct warning {
322 const char *name;
323 int *flag;
324 } warnings[] = {
325 { "cast-to-as", &Wcast_to_address_space },
326 { "decl", &Wdecl },
327 { "one-bit-signed-bitfield", &Wone_bit_signed_bitfield },
328 { "cast-truncate", &Wcast_truncate },
329 { "ptr-subtraction-blows", &Wptr_subtraction_blows },
330 { "default-bitfield-sign", &Wdefault_bitfield_sign },
331 { "undef", &Wundefined_preprocessor },
332 { "bitwise", &Wbitwise },
333 { "typesign", &Wtypesign },
334 { "context", &Wcontext },
335 { "transparent-union", &Wtransparent_union },
336 { "shadow", &Wshadow },
337 { "address-space", &Waddress_space },
338 { "enum-mismatch", &Wenum_mismatch },
342 static char **handle_switch_W(char *arg, char **next)
344 int no = 0;
345 char *p = arg + 1;
346 unsigned i;
348 // Prefixes "no" and "no-" mean to turn warning off.
349 if (p[0] == 'n' && p[1] == 'o') {
350 p += 2;
351 if (p[0] == '-')
352 p++;
353 no = 1;
356 for (i = 0; i < sizeof(warnings) / sizeof(warnings[0]); i++) {
357 if (!strcmp(p,warnings[i].name)) {
358 *warnings[i].flag = !no;
359 return next;
363 // Unknown.
364 return next;
367 static char **handle_switch_U(char *arg, char **next)
369 const char *name = arg + 1;
370 add_pre_buffer ("#undef %s\n", name);
371 return next;
374 static char **handle_switch_O(char *arg, char **next)
376 int level = 1;
377 if (arg[1] >= '0' && arg[1] <= '9')
378 level = arg[1] - '0';
379 optimize = level;
380 optimize_size = arg[1] == 's';
381 return next;
384 static char **handle_switch_f(char *arg, char **next)
386 int flag = 1;
388 arg++;
389 if (!strncmp(arg, "no-", 3)) {
390 flag = 0;
391 arg += 3;
393 /* handle switch here.. */
394 return next;
397 static char **handle_switch_G(char *arg, char **next)
399 if (!strcmp (arg, "G") && *next)
400 return next + 1; // "-G 0"
401 else
402 return next; // "-G0" or (bogus) terminal "-G"
405 static char **handle_nostdinc(char *arg, char **next)
407 add_pre_buffer("#nostdinc\n");
408 return next;
411 static char **handle_dirafter(char *arg, char **next)
413 char *path = *++next;
414 if (!path)
415 die("missing argument for -dirafter option");
416 add_pre_buffer("#add_dirafter \"%s/\"\n", path);
417 return next;
420 struct switches {
421 const char *name;
422 char **(*fn)(char *, char**);
425 char **handle_switch(char *arg, char **next)
427 static struct switches cmd[] = {
428 { "nostdinc", handle_nostdinc },
429 { "dirafter", handle_dirafter },
430 { NULL, NULL }
432 struct switches *s;
434 switch (*arg) {
435 case 'D': return handle_switch_D(arg, next);
436 case 'E': return handle_switch_E(arg, next);
437 case 'I': return handle_switch_I(arg, next);
438 case 'i': return handle_switch_i(arg, next);
439 case 'M': return handle_switch_M(arg, next);
440 case 'm': return handle_switch_m(arg, next);
441 case 'o': return handle_switch_o(arg, next);
442 case 'U': return handle_switch_U(arg, next);
443 case 'v': return handle_switch_v(arg, next);
444 case 'W': return handle_switch_W(arg, next);
445 case 'O': return handle_switch_O(arg, next);
446 case 'f': return handle_switch_f(arg, next);
447 case 'G': return handle_switch_G(arg, next);
448 default:
449 break;
452 s = cmd;
453 while (s->name) {
454 if (!strcmp(s->name, arg))
455 return s->fn(arg, next);
456 s++;
460 * Ignore unknown command line options:
461 * they're probably gcc switches
463 return next;
466 void declare_builtin_functions(void)
468 /* Gaah. gcc knows tons of builtin <string.h> functions */
469 add_pre_buffer("extern void *__builtin_memcpy(void *, const void *, __SIZE_TYPE__);\n");
470 add_pre_buffer("extern void *__builtin_memset(void *, int, __SIZE_TYPE__);\n");
471 add_pre_buffer("extern int __builtin_memcmp(const void *, const void *, __SIZE_TYPE__);\n");
472 add_pre_buffer("extern int __builtin_strcmp(const char *, const char *);\n");
473 add_pre_buffer("extern char *__builtin_strchr(const char *, int);\n");
474 add_pre_buffer("extern char *__builtin_strcpy(char *, const char *);\n");
475 add_pre_buffer("extern char *__builtin_strncpy(char *, const char *, __SIZE_TYPE__);\n");
476 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strspn(const char *, const char *);\n");
477 add_pre_buffer("extern __SIZE_TYPE__ __builtin_strcspn(const char *, const char *);\n");
479 /* And some random ones.. */
480 add_pre_buffer("extern void *__builtin_return_address(unsigned int);\n");
481 add_pre_buffer("extern void *__builtin_extract_return_addr(void *);\n");
482 add_pre_buffer("extern void *__builtin_frame_address(unsigned int);\n");
483 add_pre_buffer("extern void __builtin_trap(void);\n");
484 add_pre_buffer("extern int __builtin_ffs(int);\n");
485 add_pre_buffer("extern void *__builtin_alloca(__SIZE_TYPE__);\n");
488 void create_builtin_stream(void)
490 add_pre_buffer("#weak_define __GNUC__ %d\n", gcc_major);
491 add_pre_buffer("#weak_define __GNUC_MINOR__ %d\n", gcc_minor);
492 add_pre_buffer("#weak_define __GNUC_PATCHLEVEL__ %d\n", gcc_patchlevel);
493 add_pre_buffer("#define __extension__\n");
494 add_pre_buffer("#define __pragma__\n");
496 // gcc defines __SIZE_TYPE__ to be size_t. For linux/i86 and
497 // solaris/sparc that is really "unsigned int" and for linux/x86_64
498 // it is "long unsigned int". In either case we can probably
499 // get away with this. We need the #ifndef as cgcc will define
500 // the right __SIZE_TYPE__.
501 add_pre_buffer("#weak_define __SIZE_TYPE__ long unsigned int\n");
502 add_pre_buffer("#weak_define __STDC__ 1\n");
504 add_pre_buffer("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
505 add_pre_buffer("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
506 add_pre_buffer("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n");
507 add_pre_buffer("#define __builtin_va_alist (*(void *)0)\n");
508 add_pre_buffer("#define __builtin_va_arg_incr(x) ((x) + 1)\n");
509 add_pre_buffer("#define __builtin_va_copy(dest, src) ({ dest = src; (void)0; })\n");
510 add_pre_buffer("#define __builtin_va_end(arg)\n");
511 add_pre_buffer("#define __builtin_offsetof(type, name) ((__SIZE_TYPE__)&((type *)(0ul))->name)\n");
513 /* FIXME! We need to do these as special magic macros at expansion time! */
514 add_pre_buffer("#define __BASE_FILE__ \"base_file.c\"\n");
515 add_pre_buffer("#define __DATE__ \"??? ?? ????\"\n");
516 add_pre_buffer("#define __TIME__ \"??:??:??\"\n");
518 if (optimize)
519 add_pre_buffer("#define __OPTIMIZE__ 1\n");
520 if (optimize_size)
521 add_pre_buffer("#define __OPTIMIZE_SIZE__ 1\n");
524 static struct symbol_list *sparse_tokenstream(struct token *token)
526 // Pre-process the stream
527 token = preprocess(token);
529 if (preprocess_only) {
530 while (!eof_token(token)) {
531 int prec = 1;
532 struct token *next = token->next;
533 const char *separator = "";
534 if (next->pos.whitespace)
535 separator = " ";
536 if (next->pos.newline) {
537 separator = "\n\t\t\t\t\t";
538 prec = next->pos.pos;
539 if (prec > 4)
540 prec = 4;
542 printf("%s%.*s", show_token(token), prec, separator);
543 token = next;
545 putchar('\n');
547 return NULL;
550 // Parse the resulting C code
551 while (!eof_token(token))
552 token = external_declaration(token, &translation_unit_used_list);
553 return translation_unit_used_list;
556 static struct symbol_list *sparse_file(const char *filename)
558 int fd;
559 struct token *token;
561 if (strcmp (filename, "-") == 0) {
562 fd = 0;
563 } else {
564 fd = open(filename, O_RDONLY);
565 if (fd < 0)
566 die("No such file: %s", filename);
569 // Tokenize the input stream
570 token = tokenize(filename, fd, NULL, includepath);
571 close(fd);
573 return sparse_tokenstream(token);
577 * This handles the "-include" directive etc: we're in global
578 * scope, and all types/macros etc will affect all the following
579 * files.
581 * NOTE NOTE NOTE! "#undef" of anything in this stage will
582 * affect all subsequent files too, ie we can have non-local
583 * behaviour between files!
585 static struct symbol_list *sparse_initial(void)
587 struct token *token;
589 // Prepend any "include" file to the stream.
590 // We're in global scope, it will affect all files!
591 token = NULL;
592 if (include_fd >= 0)
593 token = tokenize(include, include_fd, NULL, includepath);
595 // Prepend the initial built-in stream
596 token = tokenize_buffer(pre_buffer, pre_buffer_size, token);
597 return sparse_tokenstream(token);
600 struct symbol_list *sparse_initialize(int argc, char **argv)
602 char **args;
603 int files = 0;
604 struct symbol_list *list;
606 // Initialize symbol stream first, so that we can add defines etc
607 init_symbols();
609 args = argv;
610 for (;;) {
611 char *arg = *++args;
612 if (!arg)
613 break;
615 if (arg[0] == '-' && arg[1]) {
616 args = handle_switch(arg+1, args);
617 continue;
621 * Hacky hacky hacky: we re-use the argument space
622 * to save the filenames.
624 argv[files++] = arg;
627 list = NULL;
628 argv[files] = NULL;
629 if (files) {
630 // Initialize type system
631 init_ctype();
633 create_builtin_stream();
634 add_pre_buffer("#define __CHECKER__ 1\n");
635 if (!preprocess_only)
636 declare_builtin_functions();
638 list = sparse_initial();
641 * Protect the initial token allocations, since
642 * they need to survive all the others
644 protect_token_alloc();
646 return list;
649 struct symbol_list * __sparse(char **argv)
651 struct symbol_list *res;
652 char *filename, *next;
654 /* Clear previous symbol list */
655 translation_unit_used_list = NULL;
657 filename = *argv;
658 if (!filename)
659 return NULL;
660 do {
661 next = argv[1];
662 *argv++ = next;
663 } while (next);
665 start_file_scope();
666 res = sparse_file(filename);
667 end_file_scope();
669 /* Drop the tokens for this file after parsing */
670 clear_token_alloc();
672 /* And return it */
673 return res;
676 struct symbol_list * sparse(char **argv)
678 struct symbol_list *res = __sparse(argv);
680 /* Evaluate the complete symbol list */
681 evaluate_symbol_list(res);
683 return res;