Debian Codegraph @

unifdef/unifdef.c

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