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

Annotation of src/usr.bin/unifdef/unifdef.c, Revision 1.20

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