unifdef.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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 getline(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. abort(); /* bug */
  274. }
  275. static void
  276. usage(void)
  277. {
  278. fprintf(stderr, "usage: unifdef [-cdeklnst] [-Ipath]"
  279. " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
  280. exit(2);
  281. }
  282. /*
  283. * A state transition function alters the global #if processing state
  284. * in a particular way. The table below is indexed by the current
  285. * processing state and the type of the current line.
  286. *
  287. * Nesting is handled by keeping a stack of states; some transition
  288. * functions increase or decrease the depth. They also maintain the
  289. * ignore state on a stack. In some complicated cases they have to
  290. * alter the preprocessor directive, as follows.
  291. *
  292. * When we have processed a group that starts off with a known-false
  293. * #if/#elif sequence (which has therefore been deleted) followed by a
  294. * #elif that we don't understand and therefore must keep, we edit the
  295. * latter into a #if to keep the nesting correct.
  296. *
  297. * When we find a true #elif in a group, the following block will
  298. * always be kept and the rest of the sequence after the next #elif or
  299. * #else will be discarded. We edit the #elif into a #else and the
  300. * following directive to #endif since this has the desired behaviour.
  301. *
  302. * "Dodgy" directives are split across multiple lines, the most common
  303. * example being a multi-line comment hanging off the right of the
  304. * directive. We can handle them correctly only if there is no change
  305. * from printing to dropping (or vice versa) caused by that directive.
  306. * If the directive is the first of a group we have a choice between
  307. * failing with an error, or passing it through unchanged instead of
  308. * evaluating it. The latter is not the default to avoid questions from
  309. * users about unifdef unexpectedly leaving behind preprocessor directives.
  310. */
  311. typedef void state_fn(void);
  312. /* report an error */
  313. static void Eelif (void) { error("Inappropriate #elif"); }
  314. static void Eelse (void) { error("Inappropriate #else"); }
  315. static void Eendif(void) { error("Inappropriate #endif"); }
  316. static void Eeof (void) { error("Premature EOF"); }
  317. static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
  318. /* plain line handling */
  319. static void print (void) { flushline(true); }
  320. static void drop (void) { flushline(false); }
  321. /* output lacks group's start line */
  322. static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
  323. static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
  324. static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
  325. /* print/pass this block */
  326. static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
  327. static void Pelse (void) { print(); state(IS_PASS_ELSE); }
  328. static void Pendif(void) { print(); unnest(); }
  329. /* discard this block */
  330. static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
  331. static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
  332. static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
  333. static void Dendif(void) { drop(); unnest(); }
  334. /* first line of group */
  335. static void Fdrop (void) { nest(); Dfalse(); }
  336. static void Fpass (void) { nest(); Pelif(); }
  337. static void Ftrue (void) { nest(); Strue(); }
  338. static void Ffalse(void) { nest(); Sfalse(); }
  339. /* variable pedantry for obfuscated lines */
  340. static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
  341. static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
  342. static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
  343. /* ignore comments in this block */
  344. static void Idrop (void) { Fdrop(); ignoreon(); }
  345. static void Itrue (void) { Ftrue(); ignoreon(); }
  346. static void Ifalse(void) { Ffalse(); ignoreon(); }
  347. /* edit this line */
  348. static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
  349. static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
  350. static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
  351. static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
  352. static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
  353. /* IS_OUTSIDE */
  354. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
  355. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
  356. print, done },
  357. /* IS_FALSE_PREFIX */
  358. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
  359. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
  360. drop, Eeof },
  361. /* IS_TRUE_PREFIX */
  362. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
  363. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  364. print, Eeof },
  365. /* IS_PASS_MIDDLE */
  366. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
  367. Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
  368. print, Eeof },
  369. /* IS_FALSE_MIDDLE */
  370. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
  371. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  372. drop, Eeof },
  373. /* IS_TRUE_MIDDLE */
  374. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
  375. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
  376. print, Eeof },
  377. /* IS_PASS_ELSE */
  378. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
  379. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
  380. print, Eeof },
  381. /* IS_FALSE_ELSE */
  382. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
  383. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
  384. drop, Eeof },
  385. /* IS_TRUE_ELSE */
  386. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
  387. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
  388. print, Eeof },
  389. /* IS_FALSE_TRAILER */
  390. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
  391. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
  392. drop, Eeof }
  393. /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
  394. TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
  395. PLAIN EOF */
  396. };
  397. /*
  398. * State machine utility functions
  399. */
  400. static void
  401. done(void)
  402. {
  403. if (incomment)
  404. error("EOF in comment");
  405. exit(exitstat);
  406. }
  407. static void
  408. ignoreoff(void)
  409. {
  410. if (depth == 0)
  411. abort(); /* bug */
  412. ignoring[depth] = ignoring[depth-1];
  413. }
  414. static void
  415. ignoreon(void)
  416. {
  417. ignoring[depth] = true;
  418. }
  419. static void
  420. keywordedit(const char *replacement)
  421. {
  422. size_t size = tline + sizeof(tline) - keyword;
  423. char *dst = keyword;
  424. const char *src = replacement;
  425. if (size != 0) {
  426. while ((--size != 0) && (*src != '\0'))
  427. *dst++ = *src++;
  428. *dst = '\0';
  429. }
  430. print();
  431. }
  432. static void
  433. nest(void)
  434. {
  435. depth += 1;
  436. if (depth >= MAXDEPTH)
  437. error("Too many levels of nesting");
  438. stifline[depth] = linenum;
  439. }
  440. static void
  441. unnest(void)
  442. {
  443. if (depth == 0)
  444. abort(); /* bug */
  445. depth -= 1;
  446. }
  447. static void
  448. state(Ifstate is)
  449. {
  450. ifstate[depth] = is;
  451. }
  452. /*
  453. * Write a line to the output or not, according to command line options.
  454. */
  455. static void
  456. flushline(bool keep)
  457. {
  458. if (symlist)
  459. return;
  460. if (keep ^ complement) {
  461. if (lnnum && delcount > 0)
  462. printf("#line %d\n", linenum);
  463. fputs(tline, stdout);
  464. delcount = 0;
  465. } else {
  466. if (lnblank)
  467. putc('\n', stdout);
  468. exitstat = 1;
  469. delcount += 1;
  470. }
  471. }
  472. /*
  473. * The driver for the state machine.
  474. */
  475. static void
  476. process(void)
  477. {
  478. Linetype lineval;
  479. for (;;) {
  480. linenum++;
  481. lineval = getline();
  482. trans_table[ifstate[depth]][lineval]();
  483. debug("process %s -> %s depth %d",
  484. linetype_name[lineval],
  485. ifstate_name[ifstate[depth]], depth);
  486. }
  487. }
  488. /*
  489. * Parse a line and determine its type. We keep the preprocessor line
  490. * parser state between calls in the global variable linestate, with
  491. * help from skipcomment().
  492. */
  493. static Linetype
  494. getline(void)
  495. {
  496. const char *cp;
  497. int cursym;
  498. int kwlen;
  499. Linetype retval;
  500. Comment_state wascomment;
  501. if (fgets(tline, MAXLINE, input) == NULL)
  502. return (LT_EOF);
  503. retval = LT_PLAIN;
  504. wascomment = incomment;
  505. cp = skipcomment(tline);
  506. if (linestate == LS_START) {
  507. if (*cp == '#') {
  508. linestate = LS_HASH;
  509. cp = skipcomment(cp + 1);
  510. } else if (*cp != '\0')
  511. linestate = LS_DIRTY;
  512. }
  513. if (!incomment && linestate == LS_HASH) {
  514. keyword = tline + (cp - tline);
  515. cp = skipsym(cp);
  516. kwlen = cp - keyword;
  517. /* no way can we deal with a continuation inside a keyword */
  518. if (strncmp(cp, "\\\n", 2) == 0)
  519. Eioccc();
  520. if (strlcmp("ifdef", keyword, kwlen) == 0 ||
  521. strlcmp("ifndef", keyword, kwlen) == 0) {
  522. cp = skipcomment(cp);
  523. if ((cursym = findsym(cp)) < 0)
  524. retval = LT_IF;
  525. else {
  526. retval = (keyword[2] == 'n')
  527. ? LT_FALSE : LT_TRUE;
  528. if (value[cursym] == NULL)
  529. retval = (retval == LT_TRUE)
  530. ? LT_FALSE : LT_TRUE;
  531. if (ignore[cursym])
  532. retval = (retval == LT_TRUE)
  533. ? LT_TRUEI : LT_FALSEI;
  534. }
  535. cp = skipsym(cp);
  536. } else if (strlcmp("if", keyword, kwlen) == 0)
  537. retval = ifeval(&cp);
  538. else if (strlcmp("elif", keyword, kwlen) == 0)
  539. retval = ifeval(&cp) - LT_IF + LT_ELIF;
  540. else if (strlcmp("else", keyword, kwlen) == 0)
  541. retval = LT_ELSE;
  542. else if (strlcmp("endif", keyword, kwlen) == 0)
  543. retval = LT_ENDIF;
  544. else {
  545. linestate = LS_DIRTY;
  546. retval = LT_PLAIN;
  547. }
  548. cp = skipcomment(cp);
  549. if (*cp != '\0') {
  550. linestate = LS_DIRTY;
  551. if (retval == LT_TRUE || retval == LT_FALSE ||
  552. retval == LT_TRUEI || retval == LT_FALSEI)
  553. retval = LT_IF;
  554. if (retval == LT_ELTRUE || retval == LT_ELFALSE)
  555. retval = LT_ELIF;
  556. }
  557. if (retval != LT_PLAIN && (wascomment || incomment)) {
  558. retval += LT_DODGY;
  559. if (incomment)
  560. linestate = LS_DIRTY;
  561. }
  562. /* skipcomment should have changed the state */
  563. if (linestate == LS_HASH)
  564. abort(); /* bug */
  565. }
  566. if (linestate == LS_DIRTY) {
  567. while (*cp != '\0')
  568. cp = skipcomment(cp + 1);
  569. }
  570. debug("parser %s comment %s line",
  571. comment_name[incomment], linestate_name[linestate]);
  572. return (retval);
  573. }
  574. /*
  575. * These are the binary operators that are supported by the expression
  576. * evaluator. Note that if support for division is added then we also
  577. * need short-circuiting booleans because of divide-by-zero.
  578. */
  579. static int op_lt(int a, int b) { return (a < b); }
  580. static int op_gt(int a, int b) { return (a > b); }
  581. static int op_le(int a, int b) { return (a <= b); }
  582. static int op_ge(int a, int b) { return (a >= b); }
  583. static int op_eq(int a, int b) { return (a == b); }
  584. static int op_ne(int a, int b) { return (a != b); }
  585. static int op_or(int a, int b) { return (a || b); }
  586. static int op_and(int a, int b) { return (a && b); }
  587. /*
  588. * An evaluation function takes three arguments, as follows: (1) a pointer to
  589. * an element of the precedence table which lists the operators at the current
  590. * level of precedence; (2) a pointer to an integer which will receive the
  591. * value of the expression; and (3) a pointer to a char* that points to the
  592. * expression to be evaluated and that is updated to the end of the expression
  593. * when evaluation is complete. The function returns LT_FALSE if the value of
  594. * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the
  595. * expression could not be evaluated.
  596. */
  597. struct ops;
  598. typedef Linetype eval_fn(const struct ops *, int *, const char **);
  599. static eval_fn eval_table, eval_unary;
  600. /*
  601. * The precedence table. Expressions involving binary operators are evaluated
  602. * in a table-driven way by eval_table. When it evaluates a subexpression it
  603. * calls the inner function with its first argument pointing to the next
  604. * element of the table. Innermost expressions have special non-table-driven
  605. * handling.
  606. */
  607. static const struct ops {
  608. eval_fn *inner;
  609. struct op {
  610. const char *str;
  611. int (*fn)(int, int);
  612. } op[5];
  613. } eval_ops[] = {
  614. { eval_table, { { "||", op_or } } },
  615. { eval_table, { { "&&", op_and } } },
  616. { eval_table, { { "==", op_eq },
  617. { "!=", op_ne } } },
  618. { eval_unary, { { "<=", op_le },
  619. { ">=", op_ge },
  620. { "<", op_lt },
  621. { ">", op_gt } } }
  622. };
  623. /*
  624. * Function for evaluating the innermost parts of expressions,
  625. * viz. !expr (expr) defined(symbol) symbol number
  626. * We reset the keepthis flag when we find a non-constant subexpression.
  627. */
  628. static Linetype
  629. eval_unary(const struct ops *ops, int *valp, const char **cpp)
  630. {
  631. const char *cp;
  632. char *ep;
  633. int sym;
  634. cp = skipcomment(*cpp);
  635. if (*cp == '!') {
  636. debug("eval%d !", ops - eval_ops);
  637. cp++;
  638. if (eval_unary(ops, valp, &cp) == LT_IF)
  639. return (LT_IF);
  640. *valp = !*valp;
  641. } else if (*cp == '(') {
  642. cp++;
  643. debug("eval%d (", ops - eval_ops);
  644. if (eval_table(eval_ops, valp, &cp) == LT_IF)
  645. return (LT_IF);
  646. cp = skipcomment(cp);
  647. if (*cp++ != ')')
  648. return (LT_IF);
  649. } else if (isdigit((unsigned char)*cp)) {
  650. debug("eval%d number", ops - eval_ops);
  651. *valp = strtol(cp, &ep, 0);
  652. cp = skipsym(cp);
  653. } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
  654. cp = skipcomment(cp+7);
  655. debug("eval%d defined", ops - eval_ops);
  656. if (*cp++ != '(')
  657. return (LT_IF);
  658. cp = skipcomment(cp);
  659. sym = findsym(cp);
  660. if (sym < 0)
  661. return (LT_IF);
  662. *valp = (value[sym] != NULL);
  663. cp = skipsym(cp);
  664. cp = skipcomment(cp);
  665. if (*cp++ != ')')
  666. return (LT_IF);
  667. keepthis = false;
  668. } else if (!endsym(*cp)) {
  669. debug("eval%d symbol", ops - eval_ops);
  670. sym = findsym(cp);
  671. if (sym < 0)
  672. return (LT_IF);
  673. if (value[sym] == NULL)
  674. *valp = 0;
  675. else {
  676. *valp = strtol(value[sym], &ep, 0);
  677. if (*ep != '\0' || ep == value[sym])
  678. return (LT_IF);
  679. }
  680. cp = skipsym(cp);
  681. keepthis = false;
  682. } else {
  683. debug("eval%d bad expr", ops - eval_ops);
  684. return (LT_IF);
  685. }
  686. *cpp = cp;
  687. debug("eval%d = %d", ops - eval_ops, *valp);
  688. return (*valp ? LT_TRUE : LT_FALSE);
  689. }
  690. /*
  691. * Table-driven evaluation of binary operators.
  692. */
  693. static Linetype
  694. eval_table(const struct ops *ops, int *valp, const char **cpp)
  695. {
  696. const struct op *op;
  697. const char *cp;
  698. int val;
  699. debug("eval%d", ops - eval_ops);
  700. cp = *cpp;
  701. if (ops->inner(ops+1, valp, &cp) == LT_IF)
  702. return (LT_IF);
  703. for (;;) {
  704. cp = skipcomment(cp);
  705. for (op = ops->op; op->str != NULL; op++)
  706. if (strncmp(cp, op->str, strlen(op->str)) == 0)
  707. break;
  708. if (op->str == NULL)
  709. break;
  710. cp += strlen(op->str);
  711. debug("eval%d %s", ops - eval_ops, op->str);
  712. if (ops->inner(ops+1, &val, &cp) == LT_IF)
  713. return (LT_IF);
  714. *valp = op->fn(*valp, val);
  715. }
  716. *cpp = cp;
  717. debug("eval%d = %d", ops - eval_ops, *valp);
  718. return (*valp ? LT_TRUE : LT_FALSE);
  719. }
  720. /*
  721. * Evaluate the expression on a #if or #elif line. If we can work out
  722. * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
  723. * return just a generic LT_IF.
  724. */
  725. static Linetype
  726. ifeval(const char **cpp)
  727. {
  728. int ret;
  729. int val;
  730. debug("eval %s", *cpp);
  731. keepthis = killconsts ? false : true;
  732. ret = eval_table(eval_ops, &val, cpp);
  733. debug("eval = %d", val);
  734. return (keepthis ? LT_IF : ret);
  735. }
  736. /*
  737. * Skip over comments, strings, and character literals and stop at the
  738. * next character position that is not whitespace. Between calls we keep
  739. * the comment state in the global variable incomment, and we also adjust
  740. * the global variable linestate when we see a newline.
  741. * XXX: doesn't cope with the buffer splitting inside a state transition.
  742. */
  743. static const char *
  744. skipcomment(const char *cp)
  745. {
  746. if (text || ignoring[depth]) {
  747. for (; isspace((unsigned char)*cp); cp++)
  748. if (*cp == '\n')
  749. linestate = LS_START;
  750. return (cp);
  751. }
  752. while (*cp != '\0')
  753. /* don't reset to LS_START after a line continuation */
  754. if (strncmp(cp, "\\\n", 2) == 0)
  755. cp += 2;
  756. else switch (incomment) {
  757. case NO_COMMENT:
  758. if (strncmp(cp, "/\\\n", 3) == 0) {
  759. incomment = STARTING_COMMENT;
  760. cp += 3;
  761. } else if (strncmp(cp, "/*", 2) == 0) {
  762. incomment = C_COMMENT;
  763. cp += 2;
  764. } else if (strncmp(cp, "//", 2) == 0) {
  765. incomment = CXX_COMMENT;
  766. cp += 2;
  767. } else if (strncmp(cp, "\'", 1) == 0) {
  768. incomment = CHAR_LITERAL;
  769. linestate = LS_DIRTY;
  770. cp += 1;
  771. } else if (strncmp(cp, "\"", 1) == 0) {
  772. incomment = STRING_LITERAL;
  773. linestate = LS_DIRTY;
  774. cp += 1;
  775. } else if (strncmp(cp, "\n", 1) == 0) {
  776. linestate = LS_START;
  777. cp += 1;
  778. } else if (strchr(" \t", *cp) != NULL) {
  779. cp += 1;
  780. } else
  781. return (cp);
  782. continue;
  783. case CXX_COMMENT:
  784. if (strncmp(cp, "\n", 1) == 0) {
  785. incomment = NO_COMMENT;
  786. linestate = LS_START;
  787. }
  788. cp += 1;
  789. continue;
  790. case CHAR_LITERAL:
  791. case STRING_LITERAL:
  792. if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
  793. (incomment == STRING_LITERAL && cp[0] == '\"')) {
  794. incomment = NO_COMMENT;
  795. cp += 1;
  796. } else if (cp[0] == '\\') {
  797. if (cp[1] == '\0')
  798. cp += 1;
  799. else
  800. cp += 2;
  801. } else if (strncmp(cp, "\n", 1) == 0) {
  802. if (incomment == CHAR_LITERAL)
  803. error("unterminated char literal");
  804. else
  805. error("unterminated string literal");
  806. } else
  807. cp += 1;
  808. continue;
  809. case C_COMMENT:
  810. if (strncmp(cp, "*\\\n", 3) == 0) {
  811. incomment = FINISHING_COMMENT;
  812. cp += 3;
  813. } else if (strncmp(cp, "*/", 2) == 0) {
  814. incomment = NO_COMMENT;
  815. cp += 2;
  816. } else
  817. cp += 1;
  818. continue;
  819. case STARTING_COMMENT:
  820. if (*cp == '*') {
  821. incomment = C_COMMENT;
  822. cp += 1;
  823. } else if (*cp == '/') {
  824. incomment = CXX_COMMENT;
  825. cp += 1;
  826. } else {
  827. incomment = NO_COMMENT;
  828. linestate = LS_DIRTY;
  829. }
  830. continue;
  831. case FINISHING_COMMENT:
  832. if (*cp == '/') {
  833. incomment = NO_COMMENT;
  834. cp += 1;
  835. } else
  836. incomment = C_COMMENT;
  837. continue;
  838. default:
  839. abort(); /* bug */
  840. }
  841. return (cp);
  842. }
  843. /*
  844. * Skip over an identifier.
  845. */
  846. static const char *
  847. skipsym(const char *cp)
  848. {
  849. while (!endsym(*cp))
  850. ++cp;
  851. return (cp);
  852. }
  853. /*
  854. * Look for the symbol in the symbol table. If is is found, we return
  855. * the symbol table index, else we return -1.
  856. */
  857. static int
  858. findsym(const char *str)
  859. {
  860. const char *cp;
  861. int symind;
  862. cp = skipsym(str);
  863. if (cp == str)
  864. return (-1);
  865. if (symlist) {
  866. printf("%.*s\n", (int)(cp-str), str);
  867. /* we don't care about the value of the symbol */
  868. return (0);
  869. }
  870. for (symind = 0; symind < nsyms; ++symind) {
  871. if (strlcmp(symname[symind], str, cp-str) == 0) {
  872. debug("findsym %s %s", symname[symind],
  873. value[symind] ? value[symind] : "");
  874. return (symind);
  875. }
  876. }
  877. return (-1);
  878. }
  879. /*
  880. * Add a symbol to the symbol table.
  881. */
  882. static void
  883. addsym(bool ignorethis, bool definethis, char *sym)
  884. {
  885. int symind;
  886. char *val;
  887. symind = findsym(sym);
  888. if (symind < 0) {
  889. if (nsyms >= MAXSYMS)
  890. errx(2, "too many symbols");
  891. symind = nsyms++;
  892. }
  893. symname[symind] = sym;
  894. ignore[symind] = ignorethis;
  895. val = sym + (skipsym(sym) - sym);
  896. if (definethis) {
  897. if (*val == '=') {
  898. value[symind] = val+1;
  899. *val = '\0';
  900. } else if (*val == '\0')
  901. value[symind] = "";
  902. else
  903. usage();
  904. } else {
  905. if (*val != '\0')
  906. usage();
  907. value[symind] = NULL;
  908. }
  909. }
  910. /*
  911. * Compare s with n characters of t.
  912. * The same as strncmp() except that it checks that s[n] == '\0'.
  913. */
  914. static int
  915. strlcmp(const char *s, const char *t, size_t n)
  916. {
  917. while (n-- && *t != '\0')
  918. if (*s != *t)
  919. return ((unsigned char)*s - (unsigned char)*t);
  920. else
  921. ++s, ++t;
  922. return ((unsigned char)*s);
  923. }
  924. /*
  925. * Diagnostics.
  926. */
  927. static void
  928. debug(const char *msg, ...)
  929. {
  930. va_list ap;
  931. if (debugging) {
  932. va_start(ap, msg);
  933. vwarnx(msg, ap);
  934. va_end(ap);
  935. }
  936. }
  937. static void
  938. error(const char *msg)
  939. {
  940. if (depth == 0)
  941. warnx("%s: %d: %s", filename, linenum, msg);
  942. else
  943. warnx("%s: %d: %s (#if line %d depth %d)",
  944. filename, linenum, msg, stifline[depth], depth);
  945. errx(2, "output may be truncated");
  946. }