user_data2: if users can only specify a single value that's not a user rl
[smatch.git] / pre-process.c
blob197341c8b76b35114cda82047b2b579dfe9de0ce
1 /*
2 * Do C preprocessing, based on a token list gathered by
3 * the tokenizer.
5 * This may not be the smartest preprocessor on the planet.
7 * Copyright (C) 2003 Transmeta Corp.
8 * 2003-2004 Linus Torvalds
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stddef.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <time.h>
38 #include <dirent.h>
39 #include <sys/stat.h>
41 #include "lib.h"
42 #include "allocate.h"
43 #include "parse.h"
44 #include "token.h"
45 #include "symbol.h"
46 #include "expression.h"
47 #include "scope.h"
49 static int false_nesting = 0;
51 #define INCLUDEPATHS 300
52 const char *includepath[INCLUDEPATHS+1] = {
53 "",
54 "/usr/include",
55 "/usr/local/include",
56 NULL
59 static const char **quote_includepath = includepath;
60 static const char **angle_includepath = includepath + 1;
61 static const char **isys_includepath = includepath + 1;
62 static const char **sys_includepath = includepath + 1;
63 static const char **dirafter_includepath = includepath + 3;
65 #define dirty_stream(stream) \
66 do { \
67 if (!stream->dirty) { \
68 stream->dirty = 1; \
69 if (!stream->ifndef) \
70 stream->protect = NULL; \
71 } \
72 } while(0)
74 #define end_group(stream) \
75 do { \
76 if (stream->ifndef == stream->top_if) { \
77 stream->ifndef = NULL; \
78 if (!stream->dirty) \
79 stream->protect = NULL; \
80 else if (stream->protect) \
81 stream->dirty = 0; \
82 } \
83 } while(0)
85 #define nesting_error(stream) \
86 do { \
87 stream->dirty = 1; \
88 stream->ifndef = NULL; \
89 stream->protect = NULL; \
90 } while(0)
92 static struct token *alloc_token(struct position *pos)
94 struct token *token = __alloc_token(0);
96 token->pos.stream = pos->stream;
97 token->pos.line = pos->line;
98 token->pos.pos = pos->pos;
99 token->pos.whitespace = 1;
100 return token;
103 /* Expand symbol 'sym' at '*list' */
104 static int expand(struct token **, struct symbol *);
106 static void replace_with_string(struct token *token, const char *str)
108 int size = strlen(str) + 1;
109 struct string *s = __alloc_string(size);
111 s->length = size;
112 memcpy(s->data, str, size);
113 token_type(token) = TOKEN_STRING;
114 token->string = s;
117 static void replace_with_integer(struct token *token, unsigned int val)
119 char *buf = __alloc_bytes(11);
120 sprintf(buf, "%u", val);
121 token_type(token) = TOKEN_NUMBER;
122 token->number = buf;
125 static struct symbol *lookup_macro(struct ident *ident)
127 struct symbol *sym = lookup_symbol(ident, NS_MACRO | NS_UNDEF);
128 if (sym && sym->namespace != NS_MACRO)
129 sym = NULL;
130 return sym;
133 static int token_defined(struct token *token)
135 if (token_type(token) == TOKEN_IDENT) {
136 struct symbol *sym = lookup_macro(token->ident);
137 if (sym) {
138 sym->used_in = file_scope;
139 return 1;
141 return 0;
144 sparse_error(token->pos, "expected preprocessor identifier");
145 return 0;
148 static void replace_with_defined(struct token *token)
150 static const char *string[] = { "0", "1" };
151 int defined = token_defined(token);
153 token_type(token) = TOKEN_NUMBER;
154 token->number = string[defined];
157 static int expand_one_symbol(struct token **list)
159 struct token *token = *list;
160 struct symbol *sym;
161 static char buffer[12]; /* __DATE__: 3 + ' ' + 2 + ' ' + 4 + '\0' */
162 static time_t t = 0;
164 if (token->pos.noexpand)
165 return 1;
167 sym = lookup_macro(token->ident);
168 if (sym) {
169 store_macro_pos(token);
170 sym->used_in = file_scope;
171 return expand(list, sym);
173 if (token->ident == &__LINE___ident) {
174 replace_with_integer(token, token->pos.line);
175 } else if (token->ident == &__FILE___ident) {
176 replace_with_string(token, stream_name(token->pos.stream));
177 } else if (token->ident == &__DATE___ident) {
178 if (!t)
179 time(&t);
180 strftime(buffer, 12, "%b %e %Y", localtime(&t));
181 replace_with_string(token, buffer);
182 } else if (token->ident == &__TIME___ident) {
183 if (!t)
184 time(&t);
185 strftime(buffer, 9, "%T", localtime(&t));
186 replace_with_string(token, buffer);
188 return 1;
191 static inline struct token *scan_next(struct token **where)
193 struct token *token = *where;
194 if (token_type(token) != TOKEN_UNTAINT)
195 return token;
196 do {
197 token->ident->tainted = 0;
198 token = token->next;
199 } while (token_type(token) == TOKEN_UNTAINT);
200 *where = token;
201 return token;
204 static void expand_list(struct token **list)
206 struct token *next;
207 while (!eof_token(next = scan_next(list))) {
208 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
209 list = &next->next;
213 static void preprocessor_line(struct stream *stream, struct token **line);
215 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
217 struct stream *stream = input_streams + prev->pos.stream;
218 struct token **p = &prev->next;
219 struct token *next;
220 int nesting = 0;
222 while (!eof_token(next = scan_next(p))) {
223 if (next->pos.newline && match_op(next, '#')) {
224 if (!next->pos.noexpand) {
225 sparse_error(next->pos,
226 "directive in argument list");
227 preprocessor_line(stream, p);
228 __free_token(next); /* Free the '#' token */
229 continue;
232 switch (token_type(next)) {
233 case TOKEN_STREAMEND:
234 case TOKEN_STREAMBEGIN:
235 *p = &eof_token_entry;
236 return next;
238 if (false_nesting) {
239 *p = next->next;
240 __free_token(next);
241 continue;
243 if (match_op(next, '(')) {
244 nesting++;
245 } else if (match_op(next, ')')) {
246 if (!nesting--)
247 break;
248 } else if (match_op(next, ',') && !nesting && !vararg) {
249 break;
251 next->pos.stream = pos->stream;
252 next->pos.line = pos->line;
253 next->pos.pos = pos->pos;
254 p = &next->next;
256 *p = &eof_token_entry;
257 return next;
261 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
264 struct arg {
265 struct token *arg;
266 struct token *expanded;
267 struct token *str;
268 int n_normal;
269 int n_quoted;
270 int n_str;
273 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
275 int wanted = arglist->count.normal;
276 struct token *next = NULL;
277 int count = 0;
279 arglist = arglist->next; /* skip counter */
281 if (!wanted) {
282 next = collect_arg(start, 0, &what->pos);
283 if (eof_token(next))
284 goto Eclosing;
285 if (!eof_token(start->next) || !match_op(next, ')')) {
286 count++;
287 goto Emany;
289 } else {
290 for (count = 0; count < wanted; count++) {
291 struct argcount *p = &arglist->next->count;
292 next = collect_arg(start, p->vararg, &what->pos);
293 arglist = arglist->next->next;
294 if (eof_token(next))
295 goto Eclosing;
296 args[count].arg = start->next;
297 args[count].n_normal = p->normal;
298 args[count].n_quoted = p->quoted;
299 args[count].n_str = p->str;
300 if (match_op(next, ')')) {
301 count++;
302 break;
304 start = next;
306 if (count == wanted && !match_op(next, ')'))
307 goto Emany;
308 if (count == wanted - 1) {
309 struct argcount *p = &arglist->next->count;
310 if (!p->vararg)
311 goto Efew;
312 args[count].arg = NULL;
313 args[count].n_normal = p->normal;
314 args[count].n_quoted = p->quoted;
315 args[count].n_str = p->str;
317 if (count < wanted - 1)
318 goto Efew;
320 what->next = next->next;
321 return 1;
323 Efew:
324 sparse_error(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
325 show_token(what), wanted, count);
326 goto out;
327 Emany:
328 while (match_op(next, ',')) {
329 next = collect_arg(next, 0, &what->pos);
330 count++;
332 if (eof_token(next))
333 goto Eclosing;
334 sparse_error(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
335 show_token(what), count, wanted);
336 goto out;
337 Eclosing:
338 sparse_error(what->pos, "unterminated argument list invoking macro \"%s\"",
339 show_token(what));
340 out:
341 what->next = next->next;
342 return 0;
345 static struct token *dup_list(struct token *list)
347 struct token *res = NULL;
348 struct token **p = &res;
350 while (!eof_token(list)) {
351 struct token *newtok = __alloc_token(0);
352 *newtok = *list;
353 *p = newtok;
354 p = &newtok->next;
355 list = list->next;
357 return res;
360 static const char *show_token_sequence(struct token *token, int quote)
362 static char buffer[MAX_STRING];
363 char *ptr = buffer;
364 int whitespace = 0;
366 if (!token && !quote)
367 return "<none>";
368 while (!eof_token(token)) {
369 const char *val = quote ? quote_token(token) : show_token(token);
370 int len = strlen(val);
372 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
373 sparse_error(token->pos, "too long token expansion");
374 break;
377 if (whitespace)
378 *ptr++ = ' ';
379 memcpy(ptr, val, len);
380 ptr += len;
381 token = token->next;
382 whitespace = token->pos.whitespace;
384 *ptr = 0;
385 return buffer;
388 static struct token *stringify(struct token *arg)
390 const char *s = show_token_sequence(arg, 1);
391 int size = strlen(s)+1;
392 struct token *token = __alloc_token(0);
393 struct string *string = __alloc_string(size);
395 memcpy(string->data, s, size);
396 string->length = size;
397 token->pos = arg->pos;
398 token_type(token) = TOKEN_STRING;
399 token->string = string;
400 token->next = &eof_token_entry;
401 return token;
404 static void expand_arguments(int count, struct arg *args)
406 int i;
407 for (i = 0; i < count; i++) {
408 struct token *arg = args[i].arg;
409 if (!arg)
410 arg = &eof_token_entry;
411 if (args[i].n_str)
412 args[i].str = stringify(arg);
413 if (args[i].n_normal) {
414 if (!args[i].n_quoted) {
415 args[i].expanded = arg;
416 args[i].arg = NULL;
417 } else if (eof_token(arg)) {
418 args[i].expanded = arg;
419 } else {
420 args[i].expanded = dup_list(arg);
422 expand_list(&args[i].expanded);
428 * Possibly valid combinations:
429 * - ident + ident -> ident
430 * - ident + number -> ident unless number contains '.', '+' or '-'.
431 * - 'L' + char constant -> wide char constant
432 * - 'L' + string literal -> wide string literal
433 * - number + number -> number
434 * - number + ident -> number
435 * - number + '.' -> number
436 * - number + '+' or '-' -> number, if number used to end on [eEpP].
437 * - '.' + number -> number, if number used to start with a digit.
438 * - special + special -> either special or an error.
440 static enum token_type combine(struct token *left, struct token *right, char *p)
442 int len;
443 enum token_type t1 = token_type(left), t2 = token_type(right);
445 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
446 return TOKEN_ERROR;
448 if (t1 == TOKEN_IDENT && left->ident == &L_ident) {
449 if (t2 >= TOKEN_CHAR && t2 < TOKEN_WIDE_CHAR)
450 return t2 + TOKEN_WIDE_CHAR - TOKEN_CHAR;
451 if (t2 == TOKEN_STRING)
452 return TOKEN_WIDE_STRING;
455 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
456 return TOKEN_ERROR;
458 strcpy(p, show_token(left));
459 strcat(p, show_token(right));
460 len = strlen(p);
462 if (len >= 256)
463 return TOKEN_ERROR;
465 if (t1 == TOKEN_IDENT) {
466 if (t2 == TOKEN_SPECIAL)
467 return TOKEN_ERROR;
468 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
469 return TOKEN_ERROR;
470 return TOKEN_IDENT;
473 if (t1 == TOKEN_NUMBER) {
474 if (t2 == TOKEN_SPECIAL) {
475 switch (right->special) {
476 case '.':
477 break;
478 case '+': case '-':
479 if (strchr("eEpP", p[len - 2]))
480 break;
481 default:
482 return TOKEN_ERROR;
485 return TOKEN_NUMBER;
488 if (p[0] == '.' && isdigit((unsigned char)p[1]))
489 return TOKEN_NUMBER;
491 return TOKEN_SPECIAL;
494 static int merge(struct token *left, struct token *right)
496 static char buffer[512];
497 enum token_type res = combine(left, right, buffer);
498 int n;
500 switch (res) {
501 case TOKEN_IDENT:
502 left->ident = built_in_ident(buffer);
503 left->pos.noexpand = 0;
504 return 1;
506 case TOKEN_NUMBER: {
507 char *number = __alloc_bytes(strlen(buffer) + 1);
508 memcpy(number, buffer, strlen(buffer) + 1);
509 token_type(left) = TOKEN_NUMBER; /* could be . + num */
510 left->number = number;
511 return 1;
514 case TOKEN_SPECIAL:
515 if (buffer[2] && buffer[3])
516 break;
517 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
518 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
519 left->special = n;
520 return 1;
523 break;
525 case TOKEN_WIDE_CHAR:
526 case TOKEN_WIDE_STRING:
527 token_type(left) = res;
528 left->pos.noexpand = 0;
529 left->string = right->string;
530 return 1;
532 case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3:
533 token_type(left) = res;
534 left->pos.noexpand = 0;
535 memcpy(left->embedded, right->embedded, 4);
536 return 1;
538 default:
541 sparse_error(left->pos, "'##' failed: concatenation is not a valid token");
542 return 0;
545 static struct token *dup_token(struct token *token, struct position *streampos)
547 struct token *alloc = alloc_token(streampos);
548 token_type(alloc) = token_type(token);
549 alloc->pos.newline = token->pos.newline;
550 alloc->pos.whitespace = token->pos.whitespace;
551 alloc->number = token->number;
552 alloc->pos.noexpand = token->pos.noexpand;
553 return alloc;
556 static struct token **copy(struct token **where, struct token *list, int *count)
558 int need_copy = --*count;
559 while (!eof_token(list)) {
560 struct token *token;
561 if (need_copy)
562 token = dup_token(list, &list->pos);
563 else
564 token = list;
565 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
566 token->pos.noexpand = 1;
567 *where = token;
568 where = &token->next;
569 list = list->next;
571 *where = &eof_token_entry;
572 return where;
575 static int handle_kludge(struct token **p, struct arg *args)
577 struct token *t = (*p)->next->next;
578 while (1) {
579 struct arg *v = &args[t->argnum];
580 if (token_type(t->next) != TOKEN_CONCAT) {
581 if (v->arg) {
582 /* ignore the first ## */
583 *p = (*p)->next;
584 return 0;
586 /* skip the entire thing */
587 *p = t;
588 return 1;
590 if (v->arg && !eof_token(v->arg))
591 return 0; /* no magic */
592 t = t->next->next;
596 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
598 struct position *base_pos = &(*list)->pos;
599 int *count;
600 enum {Normal, Placeholder, Concat} state = Normal;
602 for (; !eof_token(body); body = body->next) {
603 struct token *added, *arg;
604 struct token **tail;
605 struct token *t;
607 switch (token_type(body)) {
608 case TOKEN_GNU_KLUDGE:
610 * GNU kludge: if we had <comma>##<vararg>, behaviour
611 * depends on whether we had enough arguments to have
612 * a vararg. If we did, ## is just ignored. Otherwise
613 * both , and ## are ignored. Worse, there can be
614 * an arbitrary number of ##<arg> in between; if all of
615 * those are empty, we act as if they hadn't been there,
616 * otherwise we act as if the kludge didn't exist.
618 t = body;
619 if (handle_kludge(&body, args)) {
620 if (state == Concat)
621 state = Normal;
622 else
623 state = Placeholder;
624 continue;
626 added = dup_token(t, base_pos);
627 token_type(added) = TOKEN_SPECIAL;
628 tail = &added->next;
629 break;
631 case TOKEN_STR_ARGUMENT:
632 arg = args[body->argnum].str;
633 count = &args[body->argnum].n_str;
634 goto copy_arg;
636 case TOKEN_QUOTED_ARGUMENT:
637 arg = args[body->argnum].arg;
638 count = &args[body->argnum].n_quoted;
639 if (!arg || eof_token(arg)) {
640 if (state == Concat)
641 state = Normal;
642 else
643 state = Placeholder;
644 continue;
646 goto copy_arg;
648 case TOKEN_MACRO_ARGUMENT:
649 arg = args[body->argnum].expanded;
650 count = &args[body->argnum].n_normal;
651 if (eof_token(arg)) {
652 state = Normal;
653 continue;
655 copy_arg:
656 tail = copy(&added, arg, count);
657 added->pos.newline = body->pos.newline;
658 added->pos.whitespace = body->pos.whitespace;
659 break;
661 case TOKEN_CONCAT:
662 if (state == Placeholder)
663 state = Normal;
664 else
665 state = Concat;
666 continue;
668 case TOKEN_IDENT:
669 added = dup_token(body, base_pos);
670 if (added->ident->tainted)
671 added->pos.noexpand = 1;
672 tail = &added->next;
673 break;
675 default:
676 added = dup_token(body, base_pos);
677 tail = &added->next;
678 break;
682 * if we got to doing real concatenation, we already have
683 * added something into the list, so containing_token() is OK.
685 if (state == Concat && merge(containing_token(list), added)) {
686 *list = added->next;
687 if (tail != &added->next)
688 list = tail;
689 } else {
690 *list = added;
691 list = tail;
693 state = Normal;
695 *list = &eof_token_entry;
696 return list;
699 static int expand(struct token **list, struct symbol *sym)
701 struct token *last;
702 struct token *token = *list;
703 struct ident *expanding = token->ident;
704 struct token **tail;
705 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
706 struct arg args[nargs];
708 if (expanding->tainted) {
709 token->pos.noexpand = 1;
710 return 1;
713 if (sym->arglist) {
714 if (!match_op(scan_next(&token->next), '('))
715 return 1;
716 if (!collect_arguments(token->next, sym->arglist, args, token))
717 return 1;
718 expand_arguments(nargs, args);
721 expanding->tainted = 1;
723 last = token->next;
724 tail = substitute(list, sym->expansion, args);
726 * Note that it won't be eof - at least TOKEN_UNTAINT will be there.
727 * We still can lose the newline flag if the sucker expands to nothing,
728 * but the price of dealing with that is probably too high (we'd need
729 * to collect the flags during scan_next())
731 (*list)->pos.newline = token->pos.newline;
732 (*list)->pos.whitespace = token->pos.whitespace;
733 *tail = last;
735 return 0;
738 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
740 static char buffer[256];
741 char *ptr = buffer;
743 while (!eof_token(token) && !match_op(token, endop)) {
744 int len;
745 const char *val = token->string->data;
746 if (token_type(token) != TOKEN_STRING)
747 val = show_token(token);
748 len = strlen(val);
749 memcpy(ptr, val, len);
750 ptr += len;
751 token = token->next;
753 *ptr = 0;
754 if (endop && !match_op(token, endop))
755 sparse_error(start->pos, "expected '>' at end of filename");
756 return buffer;
759 static int already_tokenized(const char *path)
761 int stream, next;
763 for (stream = *hash_stream(path); stream >= 0 ; stream = next) {
764 struct stream *s = input_streams + stream;
766 next = s->next_stream;
767 if (s->once) {
768 if (strcmp(path, s->name))
769 continue;
770 return 1;
772 if (s->constant != CONSTANT_FILE_YES)
773 continue;
774 if (strcmp(path, s->name))
775 continue;
776 if (s->protect && !lookup_macro(s->protect))
777 continue;
778 return 1;
780 return 0;
783 /* Handle include of header files.
784 * The relevant options are made compatible with gcc. The only options that
785 * are not supported is -withprefix and friends.
787 * Three set of include paths are known:
788 * quote_includepath: Path to search when using #include "file.h"
789 * angle_includepath: Paths to search when using #include <file.h>
790 * isys_includepath: Paths specified with -isystem, come before the
791 * built-in system include paths. Gcc would suppress
792 * warnings from system headers. Here we separate
793 * them from the angle_ ones to keep search ordering.
795 * sys_includepath: Built-in include paths.
796 * dirafter_includepath Paths added with -dirafter.
798 * The above is implemented as one array with pointers
799 * +--------------+
800 * quote_includepath ---> | |
801 * +--------------+
802 * | |
803 * +--------------+
804 * angle_includepath ---> | |
805 * +--------------+
806 * isys_includepath ---> | |
807 * +--------------+
808 * sys_includepath ---> | |
809 * +--------------+
810 * dirafter_includepath -> | |
811 * +--------------+
813 * -I dir insert dir just before isys_includepath and move the rest
814 * -I- makes all dirs specified with -I before to quote dirs only and
815 * angle_includepath is set equal to isys_includepath.
816 * -nostdinc removes all sys dirs by storing NULL in entry pointed
817 * to by * sys_includepath. Note that this will reset all dirs built-in
818 * and added before -nostdinc by -isystem and -idirafter.
819 * -isystem dir adds dir where isys_includepath points adding this dir as
820 * first systemdir
821 * -idirafter dir adds dir to the end of the list
824 static void set_stream_include_path(struct stream *stream)
826 const char *path = stream->path;
827 if (!path) {
828 const char *p = strrchr(stream->name, '/');
829 path = "";
830 if (p) {
831 int len = p - stream->name + 1;
832 char *m = malloc(len+1);
833 /* This includes the final "/" */
834 memcpy(m, stream->name, len);
835 m[len] = 0;
836 path = m;
838 stream->path = path;
840 includepath[0] = path;
843 static int try_include(const char *path, const char *filename, int flen, struct token **where, const char **next_path)
845 int fd;
846 int plen = strlen(path);
847 static char fullname[PATH_MAX];
849 memcpy(fullname, path, plen);
850 if (plen && path[plen-1] != '/') {
851 fullname[plen] = '/';
852 plen++;
854 memcpy(fullname+plen, filename, flen);
855 if (already_tokenized(fullname))
856 return 1;
857 fd = open(fullname, O_RDONLY);
858 if (fd >= 0) {
859 char * streamname = __alloc_bytes(plen + flen);
860 memcpy(streamname, fullname, plen + flen);
861 *where = tokenize(streamname, fd, *where, next_path);
862 close(fd);
863 return 1;
865 return 0;
868 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
870 const char *path;
872 while ((path = *pptr++) != NULL) {
873 if (!try_include(path, filename, flen, list, pptr))
874 continue;
875 return 1;
877 return 0;
880 static int free_preprocessor_line(struct token *token)
882 while (token_type(token) != TOKEN_EOF) {
883 struct token *free = token;
884 token = token->next;
885 __free_token(free);
887 return 1;
890 const char *find_include(const char *skip, const char *look_for)
892 DIR *dp;
893 struct dirent *entry;
894 struct stat statbuf;
895 const char *ret;
896 char cwd[PATH_MAX];
897 static char buf[PATH_MAX + 1];
899 dp = opendir(".");
900 if (!dp)
901 return NULL;
903 if (!getcwd(cwd, sizeof(cwd)))
904 return NULL;
906 while ((entry = readdir(dp))) {
907 lstat(entry->d_name, &statbuf);
909 if (strcmp(entry->d_name, look_for) == 0) {
910 snprintf(buf, sizeof(buf), "%s/%s", cwd, entry->d_name);
911 return buf;
914 if (S_ISDIR(statbuf.st_mode)) {
915 /* Found a directory, but ignore . and .. */
916 if (strcmp(".", entry->d_name) == 0 ||
917 strcmp("..", entry->d_name) == 0 ||
918 strcmp(skip, entry->d_name) == 0)
919 continue;
921 chdir(entry->d_name);
922 ret = find_include("", look_for);
923 chdir("..");
924 if (ret)
925 return ret;
928 closedir(dp);
930 return NULL;
933 const char *search_dir(const char *stop, const char *look_for)
935 char cwd[PATH_MAX];
936 int len;
937 const char *ret;
939 if (!getcwd(cwd, sizeof(cwd)))
940 return NULL;
942 len = strlen(cwd);
943 while (len >= 0) {
944 ret = find_include(cwd + len + 1, look_for);
945 if (ret)
946 return ret;
948 if (strcmp(cwd, stop) == 0 ||
949 strcmp(cwd, "/usr/include") == 0 ||
950 strcmp(cwd, "/usr/local/include") == 0 ||
951 strlen(cwd) <= 10 || /* heck... don't search /usr/lib/ */
952 strcmp(cwd, "/") == 0)
953 return NULL;
955 while (--len >= 0) {
956 if (cwd[len] == '/') {
957 cwd[len] = '\0';
958 break;
962 chdir("..");
964 return NULL;
967 static void use_best_guess_header_file(struct token *token, const char *filename, struct token **list)
969 char cwd[PATH_MAX];
970 char dir_part[PATH_MAX];
971 const char *file_part;
972 const char *include_name;
973 int len;
975 if (!filename || filename[0] == '\0')
976 return;
978 file_part = filename;
979 while ((filename = strchr(filename, '/'))) {
980 ++filename;
981 if (filename[0])
982 file_part = filename;
985 snprintf(dir_part, sizeof(dir_part), "%s", stream_name(token->pos.stream));
986 len = strlen(dir_part);
987 while (--len >= 0) {
988 if (dir_part[len] == '/') {
989 dir_part[len] = '\0';
990 break;
993 if (len < 0)
994 sprintf(dir_part, ".");
996 if (!getcwd(cwd, sizeof(cwd)))
997 return;
999 chdir(dir_part);
1000 include_name = search_dir(cwd, file_part);
1001 chdir(cwd);
1002 if (!include_name)
1003 return;
1004 sparse_error(token->pos, "using '%s'", include_name);
1006 try_include("", include_name, strlen(include_name), list, includepath);
1009 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, int how)
1011 const char *filename;
1012 struct token *next;
1013 const char **path;
1014 int expect;
1015 int flen;
1017 next = token->next;
1018 expect = '>';
1019 if (!match_op(next, '<')) {
1020 expand_list(&token->next);
1021 expect = 0;
1022 next = token;
1023 if (match_op(token->next, '<')) {
1024 next = token->next;
1025 expect = '>';
1029 token = next->next;
1030 filename = token_name_sequence(token, expect, token);
1031 flen = strlen(filename) + 1;
1033 /* Absolute path? */
1034 if (filename[0] == '/') {
1035 if (try_include("", filename, flen, list, includepath))
1036 return 0;
1037 goto out;
1040 switch (how) {
1041 case 1:
1042 path = stream->next_path;
1043 break;
1044 case 2:
1045 includepath[0] = "";
1046 path = includepath;
1047 break;
1048 default:
1049 /* Dir of input file is first dir to search for quoted includes */
1050 set_stream_include_path(stream);
1051 path = expect ? angle_includepath : quote_includepath;
1052 break;
1054 /* Check the standard include paths.. */
1055 if (do_include_path(path, list, token, filename, flen))
1056 return 0;
1057 out:
1058 sparse_error(token->pos, "unable to open '%s'", filename);
1059 use_best_guess_header_file(token, filename, list);
1060 return 0;
1063 static int handle_include(struct stream *stream, struct token **list, struct token *token)
1065 return handle_include_path(stream, list, token, 0);
1068 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
1070 return handle_include_path(stream, list, token, 1);
1073 static int handle_argv_include(struct stream *stream, struct token **list, struct token *token)
1075 return handle_include_path(stream, list, token, 2);
1078 static int token_different(struct token *t1, struct token *t2)
1080 int different;
1082 if (token_type(t1) != token_type(t2))
1083 return 1;
1085 switch (token_type(t1)) {
1086 case TOKEN_IDENT:
1087 different = t1->ident != t2->ident;
1088 break;
1089 case TOKEN_ARG_COUNT:
1090 case TOKEN_UNTAINT:
1091 case TOKEN_CONCAT:
1092 case TOKEN_GNU_KLUDGE:
1093 different = 0;
1094 break;
1095 case TOKEN_NUMBER:
1096 different = strcmp(t1->number, t2->number);
1097 break;
1098 case TOKEN_SPECIAL:
1099 different = t1->special != t2->special;
1100 break;
1101 case TOKEN_MACRO_ARGUMENT:
1102 case TOKEN_QUOTED_ARGUMENT:
1103 case TOKEN_STR_ARGUMENT:
1104 different = t1->argnum != t2->argnum;
1105 break;
1106 case TOKEN_CHAR_EMBEDDED_0 ... TOKEN_CHAR_EMBEDDED_3:
1107 case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3:
1108 different = memcmp(t1->embedded, t2->embedded, 4);
1109 break;
1110 case TOKEN_CHAR:
1111 case TOKEN_WIDE_CHAR:
1112 case TOKEN_STRING:
1113 case TOKEN_WIDE_STRING: {
1114 struct string *s1, *s2;
1116 s1 = t1->string;
1117 s2 = t2->string;
1118 different = 1;
1119 if (s1->length != s2->length)
1120 break;
1121 different = memcmp(s1->data, s2->data, s1->length);
1122 break;
1124 default:
1125 different = 1;
1126 break;
1128 return different;
1131 static int token_list_different(struct token *list1, struct token *list2)
1133 for (;;) {
1134 if (list1 == list2)
1135 return 0;
1136 if (!list1 || !list2)
1137 return 1;
1138 if (token_different(list1, list2))
1139 return 1;
1140 list1 = list1->next;
1141 list2 = list2->next;
1145 static inline void set_arg_count(struct token *token)
1147 token_type(token) = TOKEN_ARG_COUNT;
1148 token->count.normal = token->count.quoted =
1149 token->count.str = token->count.vararg = 0;
1152 static struct token *parse_arguments(struct token *list)
1154 struct token *arg = list->next, *next = list;
1155 struct argcount *count = &list->count;
1157 set_arg_count(list);
1159 if (match_op(arg, ')')) {
1160 next = arg->next;
1161 list->next = &eof_token_entry;
1162 return next;
1165 while (token_type(arg) == TOKEN_IDENT) {
1166 if (arg->ident == &__VA_ARGS___ident)
1167 goto Eva_args;
1168 if (!++count->normal)
1169 goto Eargs;
1170 next = arg->next;
1172 if (match_op(next, ',')) {
1173 set_arg_count(next);
1174 arg = next->next;
1175 continue;
1178 if (match_op(next, ')')) {
1179 set_arg_count(next);
1180 next = next->next;
1181 arg->next->next = &eof_token_entry;
1182 return next;
1185 /* normal cases are finished here */
1187 if (match_op(next, SPECIAL_ELLIPSIS)) {
1188 if (match_op(next->next, ')')) {
1189 set_arg_count(next);
1190 next->count.vararg = 1;
1191 next = next->next;
1192 arg->next->next = &eof_token_entry;
1193 return next->next;
1196 arg = next;
1197 goto Enotclosed;
1200 if (eof_token(next)) {
1201 goto Enotclosed;
1202 } else {
1203 arg = next;
1204 goto Ebadstuff;
1208 if (match_op(arg, SPECIAL_ELLIPSIS)) {
1209 next = arg->next;
1210 token_type(arg) = TOKEN_IDENT;
1211 arg->ident = &__VA_ARGS___ident;
1212 if (!match_op(next, ')'))
1213 goto Enotclosed;
1214 if (!++count->normal)
1215 goto Eargs;
1216 set_arg_count(next);
1217 next->count.vararg = 1;
1218 next = next->next;
1219 arg->next->next = &eof_token_entry;
1220 return next;
1223 if (eof_token(arg)) {
1224 arg = next;
1225 goto Enotclosed;
1227 if (match_op(arg, ','))
1228 goto Emissing;
1229 else
1230 goto Ebadstuff;
1233 Emissing:
1234 sparse_error(arg->pos, "parameter name missing");
1235 return NULL;
1236 Ebadstuff:
1237 sparse_error(arg->pos, "\"%s\" may not appear in macro parameter list",
1238 show_token(arg));
1239 return NULL;
1240 Enotclosed:
1241 sparse_error(arg->pos, "missing ')' in macro parameter list");
1242 return NULL;
1243 Eva_args:
1244 sparse_error(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
1245 return NULL;
1246 Eargs:
1247 sparse_error(arg->pos, "too many arguments in macro definition");
1248 return NULL;
1251 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
1253 struct ident *ident = token->ident;
1254 int nr;
1256 if (!arglist || token_type(token) != TOKEN_IDENT)
1257 return 0;
1259 arglist = arglist->next;
1261 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
1262 if (arglist->ident == ident) {
1263 struct argcount *count = &arglist->next->count;
1264 int n;
1266 token->argnum = nr;
1267 token_type(token) = type;
1268 switch (type) {
1269 case TOKEN_MACRO_ARGUMENT:
1270 n = ++count->normal;
1271 break;
1272 case TOKEN_QUOTED_ARGUMENT:
1273 n = ++count->quoted;
1274 break;
1275 default:
1276 n = ++count->str;
1278 if (n)
1279 return count->vararg ? 2 : 1;
1281 * XXX - need saner handling of that
1282 * (>= 1024 instances of argument)
1284 token_type(token) = TOKEN_ERROR;
1285 return -1;
1288 return 0;
1291 static struct token *handle_hash(struct token **p, struct token *arglist)
1293 struct token *token = *p;
1294 if (arglist) {
1295 struct token *next = token->next;
1296 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
1297 goto Equote;
1298 next->pos.whitespace = token->pos.whitespace;
1299 __free_token(token);
1300 token = *p = next;
1301 } else {
1302 token->pos.noexpand = 1;
1304 return token;
1306 Equote:
1307 sparse_error(token->pos, "'#' is not followed by a macro parameter");
1308 return NULL;
1311 /* token->next is ## */
1312 static struct token *handle_hashhash(struct token *token, struct token *arglist)
1314 struct token *last = token;
1315 struct token *concat;
1316 int state = match_op(token, ',');
1318 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
1320 while (1) {
1321 struct token *t;
1322 int is_arg;
1324 /* eat duplicate ## */
1325 concat = token->next;
1326 while (match_op(t = concat->next, SPECIAL_HASHHASH)) {
1327 token->next = t;
1328 __free_token(concat);
1329 concat = t;
1331 token_type(concat) = TOKEN_CONCAT;
1333 if (eof_token(t))
1334 goto Econcat;
1336 if (match_op(t, '#')) {
1337 t = handle_hash(&concat->next, arglist);
1338 if (!t)
1339 return NULL;
1342 is_arg = try_arg(t, TOKEN_QUOTED_ARGUMENT, arglist);
1344 if (state == 1 && is_arg) {
1345 state = is_arg;
1346 } else {
1347 last = t;
1348 state = match_op(t, ',');
1351 token = t;
1352 if (!match_op(token->next, SPECIAL_HASHHASH))
1353 break;
1355 /* handle GNU ,##__VA_ARGS__ kludge, in all its weirdness */
1356 if (state == 2)
1357 token_type(last) = TOKEN_GNU_KLUDGE;
1358 return token;
1360 Econcat:
1361 sparse_error(concat->pos, "'##' cannot appear at the ends of macro expansion");
1362 return NULL;
1365 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
1367 struct token *token = expansion;
1368 struct token **p;
1370 if (match_op(token, SPECIAL_HASHHASH))
1371 goto Econcat;
1373 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
1374 if (match_op(token, '#')) {
1375 token = handle_hash(p, arglist);
1376 if (!token)
1377 return NULL;
1379 if (match_op(token->next, SPECIAL_HASHHASH)) {
1380 token = handle_hashhash(token, arglist);
1381 if (!token)
1382 return NULL;
1383 } else {
1384 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
1386 if (token_type(token) == TOKEN_ERROR)
1387 goto Earg;
1389 token = alloc_token(&expansion->pos);
1390 token_type(token) = TOKEN_UNTAINT;
1391 token->ident = name;
1392 token->next = *p;
1393 *p = token;
1394 return expansion;
1396 Econcat:
1397 sparse_error(token->pos, "'##' cannot appear at the ends of macro expansion");
1398 return NULL;
1399 Earg:
1400 sparse_error(token->pos, "too many instances of argument in body");
1401 return NULL;
1404 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int attr)
1406 struct token *arglist, *expansion;
1407 struct token *left = token->next;
1408 struct symbol *sym;
1409 struct ident *name;
1410 int ret;
1412 if (token_type(left) != TOKEN_IDENT) {
1413 sparse_error(token->pos, "expected identifier to 'define'");
1414 return 1;
1417 name = left->ident;
1419 arglist = NULL;
1420 expansion = left->next;
1421 if (!expansion->pos.whitespace) {
1422 if (match_op(expansion, '(')) {
1423 arglist = expansion;
1424 expansion = parse_arguments(expansion);
1425 if (!expansion)
1426 return 1;
1427 } else if (!eof_token(expansion)) {
1428 warning(expansion->pos,
1429 "no whitespace before object-like macro body");
1433 expansion = parse_expansion(expansion, arglist, name);
1434 if (!expansion)
1435 return 1;
1437 ret = 1;
1438 sym = lookup_symbol(name, NS_MACRO | NS_UNDEF);
1439 if (sym) {
1440 int clean;
1442 if (attr < sym->attr)
1443 goto out;
1445 clean = (attr == sym->attr && sym->namespace == NS_MACRO);
1447 if (token_list_different(sym->expansion, expansion) ||
1448 token_list_different(sym->arglist, arglist)) {
1449 ret = 0;
1450 if ((clean && attr == SYM_ATTR_NORMAL)
1451 || sym->used_in == file_scope) {
1452 warning(left->pos, "preprocessor token %.*s redefined",
1453 name->len, name->name);
1454 info(sym->pos, "this was the original definition");
1456 } else if (clean)
1457 goto out;
1460 if (!sym || sym->scope != file_scope) {
1461 sym = alloc_symbol(left->pos, SYM_NODE);
1462 bind_symbol(sym, name, NS_MACRO);
1463 ret = 0;
1466 if (!ret) {
1467 sym->expansion = expansion;
1468 sym->arglist = arglist;
1469 __free_token(token); /* Free the "define" token, but not the rest of the line */
1472 sym->namespace = NS_MACRO;
1473 sym->used_in = NULL;
1474 sym->attr = attr;
1475 out:
1476 return ret;
1479 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1481 return do_handle_define(stream, line, token, SYM_ATTR_NORMAL);
1484 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1486 return do_handle_define(stream, line, token, SYM_ATTR_WEAK);
1489 static int handle_strong_define(struct stream *stream, struct token **line, struct token *token)
1491 return do_handle_define(stream, line, token, SYM_ATTR_STRONG);
1494 static int do_handle_undef(struct stream *stream, struct token **line, struct token *token, int attr)
1496 struct token *left = token->next;
1497 struct symbol *sym;
1499 if (token_type(left) != TOKEN_IDENT) {
1500 sparse_error(token->pos, "expected identifier to 'undef'");
1501 return 1;
1504 sym = lookup_symbol(left->ident, NS_MACRO | NS_UNDEF);
1505 if (sym) {
1506 if (attr < sym->attr)
1507 return 1;
1508 if (attr == sym->attr && sym->namespace == NS_UNDEF)
1509 return 1;
1510 } else if (attr <= SYM_ATTR_NORMAL)
1511 return 1;
1513 if (!sym || sym->scope != file_scope) {
1514 sym = alloc_symbol(left->pos, SYM_NODE);
1515 bind_symbol(sym, left->ident, NS_MACRO);
1518 sym->namespace = NS_UNDEF;
1519 sym->used_in = NULL;
1520 sym->attr = attr;
1522 return 1;
1525 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1527 return do_handle_undef(stream, line, token, SYM_ATTR_NORMAL);
1530 static int handle_strong_undef(struct stream *stream, struct token **line, struct token *token)
1532 return do_handle_undef(stream, line, token, SYM_ATTR_STRONG);
1535 static int preprocessor_if(struct stream *stream, struct token *token, int true)
1537 token_type(token) = false_nesting ? TOKEN_SKIP_GROUPS : TOKEN_IF;
1538 free_preprocessor_line(token->next);
1539 token->next = stream->top_if;
1540 stream->top_if = token;
1541 if (false_nesting || true != 1)
1542 false_nesting++;
1543 return 0;
1546 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1548 struct token *next = token->next;
1549 int arg;
1550 if (token_type(next) == TOKEN_IDENT) {
1551 arg = token_defined(next);
1552 } else {
1553 dirty_stream(stream);
1554 if (!false_nesting)
1555 sparse_error(token->pos, "expected preprocessor identifier");
1556 arg = -1;
1558 return preprocessor_if(stream, token, arg);
1561 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1563 struct token *next = token->next;
1564 int arg;
1565 if (token_type(next) == TOKEN_IDENT) {
1566 if (!stream->dirty && !stream->ifndef) {
1567 if (!stream->protect) {
1568 stream->ifndef = token;
1569 stream->protect = next->ident;
1570 } else if (stream->protect == next->ident) {
1571 stream->ifndef = token;
1572 stream->dirty = 1;
1575 arg = !token_defined(next);
1576 } else {
1577 dirty_stream(stream);
1578 if (!false_nesting)
1579 sparse_error(token->pos, "expected preprocessor identifier");
1580 arg = -1;
1583 return preprocessor_if(stream, token, arg);
1586 static const char *show_token_sequence(struct token *token, int quote);
1589 * Expression handling for #if and #elif; it differs from normal expansion
1590 * due to special treatment of "defined".
1592 static int expression_value(struct token **where)
1594 struct expression *expr;
1595 struct token *p;
1596 struct token **list = where, **beginning = NULL;
1597 long long value;
1598 int state = 0;
1600 while (!eof_token(p = scan_next(list))) {
1601 switch (state) {
1602 case 0:
1603 if (token_type(p) != TOKEN_IDENT)
1604 break;
1605 if (p->ident == &defined_ident) {
1606 state = 1;
1607 beginning = list;
1608 break;
1610 if (!expand_one_symbol(list))
1611 continue;
1612 if (token_type(p) != TOKEN_IDENT)
1613 break;
1614 token_type(p) = TOKEN_ZERO_IDENT;
1615 break;
1616 case 1:
1617 if (match_op(p, '(')) {
1618 state = 2;
1619 } else {
1620 state = 0;
1621 replace_with_defined(p);
1622 *beginning = p;
1624 break;
1625 case 2:
1626 if (token_type(p) == TOKEN_IDENT)
1627 state = 3;
1628 else
1629 state = 0;
1630 replace_with_defined(p);
1631 *beginning = p;
1632 break;
1633 case 3:
1634 state = 0;
1635 if (!match_op(p, ')'))
1636 sparse_error(p->pos, "missing ')' after \"defined\"");
1637 *list = p->next;
1638 continue;
1640 list = &p->next;
1643 p = constant_expression(*where, &expr);
1644 if (!eof_token(p))
1645 sparse_error(p->pos, "garbage at end: %s", show_token_sequence(p, 0));
1646 value = get_expression_value(expr);
1647 return value != 0;
1650 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1652 int value = 0;
1653 if (!false_nesting)
1654 value = expression_value(&token->next);
1656 dirty_stream(stream);
1657 return preprocessor_if(stream, token, value);
1660 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1662 struct token *top_if = stream->top_if;
1663 end_group(stream);
1665 if (!top_if) {
1666 nesting_error(stream);
1667 sparse_error(token->pos, "unmatched #elif within stream");
1668 return 1;
1671 if (token_type(top_if) == TOKEN_ELSE) {
1672 nesting_error(stream);
1673 sparse_error(token->pos, "#elif after #else");
1674 if (!false_nesting)
1675 false_nesting = 1;
1676 return 1;
1679 dirty_stream(stream);
1680 if (token_type(top_if) != TOKEN_IF)
1681 return 1;
1682 if (false_nesting) {
1683 false_nesting = 0;
1684 if (!expression_value(&token->next))
1685 false_nesting = 1;
1686 } else {
1687 false_nesting = 1;
1688 token_type(top_if) = TOKEN_SKIP_GROUPS;
1690 return 1;
1693 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1695 struct token *top_if = stream->top_if;
1696 end_group(stream);
1698 if (!top_if) {
1699 nesting_error(stream);
1700 sparse_error(token->pos, "unmatched #else within stream");
1701 return 1;
1704 if (token_type(top_if) == TOKEN_ELSE) {
1705 nesting_error(stream);
1706 sparse_error(token->pos, "#else after #else");
1708 if (false_nesting) {
1709 if (token_type(top_if) == TOKEN_IF)
1710 false_nesting = 0;
1711 } else {
1712 false_nesting = 1;
1714 token_type(top_if) = TOKEN_ELSE;
1715 return 1;
1718 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1720 struct token *top_if = stream->top_if;
1721 end_group(stream);
1722 if (!top_if) {
1723 nesting_error(stream);
1724 sparse_error(token->pos, "unmatched #endif in stream");
1725 return 1;
1727 if (false_nesting)
1728 false_nesting--;
1729 stream->top_if = top_if->next;
1730 __free_token(top_if);
1731 return 1;
1734 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1736 warning(token->pos, "%s", show_token_sequence(token->next, 0));
1737 return 1;
1740 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1742 sparse_error(token->pos, "%s", show_token_sequence(token->next, 0));
1743 return 1;
1746 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1749 * Do we have any non-system includes?
1750 * Clear them out if so..
1752 *sys_includepath = NULL;
1753 return 1;
1756 static inline void update_inc_ptrs(const char ***where)
1759 if (*where <= dirafter_includepath) {
1760 dirafter_includepath++;
1761 /* If this was the entry that we prepend, don't
1762 * rise the lower entries, even if they are at
1763 * the same level. */
1764 if (where == &dirafter_includepath)
1765 return;
1767 if (*where <= sys_includepath) {
1768 sys_includepath++;
1769 if (where == &sys_includepath)
1770 return;
1772 if (*where <= isys_includepath) {
1773 isys_includepath++;
1774 if (where == &isys_includepath)
1775 return;
1778 /* angle_includepath is actually never updated, since we
1779 * don't suppport -iquote rught now. May change some day. */
1780 if (*where <= angle_includepath) {
1781 angle_includepath++;
1782 if (where == &angle_includepath)
1783 return;
1787 /* Add a path before 'where' and update the pointers associated with the
1788 * includepath array */
1789 static void add_path_entry(struct token *token, const char *path,
1790 const char ***where)
1792 const char **dst;
1793 const char *next;
1795 /* Need one free entry.. */
1796 if (includepath[INCLUDEPATHS-2])
1797 error_die(token->pos, "too many include path entries");
1799 /* check that this is not a duplicate */
1800 dst = includepath;
1801 while (*dst) {
1802 if (strcmp(*dst, path) == 0)
1803 return;
1804 dst++;
1806 next = path;
1807 dst = *where;
1809 update_inc_ptrs(where);
1812 * Move them all up starting at dst,
1813 * insert the new entry..
1815 do {
1816 const char *tmp = *dst;
1817 *dst = next;
1818 next = tmp;
1819 dst++;
1820 } while (next);
1823 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1825 for (;;) {
1826 token = token->next;
1827 if (eof_token(token))
1828 return 1;
1829 if (token_type(token) != TOKEN_STRING) {
1830 warning(token->pos, "expected path string");
1831 return 1;
1833 add_path_entry(token, token->string->data, &isys_includepath);
1837 static int handle_add_isystem(struct stream *stream, struct token **line, struct token *token)
1839 for (;;) {
1840 token = token->next;
1841 if (eof_token(token))
1842 return 1;
1843 if (token_type(token) != TOKEN_STRING) {
1844 sparse_error(token->pos, "expected path string");
1845 return 1;
1847 add_path_entry(token, token->string->data, &sys_includepath);
1851 static int handle_add_system(struct stream *stream, struct token **line, struct token *token)
1853 for (;;) {
1854 token = token->next;
1855 if (eof_token(token))
1856 return 1;
1857 if (token_type(token) != TOKEN_STRING) {
1858 sparse_error(token->pos, "expected path string");
1859 return 1;
1861 add_path_entry(token, token->string->data, &dirafter_includepath);
1865 /* Add to end on includepath list - no pointer updates */
1866 static void add_dirafter_entry(struct token *token, const char *path)
1868 const char **dst = includepath;
1870 /* Need one free entry.. */
1871 if (includepath[INCLUDEPATHS-2])
1872 error_die(token->pos, "too many include path entries");
1874 /* Add to the end */
1875 while (*dst)
1876 dst++;
1877 *dst = path;
1878 dst++;
1879 *dst = NULL;
1882 static int handle_add_dirafter(struct stream *stream, struct token **line, struct token *token)
1884 for (;;) {
1885 token = token->next;
1886 if (eof_token(token))
1887 return 1;
1888 if (token_type(token) != TOKEN_STRING) {
1889 sparse_error(token->pos, "expected path string");
1890 return 1;
1892 add_dirafter_entry(token, token->string->data);
1896 static int handle_split_include(struct stream *stream, struct token **line, struct token *token)
1899 * -I-
1900 * From info gcc:
1901 * Split the include path. Any directories specified with `-I'
1902 * options before `-I-' are searched only for headers requested with
1903 * `#include "FILE"'; they are not searched for `#include <FILE>'.
1904 * If additional directories are specified with `-I' options after
1905 * the `-I-', those directories are searched for all `#include'
1906 * directives.
1907 * In addition, `-I-' inhibits the use of the directory of the current
1908 * file directory as the first search directory for `#include "FILE"'.
1910 quote_includepath = includepath+1;
1911 angle_includepath = sys_includepath;
1912 return 1;
1916 * We replace "#pragma xxx" with "__pragma__" in the token
1917 * stream. Just as an example.
1919 * We'll just #define that away for now, but the theory here
1920 * is that we can use this to insert arbitrary token sequences
1921 * to turn the pragmas into internal front-end sequences for
1922 * when we actually start caring about them.
1924 * So eventually this will turn into some kind of extended
1925 * __attribute__() like thing, except called __pragma__(xxx).
1927 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1929 struct token *next = *line;
1931 if (match_ident(token->next, &once_ident) && eof_token(token->next->next)) {
1932 stream->once = 1;
1933 return 1;
1935 token->ident = &pragma_ident;
1936 token->pos.newline = 1;
1937 token->pos.whitespace = 1;
1938 token->pos.pos = 1;
1939 *line = token;
1940 token->next = next;
1941 return 0;
1945 * We ignore #line for now.
1947 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1949 return 1;
1952 static int handle_nondirective(struct stream *stream, struct token **line, struct token *token)
1954 sparse_error(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token, 0));
1955 return 1;
1959 static void init_preprocessor(void)
1961 int i;
1962 int stream = init_stream("preprocessor", -1, includepath);
1963 static struct {
1964 const char *name;
1965 int (*handler)(struct stream *, struct token **, struct token *);
1966 } normal[] = {
1967 { "define", handle_define },
1968 { "weak_define", handle_weak_define },
1969 { "strong_define", handle_strong_define },
1970 { "undef", handle_undef },
1971 { "strong_undef", handle_strong_undef },
1972 { "warning", handle_warning },
1973 { "error", handle_error },
1974 { "include", handle_include },
1975 { "include_next", handle_include_next },
1976 { "pragma", handle_pragma },
1977 { "line", handle_line },
1979 // our internal preprocessor tokens
1980 { "nostdinc", handle_nostdinc },
1981 { "add_include", handle_add_include },
1982 { "add_isystem", handle_add_isystem },
1983 { "add_system", handle_add_system },
1984 { "add_dirafter", handle_add_dirafter },
1985 { "split_include", handle_split_include },
1986 { "argv_include", handle_argv_include },
1987 }, special[] = {
1988 { "ifdef", handle_ifdef },
1989 { "ifndef", handle_ifndef },
1990 { "else", handle_else },
1991 { "endif", handle_endif },
1992 { "if", handle_if },
1993 { "elif", handle_elif },
1996 for (i = 0; i < ARRAY_SIZE(normal); i++) {
1997 struct symbol *sym;
1998 sym = create_symbol(stream, normal[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1999 sym->handler = normal[i].handler;
2000 sym->normal = 1;
2002 for (i = 0; i < ARRAY_SIZE(special); i++) {
2003 struct symbol *sym;
2004 sym = create_symbol(stream, special[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
2005 sym->handler = special[i].handler;
2006 sym->normal = 0;
2011 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
2013 int (*handler)(struct stream *, struct token **, struct token *);
2014 struct token *token = start->next;
2015 int is_normal = 1;
2017 if (eof_token(token))
2018 return;
2020 if (token_type(token) == TOKEN_IDENT) {
2021 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
2022 if (sym) {
2023 handler = sym->handler;
2024 is_normal = sym->normal;
2025 } else {
2026 handler = handle_nondirective;
2028 } else if (token_type(token) == TOKEN_NUMBER) {
2029 handler = handle_line;
2030 } else {
2031 handler = handle_nondirective;
2034 if (is_normal) {
2035 dirty_stream(stream);
2036 if (false_nesting)
2037 goto out;
2039 if (!handler(stream, line, token)) /* all set */
2040 return;
2042 out:
2043 free_preprocessor_line(token);
2046 static void preprocessor_line(struct stream *stream, struct token **line)
2048 struct token *start = *line, *next;
2049 struct token **tp = &start->next;
2051 for (;;) {
2052 next = *tp;
2053 if (next->pos.newline)
2054 break;
2055 tp = &next->next;
2057 *line = next;
2058 *tp = &eof_token_entry;
2059 handle_preprocessor_line(stream, line, start);
2062 static void do_preprocess(struct token **list)
2064 struct token *next;
2066 while (!eof_token(next = scan_next(list))) {
2067 struct stream *stream = input_streams + next->pos.stream;
2069 if (next->pos.newline && match_op(next, '#')) {
2070 if (!next->pos.noexpand) {
2071 preprocessor_line(stream, list);
2072 __free_token(next); /* Free the '#' token */
2073 continue;
2077 switch (token_type(next)) {
2078 case TOKEN_STREAMEND:
2079 if (stream->top_if) {
2080 nesting_error(stream);
2081 sparse_error(stream->top_if->pos, "unterminated preprocessor conditional");
2082 stream->top_if = NULL;
2083 false_nesting = 0;
2085 if (!stream->dirty)
2086 stream->constant = CONSTANT_FILE_YES;
2087 *list = next->next;
2088 continue;
2089 case TOKEN_STREAMBEGIN:
2090 *list = next->next;
2091 continue;
2093 default:
2094 dirty_stream(stream);
2095 if (false_nesting) {
2096 *list = next->next;
2097 __free_token(next);
2098 continue;
2101 if (token_type(next) != TOKEN_IDENT ||
2102 expand_one_symbol(list))
2103 list = &next->next;
2108 void init_include_path(void)
2110 FILE *fp;
2111 char path[256];
2112 char arch[32];
2113 char os[32];
2115 fp = popen("/bin/uname -m", "r");
2116 if (!fp)
2117 return;
2118 if (!fgets(arch, sizeof(arch) - 1, fp))
2119 return;
2120 pclose(fp);
2121 if (arch[strlen(arch) - 1] == '\n')
2122 arch[strlen(arch) - 1] = '\0';
2124 fp = popen("/bin/uname -o", "r");
2125 if (!fp)
2126 return;
2127 fgets(os, sizeof(os) - 1, fp);
2128 pclose(fp);
2130 if (strcmp(os, "GNU/Linux\n") != 0)
2131 return;
2132 strcpy(os, "linux-gnu");
2134 snprintf(path, sizeof(path), "/usr/include/%s-%s/", arch, os);
2135 add_pre_buffer("#add_system \"%s/\"\n", path);
2138 struct token * preprocess(struct token *token)
2140 preprocessing = 1;
2141 init_preprocessor();
2142 do_preprocess(&token);
2144 // Drop all expressions from preprocessing, they're not used any more.
2145 // This is not true when we have multiple files, though ;/
2146 // clear_expression_alloc();
2147 preprocessing = 0;
2149 return token;