unifdef.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. /*
  2. * Copyright (c) 2002 - 2011 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 <sys/types.h>
  45. #include <sys/stat.h>
  46. #include <ctype.h>
  47. #include <err.h>
  48. #include <errno.h>
  49. #include <stdarg.h>
  50. #include <stdbool.h>
  51. #include <stdio.h>
  52. #include <stdlib.h>
  53. #include <string.h>
  54. #include <unistd.h>
  55. const char copyright[] =
  56. "@(#) $Version: unifdef-2.5 $\n"
  57. "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
  58. "@(#) $URL: http://dotat.at/prog/unifdef $\n"
  59. ;
  60. /* types of input lines: */
  61. typedef enum {
  62. LT_TRUEI, /* a true #if with ignore flag */
  63. LT_FALSEI, /* a false #if with ignore flag */
  64. LT_IF, /* an unknown #if */
  65. LT_TRUE, /* a true #if */
  66. LT_FALSE, /* a false #if */
  67. LT_ELIF, /* an unknown #elif */
  68. LT_ELTRUE, /* a true #elif */
  69. LT_ELFALSE, /* a false #elif */
  70. LT_ELSE, /* #else */
  71. LT_ENDIF, /* #endif */
  72. LT_DODGY, /* flag: directive is not on one line */
  73. LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
  74. LT_PLAIN, /* ordinary line */
  75. LT_EOF, /* end of file */
  76. LT_ERROR, /* unevaluable #if */
  77. LT_COUNT
  78. } Linetype;
  79. static char const * const linetype_name[] = {
  80. "TRUEI", "FALSEI", "IF", "TRUE", "FALSE",
  81. "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF",
  82. "DODGY TRUEI", "DODGY FALSEI",
  83. "DODGY IF", "DODGY TRUE", "DODGY FALSE",
  84. "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
  85. "DODGY ELSE", "DODGY ENDIF",
  86. "PLAIN", "EOF", "ERROR"
  87. };
  88. /* state of #if processing */
  89. typedef enum {
  90. IS_OUTSIDE,
  91. IS_FALSE_PREFIX, /* false #if followed by false #elifs */
  92. IS_TRUE_PREFIX, /* first non-false #(el)if is true */
  93. IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */
  94. IS_FALSE_MIDDLE, /* a false #elif after a pass state */
  95. IS_TRUE_MIDDLE, /* a true #elif after a pass state */
  96. IS_PASS_ELSE, /* an else after a pass state */
  97. IS_FALSE_ELSE, /* an else after a true state */
  98. IS_TRUE_ELSE, /* an else after only false states */
  99. IS_FALSE_TRAILER, /* #elifs after a true are false */
  100. IS_COUNT
  101. } Ifstate;
  102. static char const * const ifstate_name[] = {
  103. "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX",
  104. "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE",
  105. "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE",
  106. "FALSE_TRAILER"
  107. };
  108. /* state of comment parser */
  109. typedef enum {
  110. NO_COMMENT = false, /* outside a comment */
  111. C_COMMENT, /* in a comment like this one */
  112. CXX_COMMENT, /* between // and end of line */
  113. STARTING_COMMENT, /* just after slash-backslash-newline */
  114. FINISHING_COMMENT, /* star-backslash-newline in a C comment */
  115. CHAR_LITERAL, /* inside '' */
  116. STRING_LITERAL /* inside "" */
  117. } Comment_state;
  118. static char const * const comment_name[] = {
  119. "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
  120. };
  121. /* state of preprocessor line parser */
  122. typedef enum {
  123. LS_START, /* only space and comments on this line */
  124. LS_HASH, /* only space, comments, and a hash */
  125. LS_DIRTY /* this line can't be a preprocessor line */
  126. } Line_state;
  127. static char const * const linestate_name[] = {
  128. "START", "HASH", "DIRTY"
  129. };
  130. /*
  131. * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1
  132. */
  133. #define MAXDEPTH 64 /* maximum #if nesting */
  134. #define MAXLINE 4096 /* maximum length of line */
  135. #define MAXSYMS 4096 /* maximum number of symbols */
  136. /*
  137. * Sometimes when editing a keyword the replacement text is longer, so
  138. * we leave some space at the end of the tline buffer to accommodate this.
  139. */
  140. #define EDITSLOP 10
  141. /*
  142. * For temporary filenames
  143. */
  144. #define TEMPLATE "unifdef.XXXXXX"
  145. /*
  146. * Globals.
  147. */
  148. static bool compblank; /* -B: compress blank lines */
  149. static bool lnblank; /* -b: blank deleted lines */
  150. static bool complement; /* -c: do the complement */
  151. static bool debugging; /* -d: debugging reports */
  152. static bool iocccok; /* -e: fewer IOCCC errors */
  153. static bool strictlogic; /* -K: keep ambiguous #ifs */
  154. static bool killconsts; /* -k: eval constant #ifs */
  155. static bool lnnum; /* -n: add #line directives */
  156. static bool symlist; /* -s: output symbol list */
  157. static bool symdepth; /* -S: output symbol depth */
  158. static bool text; /* -t: this is a text file */
  159. static const char *symname[MAXSYMS]; /* symbol name */
  160. static const char *value[MAXSYMS]; /* -Dsym=value */
  161. static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */
  162. static int nsyms; /* number of symbols */
  163. static FILE *input; /* input file pointer */
  164. static const char *filename; /* input file name */
  165. static int linenum; /* current line number */
  166. static FILE *output; /* output file pointer */
  167. static const char *ofilename; /* output file name */
  168. static bool overwriting; /* output overwrites input */
  169. static char tempname[FILENAME_MAX]; /* used when overwriting */
  170. static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
  171. static char *keyword; /* used for editing #elif's */
  172. static const char *newline; /* input file format */
  173. static const char newline_unix[] = "\n";
  174. static const char newline_crlf[] = "\r\n";
  175. static Comment_state incomment; /* comment parser state */
  176. static Line_state linestate; /* #if line parser state */
  177. static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
  178. static bool ignoring[MAXDEPTH]; /* ignore comments state */
  179. static int stifline[MAXDEPTH]; /* start of current #if */
  180. static int depth; /* current #if nesting */
  181. static int delcount; /* count of deleted lines */
  182. static unsigned blankcount; /* count of blank lines */
  183. static unsigned blankmax; /* maximum recent blankcount */
  184. static bool constexpr; /* constant #if expression */
  185. static bool zerosyms = true; /* to format symdepth output */
  186. static bool firstsym; /* ditto */
  187. static int exitstat; /* program exit status */
  188. static void addsym(bool, bool, char *);
  189. static void closeout(void);
  190. static void debug(const char *, ...);
  191. static void done(void);
  192. static void error(const char *);
  193. static int findsym(const char *);
  194. static void flushline(bool);
  195. static Linetype parseline(void);
  196. static Linetype ifeval(const char **);
  197. static void ignoreoff(void);
  198. static void ignoreon(void);
  199. static void keywordedit(const char *);
  200. static void nest(void);
  201. static void process(void);
  202. static const char *skipargs(const char *);
  203. static const char *skipcomment(const char *);
  204. static const char *skipsym(const char *);
  205. static void state(Ifstate);
  206. static int strlcmp(const char *, const char *, size_t);
  207. static void unnest(void);
  208. static void usage(void);
  209. static void version(void);
  210. #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
  211. /*
  212. * The main program.
  213. */
  214. int
  215. main(int argc, char *argv[])
  216. {
  217. int opt;
  218. while ((opt = getopt(argc, argv, "i:D:U:I:o:bBcdeKklnsStV")) != -1)
  219. switch (opt) {
  220. case 'i': /* treat stuff controlled by these symbols as text */
  221. /*
  222. * For strict backwards-compatibility the U or D
  223. * should be immediately after the -i but it doesn't
  224. * matter much if we relax that requirement.
  225. */
  226. opt = *optarg++;
  227. if (opt == 'D')
  228. addsym(true, true, optarg);
  229. else if (opt == 'U')
  230. addsym(true, false, optarg);
  231. else
  232. usage();
  233. break;
  234. case 'D': /* define a symbol */
  235. addsym(false, true, optarg);
  236. break;
  237. case 'U': /* undef a symbol */
  238. addsym(false, false, optarg);
  239. break;
  240. case 'I': /* no-op for compatibility with cpp */
  241. break;
  242. case 'b': /* blank deleted lines instead of omitting them */
  243. case 'l': /* backwards compatibility */
  244. lnblank = true;
  245. break;
  246. case 'B': /* compress blank lines around removed section */
  247. compblank = true;
  248. break;
  249. case 'c': /* treat -D as -U and vice versa */
  250. complement = true;
  251. break;
  252. case 'd':
  253. debugging = true;
  254. break;
  255. case 'e': /* fewer errors from dodgy lines */
  256. iocccok = true;
  257. break;
  258. case 'K': /* keep ambiguous #ifs */
  259. strictlogic = true;
  260. break;
  261. case 'k': /* process constant #ifs */
  262. killconsts = true;
  263. break;
  264. case 'n': /* add #line directive after deleted lines */
  265. lnnum = true;
  266. break;
  267. case 'o': /* output to a file */
  268. ofilename = optarg;
  269. break;
  270. case 's': /* only output list of symbols that control #ifs */
  271. symlist = true;
  272. break;
  273. case 'S': /* list symbols with their nesting depth */
  274. symlist = symdepth = true;
  275. break;
  276. case 't': /* don't parse C comments */
  277. text = true;
  278. break;
  279. case 'V': /* print version */
  280. version();
  281. default:
  282. usage();
  283. }
  284. argc -= optind;
  285. argv += optind;
  286. if (compblank && lnblank)
  287. errx(2, "-B and -b are mutually exclusive");
  288. if (argc > 1) {
  289. errx(2, "can only do one file");
  290. } else if (argc == 1 && strcmp(*argv, "-") != 0) {
  291. filename = *argv;
  292. input = fopen(filename, "rb");
  293. if (input == NULL)
  294. err(2, "can't open %s", filename);
  295. } else {
  296. filename = "[stdin]";
  297. input = stdin;
  298. }
  299. if (ofilename == NULL) {
  300. ofilename = "[stdout]";
  301. output = stdout;
  302. } else {
  303. struct stat ist, ost;
  304. if (stat(ofilename, &ost) == 0 &&
  305. fstat(fileno(input), &ist) == 0)
  306. overwriting = (ist.st_dev == ost.st_dev
  307. && ist.st_ino == ost.st_ino);
  308. if (overwriting) {
  309. const char *dirsep;
  310. int ofd;
  311. dirsep = strrchr(ofilename, '/');
  312. if (dirsep != NULL)
  313. snprintf(tempname, sizeof(tempname),
  314. "%.*s/" TEMPLATE,
  315. (int)(dirsep - ofilename), ofilename);
  316. else
  317. snprintf(tempname, sizeof(tempname),
  318. TEMPLATE);
  319. ofd = mkstemp(tempname);
  320. if (ofd != -1)
  321. output = fdopen(ofd, "wb+");
  322. if (output == NULL)
  323. err(2, "can't create temporary file");
  324. fchmod(ofd, ist.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO));
  325. } else {
  326. output = fopen(ofilename, "wb");
  327. if (output == NULL)
  328. err(2, "can't open %s", ofilename);
  329. }
  330. }
  331. process();
  332. abort(); /* bug */
  333. }
  334. static void
  335. version(void)
  336. {
  337. const char *c = copyright;
  338. for (;;) {
  339. while (*++c != '$')
  340. if (*c == '\0')
  341. exit(0);
  342. while (*++c != '$')
  343. putc(*c, stderr);
  344. putc('\n', stderr);
  345. }
  346. }
  347. static void
  348. usage(void)
  349. {
  350. fprintf(stderr, "usage: unifdef [-bBcdeKknsStV] [-Ipath]"
  351. " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
  352. exit(2);
  353. }
  354. /*
  355. * A state transition function alters the global #if processing state
  356. * in a particular way. The table below is indexed by the current
  357. * processing state and the type of the current line.
  358. *
  359. * Nesting is handled by keeping a stack of states; some transition
  360. * functions increase or decrease the depth. They also maintain the
  361. * ignore state on a stack. In some complicated cases they have to
  362. * alter the preprocessor directive, as follows.
  363. *
  364. * When we have processed a group that starts off with a known-false
  365. * #if/#elif sequence (which has therefore been deleted) followed by a
  366. * #elif that we don't understand and therefore must keep, we edit the
  367. * latter into a #if to keep the nesting correct. We use strncpy() to
  368. * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
  369. *
  370. * When we find a true #elif in a group, the following block will
  371. * always be kept and the rest of the sequence after the next #elif or
  372. * #else will be discarded. We edit the #elif into a #else and the
  373. * following directive to #endif since this has the desired behaviour.
  374. *
  375. * "Dodgy" directives are split across multiple lines, the most common
  376. * example being a multi-line comment hanging off the right of the
  377. * directive. We can handle them correctly only if there is no change
  378. * from printing to dropping (or vice versa) caused by that directive.
  379. * If the directive is the first of a group we have a choice between
  380. * failing with an error, or passing it through unchanged instead of
  381. * evaluating it. The latter is not the default to avoid questions from
  382. * users about unifdef unexpectedly leaving behind preprocessor directives.
  383. */
  384. typedef void state_fn(void);
  385. /* report an error */
  386. static void Eelif (void) { error("Inappropriate #elif"); }
  387. static void Eelse (void) { error("Inappropriate #else"); }
  388. static void Eendif(void) { error("Inappropriate #endif"); }
  389. static void Eeof (void) { error("Premature EOF"); }
  390. static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
  391. /* plain line handling */
  392. static void print (void) { flushline(true); }
  393. static void drop (void) { flushline(false); }
  394. /* output lacks group's start line */
  395. static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); }
  396. static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); }
  397. static void Selse (void) { drop(); state(IS_TRUE_ELSE); }
  398. /* print/pass this block */
  399. static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
  400. static void Pelse (void) { print(); state(IS_PASS_ELSE); }
  401. static void Pendif(void) { print(); unnest(); }
  402. /* discard this block */
  403. static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); }
  404. static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); }
  405. static void Delse (void) { drop(); state(IS_FALSE_ELSE); }
  406. static void Dendif(void) { drop(); unnest(); }
  407. /* first line of group */
  408. static void Fdrop (void) { nest(); Dfalse(); }
  409. static void Fpass (void) { nest(); Pelif(); }
  410. static void Ftrue (void) { nest(); Strue(); }
  411. static void Ffalse(void) { nest(); Sfalse(); }
  412. /* variable pedantry for obfuscated lines */
  413. static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
  414. static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); }
  415. static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
  416. /* ignore comments in this block */
  417. static void Idrop (void) { Fdrop(); ignoreon(); }
  418. static void Itrue (void) { Ftrue(); ignoreon(); }
  419. static void Ifalse(void) { Ffalse(); ignoreon(); }
  420. /* modify this line */
  421. static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
  422. static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
  423. static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
  424. static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
  425. static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
  426. /* IS_OUTSIDE */
  427. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
  428. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif,
  429. print, done, abort },
  430. /* IS_FALSE_PREFIX */
  431. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
  432. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
  433. drop, Eeof, abort },
  434. /* IS_TRUE_PREFIX */
  435. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
  436. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  437. print, Eeof, abort },
  438. /* IS_PASS_MIDDLE */
  439. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
  440. Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif,
  441. print, Eeof, abort },
  442. /* IS_FALSE_MIDDLE */
  443. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
  444. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
  445. drop, Eeof, abort },
  446. /* IS_TRUE_MIDDLE */
  447. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
  448. Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
  449. print, Eeof, abort },
  450. /* IS_PASS_ELSE */
  451. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
  452. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif,
  453. print, Eeof, abort },
  454. /* IS_FALSE_ELSE */
  455. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
  456. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
  457. drop, Eeof, abort },
  458. /* IS_TRUE_ELSE */
  459. { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
  460. Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc,
  461. print, Eeof, abort },
  462. /* IS_FALSE_TRAILER */
  463. { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
  464. Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
  465. drop, Eeof, abort }
  466. /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF
  467. TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY)
  468. PLAIN EOF ERROR */
  469. };
  470. /*
  471. * State machine utility functions
  472. */
  473. static void
  474. ignoreoff(void)
  475. {
  476. if (depth == 0)
  477. abort(); /* bug */
  478. ignoring[depth] = ignoring[depth-1];
  479. }
  480. static void
  481. ignoreon(void)
  482. {
  483. ignoring[depth] = true;
  484. }
  485. static void
  486. keywordedit(const char *replacement)
  487. {
  488. snprintf(keyword, tline + sizeof(tline) - keyword,
  489. "%s%s", replacement, newline);
  490. print();
  491. }
  492. static void
  493. nest(void)
  494. {
  495. if (depth > MAXDEPTH-1)
  496. abort(); /* bug */
  497. if (depth == MAXDEPTH-1)
  498. error("Too many levels of nesting");
  499. depth += 1;
  500. stifline[depth] = linenum;
  501. }
  502. static void
  503. unnest(void)
  504. {
  505. if (depth == 0)
  506. abort(); /* bug */
  507. depth -= 1;
  508. }
  509. static void
  510. state(Ifstate is)
  511. {
  512. ifstate[depth] = is;
  513. }
  514. /*
  515. * Write a line to the output or not, according to command line options.
  516. */
  517. static void
  518. flushline(bool keep)
  519. {
  520. if (symlist)
  521. return;
  522. if (keep ^ complement) {
  523. bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
  524. if (blankline && compblank && blankcount != blankmax) {
  525. delcount += 1;
  526. blankcount += 1;
  527. } else {
  528. if (lnnum && delcount > 0)
  529. printf("#line %d%s", linenum, newline);
  530. fputs(tline, output);
  531. delcount = 0;
  532. blankmax = blankcount = blankline ? blankcount + 1 : 0;
  533. }
  534. } else {
  535. if (lnblank)
  536. fputs(newline, output);
  537. exitstat = 1;
  538. delcount += 1;
  539. blankcount = 0;
  540. }
  541. if (debugging)
  542. fflush(output);
  543. }
  544. /*
  545. * The driver for the state machine.
  546. */
  547. static void
  548. process(void)
  549. {
  550. /* When compressing blank lines, act as if the file
  551. is preceded by a large number of blank lines. */
  552. blankmax = blankcount = 1000;
  553. for (;;) {
  554. Linetype lineval = parseline();
  555. trans_table[ifstate[depth]][lineval]();
  556. debug("process line %d %s -> %s depth %d",
  557. linenum, linetype_name[lineval],
  558. ifstate_name[ifstate[depth]], depth);
  559. }
  560. }
  561. /*
  562. * Flush the output and handle errors.
  563. */
  564. static void
  565. closeout(void)
  566. {
  567. if (symdepth && !zerosyms)
  568. printf("\n");
  569. if (fclose(output) == EOF) {
  570. warn("couldn't write to %s", ofilename);
  571. if (overwriting) {
  572. unlink(tempname);
  573. errx(2, "%s unchanged", filename);
  574. } else {
  575. exit(2);
  576. }
  577. }
  578. }
  579. /*
  580. * Clean up and exit.
  581. */
  582. static void
  583. done(void)
  584. {
  585. if (incomment)
  586. error("EOF in comment");
  587. closeout();
  588. if (overwriting && rename(tempname, ofilename) == -1) {
  589. warn("couldn't rename temporary file");
  590. unlink(tempname);
  591. errx(2, "%s unchanged", ofilename);
  592. }
  593. exit(exitstat);
  594. }
  595. /*
  596. * Parse a line and determine its type. We keep the preprocessor line
  597. * parser state between calls in the global variable linestate, with
  598. * help from skipcomment().
  599. */
  600. static Linetype
  601. parseline(void)
  602. {
  603. const char *cp;
  604. int cursym;
  605. int kwlen;
  606. Linetype retval;
  607. Comment_state wascomment;
  608. linenum++;
  609. if (fgets(tline, MAXLINE, input) == NULL)
  610. return (LT_EOF);
  611. if (newline == NULL) {
  612. if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
  613. newline = newline_crlf;
  614. else
  615. newline = newline_unix;
  616. }
  617. retval = LT_PLAIN;
  618. wascomment = incomment;
  619. cp = skipcomment(tline);
  620. if (linestate == LS_START) {
  621. if (*cp == '#') {
  622. linestate = LS_HASH;
  623. firstsym = true;
  624. cp = skipcomment(cp + 1);
  625. } else if (*cp != '\0')
  626. linestate = LS_DIRTY;
  627. }
  628. if (!incomment && linestate == LS_HASH) {
  629. keyword = tline + (cp - tline);
  630. cp = skipsym(cp);
  631. kwlen = cp - keyword;
  632. /* no way can we deal with a continuation inside a keyword */
  633. if (strncmp(cp, "\\\r\n", 3) == 0 ||
  634. strncmp(cp, "\\\n", 2) == 0)
  635. Eioccc();
  636. if (strlcmp("ifdef", keyword, kwlen) == 0 ||
  637. strlcmp("ifndef", keyword, kwlen) == 0) {
  638. cp = skipcomment(cp);
  639. if ((cursym = findsym(cp)) < 0)
  640. retval = LT_IF;
  641. else {
  642. retval = (keyword[2] == 'n')
  643. ? LT_FALSE : LT_TRUE;
  644. if (value[cursym] == NULL)
  645. retval = (retval == LT_TRUE)
  646. ? LT_FALSE : LT_TRUE;
  647. if (ignore[cursym])
  648. retval = (retval == LT_TRUE)
  649. ? LT_TRUEI : LT_FALSEI;
  650. }
  651. cp = skipsym(cp);
  652. } else if (strlcmp("if", keyword, kwlen) == 0)
  653. retval = ifeval(&cp);
  654. else if (strlcmp("elif", keyword, kwlen) == 0)
  655. retval = ifeval(&cp) - LT_IF + LT_ELIF;
  656. else if (strlcmp("else", keyword, kwlen) == 0)
  657. retval = LT_ELSE;
  658. else if (strlcmp("endif", keyword, kwlen) == 0)
  659. retval = LT_ENDIF;
  660. else {
  661. linestate = LS_DIRTY;
  662. retval = LT_PLAIN;
  663. }
  664. cp = skipcomment(cp);
  665. if (*cp != '\0') {
  666. linestate = LS_DIRTY;
  667. if (retval == LT_TRUE || retval == LT_FALSE ||
  668. retval == LT_TRUEI || retval == LT_FALSEI)
  669. retval = LT_IF;
  670. if (retval == LT_ELTRUE || retval == LT_ELFALSE)
  671. retval = LT_ELIF;
  672. }
  673. if (retval != LT_PLAIN && (wascomment || incomment)) {
  674. retval += LT_DODGY;
  675. if (incomment)
  676. linestate = LS_DIRTY;
  677. }
  678. /* skipcomment normally changes the state, except
  679. if the last line of the file lacks a newline, or
  680. if there is too much whitespace in a directive */
  681. if (linestate == LS_HASH) {
  682. size_t len = cp - tline;
  683. if (fgets(tline + len, MAXLINE - len, input) == NULL) {
  684. /* append the missing newline */
  685. strcpy(tline + len, newline);
  686. cp += strlen(newline);
  687. linestate = LS_START;
  688. } else {
  689. linestate = LS_DIRTY;
  690. }
  691. }
  692. }
  693. if (linestate == LS_DIRTY) {
  694. while (*cp != '\0')
  695. cp = skipcomment(cp + 1);
  696. }
  697. debug("parser line %d state %s comment %s line", linenum,
  698. comment_name[incomment], linestate_name[linestate]);
  699. return (retval);
  700. }
  701. /*
  702. * These are the binary operators that are supported by the expression
  703. * evaluator.
  704. */
  705. static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) {
  706. if(at == LT_IF || bt == LT_IF) return (LT_IF);
  707. return (*p = v, v ? LT_TRUE : LT_FALSE);
  708. }
  709. static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) {
  710. return op_strict(p, a < b, at, bt);
  711. }
  712. static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) {
  713. return op_strict(p, a > b, at, bt);
  714. }
  715. static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) {
  716. return op_strict(p, a <= b, at, bt);
  717. }
  718. static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) {
  719. return op_strict(p, a >= b, at, bt);
  720. }
  721. static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) {
  722. return op_strict(p, a == b, at, bt);
  723. }
  724. static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) {
  725. return op_strict(p, a != b, at, bt);
  726. }
  727. static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) {
  728. if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
  729. return (*p = 1, LT_TRUE);
  730. return op_strict(p, a || b, at, bt);
  731. }
  732. static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) {
  733. if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
  734. return (*p = 0, LT_FALSE);
  735. return op_strict(p, a && b, at, bt);
  736. }
  737. /*
  738. * An evaluation function takes three arguments, as follows: (1) a pointer to
  739. * an element of the precedence table which lists the operators at the current
  740. * level of precedence; (2) a pointer to an integer which will receive the
  741. * value of the expression; and (3) a pointer to a char* that points to the
  742. * expression to be evaluated and that is updated to the end of the expression
  743. * when evaluation is complete. The function returns LT_FALSE if the value of
  744. * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
  745. * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
  746. */
  747. struct ops;
  748. typedef Linetype eval_fn(const struct ops *, int *, const char **);
  749. static eval_fn eval_table, eval_unary;
  750. /*
  751. * The precedence table. Expressions involving binary operators are evaluated
  752. * in a table-driven way by eval_table. When it evaluates a subexpression it
  753. * calls the inner function with its first argument pointing to the next
  754. * element of the table. Innermost expressions have special non-table-driven
  755. * handling.
  756. */
  757. static const struct ops {
  758. eval_fn *inner;
  759. struct op {
  760. const char *str;
  761. Linetype (*fn)(int *, Linetype, int, Linetype, int);
  762. } op[5];
  763. } eval_ops[] = {
  764. { eval_table, { { "||", op_or } } },
  765. { eval_table, { { "&&", op_and } } },
  766. { eval_table, { { "==", op_eq },
  767. { "!=", op_ne } } },
  768. { eval_unary, { { "<=", op_le },
  769. { ">=", op_ge },
  770. { "<", op_lt },
  771. { ">", op_gt } } }
  772. };
  773. /*
  774. * Function for evaluating the innermost parts of expressions,
  775. * viz. !expr (expr) number defined(symbol) symbol
  776. * We reset the constexpr flag in the last two cases.
  777. */
  778. static Linetype
  779. eval_unary(const struct ops *ops, int *valp, const char **cpp)
  780. {
  781. const char *cp;
  782. char *ep;
  783. int sym;
  784. bool defparen;
  785. Linetype lt;
  786. cp = skipcomment(*cpp);
  787. if (*cp == '!') {
  788. debug("eval%d !", ops - eval_ops);
  789. cp++;
  790. lt = eval_unary(ops, valp, &cp);
  791. if (lt == LT_ERROR)
  792. return (LT_ERROR);
  793. if (lt != LT_IF) {
  794. *valp = !*valp;
  795. lt = *valp ? LT_TRUE : LT_FALSE;
  796. }
  797. } else if (*cp == '(') {
  798. cp++;
  799. debug("eval%d (", ops - eval_ops);
  800. lt = eval_table(eval_ops, valp, &cp);
  801. if (lt == LT_ERROR)
  802. return (LT_ERROR);
  803. cp = skipcomment(cp);
  804. if (*cp++ != ')')
  805. return (LT_ERROR);
  806. } else if (isdigit((unsigned char)*cp)) {
  807. debug("eval%d number", ops - eval_ops);
  808. *valp = strtol(cp, &ep, 0);
  809. if (ep == cp)
  810. return (LT_ERROR);
  811. lt = *valp ? LT_TRUE : LT_FALSE;
  812. cp = skipsym(cp);
  813. } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {
  814. cp = skipcomment(cp+7);
  815. debug("eval%d defined", ops - eval_ops);
  816. if (*cp == '(') {
  817. cp = skipcomment(cp+1);
  818. defparen = true;
  819. } else {
  820. defparen = false;
  821. }
  822. sym = findsym(cp);
  823. if (sym < 0) {
  824. lt = LT_IF;
  825. } else {
  826. *valp = (value[sym] != NULL);
  827. lt = *valp ? LT_TRUE : LT_FALSE;
  828. }
  829. cp = skipsym(cp);
  830. cp = skipcomment(cp);
  831. if (defparen && *cp++ != ')')
  832. return (LT_ERROR);
  833. constexpr = false;
  834. } else if (!endsym(*cp)) {
  835. debug("eval%d symbol", ops - eval_ops);
  836. sym = findsym(cp);
  837. cp = skipsym(cp);
  838. if (sym < 0) {
  839. lt = LT_IF;
  840. cp = skipargs(cp);
  841. } else if (value[sym] == NULL) {
  842. *valp = 0;
  843. lt = LT_FALSE;
  844. } else {
  845. *valp = strtol(value[sym], &ep, 0);
  846. if (*ep != '\0' || ep == value[sym])
  847. return (LT_ERROR);
  848. lt = *valp ? LT_TRUE : LT_FALSE;
  849. cp = skipargs(cp);
  850. }
  851. constexpr = false;
  852. } else {
  853. debug("eval%d bad expr", ops - eval_ops);
  854. return (LT_ERROR);
  855. }
  856. *cpp = cp;
  857. debug("eval%d = %d", ops - eval_ops, *valp);
  858. return (lt);
  859. }
  860. /*
  861. * Table-driven evaluation of binary operators.
  862. */
  863. static Linetype
  864. eval_table(const struct ops *ops, int *valp, const char **cpp)
  865. {
  866. const struct op *op;
  867. const char *cp;
  868. int val;
  869. Linetype lt, rt;
  870. debug("eval%d", ops - eval_ops);
  871. cp = *cpp;
  872. lt = ops->inner(ops+1, valp, &cp);
  873. if (lt == LT_ERROR)
  874. return (LT_ERROR);
  875. for (;;) {
  876. cp = skipcomment(cp);
  877. for (op = ops->op; op->str != NULL; op++)
  878. if (strncmp(cp, op->str, strlen(op->str)) == 0)
  879. break;
  880. if (op->str == NULL)
  881. break;
  882. cp += strlen(op->str);
  883. debug("eval%d %s", ops - eval_ops, op->str);
  884. rt = ops->inner(ops+1, &val, &cp);
  885. if (rt == LT_ERROR)
  886. return (LT_ERROR);
  887. lt = op->fn(valp, lt, *valp, rt, val);
  888. }
  889. *cpp = cp;
  890. debug("eval%d = %d", ops - eval_ops, *valp);
  891. debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]);
  892. return (lt);
  893. }
  894. /*
  895. * Evaluate the expression on a #if or #elif line. If we can work out
  896. * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we
  897. * return just a generic LT_IF.
  898. */
  899. static Linetype
  900. ifeval(const char **cpp)
  901. {
  902. int ret;
  903. int val = 0;
  904. debug("eval %s", *cpp);
  905. constexpr = killconsts ? false : true;
  906. ret = eval_table(eval_ops, &val, cpp);
  907. debug("eval = %d", val);
  908. return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
  909. }
  910. /*
  911. * Skip over comments, strings, and character literals and stop at the
  912. * next character position that is not whitespace. Between calls we keep
  913. * the comment state in the global variable incomment, and we also adjust
  914. * the global variable linestate when we see a newline.
  915. * XXX: doesn't cope with the buffer splitting inside a state transition.
  916. */
  917. static const char *
  918. skipcomment(const char *cp)
  919. {
  920. if (text || ignoring[depth]) {
  921. for (; isspace((unsigned char)*cp); cp++)
  922. if (*cp == '\n')
  923. linestate = LS_START;
  924. return (cp);
  925. }
  926. while (*cp != '\0')
  927. /* don't reset to LS_START after a line continuation */
  928. if (strncmp(cp, "\\\r\n", 3) == 0)
  929. cp += 3;
  930. else if (strncmp(cp, "\\\n", 2) == 0)
  931. cp += 2;
  932. else switch (incomment) {
  933. case NO_COMMENT:
  934. if (strncmp(cp, "/\\\r\n", 4) == 0) {
  935. incomment = STARTING_COMMENT;
  936. cp += 4;
  937. } else if (strncmp(cp, "/\\\n", 3) == 0) {
  938. incomment = STARTING_COMMENT;
  939. cp += 3;
  940. } else if (strncmp(cp, "/*", 2) == 0) {
  941. incomment = C_COMMENT;
  942. cp += 2;
  943. } else if (strncmp(cp, "//", 2) == 0) {
  944. incomment = CXX_COMMENT;
  945. cp += 2;
  946. } else if (strncmp(cp, "\'", 1) == 0) {
  947. incomment = CHAR_LITERAL;
  948. linestate = LS_DIRTY;
  949. cp += 1;
  950. } else if (strncmp(cp, "\"", 1) == 0) {
  951. incomment = STRING_LITERAL;
  952. linestate = LS_DIRTY;
  953. cp += 1;
  954. } else if (strncmp(cp, "\n", 1) == 0) {
  955. linestate = LS_START;
  956. cp += 1;
  957. } else if (strchr(" \r\t", *cp) != NULL) {
  958. cp += 1;
  959. } else
  960. return (cp);
  961. continue;
  962. case CXX_COMMENT:
  963. if (strncmp(cp, "\n", 1) == 0) {
  964. incomment = NO_COMMENT;
  965. linestate = LS_START;
  966. }
  967. cp += 1;
  968. continue;
  969. case CHAR_LITERAL:
  970. case STRING_LITERAL:
  971. if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
  972. (incomment == STRING_LITERAL && cp[0] == '\"')) {
  973. incomment = NO_COMMENT;
  974. cp += 1;
  975. } else if (cp[0] == '\\') {
  976. if (cp[1] == '\0')
  977. cp += 1;
  978. else
  979. cp += 2;
  980. } else if (strncmp(cp, "\n", 1) == 0) {
  981. if (incomment == CHAR_LITERAL)
  982. error("unterminated char literal");
  983. else
  984. error("unterminated string literal");
  985. } else
  986. cp += 1;
  987. continue;
  988. case C_COMMENT:
  989. if (strncmp(cp, "*\\\r\n", 4) == 0) {
  990. incomment = FINISHING_COMMENT;
  991. cp += 4;
  992. } else if (strncmp(cp, "*\\\n", 3) == 0) {
  993. incomment = FINISHING_COMMENT;
  994. cp += 3;
  995. } else if (strncmp(cp, "*/", 2) == 0) {
  996. incomment = NO_COMMENT;
  997. cp += 2;
  998. } else
  999. cp += 1;
  1000. continue;
  1001. case STARTING_COMMENT:
  1002. if (*cp == '*') {
  1003. incomment = C_COMMENT;
  1004. cp += 1;
  1005. } else if (*cp == '/') {
  1006. incomment = CXX_COMMENT;
  1007. cp += 1;
  1008. } else {
  1009. incomment = NO_COMMENT;
  1010. linestate = LS_DIRTY;
  1011. }
  1012. continue;
  1013. case FINISHING_COMMENT:
  1014. if (*cp == '/') {
  1015. incomment = NO_COMMENT;
  1016. cp += 1;
  1017. } else
  1018. incomment = C_COMMENT;
  1019. continue;
  1020. default:
  1021. abort(); /* bug */
  1022. }
  1023. return (cp);
  1024. }
  1025. /*
  1026. * Skip macro arguments.
  1027. */
  1028. static const char *
  1029. skipargs(const char *cp)
  1030. {
  1031. const char *ocp = cp;
  1032. int level = 0;
  1033. cp = skipcomment(cp);
  1034. if (*cp != '(')
  1035. return (cp);
  1036. do {
  1037. if (*cp == '(')
  1038. level++;
  1039. if (*cp == ')')
  1040. level--;
  1041. cp = skipcomment(cp+1);
  1042. } while (level != 0 && *cp != '\0');
  1043. if (level == 0)
  1044. return (cp);
  1045. else
  1046. /* Rewind and re-detect the syntax error later. */
  1047. return (ocp);
  1048. }
  1049. /*
  1050. * Skip over an identifier.
  1051. */
  1052. static const char *
  1053. skipsym(const char *cp)
  1054. {
  1055. while (!endsym(*cp))
  1056. ++cp;
  1057. return (cp);
  1058. }
  1059. /*
  1060. * Look for the symbol in the symbol table. If it is found, we return
  1061. * the symbol table index, else we return -1.
  1062. */
  1063. static int
  1064. findsym(const char *str)
  1065. {
  1066. const char *cp;
  1067. int symind;
  1068. cp = skipsym(str);
  1069. if (cp == str)
  1070. return (-1);
  1071. if (symlist) {
  1072. if (symdepth && firstsym)
  1073. printf("%s%3d", zerosyms ? "" : "\n", depth);
  1074. firstsym = zerosyms = false;
  1075. printf("%s%.*s%s",
  1076. symdepth ? " " : "",
  1077. (int)(cp-str), str,
  1078. symdepth ? "" : "\n");
  1079. /* we don't care about the value of the symbol */
  1080. return (0);
  1081. }
  1082. for (symind = 0; symind < nsyms; ++symind) {
  1083. if (strlcmp(symname[symind], str, cp-str) == 0) {
  1084. debug("findsym %s %s", symname[symind],
  1085. value[symind] ? value[symind] : "");
  1086. return (symind);
  1087. }
  1088. }
  1089. return (-1);
  1090. }
  1091. /*
  1092. * Add a symbol to the symbol table.
  1093. */
  1094. static void
  1095. addsym(bool ignorethis, bool definethis, char *sym)
  1096. {
  1097. int symind;
  1098. char *val;
  1099. symind = findsym(sym);
  1100. if (symind < 0) {
  1101. if (nsyms >= MAXSYMS)
  1102. errx(2, "too many symbols");
  1103. symind = nsyms++;
  1104. }
  1105. symname[symind] = sym;
  1106. ignore[symind] = ignorethis;
  1107. val = sym + (skipsym(sym) - sym);
  1108. if (definethis) {
  1109. if (*val == '=') {
  1110. value[symind] = val+1;
  1111. *val = '\0';
  1112. } else if (*val == '\0')
  1113. value[symind] = "1";
  1114. else
  1115. usage();
  1116. } else {
  1117. if (*val != '\0')
  1118. usage();
  1119. value[symind] = NULL;
  1120. }
  1121. debug("addsym %s=%s", symname[symind],
  1122. value[symind] ? value[symind] : "undef");
  1123. }
  1124. /*
  1125. * Compare s with n characters of t.
  1126. * The same as strncmp() except that it checks that s[n] == '\0'.
  1127. */
  1128. static int
  1129. strlcmp(const char *s, const char *t, size_t n)
  1130. {
  1131. while (n-- && *t != '\0')
  1132. if (*s != *t)
  1133. return ((unsigned char)*s - (unsigned char)*t);
  1134. else
  1135. ++s, ++t;
  1136. return ((unsigned char)*s);
  1137. }
  1138. /*
  1139. * Diagnostics.
  1140. */
  1141. static void
  1142. debug(const char *msg, ...)
  1143. {
  1144. va_list ap;
  1145. if (debugging) {
  1146. va_start(ap, msg);
  1147. vwarnx(msg, ap);
  1148. va_end(ap);
  1149. }
  1150. }
  1151. static void
  1152. error(const char *msg)
  1153. {
  1154. if (depth == 0)
  1155. warnx("%s: %d: %s", filename, linenum, msg);
  1156. else
  1157. warnx("%s: %d: %s (#if line %d depth %d)",
  1158. filename, linenum, msg, stifline[depth], depth);
  1159. closeout();
  1160. errx(2, "output may be truncated");
  1161. }