[BACK]Return to unifdef.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / unifdef

Diff for /src/usr.bin/unifdef/unifdef.c between version 1.15 and 1.16

version 1.15, 2012/03/04 04:05:15 version 1.16, 2014/04/18 21:11:34
Line 1 
Line 1 
 /*      $OpenBSD$       */  
 /*  /*
  * Copyright (c) 2002, 2003 Tony Finch <dot@dotat.at>   * Copyright (c) 2002 - 2014 Tony Finch <dot@dotat.at>
  * Copyright (c) 1985, 1993  
  *      The Regents of the University of California.  All rights reserved.  
  *   *
  * This code is derived from software contributed to Berkeley by  
  * Dave Yost. Support for #if and #elif was added by Tony Finch.  
  *  
  * Redistribution and use in source and binary forms, with or without   * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions   * modification, are permitted provided that the following conditions
  * are met:   * are met:
Line 15 
Line 9 
  * 2. Redistributions in binary form must reproduce the above copyright   * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the   *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.   *    documentation and/or other materials provided with the distribution.
  * 3. Neither the name of the University nor the names of its contributors  
  *    may be used to endorse or promote products derived from this software  
  *    without specific prior written permission.  
  *   *
  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND   * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE   * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)   * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
Line 35 
Line 26 
 /*  /*
  * unifdef - remove ifdef'ed lines   * unifdef - remove ifdef'ed lines
  *   *
    * This code was derived from software contributed to Berkeley by Dave Yost.
    * It was rewritten to support ANSI C by Tony Finch. The original version
    * of unifdef carried the 4-clause BSD copyright licence. None of its code
    * remains in this version (though some of the names remain) so it now
    * carries a more liberal licence.
    *
  *  Wishlist:   *  Wishlist:
  *      provide an option which will append the name of the   *      provide an option which will append the name of the
  *        appropriate symbol after #else's and #endif's   *        appropriate symbol after #else's and #endif's
  *      provide an option which will check symbols after   *      provide an option which will check symbols after
  *        #else's and #endif's to see that they match their   *        #else's and #endif's to see that they match their
  *        corresponding #ifdef or #ifndef   *        corresponding #ifdef or #ifndef
  *      generate #line directives in place of deleted code  
  *   *
  *   The first two items above require better buffer handling, which would   *   These require better buffer handling, which would also make
  *     also make it possible to handle all "dodgy" directives correctly.   *   it possible to handle all "dodgy" directives correctly.
  */   */
   
 #include <ctype.h>  #include "unifdef.h"
 #include <err.h>  
 #include <stdarg.h>  
 #include <stdbool.h>  
 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <unistd.h>  
   
   static const char copyright[] =
       #include "version.h"
       "@(#) $Author$\n"
       "@(#) $URL: http://dotat.at/prog/unifdef $\n"
   ;
   
 /* types of input lines: */  /* types of input lines: */
 typedef enum {  typedef enum {
         LT_TRUEI,               /* a true #if with ignore flag */          LT_TRUEI,               /* a true #if with ignore flag */
Line 72 
Line 67 
         LT_DODGY_LAST = LT_DODGY + LT_ENDIF,          LT_DODGY_LAST = LT_DODGY + LT_ENDIF,
         LT_PLAIN,               /* ordinary line */          LT_PLAIN,               /* ordinary line */
         LT_EOF,                 /* end of file */          LT_EOF,                 /* end of file */
           LT_ERROR,               /* unevaluable #if */
         LT_COUNT          LT_COUNT
 } Linetype;  } Linetype;
   
Line 82 
Line 78 
         "DODGY IF", "DODGY TRUE", "DODGY FALSE",          "DODGY IF", "DODGY TRUE", "DODGY FALSE",
         "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",          "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE",
         "DODGY ELSE", "DODGY ENDIF",          "DODGY ELSE", "DODGY ENDIF",
         "PLAIN", "EOF"          "PLAIN", "EOF", "ERROR"
 };  };
   
   #define linetype_if2elif(lt) ((Linetype)(lt - LT_IF + LT_ELIF))
   #define linetype_2dodgy(lt) ((Linetype)(lt + LT_DODGY))
   
 /* state of #if processing */  /* state of #if processing */
 typedef enum {  typedef enum {
         IS_OUTSIDE,          IS_OUTSIDE,
Line 113 
Line 112 
         C_COMMENT,              /* in a comment like this one */          C_COMMENT,              /* in a comment like this one */
         CXX_COMMENT,            /* between // and end of line */          CXX_COMMENT,            /* between // and end of line */
         STARTING_COMMENT,       /* just after slash-backslash-newline */          STARTING_COMMENT,       /* just after slash-backslash-newline */
         FINISHING_COMMENT       /* star-backslash-newline in a C comment */          FINISHING_COMMENT,      /* star-backslash-newline in a C comment */
           CHAR_LITERAL,           /* inside '' */
           STRING_LITERAL          /* inside "" */
 } Comment_state;  } Comment_state;
   
 static char const * const comment_name[] = {  static char const * const comment_name[] = {
         "NO", "C", "CXX", "STARTING", "FINISHING"          "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING"
 };  };
   
 /* state of preprocessor line parser */  /* state of preprocessor line parser */
Line 136 
Line 137 
  */   */
 #define MAXDEPTH        64                      /* maximum #if nesting */  #define MAXDEPTH        64                      /* maximum #if nesting */
 #define MAXLINE         4096                    /* maximum length of line */  #define MAXLINE         4096                    /* maximum length of line */
 #define MAXSYMS         4096                    /* maximum number of symbols */  #define MAXSYMS         16384                   /* maximum number of symbols */
   
 /*  /*
  * Sometimes when editing a keyword the replacement text is longer, so   * Sometimes when editing a keyword the replacement text is longer, so
Line 148 
Line 149 
  * Globals.   * Globals.
  */   */
   
   static bool             compblank;              /* -B: compress blank lines */
   static bool             lnblank;                /* -b: blank deleted lines */
 static bool             complement;             /* -c: do the complement */  static bool             complement;             /* -c: do the complement */
 static bool             debugging;              /* -d: debugging reports */  static bool             debugging;              /* -d: debugging reports */
   static bool             inplace;                /* -m: modify in place */
 static bool             iocccok;                /* -e: fewer IOCCC errors */  static bool             iocccok;                /* -e: fewer IOCCC errors */
   static bool             strictlogic;            /* -K: keep ambiguous #ifs */
 static bool             killconsts;             /* -k: eval constant #ifs */  static bool             killconsts;             /* -k: eval constant #ifs */
 static bool             lnblank;                /* -l: blank deleted lines */  static bool             lnnum;                  /* -n: add #line directives */
 static bool             symlist;                /* -s: output symbol list */  static bool             symlist;                /* -s: output symbol list */
   static bool             symdepth;               /* -S: output symbol depth */
 static bool             text;                   /* -t: this is a text file */  static bool             text;                   /* -t: this is a text file */
   
 static const char      *symname[MAXSYMS];       /* symbol name */  static const char      *symname[MAXSYMS];       /* symbol name */
Line 164 
Line 170 
 static FILE            *input;                  /* input file pointer */  static FILE            *input;                  /* input file pointer */
 static const char      *filename;               /* input file name */  static const char      *filename;               /* input file name */
 static int              linenum;                /* current line number */  static int              linenum;                /* current line number */
   static const char      *linefile;               /* file name for #line */
   static FILE            *output;                 /* output file pointer */
   static const char      *ofilename;              /* output file name */
   static const char      *backext;                /* backup extension */
   static char            *tempname;               /* avoid splatting input */
   
 static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */  static char             tline[MAXLINE+EDITSLOP];/* input buffer plus space */
 static char            *keyword;                /* used for editing #elif's */  static char            *keyword;                /* used for editing #elif's */
   
   /*
    * When processing a file, the output's newline style will match the
    * input's, and unifdef correctly handles CRLF or LF endings whatever
    * the platform's native style. The stdio streams are opened in binary
    * mode to accommodate platforms whose native newline style is CRLF.
    * When the output isn't a processed input file (when it is error /
    * debug / diagnostic messages) then unifdef uses native line endings.
    */
   
   static const char      *newline;                /* input file format */
   static const char       newline_unix[] = "\n";
   static const char       newline_crlf[] = "\r\n";
   
 static Comment_state    incomment;              /* comment parser state */  static Comment_state    incomment;              /* comment parser state */
 static Line_state       linestate;              /* #if line parser state */  static Line_state       linestate;              /* #if line parser state */
 static Ifstate          ifstate[MAXDEPTH];      /* #if processor state */  static Ifstate          ifstate[MAXDEPTH];      /* #if processor state */
 static bool             ignoring[MAXDEPTH];     /* ignore comments state */  static bool             ignoring[MAXDEPTH];     /* ignore comments state */
 static int              stifline[MAXDEPTH];     /* start of current #if */  static int              stifline[MAXDEPTH];     /* start of current #if */
 static int              depth;                  /* current #if nesting */  static int              depth;                  /* current #if nesting */
 static bool             keepthis;               /* don't delete constant #if */  static int              delcount;               /* count of deleted lines */
   static unsigned         blankcount;             /* count of blank lines */
   static unsigned         blankmax;               /* maximum recent blankcount */
   static bool             constexpr;              /* constant #if expression */
   static bool             zerosyms;               /* to format symdepth output */
   static bool             firstsym;               /* ditto */
   
   static int              exitmode;               /* exit status mode */
 static int              exitstat;               /* program exit status */  static int              exitstat;               /* program exit status */
   
 static void             addsym(bool, bool, char *);  static void             addsym1(bool, bool, char *);
   static void             addsym2(bool, const char *, const char *);
   static char            *astrcat(const char *, const char *);
   static void             cleantemp(void);
   static void             closeio(void);
 static void             debug(const char *, ...);  static void             debug(const char *, ...);
   static void             debugsym(const char *, int);
   static bool             defundef(void);
   static void             defundefile(const char *);
   static void             done(void);
 static void             error(const char *);  static void             error(const char *);
 static int              findsym(const char *);  static int              findsym(const char **);
 static void             flushline(bool);  static void             flushline(bool);
 static Linetype         get_line(void);  static void             hashline(void);
   static void             help(void);
 static Linetype         ifeval(const char **);  static Linetype         ifeval(const char **);
 static void             ignoreoff(void);  static void             ignoreoff(void);
 static void             ignoreon(void);  static void             ignoreon(void);
   static void             indirectsym(void);
 static void             keywordedit(const char *);  static void             keywordedit(const char *);
   static const char      *matchsym(const char *, const char *);
 static void             nest(void);  static void             nest(void);
   static Linetype         parseline(void);
 static void             process(void);  static void             process(void);
   static void             processinout(const char *, const char *);
   static const char      *skipargs(const char *);
 static const char      *skipcomment(const char *);  static const char      *skipcomment(const char *);
   static const char      *skiphash(void);
   static const char      *skipline(const char *);
 static const char      *skipsym(const char *);  static const char      *skipsym(const char *);
 static void             state(Ifstate);  static void             state(Ifstate);
 static int              strlcmp(const char *, const char *, size_t);  static void             unnest(void);
 static void             usage(void);  static void             usage(void);
   static void             version(void);
   static const char      *xstrdup(const char *, const char *);
   
 #define endsym(c) (!isalpha((unsigned char)c) && !isdigit((unsigned char)c) && c != '_')  #define endsym(c) (!isalnum((unsigned char)c) && c != '_')
   
 /*  /*
  * The main program.   * The main program.
Line 206 
Line 254 
 {  {
         int opt;          int opt;
   
         while ((opt = getopt(argc, argv, "i:D:U:I:cdeklst")) != -1)          while ((opt = getopt(argc, argv, "i:D:U:f:I:M:o:x:bBcdehKklmnsStV")) != -1)
                 switch (opt) {                  switch (opt) {
                 case 'i': /* treat stuff controlled by these symbols as text */                  case 'i': /* treat stuff controlled by these symbols as text */
                         /*                          /*
Line 216 
Line 264 
                          */                           */
                         opt = *optarg++;                          opt = *optarg++;
                         if (opt == 'D')                          if (opt == 'D')
                                 addsym(true, true, optarg);                                  addsym1(true, true, optarg);
                         else if (opt == 'U')                          else if (opt == 'U')
                                 addsym(true, false, optarg);                                  addsym1(true, false, optarg);
                         else                          else
                                 usage();                                  usage();
                         break;                          break;
                 case 'D': /* define a symbol */                  case 'D': /* define a symbol */
                         addsym(false, true, optarg);                          addsym1(false, true, optarg);
                         break;                          break;
                 case 'U': /* undef a symbol */                  case 'U': /* undef a symbol */
                         addsym(false, false, optarg);                          addsym1(false, false, optarg);
                         break;                          break;
                 case 'I':                  case 'I': /* no-op for compatibility with cpp */
                         /* no-op for compatibility with cpp */  
                         break;                          break;
                   case 'b': /* blank deleted lines instead of omitting them */
                   case 'l': /* backwards compatibility */
                           lnblank = true;
                           break;
                   case 'B': /* compress blank lines around removed section */
                           compblank = true;
                           break;
                 case 'c': /* treat -D as -U and vice versa */                  case 'c': /* treat -D as -U and vice versa */
                         complement = true;                          complement = true;
                         break;                          break;
Line 240 
Line 294 
                 case 'e': /* fewer errors from dodgy lines */                  case 'e': /* fewer errors from dodgy lines */
                         iocccok = true;                          iocccok = true;
                         break;                          break;
                   case 'f': /* definitions file */
                           defundefile(optarg);
                           break;
                   case 'h':
                           help();
                           break;
                   case 'K': /* keep ambiguous #ifs */
                           strictlogic = true;
                           break;
                 case 'k': /* process constant #ifs */                  case 'k': /* process constant #ifs */
                         killconsts = true;                          killconsts = true;
                         break;                          break;
                 case 'l': /* blank deleted lines instead of omitting them */                  case 'm': /* modify in place */
                         lnblank = true;                          inplace = true;
                         break;                          break;
                   case 'M': /* modify in place and keep backup */
                           inplace = true;
                           backext = optarg;
                           break;
                   case 'n': /* add #line directive after deleted lines */
                           lnnum = true;
                           break;
                   case 'o': /* output to a file */
                           ofilename = optarg;
                           break;
                 case 's': /* only output list of symbols that control #ifs */                  case 's': /* only output list of symbols that control #ifs */
                         symlist = true;                          symlist = true;
                         break;                          break;
                   case 'S': /* list symbols with their nesting depth */
                           symlist = symdepth = true;
                           break;
                 case 't': /* don't parse C comments */                  case 't': /* don't parse C comments */
                         text = true;                          text = true;
                         break;                          break;
                   case 'V':
                           version();
                           break;
                   case 'x':
                           exitmode = atoi(optarg);
                           if(exitmode < 0 || exitmode > 2)
                                   usage();
                           break;
                 default:                  default:
                         usage();                          usage();
                 }                  }
         argc -= optind;          argc -= optind;
         argv += optind;          argv += optind;
         if (nsyms == 0 && !symlist) {          if (compblank && lnblank)
                 warnx("must -D or -U at least one symbol");                  errx(2, "-B and -b are mutually exclusive");
                 usage();          if (symlist && (ofilename != NULL || inplace || argc > 1))
                   errx(2, "-s only works with one input file");
           if (argc > 1 && ofilename != NULL)
                   errx(2, "-o cannot be used with multiple input files");
           if (argc > 1 && !inplace)
                   errx(2, "multiple input files require -m or -M");
           if (argc == 0)
                   argc = 1;
           if (argc == 1 && !inplace && ofilename == NULL)
                   ofilename = "-";
           indirectsym();
   
           atexit(cleantemp);
           if (ofilename != NULL)
                   processinout(*argv, ofilename);
           else while (argc-- > 0) {
                   processinout(*argv, *argv);
                   argv++;
         }          }
         if (argc > 1) {          switch(exitmode) {
                 errx(2, "can only do one file");          case(0): exit(exitstat);
         } else if (argc == 1 && strcmp(*argv, "-") != 0) {          case(1): exit(!exitstat);
                 filename = *argv;          case(2): exit(0);
                 if ((input = fopen(filename, "r")) != NULL) {          default: abort(); /* bug */
                         process();          }
                         (void) fclose(input);  }
                 } else  
                         err(2, "can't open %s", *argv);  /*
         } else {   * File logistics.
    */
   static void
   processinout(const char *ifn, const char *ofn)
   {
           struct stat st;
   
           if (ifn == NULL || strcmp(ifn, "-") == 0) {
                 filename = "[stdin]";                  filename = "[stdin]";
                 input = stdin;                  linefile = NULL;
                   input = fbinmode(stdin);
           } else {
                   filename = ifn;
                   linefile = ifn;
                   input = fopen(ifn, "rb");
                   if (input == NULL)
                           err(2, "can't open %s", ifn);
           }
           if (strcmp(ofn, "-") == 0) {
                   output = fbinmode(stdout);
                 process();                  process();
                   return;
         }          }
           if (stat(ofn, &st) < 0) {
                   output = fopen(ofn, "wb");
                   if (output == NULL)
                           err(2, "can't create %s", ofn);
                   process();
                   return;
           }
   
         exit(exitstat);          tempname = astrcat(ofn, ".XXXXXX");
           output = mktempmode(tempname, st.st_mode);
           if (output == NULL)
                   err(2, "can't create %s", tempname);
   
           process();
   
           if (backext != NULL) {
                   char *backname = astrcat(ofn, backext);
                   if (rename(ofn, backname) < 0)
                           err(2, "can't rename \"%s\" to \"%s\"", ofn, backname);
                   free(backname);
           }
           if (replace(tempname, ofn) < 0)
                   err(2, "can't rename \"%s\" to \"%s\"", tempname, ofn);
           free(tempname);
           tempname = NULL;
 }  }
   
   /*
    * For cleaning up if there is an error.
    */
 static void  static void
   cleantemp(void)
   {
           if (tempname != NULL)
                   remove(tempname);
   }
   
   /*
    * Self-identification functions.
    */
   
   static void
   version(void)
   {
           const char *c = copyright;
           for (;;) {
                   while (*++c != '$')
                           if (*c == '\0')
                                   exit(0);
                   while (*++c != '$')
                           putc(*c, stderr);
                   putc('\n', stderr);
           }
   }
   
   static void
   synopsis(FILE *fp)
   {
           fprintf(fp,
               "usage:     unifdef [-bBcdehKkmnsStV] [-x{012}] [-Mext] [-opath] \\\n"
               "           [-[i]Dsym[=val]] [-[i]Usym] [-fpath] ... [file] ...\n");
   }
   
   static void
 usage(void)  usage(void)
 {  {
         fprintf(stderr,          synopsis(stderr);
             "usage: unifdef [-ceklst] [-Dsym[=val]] [-Ipath] [-iDsym[=val]] "  
             "[-iUsym] [-Usym]\n"  
             "\t[file]\n");  
         exit(2);          exit(2);
 }  }
   
   static void
   help(void)
   {
           synopsis(stdout);
           printf(
               "   -Dsym=val  define preprocessor symbol with given value\n"
               "   -Dsym      define preprocessor symbol with value 1\n"
               "   -Usym      preprocessor symbol is undefined\n"
               "   -iDsym=val \\  ignore C strings and comments\n"
               "   -iDsym      ) in sections controlled by these\n"
               "   -iUsym     /  preprocessor symbols\n"
               "   -fpath  file containing #define and #undef directives\n"
               "   -b      blank lines instead of deleting them\n"
               "   -B      compress blank lines around deleted section\n"
               "   -c      complement (invert) keep vs. delete\n"
               "   -d      debugging mode\n"
               "   -e      ignore multiline preprocessor directives\n"
               "   -h      print help\n"
               "   -Ipath  extra include file path (ignored)\n"
               "   -K      disable && and || short-circuiting\n"
               "   -k      process constant #if expressions\n"
               "   -Mext   modify in place and keep backups\n"
               "   -m      modify input files in place\n"
               "   -n      add #line directives to output\n"
               "   -opath  output file name\n"
               "   -S      list #if control symbols with nesting\n"
               "   -s      list #if control symbols\n"
               "   -t      ignore C strings and comments\n"
               "   -V      print version\n"
               "   -x{012} exit status mode\n"
           );
           exit(0);
   }
   
 /*  /*
  * A state transition function alters the global #if processing state   * A state transition function alters the global #if processing state
  * in a particular way. The table below is indexed by the current   * in a particular way. The table below is indexed by the current
  * processing state and the type of the current line. A NULL entry   * processing state and the type of the current line.
  * indicates that processing is complete.  
  *   *
  * Nesting is handled by keeping a stack of states; some transition   * Nesting is handled by keeping a stack of states; some transition
  * functions increase or decrease the depth. They also maintain the   * functions increase or decrease the depth. They also maintain the
Line 303 
Line 511 
  * When we have processed a group that starts off with a known-false   * When we have processed a group that starts off with a known-false
  * #if/#elif sequence (which has therefore been deleted) followed by a   * #if/#elif sequence (which has therefore been deleted) followed by a
  * #elif that we don't understand and therefore must keep, we edit the   * #elif that we don't understand and therefore must keep, we edit the
  * latter into a #if to keep the nesting correct.   * latter into a #if to keep the nesting correct. We use memcpy() to
    * overwrite the 4 byte token "elif" with "if  " without a '\0' byte.
  *   *
  * When we find a true #elif in a group, the following block will   * When we find a true #elif in a group, the following block will
  * always be kept and the rest of the sequence after the next #elif or   * always be kept and the rest of the sequence after the next #elif or
Line 322 
Line 531 
 typedef void state_fn(void);  typedef void state_fn(void);
   
 /* report an error */  /* report an error */
 static void  static void Eelif (void) { error("Inappropriate #elif"); }
 Eelif(void)  static void Eelse (void) { error("Inappropriate #else"); }
 {  static void Eendif(void) { error("Inappropriate #endif"); }
         error("Inappropriate #elif");  static void Eeof  (void) { error("Premature EOF"); }
 }  static void Eioccc(void) { error("Obfuscated preprocessor control line"); }
   
 static void  
 Eelse(void)  
 {  
         error("Inappropriate #else");  
 }  
   
 static void  
 Eendif(void)  
 {  
         error("Inappropriate #endif");  
 }  
   
 static void  
 Eeof(void)  
 {  
         error("Premature EOF");  
 }  
   
 static void  
 Eioccc(void)  
 {  
         error("Obfuscated preprocessor control line");  
 }  
   
 /* plain line handling */  /* plain line handling */
 static void  static void print (void) { flushline(true); }
 print(void)  static void drop  (void) { flushline(false); }
 {  
         flushline(true);  
 }  
   
 static void  
 drop(void)  
 {  
         flushline(false);  
 }  
   
 /* output lacks group's start line */  /* output lacks group's start line */
 static void  static void Strue (void) { drop();  ignoreoff(); state(IS_TRUE_PREFIX); }
 Strue(void)  static void Sfalse(void) { drop();  ignoreoff(); state(IS_FALSE_PREFIX); }
 {  static void Selse (void) { drop();               state(IS_TRUE_ELSE); }
         drop();  
         ignoreoff();  
         state(IS_TRUE_PREFIX);  
 }  
   
 static void  
 Sfalse(void)  
 {  
         drop();  
         ignoreoff();  
         state(IS_FALSE_PREFIX);  
 }  
   
 static void  
 Selse(void)  
 {  
         drop();  
         state(IS_TRUE_ELSE);  
 }  
   
 /* print/pass this block */  /* print/pass this block */
 static void  static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); }
 Pelif(void)  static void Pelse (void) { print();              state(IS_PASS_ELSE); }
 {  static void Pendif(void) { print(); unnest(); }
         print();  
         ignoreoff();  
         state(IS_PASS_MIDDLE);  
 }  
   
 static void  
 Pelse(void)  
 {  
         print();  
         state(IS_PASS_ELSE);  
 }  
   
 static void  
 Pendif(void)  
 {  
         print();  
         --depth;  
 }  
   
 /* discard this block */  /* discard this block */
 static void  static void Dfalse(void) { drop();  ignoreoff(); state(IS_FALSE_TRAILER); }
 Dfalse(void)  static void Delif (void) { drop();  ignoreoff(); state(IS_FALSE_MIDDLE); }
 {  static void Delse (void) { drop();               state(IS_FALSE_ELSE); }
         drop();  static void Dendif(void) { drop();  unnest(); }
         ignoreoff();  
         state(IS_FALSE_TRAILER);  
 }  
   
 static void  
 Delif(void)  
 {  
         drop();  
         ignoreoff();  
         state(IS_FALSE_MIDDLE);  
 }  
   
 static void  
 Delse(void)  
 {  
         drop();  
         state(IS_FALSE_ELSE);  
 }  
   
 static void  
 Dendif(void)  
 {  
         drop();  
         --depth;  
 }  
   
 /* first line of group */  /* first line of group */
 static void  static void Fdrop (void) { nest();  Dfalse(); }
 Fdrop(void)  static void Fpass (void) { nest();  Pelif(); }
 {  static void Ftrue (void) { nest();  Strue(); }
         nest();  static void Ffalse(void) { nest();  Sfalse(); }
         Dfalse();  
 }  
   
 static void  
 Fpass(void)  
 {  
         nest();  
         Pelif();  
 }  
   
 static void  
 Ftrue(void)  
 {  
         nest();  
         Strue();  
 }  
   
 static void  
 Ffalse(void)  
 {  
         nest();  
         Sfalse();  
 }  
   
 /* variable pedantry for obfuscated lines */  /* variable pedantry for obfuscated lines */
 static void  static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); }
 Oiffy(void)  static void Oif   (void) { if (!iocccok) Eioccc(); Fpass(); }
 {  static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); }
         if (iocccok)  
                 Fpass();  
         else  
                 Eioccc();  
         ignoreon();  
 }  
   
 static void  
 Oif(void)  
 {  
         if (iocccok)  
                 Fpass();  
         else  
                 Eioccc();  
 }  
   
 static void  
 Oelif(void)  
 {  
         if (iocccok)  
                 Pelif();  
         else  
                 Eioccc();  
 }  
   
 /* ignore comments in this block */  /* ignore comments in this block */
 static void  static void Idrop (void) { Fdrop();  ignoreon(); }
 Idrop(void)  static void Itrue (void) { Ftrue();  ignoreon(); }
 {  static void Ifalse(void) { Ffalse(); ignoreon(); }
         Fdrop();  /* modify this line */
         ignoreon();  static void Mpass (void) { memcpy(keyword, "if  ", 4); Pelif(); }
 }  static void Mtrue (void) { keywordedit("else");  state(IS_TRUE_MIDDLE); }
   static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); }
   static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); }
   
 static void  
 Itrue(void)  
 {  
         Ftrue();  
         ignoreon();  
 }  
   
 static void  
 Ifalse(void)  
 {  
         Ffalse();  
         ignoreon();  
 }  
   
 /* edit this line */  
 static void  
 Mpass (void)  
 {  
         strncpy(keyword, "if  ", 4);  
         Pelif();  
 }  
   
 static void  
 Mtrue (void)  
 {  
         keywordedit("else\n");  
         state(IS_TRUE_MIDDLE);  
 }  
   
 static void  
 Melif (void)  
 {  
         keywordedit("endif\n");  
         state(IS_FALSE_TRAILER);  
 }  
   
 static void  
 Melse (void)  
 {  
         keywordedit("endif\n");  
         state(IS_FALSE_ELSE);  
 }  
   
 static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {  static state_fn * const trans_table[IS_COUNT][LT_COUNT] = {
 /* IS_OUTSIDE */  /* IS_OUTSIDE */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eendif,
   print, NULL },    print, done,  abort },
 /* IS_FALSE_PREFIX */  /* IS_FALSE_PREFIX */
 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,  { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif,
   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,    Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc,
   drop,  Eeof },    drop,  Eeof,  abort },
 /* IS_TRUE_PREFIX */  /* IS_TRUE_PREFIX */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
   print, Eeof },    print, Eeof,  abort },
 /* IS_PASS_MIDDLE */  /* IS_PASS_MIDDLE */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Pelif, Oelif, Oelif, Pelse, Pendif,
   print, Eeof },    print, Eeof,  abort },
 /* IS_FALSE_MIDDLE */  /* IS_FALSE_MIDDLE */
 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,  { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif,
   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,    Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc,
   drop,  Eeof },    drop,  Eeof,  abort },
 /* IS_TRUE_MIDDLE */  /* IS_TRUE_MIDDLE */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Eioccc,Eioccc,Eioccc,Eioccc,Pendif,
   print, Eeof },    print, Eeof,  abort },
 /* IS_PASS_ELSE */  /* IS_PASS_ELSE */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Pendif,
   print, Eeof },    print, Eeof,  abort },
 /* IS_FALSE_ELSE */  /* IS_FALSE_ELSE */
 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,  { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif,
   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,    Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc,
   drop,  Eeof },    drop,  Eeof,  abort },
 /* IS_TRUE_ELSE */  /* IS_TRUE_ELSE */
 { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,  { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif,
   Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,    Oiffy, Oiffy, Fpass, Oif,   Oif,   Eelif, Eelif, Eelif, Eelse, Eioccc,
   print, Eeof },    print, Eeof,  abort },
 /* IS_FALSE_TRAILER */  /* IS_FALSE_TRAILER */
 { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,  { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif,
   Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,    Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc,
   drop,  Eeof }    drop,  Eeof,  abort }
 /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF  /*TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF
   TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)    TRUEI  FALSEI IF     TRUE   FALSE  ELIF   ELTRUE ELFALSE ELSE  ENDIF (DODGY)
   PLAIN  EOF */    PLAIN  EOF    ERROR */
 };  };
   
 /*  /*
Line 604 
Line 623 
 static void  static void
 ignoreoff(void)  ignoreoff(void)
 {  {
           if (depth == 0)
                   abort(); /* bug */
         ignoring[depth] = ignoring[depth-1];          ignoring[depth] = ignoring[depth-1];
 }  }
   
 static void  static void
 ignoreon(void)  ignoreon(void)
 {  {
         ignoring[depth] = true;          ignoring[depth] = true;
 }  }
   
 static void  static void
 keywordedit(const char *replacement)  keywordedit(const char *replacement)
 {  {
         strlcpy(keyword, replacement, tline + sizeof(tline) - keyword);          snprintf(keyword, tline + sizeof(tline) - keyword,
               "%s%s", replacement, newline);
         print();          print();
 }  }
   
 static void  static void
 nest(void)  nest(void)
 {  {
         depth += 1;          if (depth > MAXDEPTH-1)
         if (depth >= MAXDEPTH)                  abort(); /* bug */
           if (depth == MAXDEPTH-1)
                 error("Too many levels of nesting");                  error("Too many levels of nesting");
           depth += 1;
         stifline[depth] = linenum;          stifline[depth] = linenum;
 }  }
   
 static void  static void
   unnest(void)
   {
           if (depth == 0)
                   abort(); /* bug */
           depth -= 1;
   }
   static void
 state(Ifstate is)  state(Ifstate is)
 {  {
         ifstate[depth] = is;          ifstate[depth] = is;
 }  }
   
 /*  /*
    * The last state transition function. When this is called,
    * lineval == LT_EOF, so the process() loop will terminate.
    */
   static void
   done(void)
   {
           if (incomment)
                   error("EOF in comment");
           closeio();
   }
   
   /*
  * Write a line to the output or not, according to command line options.   * Write a line to the output or not, according to command line options.
    * If writing fails, closeio() will print the error and exit.
  */   */
 static void  static void
 flushline(bool keep)  flushline(bool keep)
 {  {
         if (symlist)          if (symlist)
                 return;                  return;
         if (keep ^ complement)          if (keep ^ complement) {
                 fputs(tline, stdout);                  bool blankline = tline[strspn(tline, " \t\r\n")] == '\0';
         else {                  if (blankline && compblank && blankcount != blankmax) {
                 if (lnblank)                          delcount += 1;
                         putc('\n', stdout);                          blankcount += 1;
                   } else {
                           if (lnnum && delcount > 0)
                                   hashline();
                           if (fputs(tline, output) == EOF)
                                   closeio();
                           delcount = 0;
                           blankmax = blankcount = blankline ? blankcount + 1 : 0;
                   }
           } else {
                   if (lnblank && fputs(newline, output) == EOF)
                           closeio();
                 exitstat = 1;                  exitstat = 1;
                   delcount += 1;
                   blankcount = 0;
         }          }
           if (debugging && fflush(output) == EOF)
                   closeio();
 }  }
   
 /*  /*
    * Format of #line directives depends on whether we know the input filename.
    */
   static void
   hashline(void)
   {
           int e;
   
           if (linefile == NULL)
                   e = fprintf(output, "#line %d%s", linenum, newline);
           else
                   e = fprintf(output, "#line %d \"%s\"%s",
                       linenum, linefile, newline);
           if (e < 0)
                   closeio();
   }
   
   /*
    * Flush the output and handle errors.
    */
   static void
   closeio(void)
   {
           /* Tidy up after findsym(). */
           if (symdepth && !zerosyms)
                   printf("\n");
           if (output != NULL && (ferror(output) || fclose(output) == EOF))
                           err(2, "%s: can't write to output", filename);
           fclose(input);
   }
   
   /*
  * The driver for the state machine.   * The driver for the state machine.
  */   */
 static void  static void
 process(void)  process(void)
 {  {
         Linetype lineval;          Linetype lineval = LT_PLAIN;
         state_fn *trans;          /* When compressing blank lines, act as if the file
              is preceded by a large number of blank lines. */
         for (;;) {          blankmax = blankcount = 1000;
                 linenum++;          zerosyms = true;
                 lineval = get_line();          newline = NULL;
                 trans = trans_table[ifstate[depth]][lineval];          linenum = 0;
                 if (trans == NULL)          while (lineval != LT_EOF) {
                         break;                  lineval = parseline();
                 trans();                  trans_table[ifstate[depth]][lineval]();
                 debug("process %s -> %s depth %d",                  debug("process line %d %s -> %s depth %d",
                     linetype_name[lineval],                      linenum, linetype_name[lineval],
                     ifstate_name[ifstate[depth]], depth);                      ifstate_name[ifstate[depth]], depth);
         }          }
         if (incomment)  
                 error("EOF in comment");  
 }  }
   
 /*  /*
  * Parse a line and determine its type. We keep the preprocessor line   * Parse a line and determine its type. We keep the preprocessor line
  * parser state between calls in a global variable.   * parser state between calls in the global variable linestate, with
    * help from skipcomment().
  */   */
 static Linetype  static Linetype
 get_line(void)  parseline(void)
 {  {
         const char *cp;          const char *cp;
         int cursym;          int cursym;
         int kwlen;  
         Linetype retval;          Linetype retval;
         Comment_state wascomment;          Comment_state wascomment;
   
         if (fgets(tline, MAXLINE, input) == NULL)  
                 return (LT_EOF);  
         retval = LT_PLAIN;  
         wascomment = incomment;          wascomment = incomment;
         cp = skipcomment(tline);          cp = skiphash();
         if (linestate == LS_START) {          if (cp == NULL)
                 if (*cp == '#') {                  return (LT_EOF);
                         linestate = LS_HASH;          if (newline == NULL) {
                         cp = skipcomment(cp + 1);                  if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1)
                 } else if (*cp != '\0')                          newline = newline_crlf;
                         linestate = LS_DIRTY;                  else
                           newline = newline_unix;
         }          }
         if (!incomment && linestate == LS_HASH) {          if (*cp == '\0') {
                 keyword = tline + (cp - tline);                  retval = LT_PLAIN;
                 cp = skipsym(cp);                  goto done;
                 kwlen = cp - keyword;          }
           keyword = tline + (cp - tline);
           if ((cp = matchsym("ifdef", keyword)) != NULL ||
               (cp = matchsym("ifndef", keyword)) != NULL) {
                   cp = skipcomment(cp);
                   if ((cursym = findsym(&cp)) < 0)
                           retval = LT_IF;
                   else {
                           retval = (keyword[2] == 'n')
                               ? LT_FALSE : LT_TRUE;
                           if (value[cursym] == NULL)
                                   retval = (retval == LT_TRUE)
                                       ? LT_FALSE : LT_TRUE;
                           if (ignore[cursym])
                                   retval = (retval == LT_TRUE)
                                       ? LT_TRUEI : LT_FALSEI;
                   }
           } else if ((cp = matchsym("if", keyword)) != NULL)
                   retval = ifeval(&cp);
           else if ((cp = matchsym("elif", keyword)) != NULL)
                   retval = linetype_if2elif(ifeval(&cp));
           else if ((cp = matchsym("else", keyword)) != NULL)
                   retval = LT_ELSE;
           else if ((cp = matchsym("endif", keyword)) != NULL)
                   retval = LT_ENDIF;
           else {
                   cp = skipsym(keyword);
                 /* no way can we deal with a continuation inside a keyword */                  /* no way can we deal with a continuation inside a keyword */
                 if (strncmp(cp, "\\\n", 2) == 0)                  if (strncmp(cp, "\\\r\n", 3) == 0 ||
                       strncmp(cp, "\\\n", 2) == 0)
                         Eioccc();                          Eioccc();
                 if (strlcmp("ifdef", keyword, kwlen) == 0 ||                  cp = skipline(cp);
                     strlcmp("ifndef", keyword, kwlen) == 0) {                  retval = LT_PLAIN;
                         cp = skipcomment(cp);                  goto done;
                         if ((cursym = findsym(cp)) < 0)          }
                                 retval = LT_IF;          cp = skipcomment(cp);
                         else {          if (*cp != '\0') {
                                 retval = (keyword[2] == 'n')                  cp = skipline(cp);
                                     ? LT_FALSE : LT_TRUE;                  if (retval == LT_TRUE || retval == LT_FALSE ||
                                 if (value[cursym] == NULL)                      retval == LT_TRUEI || retval == LT_FALSEI)
                                         retval = (retval == LT_TRUE)                          retval = LT_IF;
                                             ? LT_FALSE : LT_TRUE;                  if (retval == LT_ELTRUE || retval == LT_ELFALSE)
                                 if (ignore[cursym])                          retval = LT_ELIF;
                                         retval = (retval == LT_TRUE)          }
                                             ? LT_TRUEI : LT_FALSEI;          /* the following can happen if the last line of the file lacks a
                         }             newline or if there is too much whitespace in a directive */
                         cp = skipsym(cp);          if (linestate == LS_HASH) {
                 } else if (strlcmp("if", keyword, kwlen) == 0)                  long len = cp - tline;
                         retval = ifeval(&cp);                  if (fgets(tline + len, MAXLINE - len, input) == NULL) {
                 else if (strlcmp("elif", keyword, kwlen) == 0)                          if (ferror(input))
                         retval = ifeval(&cp) - LT_IF + LT_ELIF;                                  err(2, "can't read %s", filename);
                 else if (strlcmp("else", keyword, kwlen) == 0)                          /* append the missing newline at eof */
                         retval = LT_ELSE;                          strcpy(tline + len, newline);
                 else if (strlcmp("endif", keyword, kwlen) == 0)                          cp += strlen(newline);
                         retval = LT_ENDIF;                          linestate = LS_START;
                 else {                  } else {
                         linestate = LS_DIRTY;                          linestate = LS_DIRTY;
                         retval = LT_PLAIN;  
                 }                  }
                 cp = skipcomment(cp);  
                 if (*cp != '\0') {  
                         linestate = LS_DIRTY;  
                         if (retval == LT_TRUE || retval == LT_FALSE ||  
                             retval == LT_TRUEI || retval == LT_FALSEI)  
                                 retval = LT_IF;  
                         if (retval == LT_ELTRUE || retval == LT_ELFALSE)  
                                 retval = LT_ELIF;  
                 }  
                 if (retval != LT_PLAIN && (wascomment || incomment)) {  
                         retval += LT_DODGY;  
                         if (incomment)  
                                 linestate = LS_DIRTY;  
                 }  
                 /* skipcomment should have changed the state */  
                 if (linestate == LS_HASH)  
                         abort(); /* bug */  
         }          }
         if (linestate == LS_DIRTY) {          if (retval != LT_PLAIN && (wascomment || linestate != LS_START)) {
                 while (*cp != '\0')                  retval = linetype_2dodgy(retval);
                         cp = skipcomment(cp + 1);                  linestate = LS_DIRTY;
         }          }
         debug("parser %s comment %s line",  done:
           debug("parser line %d state %s comment %s line", linenum,
             comment_name[incomment], linestate_name[linestate]);              comment_name[incomment], linestate_name[linestate]);
         return (retval);          return (retval);
 }  }
   
 /*  /*
  * These are the operators that are supported by the expression   * These are the binary operators that are supported by the expression
  * evaluator. Note that if support for division is added then we also   * evaluator.
  * need short-circuiting booleans because of divide-by-zero.  
  */   */
 static int  static Linetype op_strict(long *p, long v, Linetype at, Linetype bt) {
 op_lt(int a, int b)          if(at == LT_IF || bt == LT_IF) return (LT_IF);
 {          return (*p = v, v ? LT_TRUE : LT_FALSE);
         return (a < b);  
 }  }
   static Linetype op_lt(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a < b, at, bt);
 op_gt(int a, int b)  
 {  
         return (a > b);  
 }  }
   static Linetype op_gt(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a > b, at, bt);
 op_le(int a, int b)  
 {  
         return (a <= b);  
 }  }
   static Linetype op_le(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a <= b, at, bt);
 op_ge(int a, int b)  
 {  
         return (a >= b);  
 }  }
   static Linetype op_ge(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a >= b, at, bt);
 op_eq(int a, int b)  
 {  
         return (a == b);  
 }  }
   static Linetype op_eq(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a == b, at, bt);
 op_ne(int a, int b)  
 {  
         return (a != b);  
 }  }
   static Linetype op_ne(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          return op_strict(p, a != b, at, bt);
 op_or(int a, int b)  
 {  
         return (a || b);  
 }  }
   static Linetype op_or(long *p, Linetype at, long a, Linetype bt, long b) {
 static int          if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE))
 op_and(int a, int b)                  return (*p = 1, LT_TRUE);
 {          return op_strict(p, a || b, at, bt);
         return (a && b);  
 }  }
   static Linetype op_and(long *p, Linetype at, long a, Linetype bt, long b) {
           if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE))
                   return (*p = 0, LT_FALSE);
           return op_strict(p, a && b, at, bt);
   }
   
 /*  /*
  * An evaluation function takes three arguments, as follows: (1) a pointer to   * An evaluation function takes three arguments, as follows: (1) a pointer to
Line 823 
Line 899 
  * value of the expression; and (3) a pointer to a char* that points to the   * value of the expression; and (3) a pointer to a char* that points to the
  * expression to be evaluated and that is updated to the end of the expression   * expression to be evaluated and that is updated to the end of the expression
  * when evaluation is complete. The function returns LT_FALSE if the value of   * when evaluation is complete. The function returns LT_FALSE if the value of
  * the expression is zero, LT_TRUE if it is non-zero, or LT_IF if the   * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression
  * expression could not be evaluated.   * depends on an unknown symbol, or LT_ERROR if there is a parse failure.
  */   */
 struct ops;  struct ops;
   
 typedef Linetype eval_fn(const struct ops *, int *, const char **);  typedef Linetype eval_fn(const struct ops *, long *, const char **);
   
 static eval_fn eval_table, eval_unary;  static eval_fn eval_table, eval_unary;
   
Line 839 
Line 915 
  * element of the table. Innermost expressions have special non-table-driven   * element of the table. Innermost expressions have special non-table-driven
  * handling.   * handling.
  */   */
 static const struct ops {  struct op {
           const char *str;
           Linetype (*fn)(long *, Linetype, long, Linetype, long);
   };
   struct ops {
         eval_fn *inner;          eval_fn *inner;
         struct op {          struct op op[5];
                 const char *str;  };
                 int (*fn)(int, int);  static const struct ops eval_ops[] = {
         } op[5];  
 } eval_ops[] = {  
         { eval_table, { { "||", op_or } } },          { eval_table, { { "||", op_or } } },
         { eval_table, { { "&&", op_and } } },          { eval_table, { { "&&", op_and } } },
         { eval_table, { { "==", op_eq },          { eval_table, { { "==", op_eq },
Line 856 
Line 934 
                         { ">", op_gt } } }                          { ">", op_gt } } }
 };  };
   
   /* Current operator precedence level */
   static long prec(const struct ops *ops)
   {
           return (ops - eval_ops);
   }
   
 /*  /*
  * Function for evaluating the innermost parts of expressions,   * Function for evaluating the innermost parts of expressions,
  * viz. !expr (expr) defined(symbol) symbol number   * viz. !expr (expr) number defined(symbol) symbol
  * We reset the keepthis flag when we find a non-constant subexpression.   * We reset the constexpr flag in the last two cases.
  */   */
 static Linetype  static Linetype
 eval_unary(const struct ops *ops, int *valp, const char **cpp)  eval_unary(const struct ops *ops, long *valp, const char **cpp)
 {  {
         const char *cp;          const char *cp;
         char *ep;          char *ep;
         int sym;          int sym;
           bool defparen;
           Linetype lt;
   
         cp = skipcomment(*cpp);          cp = skipcomment(*cpp);
         if (*cp == '!') {          if (*cp == '!') {
                 debug("eval%d !", ops - eval_ops);                  debug("eval%d !", prec(ops));
                 cp++;                  cp++;
                 if (eval_unary(ops, valp, &cp) == LT_IF)                  lt = eval_unary(ops, valp, &cp);
                         return (LT_IF);                  if (lt == LT_ERROR)
                 *valp = !*valp;                          return (LT_ERROR);
                   if (lt != LT_IF) {
                           *valp = !*valp;
                           lt = *valp ? LT_TRUE : LT_FALSE;
                   }
         } else if (*cp == '(') {          } else if (*cp == '(') {
                 cp++;                  cp++;
                 debug("eval%d (", ops - eval_ops);                  debug("eval%d (", prec(ops));
                 if (eval_table(eval_ops, valp, &cp) == LT_IF)                  lt = eval_table(eval_ops, valp, &cp);
                         return (LT_IF);                  if (lt == LT_ERROR)
                           return (LT_ERROR);
                 cp = skipcomment(cp);                  cp = skipcomment(cp);
                 if (*cp++ != ')')                  if (*cp++ != ')')
                         return (LT_IF);                          return (LT_ERROR);
         } else if (isdigit((unsigned char)*cp)) {          } else if (isdigit((unsigned char)*cp)) {
                 debug("eval%d number", ops - eval_ops);                  debug("eval%d number", prec(ops));
                 *valp = strtol(cp, &ep, 0);                  *valp = strtol(cp, &ep, 0);
                 cp = skipsym(cp);                  if (ep == cp)
         } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) {                          return (LT_ERROR);
                   lt = *valp ? LT_TRUE : LT_FALSE;
                   cp = ep;
           } else if (matchsym("defined", cp) != NULL) {
                 cp = skipcomment(cp+7);                  cp = skipcomment(cp+7);
                 debug("eval%d defined", ops - eval_ops);                  if (*cp == '(') {
                 if (*cp++ != '(')                          cp = skipcomment(cp+1);
                         return (LT_IF);                          defparen = true;
                   } else {
                           defparen = false;
                   }
                   sym = findsym(&cp);
                 cp = skipcomment(cp);                  cp = skipcomment(cp);
                 sym = findsym(cp);                  if (defparen && *cp++ != ')') {
                 if (sym < 0 && !symlist)                          debug("eval%d defined missing ')'", prec(ops));
                         return (LT_IF);                          return (LT_ERROR);
                 *valp = (value[sym] != NULL);                  }
                 cp = skipsym(cp);                  if (sym < 0) {
                 cp = skipcomment(cp);                          debug("eval%d defined unknown", prec(ops));
                 if (*cp++ != ')')                          lt = LT_IF;
                         return (LT_IF);                  } else {
                 keepthis = false;                          debug("eval%d defined %s", prec(ops), symname[sym]);
                           *valp = (value[sym] != NULL);
                           lt = *valp ? LT_TRUE : LT_FALSE;
                   }
                   constexpr = false;
         } else if (!endsym(*cp)) {          } else if (!endsym(*cp)) {
                 debug("eval%d symbol", ops - eval_ops);                  debug("eval%d symbol", prec(ops));
                 sym = findsym(cp);                  sym = findsym(&cp);
                 if (sym < 0 && !symlist)                  if (sym < 0) {
                         return (LT_IF);                          lt = LT_IF;
                 if (value[sym] == NULL)                          cp = skipargs(cp);
                   } else if (value[sym] == NULL) {
                         *valp = 0;                          *valp = 0;
                 else {                          lt = LT_FALSE;
                   } else {
                         *valp = strtol(value[sym], &ep, 0);                          *valp = strtol(value[sym], &ep, 0);
                         if (*ep != '\0' || ep == value[sym])                          if (*ep != '\0' || ep == value[sym])
                                 return (LT_IF);                                  return (LT_ERROR);
                           lt = *valp ? LT_TRUE : LT_FALSE;
                           cp = skipargs(cp);
                 }                  }
                 cp = skipsym(cp);                  constexpr = false;
                 keepthis = false;          } else {
         } else                  debug("eval%d bad expr", prec(ops));
                 return (LT_IF);                  return (LT_ERROR);
           }
   
         *cpp = cp;          *cpp = cp;
         debug("eval%d = %d", ops - eval_ops, *valp);          debug("eval%d = %d", prec(ops), *valp);
         return (*valp ? LT_TRUE : LT_FALSE);          return (lt);
 }  }
   
 /*  /*
  * Table-driven evaluation of binary operators.   * Table-driven evaluation of binary operators.
  */   */
 static Linetype  static Linetype
 eval_table(const struct ops *ops, int *valp, const char **cpp)  eval_table(const struct ops *ops, long *valp, const char **cpp)
 {  {
         const struct op *op;          const struct op *op;
         const char *cp;          const char *cp;
         int val;          long val;
           Linetype lt, rt;
   
         debug("eval%d", ops - eval_ops);          debug("eval%d", prec(ops));
         cp = *cpp;          cp = *cpp;
         if (ops->inner(ops+1, valp, &cp) == LT_IF)          lt = ops->inner(ops+1, valp, &cp);
                 return (LT_IF);          if (lt == LT_ERROR)
                   return (LT_ERROR);
         for (;;) {          for (;;) {
                 cp = skipcomment(cp);                  cp = skipcomment(cp);
                 for (op = ops->op; op->str != NULL; op++)                  for (op = ops->op; op->str != NULL; op++)
Line 946 
Line 1055 
                 if (op->str == NULL)                  if (op->str == NULL)
                         break;                          break;
                 cp += strlen(op->str);                  cp += strlen(op->str);
                 debug("eval%d %s", ops - eval_ops, op->str);                  debug("eval%d %s", prec(ops), op->str);
                 if (ops->inner(ops+1, &val, &cp) == LT_IF)                  rt = ops->inner(ops+1, &val, &cp);
                         return (LT_IF);                  if (rt == LT_ERROR)
                 *valp = op->fn(*valp, val);                          return (LT_ERROR);
                   lt = op->fn(valp, lt, *valp, rt, val);
         }          }
   
         *cpp = cp;          *cpp = cp;
         debug("eval%d = %d", ops - eval_ops, *valp);          debug("eval%d = %d", prec(ops), *valp);
         return (*valp ? LT_TRUE : LT_FALSE);          debug("eval%d lt = %s", prec(ops), linetype_name[lt]);
           return (lt);
 }  }
   
 /*  /*
Line 965 
Line 1076 
 static Linetype  static Linetype
 ifeval(const char **cpp)  ifeval(const char **cpp)
 {  {
         int ret;          Linetype ret;
         int val;          long val = 0;
   
         debug("eval %s", *cpp);          debug("eval %s", *cpp);
         keepthis = killconsts ? false : true;          constexpr = killconsts ? false : true;
         ret = eval_table(eval_ops, &val, cpp);          ret = eval_table(eval_ops, &val, cpp);
         return (keepthis ? LT_IF : ret);          debug("eval = %d", val);
           return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret);
 }  }
   
 /*  /*
  * Skip over comments and stop at the next character position that is   * Read a line and examine its initial part to determine if it is a
  * not whitespace. Between calls we keep the comment state in the   * preprocessor directive. Returns NULL on EOF, or a pointer to a
  * global variable incomment, and we also adjust the global variable   * preprocessor directive name, or a pointer to the zero byte at the
  * linestate when we see a newline.   * end of the line.
    */
   static const char *
   skiphash(void)
   {
           const char *cp;
   
           linenum++;
           if (fgets(tline, MAXLINE, input) == NULL) {
                   if (ferror(input))
                           err(2, "can't read %s", filename);
                   else
                           return (NULL);
           }
           cp = skipcomment(tline);
           if (linestate == LS_START && *cp == '#') {
                   linestate = LS_HASH;
                   return (skipcomment(cp + 1));
           } else if (*cp == '\0') {
                   return (cp);
           } else {
                   return (skipline(cp));
           }
   }
   
   /*
    * Mark a line dirty and consume the rest of it, keeping track of the
    * lexical state.
    */
   static const char *
   skipline(const char *cp)
   {
           if (*cp != '\0')
                   linestate = LS_DIRTY;
           while (*cp != '\0')
                   cp = skipcomment(cp + 1);
           return (cp);
   }
   
   /*
    * Skip over comments, strings, and character literals and stop at the
    * next character position that is not whitespace. Between calls we keep
    * the comment state in the global variable incomment, and we also adjust
    * the global variable linestate when we see a newline.
  * XXX: doesn't cope with the buffer splitting inside a state transition.   * XXX: doesn't cope with the buffer splitting inside a state transition.
  */   */
 static const char *  static const char *
Line 991 
Line 1146 
                 return (cp);                  return (cp);
         }          }
         while (*cp != '\0')          while (*cp != '\0')
                 if (strncmp(cp, "\\\n", 2) == 0)                  /* don't reset to LS_START after a line continuation */
                   if (strncmp(cp, "\\\r\n", 3) == 0)
                           cp += 3;
                   else if (strncmp(cp, "\\\n", 2) == 0)
                         cp += 2;                          cp += 2;
                 else switch (incomment) {                  else switch (incomment) {
                 case NO_COMMENT:                  case NO_COMMENT:
                         if (strncmp(cp, "/\\\n", 3) == 0) {                          if (strncmp(cp, "/\\\r\n", 4) == 0) {
                                 incomment = STARTING_COMMENT;                                  incomment = STARTING_COMMENT;
                                   cp += 4;
                           } else if (strncmp(cp, "/\\\n", 3) == 0) {
                                   incomment = STARTING_COMMENT;
                                 cp += 3;                                  cp += 3;
                         } else if (strncmp(cp, "/*", 2) == 0) {                          } else if (strncmp(cp, "/*", 2) == 0) {
                                 incomment = C_COMMENT;                                  incomment = C_COMMENT;
Line 1004 
Line 1165 
                         } else if (strncmp(cp, "//", 2) == 0) {                          } else if (strncmp(cp, "//", 2) == 0) {
                                 incomment = CXX_COMMENT;                                  incomment = CXX_COMMENT;
                                 cp += 2;                                  cp += 2;
                           } else if (strncmp(cp, "\'", 1) == 0) {
                                   incomment = CHAR_LITERAL;
                                   linestate = LS_DIRTY;
                                   cp += 1;
                           } else if (strncmp(cp, "\"", 1) == 0) {
                                   incomment = STRING_LITERAL;
                                   linestate = LS_DIRTY;
                                   cp += 1;
                         } else if (strncmp(cp, "\n", 1) == 0) {                          } else if (strncmp(cp, "\n", 1) == 0) {
                                 linestate = LS_START;                                  linestate = LS_START;
                                 cp += 1;                                  cp += 1;
                         } else if (strchr(" \t", *cp) != NULL) {                          } else if (strchr(" \r\t", *cp) != NULL) {
                                 cp += 1;                                  cp += 1;
                         } else                          } else
                                 return (cp);                                  return (cp);
Line 1019 
Line 1188 
                         }                          }
                         cp += 1;                          cp += 1;
                         continue;                          continue;
                   case CHAR_LITERAL:
                   case STRING_LITERAL:
                           if ((incomment == CHAR_LITERAL && cp[0] == '\'') ||
                               (incomment == STRING_LITERAL && cp[0] == '\"')) {
                                   incomment = NO_COMMENT;
                                   cp += 1;
                           } else if (cp[0] == '\\') {
                                   if (cp[1] == '\0')
                                           cp += 1;
                                   else
                                           cp += 2;
                           } else if (strncmp(cp, "\n", 1) == 0) {
                                   if (incomment == CHAR_LITERAL)
                                           error("unterminated char literal");
                                   else
                                           error("unterminated string literal");
                           } else
                                   cp += 1;
                           continue;
                 case C_COMMENT:                  case C_COMMENT:
                         if (strncmp(cp, "*\\\n", 3) == 0) {                          if (strncmp(cp, "*\\\r\n", 4) == 0) {
                                 incomment = FINISHING_COMMENT;                                  incomment = FINISHING_COMMENT;
                                   cp += 4;
                           } else if (strncmp(cp, "*\\\n", 3) == 0) {
                                   incomment = FINISHING_COMMENT;
                                 cp += 3;                                  cp += 3;
                         } else if (strncmp(cp, "*/", 2) == 0) {                          } else if (strncmp(cp, "*/", 2) == 0) {
                                 incomment = NO_COMMENT;                                  incomment = NO_COMMENT;
Line 1049 
Line 1240 
                                 incomment = C_COMMENT;                                  incomment = C_COMMENT;
                         continue;                          continue;
                 default:                  default:
                         /* bug */                          abort(); /* bug */
                         abort();  
                 }                  }
         return (cp);          return (cp);
 }  }
   
 /*  /*
    * Skip macro arguments.
    */
   static const char *
   skipargs(const char *cp)
   {
           const char *ocp = cp;
           int level = 0;
           cp = skipcomment(cp);
           if (*cp != '(')
                   return (cp);
           do {
                   if (*cp == '(')
                           level++;
                   if (*cp == ')')
                           level--;
                   cp = skipcomment(cp+1);
           } while (level != 0 && *cp != '\0');
           if (level == 0)
                   return (cp);
           else
           /* Rewind and re-detect the syntax error later. */
                   return (ocp);
   }
   
   /*
  * Skip over an identifier.   * Skip over an identifier.
  */   */
 static const char *  static const char *
Line 1067 
Line 1282 
 }  }
   
 /*  /*
    * Skip whitespace and take a copy of any following identifier.
    */
   static const char *
   getsym(const char **cpp)
   {
           const char *cp = *cpp, *sym;
   
           cp = skipcomment(cp);
           cp = skipsym(sym = cp);
           if (cp == sym)
                   return NULL;
           *cpp = cp;
           return (xstrdup(sym, cp));
   }
   
   /*
    * Check that s (a symbol) matches the start of t, and that the
    * following character in t is not a symbol character. Returns a
    * pointer to the following character in t if there is a match,
    * otherwise NULL.
    */
   static const char *
   matchsym(const char *s, const char *t)
   {
           while (*s != '\0' && *t != '\0')
                   if (*s != *t)
                           return (NULL);
                   else
                           ++s, ++t;
           if (*s == '\0' && endsym(*t))
                   return(t);
           else
                   return(NULL);
   }
   
   /*
  * Look for the symbol in the symbol table. If it is found, we return   * Look for the symbol in the symbol table. If it is found, we return
  * the symbol table index, else we return -1.   * the symbol table index, else we return -1.
  */   */
 static int  static int
 findsym(const char *str)  findsym(const char **strp)
 {  {
         const char *cp;          const char *str;
         int symind;          int symind;
   
         cp = skipsym(str);          str = *strp;
         if (cp == str)          *strp = skipsym(str);
                 return (-1);          if (symlist) {
         if (symlist)                  if (*strp == str)
                 printf("%.*s\n", (int)(cp-str), str);                          return (-1);
                   if (symdepth && firstsym)
                           printf("%s%3d", zerosyms ? "" : "\n", depth);
                   firstsym = zerosyms = false;
                   printf("%s%.*s%s",
                          symdepth ? " " : "",
                          (int)(*strp-str), str,
                          symdepth ? "" : "\n");
                   /* we don't care about the value of the symbol */
                   return (0);
           }
         for (symind = 0; symind < nsyms; ++symind) {          for (symind = 0; symind < nsyms; ++symind) {
                 if (strlcmp(symname[symind], str, cp-str) == 0) {                  if (matchsym(symname[symind], str) != NULL) {
                         debug("findsym %s %s", symname[symind],                          debugsym("findsym", symind);
                             value[symind] ? value[symind] : "");  
                         return (symind);                          return (symind);
                 }                  }
         }          }
Line 1092 
Line 1352 
 }  }
   
 /*  /*
    * Resolve indirect symbol values to their final definitions.
    */
   static void
   indirectsym(void)
   {
           const char *cp;
           int changed, sym, ind;
   
           do {
                   changed = 0;
                   for (sym = 0; sym < nsyms; ++sym) {
                           if (value[sym] == NULL)
                                   continue;
                           cp = value[sym];
                           ind = findsym(&cp);
                           if (ind == -1 || ind == sym ||
                               *cp != '\0' ||
                               value[ind] == NULL ||
                               value[ind] == value[sym])
                                   continue;
                           debugsym("indir...", sym);
                           value[sym] = value[ind];
                           debugsym("...ectsym", sym);
                           changed++;
                   }
           } while (changed);
   }
   
   /*
    * Add a symbol to the symbol table, specified with the format sym=val
    */
   static void
   addsym1(bool ignorethis, bool definethis, char *symval)
   {
           const char *sym, *val;
   
           sym = symval;
           val = skipsym(sym);
           if (definethis && *val == '=') {
                   symval[val - sym] = '\0';
                   val = val + 1;
           } else if (*val == '\0') {
                   val = definethis ? "1" : NULL;
           } else {
                   usage();
           }
           addsym2(ignorethis, sym, val);
   }
   
   /*
  * Add a symbol to the symbol table.   * Add a symbol to the symbol table.
  */   */
 static void  static void
 addsym(bool ignorethis, bool definethis, char *sym)  addsym2(bool ignorethis, const char *sym, const char *val)
 {  {
           const char *cp = sym;
         int symind;          int symind;
         char *val;  
   
         symind = findsym(sym);          symind = findsym(&cp);
         if (symind < 0) {          if (symind < 0) {
                 if (nsyms >= MAXSYMS)                  if (nsyms >= MAXSYMS)
                         errx(2, "too many symbols");                          errx(2, "too many symbols");
                 symind = nsyms++;                  symind = nsyms++;
         }          }
         symname[symind] = sym;  
         ignore[symind] = ignorethis;          ignore[symind] = ignorethis;
         val = sym + (skipsym(sym) - sym);          symname[symind] = sym;
         if (definethis) {          value[symind] = val;
                 if (*val == '=') {          debugsym("addsym", symind);
                         value[symind] = val+1;  }
                         *val = '\0';  
                 } else if (*val == '\0')  static void
                         value[symind] = "";  debugsym(const char *why, int symind)
                 else  {
                         usage();          debug("%s %s%c%s", why, symname[symind],
               value[symind] ? '=' : ' ',
               value[symind] ? value[symind] : "undef");
   }
   
   /*
    * Add symbols to the symbol table from a file containing
    * #define and #undef preprocessor directives.
    */
   static void
   defundefile(const char *fn)
   {
           filename = fn;
           input = fopen(fn, "rb");
           if (input == NULL)
                   err(2, "can't open %s", fn);
           linenum = 0;
           while (defundef())
                   ;
           if (ferror(input))
                   err(2, "can't read %s", filename);
           else
                   fclose(input);
           if (incomment)
                   error("EOF in comment");
   }
   
   /*
    * Read and process one #define or #undef directive
    */
   static bool
   defundef(void)
   {
           const char *cp, *kw, *sym, *val, *end;
   
           cp = skiphash();
           if (cp == NULL)
                   return (false);
           if (*cp == '\0')
                   goto done;
           /* strip trailing whitespace, and do a fairly rough check to
              avoid unsupported multi-line preprocessor directives */
           end = cp + strlen(cp);
           while (end > tline && strchr(" \t\n\r", end[-1]) != NULL)
                   --end;
           if (end > tline && end[-1] == '\\')
                   Eioccc();
   
           kw = cp;
           if ((cp = matchsym("define", kw)) != NULL) {
                   sym = getsym(&cp);
                   if (sym == NULL)
                           error("missing macro name in #define");
                   if (*cp == '(') {
                           val = "1";
                   } else {
                           cp = skipcomment(cp);
                           val = (cp < end) ? xstrdup(cp, end) : "";
                   }
                   debug("#define");
                   addsym2(false, sym, val);
           } else if ((cp = matchsym("undef", kw)) != NULL) {
                   sym = getsym(&cp);
                   if (sym == NULL)
                           error("missing macro name in #undef");
                   cp = skipcomment(cp);
                   debug("#undef");
                   addsym2(false, sym, NULL);
         } else {          } else {
                 if (*val != '\0')                  error("unrecognized preprocessor directive");
                         usage();  
                 value[symind] = NULL;  
         }          }
           skipline(cp);
   done:
           debug("parser line %d state %s comment %s line", linenum,
               comment_name[incomment], linestate_name[linestate]);
           return (true);
 }  }
   
 /*  /*
  * Compare s with n characters of t.   * Concatenate two strings into new memory, checking for failure.
  * The same as strncmp() except that it checks that s[n] == '\0'.  
  */   */
 static int  static char *
 strlcmp(const char *s, const char *t, size_t n)  astrcat(const char *s1, const char *s2)
 {  {
         while (n-- && *t != '\0')          char *s;
                 if (*s != *t)          int len;
                         return ((unsigned char)*s - (unsigned char)*t);          size_t size;
                 else  
                         ++s, ++t;          len = snprintf(NULL, 0, "%s%s", s1, s2);
         return ((unsigned char)*s);          if (len < 0)
                   err(2, "snprintf");
           size = (size_t)len + 1;
           s = (char *)malloc(size);
           if (s == NULL)
                   err(2, "malloc");
           snprintf(s, size, "%s%s", s1, s2);
           return (s);
 }  }
   
 /*  /*
    * Duplicate a segment of a string, checking for failure.
    */
   static const char *
   xstrdup(const char *start, const char *end)
   {
           size_t n;
           char *s;
   
           if (end < start) abort(); /* bug */
           n = (size_t)(end - start) + 1;
           s = malloc(n);
           if (s == NULL)
                   err(2, "malloc");
           snprintf(s, n, "%s", start);
           return (s);
   }
   
   /*
  * Diagnostics.   * Diagnostics.
  */   */
 static void  static void
Line 1162 
Line 1565 
         else          else
                 warnx("%s: %d: %s (#if line %d depth %d)",                  warnx("%s: %d: %s (#if line %d depth %d)",
                     filename, linenum, msg, stifline[depth], depth);                      filename, linenum, msg, stifline[depth], depth);
           closeio();
         errx(2, "output may be truncated");          errx(2, "output may be truncated");
 }  }

Legend:
Removed from v.1.15  
changed lines
  Added in v.1.16