History

unifdef: update to upstream version 2.5

Fix a long-standing cpp compatibility bug. The -DFOO argument (without an explicit value) should define FOO to 1 not to the empty string. Add a -o option to support overwriting a file in place, and a -S option to list the nesting depth of symbols. Include line numbers in debugging output. Support CRLF newlines.

Tony Finch committed 15 years ago

Commit 3cbea431 parent c56eb8f1 file · +184 −63Browse files

Showing the changes to scripts (1 of 1 file). Show all

Unified · Split

scripts/unifdef.c+184−63
@@ -1,5 +1,5 @@
11 /*
2− * Copyright (c) 2002 - 2009 Tony Finch <dot@dotat.at>
2+ * Copyright (c) 2002 - 2011 Tony Finch <dot@dotat.at>
33 *
44 * Redistribution and use in source and binary forms, with or without
55 * modification, are permitted provided that the following conditions
@@ -24,23 +24,14 @@ · 18 unmodified lines
2424 */
2525
2626 /*
27+ * unifdef - remove ifdef'ed lines
28+ *
2729 * This code was derived from software contributed to Berkeley by Dave Yost.
2830 * It was rewritten to support ANSI C by Tony Finch. The original version
2931 * of unifdef carried the 4-clause BSD copyright licence. None of its code
3032 * remains in this version (though some of the names remain) so it now
3133 * carries a more liberal licence.
3234 *
33− * The latest version is available from http://dotat.at/prog/unifdef
34− */
35−
36−static const char * const copyright[] = {
37− "@(#) Copyright (c) 2002 - 2009 Tony Finch <dot@dotat.at>\n",
38− "$dotat: unifdef/unifdef.c,v 1.190 2009/11/27 17:21:26 fanf2 Exp $",
39−};
40−
41−/*
42− * unifdef - remove ifdef'ed lines
43− *
4435 * Wishlist:
4536 * provide an option which will append the name of the
4637 * appropriate symbol after #else's and #endif's
@@ -48,12 +39,16 @@ static const char * const copyright[] = { · 1 unmodified line
4839 * #else's and #endif's to see that they match their
4940 * corresponding #ifdef or #ifndef
5041 *
51− * The first two items above require better buffer handling, which would
52− * also make it possible to handle all "dodgy" directives correctly.
42+ * These require better buffer handling, which would also make
43+ * it possible to handle all "dodgy" directives correctly.
5344 */
5445
46+#include <sys/types.h>
47+#include <sys/stat.h>
48+
5549 #include <ctype.h>
5650 #include <err.h>
51+#include <errno.h>
5752 #include <stdarg.h>
5853 #include <stdbool.h>
5954 #include <stdio.h>
@@ -61,6 +56,12 @@ static const char * const copyright[] = { · 1 unmodified line
6156 #include <string.h>
6257 #include <unistd.h>
6358
59+const char copyright[] =
60+ "@(#) $Version: unifdef-2.5 $\n"
61+ "@(#) $Author: Tony Finch (dot@dotat.at) $\n"
62+ "@(#) $URL: http://dotat.at/prog/unifdef $\n"
63+;
64+
6465 /* types of input lines: */
6566 typedef enum {
6667 LT_TRUEI, /* a true #if with ignore flag */
@@ -152,6 +153,11 @@ static char const * const linestate_name[] = { · 85 unmodified lines
152153 */
153154 #define EDITSLOP 10
154155
156+/*
157+ * For temporary filenames
158+ */
159+#define TEMPLATE "unifdef.XXXXXX"
160+
155161 /*
156162 * Globals.
157163 */
@@ -165,6 +171,7 @@ static bool strictlogic; /* -K: keep ambiguous #ifs */ · 7 unmodified lines
165171 static bool killconsts; /* -k: eval constant #ifs */
166172 static bool lnnum; /* -n: add #line directives */
167173 static bool symlist; /* -s: output symbol list */
174+static bool symdepth; /* -S: output symbol depth */
168175 static bool text; /* -t: this is a text file */
169176
170177 static const char *symname[MAXSYMS]; /* symbol name */
@@ -175,10 +182,18 @@ static int nsyms; /* number of symbols */ · 4 unmodified lines
175182 static FILE *input; /* input file pointer */
176183 static const char *filename; /* input file name */
177184 static int linenum; /* current line number */
185+static FILE *output; /* output file pointer */
186+static const char *ofilename; /* output file name */
187+static bool overwriting; /* output overwrites input */
188+static char tempname[FILENAME_MAX]; /* used when overwriting */
178189
179190 static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */
180191 static char *keyword; /* used for editing #elif's */
181192
193+static const char *newline; /* input file format */
194+static const char newline_unix[] = "\n";
195+static const char newline_crlf[] = "\r\n";
196+
182197 static Comment_state incomment; /* comment parser state */
183198 static Line_state linestate; /* #if line parser state */
184199 static Ifstate ifstate[MAXDEPTH]; /* #if processor state */
@@ -189,10 +204,13 @@ static int delcount; /* count of deleted lines */ · 4 unmodified lines
189204 static unsigned blankcount; /* count of blank lines */
190205 static unsigned blankmax; /* maximum recent blankcount */
191206 static bool constexpr; /* constant #if expression */
207+static bool zerosyms = true; /* to format symdepth output */
208+static bool firstsym; /* ditto */
192209
193210 static int exitstat; /* program exit status */
194211
195212 static void addsym(bool, bool, char *);
213+static void closeout(void);
196214 static void debug(const char *, ...);
197215 static void done(void);
198216 static void error(const char *);
@@ -212,6 +230,7 @@ static void state(Ifstate); · 13 unmodified lines
212230 static int strlcmp(const char *, const char *, size_t);
213231 static void unnest(void);
214232 static void usage(void);
233+static void version(void);
215234
216235 #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
217236
@@ -223,7 +242,7 @@ main(int argc, char *argv[]) · 5 unmodified lines
223242 {
224243 int opt;
225244
226− while ((opt = getopt(argc, argv, "i:D:U:I:BbcdeKklnst")) != -1)
245+ while ((opt = getopt(argc, argv, "i:D:U:I:o:bBcdeKklnsStV")) != -1)
227246 switch (opt) {
228247 case 'i': /* treat stuff controlled by these symbols as text */
229248 /*
@@ -245,16 +264,15 @@ main(int argc, char *argv[]) · 15 unmodified lines
245264 case 'U': /* undef a symbol */
246265 addsym(false, false, optarg);
247266 break;
248− case 'I':
249− /* no-op for compatibility with cpp */
250− break;
251− case 'B': /* compress blank lines around removed section */
252− compblank = true;
267+ case 'I': /* no-op for compatibility with cpp */
253268 break;
254269 case 'b': /* blank deleted lines instead of omitting them */
255270 case 'l': /* backwards compatibility */
256271 lnblank = true;
257272 break;
273+ case 'B': /* compress blank lines around removed section */
274+ compblank = true;
275+ break;
258276 case 'c': /* treat -D as -U and vice versa */
259277 complement = true;
260278 break;
@@ -273,12 +291,20 @@ main(int argc, char *argv[]) · 12 unmodified lines
273291 case 'n': /* add #line directive after deleted lines */
274292 lnnum = true;
275293 break;
294+ case 'o': /* output to a file */
295+ ofilename = optarg;
296+ break;
276297 case 's': /* only output list of symbols that control #ifs */
277298 symlist = true;
278299 break;
300+ case 'S': /* list symbols with their nesting depth */
301+ symlist = symdepth = true;
302+ break;
279303 case 't': /* don't parse C comments */
280304 text = true;
281305 break;
306+ case 'V': /* print version */
307+ version();
282308 default:
283309 usage();
284310 }
@@ -290,21 +316,68 @@ main(int argc, char *argv[]) · 5 unmodified lines
290316 errx(2, "can only do one file");
291317 } else if (argc == 1 && strcmp(*argv, "-") != 0) {
292318 filename = *argv;
293− input = fopen(filename, "r");
319+ input = fopen(filename, "rb");
294320 if (input == NULL)
295321 err(2, "can't open %s", filename);
296322 } else {
297323 filename = "[stdin]";
298324 input = stdin;
299325 }
326+ if (ofilename == NULL) {
327+ ofilename = "[stdout]";
328+ output = stdout;
329+ } else {
330+ struct stat ist, ost;
331+ if (stat(ofilename, &ost) == 0 &&
332+ fstat(fileno(input), &ist) == 0)
333+ overwriting = (ist.st_dev == ost.st_dev
334+ && ist.st_ino == ost.st_ino);
335+ if (overwriting) {
336+ const char *dirsep;
337+ int ofd;
338+
339+ dirsep = strrchr(ofilename, '/');
340+ if (dirsep != NULL)
341+ snprintf(tempname, sizeof(tempname),
342+ "%.*s/" TEMPLATE,
343+ (int)(dirsep - ofilename), ofilename);
344+ else
345+ snprintf(tempname, sizeof(tempname),
346+ TEMPLATE);
347+ ofd = mkstemp(tempname);
348+ if (ofd != -1)
349+ output = fdopen(ofd, "wb+");
350+ if (output == NULL)
351+ err(2, "can't create temporary file");
352+ fchmod(ofd, ist.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO));
353+ } else {
354+ output = fopen(ofilename, "wb");
355+ if (output == NULL)
356+ err(2, "can't open %s", ofilename);
357+ }
358+ }
300359 process();
301360 abort(); /* bug */
302361 }
303362
363+static void
364+version(void)
365+{
366+ const char *c = copyright;
367+ for (;;) {
368+ while (*++c != '$')
369+ if (*c == '\0')
370+ exit(0);
371+ while (*++c != '$')
372+ putc(*c, stderr);
373+ putc('\n', stderr);
374+ }
375+}
376+
304377 static void
305378 usage(void)
306379 {
307− fprintf(stderr, "usage: unifdef [-BbcdeKknst] [-Ipath]"
380+ fprintf(stderr, "usage: unifdef [-bBcdeKknsStV] [-Ipath]"
308381 " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n");
309382 exit(2);
310383 }
@@ -322,7 +395,8 @@ usage(void) · 11 unmodified lines
322395 * When we have processed a group that starts off with a known-false
323396 * #if/#elif sequence (which has therefore been deleted) followed by a
324397 * #elif that we don't understand and therefore must keep, we edit the
325− * latter into a #if to keep the nesting correct.
398+ * latter into a #if to keep the nesting correct. We use strncpy() to
399+ * overwrite the 4 byte token "elif" with "if " without a '\0' byte.
326400 *
327401 * When we find a true #elif in a group, the following block will
328402 * always be kept and the rest of the sequence after the next #elif or
@@ -375,11 +449,11 @@ static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); } · 46 unmodified lines
375449 static void Idrop (void) { Fdrop(); ignoreon(); }
376450 static void Itrue (void) { Ftrue(); ignoreon(); }
377451 static void Ifalse(void) { Ffalse(); ignoreon(); }
378−/* edit this line */
452+/* modify this line */
379453 static void Mpass (void) { strncpy(keyword, "if ", 4); Pelif(); }
380−static void Mtrue (void) { keywordedit("else\n"); state(IS_TRUE_MIDDLE); }
381−static void Melif (void) { keywordedit("endif\n"); state(IS_FALSE_TRAILER); }
382−static void Melse (void) { keywordedit("endif\n"); state(IS_FALSE_ELSE); }
454+static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); }
455+static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
456+static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
383457
384458 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
385459 /* IS_OUTSIDE */
@@ -431,13 +505,6 @@ static state_fn * const trans_table[IS_COUNT][LT_COUNT] = { · 45 unmodified lines
431505 * State machine utility functions
432506 */
433507 static void
434−done(void)
435−{
436− if (incomment)
437− error("EOF in comment");
438− exit(exitstat);
439−}
440−static void
441508 ignoreoff(void)
442509 {
443510 if (depth == 0)
@@ -452,14 +519,8 @@ ignoreon(void) · 8 unmodified lines
452519 static void
453520 keywordedit(const char *replacement)
454521 {
455− size_t size = tline + sizeof(tline) - keyword;
456− char *dst = keyword;
457− const char *src = replacement;
458− if (size != 0) {
459− while ((--size != 0) && (*src != '\0'))
460− *dst++ = *src++;
461− *dst = '\0';
462− }
522+ snprintf(keyword, tline + sizeof(tline) - keyword,
523+ "%s%s", replacement, newline);
463524 print();
464525 }
465526 static void
@@ -494,24 +555,26 @@ flushline(bool keep) · 28 unmodified lines
494555 if (symlist)
495556 return;
496557 if (keep ^ complement) {
497− bool blankline = tline[strspn(tline, " \t\n")] == '\0';
558+ bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
498559 if (blankline && compblank && blankcount != blankmax) {
499560 delcount += 1;
500561 blankcount += 1;
501562 } else {
502563 if (lnnum && delcount > 0)
503− printf("#line %d\n", linenum);
504− fputs(tline, stdout);
564+ printf("#line %d%s", linenum, newline);
565+ fputs(tline, output);
505566 delcount = 0;
506567 blankmax = blankcount = blankline ? blankcount + 1 : 0;
507568 }
508569 } else {
509570 if (lnblank)
510− putc('\n', stdout);
571+ fputs(newline, output);
511572 exitstat = 1;
512573 delcount += 1;
513574 blankcount = 0;
514575 }
576+ if (debugging)
577+ fflush(output);
515578 }
516579
517580 /*
@@ -520,21 +583,54 @@ flushline(bool keep) · 2 unmodified lines
520583 static void
521584 process(void)
522585 {
523− Linetype lineval;
524−
525586 /* When compressing blank lines, act as if the file
526587 is preceded by a large number of blank lines. */
527588 blankmax = blankcount = 1000;
528589 for (;;) {
529− linenum++;
530− lineval = parseline();
590+ Linetype lineval = parseline();
531591 trans_table[ifstate[depth]][lineval]();
532− debug("process %s -> %s depth %d",
533− linetype_name[lineval],
592+ debug("process line %d %s -> %s depth %d",
593+ linenum, linetype_name[lineval],
534594 ifstate_name[ifstate[depth]], depth);
535595 }
536596 }
537597
598+/*
599+ * Flush the output and handle errors.
600+ */
601+static void
602+closeout(void)
603+{
604+ if (symdepth && !zerosyms)
605+ printf("\n");
606+ if (fclose(output) == EOF) {
607+ warn("couldn't write to %s", ofilename);
608+ if (overwriting) {
609+ unlink(tempname);
610+ errx(2, "%s unchanged", filename);
611+ } else {
612+ exit(2);
613+ }
614+ }
615+}
616+
617+/*
618+ * Clean up and exit.
619+ */
620+static void
621+done(void)
622+{
623+ if (incomment)
624+ error("EOF in comment");
625+ closeout();
626+ if (overwriting && rename(tempname, ofilename) == -1) {
627+ warn("couldn't rename temporary file");
628+ unlink(tempname);
629+ errx(2, "%s unchanged", ofilename);
630+ }
631+ exit(exitstat);
632+}
633+
538634 /*
539635 * Parse a line and determine its type. We keep the preprocessor line
540636 * parser state between calls in the global variable linestate, with
@@ -549,14 +645,22 @@ parseline(void) · 8 unmodified lines
549645 Linetype retval;
550646 Comment_state wascomment;
551647
648+ linenum++;
552649 if (fgets(tline, MAXLINE, input) == NULL)
553650 return (LT_EOF);
651+ if (newline == NULL) {
652+ if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
653+ newline = newline_crlf;
654+ else
655+ newline = newline_unix;
656+ }
554657 retval = LT_PLAIN;
555658 wascomment = incomment;
556659 cp = skipcomment(tline);
557660 if (linestate == LS_START) {
558661 if (*cp == '#') {
559662 linestate = LS_HASH;
663+ firstsym = true;
560664 cp = skipcomment(cp + 1);
561665 } else if (*cp != '\0')
562666 linestate = LS_DIRTY;
@@ -566,7 +670,8 @@ parseline(void) · 3 unmodified lines
566670 cp = skipsym(cp);
567671 kwlen = cp - keyword;
568672 /* no way can we deal with a continuation inside a keyword */
569− if (strncmp(cp, "\\\n", 2) == 0)
673+ if (strncmp(cp, "\\\r\n", 3) == 0 ||
674+ strncmp(cp, "\\\n", 2) == 0)
570675 Eioccc();
571676 if (strlcmp("ifdef", keyword, kwlen) == 0 ||
572677 strlcmp("ifndef", keyword, kwlen) == 0) {
@@ -617,9 +722,8 @@ parseline(void) · 44 unmodified lines
617722 size_t len = cp - tline;
618723 if (fgets(tline + len, MAXLINE - len, input) == NULL) {
619724 /* append the missing newline */
620− tline[len+0] = '\n';
621− tline[len+1] = '\0';
622− cp++;
725+ strcpy(tline + len, newline);
726+ cp += strlen(newline);
623727 linestate = LS_START;
624728 } else {
625729 linestate = LS_DIRTY;
@@ -630,7 +734,7 @@ parseline(void) · 4 unmodified lines
630734 while (*cp != '\0')
631735 cp = skipcomment(cp + 1);
632736 }
633− debug("parser %s comment %s line",
737+ debug("parser line %d state %s comment %s line", linenum,
634738 comment_name[incomment], linestate_name[linestate]);
635739 return (retval);
636740 }
@@ -875,11 +979,16 @@ skipcomment(const char *cp) · 238 unmodified lines
875979 }
876980 while (*cp != '\0')
877981 /* don't reset to LS_START after a line continuation */
878− if (strncmp(cp, "\\\n", 2) == 0)
982+ if (strncmp(cp, "\\\r\n", 3) == 0)
983+ cp += 3;
984+ else if (strncmp(cp, "\\\n", 2) == 0)
879985 cp += 2;
880986 else switch (incomment) {
881987 case NO_COMMENT:
882− if (strncmp(cp, "/\\\n", 3) == 0) {
988+ if (strncmp(cp, "/\\\r\n", 4) == 0) {
989+ incomment = STARTING_COMMENT;
990+ cp += 4;
991+ } else if (strncmp(cp, "/\\\n", 3) == 0) {
883992 incomment = STARTING_COMMENT;
884993 cp += 3;
885994 } else if (strncmp(cp, "/*", 2) == 0) {
@@ -899,7 +1008,7 @@ skipcomment(const char *cp) · 13 unmodified lines
8991008 } else if (strncmp(cp, "\n", 1) == 0) {
9001009 linestate = LS_START;
9011010 cp += 1;
902− } else if (strchr(" \t", *cp) != NULL) {
1011+ } else if (strchr(" \r\t", *cp) != NULL) {
9031012 cp += 1;
9041013 } else
9051014 return (cp);
@@ -931,7 +1040,10 @@ skipcomment(const char *cp) · 25 unmodified lines
9311040 cp += 1;
9321041 continue;
9331042 case C_COMMENT:
934− if (strncmp(cp, "*\\\n", 3) == 0) {
1043+ if (strncmp(cp, "*\\\r\n", 4) == 0) {
1044+ incomment = FINISHING_COMMENT;
1045+ cp += 4;
1046+ } else if (strncmp(cp, "*\\\n", 3) == 0) {
9351047 incomment = FINISHING_COMMENT;
9361048 cp += 3;
9371049 } else if (strncmp(cp, "*/", 2) == 0) {
@@ -1015,7 +1127,13 @@ findsym(const char *str) · 77 unmodified lines
10151127 if (cp == str)
10161128 return (-1);
10171129 if (symlist) {
1018− printf("%.*s\n", (int)(cp-str), str);
1130+ if (symdepth && firstsym)
1131+ printf("%s%3d", zerosyms ? "" : "\n", depth);
1132+ firstsym = zerosyms = false;
1133+ printf("%s%.*s%s",
1134+ symdepth ? " " : "",
1135+ (int)(cp-str), str,
1136+ symdepth ? "" : "\n");
10191137 /* we don't care about the value of the symbol */
10201138 return (0);
10211139 }
@@ -1052,7 +1170,7 @@ addsym(bool ignorethis, bool definethis, char *sym) · 30 unmodified lines
10521170 value[symind] = val+1;
10531171 *val = '\0';
10541172 } else if (*val == '\0')
1055− value[symind] = "";
1173+ value[symind] = "1";
10561174 else
10571175 usage();
10581176 } else {
@@ -1060,6 +1178,8 @@ addsym(bool ignorethis, bool definethis, char *sym) · 1 unmodified line
10601178 usage();
10611179 value[symind] = NULL;
10621180 }
1181+ debug("addsym %s=%s", symname[symind],
1182+ value[symind] ? value[symind] : "undef");
10631183 }
10641184
10651185 /*
@@ -1100,5 +1220,6 @@ error(const char *msg) · 34 unmodified lines
11001220 else
11011221 warnx("%s: %d: %s (#if line %d depth %d)",
11021222 filename, linenum, msg, stifline[depth], depth);
1223+ closeout();
11031224 errx(2, "output may be truncated");
11041225 }