unifdef.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. /*
  2. * Copyright (c) 2002 - 2005 Tony Finch <dot@dotat.at>. All rights reserved.
  3. *
  4. * This code is derived from software contributed to Berkeley by Dave Yost.
  5. * It was rewritten to support ANSI C by Tony Finch. The original version of
  6. * unifdef carried the following copyright notice. None of its code remains
  7. * in this version (though some of the names remain).
  8. *
  9. * Copyright (c) 1985, 1993
  10. * The Regents of the University of California. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions
  14. * are met:
  15. * 1. Redistributions of source code must retain the above copyright
  16. * notice, this list of conditions and the following disclaimer.
  17. * 2. Redistributions in binary form must reproduce the above copyright
  18. * notice, this list of conditions and the following disclaimer in the
  19. * documentation and/or other materials provided with the distribution.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  22. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  25. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. */
  33. #include <sys/cdefs.h>
  34. #ifndef lint
  35. #if 0
  36. static const char copyright[] =
  37. "@(#) Copyright (c) 1985, 1993\n\
  38. The Regents of the University of California. All rights reserved.\n";
  39. #endif
  40. #ifdef __IDSTRING
  41. __IDSTRING(Berkeley, "@(#)unifdef.c 8.1 (Berkeley) 6/6/93");
  42. __IDSTRING(NetBSD, "$NetBSD: unifdef.c,v 1.8 2000/07/03 02:51:36 matt Exp $");
  43. __IDSTRING(dotat, "$dotat: things/unifdef.c,v 1.171 2005/03/08 12:38:48 fanf2 Exp $");
  44. #endif
  45. #endif /* not lint */
  46. #ifdef __FBSDID
  47. __FBSDID("$FreeBSD: /repoman/r/ncvs/src/usr.bin/unifdef/unifdef.c,v 1.20 2005/05/21 09:55:09 ru Exp $");
  48. #endif
  49. /*
  50. * unifdef - remove ifdef'ed lines
  51. *
  52. * Wishlist:
  53. * provide an option which will append the name of the
  54. * appropriate symbol after #else's and #endif's
  55. * provide an option which will check symbols after
  56. * #else's and #endif's to see that they match their
  57. * corresponding #ifdef or #ifndef
  58. *
  59. * The first two items above require better buffer handling, which would
  60. * also make it possible to handle all "dodgy" directives correctly.
  61. */
  62. #include <ctype.h>
  63. #include <err.h>
  64. #include <stdarg.h>
  65. #include <stdbool.h>
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <unistd.h>
  70. size_t strlcpy(char *dst, const char *src, size_t siz);
  71. /* types of input lines: */
  72. typedef enum {
  73. LT_TRUEI, /* a true #if with ignore flag */
  74. LT_FALSEI, /* a false #if with ignore flag */
  75. LT_IF, /* an unknown #if */
  76. LT_TRUE, /* a true #if */
  77. LT_FALSE, /* a false #if */
  78. LT_ELIF, /* an unknown #elif */
  79. LT_ELTRUE, /* a true #elif */
  80. LT_ELFALSE, /* a false #elif */
  81. LT_ELSE, /* #else */
  82. LT_ENDIF, /* #endif */
  83. LT_DODGY, /* flag: directive is not on one line */
  84. LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
  85. LT_PLAIN, /* ordinary line */
  86. LT_EOF, /* end of file */
  87. LT_COUNT
  88. } Linetype;
  89. static char const * const linetype_name[] = {
  90. "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
  91. "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
  92. "DODGY TRUEI", "DODGY FALSEI",
  93. "DODGY IF", "DODGY TRUE", "DODGY FALSE",
  94. "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
  95. "DODGY ELSE", "DODGY ENDIF",
  96. "PLAIN", "EOF"
  97. };
  98. /* state of #if processing */
  99. typedef enum {
  100. IS_OUTSIDE,
  101. IS_FALSE_PREFIX, /* false #if followed by false #elifs */
  102. IS_TRUE_PREFIX, /* first non-false #(el)if is true */
  103. IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
  104. IS_FALSE_MIDDLE, /* a false #elif after a pass state */
  105. IS_TRUE_MIDDLE, /* a true #elif after a pass state */
  106. IS_PASS_ELSE, /* an else after a pass state */
  107. IS_FALSE_ELSE, /* an else after a true state */
  108. IS_TRUE_ELSE, /* an else after only false states */
  109. IS_FALSE_TRAILER, /* #elifs after a true are false */
  110. IS_COUNT
  111. } Ifstate;
  112. static char const * const ifstate_name[] = {
  113. "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
  114. "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
  115. "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
  116. "FALSE_TRAILER"
  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. static char const * const comment_name[] = {
  129. "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
  130. };
  131. /* state of preprocessor line parser */
  132. typedef enum {
  133. LS_START, /* only space and comments on this line */
  134. LS_HASH, /* only space, comments, and a hash */
  135. LS_DIRTY /* this line can't be a preprocessor line */
  136. } Line_state;
  137. static char const * const linestate_name[] = {
  138. "START", "HASH", "DIRTY"
  139. };
  140. /*
  141. * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
  142. */
  143. #define MAXDEPTH 64 /* maximum #if nesting */
  144. #define MAXLINE 4096 /* maximum length of line */
  145. #define MAXSYMS 4096 /* maximum number of symbols */
  146. /*
  147. * Sometimes when editing a keyword the replacement text is longer, so
  148. * we leave some space at the end of the tline buffer to accommodate this.
  149. */
  150. #define EDITSLOP 10
  151. /*
  152. * Globals.
  153. */
  154. static bool complement; /* -c: do the complement */
  155. static bool debugging; /* -d: debugging reports */
  156. static bool iocccok; /* -e: fewer IOCCC errors */
  157. static bool killconsts; /* -k: eval constant #ifs */
  158. static bool lnblank; /* -l: blank deleted lines */
  159. static bool lnnum; /* -n: add #line directives */
  160. static bool symlist; /* -s: output symbol list */
  161. static bool text; /* -t: this is a text file */
  162. static const char *symname[MAXSYMS]; /* symbol name */
  163. static const char *value[MAXSYMS]; /* -Dsym=value */
  164. static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
  165. static int nsyms; /* number of symbols */
  166. static FILE *input; /* input file pointer */
  167. static const char *filename; /* input file name */
  168. static int linenum; /* current line number */
  169. static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
  170. static char *keyword; /* used for editing #elif's */
  171. static Comment_state incomment; /* comment parser state */
  172. static Line_state linestate; /* #if line parser state */
  173. static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
  174. static bool ignoring[MAXDEPTH]; /* ignore comments state */
  175. static int stifline[MAXDEPTH]; /* start of current #if */
  176. static int depth; /* current #if nesting */
  177. static int delcount; /* count of deleted lines */
  178. static bool keepthis; /* don't delete constant #if */
  179. static int exitstat; /* program exit status */
  180. static void addsym(bool, bool, char *);
  181. static void debug(const char *, ...);
  182. static void done(void);
  183. static void error(const char *);
  184. static int findsym(const char *);
  185. static void flushline(bool);
  186. static Linetype get_line(void);
  187. static Linetype ifeval(const char **);
  188. static void ignoreoff(void);
  189. static void ignoreon(void);
  190. static void keywordedit(const char *);
  191. static void nest(void);
  192. static void process(void);
  193. static const char *skipcomment(const char *);
  194. static const char *skipsym(const char *);
  195. static void state(Ifstate);
  196. static int strlcmp(const char *, const char *, size_t);
  197. static void unnest(void);
  198. static void usage(void);
  199. #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')
  200. /*
  201. * The main program.
  202. */
  203. int
  204. main(int argc, char *argv[])
  205. {
  206. int opt;
  207. while ((opt = getopt(argc, argv, "i:D:U:I:cdeklnst")) != -1)
  208. switch (opt) {
  209. case 'i': /* treat stuff controlled by these symbols as text */
  210. /*
  211. * For strict backwards-compatibility the U or D
  212. * should be immediately after the -i but it doesn't
  213. * matter much if we relax that requirement.
  214. */
  215. opt = *optarg++;
  216. if (opt == 'D')
  217. addsym(true, true, optarg);
  218. else if (opt == 'U')
  219. addsym(true, false, optarg);
  220. else
  221. usage();
  222. break;
  223. case 'D': /* define a symbol */
  224. addsym(false, true, optarg);
  225. break;
  226. case 'U': /* undef a symbol */
  227. addsym(false, false, optarg);
  228. break;
  229. case 'I':
  230. /* no-op for compatibility with cpp */
  231. break;
  232. case 'c': /* treat -D as -U and vice versa */
  233. complement = true;
  234. break;
  235. case 'd':
  236. debugging = true;
  237. break;
  238. case 'e': /* fewer errors from dodgy lines */
  239. iocccok = true;
  240. break;
  241. case 'k': /* process constant #ifs */
  242. killconsts = true;
  243. break;
  244. case 'l': /* blank deleted lines instead of omitting them */
  245. lnblank = true;
  246. break;
  247. case 'n': /* add #line directive after deleted lines */
  248. lnnum = true;
  249. break;
  250. case 's': /* only output list of symbols that control #ifs */
  251. symlist = true;
  252. break;
  253. case 't': /* don't parse C comments */
  254. text = true;
  255. break;
  256. default:
  257. usage();
  258. }
  259. argc -= optind;
  260. argv += optind;
  261. if (argc > 1) {
  262. errx(2, "can only do one file");
  263. } else if (argc == 1 && strcmp(*argv, "-") != 0) {
  264. filename = *argv;
  265. input = fopen(filename, "r");
  266. if (input == NULL)
  267. err(2, "can't open %s", filename);
  268. } else {
  269. filename = "[stdin]";
  270. input = stdin;
  271. }
  272. process();
  273. debug("bug at line %d", __LINE__);
  274. abort(); /* bug */
  275. }
  276. static void
  277. usage(void)
  278. {
  279. fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
  280. " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
  281. exit(2);
  282. }
  283. /*
  284. * A state transition function alters the global #if processing state
  285. * in a particular way. The table below is indexed by the current
  286. * processing state and the type of the current line.
  287. *
  288. * Nesting is handled by keeping a stack of states; some transition
  289. * functions increase or decrease the depth. They also maintain the
  290. * ignore state on a stack. In some complicated cases they have to
  291. * alter the preprocessor directive, as follows.
  292. *
  293. * When we have processed a group that starts off with a known-false
  294. * #if/#elif sequence (which has therefore been deleted) followed by a
  295. * #elif that we don't understand and therefore must keep, we edit the
  296. * latter into a #if to keep the nesting correct.
  297. *
  298. * When we find a true #elif in a group, the following block will
  299. * always be kept and the rest of the sequence after the next #elif or
  300. * #else will be discarded. We edit the #elif into a #else and the
  301. * following directive to #endif since this has the desired behaviour.
  302. *
  303. * "Dodgy" directives are split across multiple lines, the most common
  304. * example being a multi-line comment hanging off the right of the
  305. * directive. We can handle them correctly only if there is no change
  306. * from printing to dropping (or vice versa) caused by that directive.
  307. * If the directive is the first of a group we have a choice between
  308. * failing with an error, or passing it through unchanged instead of
  309. * evaluating it. The latter is not the default to avoid questions from
  310. * users about unifdef unexpectedly leaving behind preprocessor directives.
  311. */
  312. typedef void state_fn(void);
  313. /* report an error */
  314. static void Eelif (void) { error("Inappropriate #elif"); }
  315. static void Eelse (void) { error("Inappropriate #else"); }
  316. static void Eendif(void) { error("Inappropriate #endif"); }
  317. static void Eeof (void) { error("Premature EOF"); }
  318. static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
  319. /* plain line handling */
  320. static void print (void) { flushline(true); }
  321. static void drop (void) { flushline(false); }
  322. /* output lacks group's start line */
  323. static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
  324. static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
  325. static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
  326. /* print/pass this block */
  327. static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
  328. static void Pelse (void) { print(); state(IS_PASS_ELSE); }
  329. static void Pendif(void) { print(); unnest(); }
  330. /* discard this block */
  331. static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
  332. static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
  333. static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
  334. static void Dendif(void) { drop(); unnest(); }
  335. /* first line of group */
  336. static void Fdrop (void) { nest(); Dfalse(); }
  337. static void Fpass (void) { nest(); Pelif(); }
  338. static void Ftrue (void) { nest(); Strue(); }
  339. static void Ffalse(void) { nest(); Sfalse(); }
  340. /* variable pedantry for obfuscated lines */
  341. static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
  342. static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
  343. static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
  344. /* ignore comments in this block */
  345. static void Idrop (void) { Fdrop(); ignoreon(); }
  346. static void Itrue (void) { Ftrue(); ignoreon(); }
  347. static void Ifalse(void) { Ffalse(); ignoreon(); }
  348. /* edit this line */
  349. static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
  350. static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
  351. static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
  352. static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
  353. static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
  354. /* IS_OUTSIDE */
  355. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
  356. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
  357. print, done },
  358. /* IS_FALSE_PREFIX */
  359. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
  360. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
  361. drop, Eeof },
  362. /* IS_TRUE_PREFIX */
  363. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
  364. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  365. print, Eeof },
  366. /* IS_PASS_MIDDLE */
  367. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
  368. Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
  369. print, Eeof },
  370. /* IS_FALSE_MIDDLE */
  371. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
  372. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  373. drop, Eeof },
  374. /* IS_TRUE_MIDDLE */
  375. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
  376. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
  377. print, Eeof },
  378. /* IS_PASS_ELSE */
  379. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
  380. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
  381. print, Eeof },
  382. /* IS_FALSE_ELSE */
  383. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
  384. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
  385. drop, Eeof },
  386. /* IS_TRUE_ELSE */
  387. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
  388. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
  389. print, Eeof },
  390. /* IS_FALSE_TRAILER */
  391. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
  392. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
  393. drop, Eeof }
  394. /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
  395. TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
  396. PLAIN EOF */
  397. };
  398. /*
  399. * State machine utility functions
  400. */
  401. static void
  402. done(void)
  403. {
  404. if (incomment)
  405. error("EOF in comment");
  406. exit(exitstat);
  407. }
  408. static void
  409. ignoreoff(void)
  410. {
  411. if (depth == 0) {
  412. debug("bug at line %d", __LINE__);
  413. abort(); /* bug */
  414. }
  415. ignoring[depth] = ignoring[depth-1];
  416. }
  417. static void
  418. ignoreon(void)
  419. {
  420. ignoring[depth] = true;
  421. }
  422. static void
  423. keywordedit(const char *replacement)
  424. {
  425. size_t size = tline + sizeof(tline) - keyword;
  426. char *dst = keyword;
  427. const char *src = replacement;
  428. if (size != 0) {
  429. while ((--size != 0) && (*src != '\0'))
  430. *dst++ = *src++;
  431. *dst = '\0';
  432. }
  433. print();
  434. }
  435. static void
  436. nest(void)
  437. {
  438. depth += 1;
  439. if (depth >= MAXDEPTH)
  440. error("Too many levels of nesting");
  441. stifline[depth] = linenum;
  442. }
  443. static void
  444. unnest(void)
  445. {
  446. if (depth == 0) {
  447. debug("bug at line %d", __LINE__);
  448. abort(); /* bug */
  449. }
  450. depth -= 1;
  451. }
  452. static void
  453. state(Ifstate is)
  454. {
  455. ifstate[depth] = is;
  456. }
  457. /*
  458. * Write a line to the output or not, according to command line options.
  459. */
  460. static void
  461. flushline(bool keep)
  462. {
  463. if (symlist)
  464. return;
  465. if (keep ^ complement) {
  466. if (lnnum && delcount > 0)
  467. printf("#line %d\n", linenum);
  468. fputs(tline, stdout);
  469. delcount = 0;
  470. } else {
  471. if (lnblank)
  472. putc('\n', stdout);
  473. exitstat = 1;
  474. delcount += 1;
  475. }
  476. }
  477. /*
  478. * The driver for the state machine.
  479. */
  480. static void
  481. process(void)
  482. {
  483. Linetype lineval;
  484. for (;;) {
  485. linenum++;
  486. lineval = get_line();
  487. trans_table[ifstate[depth]][lineval]();
  488. debug("process %s -> %s depth %d",
  489. linetype_name[lineval],
  490. ifstate_name[ifstate[depth]], depth);
  491. }
  492. }
  493. /*
  494. * Parse a line and determine its type. We keep the preprocessor line
  495. * parser state between calls in the global variable linestate, with
  496. * help from skipcomment().
  497. */
  498. static Linetype
  499. get_line(void)
  500. {
  501. const char *cp;
  502. int cursym;
  503. int kwlen;
  504. Linetype retval;
  505. Comment_state wascomment;
  506. if (fgets(tline, MAXLINE, input) == NULL)
  507. return (LT_EOF);
  508. retval = LT_PLAIN;
  509. wascomment = incomment;
  510. cp = skipcomment(tline);
  511. if (linestate == LS_START) {
  512. if (*cp == '#') {
  513. linestate = LS_HASH;
  514. cp = skipcomment(cp + 1);
  515. } else if (*cp != '\0')
  516. linestate = LS_DIRTY;
  517. }
  518. if (!incomment && linestate == LS_HASH) {
  519. keyword = tline + (cp - tline);
  520. cp = skipsym(cp);
  521. kwlen = cp - keyword;
  522. /* no way can we deal with a continuation inside a keyword */
  523. if (strncmp(cp, "\\\n", 2) == 0)
  524. Eioccc();
  525. if (strlcmp("ifdef", keyword, kwlen) == 0 ||
  526. strlcmp("ifndef", keyword, kwlen) == 0) {
  527. cp = skipcomment(cp);
  528. if ((cursym = findsym(cp)) < 0)
  529. retval = LT_IF;
  530. else {
  531. retval = (keyword[2] == 'n')
  532. ? LT_FALSE : LT_TRUE;
  533. if (value[cursym] == NULL)
  534. retval = (retval == LT_TRUE)
  535. ? LT_FALSE : LT_TRUE;
  536. if (ignore[cursym])
  537. retval = (retval == LT_TRUE)
  538. ? LT_TRUEI : LT_FALSEI;
  539. }
  540. cp = skipsym(cp);
  541. } else if (strlcmp("if", keyword, kwlen) == 0)
  542. retval = ifeval(&cp);
  543. else if (strlcmp("elif", keyword, kwlen) == 0)
  544. retval = ifeval(&cp) - LT_IF + LT_ELIF;
  545. else if (strlcmp("else", keyword, kwlen) == 0)
  546. retval = LT_ELSE;
  547. else if (strlcmp("endif", keyword, kwlen) == 0)
  548. retval = LT_ENDIF;
  549. else {
  550. linestate = LS_DIRTY;
  551. retval = LT_PLAIN;
  552. }
  553. cp = skipcomment(cp);
  554. if (*cp != '\0') {
  555. linestate = LS_DIRTY;
  556. if (retval == LT_TRUE || retval == LT_FALSE ||
  557. retval == LT_TRUEI || retval == LT_FALSEI)
  558. retval = LT_IF;
  559. if (retval == LT_ELTRUE || retval == LT_ELFALSE)
  560. retval = LT_ELIF;
  561. }
  562. if (retval != LT_PLAIN && (wascomment || incomment)) {
  563. retval += LT_DODGY;
  564. if (incomment)
  565. linestate = LS_DIRTY;
  566. }
  567. /* skipcomment should have changed the state */
  568. // Hmm hppens sometimes on valid files
  569. // if (linestate == LS_HASH) {
  570. // debug("bug at line %d", __LINE__);
  571. // abort(); /* bug */
  572. // }
  573. }
  574. if (linestate == LS_DIRTY) {
  575. while (*cp != '\0')
  576. cp = skipcomment(cp + 1);
  577. }
  578. debug("parser %s comment %s line",
  579. comment_name[incomment], linestate_name[linestate]);
  580. return (retval);
  581. }
  582. /*
  583. * These are the binary operators that are supported by the expression
  584. * evaluator. Note that if support for division is added then we also
  585. * need short-circuiting booleans because of divide-by-zero.
  586. */
  587. static int op_lt(int a, int b) { return (a < b); }
  588. static int op_gt(int a, int b) { return (a > b); }
  589. static int op_le(int a, int b) { return (a <= b); }
  590. static int op_ge(int a, int b) { return (a >= b); }
  591. static int op_eq(int a, int b) { return (a == b); }
  592. static int op_ne(int a, int b) { return (a != b); }
  593. static int op_or(int a, int b) { return (a || b); }
  594. static int op_and(int a, int b) { return (a && b); }
  595. /*
  596. * An evaluation function takes three arguments, as follows: (1) a pointer to
  597. * an element of the precedence table which lists the operators at the current
  598. * level of precedence; (2) a pointer to an integer which will receive the
  599. * value of the expression; and (3) a pointer to a char* that points to the
  600. * expression to be evaluated and that is updated to the end of the expression
  601. * when evaluation is complete. The function returns LT_FALSE if the value of
  602. * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
  603. * expression could not be evaluated.
  604. */
  605. struct ops;
  606. typedef Linetype eval_fn(const struct ops *, int *, const char **);
  607. static eval_fn eval_table, eval_unary;
  608. /*
  609. * The precedence table. Expressions involving binary operators are evaluated
  610. * in a table-driven way by eval_table. When it evaluates a subexpression it
  611. * calls the inner function with its first argument pointing to the next
  612. * element of the table. Innermost expressions have special non-table-driven
  613. * handling.
  614. */
  615. static const struct ops {
  616. eval_fn *inner;
  617. struct op {
  618. const char *str;
  619. int short_circuit_val;
  620. int (*fn)(int, int);
  621. } op[5];
  622. } eval_ops[] = {
  623. { eval_table, { { "||", 1, op_or } } },
  624. { eval_table, { { "&&", 0, op_and } } },
  625. { eval_table, { { "==", -1, op_eq },
  626. { "!=", -1, op_ne } } },
  627. { eval_unary, { { "<=", -1, op_le },
  628. { ">=", -1, op_ge },
  629. { "<", -1, op_lt },
  630. { ">", -1, op_gt } } }
  631. };
  632. /*
  633. * Function for evaluating the innermost parts of expressions, viz.
  634. * "!expr", "(expr)", "defined(symbol)", "defined symbol", "symbol", "number".
  635. * We reset the keepthis flag when we find a non-constant subexpression.
  636. */
  637. // TODO: we use LT_IF both as "I don't know whether it's false or true"
  638. // (example: "#if defined FOO") and when we see syntax error
  639. // (example: "#if (1 || 2" - no closing paren!), but this is wrong.
  640. // Binary && and || need to distinguish these cases in order to handle this:
  641. // "#if defined KNOWN_UNDEFINED && FOO" - discard
  642. // "#if defined KNOWN_UNDEFINED && (syntax_error_here" - do not discard!
  643. static Linetype
  644. eval_unary(const struct ops *ops, int *valp, const char **cpp)
  645. {
  646. const char *cp;
  647. char *ep;
  648. int sym;
  649. cp = skipcomment(*cpp);
  650. if (*cp == '!') {
  651. debug("eval%d !", ops - eval_ops);
  652. cp++;
  653. if (eval_unary(ops, valp, &cp) == LT_IF) {
  654. *cpp = cp;
  655. return (LT_IF);
  656. }
  657. *valp = !*valp;
  658. } else if (*cp == '(') {
  659. Linetype expr_res;
  660. cp++;
  661. debug("eval%d (%s", ops - eval_ops, cp);
  662. expr_res = eval_table(eval_ops, valp, &cp);
  663. cp = skipcomment(cp);
  664. *cpp = cp;
  665. if (*cp++ != ')')
  666. return (LT_IF);
  667. *cpp = cp;
  668. if (expr_res == LT_IF)
  669. return (LT_IF);
  670. } else if (isdigit((unsigned char)*cp)) {
  671. debug("eval%d number", ops - eval_ops);
  672. *valp = strtol(cp, &ep, 0);
  673. cp = skipsym(cp);
  674. } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
  675. bool parens;
  676. cp = skipcomment(cp+7);
  677. debug("eval%d defined '%s'", ops - eval_ops, cp);
  678. parens = (*cp == '(');
  679. if (parens)
  680. cp = skipcomment(cp+1);
  681. sym = findsym(cp);
  682. cp = skipsym(cp);
  683. cp = skipcomment(cp);
  684. if (parens) {
  685. if (*cp != ')')
  686. return (LT_IF);
  687. cp = skipcomment(cp+1);
  688. }
  689. *cpp = cp;
  690. if (sym < 0) {
  691. debug("sym not found, returning LT_IF");
  692. return (LT_IF);
  693. }
  694. *valp = (value[sym] != NULL);
  695. keepthis = false;
  696. } else if (!endsym(*cp)) {
  697. debug("eval%d symbol", ops - eval_ops);
  698. sym = findsym(cp);
  699. cp = skipsym(cp);
  700. *cpp = cp;
  701. if (sym < 0)
  702. return (LT_IF);
  703. if (value[sym] == NULL)
  704. *valp = 0;
  705. else {
  706. *valp = strtol(value[sym], &ep, 0);
  707. if (*ep != '\0' || ep == value[sym])
  708. return (LT_IF);
  709. }
  710. keepthis = false;
  711. } else {
  712. debug("eval%d bad expr", ops - eval_ops);
  713. return (LT_IF);
  714. }
  715. *cpp = cp;
  716. debug("eval%d = %d", ops - eval_ops, *valp);
  717. return (*valp ? LT_TRUE : LT_FALSE);
  718. }
  719. /*
  720. * Table-driven evaluation of binary operators.
  721. */
  722. static Linetype
  723. eval_table(const struct ops *ops, int *valp, const char **cpp)
  724. {
  725. Linetype left_side;
  726. const struct op *op;
  727. const char *cp;
  728. int val;
  729. debug("eval%d '%s'", ops - eval_ops, *cpp);
  730. left_side = ops->inner(ops+1, valp, cpp);
  731. cp = *cpp;
  732. for (;;) {
  733. Linetype right_side;
  734. cp = skipcomment(cp);
  735. for (op = ops->op; op->str != NULL; op++)
  736. if (strncmp(cp, op->str, strlen(op->str)) == 0)
  737. break;
  738. if (op->str == NULL)
  739. break;
  740. cp += strlen(op->str);
  741. debug("eval%d '%s'", ops - eval_ops, op->str);
  742. right_side = ops->inner(ops+1, &val, &cp);
  743. *cpp = cp;
  744. /* If short_circuit_val is 0 or 1, we can ignore
  745. * right side if left size is known, and its value
  746. * (i.e., *valp) is 0 or !0, respectively */
  747. if (left_side != LT_IF && op->short_circuit_val == !!*valp) {
  748. debug("op->short_circuit_val:%d *valp:%d cp:'%s'",
  749. op->short_circuit_val, *valp, cp);
  750. *valp = !!*valp;
  751. break;
  752. }
  753. /* Same for the right side */
  754. if (right_side != LT_IF && op->short_circuit_val == !!val) {
  755. debug("op->short_circuit_val:%d val:%d cp:'%s'",
  756. op->short_circuit_val, val, cp);
  757. left_side = right_side;
  758. *valp = !!val;
  759. break;
  760. }
  761. if (left_side == LT_IF || right_side == LT_IF)
  762. return (LT_IF);
  763. *valp = op->fn(*valp, val);
  764. left_side = right_side;
  765. }
  766. debug("eval%d = %d LT_IF:%d", ops - eval_ops, *valp, (left_side == LT_IF));
  767. if (left_side == LT_IF)
  768. return (LT_IF);
  769. return (*valp ? LT_TRUE : LT_FALSE);
  770. }
  771. /*
  772. * Evaluate the expression on a #if or #elif line. If we can work out
  773. * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
  774. * return just a generic LT_IF.
  775. */
  776. static Linetype
  777. ifeval(const char **cpp)
  778. {
  779. int ret;
  780. int val;
  781. debug("eval %s", *cpp);
  782. keepthis = killconsts ? false : true;
  783. ret = eval_table(eval_ops, &val, cpp);
  784. debug("val:%d ret:%d keepthis:%d", val, ret, keepthis);
  785. return (keepthis ? LT_IF : ret);
  786. }
  787. /*
  788. * Skip over comments, strings, and character literals and stop at the
  789. * next character position that is not whitespace. Between calls we keep
  790. * the comment state in the global variable incomment, and we also adjust
  791. * the global variable linestate when we see a newline.
  792. * XXX: doesn't cope with the buffer splitting inside a state transition.
  793. */
  794. static const char *
  795. skipcomment(const char *cp)
  796. {
  797. if (text || ignoring[depth]) {
  798. for (; isspace((unsigned char)*cp); cp++)
  799. if (*cp == '\n')
  800. linestate = LS_START;
  801. return (cp);
  802. }
  803. while (*cp != '\0')
  804. /* don't reset to LS_START after a line continuation */
  805. if (strncmp(cp, "\\\n", 2) == 0)
  806. cp += 2;
  807. else switch (incomment) {
  808. case NO_COMMENT:
  809. if (strncmp(cp, "/\\\n", 3) == 0) {
  810. incomment = STARTING_COMMENT;
  811. cp += 3;
  812. } else if (strncmp(cp, "/*", 2) == 0) {
  813. incomment = C_COMMENT;
  814. cp += 2;
  815. } else if (strncmp(cp, "//", 2) == 0) {
  816. incomment = CXX_COMMENT;
  817. cp += 2;
  818. } else if (strncmp(cp, "\'", 1) == 0) {
  819. incomment = CHAR_LITERAL;
  820. linestate = LS_DIRTY;
  821. cp += 1;
  822. } else if (strncmp(cp, "\"", 1) == 0) {
  823. incomment = STRING_LITERAL;
  824. linestate = LS_DIRTY;
  825. cp += 1;
  826. } else if (strncmp(cp, "\n", 1) == 0) {
  827. linestate = LS_START;
  828. cp += 1;
  829. } else if (strchr(" \t", *cp) != NULL) {
  830. cp += 1;
  831. } else
  832. return (cp);
  833. continue;
  834. case CXX_COMMENT:
  835. if (strncmp(cp, "\n", 1) == 0) {
  836. incomment = NO_COMMENT;
  837. linestate = LS_START;
  838. }
  839. cp += 1;
  840. continue;
  841. case CHAR_LITERAL:
  842. case STRING_LITERAL:
  843. if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
  844. (incomment == STRING_LITERAL && cp[0] == '\"')) {
  845. incomment = NO_COMMENT;
  846. cp += 1;
  847. } else if (cp[0] == '\\') {
  848. if (cp[1] == '\0')
  849. cp += 1;
  850. else
  851. cp += 2;
  852. } else if (strncmp(cp, "\n", 1) == 0) {
  853. if (incomment == CHAR_LITERAL)
  854. error("unterminated char literal");
  855. else
  856. error("unterminated string literal");
  857. } else
  858. cp += 1;
  859. continue;
  860. case C_COMMENT:
  861. if (strncmp(cp, "*\\\n", 3) == 0) {
  862. incomment = FINISHING_COMMENT;
  863. cp += 3;
  864. } else if (strncmp(cp, "*/", 2) == 0) {
  865. incomment = NO_COMMENT;
  866. cp += 2;
  867. } else
  868. cp += 1;
  869. continue;
  870. case STARTING_COMMENT:
  871. if (*cp == '*') {
  872. incomment = C_COMMENT;
  873. cp += 1;
  874. } else if (*cp == '/') {
  875. incomment = CXX_COMMENT;
  876. cp += 1;
  877. } else {
  878. incomment = NO_COMMENT;
  879. linestate = LS_DIRTY;
  880. }
  881. continue;
  882. case FINISHING_COMMENT:
  883. if (*cp == '/') {
  884. incomment = NO_COMMENT;
  885. cp += 1;
  886. } else
  887. incomment = C_COMMENT;
  888. continue;
  889. default:
  890. debug("bug at line %d", __LINE__);
  891. abort(); /* bug */
  892. }
  893. return (cp);
  894. }
  895. /*
  896. * Skip over an identifier.
  897. */
  898. static const char *
  899. skipsym(const char *cp)
  900. {
  901. while (!endsym(*cp))
  902. ++cp;
  903. return (cp);
  904. }
  905. /*
  906. * Look for the symbol in the symbol table. If is is found, we return
  907. * the symbol table index, else we return -1.
  908. */
  909. static int
  910. findsym(const char *str)
  911. {
  912. const char *cp;
  913. int symind;
  914. cp = skipsym(str);
  915. if (cp == str)
  916. return (-1);
  917. if (symlist) {
  918. printf("%.*s\n", (int)(cp-str), str);
  919. /* we don't care about the value of the symbol */
  920. return (0);
  921. }
  922. for (symind = 0; symind < nsyms; ++symind) {
  923. if (strlcmp(symname[symind], str, cp-str) == 0) {
  924. debug("findsym %s %s", symname[symind],
  925. value[symind] ? value[symind] : "");
  926. return (symind);
  927. }
  928. }
  929. return (-1);
  930. }
  931. /*
  932. * Add a symbol to the symbol table.
  933. */
  934. static void
  935. addsym(bool ignorethis, bool definethis, char *sym)
  936. {
  937. int symind;
  938. char *val;
  939. symind = findsym(sym);
  940. if (symind < 0) {
  941. if (nsyms >= MAXSYMS)
  942. errx(2, "too many symbols");
  943. symind = nsyms++;
  944. }
  945. symname[symind] = sym;
  946. ignore[symind] = ignorethis;
  947. val = sym + (skipsym(sym) - sym);
  948. if (definethis) {
  949. if (*val == '=') {
  950. value[symind] = val+1;
  951. *val = '\0';
  952. } else if (*val == '\0')
  953. value[symind] = "";
  954. else
  955. usage();
  956. } else {
  957. if (*val != '\0')
  958. usage();
  959. value[symind] = NULL;
  960. }
  961. }
  962. /*
  963. * Compare s with n characters of t.
  964. * The same as strncmp() except that it checks that s[n] == '\0'.
  965. */
  966. static int
  967. strlcmp(const char *s, const char *t, size_t n)
  968. {
  969. while (n-- && *t != '\0')
  970. if (*s != *t)
  971. return ((unsigned char)*s - (unsigned char)*t);
  972. else
  973. ++s, ++t;
  974. return ((unsigned char)*s);
  975. }
  976. /*
  977. * Diagnostics.
  978. */
  979. static void
  980. debug(const char *msg, ...)
  981. {
  982. va_list ap;
  983. if (debugging) {
  984. va_start(ap, msg);
  985. vwarnx(msg, ap);
  986. va_end(ap);
  987. }
  988. }
  989. static void
  990. error(const char *msg)
  991. {
  992. if (depth == 0)
  993. warnx("%s: %d: %s", filename, linenum, msg);
  994. else
  995. warnx("%s: %d: %s (#if line %d depth %d)",
  996. filename, linenum, msg, stifline[depth], depth);
  997. errx(2, "output may be truncated");
  998. }