Annotation of src/usr.bin/unifdef/unifdef.c, Revision 1.22
1.1 deraadt 1: /*
1.16 sthen 2: * Copyright (c) 2002 - 2014 Tony Finch <dot@dotat.at>
1.1 deraadt 3: *
4: * Redistribution and use in source and binary forms, with or without
5: * modification, are permitted provided that the following conditions
6: * are met:
7: * 1. Redistributions of source code must retain the above copyright
8: * notice, this list of conditions and the following disclaimer.
9: * 2. Redistributions in binary form must reproduce the above copyright
10: * notice, this list of conditions and the following disclaimer in the
11: * documentation and/or other materials provided with the distribution.
12: *
1.16 sthen 13: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1.1 deraadt 14: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1.16 sthen 16: * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1.1 deraadt 17: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23: * SUCH DAMAGE.
24: */
25:
26: /*
27: * unifdef - remove ifdef'ed lines
28: *
1.16 sthen 29: * This code was derived from software contributed to Berkeley by Dave Yost.
30: * It was rewritten to support ANSI C by Tony Finch. The original version
31: * of unifdef carried the 4-clause BSD copyright licence. None of its code
32: * remains in this version (though some of the names remain) so it now
33: * carries a more liberal licence.
34: *
1.1 deraadt 35: * Wishlist:
36: * provide an option which will append the name of the
37: * appropriate symbol after #else's and #endif's
38: * provide an option which will check symbols after
39: * #else's and #endif's to see that they match their
40: * corresponding #ifdef or #ifndef
1.9 deraadt 41: *
1.16 sthen 42: * These require better buffer handling, which would also make
43: * it possible to handle all "dodgy" directives correctly.
1.1 deraadt 44: */
45:
1.22 ! deraadt 46: #include <sys/stat.h>
! 47:
! 48: #include <ctype.h>
! 49: #include <err.h>
! 50: #include <stdarg.h>
! 51: #include <stdbool.h>
! 52: #include <stdio.h>
! 53: #include <stdlib.h>
! 54: #include <string.h>
! 55: #include <unistd.h>
1.16 sthen 56:
57: static const char copyright[] =
58: #include "version.h"
1.22 ! deraadt 59: "@(#) $Author: tedu $\n"
1.16 sthen 60: "@(#) $URL: http://dotat.at/prog/unifdef $\n"
61: ;
1.1 deraadt 62:
1.7 deraadt 63: /* types of input lines: */
64: typedef enum {
1.8 deraadt 65: LT_TRUEI, /* a true #if with ignore flag */
66: LT_FALSEI, /* a false #if with ignore flag */
67: LT_IF, /* an unknown #if */
1.7 deraadt 68: LT_TRUE, /* a true #if */
69: LT_FALSE, /* a false #if */
1.8 deraadt 70: LT_ELIF, /* an unknown #elif */
1.7 deraadt 71: LT_ELTRUE, /* a true #elif */
72: LT_ELFALSE, /* a false #elif */
73: LT_ELSE, /* #else */
74: LT_ENDIF, /* #endif */
1.9 deraadt 75: LT_DODGY, /* flag: directive is not on one line */
76: LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
77: LT_PLAIN, /* ordinary line */
1.8 deraadt 78: LT_EOF, /* end of file */
1.16 sthen 79: LT_ERROR, /* unevaluable #if */
1.8 deraadt 80: LT_COUNT
1.7 deraadt 81: } Linetype;
82:
1.8 deraadt 83: static char const * const linetype_name[] = {
1.9 deraadt 84: "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
85: "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
86: "DODGY TRUEI", "DODGY FALSEI",
87: "DODGY IF", "DODGY TRUE", "DODGY FALSE",
88: "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
89: "DODGY ELSE", "DODGY ENDIF",
1.16 sthen 90: "PLAIN", "EOF", "ERROR"
1.8 deraadt 91: };
1.7 deraadt 92:
1.16 sthen 93: #define linetype_if2elif(lt) ((Linetype)(lt - LT_IF + LT_ELIF))
94: #define linetype_2dodgy(lt) ((Linetype)(lt + LT_DODGY))
95:
1.8 deraadt 96: /* state of #if processing */
1.7 deraadt 97: typedef enum {
1.8 deraadt 98: IS_OUTSIDE,
99: IS_FALSE_PREFIX, /* false #if followed by false #elifs */
100: IS_TRUE_PREFIX, /* first non-false #(el)if is true */
101: IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
102: IS_FALSE_MIDDLE, /* a false #elif after a pass state */
103: IS_TRUE_MIDDLE, /* a true #elif after a pass state */
104: IS_PASS_ELSE, /* an else after a pass state */
105: IS_FALSE_ELSE, /* an else after a true state */
106: IS_TRUE_ELSE, /* an else after only false states */
107: IS_FALSE_TRAILER, /* #elifs after a true are false */
108: IS_COUNT
109: } Ifstate;
110:
111: static char const * const ifstate_name[] = {
112: "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
113: "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
114: "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
115: "FALSE_TRAILER"
116: };
117:
118: /* state of comment parser */
119: typedef enum {
120: NO_COMMENT = false, /* outside a comment */
121: C_COMMENT, /* in a comment like this one */
122: CXX_COMMENT, /* between // and end of line */
123: STARTING_COMMENT, /* just after slash-backslash-newline */
1.16 sthen 124: FINISHING_COMMENT, /* star-backslash-newline in a C comment */
125: CHAR_LITERAL, /* inside '' */
126: STRING_LITERAL /* inside "" */
1.7 deraadt 127: } Comment_state;
128:
1.8 deraadt 129: static char const * const comment_name[] = {
1.16 sthen 130: "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
1.1 deraadt 131: };
1.7 deraadt 132:
1.8 deraadt 133: /* state of preprocessor line parser */
134: typedef enum {
135: LS_START, /* only space and comments on this line */
136: LS_HASH, /* only space, comments, and a hash */
137: LS_DIRTY /* this line can't be a preprocessor line */
138: } Line_state;
1.7 deraadt 139:
1.8 deraadt 140: static char const * const linestate_name[] = {
141: "START", "HASH", "DIRTY"
142: };
1.7 deraadt 143:
144: /*
1.8 deraadt 145: * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
1.7 deraadt 146: */
1.8 deraadt 147: #define MAXDEPTH 64 /* maximum #if nesting */
148: #define MAXLINE 4096 /* maximum length of line */
1.16 sthen 149: #define MAXSYMS 16384 /* maximum number of symbols */
1.7 deraadt 150:
151: /*
1.9 deraadt 152: * Sometimes when editing a keyword the replacement text is longer, so
153: * we leave some space at the end of the tline buffer to accommodate this.
154: */
155: #define EDITSLOP 10
156:
157: /*
1.8 deraadt 158: * Globals.
1.7 deraadt 159: */
160:
1.16 sthen 161: static bool compblank; /* -B: compress blank lines */
162: static bool lnblank; /* -b: blank deleted lines */
1.8 deraadt 163: static bool complement; /* -c: do the complement */
164: static bool debugging; /* -d: debugging reports */
1.16 sthen 165: static bool inplace; /* -m: modify in place */
1.9 deraadt 166: static bool iocccok; /* -e: fewer IOCCC errors */
1.16 sthen 167: static bool strictlogic; /* -K: keep ambiguous #ifs */
1.8 deraadt 168: static bool killconsts; /* -k: eval constant #ifs */
1.16 sthen 169: static bool lnnum; /* -n: add #line directives */
1.8 deraadt 170: static bool symlist; /* -s: output symbol list */
1.16 sthen 171: static bool symdepth; /* -S: output symbol depth */
1.8 deraadt 172: static bool text; /* -t: this is a text file */
173:
174: static const char *symname[MAXSYMS]; /* symbol name */
175: static const char *value[MAXSYMS]; /* -Dsym=value */
176: static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
177: static int nsyms; /* number of symbols */
178:
179: static FILE *input; /* input file pointer */
180: static const char *filename; /* input file name */
181: static int linenum; /* current line number */
1.16 sthen 182: static const char *linefile; /* file name for #line */
183: static FILE *output; /* output file pointer */
184: static const char *ofilename; /* output file name */
185: static const char *backext; /* backup extension */
186: static char *tempname; /* avoid splatting input */
1.8 deraadt 187:
1.9 deraadt 188: static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
1.8 deraadt 189: static char *keyword; /* used for editing #elif's */
190:
1.16 sthen 191: /*
192: * When processing a file, the output's newline style will match the
193: * input's, and unifdef correctly handles CRLF or LF endings whatever
194: * the platform's native style. The stdio streams are opened in binary
195: * mode to accommodate platforms whose native newline style is CRLF.
196: * When the output isn't a processed input file (when it is error /
197: * debug / diagnostic messages) then unifdef uses native line endings.
198: */
199:
200: static const char *newline; /* input file format */
201: static const char newline_unix[] = "\n";
202: static const char newline_crlf[] = "\r\n";
203:
1.8 deraadt 204: static Comment_state incomment; /* comment parser state */
205: static Line_state linestate; /* #if line parser state */
206: static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
207: static bool ignoring[MAXDEPTH]; /* ignore comments state */
208: static int stifline[MAXDEPTH]; /* start of current #if */
209: static int depth; /* current #if nesting */
1.16 sthen 210: static int delcount; /* count of deleted lines */
211: static unsigned blankcount; /* count of blank lines */
212: static unsigned blankmax; /* maximum recent blankcount */
213: static bool constexpr; /* constant #if expression */
214: static bool zerosyms; /* to format symdepth output */
215: static bool firstsym; /* ditto */
1.8 deraadt 216:
1.16 sthen 217: static int exitmode; /* exit status mode */
1.8 deraadt 218: static int exitstat; /* program exit status */
219:
1.16 sthen 220: static void addsym1(bool, bool, char *);
221: static void addsym2(bool, const char *, const char *);
222: static char *astrcat(const char *, const char *);
223: static void cleantemp(void);
224: static void closeio(void);
1.8 deraadt 225: static void debug(const char *, ...);
1.16 sthen 226: static void debugsym(const char *, int);
227: static bool defundef(void);
228: static void defundefile(const char *);
229: static void done(void);
1.8 deraadt 230: static void error(const char *);
1.16 sthen 231: static int findsym(const char **);
1.8 deraadt 232: static void flushline(bool);
1.16 sthen 233: static void hashline(void);
234: static void help(void);
1.8 deraadt 235: static Linetype ifeval(const char **);
1.9 deraadt 236: static void ignoreoff(void);
237: static void ignoreon(void);
1.16 sthen 238: static void indirectsym(void);
1.9 deraadt 239: static void keywordedit(const char *);
1.16 sthen 240: static const char *matchsym(const char *, const char *);
1.8 deraadt 241: static void nest(void);
1.16 sthen 242: static Linetype parseline(void);
1.8 deraadt 243: static void process(void);
1.16 sthen 244: static void processinout(const char *, const char *);
245: static const char *skipargs(const char *);
1.8 deraadt 246: static const char *skipcomment(const char *);
1.16 sthen 247: static const char *skiphash(void);
248: static const char *skipline(const char *);
1.8 deraadt 249: static const char *skipsym(const char *);
250: static void state(Ifstate);
1.16 sthen 251: static void unnest(void);
1.8 deraadt 252: static void usage(void);
1.16 sthen 253: static void version(void);
254: static const char *xstrdup(const char *, const char *);
1.22 ! deraadt 255: static FILE * mktempmode(char *tmp, int mode);
1.7 deraadt 256:
1.16 sthen 257: #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
1.7 deraadt 258:
1.8 deraadt 259: /*
260: * The main program.
261: */
1.7 deraadt 262: int
263: main(int argc, char *argv[])
264: {
1.19 deraadt 265: const char *errstr;
1.7 deraadt 266: int opt;
267:
1.16 sthen 268: while ((opt = getopt(argc, argv, "i:D:U:f:I:M:o:x:bBcdehKklmnsStV")) != -1)
1.7 deraadt 269: switch (opt) {
270: case 'i': /* treat stuff controlled by these symbols as text */
271: /*
272: * For strict backwards-compatibility the U or D
273: * should be immediately after the -i but it doesn't
274: * matter much if we relax that requirement.
275: */
276: opt = *optarg++;
277: if (opt == 'D')
1.16 sthen 278: addsym1(true, true, optarg);
1.7 deraadt 279: else if (opt == 'U')
1.16 sthen 280: addsym1(true, false, optarg);
1.7 deraadt 281: else
282: usage();
283: break;
284: case 'D': /* define a symbol */
1.16 sthen 285: addsym1(false, true, optarg);
1.7 deraadt 286: break;
287: case 'U': /* undef a symbol */
1.16 sthen 288: addsym1(false, false, optarg);
289: break;
290: case 'I': /* no-op for compatibility with cpp */
291: break;
292: case 'b': /* blank deleted lines instead of omitting them */
293: case 'l': /* backwards compatibility */
294: lnblank = true;
1.7 deraadt 295: break;
1.16 sthen 296: case 'B': /* compress blank lines around removed section */
297: compblank = true;
1.11 avsm 298: break;
1.7 deraadt 299: case 'c': /* treat -D as -U and vice versa */
300: complement = true;
301: break;
1.8 deraadt 302: case 'd':
303: debugging = true;
304: break;
1.9 deraadt 305: case 'e': /* fewer errors from dodgy lines */
306: iocccok = true;
307: break;
1.16 sthen 308: case 'f': /* definitions file */
309: defundefile(optarg);
310: break;
311: case 'h':
312: help();
313: break;
314: case 'K': /* keep ambiguous #ifs */
315: strictlogic = true;
316: break;
1.7 deraadt 317: case 'k': /* process constant #ifs */
318: killconsts = true;
319: break;
1.16 sthen 320: case 'm': /* modify in place */
321: inplace = true;
322: break;
323: case 'M': /* modify in place and keep backup */
324: inplace = true;
325: backext = optarg;
326: break;
327: case 'n': /* add #line directive after deleted lines */
328: lnnum = true;
329: break;
330: case 'o': /* output to a file */
331: ofilename = optarg;
1.7 deraadt 332: break;
333: case 's': /* only output list of symbols that control #ifs */
334: symlist = true;
335: break;
1.16 sthen 336: case 'S': /* list symbols with their nesting depth */
337: symlist = symdepth = true;
338: break;
1.8 deraadt 339: case 't': /* don't parse C comments */
1.7 deraadt 340: text = true;
341: break;
1.16 sthen 342: case 'V':
343: version();
344: break;
345: case 'x':
1.19 deraadt 346: exitmode = strtonum(optarg, 0, 2, &errstr);
347: if (errstr)
348: errx(1, "-x %s: %s", optarg, errstr);
1.16 sthen 349: break;
1.7 deraadt 350: default:
351: usage();
352: }
353: argc -= optind;
354: argv += optind;
1.16 sthen 355: if (compblank && lnblank)
356: errx(2, "-B and -b are mutually exclusive");
357: if (symlist && (ofilename != NULL || inplace || argc > 1))
358: errx(2, "-s only works with one input file");
359: if (argc > 1 && ofilename != NULL)
360: errx(2, "-o cannot be used with multiple input files");
361: if (argc > 1 && !inplace)
362: errx(2, "multiple input files require -m or -M");
1.21 tedu 363: if (argc == 0 && inplace)
364: errx(2, "can't edit stdin in place");
1.16 sthen 365: if (argc == 0)
366: argc = 1;
367: if (argc == 1 && !inplace && ofilename == NULL)
368: ofilename = "-";
369: indirectsym();
370:
371: atexit(cleantemp);
372: if (ofilename != NULL)
373: processinout(*argv, ofilename);
374: else while (argc-- > 0) {
375: processinout(*argv, *argv);
376: argv++;
377: }
378: switch(exitmode) {
379: case(0): exit(exitstat);
380: case(1): exit(!exitstat);
381: case(2): exit(0);
382: default: abort(); /* bug */
1.7 deraadt 383: }
1.16 sthen 384: }
385:
386: /*
387: * File logistics.
388: */
389: static void
390: processinout(const char *ifn, const char *ofn)
391: {
392: struct stat st;
393:
394: if (ifn == NULL || strcmp(ifn, "-") == 0) {
395: filename = "[stdin]";
396: linefile = NULL;
1.22 ! deraadt 397: input = stdin;
1.7 deraadt 398: } else {
1.16 sthen 399: filename = ifn;
400: linefile = ifn;
401: input = fopen(ifn, "rb");
402: if (input == NULL)
403: err(2, "can't open %s", ifn);
404: }
405: if (strcmp(ofn, "-") == 0) {
1.22 ! deraadt 406: output = stdout;
1.16 sthen 407: process();
408: return;
409: }
410: if (stat(ofn, &st) < 0) {
411: output = fopen(ofn, "wb");
412: if (output == NULL)
413: err(2, "can't create %s", ofn);
1.8 deraadt 414: process();
1.16 sthen 415: return;
416: }
417:
418: tempname = astrcat(ofn, ".XXXXXX");
419: output = mktempmode(tempname, st.st_mode);
420: if (output == NULL)
421: err(2, "can't create %s", tempname);
422:
423: process();
424:
425: if (backext != NULL) {
426: char *backname = astrcat(ofn, backext);
427: if (rename(ofn, backname) < 0)
428: err(2, "can't rename \"%s\" to \"%s\"", ofn, backname);
429: free(backname);
430: }
1.22 ! deraadt 431: if (rename(tempname, ofn) < 0)
1.16 sthen 432: err(2, "can't rename \"%s\" to \"%s\"", tempname, ofn);
433: free(tempname);
434: tempname = NULL;
435: }
436:
437: /*
438: * For cleaning up if there is an error.
439: */
440: static void
441: cleantemp(void)
442: {
443: if (tempname != NULL)
444: remove(tempname);
445: }
446:
447: /*
448: * Self-identification functions.
449: */
450:
451: static void
452: version(void)
453: {
454: const char *c = copyright;
455: for (;;) {
456: while (*++c != '$')
457: if (*c == '\0')
458: exit(0);
459: while (*++c != '$')
460: putc(*c, stderr);
461: putc('\n', stderr);
1.7 deraadt 462: }
1.16 sthen 463: }
1.7 deraadt 464:
1.16 sthen 465: static void
466: synopsis(FILE *fp)
467: {
468: fprintf(fp,
1.17 jmc 469: "usage: unifdef [-BbcdehKkmnSstV] [-[i]Dsym[=val]] [-[i]Usym] [-f defile]\n"
470: " [-M backext] [-o outfile] [-x 0 | 1 | 2] file ...\n");
1.7 deraadt 471: }
1.1 deraadt 472:
1.8 deraadt 473: static void
1.7 deraadt 474: usage(void)
1.1 deraadt 475: {
1.16 sthen 476: synopsis(stderr);
1.8 deraadt 477: exit(2);
478: }
479:
1.16 sthen 480: static void
481: help(void)
482: {
483: synopsis(stdout);
484: printf(
485: " -Dsym=val define preprocessor symbol with given value\n"
486: " -Dsym define preprocessor symbol with value 1\n"
487: " -Usym preprocessor symbol is undefined\n"
488: " -iDsym=val \\ ignore C strings and comments\n"
489: " -iDsym ) in sections controlled by these\n"
490: " -iUsym / preprocessor symbols\n"
491: " -fpath file containing #define and #undef directives\n"
492: " -b blank lines instead of deleting them\n"
493: " -B compress blank lines around deleted section\n"
494: " -c complement (invert) keep vs. delete\n"
495: " -d debugging mode\n"
496: " -e ignore multiline preprocessor directives\n"
497: " -h print help\n"
498: " -Ipath extra include file path (ignored)\n"
499: " -K disable && and || short-circuiting\n"
500: " -k process constant #if expressions\n"
501: " -Mext modify in place and keep backups\n"
502: " -m modify input files in place\n"
503: " -n add #line directives to output\n"
504: " -opath output file name\n"
505: " -S list #if control symbols with nesting\n"
506: " -s list #if control symbols\n"
507: " -t ignore C strings and comments\n"
508: " -V print version\n"
509: " -x{012} exit status mode\n"
510: );
511: exit(0);
512: }
513:
1.8 deraadt 514: /*
515: * A state transition function alters the global #if processing state
516: * in a particular way. The table below is indexed by the current
1.16 sthen 517: * processing state and the type of the current line.
1.8 deraadt 518: *
519: * Nesting is handled by keeping a stack of states; some transition
1.9 deraadt 520: * functions increase or decrease the depth. They also maintain the
1.8 deraadt 521: * ignore state on a stack. In some complicated cases they have to
522: * alter the preprocessor directive, as follows.
523: *
524: * When we have processed a group that starts off with a known-false
525: * #if/#elif sequence (which has therefore been deleted) followed by a
1.9 deraadt 526: * #elif that we don't understand and therefore must keep, we edit the
1.16 sthen 527: * latter into a #if to keep the nesting correct. We use memcpy() to
528: * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
1.8 deraadt 529: *
530: * When we find a true #elif in a group, the following block will
531: * always be kept and the rest of the sequence after the next #elif or
1.9 deraadt 532: * #else will be discarded. We edit the #elif into a #else and the
1.8 deraadt 533: * following directive to #endif since this has the desired behaviour.
1.9 deraadt 534: *
535: * "Dodgy" directives are split across multiple lines, the most common
536: * example being a multi-line comment hanging off the right of the
537: * directive. We can handle them correctly only if there is no change
538: * from printing to dropping (or vice versa) caused by that directive.
539: * If the directive is the first of a group we have a choice between
540: * failing with an error, or passing it through unchanged instead of
541: * evaluating it. The latter is not the default to avoid questions from
542: * users about unifdef unexpectedly leaving behind preprocessor directives.
1.8 deraadt 543: */
544: typedef void state_fn(void);
545:
546: /* report an error */
1.16 sthen 547: static void Eelif (void) { error("Inappropriate #elif"); }
548: static void Eelse (void) { error("Inappropriate #else"); }
549: static void Eendif(void) { error("Inappropriate #endif"); }
550: static void Eeof (void) { error("Premature EOF"); }
551: static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
1.8 deraadt 552: /* plain line handling */
1.16 sthen 553: static void print (void) { flushline(true); }
554: static void drop (void) { flushline(false); }
1.8 deraadt 555: /* output lacks group's start line */
1.16 sthen 556: static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
557: static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
558: static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
1.8 deraadt 559: /* print/pass this block */
1.16 sthen 560: static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
561: static void Pelse (void) { print(); state(IS_PASS_ELSE); }
562: static void Pendif(void) { print(); unnest(); }
1.8 deraadt 563: /* discard this block */
1.16 sthen 564: static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
565: static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
566: static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
567: static void Dendif(void) { drop(); unnest(); }
1.8 deraadt 568: /* first line of group */
1.16 sthen 569: static void Fdrop (void) { nest(); Dfalse(); }
570: static void Fpass (void) { nest(); Pelif(); }
571: static void Ftrue (void) { nest(); Strue(); }
572: static void Ffalse(void) { nest(); Sfalse(); }
1.9 deraadt 573: /* variable pedantry for obfuscated lines */
1.16 sthen 574: static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
575: static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
576: static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
1.8 deraadt 577: /* ignore comments in this block */
1.16 sthen 578: static void Idrop (void) { Fdrop(); ignoreon(); }
579: static void Itrue (void) { Ftrue(); ignoreon(); }
580: static void Ifalse(void) { Ffalse(); ignoreon(); }
581: /* modify this line */
582: static void Mpass (void) { memcpy(keyword, "if ", 4); Pelif(); }
583: static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
584: static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
585: static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
1.8 deraadt 586:
587: static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
588: /* IS_OUTSIDE */
1.9 deraadt 589: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
590: Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
1.16 sthen 591: print, done, abort },
1.8 deraadt 592: /* IS_FALSE_PREFIX */
1.9 deraadt 593: { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
594: Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
1.16 sthen 595: drop, Eeof, abort },
1.8 deraadt 596: /* IS_TRUE_PREFIX */
1.9 deraadt 597: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
598: Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
1.16 sthen 599: print, Eeof, abort },
1.8 deraadt 600: /* IS_PASS_MIDDLE */
1.9 deraadt 601: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
602: Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
1.16 sthen 603: print, Eeof, abort },
1.8 deraadt 604: /* IS_FALSE_MIDDLE */
1.9 deraadt 605: { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
606: Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
1.16 sthen 607: drop, Eeof, abort },
1.8 deraadt 608: /* IS_TRUE_MIDDLE */
1.9 deraadt 609: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
610: Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
1.16 sthen 611: print, Eeof, abort },
1.8 deraadt 612: /* IS_PASS_ELSE */
1.9 deraadt 613: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
614: Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
1.16 sthen 615: print, Eeof, abort },
1.8 deraadt 616: /* IS_FALSE_ELSE */
1.9 deraadt 617: { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
618: Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
1.16 sthen 619: drop, Eeof, abort },
1.8 deraadt 620: /* IS_TRUE_ELSE */
1.9 deraadt 621: { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
622: Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
1.16 sthen 623: print, Eeof, abort },
1.8 deraadt 624: /* IS_FALSE_TRAILER */
1.9 deraadt 625: { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
626: Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
1.16 sthen 627: drop, Eeof, abort }
1.9 deraadt 628: /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
629: TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
1.16 sthen 630: PLAIN EOF ERROR */
1.8 deraadt 631: };
632:
633: /*
634: * State machine utility functions
635: */
636: static void
1.9 deraadt 637: ignoreoff(void)
638: {
1.16 sthen 639: if (depth == 0)
640: abort(); /* bug */
1.9 deraadt 641: ignoring[depth] = ignoring[depth-1];
642: }
643: static void
644: ignoreon(void)
645: {
646: ignoring[depth] = true;
647: }
648: static void
649: keywordedit(const char *replacement)
650: {
1.16 sthen 651: snprintf(keyword, tline + sizeof(tline) - keyword,
652: "%s%s", replacement, newline);
1.9 deraadt 653: print();
654: }
655: static void
1.8 deraadt 656: nest(void)
657: {
1.16 sthen 658: if (depth > MAXDEPTH-1)
659: abort(); /* bug */
660: if (depth == MAXDEPTH-1)
661: error("Too many levels of nesting");
1.8 deraadt 662: depth += 1;
663: stifline[depth] = linenum;
664: }
1.16 sthen 665: static void
666: unnest(void)
667: {
668: if (depth == 0)
669: abort(); /* bug */
670: depth -= 1;
671: }
1.8 deraadt 672: static void
673: state(Ifstate is)
674: {
675: ifstate[depth] = is;
676: }
677:
1.7 deraadt 678: /*
1.16 sthen 679: * The last state transition function. When this is called,
680: * lineval == LT_EOF, so the process() loop will terminate.
681: */
682: static void
683: done(void)
684: {
685: if (incomment)
686: error("EOF in comment");
687: closeio();
688: }
689:
690: /*
1.8 deraadt 691: * Write a line to the output or not, according to command line options.
1.16 sthen 692: * If writing fails, closeio() will print the error and exit.
1.8 deraadt 693: */
694: static void
695: flushline(bool keep)
696: {
697: if (symlist)
698: return;
1.16 sthen 699: if (keep ^ complement) {
700: bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
701: if (blankline && compblank && blankcount != blankmax) {
702: delcount += 1;
703: blankcount += 1;
704: } else {
705: if (lnnum && delcount > 0)
706: hashline();
707: if (fputs(tline, output) == EOF)
708: closeio();
709: delcount = 0;
710: blankmax = blankcount = blankline ? blankcount + 1 : 0;
711: }
712: } else {
713: if (lnblank && fputs(newline, output) == EOF)
714: closeio();
1.8 deraadt 715: exitstat = 1;
1.16 sthen 716: delcount += 1;
717: blankcount = 0;
1.7 deraadt 718: }
1.16 sthen 719: if (debugging && fflush(output) == EOF)
720: closeio();
721: }
722:
723: /*
724: * Format of #line directives depends on whether we know the input filename.
725: */
726: static void
727: hashline(void)
728: {
729: int e;
730:
731: if (linefile == NULL)
732: e = fprintf(output, "#line %d%s", linenum, newline);
733: else
734: e = fprintf(output, "#line %d \"%s\"%s",
735: linenum, linefile, newline);
736: if (e < 0)
737: closeio();
738: }
739:
740: /*
741: * Flush the output and handle errors.
742: */
743: static void
744: closeio(void)
745: {
746: /* Tidy up after findsym(). */
747: if (symdepth && !zerosyms)
748: printf("\n");
749: if (output != NULL && (ferror(output) || fclose(output) == EOF))
750: err(2, "%s: can't write to output", filename);
751: fclose(input);
1.7 deraadt 752: }
1.3 deraadt 753:
1.7 deraadt 754: /*
1.8 deraadt 755: * The driver for the state machine.
1.7 deraadt 756: */
1.8 deraadt 757: static void
758: process(void)
1.7 deraadt 759: {
1.16 sthen 760: Linetype lineval = LT_PLAIN;
761: /* When compressing blank lines, act as if the file
762: is preceded by a large number of blank lines. */
763: blankmax = blankcount = 1000;
764: zerosyms = true;
765: newline = NULL;
766: linenum = 0;
767: while (lineval != LT_EOF) {
768: lineval = parseline();
769: trans_table[ifstate[depth]][lineval]();
770: debug("process line %d %s -> %s depth %d",
771: linenum, linetype_name[lineval],
1.8 deraadt 772: ifstate_name[ifstate[depth]], depth);
1.1 deraadt 773: }
774: }
775:
1.7 deraadt 776: /*
1.8 deraadt 777: * Parse a line and determine its type. We keep the preprocessor line
1.16 sthen 778: * parser state between calls in the global variable linestate, with
779: * help from skipcomment().
1.7 deraadt 780: */
1.8 deraadt 781: static Linetype
1.16 sthen 782: parseline(void)
1.3 deraadt 783: {
1.7 deraadt 784: const char *cp;
1.8 deraadt 785: int cursym;
1.3 deraadt 786: Linetype retval;
1.8 deraadt 787: Comment_state wascomment;
1.3 deraadt 788:
1.16 sthen 789: wascomment = incomment;
790: cp = skiphash();
791: if (cp == NULL)
1.8 deraadt 792: return (LT_EOF);
1.16 sthen 793: if (newline == NULL) {
794: if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
795: newline = newline_crlf;
796: else
797: newline = newline_unix;
798: }
799: if (*cp == '\0') {
800: retval = LT_PLAIN;
801: goto done;
1.8 deraadt 802: }
1.16 sthen 803: keyword = tline + (cp - tline);
804: if ((cp = matchsym("ifdef", keyword)) != NULL ||
805: (cp = matchsym("ifndef", keyword)) != NULL) {
806: cp = skipcomment(cp);
807: if ((cursym = findsym(&cp)) < 0)
808: retval = LT_IF;
809: else {
810: retval = (keyword[2] == 'n')
811: ? LT_FALSE : LT_TRUE;
812: if (value[cursym] == NULL)
813: retval = (retval == LT_TRUE)
814: ? LT_FALSE : LT_TRUE;
815: if (ignore[cursym])
816: retval = (retval == LT_TRUE)
817: ? LT_TRUEI : LT_FALSEI;
818: }
819: } else if ((cp = matchsym("if", keyword)) != NULL)
820: retval = ifeval(&cp);
821: else if ((cp = matchsym("elif", keyword)) != NULL)
822: retval = linetype_if2elif(ifeval(&cp));
823: else if ((cp = matchsym("else", keyword)) != NULL)
824: retval = LT_ELSE;
825: else if ((cp = matchsym("endif", keyword)) != NULL)
826: retval = LT_ENDIF;
827: else {
828: cp = skipsym(keyword);
1.9 deraadt 829: /* no way can we deal with a continuation inside a keyword */
1.16 sthen 830: if (strncmp(cp, "\\\r\n", 3) == 0 ||
831: strncmp(cp, "\\\n", 2) == 0)
1.8 deraadt 832: Eioccc();
1.16 sthen 833: cp = skipline(cp);
834: retval = LT_PLAIN;
835: goto done;
836: }
837: cp = skipcomment(cp);
838: if (*cp != '\0') {
839: cp = skipline(cp);
840: if (retval == LT_TRUE || retval == LT_FALSE ||
841: retval == LT_TRUEI || retval == LT_FALSEI)
842: retval = LT_IF;
843: if (retval == LT_ELTRUE || retval == LT_ELFALSE)
844: retval = LT_ELIF;
845: }
846: /* the following can happen if the last line of the file lacks a
847: newline or if there is too much whitespace in a directive */
848: if (linestate == LS_HASH) {
849: long len = cp - tline;
850: if (fgets(tline + len, MAXLINE - len, input) == NULL) {
851: if (ferror(input))
852: err(2, "can't read %s", filename);
853: /* append the missing newline at eof */
1.18 miod 854: strlcpy(tline + len, newline, sizeof(tline) - len);
1.16 sthen 855: cp += strlen(newline);
856: linestate = LS_START;
857: } else {
1.8 deraadt 858: linestate = LS_DIRTY;
1.7 deraadt 859: }
860: }
1.16 sthen 861: if (retval != LT_PLAIN && (wascomment || linestate != LS_START)) {
862: retval = linetype_2dodgy(retval);
863: linestate = LS_DIRTY;
1.8 deraadt 864: }
1.16 sthen 865: done:
866: debug("parser line %d state %s comment %s line", linenum,
1.8 deraadt 867: comment_name[incomment], linestate_name[linestate]);
1.7 deraadt 868: return (retval);
869: }
870:
871: /*
1.16 sthen 872: * These are the binary operators that are supported by the expression
873: * evaluator.
1.7 deraadt 874: */
1.16 sthen 875: static Linetype op_strict(long *p, long v, Linetype at, Linetype bt) {
876: if(at == LT_IF || bt == LT_IF) return (LT_IF);
877: return (*p = v, v ? LT_TRUE : LT_FALSE);
878: }
879: static Linetype op_lt(long *p, Linetype at, long a, Linetype bt, long b) {
880: return op_strict(p, a < b, at, bt);
1.8 deraadt 881: }
1.16 sthen 882: static Linetype op_gt(long *p, Linetype at, long a, Linetype bt, long b) {
883: return op_strict(p, a > b, at, bt);
1.8 deraadt 884: }
1.16 sthen 885: static Linetype op_le(long *p, Linetype at, long a, Linetype bt, long b) {
886: return op_strict(p, a <= b, at, bt);
1.8 deraadt 887: }
1.16 sthen 888: static Linetype op_ge(long *p, Linetype at, long a, Linetype bt, long b) {
889: return op_strict(p, a >= b, at, bt);
1.8 deraadt 890: }
1.16 sthen 891: static Linetype op_eq(long *p, Linetype at, long a, Linetype bt, long b) {
892: return op_strict(p, a == b, at, bt);
1.8 deraadt 893: }
1.16 sthen 894: static Linetype op_ne(long *p, Linetype at, long a, Linetype bt, long b) {
895: return op_strict(p, a != b, at, bt);
1.8 deraadt 896: }
1.16 sthen 897: static Linetype op_or(long *p, Linetype at, long a, Linetype bt, long b) {
898: if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
899: return (*p = 1, LT_TRUE);
900: return op_strict(p, a || b, at, bt);
1.8 deraadt 901: }
1.16 sthen 902: static Linetype op_and(long *p, Linetype at, long a, Linetype bt, long b) {
903: if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
904: return (*p = 0, LT_FALSE);
905: return op_strict(p, a && b, at, bt);
1.7 deraadt 906: }
907:
908: /*
1.8 deraadt 909: * An evaluation function takes three arguments, as follows: (1) a pointer to
910: * an element of the precedence table which lists the operators at the current
911: * level of precedence; (2) a pointer to an integer which will receive the
912: * value of the expression; and (3) a pointer to a char* that points to the
913: * expression to be evaluated and that is updated to the end of the expression
914: * when evaluation is complete. The function returns LT_FALSE if the value of
1.16 sthen 915: * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
916: * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
1.7 deraadt 917: */
1.8 deraadt 918: struct ops;
919:
1.16 sthen 920: typedef Linetype eval_fn(const struct ops *, long *, const char **);
1.8 deraadt 921:
922: static eval_fn eval_table, eval_unary;
923:
924: /*
925: * The precedence table. Expressions involving binary operators are evaluated
926: * in a table-driven way by eval_table. When it evaluates a subexpression it
927: * calls the inner function with its first argument pointing to the next
928: * element of the table. Innermost expressions have special non-table-driven
929: * handling.
930: */
1.16 sthen 931: struct op {
932: const char *str;
933: Linetype (*fn)(long *, Linetype, long, Linetype, long);
934: };
935: struct ops {
1.8 deraadt 936: eval_fn *inner;
1.16 sthen 937: struct op op[5];
938: };
939: static const struct ops eval_ops[] = {
1.8 deraadt 940: { eval_table, { { "||", op_or } } },
941: { eval_table, { { "&&", op_and } } },
942: { eval_table, { { "==", op_eq },
943: { "!=", op_ne } } },
944: { eval_unary, { { "<=", op_le },
945: { ">=", op_ge },
946: { "<", op_lt },
947: { ">", op_gt } } }
948: };
1.7 deraadt 949:
1.16 sthen 950: /* Current operator precedence level */
951: static long prec(const struct ops *ops)
952: {
953: return (ops - eval_ops);
954: }
955:
1.7 deraadt 956: /*
957: * Function for evaluating the innermost parts of expressions,
1.16 sthen 958: * viz. !expr (expr) number defined(symbol) symbol
959: * We reset the constexpr flag in the last two cases.
1.7 deraadt 960: */
1.8 deraadt 961: static Linetype
1.16 sthen 962: eval_unary(const struct ops *ops, long *valp, const char **cpp)
1.7 deraadt 963: {
964: const char *cp;
965: char *ep;
966: int sym;
1.16 sthen 967: bool defparen;
968: Linetype lt;
1.7 deraadt 969:
970: cp = skipcomment(*cpp);
1.8 deraadt 971: if (*cp == '!') {
1.16 sthen 972: debug("eval%d !", prec(ops));
1.7 deraadt 973: cp++;
1.16 sthen 974: lt = eval_unary(ops, valp, &cp);
975: if (lt == LT_ERROR)
976: return (LT_ERROR);
977: if (lt != LT_IF) {
978: *valp = !*valp;
979: lt = *valp ? LT_TRUE : LT_FALSE;
980: }
1.7 deraadt 981: } else if (*cp == '(') {
982: cp++;
1.16 sthen 983: debug("eval%d (", prec(ops));
984: lt = eval_table(eval_ops, valp, &cp);
985: if (lt == LT_ERROR)
986: return (LT_ERROR);
1.7 deraadt 987: cp = skipcomment(cp);
988: if (*cp++ != ')')
1.16 sthen 989: return (LT_ERROR);
1.7 deraadt 990: } else if (isdigit((unsigned char)*cp)) {
1.16 sthen 991: debug("eval%d number", prec(ops));
1.7 deraadt 992: *valp = strtol(cp, &ep, 0);
1.16 sthen 993: if (ep == cp)
994: return (LT_ERROR);
995: lt = *valp ? LT_TRUE : LT_FALSE;
996: cp = ep;
997: } else if (matchsym("defined", cp) != NULL) {
1.7 deraadt 998: cp = skipcomment(cp+7);
1.16 sthen 999: if (*cp == '(') {
1000: cp = skipcomment(cp+1);
1001: defparen = true;
1002: } else {
1003: defparen = false;
1004: }
1005: sym = findsym(&cp);
1.7 deraadt 1006: cp = skipcomment(cp);
1.16 sthen 1007: if (defparen && *cp++ != ')') {
1008: debug("eval%d defined missing ')'", prec(ops));
1009: return (LT_ERROR);
1010: }
1011: if (sym < 0) {
1012: debug("eval%d defined unknown", prec(ops));
1013: lt = LT_IF;
1014: } else {
1015: debug("eval%d defined %s", prec(ops), symname[sym]);
1016: *valp = (value[sym] != NULL);
1017: lt = *valp ? LT_TRUE : LT_FALSE;
1018: }
1019: constexpr = false;
1.7 deraadt 1020: } else if (!endsym(*cp)) {
1.16 sthen 1021: debug("eval%d symbol", prec(ops));
1022: sym = findsym(&cp);
1023: if (sym < 0) {
1024: lt = LT_IF;
1025: cp = skipargs(cp);
1026: } else if (value[sym] == NULL) {
1.7 deraadt 1027: *valp = 0;
1.16 sthen 1028: lt = LT_FALSE;
1029: } else {
1.7 deraadt 1030: *valp = strtol(value[sym], &ep, 0);
1031: if (*ep != '\0' || ep == value[sym])
1.16 sthen 1032: return (LT_ERROR);
1033: lt = *valp ? LT_TRUE : LT_FALSE;
1034: cp = skipargs(cp);
1.7 deraadt 1035: }
1.16 sthen 1036: constexpr = false;
1037: } else {
1038: debug("eval%d bad expr", prec(ops));
1039: return (LT_ERROR);
1040: }
1.7 deraadt 1041:
1042: *cpp = cp;
1.16 sthen 1043: debug("eval%d = %d", prec(ops), *valp);
1044: return (lt);
1.7 deraadt 1045: }
1046:
1047: /*
1048: * Table-driven evaluation of binary operators.
1049: */
1.8 deraadt 1050: static Linetype
1.16 sthen 1051: eval_table(const struct ops *ops, long *valp, const char **cpp)
1.7 deraadt 1052: {
1.8 deraadt 1053: const struct op *op;
1.7 deraadt 1054: const char *cp;
1.16 sthen 1055: long val;
1056: Linetype lt, rt;
1.7 deraadt 1057:
1.16 sthen 1058: debug("eval%d", prec(ops));
1.7 deraadt 1059: cp = *cpp;
1.16 sthen 1060: lt = ops->inner(ops+1, valp, &cp);
1061: if (lt == LT_ERROR)
1062: return (LT_ERROR);
1.7 deraadt 1063: for (;;) {
1064: cp = skipcomment(cp);
1065: for (op = ops->op; op->str != NULL; op++)
1066: if (strncmp(cp, op->str, strlen(op->str)) == 0)
1067: break;
1068: if (op->str == NULL)
1069: break;
1070: cp += strlen(op->str);
1.16 sthen 1071: debug("eval%d %s", prec(ops), op->str);
1072: rt = ops->inner(ops+1, &val, &cp);
1073: if (rt == LT_ERROR)
1074: return (LT_ERROR);
1075: lt = op->fn(valp, lt, *valp, rt, val);
1.7 deraadt 1076: }
1077:
1078: *cpp = cp;
1.16 sthen 1079: debug("eval%d = %d", prec(ops), *valp);
1080: debug("eval%d lt = %s", prec(ops), linetype_name[lt]);
1081: return (lt);
1.1 deraadt 1082: }
1.7 deraadt 1083:
1.1 deraadt 1084: /*
1.7 deraadt 1085: * Evaluate the expression on a #if or #elif line. If we can work out
1086: * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
1.8 deraadt 1087: * return just a generic LT_IF.
1.1 deraadt 1088: */
1.8 deraadt 1089: static Linetype
1.7 deraadt 1090: ifeval(const char **cpp)
1091: {
1.16 sthen 1092: Linetype ret;
1093: long val = 0;
1.7 deraadt 1094:
1095: debug("eval %s", *cpp);
1.16 sthen 1096: constexpr = killconsts ? false : true;
1.8 deraadt 1097: ret = eval_table(eval_ops, &val, cpp);
1.16 sthen 1098: debug("eval = %d", val);
1099: return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
1100: }
1101:
1102: /*
1103: * Read a line and examine its initial part to determine if it is a
1104: * preprocessor directive. Returns NULL on EOF, or a pointer to a
1105: * preprocessor directive name, or a pointer to the zero byte at the
1106: * end of the line.
1107: */
1108: static const char *
1109: skiphash(void)
1110: {
1111: const char *cp;
1112:
1113: linenum++;
1114: if (fgets(tline, MAXLINE, input) == NULL) {
1115: if (ferror(input))
1116: err(2, "can't read %s", filename);
1117: else
1118: return (NULL);
1119: }
1120: cp = skipcomment(tline);
1121: if (linestate == LS_START && *cp == '#') {
1122: linestate = LS_HASH;
1123: return (skipcomment(cp + 1));
1124: } else if (*cp == '\0') {
1125: return (cp);
1126: } else {
1127: return (skipline(cp));
1128: }
1129: }
1130:
1131: /*
1132: * Mark a line dirty and consume the rest of it, keeping track of the
1133: * lexical state.
1134: */
1135: static const char *
1136: skipline(const char *cp)
1137: {
1138: if (*cp != '\0')
1139: linestate = LS_DIRTY;
1140: while (*cp != '\0')
1141: cp = skipcomment(cp + 1);
1142: return (cp);
1.7 deraadt 1143: }
1144:
1145: /*
1.16 sthen 1146: * Skip over comments, strings, and character literals and stop at the
1147: * next character position that is not whitespace. Between calls we keep
1148: * the comment state in the global variable incomment, and we also adjust
1149: * the global variable linestate when we see a newline.
1.8 deraadt 1150: * XXX: doesn't cope with the buffer splitting inside a state transition.
1.7 deraadt 1151: */
1.8 deraadt 1152: static const char *
1.7 deraadt 1153: skipcomment(const char *cp)
1.3 deraadt 1154: {
1.8 deraadt 1155: if (text || ignoring[depth]) {
1.11 avsm 1156: for (; isspace((unsigned char)*cp); cp++)
1157: if (*cp == '\n')
1158: linestate = LS_START;
1.8 deraadt 1159: return (cp);
1160: }
1161: while (*cp != '\0')
1.16 sthen 1162: /* don't reset to LS_START after a line continuation */
1163: if (strncmp(cp, "\\\r\n", 3) == 0)
1164: cp += 3;
1165: else if (strncmp(cp, "\\\n", 2) == 0)
1.8 deraadt 1166: cp += 2;
1167: else switch (incomment) {
1168: case NO_COMMENT:
1.16 sthen 1169: if (strncmp(cp, "/\\\r\n", 4) == 0) {
1170: incomment = STARTING_COMMENT;
1171: cp += 4;
1172: } else if (strncmp(cp, "/\\\n", 3) == 0) {
1.8 deraadt 1173: incomment = STARTING_COMMENT;
1174: cp += 3;
1175: } else if (strncmp(cp, "/*", 2) == 0) {
1.3 deraadt 1176: incomment = C_COMMENT;
1.8 deraadt 1177: cp += 2;
1178: } else if (strncmp(cp, "//", 2) == 0) {
1179: incomment = CXX_COMMENT;
1180: cp += 2;
1.16 sthen 1181: } else if (strncmp(cp, "\'", 1) == 0) {
1182: incomment = CHAR_LITERAL;
1183: linestate = LS_DIRTY;
1184: cp += 1;
1185: } else if (strncmp(cp, "\"", 1) == 0) {
1186: incomment = STRING_LITERAL;
1187: linestate = LS_DIRTY;
1188: cp += 1;
1.8 deraadt 1189: } else if (strncmp(cp, "\n", 1) == 0) {
1190: linestate = LS_START;
1191: cp += 1;
1.16 sthen 1192: } else if (strchr(" \r\t", *cp) != NULL) {
1.8 deraadt 1193: cp += 1;
1194: } else
1195: return (cp);
1196: continue;
1197: case CXX_COMMENT:
1198: if (strncmp(cp, "\n", 1) == 0) {
1199: incomment = NO_COMMENT;
1200: linestate = LS_START;
1.3 deraadt 1201: }
1.8 deraadt 1202: cp += 1;
1203: continue;
1.16 sthen 1204: case CHAR_LITERAL:
1205: case STRING_LITERAL:
1206: if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
1207: (incomment == STRING_LITERAL && cp[0] == '\"')) {
1208: incomment = NO_COMMENT;
1209: cp += 1;
1210: } else if (cp[0] == '\\') {
1211: if (cp[1] == '\0')
1212: cp += 1;
1213: else
1214: cp += 2;
1215: } else if (strncmp(cp, "\n", 1) == 0) {
1216: if (incomment == CHAR_LITERAL)
1217: error("unterminated char literal");
1218: else
1219: error("unterminated string literal");
1220: } else
1221: cp += 1;
1222: continue;
1.8 deraadt 1223: case C_COMMENT:
1.16 sthen 1224: if (strncmp(cp, "*\\\r\n", 4) == 0) {
1225: incomment = FINISHING_COMMENT;
1226: cp += 4;
1227: } else if (strncmp(cp, "*\\\n", 3) == 0) {
1.8 deraadt 1228: incomment = FINISHING_COMMENT;
1229: cp += 3;
1230: } else if (strncmp(cp, "*/", 2) == 0) {
1231: incomment = NO_COMMENT;
1232: cp += 2;
1233: } else
1234: cp += 1;
1235: continue;
1236: case STARTING_COMMENT:
1237: if (*cp == '*') {
1238: incomment = C_COMMENT;
1239: cp += 1;
1240: } else if (*cp == '/') {
1.3 deraadt 1241: incomment = CXX_COMMENT;
1.8 deraadt 1242: cp += 1;
1243: } else {
1244: incomment = NO_COMMENT;
1245: linestate = LS_DIRTY;
1.3 deraadt 1246: }
1.8 deraadt 1247: continue;
1248: case FINISHING_COMMENT:
1249: if (*cp == '/') {
1250: incomment = NO_COMMENT;
1251: cp += 1;
1252: } else
1253: incomment = C_COMMENT;
1254: continue;
1255: default:
1.16 sthen 1256: abort(); /* bug */
1.3 deraadt 1257: }
1.8 deraadt 1258: return (cp);
1.1 deraadt 1259: }
1.7 deraadt 1260:
1261: /*
1.16 sthen 1262: * Skip macro arguments.
1263: */
1264: static const char *
1265: skipargs(const char *cp)
1266: {
1267: const char *ocp = cp;
1268: int level = 0;
1269: cp = skipcomment(cp);
1270: if (*cp != '(')
1271: return (cp);
1272: do {
1273: if (*cp == '(')
1274: level++;
1275: if (*cp == ')')
1276: level--;
1277: cp = skipcomment(cp+1);
1278: } while (level != 0 && *cp != '\0');
1279: if (level == 0)
1280: return (cp);
1281: else
1282: /* Rewind and re-detect the syntax error later. */
1283: return (ocp);
1284: }
1285:
1286: /*
1.7 deraadt 1287: * Skip over an identifier.
1288: */
1.8 deraadt 1289: static const char *
1.7 deraadt 1290: skipsym(const char *cp)
1291: {
1292: while (!endsym(*cp))
1293: ++cp;
1294: return (cp);
1295: }
1296:
1.1 deraadt 1297: /*
1.16 sthen 1298: * Skip whitespace and take a copy of any following identifier.
1299: */
1300: static const char *
1301: getsym(const char **cpp)
1302: {
1303: const char *cp = *cpp, *sym;
1304:
1305: cp = skipcomment(cp);
1306: cp = skipsym(sym = cp);
1307: if (cp == sym)
1308: return NULL;
1309: *cpp = cp;
1310: return (xstrdup(sym, cp));
1311: }
1312:
1313: /*
1314: * Check that s (a symbol) matches the start of t, and that the
1315: * following character in t is not a symbol character. Returns a
1316: * pointer to the following character in t if there is a match,
1317: * otherwise NULL.
1318: */
1319: static const char *
1320: matchsym(const char *s, const char *t)
1321: {
1322: while (*s != '\0' && *t != '\0')
1323: if (*s != *t)
1324: return (NULL);
1325: else
1326: ++s, ++t;
1327: if (*s == '\0' && endsym(*t))
1328: return(t);
1329: else
1330: return(NULL);
1331: }
1332:
1333: /*
1.13 jmc 1334: * Look for the symbol in the symbol table. If it is found, we return
1.8 deraadt 1335: * the symbol table index, else we return -1.
1.1 deraadt 1336: */
1.8 deraadt 1337: static int
1.16 sthen 1338: findsym(const char **strp)
1.1 deraadt 1339: {
1.16 sthen 1340: const char *str;
1.3 deraadt 1341: int symind;
1342:
1.16 sthen 1343: str = *strp;
1344: *strp = skipsym(str);
1345: if (symlist) {
1346: if (*strp == str)
1347: return (-1);
1348: if (symdepth && firstsym)
1349: printf("%s%3d", zerosyms ? "" : "\n", depth);
1350: firstsym = zerosyms = false;
1351: printf("%s%.*s%s",
1352: symdepth ? " " : "",
1353: (int)(*strp-str), str,
1354: symdepth ? "" : "\n");
1355: /* we don't care about the value of the symbol */
1356: return (0);
1357: }
1.8 deraadt 1358: for (symind = 0; symind < nsyms; ++symind) {
1.16 sthen 1359: if (matchsym(symname[symind], str) != NULL) {
1360: debugsym("findsym", symind);
1.7 deraadt 1361: return (symind);
1.3 deraadt 1362: }
1.1 deraadt 1363: }
1.8 deraadt 1364: return (-1);
1.1 deraadt 1365: }
1.7 deraadt 1366:
1.1 deraadt 1367: /*
1.16 sthen 1368: * Resolve indirect symbol values to their final definitions.
1369: */
1370: static void
1371: indirectsym(void)
1372: {
1373: const char *cp;
1374: int changed, sym, ind;
1375:
1376: do {
1377: changed = 0;
1378: for (sym = 0; sym < nsyms; ++sym) {
1379: if (value[sym] == NULL)
1380: continue;
1381: cp = value[sym];
1382: ind = findsym(&cp);
1383: if (ind == -1 || ind == sym ||
1384: *cp != '\0' ||
1385: value[ind] == NULL ||
1386: value[ind] == value[sym])
1387: continue;
1388: debugsym("indir...", sym);
1389: value[sym] = value[ind];
1390: debugsym("...ectsym", sym);
1391: changed++;
1392: }
1393: } while (changed);
1394: }
1395:
1396: /*
1397: * Add a symbol to the symbol table, specified with the format sym=val
1398: */
1399: static void
1400: addsym1(bool ignorethis, bool definethis, char *symval)
1401: {
1402: const char *sym, *val;
1403:
1404: sym = symval;
1405: val = skipsym(sym);
1406: if (definethis && *val == '=') {
1407: symval[val - sym] = '\0';
1408: val = val + 1;
1409: } else if (*val == '\0') {
1410: val = definethis ? "1" : NULL;
1411: } else {
1412: usage();
1413: }
1414: addsym2(ignorethis, sym, val);
1415: }
1416:
1417: /*
1.7 deraadt 1418: * Add a symbol to the symbol table.
1419: */
1.8 deraadt 1420: static void
1.16 sthen 1421: addsym2(bool ignorethis, const char *sym, const char *val)
1.7 deraadt 1422: {
1.16 sthen 1423: const char *cp = sym;
1.7 deraadt 1424: int symind;
1425:
1.16 sthen 1426: symind = findsym(&cp);
1.8 deraadt 1427: if (symind < 0) {
1.7 deraadt 1428: if (nsyms >= MAXSYMS)
1429: errx(2, "too many symbols");
1430: symind = nsyms++;
1431: }
1.16 sthen 1432: ignore[symind] = ignorethis;
1.7 deraadt 1433: symname[symind] = sym;
1.16 sthen 1434: value[symind] = val;
1435: debugsym("addsym", symind);
1436: }
1437:
1438: static void
1439: debugsym(const char *why, int symind)
1440: {
1441: debug("%s %s%c%s", why, symname[symind],
1442: value[symind] ? '=' : ' ',
1443: value[symind] ? value[symind] : "undef");
1444: }
1445:
1446: /*
1447: * Add symbols to the symbol table from a file containing
1448: * #define and #undef preprocessor directives.
1449: */
1450: static void
1451: defundefile(const char *fn)
1452: {
1453: filename = fn;
1454: input = fopen(fn, "rb");
1455: if (input == NULL)
1456: err(2, "can't open %s", fn);
1457: linenum = 0;
1458: while (defundef())
1459: ;
1460: if (ferror(input))
1461: err(2, "can't read %s", filename);
1462: else
1463: fclose(input);
1464: if (incomment)
1465: error("EOF in comment");
1466: }
1467:
1468: /*
1469: * Read and process one #define or #undef directive
1470: */
1471: static bool
1472: defundef(void)
1473: {
1474: const char *cp, *kw, *sym, *val, *end;
1475:
1476: cp = skiphash();
1477: if (cp == NULL)
1478: return (false);
1479: if (*cp == '\0')
1480: goto done;
1481: /* strip trailing whitespace, and do a fairly rough check to
1482: avoid unsupported multi-line preprocessor directives */
1483: end = cp + strlen(cp);
1484: while (end > tline && strchr(" \t\n\r", end[-1]) != NULL)
1485: --end;
1486: if (end > tline && end[-1] == '\\')
1487: Eioccc();
1488:
1489: kw = cp;
1490: if ((cp = matchsym("define", kw)) != NULL) {
1491: sym = getsym(&cp);
1492: if (sym == NULL)
1493: error("missing macro name in #define");
1494: if (*cp == '(') {
1495: val = "1";
1496: } else {
1497: cp = skipcomment(cp);
1498: val = (cp < end) ? xstrdup(cp, end) : "";
1499: }
1500: debug("#define");
1501: addsym2(false, sym, val);
1502: } else if ((cp = matchsym("undef", kw)) != NULL) {
1503: sym = getsym(&cp);
1504: if (sym == NULL)
1505: error("missing macro name in #undef");
1506: cp = skipcomment(cp);
1507: debug("#undef");
1508: addsym2(false, sym, NULL);
1.7 deraadt 1509: } else {
1.16 sthen 1510: error("unrecognized preprocessor directive");
1.7 deraadt 1511: }
1.16 sthen 1512: skipline(cp);
1513: done:
1514: debug("parser line %d state %s comment %s line", linenum,
1515: comment_name[incomment], linestate_name[linestate]);
1516: return (true);
1517: }
1518:
1519: /*
1520: * Concatenate two strings into new memory, checking for failure.
1521: */
1522: static char *
1523: astrcat(const char *s1, const char *s2)
1524: {
1525: char *s;
1526: int len;
1527: size_t size;
1528:
1529: len = snprintf(NULL, 0, "%s%s", s1, s2);
1530: if (len < 0)
1531: err(2, "snprintf");
1532: size = (size_t)len + 1;
1.20 deraadt 1533: s = malloc(size);
1.16 sthen 1534: if (s == NULL)
1535: err(2, "malloc");
1536: snprintf(s, size, "%s%s", s1, s2);
1537: return (s);
1.7 deraadt 1538: }
1539:
1540: /*
1.16 sthen 1541: * Duplicate a segment of a string, checking for failure.
1.1 deraadt 1542: */
1.16 sthen 1543: static const char *
1544: xstrdup(const char *start, const char *end)
1.3 deraadt 1545: {
1.16 sthen 1546: size_t n;
1547: char *s;
1548:
1549: if (end < start) abort(); /* bug */
1550: n = (size_t)(end - start) + 1;
1551: s = malloc(n);
1552: if (s == NULL)
1553: err(2, "malloc");
1554: snprintf(s, n, "%s", start);
1555: return (s);
1.1 deraadt 1556: }
1557:
1.7 deraadt 1558: /*
1.8 deraadt 1559: * Diagnostics.
1.7 deraadt 1560: */
1.8 deraadt 1561: static void
1.7 deraadt 1562: debug(const char *msg, ...)
1.1 deraadt 1563: {
1.7 deraadt 1564: va_list ap;
1565:
1566: if (debugging) {
1567: va_start(ap, msg);
1568: vwarnx(msg, ap);
1569: va_end(ap);
1570: }
1.1 deraadt 1571: }
1572:
1.8 deraadt 1573: static void
1574: error(const char *msg)
1.7 deraadt 1575: {
1.8 deraadt 1576: if (depth == 0)
1.9 deraadt 1577: warnx("%s: %d: %s", filename, linenum, msg);
1.7 deraadt 1578: else
1.9 deraadt 1579: warnx("%s: %d: %s (#if line %d depth %d)",
1.8 deraadt 1580: filename, linenum, msg, stifline[depth], depth);
1.16 sthen 1581: closeio();
1.9 deraadt 1582: errx(2, "output may be truncated");
1.22 ! deraadt 1583: }
! 1584:
! 1585: static FILE *
! 1586: mktempmode(char *tmp, int mode)
! 1587: {
! 1588: int fd = mkstemp(tmp);
! 1589: if (fd < 0)
! 1590: return (NULL);
! 1591: fchmod(fd, mode & (S_IRWXU|S_IRWXG|S_IRWXO));
! 1592: return (fdopen(fd, "wb"));
1.1 deraadt 1593: }