Make 'cgcc' work at least half-way better
[smatch.git] / lib.c
blobdb4ffd47c9a063868acc5ea36fccfe53faa6bb23
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;
33 #ifndef __GNUC__
34 # define __GNUC__ 2
35 # define __GNUC_MINOR__ 95
36 #endif
38 int gcc_major = __GNUC__;
39 int gcc_minor = __GNUC_MINOR__;
41 struct token *skip_to(struct token *token, int op)
43 while (!match_op(token, op) && !eof_token(token))
44 token = token->next;
45 return token;
48 struct token *expect(struct token *token, int op, const char *where)
50 if (!match_op(token, op)) {
51 static struct token bad_token;
52 if (token != &bad_token) {
53 bad_token.next = token;
54 warning(token->pos, "Expected %s %s", show_special(op), where);
55 warning(token->pos, "got %s", show_token(token));
57 if (op == ';')
58 return skip_to(token, op);
59 return &bad_token;
61 return token->next;
64 unsigned int hexval(unsigned int c)
66 int retval = 256;
67 switch (c) {
68 case '0'...'9':
69 retval = c - '0';
70 break;
71 case 'a'...'f':
72 retval = c - 'a' + 10;
73 break;
74 case 'A'...'F':
75 retval = c - 'A' + 10;
76 break;
78 return retval;
81 static void do_warn(const char *type, struct position pos, const char * fmt, va_list args)
83 static char buffer[512];
84 const char *name;
86 vsprintf(buffer, fmt, args);
87 name = stream_name(pos.stream);
89 fprintf(stderr, "%s:%d:%d: %s%s\n",
90 name, pos.line, pos.pos, type, buffer);
93 static int max_warnings = 100;
95 void info(struct position pos, const char * fmt, ...)
97 va_list args;
99 if (!max_warnings)
100 return;
101 va_start(args, fmt);
102 do_warn("", pos, fmt, args);
103 va_end(args);
106 void warning(struct position pos, const char * fmt, ...)
108 va_list args;
110 if (!max_warnings)
111 return;
113 if (!--max_warnings)
114 fmt = "too many warnings";
116 va_start(args, fmt);
117 do_warn("warning: ", pos, fmt, args);
118 va_end(args);
121 void error(struct position pos, const char * fmt, ...)
123 static int errors = 0;
124 va_list args;
126 /* Shut up warnings after an error */
127 max_warnings = 0;
128 if (errors > 100) {
129 static int once = 0;
130 if (once)
131 return;
132 fmt = "too many errors";
133 once = 1;
136 va_start(args, fmt);
137 do_warn("error: ", pos, fmt, args);
138 va_end(args);
139 errors++;
142 void error_die(struct position pos, const char * fmt, ...)
144 va_list args;
145 va_start(args, fmt);
146 do_warn("error: ", pos, fmt, args);
147 va_end(args);
148 exit(1);
151 void die(const char *fmt, ...)
153 va_list args;
154 static char buffer[512];
156 va_start(args, fmt);
157 vsnprintf(buffer, sizeof(buffer), fmt, args);
158 va_end(args);
160 fprintf(stderr, "%s\n", buffer);
161 exit(1);
164 static unsigned int pre_buffer_size;
165 static char pre_buffer[8192];
167 int Wdefault_bitfield_sign = 0;
168 int Wbitwise = 0;
169 int Wtypesign = 0;
170 int Wcontext = 0;
171 int Wundefined_preprocessor = 0;
172 int Wptr_subtraction_blows = 0;
173 int Wtransparent_union = 1;
174 int preprocess_only;
175 char *include;
176 int include_fd = -1;
178 void add_pre_buffer(const char *fmt, ...)
180 va_list args;
181 unsigned int size;
183 va_start(args, fmt);
184 size = pre_buffer_size;
185 size += vsnprintf(pre_buffer + size,
186 sizeof(pre_buffer) - size,
187 fmt, args);
188 pre_buffer_size = size;
189 va_end(args);
192 static char **handle_switch_D(char *arg, char **next)
194 const char *name = arg + 1;
195 const char *value = "1";
196 for (;;) {
197 char c;
198 c = *++arg;
199 if (!c)
200 break;
201 if (isspace((unsigned char)c) || c == '=') {
202 *arg = '\0';
203 value = arg + 1;
204 break;
207 add_pre_buffer("#define %s %s\n", name, value);
208 return next;
211 static char **handle_switch_E(char *arg, char **next)
213 preprocess_only = 1;
214 return next;
217 static char **handle_switch_v(char *arg, char **next)
219 do {
220 verbose++;
221 } while (*++arg == 'v');
222 return next;
225 static char **handle_switch_I(char *arg, char **next)
227 char *path = arg+1;
229 switch (arg[1]) {
230 case '-':
231 add_pre_buffer("#split_include\n");
232 break;
234 case '\0': /* Plain "-I" */
235 path = *++next;
236 if (!path)
237 die("missing argument for -I option");
238 /* Fallthrough */
239 default:
240 add_pre_buffer("#add_include \"%s/\"\n", path);
242 return next;
245 static char **handle_switch_i(char *arg, char **next)
247 if (*next && !strcmp(arg, "include")) {
248 char *name = *++next;
249 int fd = open(name, O_RDONLY);
251 include_fd = fd;
252 include = name;
253 if (fd < 0)
254 perror(name);
256 else if (*next && !strcmp(arg, "isystem")) {
257 char *path = *++next;
258 if (!path)
259 die("missing argument for -isystem option");
260 add_pre_buffer("#add_isystem \"%s/\"\n", path);
262 return next;
265 static char **handle_switch_M(char *arg, char **next)
267 if (!strcmp(arg, "MF") || !strcmp(arg,"MQ") || !strcmp(arg,"MT")) {
268 if (!*next)
269 die("missing argument for -%s option", arg);
270 return next + 1;
272 return next;
275 static char **handle_switch_m(char *arg, char **next)
277 if (!strcmp(arg, "m64")) {
278 bits_in_long = 64;
279 max_int_alignment = 8;
280 bits_in_pointer = 64;
281 pointer_alignment = 8;
283 return next;
286 static char **handle_switch_o(char *arg, char **next)
288 if (!strcmp (arg, "o") && *next)
289 return next + 1; // "-o foo"
290 else
291 return next; // "-ofoo" or (bogus) terminal "-o"
294 static const struct warning {
295 const char *name;
296 int *flag;
297 } warnings[] = {
298 { "ptr-subtraction-blows", &Wptr_subtraction_blows },
299 { "default-bitfield-sign", &Wdefault_bitfield_sign },
300 { "undef", &Wundefined_preprocessor },
301 { "bitwise", &Wbitwise },
302 { "typesign", &Wtypesign },
303 { "context", &Wcontext },
304 { "transparent-union", &Wtransparent_union },
308 static char **handle_switch_W(char *arg, char **next)
310 int no = 0;
311 char *p = arg + 1;
312 unsigned i;
314 // Prefixes "no" and "no-" mean to turn warning off.
315 if (p[0] == 'n' && p[1] == 'o') {
316 p += 2;
317 if (p[0] == '-')
318 p++;
319 no = 1;
322 for (i = 0; i < sizeof(warnings) / sizeof(warnings[0]); i++) {
323 if (!strcmp(p,warnings[i].name)) {
324 *warnings[i].flag = !no;
325 return next;
329 // Unknown.
330 return next;
333 static char **handle_switch_U(char *arg, char **next)
335 const char *name = arg + 1;
336 add_pre_buffer ("#undef %s\n", name);
337 return next;
340 static char **handle_switch_O(char *arg, char **next)
342 int level = 1;
343 if (arg[1] >= '0' && arg[1] <= '9')
344 level = arg[1] - '0';
345 optimize = level;
346 optimize_size = arg[1] == 's';
347 return next;
350 static char **handle_switch_f(char *arg, char **next)
352 int flag = 1;
354 arg++;
355 if (!strncmp(arg, "no-", 3)) {
356 flag = 0;
357 arg += 3;
359 /* handle switch here.. */
360 return next;
363 static char **handle_nostdinc(char *arg, char **next)
365 add_pre_buffer("#nostdinc\n");
366 return next;
369 static char **handle_dirafter(char *arg, char **next)
371 char *path = *++next;
372 if (!path)
373 die("missing argument for -dirafter option");
374 add_pre_buffer("#add_dirafter \"%s/\"\n", path);
375 return next;
378 struct switches {
379 const char *name;
380 char **(*fn)(char *, char**);
383 char **handle_switch(char *arg, char **next)
385 static struct switches cmd[] = {
386 { "nostdinc", handle_nostdinc },
387 { "dirafter", handle_dirafter },
388 { NULL, NULL }
390 struct switches *s;
392 switch (*arg) {
393 case 'D': return handle_switch_D(arg, next);
394 case 'E': return handle_switch_E(arg, next);
395 case 'I': return handle_switch_I(arg, next);
396 case 'i': return handle_switch_i(arg, next);
397 case 'M': return handle_switch_M(arg, next);
398 case 'm': return handle_switch_m(arg, next);
399 case 'o': return handle_switch_o(arg, next);
400 case 'U': return handle_switch_U(arg, next);
401 case 'v': return handle_switch_v(arg, next);
402 case 'W': return handle_switch_W(arg, next);
403 case 'O': return handle_switch_O(arg, next);
404 case 'f': return handle_switch_f(arg, next);
405 default:
406 break;
409 s = cmd;
410 while (s->name) {
411 if (!strcmp(s->name, arg))
412 return s->fn(arg, next);
413 s++;
417 * Ignore unknown command line options:
418 * they're probably gcc switches
420 return next;
423 void declare_builtin_functions(void)
425 add_pre_buffer("extern void *__builtin_memcpy(void *, const void *, __SIZE_TYPE__);\n");
426 add_pre_buffer("extern void *__builtin_return_address(unsigned int);\n");
427 add_pre_buffer("extern void *__builtin_frame_address(unsigned int);\n");
428 add_pre_buffer("extern void *__builtin_memset(void *, int, __SIZE_TYPE__);\n");
429 add_pre_buffer("extern void __builtin_trap(void);\n");
430 add_pre_buffer("extern int __builtin_ffs(int);\n");
431 add_pre_buffer("extern void *__builtin_alloca(__SIZE_TYPE__);\n");
434 void create_builtin_stream(void)
436 add_pre_buffer("#define __GNUC__ %d\n", gcc_major);
437 add_pre_buffer("#define __GNUC_MINOR__ %d\n", gcc_minor);
438 add_pre_buffer("#define __extension__\n");
439 add_pre_buffer("#define __pragma__\n");
441 // gcc defines __SIZE_TYPE__ to be size_t. For linux/i86 and
442 // solaris/sparc that is really "unsigned int" and for linux/x86_64
443 // it is "long unsigned int". In either case we can probably
444 // get away with this. We need the #ifndef as cgcc will define
445 // the right __SIZE_TYPE__.
446 add_pre_buffer("#weak_define __SIZE_TYPE__ long unsigned int\n");
447 add_pre_buffer("#weak_define __STDC__ 1\n");
449 add_pre_buffer("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
450 add_pre_buffer("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n");
451 add_pre_buffer("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n");
452 add_pre_buffer("#define __builtin_va_alist (*(void *)0)\n");
453 add_pre_buffer("#define __builtin_va_arg_incr(x) ((x) + 1)\n");
454 add_pre_buffer("#define __builtin_va_end(arg)\n");
455 add_pre_buffer("#define __builtin_offsetof(type, name) ((__SIZE_TYPE__)&((type *)(0ul))->name)\n");
457 /* FIXME! We need to do these as special magic macros at expansion time! */
458 add_pre_buffer("#define __BASE_FILE__ \"base_file.c\"\n");
459 add_pre_buffer("#define __DATE__ \"??? ?? ????\"\n");
460 add_pre_buffer("#define __TIME__ \"??:??:??\"\n");
462 if (optimize)
463 add_pre_buffer("#define __OPTIMIZE__\n");
464 if (optimize_size)
465 add_pre_buffer("#define __OPTIMIZE_SIZE__\n");
468 static struct symbol_list *sparse_tokenstream(struct token *token)
470 // Pre-process the stream
471 token = preprocess(token);
473 if (preprocess_only) {
474 while (!eof_token(token)) {
475 int prec = 1;
476 struct token *next = token->next;
477 const char *separator = "";
478 if (next->pos.whitespace)
479 separator = " ";
480 if (next->pos.newline) {
481 separator = "\n\t\t\t\t\t";
482 prec = next->pos.pos;
483 if (prec > 4)
484 prec = 4;
486 printf("%s%.*s", show_token(token), prec, separator);
487 token = next;
489 putchar('\n');
491 return NULL;
494 // Parse the resulting C code
495 while (!eof_token(token))
496 token = external_declaration(token, &translation_unit_used_list);
497 return translation_unit_used_list;
500 static struct symbol_list *sparse_file(const char *filename)
502 int fd;
503 struct token *token;
505 if (strcmp (filename, "-") == 0) {
506 fd = 0;
507 } else {
508 fd = open(filename, O_RDONLY);
509 if (fd < 0)
510 die("No such file: %s", filename);
513 // Tokenize the input stream
514 token = tokenize(filename, fd, NULL, includepath);
515 close(fd);
517 return sparse_tokenstream(token);
521 * This handles the "-include" directive etc: we're in global
522 * scope, and all types/macros etc will affect all the following
523 * files.
525 * NOTE NOTE NOTE! "#undef" of anything in this stage will
526 * affect all subsequent files too, ie we can have non-local
527 * behaviour between files!
529 static void sparse_initial(void)
531 struct token *token;
533 // Prepend any "include" file to the stream.
534 // We're in global scope, it will affect all files!
535 token = NULL;
536 if (include_fd >= 0)
537 token = tokenize(include, include_fd, NULL, includepath);
539 // Prepend the initial built-in stream
540 token = tokenize_buffer(pre_buffer, pre_buffer_size, token);
541 sparse_tokenstream(token);
544 int sparse_initialize(int argc, char **argv)
546 char **args;
547 int files = 0;
549 // Initialize symbol stream first, so that we can add defines etc
550 init_symbols();
552 args = argv;
553 for (;;) {
554 char *arg = *++args;
555 if (!arg)
556 break;
558 if (arg[0] == '-' && arg[1]) {
559 args = handle_switch(arg+1, args);
560 continue;
564 * Hacky hacky hacky: we re-use the argument space
565 * to save the filenames.
567 argv[files++] = arg;
570 argv[files] = NULL;
571 if (files) {
572 // Initialize type system
573 init_ctype();
575 create_builtin_stream();
576 add_pre_buffer("#define __CHECKER__ 1\n");
577 if (!preprocess_only)
578 declare_builtin_functions();
580 sparse_initial();
583 * Protect the initial token allocations, since
584 * they need to survive all the others
586 protect_token_alloc();
588 return files;
591 struct symbol_list * sparse(char **argv)
593 struct symbol_list *res;
594 char *filename, *next;
596 /* Clear previous symbol list */
597 translation_unit_used_list = NULL;
599 filename = *argv;
600 if (!filename)
601 return NULL;
602 do {
603 next = argv[1];
604 *argv++ = next;
605 } while (next);
607 start_file_scope();
608 res = sparse_file(filename);
609 end_file_scope();
611 /* Drop the tokens for this file after parsing */
612 clear_token_alloc();
614 /* Evaluate the complete symbol list */
615 evaluate_symbol_list(res);
617 /* And return it */
618 return res;