]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/unifdef/unifdef.c
Add a -o outfile option, which can be used to specify an output file. The
[FreeBSD/FreeBSD.git] / usr.bin / unifdef / unifdef.c
1 /*
2  * Copyright (c) 2002 - 2010 Tony Finch <dot@dotat.at>
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  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
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  *
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  *
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
41  *
42  *   The first two items above require better buffer handling, which would
43  *     also make it possible to handle all "dodgy" directives correctly.
44  */
45
46 #include <sys/types.h>
47 #include <sys/stat.h>
48
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <stdarg.h>
53 #include <stdbool.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58
59 #ifdef __IDSTRING
60 __IDSTRING(dotat, "$dotat: unifdef/unifdef.c,v 1.193 2010/01/19 18:03:02 fanf2 Exp $");
61 #endif
62 #ifdef __FBSDID
63 __FBSDID("$FreeBSD$");
64 #endif
65
66 /* types of input lines: */
67 typedef enum {
68         LT_TRUEI,               /* a true #if with ignore flag */
69         LT_FALSEI,              /* a false #if with ignore flag */
70         LT_IF,                  /* an unknown #if */
71         LT_TRUE,                /* a true #if */
72         LT_FALSE,               /* a false #if */
73         LT_ELIF,                /* an unknown #elif */
74         LT_ELTRUE,              /* a true #elif */
75         LT_ELFALSE,             /* a false #elif */
76         LT_ELSE,                /* #else */
77         LT_ENDIF,               /* #endif */
78         LT_DODGY,               /* flag: directive is not on one line */
79         LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
80         LT_PLAIN,               /* ordinary line */
81         LT_EOF,                 /* end of file */
82         LT_ERROR,               /* unevaluable #if */
83         LT_COUNT
84 } Linetype;
85
86 static char const * const linetype_name[] = {
87         "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
88         "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
89         "DODGY TRUEI", "DODGY FALSEI",
90         "DODGY IF", "DODGY TRUE", "DODGY FALSE",
91         "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
92         "DODGY ELSE", "DODGY ENDIF",
93         "PLAIN", "EOF", "ERROR"
94 };
95
96 /* state of #if processing */
97 typedef enum {
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 */
124         FINISHING_COMMENT,      /* star-backslash-newline in a C comment */
125         CHAR_LITERAL,           /* inside '' */
126         STRING_LITERAL          /* inside "" */
127 } Comment_state;
128
129 static char const * const comment_name[] = {
130         "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
131 };
132
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;
139
140 static char const * const linestate_name[] = {
141         "START", "HASH", "DIRTY"
142 };
143
144 /*
145  * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
146  */
147 #define MAXDEPTH        64                      /* maximum #if nesting */
148 #define MAXLINE         4096                    /* maximum length of line */
149 #define MAXSYMS         4096                    /* maximum number of symbols */
150
151 /*
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 /*
158  * For temporary filenames
159  */
160 #define TEMPLATE        "unifdef.XXXXXX"
161
162 /*
163  * Globals.
164  */
165
166 static bool             compblank;              /* -B: compress blank lines */
167 static bool             lnblank;                /* -b: blank deleted lines */
168 static bool             complement;             /* -c: do the complement */
169 static bool             debugging;              /* -d: debugging reports */
170 static bool             iocccok;                /* -e: fewer IOCCC errors */
171 static bool             strictlogic;            /* -K: keep ambiguous #ifs */
172 static bool             killconsts;             /* -k: eval constant #ifs */
173 static bool             lnnum;                  /* -n: add #line directives */
174 static bool             symlist;                /* -s: output symbol list */
175 static bool             text;                   /* -t: this is a text file */
176
177 static const char      *symname[MAXSYMS];       /* symbol name */
178 static const char      *value[MAXSYMS];         /* -Dsym=value */
179 static bool             ignore[MAXSYMS];        /* -iDsym or -iUsym */
180 static int              nsyms;                  /* number of symbols */
181
182 static FILE            *input;                  /* input file pointer */
183 static const char      *filename;               /* input file name */
184 static int              linenum;                /* current line number */
185 static FILE            *output;                 /* output file pointer */
186 static const char      *ofilename;              /* output file name */
187 static bool             overwriting;            /* output overwrites input */
188 static char             tempname[FILENAME_MAX]; /* used when overwriting */
189
190 static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
191 static char            *keyword;                /* used for editing #elif's */
192
193 static Comment_state    incomment;              /* comment parser state */
194 static Line_state       linestate;              /* #if line parser state */
195 static Ifstate          ifstate[MAXDEPTH];      /* #if processor state */
196 static bool             ignoring[MAXDEPTH];     /* ignore comments state */
197 static int              stifline[MAXDEPTH];     /* start of current #if */
198 static int              depth;                  /* current #if nesting */
199 static int              delcount;               /* count of deleted lines */
200 static unsigned         blankcount;             /* count of blank lines */
201 static unsigned         blankmax;               /* maximum recent blankcount */
202 static bool             constexpr;              /* constant #if expression */
203
204 static int              exitstat;               /* program exit status */
205
206 static void             addsym(bool, bool, char *);
207 static void             closeout(void);
208 static void             debug(const char *, ...);
209 static void             done(void);
210 static void             error(const char *);
211 static int              findsym(const char *);
212 static void             flushline(bool);
213 static Linetype         parseline(void);
214 static Linetype         ifeval(const char **);
215 static void             ignoreoff(void);
216 static void             ignoreon(void);
217 static void             keywordedit(const char *);
218 static void             nest(void);
219 static void             process(void);
220 static const char      *skipargs(const char *);
221 static const char      *skipcomment(const char *);
222 static const char      *skipsym(const char *);
223 static void             state(Ifstate);
224 static int              strlcmp(const char *, const char *, size_t);
225 static void             unnest(void);
226 static void             usage(void);
227
228 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
229
230 /*
231  * The main program.
232  */
233 int
234 main(int argc, char *argv[])
235 {
236         int opt;
237
238         while ((opt = getopt(argc, argv, "i:D:U:I:o:BbcdeKklnst")) != -1)
239                 switch (opt) {
240                 case 'i': /* treat stuff controlled by these symbols as text */
241                         /*
242                          * For strict backwards-compatibility the U or D
243                          * should be immediately after the -i but it doesn't
244                          * matter much if we relax that requirement.
245                          */
246                         opt = *optarg++;
247                         if (opt == 'D')
248                                 addsym(true, true, optarg);
249                         else if (opt == 'U')
250                                 addsym(true, false, optarg);
251                         else
252                                 usage();
253                         break;
254                 case 'D': /* define a symbol */
255                         addsym(false, true, optarg);
256                         break;
257                 case 'U': /* undef a symbol */
258                         addsym(false, false, optarg);
259                         break;
260                 case 'I':
261                         /* no-op for compatibility with cpp */
262                         break;
263                 case 'B': /* compress blank lines around removed section */
264                         compblank = true;
265                         break;
266                 case 'b': /* blank deleted lines instead of omitting them */
267                 case 'l': /* backwards compatibility */
268                         lnblank = true;
269                         break;
270                 case 'c': /* treat -D as -U and vice versa */
271                         complement = true;
272                         break;
273                 case 'd':
274                         debugging = true;
275                         break;
276                 case 'e': /* fewer errors from dodgy lines */
277                         iocccok = true;
278                         break;
279                 case 'K': /* keep ambiguous #ifs */
280                         strictlogic = true;
281                         break;
282                 case 'k': /* process constant #ifs */
283                         killconsts = true;
284                         break;
285                 case 'n': /* add #line directive after deleted lines */
286                         lnnum = true;
287                         break;
288                 case 'o': /* output to a file */
289                         ofilename = optarg;
290                         break;
291                 case 's': /* only output list of symbols that control #ifs */
292                         symlist = true;
293                         break;
294                 case 't': /* don't parse C comments */
295                         text = true;
296                         break;
297                 default:
298                         usage();
299                 }
300         argc -= optind;
301         argv += optind;
302         if (compblank && lnblank)
303                 errx(2, "-B and -b are mutually exclusive");
304         if (argc > 1) {
305                 errx(2, "can only do one file");
306         } else if (argc == 1 && strcmp(*argv, "-") != 0) {
307                 filename = *argv;
308                 input = fopen(filename, "r");
309                 if (input == NULL)
310                         err(2, "can't open %s", filename);
311         } else {
312                 filename = "[stdin]";
313                 input = stdin;
314         }
315         if (ofilename == NULL) {
316                 output = stdout;
317         } else {
318                 struct stat ist, ost;
319                 memset(&ist, 0, sizeof(ist));
320                 memset(&ost, 0, sizeof(ost));
321
322                 if (fstat(fileno(input), &ist) != 0)
323                         err(2, "can't fstat %s", filename);
324                 if (stat(ofilename, &ost) != 0 && errno != ENOENT)
325                         warn("can't stat %s", ofilename);
326
327                 overwriting = (ist.st_dev == ost.st_dev
328                             && ist.st_ino == ost.st_ino);
329                 if (overwriting) {
330                         const char *dirsep;
331                         int ofd;
332
333                         dirsep = strrchr(ofilename, '/');
334                         if (dirsep != NULL)
335                                 snprintf(tempname, sizeof(tempname),
336                                     "%.*s/" TEMPLATE,
337                                     dirsep - ofilename, ofilename);
338                         else
339                                 strlcpy(tempname, TEMPLATE, sizeof(tempname));
340                         ofd = mkstemp(tempname);
341                         if (ofd != -1)
342                                 output = fdopen(ofd, "w+");
343                         if (output == NULL)
344                                 err(2, "can't create temporary file");
345                         fchmod(ofd, ist.st_mode & ACCESSPERMS);
346                 } else {
347                         output = fopen(ofilename, "w");
348                         if (output == NULL)
349                                 err(2, "can't open %s", ofilename);
350                 }
351         }
352         process();
353         abort(); /* bug */
354 }
355
356 static void
357 usage(void)
358 {
359         fprintf(stderr, "usage: unifdef [-BbcdeKknst] [-Ipath]"
360             " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
361         exit(2);
362 }
363
364 /*
365  * A state transition function alters the global #if processing state
366  * in a particular way. The table below is indexed by the current
367  * processing state and the type of the current line.
368  *
369  * Nesting is handled by keeping a stack of states; some transition
370  * functions increase or decrease the depth. They also maintain the
371  * ignore state on a stack. In some complicated cases they have to
372  * alter the preprocessor directive, as follows.
373  *
374  * When we have processed a group that starts off with a known-false
375  * #if/#elif sequence (which has therefore been deleted) followed by a
376  * #elif that we don't understand and therefore must keep, we edit the
377  * latter into a #if to keep the nesting correct.
378  *
379  * When we find a true #elif in a group, the following block will
380  * always be kept and the rest of the sequence after the next #elif or
381  * #else will be discarded. We edit the #elif into a #else and the
382  * following directive to #endif since this has the desired behaviour.
383  *
384  * "Dodgy" directives are split across multiple lines, the most common
385  * example being a multi-line comment hanging off the right of the
386  * directive. We can handle them correctly only if there is no change
387  * from printing to dropping (or vice versa) caused by that directive.
388  * If the directive is the first of a group we have a choice between
389  * failing with an error, or passing it through unchanged instead of
390  * evaluating it. The latter is not the default to avoid questions from
391  * users about unifdef unexpectedly leaving behind preprocessor directives.
392  */
393 typedef void state_fn(void);
394
395 /* report an error */
396 static void Eelif (void) { error("Inappropriate #elif"); }
397 static void Eelse (void) { error("Inappropriate #else"); }
398 static void Eendif(void) { error("Inappropriate #endif"); }
399 static void Eeof  (void) { error("Premature EOF"); }
400 static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
401 /* plain line handling */
402 static void print (void) { flushline(true); }
403 static void drop  (void) { flushline(false); }
404 /* output lacks group's start line */
405 static void Strue (void) { drop();  ignoreoff(); state(IS_TRUE_PREFIX); }
406 static void Sfalse(void) { drop();  ignoreoff(); state(IS_FALSE_PREFIX); }
407 static void Selse (void) { drop();               state(IS_TRUE_ELSE); }
408 /* print/pass this block */
409 static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
410 static void Pelse (void) { print();              state(IS_PASS_ELSE); }
411 static void Pendif(void) { print(); unnest(); }
412 /* discard this block */
413 static void Dfalse(void) { drop();  ignoreoff(); state(IS_FALSE_TRAILER); }
414 static void Delif (void) { drop();  ignoreoff(); state(IS_FALSE_MIDDLE); }
415 static void Delse (void) { drop();               state(IS_FALSE_ELSE); }
416 static void Dendif(void) { drop();  unnest(); }
417 /* first line of group */
418 static void Fdrop (void) { nest();  Dfalse(); }
419 static void Fpass (void) { nest();  Pelif(); }
420 static void Ftrue (void) { nest();  Strue(); }
421 static void Ffalse(void) { nest();  Sfalse(); }
422 /* variable pedantry for obfuscated lines */
423 static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
424 static void Oif   (void) { if (!iocccok) Eioccc(); Fpass(); }
425 static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
426 /* ignore comments in this block */
427 static void Idrop (void) { Fdrop();  ignoreon(); }
428 static void Itrue (void) { Ftrue();  ignoreon(); }
429 static void Ifalse(void) { Ffalse(); ignoreon(); }
430 /* edit this line */
431 static void Mpass (void) { strncpy(keyword, "if  ", 4); Pelif(); }
432 static void Mtrue (void) { keywordedit("else\n");  state(IS_TRUE_MIDDLE); }
433 static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
434 static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
435
436 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
437 /* IS_OUTSIDE */
438 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
439   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
440   print, done,  abort },
441 /* IS_FALSE_PREFIX */
442 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
443   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
444   drop,  Eeof,  abort },
445 /* IS_TRUE_PREFIX */
446 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
447   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
448   print, Eeof,  abort },
449 /* IS_PASS_MIDDLE */
450 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
451   Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
452   print, Eeof,  abort },
453 /* IS_FALSE_MIDDLE */
454 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
455   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
456   drop,  Eeof,  abort },
457 /* IS_TRUE_MIDDLE */
458 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
459   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
460   print, Eeof,  abort },
461 /* IS_PASS_ELSE */
462 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
463   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
464   print, Eeof,  abort },
465 /* IS_FALSE_ELSE */
466 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
467   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
468   drop,  Eeof,  abort },
469 /* IS_TRUE_ELSE */
470 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
471   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
472   print, Eeof,  abort },
473 /* IS_FALSE_TRAILER */
474 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
475   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
476   drop,  Eeof,  abort }
477 /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
478   TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
479   PLAIN  EOF    ERROR */
480 };
481
482 /*
483  * State machine utility functions
484  */
485 static void
486 ignoreoff(void)
487 {
488         if (depth == 0)
489                 abort(); /* bug */
490         ignoring[depth] = ignoring[depth-1];
491 }
492 static void
493 ignoreon(void)
494 {
495         ignoring[depth] = true;
496 }
497 static void
498 keywordedit(const char *replacement)
499 {
500         strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);
501         print();
502 }
503 static void
504 nest(void)
505 {
506         if (depth > MAXDEPTH-1)
507                 abort(); /* bug */
508         if (depth == MAXDEPTH-1)
509                 error("Too many levels of nesting");
510         depth += 1;
511         stifline[depth] = linenum;
512 }
513 static void
514 unnest(void)
515 {
516         if (depth == 0)
517                 abort(); /* bug */
518         depth -= 1;
519 }
520 static void
521 state(Ifstate is)
522 {
523         ifstate[depth] = is;
524 }
525
526 /*
527  * Write a line to the output or not, according to command line options.
528  */
529 static void
530 flushline(bool keep)
531 {
532         if (symlist)
533                 return;
534         if (keep ^ complement) {
535                 bool blankline = tline[strspn(tline, " \t\n")] == '\0';
536                 if (blankline && compblank && blankcount != blankmax) {
537                         delcount += 1;
538                         blankcount += 1;
539                 } else {
540                         if (lnnum && delcount > 0)
541                                 printf("#line %d\n", linenum);
542                         fputs(tline, output);
543                         delcount = 0;
544                         blankmax = blankcount = blankline ? blankcount + 1 : 0;
545                 }
546         } else {
547                 if (lnblank)
548                         putc('\n', output);
549                 exitstat = 1;
550                 delcount += 1;
551                 blankcount = 0;
552         }
553 }
554
555 /*
556  * The driver for the state machine.
557  */
558 static void
559 process(void)
560 {
561         Linetype lineval;
562
563         /* When compressing blank lines, act as if the file
564            is preceded by a large number of blank lines. */
565         blankmax = blankcount = 1000;
566         for (;;) {
567                 linenum++;
568                 lineval = parseline();
569                 trans_table[ifstate[depth]][lineval]();
570                 debug("process %s -> %s depth %d",
571                     linetype_name[lineval],
572                     ifstate_name[ifstate[depth]], depth);
573         }
574 }
575
576 /*
577  * Flush the output and handle errors.
578  */
579 static void
580 closeout(void)
581 {
582         if (fclose(output) == EOF) {
583                 warn("couldn't write to output");
584                 if (overwriting) {
585                         unlink(tempname);
586                         errx(2, "%s unchanged", filename);
587                 } else {
588                         exit(2);
589                 }
590         }
591 }
592
593 /*
594  * Clean up and exit.
595  */
596 static void
597 done(void)
598 {
599         if (incomment)
600                 error("EOF in comment");
601         closeout();
602         if (overwriting && rename(tempname, filename) == -1) {
603                 warn("couldn't rename temporary file");
604                 unlink(tempname);
605                 errx(2, "%s unchanged", filename);
606         }
607         exit(exitstat);
608 }
609
610 /*
611  * Parse a line and determine its type. We keep the preprocessor line
612  * parser state between calls in the global variable linestate, with
613  * help from skipcomment().
614  */
615 static Linetype
616 parseline(void)
617 {
618         const char *cp;
619         int cursym;
620         int kwlen;
621         Linetype retval;
622         Comment_state wascomment;
623
624         if (fgets(tline, MAXLINE, input) == NULL)
625                 return (LT_EOF);
626         retval = LT_PLAIN;
627         wascomment = incomment;
628         cp = skipcomment(tline);
629         if (linestate == LS_START) {
630                 if (*cp == '#') {
631                         linestate = LS_HASH;
632                         cp = skipcomment(cp + 1);
633                 } else if (*cp != '\0')
634                         linestate = LS_DIRTY;
635         }
636         if (!incomment && linestate == LS_HASH) {
637                 keyword = tline + (cp - tline);
638                 cp = skipsym(cp);
639                 kwlen = cp - keyword;
640                 /* no way can we deal with a continuation inside a keyword */
641                 if (strncmp(cp, "\\\n", 2) == 0)
642                         Eioccc();
643                 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
644                     strlcmp("ifndef", keyword, kwlen) == 0) {
645                         cp = skipcomment(cp);
646                         if ((cursym = findsym(cp)) < 0)
647                                 retval = LT_IF;
648                         else {
649                                 retval = (keyword[2] == 'n')
650                                     ? LT_FALSE : LT_TRUE;
651                                 if (value[cursym] == NULL)
652                                         retval = (retval == LT_TRUE)
653                                             ? LT_FALSE : LT_TRUE;
654                                 if (ignore[cursym])
655                                         retval = (retval == LT_TRUE)
656                                             ? LT_TRUEI : LT_FALSEI;
657                         }
658                         cp = skipsym(cp);
659                 } else if (strlcmp("if", keyword, kwlen) == 0)
660                         retval = ifeval(&cp);
661                 else if (strlcmp("elif", keyword, kwlen) == 0)
662                         retval = ifeval(&cp) - LT_IF + LT_ELIF;
663                 else if (strlcmp("else", keyword, kwlen) == 0)
664                         retval = LT_ELSE;
665                 else if (strlcmp("endif", keyword, kwlen) == 0)
666                         retval = LT_ENDIF;
667                 else {
668                         linestate = LS_DIRTY;
669                         retval = LT_PLAIN;
670                 }
671                 cp = skipcomment(cp);
672                 if (*cp != '\0') {
673                         linestate = LS_DIRTY;
674                         if (retval == LT_TRUE || retval == LT_FALSE ||
675                             retval == LT_TRUEI || retval == LT_FALSEI)
676                                 retval = LT_IF;
677                         if (retval == LT_ELTRUE || retval == LT_ELFALSE)
678                                 retval = LT_ELIF;
679                 }
680                 if (retval != LT_PLAIN && (wascomment || incomment)) {
681                         retval += LT_DODGY;
682                         if (incomment)
683                                 linestate = LS_DIRTY;
684                 }
685                 /* skipcomment normally changes the state, except
686                    if the last line of the file lacks a newline, or
687                    if there is too much whitespace in a directive */
688                 if (linestate == LS_HASH) {
689                         size_t len = cp - tline;
690                         if (fgets(tline + len, MAXLINE - len, input) == NULL) {
691                                 /* append the missing newline */
692                                 tline[len+0] = '\n';
693                                 tline[len+1] = '\0';
694                                 cp++;
695                                 linestate = LS_START;
696                         } else {
697                                 linestate = LS_DIRTY;
698                         }
699                 }
700         }
701         if (linestate == LS_DIRTY) {
702                 while (*cp != '\0')
703                         cp = skipcomment(cp + 1);
704         }
705         debug("parser %s comment %s line",
706             comment_name[incomment], linestate_name[linestate]);
707         return (retval);
708 }
709
710 /*
711  * These are the binary operators that are supported by the expression
712  * evaluator.
713  */
714 static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) {
715         if(at == LT_IF || bt == LT_IF) return (LT_IF);
716         return (*p = v, v ? LT_TRUE : LT_FALSE);
717 }
718 static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) {
719         return op_strict(p, a < b, at, bt);
720 }
721 static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) {
722         return op_strict(p, a > b, at, bt);
723 }
724 static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) {
725         return op_strict(p, a <= b, at, bt);
726 }
727 static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) {
728         return op_strict(p, a >= b, at, bt);
729 }
730 static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) {
731         return op_strict(p, a == b, at, bt);
732 }
733 static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) {
734         return op_strict(p, a != b, at, bt);
735 }
736 static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) {
737         if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
738                 return (*p = 1, LT_TRUE);
739         return op_strict(p, a || b, at, bt);
740 }
741 static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) {
742         if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
743                 return (*p = 0, LT_FALSE);
744         return op_strict(p, a && b, at, bt);
745 }
746
747 /*
748  * An evaluation function takes three arguments, as follows: (1) a pointer to
749  * an element of the precedence table which lists the operators at the current
750  * level of precedence; (2) a pointer to an integer which will receive the
751  * value of the expression; and (3) a pointer to a char* that points to the
752  * expression to be evaluated and that is updated to the end of the expression
753  * when evaluation is complete. The function returns LT_FALSE if the value of
754  * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
755  * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
756  */
757 struct ops;
758
759 typedef Linetype eval_fn(const struct ops *, int *, const char **);
760
761 static eval_fn eval_table, eval_unary;
762
763 /*
764  * The precedence table. Expressions involving binary operators are evaluated
765  * in a table-driven way by eval_table. When it evaluates a subexpression it
766  * calls the inner function with its first argument pointing to the next
767  * element of the table. Innermost expressions have special non-table-driven
768  * handling.
769  */
770 static const struct ops {
771         eval_fn *inner;
772         struct op {
773                 const char *str;
774                 Linetype (*fn)(int *, Linetype, int, Linetype, int);
775         } op[5];
776 } eval_ops[] = {
777         { eval_table, { { "||", op_or } } },
778         { eval_table, { { "&&", op_and } } },
779         { eval_table, { { "==", op_eq },
780                         { "!=", op_ne } } },
781         { eval_unary, { { "<=", op_le },
782                         { ">=", op_ge },
783                         { "<", op_lt },
784                         { ">", op_gt } } }
785 };
786
787 /*
788  * Function for evaluating the innermost parts of expressions,
789  * viz. !expr (expr) number defined(symbol) symbol
790  * We reset the constexpr flag in the last two cases.
791  */
792 static Linetype
793 eval_unary(const struct ops *ops, int *valp, const char **cpp)
794 {
795         const char *cp;
796         char *ep;
797         int sym;
798         bool defparen;
799         Linetype lt;
800
801         cp = skipcomment(*cpp);
802         if (*cp == '!') {
803                 debug("eval%d !", ops - eval_ops);
804                 cp++;
805                 lt = eval_unary(ops, valp, &cp);
806                 if (lt == LT_ERROR)
807                         return (LT_ERROR);
808                 if (lt != LT_IF) {
809                         *valp = !*valp;
810                         lt = *valp ? LT_TRUE : LT_FALSE;
811                 }
812         } else if (*cp == '(') {
813                 cp++;
814                 debug("eval%d (", ops - eval_ops);
815                 lt = eval_table(eval_ops, valp, &cp);
816                 if (lt == LT_ERROR)
817                         return (LT_ERROR);
818                 cp = skipcomment(cp);
819                 if (*cp++ != ')')
820                         return (LT_ERROR);
821         } else if (isdigit((unsigned char)*cp)) {
822                 debug("eval%d number", ops - eval_ops);
823                 *valp = strtol(cp, &ep, 0);
824                 if (ep == cp)
825                         return (LT_ERROR);
826                 lt = *valp ? LT_TRUE : LT_FALSE;
827                 cp = skipsym(cp);
828         } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
829                 cp = skipcomment(cp+7);
830                 debug("eval%d defined", ops - eval_ops);
831                 if (*cp == '(') {
832                         cp = skipcomment(cp+1);
833                         defparen = true;
834                 } else {
835                         defparen = false;
836                 }
837                 sym = findsym(cp);
838                 if (sym < 0) {
839                         lt = LT_IF;
840                 } else {
841                         *valp = (value[sym] != NULL);
842                         lt = *valp ? LT_TRUE : LT_FALSE;
843                 }
844                 cp = skipsym(cp);
845                 cp = skipcomment(cp);
846                 if (defparen && *cp++ != ')')
847                         return (LT_ERROR);
848                 constexpr = false;
849         } else if (!endsym(*cp)) {
850                 debug("eval%d symbol", ops - eval_ops);
851                 sym = findsym(cp);
852                 cp = skipsym(cp);
853                 if (sym < 0) {
854                         lt = LT_IF;
855                         cp = skipargs(cp);
856                 } else if (value[sym] == NULL) {
857                         *valp = 0;
858                         lt = LT_FALSE;
859                 } else {
860                         *valp = strtol(value[sym], &ep, 0);
861                         if (*ep != '\0' || ep == value[sym])
862                                 return (LT_ERROR);
863                         lt = *valp ? LT_TRUE : LT_FALSE;
864                         cp = skipargs(cp);
865                 }
866                 constexpr = false;
867         } else {
868                 debug("eval%d bad expr", ops - eval_ops);
869                 return (LT_ERROR);
870         }
871
872         *cpp = cp;
873         debug("eval%d = %d", ops - eval_ops, *valp);
874         return (lt);
875 }
876
877 /*
878  * Table-driven evaluation of binary operators.
879  */
880 static Linetype
881 eval_table(const struct ops *ops, int *valp, const char **cpp)
882 {
883         const struct op *op;
884         const char *cp;
885         int val;
886         Linetype lt, rt;
887
888         debug("eval%d", ops - eval_ops);
889         cp = *cpp;
890         lt = ops->inner(ops+1, valp, &cp);
891         if (lt == LT_ERROR)
892                 return (LT_ERROR);
893         for (;;) {
894                 cp = skipcomment(cp);
895                 for (op = ops->op; op->str != NULL; op++)
896                         if (strncmp(cp, op->str, strlen(op->str)) == 0)
897                                 break;
898                 if (op->str == NULL)
899                         break;
900                 cp += strlen(op->str);
901                 debug("eval%d %s", ops - eval_ops, op->str);
902                 rt = ops->inner(ops+1, &val, &cp);
903                 if (rt == LT_ERROR)
904                         return (LT_ERROR);
905                 lt = op->fn(valp, lt, *valp, rt, val);
906         }
907
908         *cpp = cp;
909         debug("eval%d = %d", ops - eval_ops, *valp);
910         debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]);
911         return (lt);
912 }
913
914 /*
915  * Evaluate the expression on a #if or #elif line. If we can work out
916  * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
917  * return just a generic LT_IF.
918  */
919 static Linetype
920 ifeval(const char **cpp)
921 {
922         int ret;
923         int val = 0;
924
925         debug("eval %s", *cpp);
926         constexpr = killconsts ? false : true;
927         ret = eval_table(eval_ops, &val, cpp);
928         debug("eval = %d", val);
929         return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
930 }
931
932 /*
933  * Skip over comments, strings, and character literals and stop at the
934  * next character position that is not whitespace. Between calls we keep
935  * the comment state in the global variable incomment, and we also adjust
936  * the global variable linestate when we see a newline.
937  * XXX: doesn't cope with the buffer splitting inside a state transition.
938  */
939 static const char *
940 skipcomment(const char *cp)
941 {
942         if (text || ignoring[depth]) {
943                 for (; isspace((unsigned char)*cp); cp++)
944                         if (*cp == '\n')
945                                 linestate = LS_START;
946                 return (cp);
947         }
948         while (*cp != '\0')
949                 /* don't reset to LS_START after a line continuation */
950                 if (strncmp(cp, "\\\n", 2) == 0)
951                         cp += 2;
952                 else switch (incomment) {
953                 case NO_COMMENT:
954                         if (strncmp(cp, "/\\\n", 3) == 0) {
955                                 incomment = STARTING_COMMENT;
956                                 cp += 3;
957                         } else if (strncmp(cp, "/*", 2) == 0) {
958                                 incomment = C_COMMENT;
959                                 cp += 2;
960                         } else if (strncmp(cp, "//", 2) == 0) {
961                                 incomment = CXX_COMMENT;
962                                 cp += 2;
963                         } else if (strncmp(cp, "\'", 1) == 0) {
964                                 incomment = CHAR_LITERAL;
965                                 linestate = LS_DIRTY;
966                                 cp += 1;
967                         } else if (strncmp(cp, "\"", 1) == 0) {
968                                 incomment = STRING_LITERAL;
969                                 linestate = LS_DIRTY;
970                                 cp += 1;
971                         } else if (strncmp(cp, "\n", 1) == 0) {
972                                 linestate = LS_START;
973                                 cp += 1;
974                         } else if (strchr(" \t", *cp) != NULL) {
975                                 cp += 1;
976                         } else
977                                 return (cp);
978                         continue;
979                 case CXX_COMMENT:
980                         if (strncmp(cp, "\n", 1) == 0) {
981                                 incomment = NO_COMMENT;
982                                 linestate = LS_START;
983                         }
984                         cp += 1;
985                         continue;
986                 case CHAR_LITERAL:
987                 case STRING_LITERAL:
988                         if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
989                             (incomment == STRING_LITERAL && cp[0] == '\"')) {
990                                 incomment = NO_COMMENT;
991                                 cp += 1;
992                         } else if (cp[0] == '\\') {
993                                 if (cp[1] == '\0')
994                                         cp += 1;
995                                 else
996                                         cp += 2;
997                         } else if (strncmp(cp, "\n", 1) == 0) {
998                                 if (incomment == CHAR_LITERAL)
999                                         error("unterminated char literal");
1000                                 else
1001                                         error("unterminated string literal");
1002                         } else
1003                                 cp += 1;
1004                         continue;
1005                 case C_COMMENT:
1006                         if (strncmp(cp, "*\\\n", 3) == 0) {
1007                                 incomment = FINISHING_COMMENT;
1008                                 cp += 3;
1009                         } else if (strncmp(cp, "*/", 2) == 0) {
1010                                 incomment = NO_COMMENT;
1011                                 cp += 2;
1012                         } else
1013                                 cp += 1;
1014                         continue;
1015                 case STARTING_COMMENT:
1016                         if (*cp == '*') {
1017                                 incomment = C_COMMENT;
1018                                 cp += 1;
1019                         } else if (*cp == '/') {
1020                                 incomment = CXX_COMMENT;
1021                                 cp += 1;
1022                         } else {
1023                                 incomment = NO_COMMENT;
1024                                 linestate = LS_DIRTY;
1025                         }
1026                         continue;
1027                 case FINISHING_COMMENT:
1028                         if (*cp == '/') {
1029                                 incomment = NO_COMMENT;
1030                                 cp += 1;
1031                         } else
1032                                 incomment = C_COMMENT;
1033                         continue;
1034                 default:
1035                         abort(); /* bug */
1036                 }
1037         return (cp);
1038 }
1039
1040 /*
1041  * Skip macro arguments.
1042  */
1043 static const char *
1044 skipargs(const char *cp)
1045 {
1046         const char *ocp = cp;
1047         int level = 0;
1048         cp = skipcomment(cp);
1049         if (*cp != '(')
1050                 return (cp);
1051         do {
1052                 if (*cp == '(')
1053                         level++;
1054                 if (*cp == ')')
1055                         level--;
1056                 cp = skipcomment(cp+1);
1057         } while (level != 0 && *cp != '\0');
1058         if (level == 0)
1059                 return (cp);
1060         else
1061         /* Rewind and re-detect the syntax error later. */
1062                 return (ocp);
1063 }
1064
1065 /*
1066  * Skip over an identifier.
1067  */
1068 static const char *
1069 skipsym(const char *cp)
1070 {
1071         while (!endsym(*cp))
1072                 ++cp;
1073         return (cp);
1074 }
1075
1076 /*
1077  * Look for the symbol in the symbol table. If it is found, we return
1078  * the symbol table index, else we return -1.
1079  */
1080 static int
1081 findsym(const char *str)
1082 {
1083         const char *cp;
1084         int symind;
1085
1086         cp = skipsym(str);
1087         if (cp == str)
1088                 return (-1);
1089         if (symlist) {
1090                 printf("%.*s\n", (int)(cp-str), str);
1091                 /* we don't care about the value of the symbol */
1092                 return (0);
1093         }
1094         for (symind = 0; symind < nsyms; ++symind) {
1095                 if (strlcmp(symname[symind], str, cp-str) == 0) {
1096                         debug("findsym %s %s", symname[symind],
1097                             value[symind] ? value[symind] : "");
1098                         return (symind);
1099                 }
1100         }
1101         return (-1);
1102 }
1103
1104 /*
1105  * Add a symbol to the symbol table.
1106  */
1107 static void
1108 addsym(bool ignorethis, bool definethis, char *sym)
1109 {
1110         int symind;
1111         char *val;
1112
1113         symind = findsym(sym);
1114         if (symind < 0) {
1115                 if (nsyms >= MAXSYMS)
1116                         errx(2, "too many symbols");
1117                 symind = nsyms++;
1118         }
1119         symname[symind] = sym;
1120         ignore[symind] = ignorethis;
1121         val = sym + (skipsym(sym) - sym);
1122         if (definethis) {
1123                 if (*val == '=') {
1124                         value[symind] = val+1;
1125                         *val = '\0';
1126                 } else if (*val == '\0')
1127                         value[symind] = "";
1128                 else
1129                         usage();
1130         } else {
1131                 if (*val != '\0')
1132                         usage();
1133                 value[symind] = NULL;
1134         }
1135 }
1136
1137 /*
1138  * Compare s with n characters of t.
1139  * The same as strncmp() except that it checks that s[n] == '\0'.
1140  */
1141 static int
1142 strlcmp(const char *s, const char *t, size_t n)
1143 {
1144         while (n-- && *t != '\0')
1145                 if (*s != *t)
1146                         return ((unsigned char)*s - (unsigned char)*t);
1147                 else
1148                         ++s, ++t;
1149         return ((unsigned char)*s);
1150 }
1151
1152 /*
1153  * Diagnostics.
1154  */
1155 static void
1156 debug(const char *msg, ...)
1157 {
1158         va_list ap;
1159
1160         if (debugging) {
1161                 va_start(ap, msg);
1162                 vwarnx(msg, ap);
1163                 va_end(ap);
1164         }
1165 }
1166
1167 static void
1168 error(const char *msg)
1169 {
1170         if (depth == 0)
1171                 warnx("%s: %d: %s", filename, linenum, msg);
1172         else
1173                 warnx("%s: %d: %s (#if line %d depth %d)",
1174                     filename, linenum, msg, stifline[depth], depth);
1175         closeout();
1176         errx(2, "output may be truncated");
1177 }