unifdef.c 43 KB

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