unifdef.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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. 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 = get_line();
  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. get_line(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. *cpp = cp;
  640. return (LT_IF);
  641. }
  642. *valp = !*valp;
  643. } else if (*cp == '(') {
  644. cp++;
  645. debug("eval%d (", ops - eval_ops);
  646. if (eval_table(eval_ops, valp, &cp) == LT_IF)
  647. return (LT_IF);
  648. cp = skipcomment(cp);
  649. if (*cp++ != ')')
  650. return (LT_IF);
  651. } else if (isdigit((unsigned char)*cp)) {
  652. debug("eval%d number", ops - eval_ops);
  653. *valp = strtol(cp, &ep, 0);
  654. cp = skipsym(cp);
  655. } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
  656. cp = skipcomment(cp+7);
  657. debug("eval%d defined", ops - eval_ops);
  658. if (*cp++ != '(')
  659. return (LT_IF);
  660. cp = skipcomment(cp);
  661. sym = findsym(cp);
  662. cp = skipsym(cp);
  663. cp = skipcomment(cp);
  664. if (*cp++ != ')')
  665. return (LT_IF);
  666. if (sym >= 0)
  667. *valp = (value[sym] != NULL);
  668. else {
  669. *cpp = cp;
  670. return (LT_IF);
  671. }
  672. keepthis = false;
  673. } else if (!endsym(*cp)) {
  674. debug("eval%d symbol", ops - eval_ops);
  675. sym = findsym(cp);
  676. if (sym < 0)
  677. return (LT_IF);
  678. if (value[sym] == NULL)
  679. *valp = 0;
  680. else {
  681. *valp = strtol(value[sym], &ep, 0);
  682. if (*ep != '\0' || ep == value[sym])
  683. return (LT_IF);
  684. }
  685. cp = skipsym(cp);
  686. keepthis = false;
  687. } else {
  688. debug("eval%d bad expr", ops - eval_ops);
  689. return (LT_IF);
  690. }
  691. *cpp = cp;
  692. debug("eval%d = %d", ops - eval_ops, *valp);
  693. return (*valp ? LT_TRUE : LT_FALSE);
  694. }
  695. /*
  696. * Table-driven evaluation of binary operators.
  697. */
  698. static Linetype
  699. eval_table(const struct ops *ops, int *valp, const char **cpp)
  700. {
  701. const struct op *op;
  702. const char *cp;
  703. int val;
  704. Linetype lhs, rhs;
  705. debug("eval%d", ops - eval_ops);
  706. cp = *cpp;
  707. lhs = ops->inner(ops+1, valp, &cp);
  708. for (;;) {
  709. cp = skipcomment(cp);
  710. for (op = ops->op; op->str != NULL; op++)
  711. if (strncmp(cp, op->str, strlen(op->str)) == 0)
  712. break;
  713. if (op->str == NULL)
  714. break;
  715. cp += strlen(op->str);
  716. debug("eval%d %s", ops - eval_ops, op->str);
  717. rhs = ops->inner(ops+1, &val, &cp);
  718. if (op->fn == op_and && (lhs == LT_FALSE || rhs == LT_FALSE)) {
  719. debug("eval%d: and always false", ops - eval_ops);
  720. if (lhs == LT_IF)
  721. *valp = val;
  722. lhs = LT_FALSE;
  723. continue;
  724. }
  725. if (op->fn == op_or && (lhs == LT_TRUE || rhs == LT_TRUE)) {
  726. debug("eval%d: or always true", ops - eval_ops);
  727. if (lhs == LT_IF)
  728. *valp = val;
  729. lhs = LT_TRUE;
  730. continue;
  731. }
  732. if (rhs == LT_IF)
  733. lhs = LT_IF;
  734. if (lhs != LT_IF)
  735. *valp = op->fn(*valp, val);
  736. }
  737. *cpp = cp;
  738. debug("eval%d = %d", ops - eval_ops, *valp);
  739. if (lhs != LT_IF)
  740. lhs = (*valp ? LT_TRUE : LT_FALSE);
  741. return lhs;
  742. }
  743. /*
  744. * Evaluate the expression on a #if or #elif line. If we can work out
  745. * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
  746. * return just a generic LT_IF.
  747. */
  748. static Linetype
  749. ifeval(const char **cpp)
  750. {
  751. const char *cp = *cpp;
  752. int ret;
  753. int val;
  754. debug("eval %s", *cpp);
  755. keepthis = killconsts ? false : true;
  756. ret = eval_table(eval_ops, &val, &cp);
  757. if (ret != LT_IF)
  758. *cpp = cp;
  759. debug("eval = %d", val);
  760. return (keepthis ? LT_IF : ret);
  761. }
  762. /*
  763. * Skip over comments, strings, and character literals and stop at the
  764. * next character position that is not whitespace. Between calls we keep
  765. * the comment state in the global variable incomment, and we also adjust
  766. * the global variable linestate when we see a newline.
  767. * XXX: doesn't cope with the buffer splitting inside a state transition.
  768. */
  769. static const char *
  770. skipcomment(const char *cp)
  771. {
  772. if (text || ignoring[depth]) {
  773. for (; isspace((unsigned char)*cp); cp++)
  774. if (*cp == '\n')
  775. linestate = LS_START;
  776. return (cp);
  777. }
  778. while (*cp != '\0')
  779. /* don't reset to LS_START after a line continuation */
  780. if (strncmp(cp, "\\\n", 2) == 0)
  781. cp += 2;
  782. else switch (incomment) {
  783. case NO_COMMENT:
  784. if (strncmp(cp, "/\\\n", 3) == 0) {
  785. incomment = STARTING_COMMENT;
  786. cp += 3;
  787. } else if (strncmp(cp, "/*", 2) == 0) {
  788. incomment = C_COMMENT;
  789. cp += 2;
  790. } else if (strncmp(cp, "//", 2) == 0) {
  791. incomment = CXX_COMMENT;
  792. cp += 2;
  793. } else if (strncmp(cp, "\'", 1) == 0) {
  794. incomment = CHAR_LITERAL;
  795. linestate = LS_DIRTY;
  796. cp += 1;
  797. } else if (strncmp(cp, "\"", 1) == 0) {
  798. incomment = STRING_LITERAL;
  799. linestate = LS_DIRTY;
  800. cp += 1;
  801. } else if (strncmp(cp, "\n", 1) == 0) {
  802. linestate = LS_START;
  803. cp += 1;
  804. } else if (strchr(" \t", *cp) != NULL) {
  805. cp += 1;
  806. } else
  807. return (cp);
  808. continue;
  809. case CXX_COMMENT:
  810. if (strncmp(cp, "\n", 1) == 0) {
  811. incomment = NO_COMMENT;
  812. linestate = LS_START;
  813. }
  814. cp += 1;
  815. continue;
  816. case CHAR_LITERAL:
  817. case STRING_LITERAL:
  818. if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
  819. (incomment == STRING_LITERAL && cp[0] == '\"')) {
  820. incomment = NO_COMMENT;
  821. cp += 1;
  822. } else if (cp[0] == '\\') {
  823. if (cp[1] == '\0')
  824. cp += 1;
  825. else
  826. cp += 2;
  827. } else if (strncmp(cp, "\n", 1) == 0) {
  828. if (incomment == CHAR_LITERAL)
  829. error("unterminated char literal");
  830. else
  831. error("unterminated string literal");
  832. } else
  833. cp += 1;
  834. continue;
  835. case C_COMMENT:
  836. if (strncmp(cp, "*\\\n", 3) == 0) {
  837. incomment = FINISHING_COMMENT;
  838. cp += 3;
  839. } else if (strncmp(cp, "*/", 2) == 0) {
  840. incomment = NO_COMMENT;
  841. cp += 2;
  842. } else
  843. cp += 1;
  844. continue;
  845. case STARTING_COMMENT:
  846. if (*cp == '*') {
  847. incomment = C_COMMENT;
  848. cp += 1;
  849. } else if (*cp == '/') {
  850. incomment = CXX_COMMENT;
  851. cp += 1;
  852. } else {
  853. incomment = NO_COMMENT;
  854. linestate = LS_DIRTY;
  855. }
  856. continue;
  857. case FINISHING_COMMENT:
  858. if (*cp == '/') {
  859. incomment = NO_COMMENT;
  860. cp += 1;
  861. } else
  862. incomment = C_COMMENT;
  863. continue;
  864. default:
  865. abort(); /* bug */
  866. }
  867. return (cp);
  868. }
  869. /*
  870. * Skip over an identifier.
  871. */
  872. static const char *
  873. skipsym(const char *cp)
  874. {
  875. while (!endsym(*cp))
  876. ++cp;
  877. return (cp);
  878. }
  879. /*
  880. * Look for the symbol in the symbol table. If is is found, we return
  881. * the symbol table index, else we return -1.
  882. */
  883. static int
  884. findsym(const char *str)
  885. {
  886. const char *cp;
  887. int symind;
  888. cp = skipsym(str);
  889. if (cp == str)
  890. return (-1);
  891. if (symlist) {
  892. printf("%.*s\n", (int)(cp-str), str);
  893. /* we don't care about the value of the symbol */
  894. return (0);
  895. }
  896. for (symind = 0; symind < nsyms; ++symind) {
  897. if (strlcmp(symname[symind], str, cp-str) == 0) {
  898. debug("findsym %s %s", symname[symind],
  899. value[symind] ? value[symind] : "");
  900. return (symind);
  901. }
  902. }
  903. return (-1);
  904. }
  905. /*
  906. * Add a symbol to the symbol table.
  907. */
  908. static void
  909. addsym(bool ignorethis, bool definethis, char *sym)
  910. {
  911. int symind;
  912. char *val;
  913. symind = findsym(sym);
  914. if (symind < 0) {
  915. if (nsyms >= MAXSYMS)
  916. errx(2, "too many symbols");
  917. symind = nsyms++;
  918. }
  919. symname[symind] = sym;
  920. ignore[symind] = ignorethis;
  921. val = sym + (skipsym(sym) - sym);
  922. if (definethis) {
  923. if (*val == '=') {
  924. value[symind] = val+1;
  925. *val = '\0';
  926. } else if (*val == '\0')
  927. value[symind] = "";
  928. else
  929. usage();
  930. } else {
  931. if (*val != '\0')
  932. usage();
  933. value[symind] = NULL;
  934. }
  935. }
  936. /*
  937. * Compare s with n characters of t.
  938. * The same as strncmp() except that it checks that s[n] == '\0'.
  939. */
  940. static int
  941. strlcmp(const char *s, const char *t, size_t n)
  942. {
  943. while (n-- && *t != '\0')
  944. if (*s != *t)
  945. return ((unsigned char)*s - (unsigned char)*t);
  946. else
  947. ++s, ++t;
  948. return ((unsigned char)*s);
  949. }
  950. /*
  951. * Diagnostics.
  952. */
  953. static void
  954. debug(const char *msg, ...)
  955. {
  956. va_list ap;
  957. if (debugging) {
  958. va_start(ap, msg);
  959. vwarnx(msg, ap);
  960. va_end(ap);
  961. }
  962. }
  963. static void
  964. error(const char *msg)
  965. {
  966. if (depth == 0)
  967. warnx("%s: %d: %s", filename, linenum, msg);
  968. else
  969. warnx("%s: %d: %s (#if line %d depth %d)",
  970. filename, linenum, msg, stifline[depth], depth);
  971. errx(2, "output may be truncated");
  972. }