[BACK]Return to var.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / usr.bin / make

Annotation of src/usr.bin/make/var.c, Revision 1.139

1.139   ! dsl         1: /*     $NetBSD: var.c,v 1.138 2008/12/20 16:03:59 dsl Exp $    */
1.11      christos    2:
1.1       cgd         3: /*
1.15      christos    4:  * Copyright (c) 1988, 1989, 1990, 1993
                      5:  *     The Regents of the University of California.  All rights reserved.
1.80      agc         6:  *
                      7:  * This code is derived from software contributed to Berkeley by
                      8:  * Adam de Boor.
                      9:  *
                     10:  * Redistribution and use in source and binary forms, with or without
                     11:  * modification, are permitted provided that the following conditions
                     12:  * are met:
                     13:  * 1. Redistributions of source code must retain the above copyright
                     14:  *    notice, this list of conditions and the following disclaimer.
                     15:  * 2. Redistributions in binary form must reproduce the above copyright
                     16:  *    notice, this list of conditions and the following disclaimer in the
                     17:  *    documentation and/or other materials provided with the distribution.
                     18:  * 3. Neither the name of the University nor the names of its contributors
                     19:  *    may be used to endorse or promote products derived from this software
                     20:  *    without specific prior written permission.
                     21:  *
                     22:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     23:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     24:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     25:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     26:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     27:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     28:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     29:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     30:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     31:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     32:  * SUCH DAMAGE.
                     33:  */
                     34:
                     35: /*
1.1       cgd        36:  * Copyright (c) 1989 by Berkeley Softworks
                     37:  * All rights reserved.
                     38:  *
                     39:  * This code is derived from software contributed to Berkeley by
                     40:  * Adam de Boor.
                     41:  *
                     42:  * Redistribution and use in source and binary forms, with or without
                     43:  * modification, are permitted provided that the following conditions
                     44:  * are met:
                     45:  * 1. Redistributions of source code must retain the above copyright
                     46:  *    notice, this list of conditions and the following disclaimer.
                     47:  * 2. Redistributions in binary form must reproduce the above copyright
                     48:  *    notice, this list of conditions and the following disclaimer in the
                     49:  *    documentation and/or other materials provided with the distribution.
                     50:  * 3. All advertising materials mentioning features or use of this software
                     51:  *    must display the following acknowledgement:
                     52:  *     This product includes software developed by the University of
                     53:  *     California, Berkeley and its contributors.
                     54:  * 4. Neither the name of the University nor the names of its contributors
                     55:  *    may be used to endorse or promote products derived from this software
                     56:  *    without specific prior written permission.
                     57:  *
                     58:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     59:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     60:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     61:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     62:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     63:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     64:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     65:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     66:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     67:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     68:  * SUCH DAMAGE.
                     69:  */
                     70:
1.88      ross       71: #ifndef MAKE_NATIVE
1.139   ! dsl        72: static char rcsid[] = "$NetBSD: var.c,v 1.138 2008/12/20 16:03:59 dsl Exp $";
1.23      lukem      73: #else
1.19      christos   74: #include <sys/cdefs.h>
1.1       cgd        75: #ifndef lint
1.11      christos   76: #if 0
1.15      christos   77: static char sccsid[] = "@(#)var.c      8.3 (Berkeley) 3/19/94";
1.11      christos   78: #else
1.139   ! dsl        79: __RCSID("$NetBSD: var.c,v 1.138 2008/12/20 16:03:59 dsl Exp $");
1.11      christos   80: #endif
1.1       cgd        81: #endif /* not lint */
1.23      lukem      82: #endif
1.1       cgd        83:
                     84: /*-
                     85:  * var.c --
                     86:  *     Variable-handling functions
                     87:  *
                     88:  * Interface:
1.138     dsl        89:  *     Var_Set             Set the value of a variable in the given
                     90:  *                         context. The variable is created if it doesn't
                     91:  *                         yet exist. The value and variable name need not
                     92:  *                         be preserved.
1.1       cgd        93:  *
                     94:  *     Var_Append          Append more characters to an existing variable
1.138     dsl        95:  *                         in the given context. The variable needn't
                     96:  *                         exist already -- it will be created if it doesn't.
                     97:  *                         A space is placed between the old value and the
                     98:  *                         new one.
1.1       cgd        99:  *
                    100:  *     Var_Exists          See if a variable exists.
                    101:  *
                    102:  *     Var_Value           Return the value of a variable in a context or
1.138     dsl       103:  *                         NULL if the variable is undefined.
1.1       cgd       104:  *
1.5       cgd       105:  *     Var_Subst           Substitute named variable, or all variables if
                    106:  *                         NULL in a string using
1.138     dsl       107:  *                         the given context as the top-most one. If the
                    108:  *                         third argument is non-zero, Parse_Error is
                    109:  *                         called if any variables are undefined.
1.1       cgd       110:  *
                    111:  *     Var_Parse           Parse a variable expansion from a string and
1.138     dsl       112:  *                         return the result and the number of characters
                    113:  *                         consumed.
1.1       cgd       114:  *
                    115:  *     Var_Delete          Delete a variable in a context.
                    116:  *
                    117:  *     Var_Init            Initialize this module.
                    118:  *
                    119:  * Debugging:
                    120:  *     Var_Dump            Print out all variables defined in the given
1.138     dsl       121:  *                         context.
1.1       cgd       122:  *
                    123:  * XXX: There's a lot of duplication in these functions.
                    124:  */
                    125:
1.31      gwr       126: #ifndef NO_REGEX
1.28      wsanchez  127: #include    <sys/types.h>
1.16      christos  128: #include    <regex.h>
1.17      christos  129: #endif
1.70      wiz       130: #include    <ctype.h>
1.17      christos  131: #include    <stdlib.h>
1.82      jmc       132: #include    <limits.h>
1.70      wiz       133:
1.1       cgd       134: #include    "make.h"
                    135: #include    "buf.h"
1.103     sjg       136: #include    "dir.h"
1.111     rillig    137: #include    "job.h"
1.1       cgd       138:
                    139: /*
                    140:  * This is a harmless return value for Var_Parse that can be used by Var_Subst
                    141:  * to determine if there was an error in parsing -- easier than returning
                    142:  * a flag, as things outside this module don't give a hoot.
                    143:  */
1.126     christos  144: char   var_Error[] = "";
1.1       cgd       145:
                    146: /*
1.113     christos  147:  * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
1.1       cgd       148:  * set false. Why not just use a constant? Well, gcc likes to condense
                    149:  * identical string instances...
                    150:  */
1.126     christos  151: static char    varNoError[] = "";
1.1       cgd       152:
                    153: /*
                    154:  * Internally, variables are contained in four different contexts.
                    155:  *     1) the environment. They may not be changed. If an environment
                    156:  *         variable is appended-to, the result is placed in the global
                    157:  *         context.
                    158:  *     2) the global context. Variables set in the Makefile are located in
                    159:  *         the global context. It is the penultimate context searched when
                    160:  *         substituting.
                    161:  *     3) the command-line context. All variables set on the command line
                    162:  *        are placed in this context. They are UNALTERABLE once placed here.
                    163:  *     4) the local context. Each target has associated with it a context
                    164:  *        list. On this list are located the structures describing such
                    165:  *        local variables as $(@) and $(*)
                    166:  * The four contexts are searched in the reverse order from which they are
                    167:  * listed.
                    168:  */
                    169: GNode          *VAR_GLOBAL;   /* variables from the makefile */
                    170: GNode          *VAR_CMD;      /* variables defined on the command-line */
                    171:
                    172: #define FIND_CMD       0x1   /* look in VAR_CMD when searching */
                    173: #define FIND_GLOBAL    0x2   /* look in VAR_GLOBAL as well */
                    174: #define FIND_ENV       0x4   /* look in the environment also */
                    175:
                    176: typedef struct Var {
                    177:     char          *name;       /* the variable's name */
1.138     dsl       178:     Buffer       val;          /* its value */
                    179:     int                  flags;        /* miscellaneous status flags */
1.1       cgd       180: #define VAR_IN_USE     1           /* Variable's value currently being used.
                    181:                                     * Used to avoid recursion */
                    182: #define VAR_FROM_ENV   2           /* Variable comes from the environment */
                    183: #define VAR_JUNK       4           /* Variable is a junk variable that
                    184:                                     * should be destroyed when done with
                    185:                                     * it. Used by Var_Parse for undefined,
                    186:                                     * modified variables */
1.40      sjg       187: #define VAR_KEEP       8           /* Variable is VAR_JUNK, but we found
                    188:                                     * a use for it in some modifier and
                    189:                                     * the value is therefore valid */
1.118     sjg       190: #define VAR_EXPORTED   16          /* Variable is exported */
                    191: #define VAR_REEXPORT   32          /* Indicate if var needs re-export.
                    192:                                     * This would be true if it contains $'s
                    193:                                     */
1.131     sjg       194: #define VAR_FROM_CMD   64          /* Variable came from command line */
1.1       cgd       195: }  Var;
                    196:
1.118     sjg       197: /*
                    198:  * Exporting vars is expensive so skip it if we can
                    199:  */
                    200: #define VAR_EXPORTED_NONE      0
                    201: #define VAR_EXPORTED_YES       1
                    202: #define VAR_EXPORTED_ALL       2
                    203: static int var_exportedVars = VAR_EXPORTED_NONE;
                    204: /*
                    205:  * We pass this to Var_Export when doing the initial export
                    206:  * or after updating an exported var.
                    207:  */
                    208: #define VAR_EXPORT_FORCE 1
1.16      christos  209:
                    210: /* Var*Pattern flags */
                    211: #define VAR_SUB_GLOBAL 0x01    /* Apply substitution globally */
                    212: #define VAR_SUB_ONE    0x02    /* Apply substitution to one word */
                    213: #define VAR_SUB_MATCHED        0x04    /* There was a match */
                    214: #define VAR_MATCH_START        0x08    /* Match at start of word */
                    215: #define VAR_MATCH_END  0x10    /* Match at end of word */
1.40      sjg       216: #define VAR_NOSUBST    0x20    /* don't expand vars in VarGetPattern */
1.16      christos  217:
1.65      sjg       218: /* Var_Set flags */
                    219: #define VAR_NO_EXPORT  0x01    /* do not export */
                    220:
1.5       cgd       221: typedef struct {
1.81      sjg       222:     /*
                    223:      * The following fields are set by Var_Parse() when it
                    224:      * encounters modifiers that need to keep state for use by
                    225:      * subsequent modifiers within the same variable expansion.
                    226:      */
                    227:     Byte       varSpace;       /* Word separator in expansions */
                    228:     Boolean    oneBigWord;     /* TRUE if we will treat the variable as a
                    229:                                 * single big word, even if it contains
                    230:                                 * embedded spaces (as opposed to the
                    231:                                 * usual behaviour of treating it as
                    232:                                 * several space-separated words). */
                    233: } Var_Parse_State;
                    234:
                    235: /* struct passed as ClientData to VarSubstitute() for ":S/lhs/rhs/",
                    236:  * to VarSYSVMatch() for ":lhs=rhs". */
                    237: typedef struct {
1.73      christos  238:     const char   *lhs;     /* String to match */
1.138     dsl       239:     int                  leftLen; /* Length of string */
1.73      christos  240:     const char   *rhs;     /* Replacement string (w/ &'s removed) */
1.138     dsl       241:     int                  rightLen; /* Length of replacement */
                    242:     int                  flags;
1.5       cgd       243: } VarPattern;
                    244:
1.81      sjg       245: /* struct passed as ClientData to VarLoopExpand() for ":@tvar@str@" */
1.41      sjg       246: typedef struct {
                    247:     GNode      *ctxt;          /* variable context */
                    248:     char       *tvar;          /* name of temp var */
1.127     christos  249:     int                tvarLen;
1.41      sjg       250:     char       *str;           /* string to expand */
1.127     christos  251:     int                strLen;
1.113     christos  252:     int                errnum;         /* errnum for not defined */
1.41      sjg       253: } VarLoop_t;
                    254:
1.31      gwr       255: #ifndef NO_REGEX
1.81      sjg       256: /* struct passed as ClientData to VarRESubstitute() for ":C///" */
1.16      christos  257: typedef struct {
                    258:     regex_t       re;
1.127     christos  259:     int                   nsub;
1.16      christos  260:     regmatch_t           *matches;
                    261:     char         *replace;
                    262:     int                   flags;
                    263: } VarREPattern;
1.17      christos  264: #endif
1.16      christos  265:
1.81      sjg       266: /* struct passed to VarSelectWords() for ":[start..end]" */
                    267: typedef struct {
                    268:     int                start;          /* first word to select */
                    269:     int                end;            /* last word to select */
                    270: } VarSelectWords_t;
                    271:
1.73      christos  272: static Var *VarFind(const char *, GNode *, int);
                    273: static void VarAdd(const char *, const char *, GNode *);
1.81      sjg       274: static Boolean VarHead(GNode *, Var_Parse_State *,
                    275:                        char *, Boolean, Buffer, ClientData);
                    276: static Boolean VarTail(GNode *, Var_Parse_State *,
                    277:                        char *, Boolean, Buffer, ClientData);
                    278: static Boolean VarSuffix(GNode *, Var_Parse_State *,
                    279:                        char *, Boolean, Buffer, ClientData);
                    280: static Boolean VarRoot(GNode *, Var_Parse_State *,
                    281:                        char *, Boolean, Buffer, ClientData);
                    282: static Boolean VarMatch(GNode *, Var_Parse_State *,
                    283:                        char *, Boolean, Buffer, ClientData);
1.13      christos  284: #ifdef SYSVVARSUB
1.81      sjg       285: static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
                    286:                        char *, Boolean, Buffer, ClientData);
1.13      christos  287: #endif
1.81      sjg       288: static Boolean VarNoMatch(GNode *, Var_Parse_State *,
                    289:                        char *, Boolean, Buffer, ClientData);
1.31      gwr       290: #ifndef NO_REGEX
1.70      wiz       291: static void VarREError(int, regex_t *, const char *);
1.81      sjg       292: static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
                    293:                        char *, Boolean, Buffer, ClientData);
1.17      christos  294: #endif
1.81      sjg       295: static Boolean VarSubstitute(GNode *, Var_Parse_State *,
                    296:                        char *, Boolean, Buffer, ClientData);
                    297: static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
                    298:                        char *, Boolean, Buffer, ClientData);
                    299: static char *VarGetPattern(GNode *, Var_Parse_State *,
1.127     christos  300:                           int, const char **, int, int *, int *,
1.70      wiz       301:                           VarPattern *);
                    302: static char *VarQuote(char *);
                    303: static char *VarChangeCase(char *, int);
1.81      sjg       304: static char *VarModify(GNode *, Var_Parse_State *,
                    305:     const char *,
                    306:     Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer, ClientData),
1.73      christos  307:     ClientData);
1.93      sjg       308: static char *VarOrder(const char *, const char);
1.73      christos  309: static char *VarUniq(const char *);
1.70      wiz       310: static int VarWordCompare(const void *, const void *);
                    311: static void VarPrintVar(ClientData);
1.1       cgd       312:
1.100     christos  313: #define BROPEN '{'
                    314: #define BRCLOSE        '}'
                    315: #define PROPEN '('
                    316: #define PRCLOSE        ')'
                    317:
1.1       cgd       318: /*-
                    319:  *-----------------------------------------------------------------------
                    320:  * VarFind --
                    321:  *     Find the given variable in the given context and any other contexts
                    322:  *     indicated.
                    323:  *
1.70      wiz       324:  * Input:
                    325:  *     name            name to find
                    326:  *     ctxt            context in which to find it
                    327:  *     flags           FIND_GLOBAL set means to look in the
                    328:  *                     VAR_GLOBAL context as well. FIND_CMD set means
                    329:  *                     to look in the VAR_CMD context also. FIND_ENV
                    330:  *                     set means to look in the environment
                    331:  *
1.1       cgd       332:  * Results:
                    333:  *     A pointer to the structure describing the desired variable or
1.136     dsl       334:  *     NULL if the variable does not exist.
1.1       cgd       335:  *
                    336:  * Side Effects:
                    337:  *     None
                    338:  *-----------------------------------------------------------------------
                    339:  */
                    340: static Var *
1.73      christos  341: VarFind(const char *name, GNode *ctxt, int flags)
1.1       cgd       342: {
1.36      mycroft   343:     Hash_Entry                 *var;
1.138     dsl       344:     Var                        *v;
1.1       cgd       345:
                    346:        /*
                    347:         * If the variable name begins with a '.', it could very well be one of
                    348:         * the local ones.  We check the name against all the local variables
                    349:         * and substitute the short version in for 'name' if it matches one of
                    350:         * them.
                    351:         */
1.6       jtc       352:        if (*name == '.' && isupper((unsigned char) name[1]))
1.1       cgd       353:                switch (name[1]) {
                    354:                case 'A':
                    355:                        if (!strcmp(name, ".ALLSRC"))
                    356:                                name = ALLSRC;
                    357:                        if (!strcmp(name, ".ARCHIVE"))
                    358:                                name = ARCHIVE;
                    359:                        break;
                    360:                case 'I':
                    361:                        if (!strcmp(name, ".IMPSRC"))
                    362:                                name = IMPSRC;
                    363:                        break;
                    364:                case 'M':
                    365:                        if (!strcmp(name, ".MEMBER"))
                    366:                                name = MEMBER;
                    367:                        break;
                    368:                case 'O':
                    369:                        if (!strcmp(name, ".OODATE"))
                    370:                                name = OODATE;
                    371:                        break;
                    372:                case 'P':
                    373:                        if (!strcmp(name, ".PREFIX"))
                    374:                                name = PREFIX;
                    375:                        break;
                    376:                case 'T':
                    377:                        if (!strcmp(name, ".TARGET"))
                    378:                                name = TARGET;
                    379:                        break;
                    380:                }
                    381:     /*
                    382:      * First look for the variable in the given context. If it's not there,
                    383:      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
                    384:      * depending on the FIND_* flags in 'flags'
                    385:      */
1.92      christos  386:     var = Hash_FindEntry(&ctxt->context, name);
1.1       cgd       387:
1.36      mycroft   388:     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
1.92      christos  389:        var = Hash_FindEntry(&VAR_CMD->context, name);
1.1       cgd       390:     }
1.36      mycroft   391:     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
1.1       cgd       392:        (ctxt != VAR_GLOBAL))
                    393:     {
1.92      christos  394:        var = Hash_FindEntry(&VAR_GLOBAL->context, name);
1.1       cgd       395:     }
1.36      mycroft   396:     if ((var == NULL) && (flags & FIND_ENV)) {
1.1       cgd       397:        char *env;
                    398:
1.97      christos  399:        if ((env = getenv(name)) != NULL) {
1.138     dsl       400:            int         len;
1.15      christos  401:
1.134     joerg     402:            v = bmake_malloc(sizeof(Var));
                    403:            v->name = bmake_strdup(name);
1.1       cgd       404:
                    405:            len = strlen(env);
1.15      christos  406:
1.116     dsl       407:            v->val = Buf_Init(len + 1);
1.1       cgd       408:            Buf_AddBytes(v->val, len, (Byte *)env);
1.15      christos  409:
1.1       cgd       410:            v->flags = VAR_FROM_ENV;
                    411:            return (v);
                    412:        } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
                    413:                   (ctxt != VAR_GLOBAL))
                    414:        {
1.92      christos  415:            var = Hash_FindEntry(&VAR_GLOBAL->context, name);
1.36      mycroft   416:            if (var == NULL) {
1.136     dsl       417:                return NULL;
1.1       cgd       418:            } else {
1.36      mycroft   419:                return ((Var *)Hash_GetValue(var));
1.1       cgd       420:            }
                    421:        } else {
1.136     dsl       422:            return NULL;
1.1       cgd       423:        }
1.36      mycroft   424:     } else if (var == NULL) {
1.136     dsl       425:        return NULL;
1.1       cgd       426:     } else {
1.97      christos  427:        return ((Var *)Hash_GetValue(var));
1.1       cgd       428:     }
                    429: }
                    430:
                    431: /*-
                    432:  *-----------------------------------------------------------------------
1.105     christos  433:  * VarFreeEnv  --
                    434:  *     If the variable is an environment variable, free it
                    435:  *
                    436:  * Input:
                    437:  *     v               the variable
                    438:  *     destroy         true if the value buffer should be destroyed.
                    439:  *
                    440:  * Results:
                    441:  *     1 if it is an environment variable 0 ow.
                    442:  *
                    443:  * Side Effects:
                    444:  *     The variable is free'ed if it is an environent variable.
                    445:  *-----------------------------------------------------------------------
                    446:  */
                    447: static Boolean
                    448: VarFreeEnv(Var *v, Boolean destroy)
                    449: {
                    450:     if ((v->flags & VAR_FROM_ENV) == 0)
                    451:        return FALSE;
                    452:     free(v->name);
                    453:     Buf_Destroy(v->val, destroy);
                    454:     free(v);
                    455:     return TRUE;
                    456: }
                    457:
                    458: /*-
                    459:  *-----------------------------------------------------------------------
1.1       cgd       460:  * VarAdd  --
                    461:  *     Add a new variable of name name and value val to the given context
                    462:  *
1.70      wiz       463:  * Input:
                    464:  *     name            name of variable to add
                    465:  *     val             value to set it to
                    466:  *     ctxt            context in which to set it
                    467:  *
1.1       cgd       468:  * Results:
                    469:  *     None
                    470:  *
                    471:  * Side Effects:
                    472:  *     The new variable is placed at the front of the given context
                    473:  *     The name and val arguments are duplicated so they may
                    474:  *     safely be freed.
                    475:  *-----------------------------------------------------------------------
                    476:  */
1.5       cgd       477: static void
1.73      christos  478: VarAdd(const char *name, const char *val, GNode *ctxt)
1.1       cgd       479: {
1.70      wiz       480:     Var          *v;
1.138     dsl       481:     int                  len;
1.70      wiz       482:     Hash_Entry    *h;
1.1       cgd       483:
1.134     joerg     484:     v = bmake_malloc(sizeof(Var));
1.1       cgd       485:
1.5       cgd       486:     len = val ? strlen(val) : 0;
1.1       cgd       487:     v->val = Buf_Init(len+1);
1.73      christos  488:     Buf_AddBytes(v->val, len, (const Byte *)val);
1.1       cgd       489:
                    490:     v->flags = 0;
                    491:
1.92      christos  492:     h = Hash_CreateEntry(&ctxt->context, name, NULL);
1.36      mycroft   493:     Hash_SetValue(h, v);
1.37      sommerfe  494:     v->name = h->name;
1.1       cgd       495:     if (DEBUG(VAR)) {
1.114     dsl       496:        fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
1.1       cgd       497:     }
                    498: }
                    499:
                    500: /*-
                    501:  *-----------------------------------------------------------------------
                    502:  * Var_Delete --
                    503:  *     Remove a variable from a context.
                    504:  *
                    505:  * Results:
                    506:  *     None.
                    507:  *
                    508:  * Side Effects:
                    509:  *     The Var structure is removed and freed.
                    510:  *
                    511:  *-----------------------------------------------------------------------
                    512:  */
                    513: void
1.73      christos  514: Var_Delete(const char *name, GNode *ctxt)
1.1       cgd       515: {
1.36      mycroft   516:     Hash_Entry           *ln;
1.1       cgd       517:
1.117     dsl       518:     ln = Hash_FindEntry(&ctxt->context, name);
1.1       cgd       519:     if (DEBUG(VAR)) {
1.117     dsl       520:        fprintf(debug_file, "%s:delete %s%s\n",
                    521:            ctxt->name, name, ln ? "" : " (not found)");
1.1       cgd       522:     }
1.36      mycroft   523:     if (ln != NULL) {
1.70      wiz       524:        Var       *v;
1.1       cgd       525:
1.36      mycroft   526:        v = (Var *)Hash_GetValue(ln);
1.118     sjg       527:        if ((v->flags & VAR_EXPORTED)) {
                    528:            unsetenv(v->name);
                    529:        }
1.37      sommerfe  530:        if (v->name != ln->name)
                    531:                free(v->name);
1.36      mycroft   532:        Hash_DeleteEntry(&ctxt->context, ln);
1.37      sommerfe  533:        Buf_Destroy(v->val, TRUE);
1.98      christos  534:        free(v);
1.1       cgd       535:     }
                    536: }
                    537:
1.118     sjg       538:
                    539: /*
                    540:  * Export a var.
                    541:  * We ignore make internal variables (those which start with '.')
                    542:  * Also we jump through some hoops to avoid calling setenv
                    543:  * more than necessary since it can leak.
                    544:  */
                    545: static int
                    546: Var_Export1(const char *name, int force)
                    547: {
                    548:     char tmp[BUFSIZ];
                    549:     Var *v;
                    550:     char *val = NULL;
                    551:     int n;
                    552:
                    553:     if (*name == '.')
                    554:        return 0;                       /* skip internals */
                    555:     if (!name[1]) {
                    556:        /*
                    557:         * A single char.
                    558:         * If it is one of the vars that should only appear in
                    559:         * local context, skip it, else we can get Var_Subst
                    560:         * into a loop.
                    561:         */
                    562:        switch (name[0]) {
                    563:        case '@':
                    564:        case '%':
                    565:        case '*':
                    566:        case '!':
                    567:            return 0;
                    568:        }
                    569:     }
                    570:     v = VarFind(name, VAR_GLOBAL, 0);
1.136     dsl       571:     if (v == NULL) {
1.118     sjg       572:        return 0;
                    573:     }
                    574:     if (!force &&
                    575:        (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
                    576:        return 0;                       /* nothing to do */
                    577:     }
                    578:     val = (char *)Buf_GetAll(v->val, NULL);
                    579:     if (strchr(val, '$')) {
                    580:        /* Flag this as something we need to re-export */
                    581:        v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
                    582:        if (force) {
                    583:            /*
                    584:             * No point actually exporting it now though,
                    585:             * the child can do it at the last minute.
                    586:             */
                    587:            return 1;
                    588:        }
                    589:        n = snprintf(tmp, sizeof(tmp), "${%s}", name);
                    590:        if (n < sizeof(tmp)) {
                    591:            val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
                    592:            setenv(name, val, 1);
                    593:            free(val);
                    594:        }
                    595:     } else {
                    596:        v->flags &= ~VAR_REEXPORT;      /* once will do */
                    597:        if (force || !(v->flags & VAR_EXPORTED)) {
                    598:            setenv(name, val, 1);
                    599:        }
                    600:     }
                    601:     /*
                    602:      * This is so Var_Set knows to call Var_Export again...
                    603:      */
                    604:     v->flags |= VAR_EXPORTED;
                    605:     return 1;
                    606: }
                    607:
                    608: /*
                    609:  * This gets called from our children.
                    610:  */
                    611: void
                    612: Var_ExportVars(void)
                    613: {
                    614:     char tmp[BUFSIZ];
                    615:     Hash_Entry                 *var;
                    616:     Hash_Search        state;
                    617:     Var *v;
                    618:     char *val;
                    619:     int n;
                    620:
                    621:     if (VAR_EXPORTED_NONE == var_exportedVars)
                    622:        return;
                    623:
                    624:     if (VAR_EXPORTED_ALL == var_exportedVars) {
                    625:        /*
                    626:         * Ouch! This is crazy...
                    627:         */
                    628:        for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
                    629:             var != NULL;
                    630:             var = Hash_EnumNext(&state)) {
                    631:            v = (Var *)Hash_GetValue(var);
                    632:            Var_Export1(v->name, 0);
                    633:        }
                    634:        return;
                    635:     }
                    636:     /*
                    637:      * We have a number of exported vars,
                    638:      */
                    639:     n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
                    640:     if (n < sizeof(tmp)) {
                    641:        char **av;
                    642:        char *as;
1.127     christos  643:        int ac;
1.118     sjg       644:        int i;
                    645:
                    646:        val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
                    647:        av = brk_string(val, &ac, FALSE, &as);
                    648:        for (i = 0; i < ac; i++) {
                    649:            Var_Export1(av[i], 0);
                    650:        }
                    651:        free(val);
                    652:        free(as);
                    653:        free(av);
                    654:     }
                    655: }
                    656:
                    657: /*
                    658:  * This is called when .export is seen or
                    659:  * .MAKE.EXPORTED is modified.
                    660:  * It is also called when any exported var is modified.
                    661:  */
                    662: void
                    663: Var_Export(char *str, int isExport)
                    664: {
                    665:     char *name;
                    666:     char *val;
                    667:     char **av;
                    668:     char *as;
1.127     christos  669:     int ac;
1.118     sjg       670:     int i;
                    671:
                    672:     if (isExport && (!str || !str[0])) {
                    673:        var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
                    674:        return;
                    675:     }
                    676:
                    677:     val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
                    678:     av = brk_string(val, &ac, FALSE, &as);
                    679:     for (i = 0; i < ac; i++) {
                    680:        name = av[i];
                    681:        if (!name[1]) {
                    682:            /*
                    683:             * A single char.
                    684:             * If it is one of the vars that should only appear in
                    685:             * local context, skip it, else we can get Var_Subst
                    686:             * into a loop.
                    687:             */
                    688:            switch (name[0]) {
                    689:            case '@':
                    690:            case '%':
                    691:            case '*':
                    692:            case '!':
                    693:                continue;
                    694:            }
                    695:        }
                    696:        if (Var_Export1(name, VAR_EXPORT_FORCE)) {
                    697:            if (VAR_EXPORTED_ALL != var_exportedVars)
                    698:                var_exportedVars = VAR_EXPORTED_YES;
                    699:            if (isExport) {
                    700:                Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
                    701:            }
                    702:        }
                    703:     }
                    704:     free(val);
                    705:     free(as);
                    706:     free(av);
                    707: }
                    708:
1.1       cgd       709: /*-
                    710:  *-----------------------------------------------------------------------
                    711:  * Var_Set --
                    712:  *     Set the variable name to the value val in the given context.
                    713:  *
1.70      wiz       714:  * Input:
                    715:  *     name            name of variable to set
                    716:  *     val             value to give to the variable
                    717:  *     ctxt            context in which to set it
                    718:  *
1.1       cgd       719:  * Results:
                    720:  *     None.
                    721:  *
                    722:  * Side Effects:
                    723:  *     If the variable doesn't yet exist, a new record is created for it.
                    724:  *     Else the old value is freed and the new one stuck in its place
                    725:  *
                    726:  * Notes:
                    727:  *     The variable is searched for only in its context before being
                    728:  *     created in that context. I.e. if the context is VAR_GLOBAL,
                    729:  *     only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
                    730:  *     VAR_CMD->context is searched. This is done to avoid the literally
                    731:  *     thousands of unnecessary strcmp's that used to be done to
                    732:  *     set, say, $(@) or $(<).
1.131     sjg       733:  *     If the context is VAR_GLOBAL though, we check if the variable
                    734:  *     was set in VAR_CMD from the command line and skip it if so.
1.1       cgd       735:  *-----------------------------------------------------------------------
                    736:  */
                    737: void
1.73      christos  738: Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
1.1       cgd       739: {
1.70      wiz       740:     Var   *v;
1.139   ! dsl       741:     char *expanded_name = NULL;
1.42      sjg       742:
1.1       cgd       743:     /*
                    744:      * We only look for a variable in the given context since anything set
                    745:      * here will override anything in a lower context, so there's not much
                    746:      * point in searching them all just to save a bit of memory...
                    747:      */
1.139   ! dsl       748:     if (strchr(name, '$') != NULL) {
        !           749:        expanded_name = Var_Subst(NULL, name, ctxt, 0);
        !           750:        if (expanded_name[0] == 0) {
        !           751:            if (DEBUG(VAR)) {
        !           752:                fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
        !           753:                        "name expands to empty string - ignored\n",
        !           754:                        name, val);
        !           755:            }
        !           756:            free(expanded_name);
        !           757:            return;
        !           758:        }
        !           759:        name = expanded_name;
        !           760:     }
1.129     sjg       761:     if (ctxt == VAR_GLOBAL) {
                    762:        v = VarFind(name, VAR_CMD, 0);
1.136     dsl       763:        if (v != NULL) {
1.131     sjg       764:            if ((v->flags & VAR_FROM_CMD)) {
                    765:                if (DEBUG(VAR)) {
                    766:                    fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
                    767:                }
                    768:                goto out;
                    769:            }
                    770:            VarFreeEnv(v, TRUE);
1.129     sjg       771:        }
                    772:     }
1.92      christos  773:     v = VarFind(name, ctxt, 0);
1.136     dsl       774:     if (v == NULL) {
1.92      christos  775:        VarAdd(name, val, ctxt);
1.1       cgd       776:     } else {
                    777:        Buf_Discard(v->val, Buf_Size(v->val));
1.73      christos  778:        Buf_AddBytes(v->val, strlen(val), (const Byte *)val);
1.1       cgd       779:
                    780:        if (DEBUG(VAR)) {
1.114     dsl       781:            fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
1.1       cgd       782:        }
1.118     sjg       783:        if ((v->flags & VAR_EXPORTED)) {
                    784:            Var_Export1(name, VAR_EXPORT_FORCE);
                    785:        }
1.1       cgd       786:     }
                    787:     /*
                    788:      * Any variables given on the command line are automatically exported
                    789:      * to the environment (as per POSIX standard)
                    790:      */
1.65      sjg       791:     if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
1.136     dsl       792:        if (v == NULL) {
1.131     sjg       793:            /* we just added it */
                    794:            v = VarFind(name, ctxt, 0);
                    795:        }
                    796:        v->flags |= VAR_FROM_CMD;
1.71      thorpej   797:        /*
                    798:         * If requested, don't export these in the environment
                    799:         * individually.  We still put them in MAKEOVERRIDES so
                    800:         * that the command-line settings continue to override
                    801:         * Makefile settings.
                    802:         */
                    803:        if (varNoExportEnv != TRUE)
                    804:            setenv(name, val, 1);
1.62      sjg       805:
1.64      sjg       806:        Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
1.1       cgd       807:     }
1.129     sjg       808:  out:
1.139   ! dsl       809:     if (expanded_name != NULL)
        !           810:        free(expanded_name);
1.136     dsl       811:     if (v != NULL)
1.107     christos  812:        VarFreeEnv(v, TRUE);
1.1       cgd       813: }
                    814:
                    815: /*-
                    816:  *-----------------------------------------------------------------------
                    817:  * Var_Append --
                    818:  *     The variable of the given name has the given value appended to it in
                    819:  *     the given context.
                    820:  *
1.70      wiz       821:  * Input:
                    822:  *     name            name of variable to modify
                    823:  *     val             String to append to it
                    824:  *     ctxt            Context in which this should occur
                    825:  *
1.1       cgd       826:  * Results:
                    827:  *     None
                    828:  *
                    829:  * Side Effects:
                    830:  *     If the variable doesn't exist, it is created. Else the strings
                    831:  *     are concatenated (with a space in between).
                    832:  *
                    833:  * Notes:
                    834:  *     Only if the variable is being sought in the global context is the
                    835:  *     environment searched.
                    836:  *     XXX: Knows its calling circumstances in that if called with ctxt
                    837:  *     an actual target, it will only search that context since only
                    838:  *     a local variable could be being appended to. This is actually
                    839:  *     a big win and must be tolerated.
                    840:  *-----------------------------------------------------------------------
                    841:  */
                    842: void
1.73      christos  843: Var_Append(const char *name, const char *val, GNode *ctxt)
1.1       cgd       844: {
1.70      wiz       845:     Var                   *v;
1.36      mycroft   846:     Hash_Entry    *h;
1.139   ! dsl       847:     char *expanded_name = NULL;
1.1       cgd       848:
1.139   ! dsl       849:     if (strchr(name, '$') != NULL) {
        !           850:        expanded_name = Var_Subst(NULL, name, ctxt, 0);
        !           851:        if (expanded_name[0] == 0) {
        !           852:            if (DEBUG(VAR)) {
        !           853:                fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
        !           854:                        "name expands to empty string - ignored\n",
        !           855:                        name, val);
        !           856:            }
        !           857:            free(expanded_name);
        !           858:            return;
        !           859:        }
        !           860:        name = expanded_name;
        !           861:     }
1.42      sjg       862:
1.92      christos  863:     v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1.1       cgd       864:
1.136     dsl       865:     if (v == NULL) {
1.92      christos  866:        VarAdd(name, val, ctxt);
1.1       cgd       867:     } else {
                    868:        Buf_AddByte(v->val, (Byte)' ');
1.73      christos  869:        Buf_AddBytes(v->val, strlen(val), (const Byte *)val);
1.1       cgd       870:
                    871:        if (DEBUG(VAR)) {
1.114     dsl       872:            fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1.99      christos  873:                   (char *)Buf_GetAll(v->val, NULL));
1.1       cgd       874:        }
                    875:
                    876:        if (v->flags & VAR_FROM_ENV) {
                    877:            /*
                    878:             * If the original variable came from the environment, we
                    879:             * have to install it in the global context (we could place
                    880:             * it in the environment, but then we should provide a way to
                    881:             * export other variables...)
                    882:             */
                    883:            v->flags &= ~VAR_FROM_ENV;
1.92      christos  884:            h = Hash_CreateEntry(&ctxt->context, name, NULL);
1.36      mycroft   885:            Hash_SetValue(h, v);
1.1       cgd       886:        }
                    887:     }
1.139   ! dsl       888:     if (expanded_name != NULL)
        !           889:        free(expanded_name);
1.1       cgd       890: }
                    891:
                    892: /*-
                    893:  *-----------------------------------------------------------------------
                    894:  * Var_Exists --
                    895:  *     See if the given variable exists.
                    896:  *
1.70      wiz       897:  * Input:
                    898:  *     name            Variable to find
                    899:  *     ctxt            Context in which to start search
                    900:  *
1.1       cgd       901:  * Results:
                    902:  *     TRUE if it does, FALSE if it doesn't
                    903:  *
                    904:  * Side Effects:
                    905:  *     None.
                    906:  *
                    907:  *-----------------------------------------------------------------------
                    908:  */
                    909: Boolean
1.73      christos  910: Var_Exists(const char *name, GNode *ctxt)
1.1       cgd       911: {
1.138     dsl       912:     Var                  *v;
1.128     sjg       913:     char          *cp;
1.1       cgd       914:
1.128     sjg       915:     if ((cp = strchr(name, '$')) != NULL) {
                    916:        cp = Var_Subst(NULL, name, ctxt, FALSE);
                    917:     }
                    918:     v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
                    919:     if (cp != NULL) {
                    920:        free(cp);
                    921:     }
1.136     dsl       922:     if (v == NULL) {
1.1       cgd       923:        return(FALSE);
1.105     christos  924:     } else {
                    925:        (void)VarFreeEnv(v, TRUE);
1.1       cgd       926:     }
                    927:     return(TRUE);
                    928: }
                    929:
                    930: /*-
                    931:  *-----------------------------------------------------------------------
                    932:  * Var_Value --
                    933:  *     Return the value of the named variable in the given context
                    934:  *
1.70      wiz       935:  * Input:
                    936:  *     name            name to find
                    937:  *     ctxt            context in which to search for it
                    938:  *
1.1       cgd       939:  * Results:
                    940:  *     The value if the variable exists, NULL if it doesn't
                    941:  *
                    942:  * Side Effects:
                    943:  *     None
                    944:  *-----------------------------------------------------------------------
                    945:  */
                    946: char *
1.73      christos  947: Var_Value(const char *name, GNode *ctxt, char **frp)
1.1       cgd       948: {
                    949:     Var            *v;
                    950:
1.92      christos  951:     v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1.6       jtc       952:     *frp = NULL;
1.136     dsl       953:     if (v != NULL) {
1.99      christos  954:        char *p = ((char *)Buf_GetAll(v->val, NULL));
1.105     christos  955:        if (VarFreeEnv(v, FALSE))
1.6       jtc       956:            *frp = p;
                    957:        return p;
1.1       cgd       958:     } else {
1.136     dsl       959:        return NULL;
1.1       cgd       960:     }
                    961: }
                    962:
                    963: /*-
                    964:  *-----------------------------------------------------------------------
                    965:  * VarHead --
                    966:  *     Remove the tail of the given word and place the result in the given
                    967:  *     buffer.
                    968:  *
1.70      wiz       969:  * Input:
                    970:  *     word            Word to trim
                    971:  *     addSpace        True if need to add a space to the buffer
                    972:  *                     before sticking in the head
                    973:  *     buf             Buffer in which to store it
                    974:  *
1.1       cgd       975:  * Results:
                    976:  *     TRUE if characters were added to the buffer (a space needs to be
                    977:  *     added to the buffer before the next word).
                    978:  *
                    979:  * Side Effects:
                    980:  *     The trimmed word is added to the buffer.
                    981:  *
                    982:  *-----------------------------------------------------------------------
                    983:  */
                    984: static Boolean
1.90      jmc       985: VarHead(GNode *ctx __unused, Var_Parse_State *vpstate,
1.89      jmc       986:        char *word, Boolean addSpace, Buffer buf,
                    987:        ClientData dummy)
1.1       cgd       988: {
1.70      wiz       989:     char *slash;
1.1       cgd       990:
1.97      christos  991:     slash = strrchr(word, '/');
1.99      christos  992:     if (slash != NULL) {
1.81      sjg       993:        if (addSpace && vpstate->varSpace) {
1.97      christos  994:            Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd       995:        }
                    996:        *slash = '\0';
1.97      christos  997:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
1.1       cgd       998:        *slash = '/';
                    999:        return (TRUE);
                   1000:     } else {
                   1001:        /*
                   1002:         * If no directory part, give . (q.v. the POSIX standard)
                   1003:         */
1.81      sjg      1004:        if (addSpace && vpstate->varSpace)
                   1005:            Buf_AddByte(buf, vpstate->varSpace);
1.74      sjg      1006:        Buf_AddByte(buf, (Byte)'.');
1.1       cgd      1007:     }
1.6       jtc      1008:     return(dummy ? TRUE : TRUE);
1.1       cgd      1009: }
                   1010:
                   1011: /*-
                   1012:  *-----------------------------------------------------------------------
                   1013:  * VarTail --
                   1014:  *     Remove the head of the given word and place the result in the given
                   1015:  *     buffer.
                   1016:  *
1.70      wiz      1017:  * Input:
                   1018:  *     word            Word to trim
                   1019:  *     addSpace        True if need to add a space to the buffer
                   1020:  *                     before adding the tail
                   1021:  *     buf             Buffer in which to store it
                   1022:  *
1.1       cgd      1023:  * Results:
                   1024:  *     TRUE if characters were added to the buffer (a space needs to be
                   1025:  *     added to the buffer before the next word).
                   1026:  *
                   1027:  * Side Effects:
                   1028:  *     The trimmed word is added to the buffer.
                   1029:  *
                   1030:  *-----------------------------------------------------------------------
                   1031:  */
                   1032: static Boolean
1.90      jmc      1033: VarTail(GNode *ctx __unused, Var_Parse_State *vpstate,
1.89      jmc      1034:        char *word, Boolean addSpace, Buffer buf,
                   1035:        ClientData dummy)
1.1       cgd      1036: {
1.70      wiz      1037:     char *slash;
1.1       cgd      1038:
1.81      sjg      1039:     if (addSpace && vpstate->varSpace) {
1.97      christos 1040:        Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1041:     }
                   1042:
1.97      christos 1043:     slash = strrchr(word, '/');
1.99      christos 1044:     if (slash != NULL) {
1.1       cgd      1045:        *slash++ = '\0';
1.92      christos 1046:        Buf_AddBytes(buf, strlen(slash), (Byte *)slash);
1.1       cgd      1047:        slash[-1] = '/';
                   1048:     } else {
1.92      christos 1049:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
1.1       cgd      1050:     }
1.6       jtc      1051:     return (dummy ? TRUE : TRUE);
1.1       cgd      1052: }
                   1053:
                   1054: /*-
                   1055:  *-----------------------------------------------------------------------
                   1056:  * VarSuffix --
                   1057:  *     Place the suffix of the given word in the given buffer.
                   1058:  *
1.70      wiz      1059:  * Input:
                   1060:  *     word            Word to trim
                   1061:  *     addSpace        TRUE if need to add a space before placing the
                   1062:  *                     suffix in the buffer
                   1063:  *     buf             Buffer in which to store it
                   1064:  *
1.1       cgd      1065:  * Results:
                   1066:  *     TRUE if characters were added to the buffer (a space needs to be
                   1067:  *     added to the buffer before the next word).
                   1068:  *
                   1069:  * Side Effects:
                   1070:  *     The suffix from the word is placed in the buffer.
                   1071:  *
                   1072:  *-----------------------------------------------------------------------
                   1073:  */
                   1074: static Boolean
1.90      jmc      1075: VarSuffix(GNode *ctx __unused, Var_Parse_State *vpstate,
1.81      sjg      1076:          char *word, Boolean addSpace, Buffer buf,
1.70      wiz      1077:          ClientData dummy)
1.1       cgd      1078: {
1.70      wiz      1079:     char *dot;
1.1       cgd      1080:
1.97      christos 1081:     dot = strrchr(word, '.');
1.99      christos 1082:     if (dot != NULL) {
1.81      sjg      1083:        if (addSpace && vpstate->varSpace) {
1.97      christos 1084:            Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1085:        }
                   1086:        *dot++ = '\0';
1.97      christos 1087:        Buf_AddBytes(buf, strlen(dot), (Byte *)dot);
1.1       cgd      1088:        dot[-1] = '.';
1.6       jtc      1089:        addSpace = TRUE;
1.1       cgd      1090:     }
1.6       jtc      1091:     return (dummy ? addSpace : addSpace);
1.1       cgd      1092: }
                   1093:
                   1094: /*-
                   1095:  *-----------------------------------------------------------------------
                   1096:  * VarRoot --
                   1097:  *     Remove the suffix of the given word and place the result in the
                   1098:  *     buffer.
                   1099:  *
1.70      wiz      1100:  * Input:
                   1101:  *     word            Word to trim
                   1102:  *     addSpace        TRUE if need to add a space to the buffer
                   1103:  *                     before placing the root in it
                   1104:  *     buf             Buffer in which to store it
                   1105:  *
1.1       cgd      1106:  * Results:
                   1107:  *     TRUE if characters were added to the buffer (a space needs to be
                   1108:  *     added to the buffer before the next word).
                   1109:  *
                   1110:  * Side Effects:
                   1111:  *     The trimmed word is added to the buffer.
                   1112:  *
                   1113:  *-----------------------------------------------------------------------
                   1114:  */
                   1115: static Boolean
1.90      jmc      1116: VarRoot(GNode *ctx __unused, Var_Parse_State *vpstate,
1.81      sjg      1117:        char *word, Boolean addSpace, Buffer buf,
1.70      wiz      1118:        ClientData dummy)
1.1       cgd      1119: {
1.70      wiz      1120:     char *dot;
1.1       cgd      1121:
1.81      sjg      1122:     if (addSpace && vpstate->varSpace) {
1.97      christos 1123:        Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1124:     }
                   1125:
1.97      christos 1126:     dot = strrchr(word, '.');
1.99      christos 1127:     if (dot != NULL) {
1.1       cgd      1128:        *dot = '\0';
1.97      christos 1129:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
1.1       cgd      1130:        *dot = '.';
                   1131:     } else {
1.92      christos 1132:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
1.1       cgd      1133:     }
1.6       jtc      1134:     return (dummy ? TRUE : TRUE);
1.1       cgd      1135: }
                   1136:
                   1137: /*-
                   1138:  *-----------------------------------------------------------------------
                   1139:  * VarMatch --
                   1140:  *     Place the word in the buffer if it matches the given pattern.
                   1141:  *     Callback function for VarModify to implement the :M modifier.
1.15      christos 1142:  *
1.70      wiz      1143:  * Input:
                   1144:  *     word            Word to examine
                   1145:  *     addSpace        TRUE if need to add a space to the buffer
                   1146:  *                     before adding the word, if it matches
                   1147:  *     buf             Buffer in which to store it
                   1148:  *     pattern         Pattern the word must match
                   1149:  *
1.1       cgd      1150:  * Results:
                   1151:  *     TRUE if a space should be placed in the buffer before the next
                   1152:  *     word.
                   1153:  *
                   1154:  * Side Effects:
                   1155:  *     The word may be copied to the buffer.
                   1156:  *
                   1157:  *-----------------------------------------------------------------------
                   1158:  */
                   1159: static Boolean
1.90      jmc      1160: VarMatch(GNode *ctx __unused, Var_Parse_State *vpstate,
1.89      jmc      1161:         char *word, Boolean addSpace, Buffer buf,
                   1162:         ClientData pattern)
1.1       cgd      1163: {
1.137     christos 1164:     if (DEBUG(VAR))
                   1165:        fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1.99      christos 1166:     if (Str_Match(word, (char *)pattern)) {
1.81      sjg      1167:        if (addSpace && vpstate->varSpace) {
                   1168:            Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1169:        }
                   1170:        addSpace = TRUE;
                   1171:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
                   1172:     }
                   1173:     return(addSpace);
                   1174: }
                   1175:
1.13      christos 1176: #ifdef SYSVVARSUB
1.5       cgd      1177: /*-
                   1178:  *-----------------------------------------------------------------------
                   1179:  * VarSYSVMatch --
                   1180:  *     Place the word in the buffer if it matches the given pattern.
                   1181:  *     Callback function for VarModify to implement the System V %
                   1182:  *     modifiers.
1.15      christos 1183:  *
1.70      wiz      1184:  * Input:
                   1185:  *     word            Word to examine
                   1186:  *     addSpace        TRUE if need to add a space to the buffer
                   1187:  *                     before adding the word, if it matches
                   1188:  *     buf             Buffer in which to store it
                   1189:  *     patp            Pattern the word must match
                   1190:  *
1.5       cgd      1191:  * Results:
                   1192:  *     TRUE if a space should be placed in the buffer before the next
                   1193:  *     word.
                   1194:  *
                   1195:  * Side Effects:
                   1196:  *     The word may be copied to the buffer.
                   1197:  *
                   1198:  *-----------------------------------------------------------------------
                   1199:  */
                   1200: static Boolean
1.81      sjg      1201: VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
                   1202:             char *word, Boolean addSpace, Buffer buf,
1.70      wiz      1203:             ClientData patp)
1.5       cgd      1204: {
1.127     christos 1205:     int len;
1.5       cgd      1206:     char *ptr;
1.99      christos 1207:     VarPattern           *pat = (VarPattern *)patp;
1.61      explorer 1208:     char *varexp;
1.5       cgd      1209:
1.81      sjg      1210:     if (addSpace && vpstate->varSpace)
                   1211:        Buf_AddByte(buf, vpstate->varSpace);
1.5       cgd      1212:
                   1213:     addSpace = TRUE;
                   1214:
1.61      explorer 1215:     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
                   1216:         varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
                   1217:        Str_SYSVSubst(buf, varexp, ptr, len);
                   1218:        free(varexp);
                   1219:     } else {
1.99      christos 1220:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
1.61      explorer 1221:     }
1.5       cgd      1222:
                   1223:     return(addSpace);
                   1224: }
1.13      christos 1225: #endif
1.5       cgd      1226:
                   1227:
1.1       cgd      1228: /*-
                   1229:  *-----------------------------------------------------------------------
                   1230:  * VarNoMatch --
                   1231:  *     Place the word in the buffer if it doesn't match the given pattern.
                   1232:  *     Callback function for VarModify to implement the :N modifier.
1.15      christos 1233:  *
1.70      wiz      1234:  * Input:
                   1235:  *     word            Word to examine
                   1236:  *     addSpace        TRUE if need to add a space to the buffer
                   1237:  *                     before adding the word, if it matches
                   1238:  *     buf             Buffer in which to store it
                   1239:  *     pattern         Pattern the word must match
                   1240:  *
1.1       cgd      1241:  * Results:
                   1242:  *     TRUE if a space should be placed in the buffer before the next
                   1243:  *     word.
                   1244:  *
                   1245:  * Side Effects:
                   1246:  *     The word may be copied to the buffer.
                   1247:  *
                   1248:  *-----------------------------------------------------------------------
                   1249:  */
                   1250: static Boolean
1.90      jmc      1251: VarNoMatch(GNode *ctx __unused, Var_Parse_State *vpstate,
1.89      jmc      1252:           char *word, Boolean addSpace, Buffer buf,
                   1253:           ClientData pattern)
1.1       cgd      1254: {
1.99      christos 1255:     if (!Str_Match(word, (char *)pattern)) {
1.81      sjg      1256:        if (addSpace && vpstate->varSpace) {
                   1257:            Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1258:        }
                   1259:        addSpace = TRUE;
                   1260:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
                   1261:     }
                   1262:     return(addSpace);
                   1263: }
                   1264:
                   1265:
                   1266: /*-
                   1267:  *-----------------------------------------------------------------------
                   1268:  * VarSubstitute --
                   1269:  *     Perform a string-substitution on the given word, placing the
                   1270:  *     result in the passed buffer.
                   1271:  *
1.70      wiz      1272:  * Input:
                   1273:  *     word            Word to modify
                   1274:  *     addSpace        True if space should be added before
                   1275:  *                     other characters
                   1276:  *     buf             Buffer for result
                   1277:  *     patternp        Pattern for substitution
                   1278:  *
1.1       cgd      1279:  * Results:
                   1280:  *     TRUE if a space is needed before more characters are added.
                   1281:  *
                   1282:  * Side Effects:
                   1283:  *     None.
                   1284:  *
                   1285:  *-----------------------------------------------------------------------
                   1286:  */
                   1287: static Boolean
1.90      jmc      1288: VarSubstitute(GNode *ctx __unused, Var_Parse_State *vpstate,
1.81      sjg      1289:              char *word, Boolean addSpace, Buffer buf,
1.70      wiz      1290:              ClientData patternp)
1.1       cgd      1291: {
1.70      wiz      1292:     int        wordLen;    /* Length of word */
                   1293:     char       *cp;        /* General pointer */
1.99      christos 1294:     VarPattern *pattern = (VarPattern *)patternp;
1.1       cgd      1295:
                   1296:     wordLen = strlen(word);
1.16      christos 1297:     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
                   1298:        (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1.1       cgd      1299:        /*
1.16      christos 1300:         * Still substituting -- break it down into simple anchored cases
1.1       cgd      1301:         * and if none of them fits, perform the general substitution case.
                   1302:         */
                   1303:        if ((pattern->flags & VAR_MATCH_START) &&
                   1304:            (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
                   1305:                /*
                   1306:                 * Anchored at start and beginning of word matches pattern
                   1307:                 */
                   1308:                if ((pattern->flags & VAR_MATCH_END) &&
                   1309:                    (wordLen == pattern->leftLen)) {
                   1310:                        /*
                   1311:                         * Also anchored at end and matches to the end (word
                   1312:                         * is same length as pattern) add space and rhs only
                   1313:                         * if rhs is non-null.
                   1314:                         */
                   1315:                        if (pattern->rightLen != 0) {
1.81      sjg      1316:                            if (addSpace && vpstate->varSpace) {
                   1317:                                Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1318:                            }
                   1319:                            addSpace = TRUE;
                   1320:                            Buf_AddBytes(buf, pattern->rightLen,
1.73      christos 1321:                                         (const Byte *)pattern->rhs);
1.1       cgd      1322:                        }
1.16      christos 1323:                        pattern->flags |= VAR_SUB_MATCHED;
1.1       cgd      1324:                } else if (pattern->flags & VAR_MATCH_END) {
                   1325:                    /*
                   1326:                     * Doesn't match to end -- copy word wholesale
                   1327:                     */
                   1328:                    goto nosub;
                   1329:                } else {
                   1330:                    /*
                   1331:                     * Matches at start but need to copy in trailing characters
                   1332:                     */
                   1333:                    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1.81      sjg      1334:                        if (addSpace && vpstate->varSpace) {
                   1335:                            Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1336:                        }
                   1337:                        addSpace = TRUE;
                   1338:                    }
1.73      christos 1339:                    Buf_AddBytes(buf, pattern->rightLen,
                   1340:                        (const Byte *)pattern->rhs);
1.1       cgd      1341:                    Buf_AddBytes(buf, wordLen - pattern->leftLen,
                   1342:                                 (Byte *)(word + pattern->leftLen));
1.16      christos 1343:                    pattern->flags |= VAR_SUB_MATCHED;
1.1       cgd      1344:                }
                   1345:        } else if (pattern->flags & VAR_MATCH_START) {
                   1346:            /*
                   1347:             * Had to match at start of word and didn't -- copy whole word.
                   1348:             */
                   1349:            goto nosub;
                   1350:        } else if (pattern->flags & VAR_MATCH_END) {
                   1351:            /*
                   1352:             * Anchored at end, Find only place match could occur (leftLen
                   1353:             * characters from the end of the word) and see if it does. Note
                   1354:             * that because the $ will be left at the end of the lhs, we have
                   1355:             * to use strncmp.
                   1356:             */
                   1357:            cp = word + (wordLen - pattern->leftLen);
                   1358:            if ((cp >= word) &&
                   1359:                (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
                   1360:                /*
                   1361:                 * Match found. If we will place characters in the buffer,
                   1362:                 * add a space before hand as indicated by addSpace, then
                   1363:                 * stuff in the initial, unmatched part of the word followed
                   1364:                 * by the right-hand-side.
                   1365:                 */
                   1366:                if (((cp - word) + pattern->rightLen) != 0) {
1.81      sjg      1367:                    if (addSpace && vpstate->varSpace) {
                   1368:                        Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1369:                    }
                   1370:                    addSpace = TRUE;
                   1371:                }
1.73      christos 1372:                Buf_AddBytes(buf, cp - word, (const Byte *)word);
                   1373:                Buf_AddBytes(buf, pattern->rightLen,
                   1374:                    (const Byte *)pattern->rhs);
1.16      christos 1375:                pattern->flags |= VAR_SUB_MATCHED;
1.1       cgd      1376:            } else {
                   1377:                /*
                   1378:                 * Had to match at end and didn't. Copy entire word.
                   1379:                 */
                   1380:                goto nosub;
                   1381:            }
                   1382:        } else {
                   1383:            /*
                   1384:             * Pattern is unanchored: search for the pattern in the word using
                   1385:             * String_FindSubstring, copying unmatched portions and the
                   1386:             * right-hand-side for each match found, handling non-global
1.15      christos 1387:             * substitutions correctly, etc. When the loop is done, any
1.1       cgd      1388:             * remaining part of the word (word and wordLen are adjusted
                   1389:             * accordingly through the loop) is copied straight into the
                   1390:             * buffer.
                   1391:             * addSpace is set FALSE as soon as a space is added to the
                   1392:             * buffer.
                   1393:             */
1.70      wiz      1394:            Boolean done;
1.1       cgd      1395:            int origSize;
                   1396:
                   1397:            done = FALSE;
                   1398:            origSize = Buf_Size(buf);
                   1399:            while (!done) {
                   1400:                cp = Str_FindSubstring(word, pattern->lhs);
1.99      christos 1401:                if (cp != NULL) {
1.127     christos 1402:                    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1.81      sjg      1403:                        Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1404:                        addSpace = FALSE;
                   1405:                    }
1.127     christos 1406:                    Buf_AddBytes(buf, cp-word, (const Byte *)word);
1.73      christos 1407:                    Buf_AddBytes(buf, pattern->rightLen,
                   1408:                        (const Byte *)pattern->rhs);
1.127     christos 1409:                    wordLen -= (cp - word) + pattern->leftLen;
1.1       cgd      1410:                    word = cp + pattern->leftLen;
1.16      christos 1411:                    if (wordLen == 0) {
                   1412:                        done = TRUE;
                   1413:                    }
                   1414:                    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1.1       cgd      1415:                        done = TRUE;
                   1416:                    }
1.16      christos 1417:                    pattern->flags |= VAR_SUB_MATCHED;
1.1       cgd      1418:                } else {
                   1419:                    done = TRUE;
                   1420:                }
                   1421:            }
                   1422:            if (wordLen != 0) {
1.81      sjg      1423:                if (addSpace && vpstate->varSpace) {
                   1424:                    Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1425:                }
                   1426:                Buf_AddBytes(buf, wordLen, (Byte *)word);
                   1427:            }
                   1428:            /*
                   1429:             * If added characters to the buffer, need to add a space
                   1430:             * before we add any more. If we didn't add any, just return
                   1431:             * the previous value of addSpace.
                   1432:             */
                   1433:            return ((Buf_Size(buf) != origSize) || addSpace);
                   1434:        }
                   1435:        return (addSpace);
                   1436:     }
                   1437:  nosub:
1.81      sjg      1438:     if (addSpace && vpstate->varSpace) {
                   1439:        Buf_AddByte(buf, vpstate->varSpace);
1.1       cgd      1440:     }
                   1441:     Buf_AddBytes(buf, wordLen, (Byte *)word);
                   1442:     return(TRUE);
                   1443: }
                   1444:
1.31      gwr      1445: #ifndef NO_REGEX
1.16      christos 1446: /*-
                   1447:  *-----------------------------------------------------------------------
                   1448:  * VarREError --
                   1449:  *     Print the error caused by a regcomp or regexec call.
                   1450:  *
                   1451:  * Results:
                   1452:  *     None.
                   1453:  *
                   1454:  * Side Effects:
                   1455:  *     An error gets printed.
                   1456:  *
                   1457:  *-----------------------------------------------------------------------
                   1458:  */
                   1459: static void
1.113     christos 1460: VarREError(int errnum, regex_t *pat, const char *str)
1.16      christos 1461: {
                   1462:     char *errbuf;
1.127     christos 1463:     int errlen;
1.16      christos 1464:
1.113     christos 1465:     errlen = regerror(errnum, pat, 0, 0);
1.134     joerg    1466:     errbuf = bmake_malloc(errlen);
1.113     christos 1467:     regerror(errnum, pat, errbuf, errlen);
1.16      christos 1468:     Error("%s: %s", str, errbuf);
                   1469:     free(errbuf);
                   1470: }
                   1471:
                   1472:
                   1473: /*-
                   1474:  *-----------------------------------------------------------------------
                   1475:  * VarRESubstitute --
                   1476:  *     Perform a regex substitution on the given word, placing the
                   1477:  *     result in the passed buffer.
                   1478:  *
                   1479:  * Results:
                   1480:  *     TRUE if a space is needed before more characters are added.
                   1481:  *
                   1482:  * Side Effects:
                   1483:  *     None.
                   1484:  *
                   1485:  *-----------------------------------------------------------------------
                   1486:  */
                   1487: static Boolean
1.90      jmc      1488: VarRESubstitute(GNode *ctx __unused, Var_Parse_State *vpstate __unused,
1.89      jmc      1489:                char *word, Boolean addSpace, Buffer buf,
                   1490:                ClientData patternp)
1.16      christos 1491: {
                   1492:     VarREPattern *pat;
                   1493:     int xrv;
                   1494:     char *wp;
                   1495:     char *rp;
                   1496:     int added;
1.20      christos 1497:     int flags = 0;
1.16      christos 1498:
                   1499: #define MAYBE_ADD_SPACE()              \
                   1500:        if (addSpace && !added)         \
                   1501:            Buf_AddByte(buf, ' ');      \
                   1502:        added = 1
                   1503:
                   1504:     added = 0;
                   1505:     wp = word;
                   1506:     pat = patternp;
                   1507:
                   1508:     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
                   1509:        (VAR_SUB_ONE|VAR_SUB_MATCHED))
                   1510:        xrv = REG_NOMATCH;
                   1511:     else {
                   1512:     tryagain:
1.21      christos 1513:        xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1.16      christos 1514:     }
                   1515:
                   1516:     switch (xrv) {
                   1517:     case 0:
                   1518:        pat->flags |= VAR_SUB_MATCHED;
                   1519:        if (pat->matches[0].rm_so > 0) {
                   1520:            MAYBE_ADD_SPACE();
1.127     christos 1521:            Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1.16      christos 1522:        }
                   1523:
                   1524:        for (rp = pat->replace; *rp; rp++) {
                   1525:            if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
                   1526:                MAYBE_ADD_SPACE();
1.127     christos 1527:                Buf_AddByte(buf,rp[1]);
1.16      christos 1528:                rp++;
                   1529:            }
1.30      christos 1530:            else if ((*rp == '&') ||
                   1531:                ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1.16      christos 1532:                int n;
1.73      christos 1533:                const char *subbuf;
1.16      christos 1534:                int sublen;
                   1535:                char errstr[3];
                   1536:
                   1537:                if (*rp == '&') {
                   1538:                    n = 0;
                   1539:                    errstr[0] = '&';
                   1540:                    errstr[1] = '\0';
                   1541:                } else {
                   1542:                    n = rp[1] - '0';
                   1543:                    errstr[0] = '\\';
                   1544:                    errstr[1] = rp[1];
                   1545:                    errstr[2] = '\0';
                   1546:                    rp++;
                   1547:                }
                   1548:
                   1549:                if (n > pat->nsub) {
                   1550:                    Error("No subexpression %s", &errstr[0]);
                   1551:                    subbuf = "";
                   1552:                    sublen = 0;
                   1553:                } else if ((pat->matches[n].rm_so == -1) &&
                   1554:                           (pat->matches[n].rm_eo == -1)) {
                   1555:                    Error("No match for subexpression %s", &errstr[0]);
                   1556:                    subbuf = "";
                   1557:                    sublen = 0;
                   1558:                } else {
1.127     christos 1559:                    subbuf = wp + pat->matches[n].rm_so;
                   1560:                    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1.16      christos 1561:                }
                   1562:
                   1563:                if (sublen > 0) {
                   1564:                    MAYBE_ADD_SPACE();
                   1565:                    Buf_AddBytes(buf, sublen, subbuf);
                   1566:                }
                   1567:            } else {
                   1568:                MAYBE_ADD_SPACE();
                   1569:                Buf_AddByte(buf, *rp);
                   1570:            }
                   1571:        }
1.127     christos 1572:        wp += pat->matches[0].rm_eo;
1.20      christos 1573:        if (pat->flags & VAR_SUB_GLOBAL) {
                   1574:            flags |= REG_NOTBOL;
                   1575:            if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
                   1576:                MAYBE_ADD_SPACE();
                   1577:                Buf_AddByte(buf, *wp);
                   1578:                wp++;
                   1579:
                   1580:            }
                   1581:            if (*wp)
                   1582:                goto tryagain;
                   1583:        }
1.16      christos 1584:        if (*wp) {
                   1585:            MAYBE_ADD_SPACE();
                   1586:            Buf_AddBytes(buf, strlen(wp), wp);
                   1587:        }
                   1588:        break;
                   1589:     default:
                   1590:        VarREError(xrv, &pat->re, "Unexpected regex error");
1.127     christos 1591:        /* fall through */
1.16      christos 1592:     case REG_NOMATCH:
                   1593:        if (*wp) {
                   1594:            MAYBE_ADD_SPACE();
1.127     christos 1595:            Buf_AddBytes(buf,strlen(wp),wp);
1.16      christos 1596:        }
                   1597:        break;
                   1598:     }
1.127     christos 1599:     return(addSpace||added);
1.16      christos 1600: }
1.17      christos 1601: #endif
1.16      christos 1602:
                   1603:
1.40      sjg      1604:
                   1605: /*-
                   1606:  *-----------------------------------------------------------------------
                   1607:  * VarLoopExpand --
                   1608:  *     Implements the :@<temp>@<string>@ modifier of ODE make.
                   1609:  *     We set the temp variable named in pattern.lhs to word and expand
                   1610:  *     pattern.rhs storing the result in the passed buffer.
                   1611:  *
1.70      wiz      1612:  * Input:
                   1613:  *     word            Word to modify
                   1614:  *     addSpace        True if space should be added before
                   1615:  *                     other characters
                   1616:  *     buf             Buffer for result
                   1617:  *     pattern         Datafor substitution
                   1618:  *
1.40      sjg      1619:  * Results:
                   1620:  *     TRUE if a space is needed before more characters are added.
                   1621:  *
                   1622:  * Side Effects:
                   1623:  *     None.
                   1624:  *
                   1625:  *-----------------------------------------------------------------------
                   1626:  */
                   1627: static Boolean
1.90      jmc      1628: VarLoopExpand(GNode *ctx __unused, Var_Parse_State *vpstate __unused,
1.89      jmc      1629:              char *word, Boolean addSpace, Buffer buf,
                   1630:              ClientData loopp)
1.40      sjg      1631: {
1.99      christos 1632:     VarLoop_t  *loop = (VarLoop_t *)loopp;
1.40      sjg      1633:     char *s;
1.60      sjg      1634:     int slen;
1.64      sjg      1635:
                   1636:     if (word && *word) {
1.65      sjg      1637:         Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1.113     christos 1638:         s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1.64      sjg      1639:         if (s != NULL && *s != '\0') {
                   1640:             if (addSpace && *s != '\n')
                   1641:                 Buf_AddByte(buf, ' ');
                   1642:             Buf_AddBytes(buf, (slen = strlen(s)), (Byte *)s);
                   1643:             addSpace = (slen > 0 && s[slen - 1] != '\n');
                   1644:             free(s);
                   1645:         }
1.40      sjg      1646:     }
                   1647:     return addSpace;
                   1648: }
                   1649:
1.81      sjg      1650:
                   1651: /*-
                   1652:  *-----------------------------------------------------------------------
                   1653:  * VarSelectWords --
                   1654:  *     Implements the :[start..end] modifier.
                   1655:  *     This is a special case of VarModify since we want to be able
                   1656:  *     to scan the list backwards if start > end.
                   1657:  *
                   1658:  * Input:
                   1659:  *     str             String whose words should be trimmed
                   1660:  *     seldata         words to select
                   1661:  *
                   1662:  * Results:
                   1663:  *     A string of all the words selected.
                   1664:  *
                   1665:  * Side Effects:
                   1666:  *     None.
                   1667:  *
                   1668:  *-----------------------------------------------------------------------
                   1669:  */
                   1670: static char *
1.90      jmc      1671: VarSelectWords(GNode *ctx __unused, Var_Parse_State *vpstate,
1.81      sjg      1672:               const char *str, VarSelectWords_t *seldata)
                   1673: {
1.138     dsl      1674:     Buffer       buf;              /* Buffer for the new string */
1.81      sjg      1675:     Boolean      addSpace;         /* TRUE if need to add a space to the
                   1676:                                     * buffer before adding the trimmed
                   1677:                                     * word */
                   1678:     char **av;                     /* word list */
                   1679:     char *as;                      /* word list memory */
1.127     christos 1680:     int ac, i;
1.81      sjg      1681:     int start, end, step;
                   1682:
1.92      christos 1683:     buf = Buf_Init(0);
1.81      sjg      1684:     addSpace = FALSE;
                   1685:
                   1686:     if (vpstate->oneBigWord) {
                   1687:        /* fake what brk_string() would do if there were only one word */
                   1688:        ac = 1;
1.134     joerg    1689:        av = bmake_malloc((ac + 1) * sizeof(char *));
                   1690:        as = bmake_strdup(str);
1.81      sjg      1691:        av[0] = as;
                   1692:        av[1] = NULL;
                   1693:     } else {
                   1694:        av = brk_string(str, &ac, FALSE, &as);
                   1695:     }
                   1696:
                   1697:     /*
                   1698:      * Now sanitize seldata.
                   1699:      * If seldata->start or seldata->end are negative, convert them to
                   1700:      * the positive equivalents (-1 gets converted to argc, -2 gets
                   1701:      * converted to (argc-1), etc.).
                   1702:      */
                   1703:     if (seldata->start < 0)
                   1704:        seldata->start = ac + seldata->start + 1;
                   1705:     if (seldata->end < 0)
                   1706:        seldata->end = ac + seldata->end + 1;
                   1707:
                   1708:     /*
                   1709:      * We avoid scanning more of the list than we need to.
                   1710:      */
                   1711:     if (seldata->start > seldata->end) {
                   1712:        start = MIN(ac, seldata->start) - 1;
                   1713:        end = MAX(0, seldata->end - 1);
                   1714:        step = -1;
                   1715:     } else {
                   1716:        start = MAX(0, seldata->start - 1);
                   1717:        end = MIN(ac, seldata->end);
                   1718:        step = 1;
                   1719:     }
                   1720:
                   1721:     for (i = start;
                   1722:         (step < 0 && i >= end) || (step > 0 && i < end);
                   1723:         i += step) {
                   1724:        if (av[i] && *av[i]) {
                   1725:            if (addSpace && vpstate->varSpace) {
                   1726:                Buf_AddByte(buf, vpstate->varSpace);
                   1727:            }
                   1728:            Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
                   1729:            addSpace = TRUE;
                   1730:        }
                   1731:     }
                   1732:
                   1733:     free(as);
                   1734:     free(av);
                   1735:
1.97      christos 1736:     Buf_AddByte(buf, '\0');
1.99      christos 1737:     as = (char *)Buf_GetAll(buf, NULL);
1.92      christos 1738:     Buf_Destroy(buf, FALSE);
1.81      sjg      1739:     return (as);
                   1740: }
                   1741:
1.1       cgd      1742: /*-
                   1743:  *-----------------------------------------------------------------------
                   1744:  * VarModify --
                   1745:  *     Modify each of the words of the passed string using the given
                   1746:  *     function. Used to implement all modifiers.
                   1747:  *
1.70      wiz      1748:  * Input:
                   1749:  *     str             String whose words should be trimmed
                   1750:  *     modProc         Function to use to modify them
                   1751:  *     datum           Datum to pass it
                   1752:  *
1.1       cgd      1753:  * Results:
                   1754:  *     A string of all the words modified appropriately.
                   1755:  *
                   1756:  * Side Effects:
                   1757:  *     None.
                   1758:  *
                   1759:  *-----------------------------------------------------------------------
                   1760:  */
                   1761: static char *
1.81      sjg      1762: VarModify(GNode *ctx, Var_Parse_State *vpstate,
                   1763:     const char *str,
                   1764:     Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
                   1765:                       Boolean, Buffer, ClientData),
1.73      christos 1766:     ClientData datum)
1.1       cgd      1767: {
1.138     dsl      1768:     Buffer       buf;              /* Buffer for the new string */
1.1       cgd      1769:     Boolean      addSpace;         /* TRUE if need to add a space to the
                   1770:                                     * buffer before adding the trimmed
                   1771:                                     * word */
1.81      sjg      1772:     char **av;                     /* word list */
1.24      christos 1773:     char *as;                      /* word list memory */
1.127     christos 1774:     int ac, i;
1.7       jtc      1775:
1.92      christos 1776:     buf = Buf_Init(0);
1.1       cgd      1777:     addSpace = FALSE;
                   1778:
1.81      sjg      1779:     if (vpstate->oneBigWord) {
                   1780:        /* fake what brk_string() would do if there were only one word */
                   1781:        ac = 1;
1.134     joerg    1782:        av = bmake_malloc((ac + 1) * sizeof(char *));
                   1783:        as = bmake_strdup(str);
1.81      sjg      1784:        av[0] = as;
                   1785:        av[1] = NULL;
                   1786:     } else {
                   1787:        av = brk_string(str, &ac, FALSE, &as);
                   1788:     }
1.1       cgd      1789:
1.81      sjg      1790:     for (i = 0; i < ac; i++) {
                   1791:        addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, buf, datum);
                   1792:     }
1.24      christos 1793:
                   1794:     free(as);
                   1795:     free(av);
1.15      christos 1796:
1.97      christos 1797:     Buf_AddByte(buf, '\0');
1.99      christos 1798:     as = (char *)Buf_GetAll(buf, NULL);
1.92      christos 1799:     Buf_Destroy(buf, FALSE);
1.73      christos 1800:     return (as);
1.1       cgd      1801: }
                   1802:
1.35      christos 1803:
                   1804: static int
1.70      wiz      1805: VarWordCompare(const void *a, const void *b)
1.35      christos 1806: {
1.79      scw      1807:        int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1.35      christos 1808:        return r;
                   1809: }
                   1810:
                   1811: /*-
                   1812:  *-----------------------------------------------------------------------
1.93      sjg      1813:  * VarOrder --
                   1814:  *     Order the words in the string.
1.35      christos 1815:  *
1.70      wiz      1816:  * Input:
1.93      sjg      1817:  *     str             String whose words should be sorted.
                   1818:  *     otype           How to order: s - sort, x - random.
1.70      wiz      1819:  *
1.35      christos 1820:  * Results:
1.93      sjg      1821:  *     A string containing the words ordered.
1.35      christos 1822:  *
                   1823:  * Side Effects:
                   1824:  *     None.
                   1825:  *
                   1826:  *-----------------------------------------------------------------------
                   1827:  */
                   1828: static char *
1.93      sjg      1829: VarOrder(const char *str, const char otype)
1.35      christos 1830: {
1.138     dsl      1831:     Buffer       buf;              /* Buffer for the new string */
1.35      christos 1832:     char **av;                     /* word list [first word does not count] */
                   1833:     char *as;                      /* word list memory */
1.127     christos 1834:     int ac, i;
1.35      christos 1835:
1.92      christos 1836:     buf = Buf_Init(0);
1.35      christos 1837:
                   1838:     av = brk_string(str, &ac, FALSE, &as);
                   1839:
                   1840:     if (ac > 0)
1.93      sjg      1841:        switch (otype) {
                   1842:        case 's':       /* sort alphabetically */
                   1843:            qsort(av, ac, sizeof(char *), VarWordCompare);
                   1844:            break;
                   1845:        case 'x':       /* randomize */
                   1846:        {
                   1847:            int rndidx;
                   1848:            char *t;
                   1849:
                   1850:            /*
                   1851:             * We will use [ac..2] range for mod factors. This will produce
                   1852:             * random numbers in [(ac-1)..0] interval, and minimal
                   1853:             * reasonable value for mod factor is 2 (the mod 1 will produce
                   1854:             * 0 with probability 1).
                   1855:             */
                   1856:            for (i = ac-1; i > 0; i--) {
                   1857:                rndidx = random() % (i + 1);
                   1858:                if (i != rndidx) {
                   1859:                    t = av[i];
                   1860:                    av[i] = av[rndidx];
                   1861:                    av[rndidx] = t;
                   1862:                }
                   1863:            }
                   1864:        }
                   1865:        } /* end of switch */
1.35      christos 1866:
                   1867:     for (i = 0; i < ac; i++) {
1.99      christos 1868:        Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
1.35      christos 1869:        if (i != ac - 1)
1.97      christos 1870:            Buf_AddByte(buf, ' ');
1.35      christos 1871:     }
                   1872:
                   1873:     free(as);
                   1874:     free(av);
                   1875:
1.97      christos 1876:     Buf_AddByte(buf, '\0');
1.99      christos 1877:     as = (char *)Buf_GetAll(buf, NULL);
1.92      christos 1878:     Buf_Destroy(buf, FALSE);
1.73      christos 1879:     return (as);
1.35      christos 1880: }
                   1881:
                   1882:
1.1       cgd      1883: /*-
                   1884:  *-----------------------------------------------------------------------
1.55      christos 1885:  * VarUniq --
                   1886:  *     Remove adjacent duplicate words.
                   1887:  *
1.70      wiz      1888:  * Input:
                   1889:  *     str             String whose words should be sorted
                   1890:  *
1.55      christos 1891:  * Results:
                   1892:  *     A string containing the resulting words.
                   1893:  *
                   1894:  * Side Effects:
                   1895:  *     None.
                   1896:  *
                   1897:  *-----------------------------------------------------------------------
                   1898:  */
                   1899: static char *
1.73      christos 1900: VarUniq(const char *str)
1.55      christos 1901: {
1.138     dsl      1902:     Buffer       buf;              /* Buffer for new string */
1.55      christos 1903:     char       **av;               /* List of words to affect */
                   1904:     char        *as;               /* Word list memory */
1.127     christos 1905:     int          ac, i, j;
1.55      christos 1906:
                   1907:     buf = Buf_Init(0);
                   1908:     av = brk_string(str, &ac, FALSE, &as);
                   1909:
                   1910:     if (ac > 1) {
                   1911:        for (j = 0, i = 1; i < ac; i++)
                   1912:            if (strcmp(av[i], av[j]) != 0 && (++j != i))
                   1913:                av[j] = av[i];
                   1914:        ac = j + 1;
                   1915:     }
                   1916:
                   1917:     for (i = 0; i < ac; i++) {
                   1918:        Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
                   1919:        if (i != ac - 1)
                   1920:            Buf_AddByte(buf, ' ');
                   1921:     }
                   1922:
                   1923:     free(as);
                   1924:     free(av);
                   1925:
                   1926:     Buf_AddByte(buf, '\0');
1.99      christos 1927:     as = (char *)Buf_GetAll(buf, NULL);
1.55      christos 1928:     Buf_Destroy(buf, FALSE);
1.73      christos 1929:     return as;
1.55      christos 1930: }
                   1931:
                   1932:
                   1933: /*-
                   1934:  *-----------------------------------------------------------------------
1.16      christos 1935:  * VarGetPattern --
                   1936:  *     Pass through the tstr looking for 1) escaped delimiters,
                   1937:  *     '$'s and backslashes (place the escaped character in
                   1938:  *     uninterpreted) and 2) unescaped $'s that aren't before
1.40      sjg      1939:  *     the delimiter (expand the variable substitution unless flags
                   1940:  *     has VAR_NOSUBST set).
1.16      christos 1941:  *     Return the expanded string or NULL if the delimiter was missing
1.25      christos 1942:  *     If pattern is specified, handle escaped ampersands, and replace
1.16      christos 1943:  *     unescaped ampersands with the lhs of the pattern.
                   1944:  *
                   1945:  * Results:
                   1946:  *     A string of all the words modified appropriately.
                   1947:  *     If length is specified, return the string length of the buffer
                   1948:  *     If flags is specified and the last character of the pattern is a
                   1949:  *     $ set the VAR_MATCH_END bit of flags.
                   1950:  *
                   1951:  * Side Effects:
                   1952:  *     None.
                   1953:  *-----------------------------------------------------------------------
                   1954:  */
                   1955: static char *
1.90      jmc      1956: VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate __unused,
1.113     christos 1957:              int errnum, const char **tstr, int delim, int *flags,
1.127     christos 1958:              int *length, VarPattern *pattern)
1.16      christos 1959: {
1.73      christos 1960:     const char *cp;
1.16      christos 1961:     Buffer buf = Buf_Init(0);
1.127     christos 1962:     int junk;
1.16      christos 1963:     if (length == NULL)
                   1964:        length = &junk;
                   1965:
                   1966: #define IS_A_MATCH(cp, delim) \
                   1967:     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
                   1968:      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
                   1969:
                   1970:     /*
                   1971:      * Skim through until the matching delimiter is found;
                   1972:      * pick up variable substitutions on the way. Also allow
                   1973:      * backslashes to quote the delimiter, $, and \, but don't
                   1974:      * touch other backslashes.
                   1975:      */
                   1976:     for (cp = *tstr; *cp && (*cp != delim); cp++) {
                   1977:        if (IS_A_MATCH(cp, delim)) {
1.99      christos 1978:            Buf_AddByte(buf, (Byte)cp[1]);
1.16      christos 1979:            cp++;
                   1980:        } else if (*cp == '$') {
                   1981:            if (cp[1] == delim) {
                   1982:                if (flags == NULL)
1.99      christos 1983:                    Buf_AddByte(buf, (Byte)*cp);
1.16      christos 1984:                else
                   1985:                    /*
                   1986:                     * Unescaped $ at end of pattern => anchor
                   1987:                     * pattern at end.
                   1988:                     */
                   1989:                    *flags |= VAR_MATCH_END;
1.40      sjg      1990:            } else {
                   1991:                if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
                   1992:                    char   *cp2;
1.127     christos 1993:                    int     len;
1.104     christos 1994:                    void   *freeIt;
1.40      sjg      1995:
                   1996:                    /*
                   1997:                     * If unescaped dollar sign not before the
                   1998:                     * delimiter, assume it's a variable
                   1999:                     * substitution and recurse.
                   2000:                     */
1.113     christos 2001:                    cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
1.99      christos 2002:                    Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1.40      sjg      2003:                    if (freeIt)
1.104     christos 2004:                        free(freeIt);
1.40      sjg      2005:                    cp += len - 1;
                   2006:                } else {
1.73      christos 2007:                    const char *cp2 = &cp[1];
1.16      christos 2008:
1.100     christos 2009:                    if (*cp2 == PROPEN || *cp2 == BROPEN) {
1.40      sjg      2010:                        /*
                   2011:                         * Find the end of this variable reference
                   2012:                         * and suck it in without further ado.
                   2013:                         * It will be interperated later.
                   2014:                         */
                   2015:                        int have = *cp2;
1.100     christos 2016:                        int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
1.40      sjg      2017:                        int depth = 1;
                   2018:
                   2019:                        for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
                   2020:                            if (cp2[-1] != '\\') {
                   2021:                                if (*cp2 == have)
                   2022:                                    ++depth;
                   2023:                                if (*cp2 == want)
                   2024:                                    --depth;
                   2025:                            }
                   2026:                        }
1.127     christos 2027:                        Buf_AddBytes(buf, cp2 - cp, (const Byte *)cp);
1.40      sjg      2028:                        cp = --cp2;
                   2029:                    } else
1.99      christos 2030:                        Buf_AddByte(buf, (Byte)*cp);
1.40      sjg      2031:                }
1.16      christos 2032:            }
                   2033:        }
                   2034:        else if (pattern && *cp == '&')
1.73      christos 2035:            Buf_AddBytes(buf, pattern->leftLen, (const Byte *)pattern->lhs);
1.16      christos 2036:        else
1.99      christos 2037:            Buf_AddByte(buf, (Byte)*cp);
1.16      christos 2038:     }
                   2039:
1.99      christos 2040:     Buf_AddByte(buf, (Byte)'\0');
1.16      christos 2041:
                   2042:     if (*cp != delim) {
                   2043:        *tstr = cp;
                   2044:        *length = 0;
                   2045:        return NULL;
                   2046:     }
                   2047:     else {
1.73      christos 2048:        char *rstr;
1.16      christos 2049:        *tstr = ++cp;
1.97      christos 2050:        rstr = (char *)Buf_GetAll(buf, length);
1.16      christos 2051:        *length -= 1;   /* Don't count the NULL */
                   2052:        Buf_Destroy(buf, FALSE);
1.73      christos 2053:        return rstr;
1.16      christos 2054:     }
                   2055: }
                   2056:
                   2057: /*-
                   2058:  *-----------------------------------------------------------------------
                   2059:  * VarQuote --
                   2060:  *     Quote shell meta-characters in the string
                   2061:  *
                   2062:  * Results:
                   2063:  *     The quoted string
                   2064:  *
                   2065:  * Side Effects:
                   2066:  *     None.
                   2067:  *
                   2068:  *-----------------------------------------------------------------------
                   2069:  */
                   2070: static char *
1.70      wiz      2071: VarQuote(char *str)
1.16      christos 2072: {
                   2073:
                   2074:     Buffer       buf;
                   2075:     /* This should cover most shells :-( */
1.132     joerg    2076:     static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1.111     rillig   2077:     const char *newline;
1.133     joerg    2078:     size_t len, nlen;
1.111     rillig   2079:
1.133     joerg    2080:     if ((newline = Shell_GetNewline()) == NULL)
                   2081:            newline = "\\\n";
                   2082:     nlen = strlen(newline);
1.16      christos 2083:
1.116     dsl      2084:     buf = Buf_Init(0);
1.133     joerg    2085:     while (*str != '\0') {
                   2086:        if ((len = strcspn(str, meta)) != 0) {
                   2087:            Buf_AddBytes(buf, len, str);
                   2088:            str += len;
                   2089:        } else if (*str == '\n') {
                   2090:            Buf_AddBytes(buf, nlen, newline);
                   2091:            ++str;
1.111     rillig   2092:        } else {
1.133     joerg    2093:            Buf_AddByte(buf, (Byte)'\\');
1.111     rillig   2094:            Buf_AddByte(buf, (Byte)*str);
1.133     joerg    2095:            ++str;
1.111     rillig   2096:        }
1.16      christos 2097:     }
1.99      christos 2098:     Buf_AddByte(buf, (Byte)'\0');
                   2099:     str = (char *)Buf_GetAll(buf, NULL);
1.92      christos 2100:     Buf_Destroy(buf, FALSE);
1.137     christos 2101:     if (DEBUG(VAR))
                   2102:        fprintf(debug_file, "QuoteMeta: [%s]\n", str);
1.16      christos 2103:     return str;
                   2104: }
                   2105:
1.68      pk       2106: /*-
                   2107:  *-----------------------------------------------------------------------
                   2108:  * VarChangeCase --
                   2109:  *      Change the string to all uppercase or all lowercase
                   2110:  *
1.70      wiz      2111:  * Input:
                   2112:  *     str             String to modify
                   2113:  *     upper           TRUE -> uppercase, else lowercase
                   2114:  *
1.68      pk       2115:  * Results:
                   2116:  *      The string with case changed
                   2117:  *
                   2118:  * Side Effects:
                   2119:  *      None.
                   2120:  *
                   2121:  *-----------------------------------------------------------------------
                   2122:  */
                   2123: static char *
1.70      wiz      2124: VarChangeCase(char *str, int upper)
1.68      pk       2125: {
                   2126:    Buffer         buf;
1.70      wiz      2127:    int            (*modProc)(int);
1.68      pk       2128:
                   2129:    modProc = (upper ? toupper : tolower);
1.116     dsl      2130:    buf = Buf_Init(0);
1.68      pk       2131:    for (; *str ; str++) {
1.99      christos 2132:        Buf_AddByte(buf, (Byte)modProc(*str));
1.68      pk       2133:    }
1.99      christos 2134:    Buf_AddByte(buf, (Byte)'\0');
                   2135:    str = (char *)Buf_GetAll(buf, NULL);
1.92      christos 2136:    Buf_Destroy(buf, FALSE);
1.68      pk       2137:    return str;
                   2138: }
1.16      christos 2139:
1.108     sjg      2140: /*
                   2141:  * Now we need to apply any modifiers the user wants applied.
                   2142:  * These are:
                   2143:  *       :M<pattern>   words which match the given <pattern>.
1.138     dsl      2144:  *                     <pattern> is of the standard file
                   2145:  *                     wildcarding form.
1.108     sjg      2146:  *       :N<pattern>   words which do not match the given <pattern>.
                   2147:  *       :S<d><pat1><d><pat2><d>[1gW]
1.138     dsl      2148:  *                     Substitute <pat2> for <pat1> in the value
1.108     sjg      2149:  *       :C<d><pat1><d><pat2><d>[1gW]
1.138     dsl      2150:  *                     Substitute <pat2> for regex <pat1> in the value
                   2151:  *       :H            Substitute the head of each word
                   2152:  *       :T            Substitute the tail of each word
                   2153:  *       :E            Substitute the extension (minus '.') of
                   2154:  *                     each word
                   2155:  *       :R            Substitute the root of each word
                   2156:  *                     (pathname minus the suffix).
                   2157:  *       :O            ("Order") Alphabeticaly sort words in variable.
                   2158:  *       :Ox           ("intermiX") Randomize words in variable.
                   2159:  *       :u            ("uniq") Remove adjacent duplicate words.
                   2160:  *       :tu           Converts the variable contents to uppercase.
                   2161:  *       :tl           Converts the variable contents to lowercase.
                   2162:  *       :ts[c]        Sets varSpace - the char used to
                   2163:  *                     separate words to 'c'. If 'c' is
                   2164:  *                     omitted then no separation is used.
                   2165:  *       :tW           Treat the variable contents as a single
                   2166:  *                     word, even if it contains spaces.
                   2167:  *                     (Mnemonic: one big 'W'ord.)
                   2168:  *       :tw           Treat the variable contents as multiple
                   2169:  *                     space-separated words.
                   2170:  *                     (Mnemonic: many small 'w'ords.)
                   2171:  *       :[index]      Select a single word from the value.
                   2172:  *       :[start..end] Select multiple words from the value.
                   2173:  *       :[*] or :[0]  Select the entire value, as a single
                   2174:  *                     word.  Equivalent to :tW.
                   2175:  *       :[@]          Select the entire value, as multiple
                   2176:  *                     words.  Undoes the effect of :[*].
                   2177:  *                     Equivalent to :tw.
                   2178:  *       :[#]          Returns the number of words in the value.
                   2179:  *
                   2180:  *       :?<true-value>:<false-value>
                   2181:  *                     If the variable evaluates to true, return
                   2182:  *                     true value, else return the second value.
                   2183:  *       :lhs=rhs      Like :S, but the rhs goes to the end of
                   2184:  *                     the invocation.
                   2185:  *       :sh           Treat the current value as a command
                   2186:  *                     to be run, new value is its output.
1.108     sjg      2187:  * The following added so we can handle ODE makefiles.
1.138     dsl      2188:  *       :@<tmpvar>@<newval>@
                   2189:  *                     Assign a temporary local variable <tmpvar>
                   2190:  *                     to the current value of each word in turn
                   2191:  *                     and replace each word with the result of
                   2192:  *                     evaluating <newval>
                   2193:  *       :D<newval>    Use <newval> as value if variable defined
                   2194:  *       :U<newval>    Use <newval> as value if variable undefined
                   2195:  *       :L            Use the name of the variable as the value.
                   2196:  *       :P            Use the path of the node that has the same
                   2197:  *                     name as the variable as the value.  This
                   2198:  *                     basically includes an implied :L so that
                   2199:  *                     the common method of refering to the path
                   2200:  *                     of your dependent 'x' in a rule is to use
                   2201:  *                     the form '${x:P}'.
                   2202:  *       :!<cmd>!      Run cmd much the same as :sh run's the
                   2203:  *                     current value of the variable.
1.108     sjg      2204:  * The ::= modifiers, actually assign a value to the variable.
                   2205:  * Their main purpose is in supporting modifiers of .for loop
                   2206:  * iterators and other obscure uses.  They always expand to
                   2207:  * nothing.  In a target rule that would otherwise expand to an
                   2208:  * empty line they can be preceded with @: to keep make happy.
                   2209:  * Eg.
                   2210:  *
                   2211:  * foo:        .USE
                   2212:  * .for i in ${.TARGET} ${.TARGET:R}.gz
1.138     dsl      2213:  *     @: ${t::=$i}
                   2214:  *     @echo blah ${t:T}
1.108     sjg      2215:  * .endfor
                   2216:  *
1.138     dsl      2217:  *       ::=<str>      Assigns <str> as the new value of variable.
                   2218:  *       ::?=<str>     Assigns <str> as value of variable if
                   2219:  *                     it was not already set.
                   2220:  *       ::+=<str>     Appends <str> to variable.
                   2221:  *       ::!=<cmd>     Assigns output of <cmd> as the new value of
                   2222:  *                     variable.
1.1       cgd      2223:  */
1.108     sjg      2224:
                   2225: static char *
                   2226: ApplyModifiers(char *nstr, const char *tstr,
                   2227:               int startc, int endc,
1.113     christos 2228:               Var *v, GNode *ctxt, Boolean errnum,
1.127     christos 2229:               int *lengthPtr, void **freePtr)
1.1       cgd      2230: {
1.108     sjg      2231:     const char            *start;
1.73      christos 2232:     const char     *cp;        /* Secondary pointer into str (place marker
1.1       cgd      2233:                                 * for tstr) */
1.123     apb      2234:     char          *newStr;     /* New value to return */
                   2235:     char           termc;      /* Character which terminated scan */
1.9       christos 2236:     int             cnt;       /* Used to count brace pairs when variable in
                   2237:                                 * in parens or braces */
1.108     sjg      2238:     char       delim;
1.112     sjg      2239:     int                modifier;       /* that we are processing */
1.89      jmc      2240:     Var_Parse_State parsestate; /* Flags passed to helper functions */
1.15      christos 2241:
1.108     sjg      2242:     delim = '\0';
1.81      sjg      2243:     parsestate.oneBigWord = FALSE;
                   2244:     parsestate.varSpace = ' '; /* word separator */
1.15      christos 2245:
1.108     sjg      2246:     start = cp = tstr;
                   2247:
                   2248:     while (*tstr && *tstr != endc) {
1.15      christos 2249:
1.108     sjg      2250:        if (*tstr == '$') {
                   2251:            /*
                   2252:             * We have some complex modifiers in a variable.
1.1       cgd      2253:             */
1.108     sjg      2254:            void *freeIt;
                   2255:            char *rval;
1.127     christos 2256:            int rlen;
1.22      christos 2257:
1.113     christos 2258:            rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
1.1       cgd      2259:
1.108     sjg      2260:            if (DEBUG(VAR)) {
1.114     dsl      2261:                fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
1.127     christos 2262:                       rval, rlen, tstr, rlen, tstr + rlen);
1.22      christos 2263:            }
1.1       cgd      2264:
1.108     sjg      2265:            tstr += rlen;
1.15      christos 2266:
1.108     sjg      2267:            if (rval != NULL && *rval) {
1.127     christos 2268:                int used;
1.15      christos 2269:
1.108     sjg      2270:                nstr = ApplyModifiers(nstr, rval,
                   2271:                                      0, 0,
1.113     christos 2272:                                      v, ctxt, errnum, &used, freePtr);
1.108     sjg      2273:                if (nstr == var_Error
1.113     christos 2274:                    || (nstr == varNoError && errnum == 0)
1.111     rillig   2275:                    || strlen(rval) != (size_t) used) {
1.108     sjg      2276:                    if (freeIt)
                   2277:                        free(freeIt);
                   2278:                    goto out;           /* error already reported */
1.1       cgd      2279:                }
                   2280:            }
1.108     sjg      2281:            if (freeIt)
                   2282:                free(freeIt);
                   2283:            if (*tstr == ':')
                   2284:                tstr++;
1.119     sjg      2285:            else if (!*tstr && endc) {
                   2286:                Error("Unclosed variable specification for %s", v->name);
                   2287:                goto out;
                   2288:            }
1.108     sjg      2289:            continue;
                   2290:        }
                   2291:        if (DEBUG(VAR)) {
1.114     dsl      2292:            fprintf(debug_file, "Applying :%c to \"%s\"\n", *tstr, nstr);
1.1       cgd      2293:        }
1.108     sjg      2294:        newStr = var_Error;
1.112     sjg      2295:        switch ((modifier = *tstr)) {
1.108     sjg      2296:        case ':':
1.1       cgd      2297:            {
1.45      sjg      2298:                if (tstr[1] == '=' ||
                   2299:                    (tstr[2] == '=' &&
                   2300:                     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
1.81      sjg      2301:                    /*
                   2302:                     * "::=", "::!=", "::+=", or "::?="
                   2303:                     */
1.44      sjg      2304:                    GNode *v_ctxt;              /* context where v belongs */
1.73      christos 2305:                    const char *emsg;
1.86      dsl      2306:                    char *sv_name;
1.44      sjg      2307:                    VarPattern  pattern;
                   2308:                    int how;
1.45      sjg      2309:
1.135     dsl      2310:                    if (v->name[0] == 0)
                   2311:                        goto bad_modifier;
                   2312:
1.95      lukem    2313:                    v_ctxt = ctxt;
                   2314:                    sv_name = NULL;
1.45      sjg      2315:                    ++tstr;
1.44      sjg      2316:                    if (v->flags & VAR_JUNK) {
                   2317:                        /*
1.134     joerg    2318:                         * We need to bmake_strdup() it incase
1.44      sjg      2319:                         * VarGetPattern() recurses.
                   2320:                         */
1.86      dsl      2321:                        sv_name = v->name;
1.134     joerg    2322:                        v->name = bmake_strdup(v->name);
1.44      sjg      2323:                    } else if (ctxt != VAR_GLOBAL) {
1.109     christos 2324:                        Var *gv = VarFind(v->name, ctxt, 0);
1.136     dsl      2325:                        if (gv == NULL)
1.44      sjg      2326:                            v_ctxt = VAR_GLOBAL;
1.109     christos 2327:                        else
                   2328:                            VarFreeEnv(gv, TRUE);
1.44      sjg      2329:                    }
                   2330:
1.45      sjg      2331:                    switch ((how = *tstr)) {
1.44      sjg      2332:                    case '+':
                   2333:                    case '?':
                   2334:                    case '!':
                   2335:                        cp = &tstr[2];
                   2336:                        break;
                   2337:                    default:
                   2338:                        cp = ++tstr;
                   2339:                        break;
                   2340:                    }
1.100     christos 2341:                    delim = BRCLOSE;
1.44      sjg      2342:                    pattern.flags = 0;
                   2343:
1.113     christos 2344:                    pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2345:                                                &cp, delim, NULL,
                   2346:                                                &pattern.rightLen,
                   2347:                                                NULL);
1.86      dsl      2348:                    if (v->flags & VAR_JUNK) {
                   2349:                        /* restore original name */
                   2350:                        free(v->name);
                   2351:                        v->name = sv_name;
                   2352:                    }
                   2353:                    if (pattern.rhs == NULL)
1.44      sjg      2354:                        goto cleanup;
1.86      dsl      2355:
1.44      sjg      2356:                    termc = *--cp;
                   2357:                    delim = '\0';
                   2358:
1.48      mycroft  2359:                    switch (how) {
                   2360:                    case '+':
                   2361:                        Var_Append(v->name, pattern.rhs, v_ctxt);
                   2362:                        break;
                   2363:                    case '!':
1.92      christos 2364:                        newStr = Cmd_Exec(pattern.rhs, &emsg);
1.48      mycroft  2365:                        if (emsg)
1.92      christos 2366:                            Error(emsg, nstr);
1.48      mycroft  2367:                        else
1.108     sjg      2368:                            Var_Set(v->name, newStr,  v_ctxt, 0);
1.48      mycroft  2369:                        if (newStr)
                   2370:                            free(newStr);
                   2371:                        break;
                   2372:                    case '?':
                   2373:                        if ((v->flags & VAR_JUNK) == 0)
1.47      sjg      2374:                            break;
1.48      mycroft  2375:                        /* FALLTHROUGH */
                   2376:                    default:
1.65      sjg      2377:                        Var_Set(v->name, pattern.rhs, v_ctxt, 0);
1.48      mycroft  2378:                        break;
1.44      sjg      2379:                    }
1.73      christos 2380:                    free(UNCONST(pattern.rhs));
1.44      sjg      2381:                    newStr = var_Error;
                   2382:                    break;
                   2383:                }
1.81      sjg      2384:                goto default_case; /* "::<unrecognised>" */
1.108     sjg      2385:            }
                   2386:        case '@':
                   2387:            {
                   2388:                VarLoop_t       loop;
                   2389:                int flags = VAR_NOSUBST;
1.40      sjg      2390:
1.108     sjg      2391:                cp = ++tstr;
                   2392:                delim = '@';
1.113     christos 2393:                if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2394:                                               &cp, delim,
                   2395:                                               &flags, &loop.tvarLen,
                   2396:                                               NULL)) == NULL)
                   2397:                    goto cleanup;
                   2398:
1.113     christos 2399:                if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2400:                                              &cp, delim,
                   2401:                                              &flags, &loop.strLen,
                   2402:                                              NULL)) == NULL)
                   2403:                    goto cleanup;
                   2404:
                   2405:                termc = *cp;
                   2406:                delim = '\0';
                   2407:
1.113     christos 2408:                loop.errnum = errnum;
1.108     sjg      2409:                loop.ctxt = ctxt;
                   2410:                newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
1.115     dsl      2411:                                   &loop);
1.108     sjg      2412:                free(loop.tvar);
                   2413:                free(loop.str);
                   2414:                break;
                   2415:            }
                   2416:        case 'D':
                   2417:        case 'U':
                   2418:            {
                   2419:                Buffer  buf;            /* Buffer for patterns */
                   2420:                int         wantit;     /* want data in buffer */
1.40      sjg      2421:
1.108     sjg      2422:                /*
                   2423:                 * Pass through tstr looking for 1) escaped delimiters,
                   2424:                 * '$'s and backslashes (place the escaped character in
                   2425:                 * uninterpreted) and 2) unescaped $'s that aren't before
                   2426:                 * the delimiter (expand the variable substitution).
                   2427:                 * The result is left in the Buffer buf.
                   2428:                 */
                   2429:                buf = Buf_Init(0);
                   2430:                for (cp = tstr + 1;
                   2431:                     *cp != endc && *cp != ':' && *cp != '\0';
                   2432:                     cp++) {
                   2433:                    if ((*cp == '\\') &&
                   2434:                        ((cp[1] == ':') ||
                   2435:                         (cp[1] == '$') ||
                   2436:                         (cp[1] == endc) ||
                   2437:                         (cp[1] == '\\')))
1.49      mycroft  2438:                        {
1.99      christos 2439:                            Buf_AddByte(buf, (Byte)cp[1]);
1.49      mycroft  2440:                            cp++;
                   2441:                        } else if (*cp == '$') {
                   2442:                            /*
                   2443:                             * If unescaped dollar sign, assume it's a
                   2444:                             * variable substitution and recurse.
                   2445:                             */
                   2446:                            char    *cp2;
1.127     christos 2447:                            int     len;
1.104     christos 2448:                            void    *freeIt;
1.49      mycroft  2449:
1.113     christos 2450:                            cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
1.99      christos 2451:                            Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1.49      mycroft  2452:                            if (freeIt)
1.104     christos 2453:                                free(freeIt);
1.49      mycroft  2454:                            cp += len - 1;
                   2455:                        } else {
1.99      christos 2456:                            Buf_AddByte(buf, (Byte)*cp);
1.49      mycroft  2457:                        }
1.108     sjg      2458:                }
                   2459:                Buf_AddByte(buf, (Byte)'\0');
1.40      sjg      2460:
1.108     sjg      2461:                termc = *cp;
1.40      sjg      2462:
1.108     sjg      2463:                if (*tstr == 'U')
                   2464:                    wantit = ((v->flags & VAR_JUNK) != 0);
                   2465:                else
                   2466:                    wantit = ((v->flags & VAR_JUNK) == 0);
                   2467:                if ((v->flags & VAR_JUNK) != 0)
                   2468:                    v->flags |= VAR_KEEP;
                   2469:                if (wantit) {
                   2470:                    newStr = (char *)Buf_GetAll(buf, NULL);
                   2471:                    Buf_Destroy(buf, FALSE);
                   2472:                } else {
                   2473:                    newStr = nstr;
                   2474:                    Buf_Destroy(buf, TRUE);
                   2475:                }
                   2476:                break;
                   2477:            }
                   2478:        case 'L':
                   2479:            {
                   2480:                if ((v->flags & VAR_JUNK) != 0)
                   2481:                    v->flags |= VAR_KEEP;
1.134     joerg    2482:                newStr = bmake_strdup(v->name);
1.108     sjg      2483:                cp = ++tstr;
                   2484:                termc = *tstr;
                   2485:                break;
                   2486:            }
                   2487:        case 'P':
                   2488:            {
                   2489:                GNode *gn;
                   2490:
                   2491:                if ((v->flags & VAR_JUNK) != 0)
                   2492:                    v->flags |= VAR_KEEP;
                   2493:                gn = Targ_FindNode(v->name, TARG_NOCREATE);
1.136     dsl      2494:                if (gn == NULL || gn->type & OP_NOPATH) {
1.108     sjg      2495:                    newStr = NULL;
                   2496:                } else if (gn->path) {
1.134     joerg    2497:                    newStr = bmake_strdup(gn->path);
1.108     sjg      2498:                } else {
                   2499:                    newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
1.40      sjg      2500:                }
1.108     sjg      2501:                if (!newStr) {
1.134     joerg    2502:                    newStr = bmake_strdup(v->name);
1.40      sjg      2503:                }
1.108     sjg      2504:                cp = ++tstr;
                   2505:                termc = *tstr;
                   2506:                break;
                   2507:            }
                   2508:        case '!':
                   2509:            {
                   2510:                const char *emsg;
                   2511:                VarPattern          pattern;
                   2512:                pattern.flags = 0;
                   2513:
                   2514:                delim = '!';
                   2515:
                   2516:                cp = ++tstr;
1.113     christos 2517:                if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2518:                                                 &cp, delim,
                   2519:                                                 NULL, &pattern.rightLen,
                   2520:                                                 NULL)) == NULL)
                   2521:                    goto cleanup;
                   2522:                newStr = Cmd_Exec(pattern.rhs, &emsg);
                   2523:                free(UNCONST(pattern.rhs));
                   2524:                if (emsg)
                   2525:                    Error(emsg, nstr);
                   2526:                termc = *cp;
                   2527:                delim = '\0';
                   2528:                if (v->flags & VAR_JUNK) {
                   2529:                    v->flags |= VAR_KEEP;
                   2530:                }
                   2531:                break;
                   2532:            }
                   2533:        case '[':
                   2534:            {
                   2535:                /*
                   2536:                 * Look for the closing ']', recursively
                   2537:                 * expanding any embedded variables.
                   2538:                 *
                   2539:                 * estr is a pointer to the expanded result,
                   2540:                 * which we must free().
                   2541:                 */
                   2542:                char *estr;
1.40      sjg      2543:
1.108     sjg      2544:                cp = tstr+1; /* point to char after '[' */
                   2545:                delim = ']'; /* look for closing ']' */
                   2546:                estr = VarGetPattern(ctxt, &parsestate,
1.113     christos 2547:                                     errnum, &cp, delim,
1.108     sjg      2548:                                     NULL, NULL, NULL);
                   2549:                if (estr == NULL)
                   2550:                    goto cleanup; /* report missing ']' */
                   2551:                /* now cp points just after the closing ']' */
                   2552:                delim = '\0';
                   2553:                if (cp[0] != ':' && cp[0] != endc) {
                   2554:                    /* Found junk after ']' */
                   2555:                    free(estr);
                   2556:                    goto bad_modifier;
                   2557:                }
                   2558:                if (estr[0] == '\0') {
                   2559:                    /* Found empty square brackets in ":[]". */
                   2560:                    free(estr);
                   2561:                    goto bad_modifier;
                   2562:                } else if (estr[0] == '#' && estr[1] == '\0') {
                   2563:                    /* Found ":[#]" */
                   2564:
                   2565:                    /*
                   2566:                     * We will need enough space for the decimal
                   2567:                     * representation of an int.  We calculate the
                   2568:                     * space needed for the octal representation,
                   2569:                     * and add enough slop to cope with a '-' sign
                   2570:                     * (which should never be needed) and a '\0'
                   2571:                     * string terminator.
                   2572:                     */
1.127     christos 2573:                    int newStrSize =
1.108     sjg      2574:                        (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
                   2575:
1.134     joerg    2576:                    newStr = bmake_malloc(newStrSize);
1.108     sjg      2577:                    if (parsestate.oneBigWord) {
1.127     christos 2578:                        strncpy(newStr, "1", newStrSize);
1.103     sjg      2579:                    } else {
1.108     sjg      2580:                        /* XXX: brk_string() is a rather expensive
                   2581:                         * way of counting words. */
                   2582:                        char **av;
                   2583:                        char *as;
1.127     christos 2584:                        int ac;
1.108     sjg      2585:
                   2586:                        av = brk_string(nstr, &ac, FALSE, &as);
1.127     christos 2587:                        snprintf(newStr, newStrSize,  "%d", ac);
1.108     sjg      2588:                        free(as);
                   2589:                        free(av);
1.103     sjg      2590:                    }
1.108     sjg      2591:                    termc = *cp;
                   2592:                    free(estr);
                   2593:                    break;
                   2594:                } else if (estr[0] == '*' && estr[1] == '\0') {
                   2595:                    /* Found ":[*]" */
                   2596:                    parsestate.oneBigWord = TRUE;
                   2597:                    newStr = nstr;
                   2598:                    termc = *cp;
                   2599:                    free(estr);
1.40      sjg      2600:                    break;
1.108     sjg      2601:                } else if (estr[0] == '@' && estr[1] == '\0') {
                   2602:                    /* Found ":[@]" */
                   2603:                    parsestate.oneBigWord = FALSE;
                   2604:                    newStr = nstr;
1.40      sjg      2605:                    termc = *cp;
1.108     sjg      2606:                    free(estr);
1.68      pk       2607:                    break;
1.108     sjg      2608:                } else {
1.81      sjg      2609:                    /*
1.108     sjg      2610:                     * We expect estr to contain a single
                   2611:                     * integer for :[N], or two integers
                   2612:                     * separated by ".." for :[start..end].
1.81      sjg      2613:                     */
1.108     sjg      2614:                    char *ep;
                   2615:
                   2616:                    VarSelectWords_t seldata = { 0, 0 };
                   2617:
                   2618:                    seldata.start = strtol(estr, &ep, 0);
                   2619:                    if (ep == estr) {
                   2620:                        /* Found junk instead of a number */
1.81      sjg      2621:                        free(estr);
                   2622:                        goto bad_modifier;
1.108     sjg      2623:                    } else if (ep[0] == '\0') {
                   2624:                        /* Found only one integer in :[N] */
                   2625:                        seldata.end = seldata.start;
                   2626:                    } else if (ep[0] == '.' && ep[1] == '.' &&
                   2627:                               ep[2] != '\0') {
                   2628:                        /* Expecting another integer after ".." */
                   2629:                        ep += 2;
                   2630:                        seldata.end = strtol(ep, &ep, 0);
                   2631:                        if (ep[0] != '\0') {
                   2632:                            /* Found junk after ".." */
                   2633:                            free(estr);
                   2634:                            goto bad_modifier;
                   2635:                        }
                   2636:                    } else {
                   2637:                        /* Found junk instead of ".." */
1.81      sjg      2638:                        free(estr);
                   2639:                        goto bad_modifier;
1.108     sjg      2640:                    }
                   2641:                    /*
                   2642:                     * Now seldata is properly filled in,
                   2643:                     * but we still have to check for 0 as
                   2644:                     * a special case.
                   2645:                     */
                   2646:                    if (seldata.start == 0 && seldata.end == 0) {
                   2647:                        /* ":[0]" or perhaps ":[0..0]" */
1.81      sjg      2648:                        parsestate.oneBigWord = TRUE;
                   2649:                        newStr = nstr;
                   2650:                        termc = *cp;
                   2651:                        free(estr);
                   2652:                        break;
1.108     sjg      2653:                    } else if (seldata.start == 0 ||
                   2654:                               seldata.end == 0) {
                   2655:                        /* ":[0..N]" or ":[N..0]" */
1.81      sjg      2656:                        free(estr);
1.108     sjg      2657:                        goto bad_modifier;
                   2658:                    }
                   2659:                    /*
                   2660:                     * Normal case: select the words
                   2661:                     * described by seldata.
                   2662:                     */
                   2663:                    newStr = VarSelectWords(ctxt, &parsestate,
                   2664:                                            nstr, &seldata);
                   2665:
                   2666:                    termc = *cp;
                   2667:                    free(estr);
                   2668:                    break;
                   2669:                }
                   2670:
                   2671:            }
                   2672:        case 't':
                   2673:            {
                   2674:                cp = tstr + 1;  /* make sure it is set */
                   2675:                if (tstr[1] != endc && tstr[1] != ':') {
                   2676:                    if (tstr[1] == 's') {
1.81      sjg      2677:                        /*
1.108     sjg      2678:                         * Use the char (if any) at tstr[2]
                   2679:                         * as the word separator.
1.81      sjg      2680:                         */
1.108     sjg      2681:                        VarPattern pattern;
1.81      sjg      2682:
1.108     sjg      2683:                        if (tstr[2] != endc &&
                   2684:                            (tstr[3] == endc || tstr[3] == ':')) {
                   2685:                            /* ":ts<unrecognised><endc>" or
                   2686:                             * ":ts<unrecognised>:" */
                   2687:                            parsestate.varSpace = tstr[2];
                   2688:                            cp = tstr + 3;
                   2689:                        } else if (tstr[2] == endc || tstr[2] == ':') {
                   2690:                            /* ":ts<endc>" or ":ts:" */
                   2691:                            parsestate.varSpace = 0; /* no separator */
                   2692:                            cp = tstr + 2;
                   2693:                        } else if (tstr[2] == '\\') {
                   2694:                            switch (tstr[3]) {
                   2695:                            case 'n':
                   2696:                                parsestate.varSpace = '\n';
                   2697:                                cp = tstr + 4;
                   2698:                                break;
                   2699:                            case 't':
                   2700:                                parsestate.varSpace = '\t';
                   2701:                                cp = tstr + 4;
                   2702:                                break;
                   2703:                            default:
                   2704:                                if (isdigit((unsigned char)tstr[3])) {
                   2705:                                    char *ep;
                   2706:
1.127     christos 2707:                                    parsestate.varSpace =
1.108     sjg      2708:                                        strtoul(&tstr[3], &ep, 0);
                   2709:                                    if (*ep != ':' && *ep != endc)
                   2710:                                        goto bad_modifier;
                   2711:                                    cp = ep;
                   2712:                                } else {
                   2713:                                    /*
                   2714:                                     * ":ts<backslash><unrecognised>".
                   2715:                                     */
                   2716:                                    goto bad_modifier;
                   2717:                                }
                   2718:                                break;
1.81      sjg      2719:                            }
                   2720:                        } else {
1.108     sjg      2721:                            /*
                   2722:                             * Found ":ts<unrecognised><unrecognised>".
                   2723:                             */
1.81      sjg      2724:                            goto bad_modifier;
                   2725:                        }
1.108     sjg      2726:
                   2727:                        termc = *cp;
                   2728:
1.81      sjg      2729:                        /*
1.108     sjg      2730:                         * We cannot be certain that VarModify
                   2731:                         * will be used - even if there is a
                   2732:                         * subsequent modifier, so do a no-op
                   2733:                         * VarSubstitute now to for str to be
                   2734:                         * re-expanded without the spaces.
1.81      sjg      2735:                         */
1.108     sjg      2736:                        pattern.flags = VAR_SUB_ONE;
                   2737:                        pattern.lhs = pattern.rhs = "\032";
                   2738:                        pattern.leftLen = pattern.rightLen = 1;
                   2739:
                   2740:                        newStr = VarModify(ctxt, &parsestate, nstr,
                   2741:                                           VarSubstitute,
1.115     dsl      2742:                                           &pattern);
1.108     sjg      2743:                    } else if (tstr[2] == endc || tstr[2] == ':') {
1.81      sjg      2744:                        /*
1.108     sjg      2745:                         * Check for two-character options:
                   2746:                         * ":tu", ":tl"
1.81      sjg      2747:                         */
1.108     sjg      2748:                        if (tstr[1] == 'u' || tstr[1] == 'l') {
                   2749:                            newStr = VarChangeCase(nstr, (tstr[1] == 'u'));
                   2750:                            cp = tstr + 2;
                   2751:                            termc = *cp;
                   2752:                        } else if (tstr[1] == 'W' || tstr[1] == 'w') {
                   2753:                            parsestate.oneBigWord = (tstr[1] == 'W');
                   2754:                            newStr = nstr;
                   2755:                            cp = tstr + 2;
1.74      sjg      2756:                            termc = *cp;
1.81      sjg      2757:                        } else {
1.108     sjg      2758:                            /* Found ":t<unrecognised>:" or
                   2759:                             * ":t<unrecognised><endc>". */
1.95      lukem    2760:                            goto bad_modifier;
1.74      sjg      2761:                        }
1.81      sjg      2762:                    } else {
                   2763:                        /*
1.108     sjg      2764:                         * Found ":t<unrecognised><unrecognised>".
1.81      sjg      2765:                         */
1.95      lukem    2766:                        goto bad_modifier;
1.40      sjg      2767:                    }
1.108     sjg      2768:                } else {
                   2769:                    /*
                   2770:                     * Found ":t<endc>" or ":t:".
                   2771:                     */
                   2772:                    goto bad_modifier;
1.40      sjg      2773:                }
1.108     sjg      2774:                break;
                   2775:            }
                   2776:        case 'N':
                   2777:        case 'M':
                   2778:            {
                   2779:                char    *pattern;
1.123     apb      2780:                const char *endpat; /* points just after end of pattern */
1.108     sjg      2781:                char    *cp2;
1.123     apb      2782:                Boolean copy;   /* pattern should be, or has been, copied */
1.108     sjg      2783:                int nest;
1.1       cgd      2784:
1.108     sjg      2785:                copy = FALSE;
                   2786:                nest = 1;
                   2787:                /*
                   2788:                 * In the loop below, ignore ':' unless we are at
                   2789:                 * (or back to) the original brace level.
                   2790:                 * XXX This will likely not work right if $() and ${}
                   2791:                 * are intermixed.
                   2792:                 */
                   2793:                for (cp = tstr + 1;
                   2794:                     *cp != '\0' && !(*cp == ':' && nest == 1);
                   2795:                     cp++)
1.1       cgd      2796:                    {
1.43      sjg      2797:                        if (*cp == '\\' &&
                   2798:                            (cp[1] == ':' ||
                   2799:                             cp[1] == endc || cp[1] == startc)) {
1.1       cgd      2800:                            copy = TRUE;
                   2801:                            cp++;
1.43      sjg      2802:                            continue;
                   2803:                        }
                   2804:                        if (*cp == startc)
                   2805:                            ++nest;
                   2806:                        if (*cp == endc) {
                   2807:                            --nest;
                   2808:                            if (nest == 0)
                   2809:                                break;
1.1       cgd      2810:                        }
                   2811:                    }
1.108     sjg      2812:                termc = *cp;
1.123     apb      2813:                endpat = cp;
1.108     sjg      2814:                if (copy) {
                   2815:                    /*
                   2816:                     * Need to compress the \:'s out of the pattern, so
                   2817:                     * allocate enough room to hold the uncompressed
                   2818:                     * pattern (note that cp started at tstr+1, so
                   2819:                     * cp - tstr takes the null byte into account) and
                   2820:                     * compress the pattern into the space.
                   2821:                     */
1.134     joerg    2822:                    pattern = bmake_malloc(cp - tstr);
1.108     sjg      2823:                    for (cp2 = pattern, cp = tstr + 1;
1.123     apb      2824:                         cp < endpat;
1.108     sjg      2825:                         cp++, cp2++)
1.1       cgd      2826:                        {
1.123     apb      2827:                            if ((*cp == '\\') && (cp+1 < endpat) &&
1.1       cgd      2828:                                (cp[1] == ':' || cp[1] == endc)) {
1.108     sjg      2829:                                cp++;
1.1       cgd      2830:                            }
                   2831:                            *cp2 = *cp;
                   2832:                        }
1.108     sjg      2833:                    *cp2 = '\0';
1.123     apb      2834:                    endpat = cp2;
1.108     sjg      2835:                } else {
1.123     apb      2836:                    /*
                   2837:                     * Either Var_Subst or VarModify will need a
                   2838:                     * nul-terminated string soon, so construct one now.
                   2839:                     */
1.134     joerg    2840:                    pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
1.123     apb      2841:                    copy = TRUE;
1.108     sjg      2842:                }
1.123     apb      2843:                if (strchr(pattern, '$') != NULL) {
                   2844:                    /*
                   2845:                     * pattern contains embedded '$', so use Var_Subst to
                   2846:                     * expand it.
                   2847:                     */
1.108     sjg      2848:                    cp2 = pattern;
1.113     christos 2849:                    pattern = Var_Subst(NULL, cp2, ctxt, errnum);
1.108     sjg      2850:                    if (copy)
                   2851:                        free(cp2);
                   2852:                    copy = TRUE;
                   2853:                }
1.137     christos 2854:                if (DEBUG(VAR))
                   2855:                    fprintf(debug_file, "Pattern for [%s] is [%s]\n", nstr,
                   2856:                        pattern);
1.108     sjg      2857:                if (*tstr == 'M' || *tstr == 'm') {
                   2858:                    newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
1.115     dsl      2859:                                       pattern);
1.108     sjg      2860:                } else {
                   2861:                    newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
1.115     dsl      2862:                                       pattern);
1.108     sjg      2863:                }
                   2864:                if (copy) {
                   2865:                    free(pattern);
                   2866:                }
                   2867:                break;
                   2868:            }
                   2869:        case 'S':
                   2870:            {
                   2871:                VarPattern          pattern;
                   2872:                Var_Parse_State tmpparsestate;
                   2873:
                   2874:                pattern.flags = 0;
                   2875:                tmpparsestate = parsestate;
                   2876:                delim = tstr[1];
                   2877:                tstr += 2;
                   2878:
                   2879:                /*
                   2880:                 * If pattern begins with '^', it is anchored to the
                   2881:                 * start of the word -- skip over it and flag pattern.
                   2882:                 */
                   2883:                if (*tstr == '^') {
                   2884:                    pattern.flags |= VAR_MATCH_START;
                   2885:                    tstr += 1;
                   2886:                }
                   2887:
                   2888:                cp = tstr;
1.113     christos 2889:                if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2890:                                                 &cp, delim,
                   2891:                                                 &pattern.flags,
                   2892:                                                 &pattern.leftLen,
                   2893:                                                 NULL)) == NULL)
                   2894:                    goto cleanup;
                   2895:
1.113     christos 2896:                if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2897:                                                 &cp, delim, NULL,
                   2898:                                                 &pattern.rightLen,
                   2899:                                                 &pattern)) == NULL)
                   2900:                    goto cleanup;
                   2901:
                   2902:                /*
                   2903:                 * Check for global substitution. If 'g' after the final
                   2904:                 * delimiter, substitution is global and is marked that
                   2905:                 * way.
                   2906:                 */
                   2907:                for (;; cp++) {
                   2908:                    switch (*cp) {
                   2909:                    case 'g':
                   2910:                        pattern.flags |= VAR_SUB_GLOBAL;
                   2911:                        continue;
                   2912:                    case '1':
                   2913:                        pattern.flags |= VAR_SUB_ONE;
                   2914:                        continue;
                   2915:                    case 'W':
                   2916:                        tmpparsestate.oneBigWord = TRUE;
                   2917:                        continue;
1.1       cgd      2918:                    }
                   2919:                    break;
                   2920:                }
                   2921:
1.108     sjg      2922:                termc = *cp;
                   2923:                newStr = VarModify(ctxt, &tmpparsestate, nstr,
                   2924:                                   VarSubstitute,
1.115     dsl      2925:                                   &pattern);
1.108     sjg      2926:
                   2927:                /*
                   2928:                 * Free the two strings.
                   2929:                 */
                   2930:                free(UNCONST(pattern.lhs));
                   2931:                free(UNCONST(pattern.rhs));
                   2932:                delim = '\0';
                   2933:                break;
                   2934:            }
                   2935:        case '?':
                   2936:            {
                   2937:                VarPattern      pattern;
                   2938:                Boolean value;
                   2939:
                   2940:                /* find ':', and then substitute accordingly */
                   2941:
                   2942:                pattern.flags = 0;
                   2943:
                   2944:                cp = ++tstr;
                   2945:                delim = ':';
1.113     christos 2946:                if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2947:                                                 &cp, delim, NULL,
                   2948:                                                 &pattern.leftLen,
                   2949:                                                 NULL)) == NULL)
                   2950:                    goto cleanup;
                   2951:
                   2952:                /* BROPEN or PROPEN */
                   2953:                delim = endc;
1.113     christos 2954:                if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
1.108     sjg      2955:                                                 &cp, delim, NULL,
                   2956:                                                 &pattern.rightLen,
                   2957:                                                 NULL)) == NULL)
                   2958:                    goto cleanup;
                   2959:
                   2960:                termc = *--cp;
                   2961:                delim = '\0';
                   2962:                if (Cond_EvalExpression(1, v->name, &value, 0)
                   2963:                    == COND_INVALID) {
                   2964:                    Error("Bad conditional expression `%s' in %s?%s:%s",
                   2965:                          v->name, v->name, pattern.lhs, pattern.rhs);
                   2966:                    goto cleanup;
                   2967:                }
                   2968:
                   2969:                if (value) {
                   2970:                    newStr = UNCONST(pattern.lhs);
                   2971:                    free(UNCONST(pattern.rhs));
                   2972:                } else {
                   2973:                    newStr = UNCONST(pattern.rhs);
                   2974:                    free(UNCONST(pattern.lhs));
                   2975:                }
                   2976:                if (v->flags & VAR_JUNK) {
                   2977:                    v->flags |= VAR_KEEP;
                   2978:                }
                   2979:                break;
                   2980:            }
                   2981: #ifndef NO_REGEX
                   2982:        case 'C':
                   2983:            {
                   2984:                VarREPattern    pattern;
                   2985:                char           *re;
                   2986:                int             error;
                   2987:                Var_Parse_State tmpparsestate;
                   2988:
                   2989:                pattern.flags = 0;
                   2990:                tmpparsestate = parsestate;
                   2991:                delim = tstr[1];
                   2992:                tstr += 2;
                   2993:
                   2994:                cp = tstr;
                   2995:
1.113     christos 2996:                if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
1.108     sjg      2997:                                        NULL, NULL, NULL)) == NULL)
                   2998:                    goto cleanup;
                   2999:
                   3000:                if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
1.113     christos 3001:                                                     errnum, &cp, delim, NULL,
1.108     sjg      3002:                                                     NULL, NULL)) == NULL){
                   3003:                    free(re);
                   3004:                    goto cleanup;
                   3005:                }
1.16      christos 3006:
1.108     sjg      3007:                for (;; cp++) {
                   3008:                    switch (*cp) {
                   3009:                    case 'g':
                   3010:                        pattern.flags |= VAR_SUB_GLOBAL;
                   3011:                        continue;
                   3012:                    case '1':
                   3013:                        pattern.flags |= VAR_SUB_ONE;
                   3014:                        continue;
                   3015:                    case 'W':
                   3016:                        tmpparsestate.oneBigWord = TRUE;
                   3017:                        continue;
1.1       cgd      3018:                    }
1.108     sjg      3019:                    break;
                   3020:                }
1.1       cgd      3021:
1.108     sjg      3022:                termc = *cp;
1.16      christos 3023:
1.108     sjg      3024:                error = regcomp(&pattern.re, re, REG_EXTENDED);
                   3025:                free(re);
                   3026:                if (error)  {
                   3027:                    *lengthPtr = cp - start + 1;
                   3028:                    VarREError(error, &pattern.re, "RE substitution error");
                   3029:                    free(pattern.replace);
                   3030:                    goto cleanup;
                   3031:                }
1.15      christos 3032:
1.108     sjg      3033:                pattern.nsub = pattern.re.re_nsub + 1;
                   3034:                if (pattern.nsub < 1)
                   3035:                    pattern.nsub = 1;
                   3036:                if (pattern.nsub > 10)
                   3037:                    pattern.nsub = 10;
1.134     joerg    3038:                pattern.matches = bmake_malloc(pattern.nsub *
1.108     sjg      3039:                                          sizeof(regmatch_t));
                   3040:                newStr = VarModify(ctxt, &tmpparsestate, nstr,
                   3041:                                   VarRESubstitute,
1.115     dsl      3042:                                   &pattern);
1.108     sjg      3043:                regfree(&pattern.re);
                   3044:                free(pattern.replace);
                   3045:                free(pattern.matches);
                   3046:                delim = '\0';
                   3047:                break;
                   3048:            }
                   3049: #endif
                   3050:        case 'Q':
                   3051:            if (tstr[1] == endc || tstr[1] == ':') {
                   3052:                newStr = VarQuote(nstr);
                   3053:                cp = tstr + 1;
                   3054:                termc = *cp;
                   3055:                break;
                   3056:            }
                   3057:            goto default_case;
                   3058:        case 'T':
                   3059:            if (tstr[1] == endc || tstr[1] == ':') {
                   3060:                newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
1.115     dsl      3061:                                   NULL);
1.108     sjg      3062:                cp = tstr + 1;
                   3063:                termc = *cp;
                   3064:                break;
                   3065:            }
                   3066:            goto default_case;
                   3067:        case 'H':
                   3068:            if (tstr[1] == endc || tstr[1] == ':') {
                   3069:                newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
1.115     dsl      3070:                                   NULL);
1.108     sjg      3071:                cp = tstr + 1;
                   3072:                termc = *cp;
                   3073:                break;
                   3074:            }
                   3075:            goto default_case;
                   3076:        case 'E':
                   3077:            if (tstr[1] == endc || tstr[1] == ':') {
                   3078:                newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
1.115     dsl      3079:                                   NULL);
1.108     sjg      3080:                cp = tstr + 1;
                   3081:                termc = *cp;
                   3082:                break;
                   3083:            }
                   3084:            goto default_case;
                   3085:        case 'R':
                   3086:            if (tstr[1] == endc || tstr[1] == ':') {
                   3087:                newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
1.115     dsl      3088:                                   NULL);
1.108     sjg      3089:                cp = tstr + 1;
                   3090:                termc = *cp;
                   3091:                break;
                   3092:            }
                   3093:            goto default_case;
                   3094:        case 'O':
                   3095:            {
                   3096:                char otype;
1.1       cgd      3097:
1.108     sjg      3098:                cp = tstr + 1;  /* skip to the rest in any case */
                   3099:                if (tstr[1] == endc || tstr[1] == ':') {
                   3100:                    otype = 's';
1.16      christos 3101:                    termc = *cp;
1.108     sjg      3102:                } else if ( (tstr[1] == 'x') &&
                   3103:                            (tstr[2] == endc || tstr[2] == ':') ) {
                   3104:                    otype = tstr[1];
                   3105:                    cp = tstr + 2;
                   3106:                    termc = *cp;
                   3107:                } else {
                   3108:                    goto bad_modifier;
                   3109:                }
                   3110:                newStr = VarOrder(nstr, otype);
                   3111:                break;
                   3112:            }
                   3113:        case 'u':
                   3114:            if (tstr[1] == endc || tstr[1] == ':') {
                   3115:                newStr = VarUniq(nstr);
                   3116:                cp = tstr + 1;
                   3117:                termc = *cp;
                   3118:                break;
                   3119:            }
                   3120:            goto default_case;
                   3121: #ifdef SUNSHCMD
                   3122:        case 's':
                   3123:            if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
                   3124:                const char *emsg;
                   3125:                newStr = Cmd_Exec(nstr, &emsg);
                   3126:                if (emsg)
                   3127:                    Error(emsg, nstr);
                   3128:                cp = tstr + 2;
                   3129:                termc = *cp;
                   3130:                break;
                   3131:            }
                   3132:            goto default_case;
                   3133: #endif
                   3134:        default:
                   3135:        default_case:
                   3136:        {
                   3137: #ifdef SYSVVARSUB
                   3138:            /*
                   3139:             * This can either be a bogus modifier or a System-V
                   3140:             * substitution command.
                   3141:             */
                   3142:            VarPattern      pattern;
                   3143:            Boolean         eqFound;
1.15      christos 3144:
1.108     sjg      3145:            pattern.flags = 0;
                   3146:            eqFound = FALSE;
                   3147:            /*
                   3148:             * First we make a pass through the string trying
                   3149:             * to verify it is a SYSV-make-style translation:
                   3150:             * it must be: <string1>=<string2>)
                   3151:             */
                   3152:            cp = tstr;
                   3153:            cnt = 1;
                   3154:            while (*cp != '\0' && cnt) {
                   3155:                if (*cp == '=') {
                   3156:                    eqFound = TRUE;
                   3157:                    /* continue looking for endc */
                   3158:                }
                   3159:                else if (*cp == endc)
                   3160:                    cnt--;
                   3161:                else if (*cp == startc)
                   3162:                    cnt++;
                   3163:                if (cnt)
                   3164:                    cp++;
                   3165:            }
                   3166:            if (*cp == endc && eqFound) {
1.25      christos 3167:
1.108     sjg      3168:                /*
                   3169:                 * Now we break this sucker into the lhs and
                   3170:                 * rhs. We must null terminate them of course.
                   3171:                 */
                   3172:                delim='=';
                   3173:                cp = tstr;
                   3174:                if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
1.113     christos 3175:                                                 errnum, &cp, delim, &pattern.flags,
1.108     sjg      3176:                                                 &pattern.leftLen, NULL)) == NULL)
                   3177:                    goto cleanup;
                   3178:                delim = endc;
                   3179:                if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
1.113     christos 3180:                                                 errnum, &cp, delim, NULL, &pattern.rightLen,
1.108     sjg      3181:                                                 &pattern)) == NULL)
                   3182:                    goto cleanup;
1.25      christos 3183:
1.108     sjg      3184:                /*
                   3185:                 * SYSV modifications happen through the whole
                   3186:                 * string. Note the pattern is anchored at the end.
                   3187:                 */
                   3188:                termc = *--cp;
                   3189:                delim = '\0';
                   3190:                newStr = VarModify(ctxt, &parsestate, nstr,
                   3191:                                   VarSYSVMatch,
1.115     dsl      3192:                                   &pattern);
1.108     sjg      3193:                free(UNCONST(pattern.lhs));
                   3194:                free(UNCONST(pattern.rhs));
                   3195:            } else
                   3196: #endif
                   3197:                {
                   3198:                    Error("Unknown modifier '%c'", *tstr);
                   3199:                    for (cp = tstr+1;
                   3200:                         *cp != ':' && *cp != endc && *cp != '\0';
                   3201:                         cp++)
                   3202:                        continue;
                   3203:                    termc = *cp;
                   3204:                    newStr = var_Error;
                   3205:                }
                   3206:            }
                   3207:        }
                   3208:        if (DEBUG(VAR)) {
1.114     dsl      3209:            fprintf(debug_file, "Result of :%c is \"%s\"\n", modifier, newStr);
1.108     sjg      3210:        }
1.25      christos 3211:
1.108     sjg      3212:        if (newStr != nstr) {
                   3213:            if (*freePtr) {
                   3214:                free(nstr);
                   3215:                *freePtr = NULL;
                   3216:            }
                   3217:            nstr = newStr;
                   3218:            if (nstr != var_Error && nstr != varNoError) {
                   3219:                *freePtr = nstr;
                   3220:            }
                   3221:        }
                   3222:        if (termc == '\0' && endc != '\0') {
                   3223:            Error("Unclosed variable specification for %s", v->name);
                   3224:        } else if (termc == ':') {
                   3225:            cp++;
                   3226:        }
                   3227:        tstr = cp;
                   3228:     }
                   3229:  out:
                   3230:     *lengthPtr = tstr - start;
                   3231:     return (nstr);
1.25      christos 3232:
1.108     sjg      3233:  bad_modifier:
                   3234:     /* "{(" */
                   3235:     Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
                   3236:          v->name);
1.25      christos 3237:
1.108     sjg      3238:  cleanup:
                   3239:     *lengthPtr = cp - start;
                   3240:     if (delim != '\0')
                   3241:        Error("Unclosed substitution for %s (%c missing)",
                   3242:              v->name, delim);
                   3243:     if (*freePtr) {
                   3244:        free(*freePtr);
                   3245:        *freePtr = NULL;
                   3246:     }
                   3247:     return (var_Error);
                   3248: }
1.25      christos 3249:
1.108     sjg      3250: /*-
                   3251:  *-----------------------------------------------------------------------
                   3252:  * Var_Parse --
                   3253:  *     Given the start of a variable invocation, extract the variable
                   3254:  *     name and find its value, then modify it according to the
                   3255:  *     specification.
                   3256:  *
                   3257:  * Input:
                   3258:  *     str             The string to parse
                   3259:  *     ctxt            The context for the variable
1.113     christos 3260:  *     errnum          TRUE if undefined variables are an error
1.108     sjg      3261:  *     lengthPtr       OUT: The length of the specification
1.121     apb      3262:  *     freePtr         OUT: Non-NULL if caller should free *freePtr
1.108     sjg      3263:  *
                   3264:  * Results:
                   3265:  *     The (possibly-modified) value of the variable or var_Error if the
                   3266:  *     specification is invalid. The length of the specification is
                   3267:  *     placed in *lengthPtr (for invalid specifications, this is just
                   3268:  *     2...?).
1.121     apb      3269:  *     If *freePtr is non-NULL then it's a pointer that the caller
                   3270:  *     should pass to free() to free memory used by the result.
1.108     sjg      3271:  *
                   3272:  * Side Effects:
                   3273:  *     None.
                   3274:  *
                   3275:  *-----------------------------------------------------------------------
                   3276:  */
                   3277: /* coverity[+alloc : arg-*4] */
                   3278: char *
1.127     christos 3279: Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
1.108     sjg      3280:          void **freePtr)
                   3281: {
                   3282:     const char    *tstr;       /* Pointer into str */
1.138     dsl      3283:     Var                   *v;          /* Variable in invocation */
1.108     sjg      3284:     Boolean        haveModifier;/* TRUE if have modifiers for the variable */
                   3285:     char           endc;       /* Ending character when variable in parens
                   3286:                                 * or braces */
                   3287:     char           startc=0;   /* Starting character when variable in parens
                   3288:                                 * or braces */
1.127     christos 3289:     int                    vlen;       /* Length of variable name */
1.123     apb      3290:     const char            *start;      /* Points to original start of str */
                   3291:     char          *nstr;       /* New string, used during expansion */
1.108     sjg      3292:     Boolean        dynamic;    /* TRUE if the variable is local and we're
                   3293:                                 * expanding it in a non-local context. This
                   3294:                                 * is done to support dynamic sources. The
                   3295:                                 * result is just the invocation, unaltered */
                   3296:     Var_Parse_State parsestate; /* Flags passed to helper functions */
1.1       cgd      3297:
1.108     sjg      3298:     *freePtr = NULL;
                   3299:     dynamic = FALSE;
                   3300:     start = str;
                   3301:     parsestate.oneBigWord = FALSE;
                   3302:     parsestate.varSpace = ' '; /* word separator */
1.1       cgd      3303:
1.108     sjg      3304:     if (str[1] != PROPEN && str[1] != BROPEN) {
                   3305:        /*
                   3306:         * If it's not bounded by braces of some sort, life is much simpler.
                   3307:         * We just need to check for the first character and return the
                   3308:         * value if it exists.
                   3309:         */
                   3310:        char      name[2];
1.15      christos 3311:
1.108     sjg      3312:        name[0] = str[1];
                   3313:        name[1] = '\0';
1.16      christos 3314:
1.108     sjg      3315:        v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1.136     dsl      3316:        if (v == NULL) {
1.108     sjg      3317:            *lengthPtr = 2;
1.1       cgd      3318:
1.108     sjg      3319:            if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
                   3320:                /*
                   3321:                 * If substituting a local variable in a non-local context,
                   3322:                 * assume it's for dynamic source stuff. We have to handle
                   3323:                 * this specially and return the longhand for the variable
                   3324:                 * with the dollar sign escaped so it makes it back to the
                   3325:                 * caller. Only four of the local variables are treated
                   3326:                 * specially as they are the only four that will be set
                   3327:                 * when dynamic sources are expanded.
                   3328:                 */
                   3329:                switch (str[1]) {
                   3330:                    case '@':
                   3331:                        return UNCONST("$(.TARGET)");
                   3332:                    case '%':
                   3333:                        return UNCONST("$(.ARCHIVE)");
                   3334:                    case '*':
                   3335:                        return UNCONST("$(.PREFIX)");
                   3336:                    case '!':
                   3337:                        return UNCONST("$(.MEMBER)");
                   3338:                }
                   3339:            }
                   3340:            /*
                   3341:             * Error
                   3342:             */
1.113     christos 3343:            return (errnum ? var_Error : varNoError);
1.108     sjg      3344:        } else {
                   3345:            haveModifier = FALSE;
                   3346:            tstr = &str[1];
                   3347:            endc = str[1];
                   3348:        }
                   3349:     } else if (str[1] == '\0') {
                   3350:        *lengthPtr = 1;
1.113     christos 3351:        return (errnum ? var_Error : varNoError);
1.123     apb      3352:     } else {
1.108     sjg      3353:        Buffer buf;     /* Holds the variable name */
1.1       cgd      3354:
1.108     sjg      3355:        startc = str[1];
                   3356:        endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
1.116     dsl      3357:        buf = Buf_Init(0);
1.1       cgd      3358:
1.108     sjg      3359:        /*
                   3360:         * Skip to the end character or a colon, whichever comes first.
                   3361:         */
                   3362:        for (tstr = str + 2;
                   3363:             *tstr != '\0' && *tstr != endc && *tstr != ':';
                   3364:             tstr++)
                   3365:        {
                   3366:            /*
                   3367:             * A variable inside a variable, expand
                   3368:             */
                   3369:            if (*tstr == '$') {
1.127     christos 3370:                int rlen;
1.108     sjg      3371:                void *freeIt;
1.113     christos 3372:                char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
1.108     sjg      3373:                if (rval != NULL) {
                   3374:                    Buf_AddBytes(buf, strlen(rval), (Byte *)rval);
1.1       cgd      3375:                }
1.108     sjg      3376:                if (freeIt)
                   3377:                    free(freeIt);
                   3378:                tstr += rlen - 1;
                   3379:            }
                   3380:            else
                   3381:                Buf_AddByte(buf, (Byte)*tstr);
                   3382:        }
                   3383:        if (*tstr == ':') {
                   3384:            haveModifier = TRUE;
                   3385:        } else if (*tstr != '\0') {
                   3386:            haveModifier = FALSE;
                   3387:        } else {
                   3388:            /*
                   3389:             * If we never did find the end character, return NULL
                   3390:             * right now, setting the length to be the distance to
                   3391:             * the end of the string, since that's what make does.
                   3392:             */
                   3393:            *lengthPtr = tstr - str;
1.110     christos 3394:            Buf_Destroy(buf, TRUE);
1.108     sjg      3395:            return (var_Error);
                   3396:        }
                   3397:        Buf_AddByte(buf, (Byte)'\0');
                   3398:        str = Buf_GetAll(buf, NULL);
                   3399:        vlen = strlen(str);
1.93      sjg      3400:
1.123     apb      3401:        /*
                   3402:         * At this point, str points into newly allocated memory from
                   3403:         * buf, containing only the name of the variable.
                   3404:         *
                   3405:         * start and tstr point into the const string that was pointed
                   3406:         * to by the original value of the str parameter.  start points
                   3407:         * to the '$' at the beginning of the string, while tstr points
                   3408:         * to the char just after the end of the variable name -- this
                   3409:         * will be '\0', ':', PRCLOSE, or BRCLOSE.
                   3410:         */
                   3411:
1.108     sjg      3412:        v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1.136     dsl      3413:        if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1.108     sjg      3414:            (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
                   3415:        {
                   3416:            /*
                   3417:             * Check for bogus D and F forms of local variables since we're
                   3418:             * in a local context and the name is the right length.
                   3419:             */
                   3420:            switch(*str) {
                   3421:                case '@':
                   3422:                case '%':
                   3423:                case '*':
                   3424:                case '!':
                   3425:                case '>':
                   3426:                case '<':
1.13      christos 3427:                {
1.108     sjg      3428:                    char    vname[2];
                   3429:                    char    *val;
1.15      christos 3430:
1.1       cgd      3431:                    /*
1.108     sjg      3432:                     * Well, it's local -- go look for it.
1.1       cgd      3433:                     */
1.108     sjg      3434:                    vname[0] = *str;
                   3435:                    vname[1] = '\0';
                   3436:                    v = VarFind(vname, ctxt, 0);
1.15      christos 3437:
1.136     dsl      3438:                    if (v != NULL) {
1.1       cgd      3439:                        /*
1.108     sjg      3440:                         * No need for nested expansion or anything, as we're
                   3441:                         * the only one who sets these things and we sure don't
                   3442:                         * but nested invocations in them...
1.1       cgd      3443:                         */
1.108     sjg      3444:                        val = (char *)Buf_GetAll(v->val, NULL);
1.15      christos 3445:
1.108     sjg      3446:                        if (str[1] == 'D') {
                   3447:                            val = VarModify(ctxt, &parsestate, val, VarHead,
1.115     dsl      3448:                                            NULL);
1.108     sjg      3449:                        } else {
                   3450:                            val = VarModify(ctxt, &parsestate, val, VarTail,
1.115     dsl      3451:                                            NULL);
1.108     sjg      3452:                        }
1.1       cgd      3453:                        /*
1.108     sjg      3454:                         * Resulting string is dynamically allocated, so
                   3455:                         * tell caller to free it.
1.1       cgd      3456:                         */
1.108     sjg      3457:                        *freePtr = val;
                   3458:                        *lengthPtr = tstr-start+1;
                   3459:                        Buf_Destroy(buf, TRUE);
                   3460:                        VarFreeEnv(v, TRUE);
                   3461:                        return(val);
1.1       cgd      3462:                    }
1.108     sjg      3463:                    break;
1.1       cgd      3464:                }
                   3465:            }
1.108     sjg      3466:        }
                   3467:
1.136     dsl      3468:        if (v == NULL) {
1.108     sjg      3469:            if (((vlen == 1) ||
                   3470:                 (((vlen == 2) && (str[1] == 'F' ||
                   3471:                                         str[1] == 'D')))) &&
                   3472:                ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
                   3473:            {
                   3474:                /*
                   3475:                 * If substituting a local variable in a non-local context,
                   3476:                 * assume it's for dynamic source stuff. We have to handle
                   3477:                 * this specially and return the longhand for the variable
                   3478:                 * with the dollar sign escaped so it makes it back to the
                   3479:                 * caller. Only four of the local variables are treated
                   3480:                 * specially as they are the only four that will be set
                   3481:                 * when dynamic sources are expanded.
                   3482:                 */
                   3483:                switch (*str) {
                   3484:                    case '@':
                   3485:                    case '%':
                   3486:                    case '*':
                   3487:                    case '!':
                   3488:                        dynamic = TRUE;
                   3489:                        break;
                   3490:                }
                   3491:            } else if ((vlen > 2) && (*str == '.') &&
                   3492:                       isupper((unsigned char) str[1]) &&
                   3493:                       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
                   3494:            {
1.127     christos 3495:                int     len;
1.108     sjg      3496:
                   3497:                len = vlen - 1;
                   3498:                if ((strncmp(str, ".TARGET", len) == 0) ||
                   3499:                    (strncmp(str, ".ARCHIVE", len) == 0) ||
                   3500:                    (strncmp(str, ".PREFIX", len) == 0) ||
                   3501:                    (strncmp(str, ".MEMBER", len) == 0))
                   3502:                {
                   3503:                    dynamic = TRUE;
                   3504:                }
1.1       cgd      3505:            }
1.15      christos 3506:
1.108     sjg      3507:            if (!haveModifier) {
                   3508:                /*
                   3509:                 * No modifiers -- have specification length so we can return
                   3510:                 * now.
                   3511:                 */
                   3512:                *lengthPtr = tstr - start + 1;
                   3513:                if (dynamic) {
1.134     joerg    3514:                    char *pstr = bmake_strndup(start, *lengthPtr);
1.108     sjg      3515:                    *freePtr = pstr;
                   3516:                    Buf_Destroy(buf, TRUE);
                   3517:                    return(pstr);
1.40      sjg      3518:                } else {
1.108     sjg      3519:                    Buf_Destroy(buf, TRUE);
1.113     christos 3520:                    return (errnum ? var_Error : varNoError);
1.40      sjg      3521:                }
1.1       cgd      3522:            } else {
1.108     sjg      3523:                /*
                   3524:                 * Still need to get to the end of the variable specification,
                   3525:                 * so kludge up a Var structure for the modifications
                   3526:                 */
1.134     joerg    3527:                v = bmake_malloc(sizeof(Var));
1.108     sjg      3528:                v->name = UNCONST(str);
                   3529:                v->val = Buf_Init(1);
                   3530:                v->flags = VAR_JUNK;
                   3531:                Buf_Destroy(buf, FALSE);
1.1       cgd      3532:            }
1.108     sjg      3533:        } else
                   3534:            Buf_Destroy(buf, TRUE);
                   3535:     }
                   3536:
                   3537:     if (v->flags & VAR_IN_USE) {
                   3538:        Fatal("Variable %s is recursive.", v->name);
                   3539:        /*NOTREACHED*/
                   3540:     } else {
                   3541:        v->flags |= VAR_IN_USE;
                   3542:     }
                   3543:     /*
                   3544:      * Before doing any modification, we have to make sure the value
                   3545:      * has been fully expanded. If it looks like recursion might be
                   3546:      * necessary (there's a dollar sign somewhere in the variable's value)
                   3547:      * we just call Var_Subst to do any other substitutions that are
                   3548:      * necessary. Note that the value returned by Var_Subst will have
                   3549:      * been dynamically-allocated, so it will need freeing when we
                   3550:      * return.
                   3551:      */
                   3552:     nstr = (char *)Buf_GetAll(v->val, NULL);
                   3553:     if (strchr(nstr, '$') != NULL) {
1.113     christos 3554:        nstr = Var_Subst(NULL, nstr, ctxt, errnum);
1.108     sjg      3555:        *freePtr = nstr;
                   3556:     }
                   3557:
                   3558:     v->flags &= ~VAR_IN_USE;
                   3559:
                   3560:     if ((nstr != NULL) && haveModifier) {
1.127     christos 3561:        int used;
1.108     sjg      3562:        /*
1.123     apb      3563:         * Skip initial colon.
1.108     sjg      3564:         */
                   3565:        tstr++;
                   3566:
                   3567:        nstr = ApplyModifiers(nstr, tstr, startc, endc,
1.113     christos 3568:                              v, ctxt, errnum, &used, freePtr);
1.108     sjg      3569:        tstr += used;
1.119     sjg      3570:     }
                   3571:     if (*tstr) {
1.1       cgd      3572:        *lengthPtr = tstr - start + 1;
                   3573:     } else {
1.119     sjg      3574:        *lengthPtr = tstr - start;
1.1       cgd      3575:     }
1.15      christos 3576:
1.1       cgd      3577:     if (v->flags & VAR_FROM_ENV) {
                   3578:        Boolean   destroy = FALSE;
1.15      christos 3579:
1.99      christos 3580:        if (nstr != (char *)Buf_GetAll(v->val, NULL)) {
1.1       cgd      3581:            destroy = TRUE;
                   3582:        } else {
                   3583:            /*
                   3584:             * Returning the value unmodified, so tell the caller to free
                   3585:             * the thing.
                   3586:             */
1.104     christos 3587:            *freePtr = nstr;
1.1       cgd      3588:        }
1.105     christos 3589:        VarFreeEnv(v, destroy);
1.1       cgd      3590:     } else if (v->flags & VAR_JUNK) {
                   3591:        /*
1.121     apb      3592:         * Perform any free'ing needed and set *freePtr to NULL so the caller
1.1       cgd      3593:         * doesn't try to free a static pointer.
1.40      sjg      3594:         * If VAR_KEEP is also set then we want to keep str as is.
1.1       cgd      3595:         */
1.58      itojun   3596:        if (!(v->flags & VAR_KEEP)) {
1.40      sjg      3597:            if (*freePtr) {
1.73      christos 3598:                free(nstr);
1.108     sjg      3599:                *freePtr = NULL;
1.40      sjg      3600:            }
                   3601:            if (dynamic) {
1.134     joerg    3602:                nstr = bmake_strndup(start, *lengthPtr);
1.104     christos 3603:                *freePtr = nstr;
1.40      sjg      3604:            } else {
1.73      christos 3605:                nstr = var_Error;
1.40      sjg      3606:            }
1.34      christos 3607:        }
1.99      christos 3608:        if (nstr != (char *)Buf_GetAll(v->val, NULL))
1.58      itojun   3609:            Buf_Destroy(v->val, TRUE);
1.98      christos 3610:        free(v->name);
                   3611:        free(v);
1.1       cgd      3612:     }
1.73      christos 3613:     return (nstr);
1.1       cgd      3614: }
                   3615:
                   3616: /*-
                   3617:  *-----------------------------------------------------------------------
                   3618:  * Var_Subst  --
                   3619:  *     Substitute for all variables in the given string in the given context
                   3620:  *     If undefErr is TRUE, Parse_Error will be called when an undefined
                   3621:  *     variable is encountered.
                   3622:  *
1.70      wiz      3623:  * Input:
                   3624:  *     var             Named variable || NULL for all
                   3625:  *     str             the string which to substitute
                   3626:  *     ctxt            the context wherein to find variables
                   3627:  *     undefErr        TRUE if undefineds are an error
                   3628:  *
1.1       cgd      3629:  * Results:
                   3630:  *     The resulting string.
                   3631:  *
                   3632:  * Side Effects:
                   3633:  *     None. The old string must be freed by the caller
                   3634:  *-----------------------------------------------------------------------
                   3635:  */
                   3636: char *
1.73      christos 3637: Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1.1       cgd      3638: {
1.138     dsl      3639:     Buffer       buf;              /* Buffer for forming things */
1.1       cgd      3640:     char         *val;             /* Value to substitute for a variable */
1.138     dsl      3641:     int                  length;           /* Length of the variable invocation */
1.96      christos 3642:     Boolean      trailingBslash;   /* variable ends in \ */
1.104     christos 3643:     void         *freeIt = NULL;    /* Set if it should be freed */
1.1       cgd      3644:     static Boolean errorReported;   /* Set true if an error has already
                   3645:                                     * been reported to prevent a plethora
                   3646:                                     * of messages when recursing */
                   3647:
1.116     dsl      3648:     buf = Buf_Init(0);
1.1       cgd      3649:     errorReported = FALSE;
1.96      christos 3650:     trailingBslash = FALSE;
1.1       cgd      3651:
                   3652:     while (*str) {
1.96      christos 3653:        if (*str == '\n' && trailingBslash)
                   3654:            Buf_AddByte(buf, ' ');
1.48      mycroft  3655:        if (var == NULL && (*str == '$') && (str[1] == '$')) {
1.1       cgd      3656:            /*
                   3657:             * A dollar sign may be escaped either with another dollar sign.
                   3658:             * In such a case, we skip over the escape character and store the
                   3659:             * dollar sign into the buffer directly.
                   3660:             */
                   3661:            str++;
                   3662:            Buf_AddByte(buf, (Byte)*str);
                   3663:            str++;
                   3664:        } else if (*str != '$') {
                   3665:            /*
                   3666:             * Skip as many characters as possible -- either to the end of
                   3667:             * the string or to the next dollar sign (variable invocation).
                   3668:             */
1.73      christos 3669:            const char  *cp;
1.1       cgd      3670:
1.5       cgd      3671:            for (cp = str++; *str != '$' && *str != '\0'; str++)
                   3672:                continue;
1.127     christos 3673:            Buf_AddBytes(buf, str - cp, (const Byte *)cp);
1.1       cgd      3674:        } else {
1.48      mycroft  3675:            if (var != NULL) {
                   3676:                int expand;
                   3677:                for (;;) {
1.100     christos 3678:                    if (str[1] == '\0') {
                   3679:                        /* A trailing $ is kind of a special case */
                   3680:                        Buf_AddByte(buf, str[0]);
                   3681:                        str++;
                   3682:                        expand = FALSE;
                   3683:                    } else if (str[1] != PROPEN && str[1] != BROPEN) {
1.48      mycroft  3684:                        if (str[1] != *var || strlen(var) > 1) {
1.73      christos 3685:                            Buf_AddBytes(buf, 2, (const Byte *)str);
1.48      mycroft  3686:                            str += 2;
                   3687:                            expand = FALSE;
                   3688:                        }
                   3689:                        else
                   3690:                            expand = TRUE;
                   3691:                        break;
                   3692:                    }
                   3693:                    else {
1.73      christos 3694:                        const char *p;
1.48      mycroft  3695:
                   3696:                        /*
                   3697:                         * Scan up to the end of the variable name.
                   3698:                         */
                   3699:                        for (p = &str[2]; *p &&
1.100     christos 3700:                             *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
1.48      mycroft  3701:                            if (*p == '$')
                   3702:                                break;
                   3703:                        /*
                   3704:                         * A variable inside the variable. We cannot expand
                   3705:                         * the external variable yet, so we try again with
                   3706:                         * the nested one
                   3707:                         */
                   3708:                        if (*p == '$') {
1.127     christos 3709:                            Buf_AddBytes(buf, p - str, (const Byte *)str);
1.48      mycroft  3710:                            str = p;
                   3711:                            continue;
                   3712:                        }
                   3713:
1.127     christos 3714:                        if (strncmp(var, str + 2, p - str - 2) != 0 ||
1.48      mycroft  3715:                            var[p - str - 2] != '\0') {
                   3716:                            /*
                   3717:                             * Not the variable we want to expand, scan
                   3718:                             * until the next variable
                   3719:                             */
                   3720:                            for (;*p != '$' && *p != '\0'; p++)
                   3721:                                continue;
1.127     christos 3722:                            Buf_AddBytes(buf, p - str, (const Byte *)str);
1.48      mycroft  3723:                            str = p;
                   3724:                            expand = FALSE;
                   3725:                        }
                   3726:                        else
                   3727:                            expand = TRUE;
                   3728:                        break;
                   3729:                    }
                   3730:                }
                   3731:                if (!expand)
                   3732:                    continue;
                   3733:            }
                   3734:
1.104     christos 3735:            val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
1.1       cgd      3736:
                   3737:            /*
                   3738:             * When we come down here, val should either point to the
                   3739:             * value of this variable, suitably modified, or be NULL.
                   3740:             * Length should be the total length of the potential
                   3741:             * variable invocation (from $ to end character...)
                   3742:             */
                   3743:            if (val == var_Error || val == varNoError) {
                   3744:                /*
                   3745:                 * If performing old-time variable substitution, skip over
                   3746:                 * the variable and continue with the substitution. Otherwise,
                   3747:                 * store the dollar sign and advance str so we continue with
                   3748:                 * the string...
                   3749:                 */
                   3750:                if (oldVars) {
                   3751:                    str += length;
                   3752:                } else if (undefErr) {
                   3753:                    /*
                   3754:                     * If variable is undefined, complain and skip the
                   3755:                     * variable. The complaint will stop us from doing anything
                   3756:                     * when the file is parsed.
                   3757:                     */
                   3758:                    if (!errorReported) {
1.92      christos 3759:                        Parse_Error(PARSE_FATAL,
1.127     christos 3760:                                     "Undefined variable \"%.*s\"",length,str);
1.1       cgd      3761:                    }
                   3762:                    str += length;
                   3763:                    errorReported = TRUE;
                   3764:                } else {
1.97      christos 3765:                    Buf_AddByte(buf, (Byte)*str);
1.1       cgd      3766:                    str += 1;
                   3767:                }
                   3768:            } else {
                   3769:                /*
                   3770:                 * We've now got a variable structure to store in. But first,
                   3771:                 * advance the string pointer.
                   3772:                 */
                   3773:                str += length;
1.15      christos 3774:
1.1       cgd      3775:                /*
                   3776:                 * Copy all the characters from the variable value straight
                   3777:                 * into the new string.
                   3778:                 */
1.96      christos 3779:                length = strlen(val);
                   3780:                Buf_AddBytes(buf, length, (Byte *)val);
                   3781:                trailingBslash = length > 0 && val[length - 1] == '\\';
1.104     christos 3782:            }
                   3783:            if (freeIt) {
                   3784:                free(freeIt);
                   3785:                freeIt = NULL;
1.1       cgd      3786:            }
                   3787:        }
                   3788:     }
1.15      christos 3789:
1.97      christos 3790:     Buf_AddByte(buf, '\0');
1.99      christos 3791:     val = (char *)Buf_GetAll(buf, NULL);
1.92      christos 3792:     Buf_Destroy(buf, FALSE);
1.73      christos 3793:     return (val);
1.1       cgd      3794: }
                   3795:
                   3796: /*-
                   3797:  *-----------------------------------------------------------------------
                   3798:  * Var_GetTail --
                   3799:  *     Return the tail from each of a list of words. Used to set the
                   3800:  *     System V local variables.
                   3801:  *
1.70      wiz      3802:  * Input:
                   3803:  *     file            Filename to modify
                   3804:  *
1.1       cgd      3805:  * Results:
                   3806:  *     The resulting string.
                   3807:  *
                   3808:  * Side Effects:
                   3809:  *     None.
                   3810:  *
                   3811:  *-----------------------------------------------------------------------
                   3812:  */
1.61      explorer 3813: #if 0
1.1       cgd      3814: char *
1.70      wiz      3815: Var_GetTail(char *file)
1.1       cgd      3816: {
1.115     dsl      3817:     return(VarModify(file, VarTail, NULL));
1.1       cgd      3818: }
                   3819:
                   3820: /*-
                   3821:  *-----------------------------------------------------------------------
                   3822:  * Var_GetHead --
                   3823:  *     Find the leading components of a (list of) filename(s).
                   3824:  *     XXX: VarHead does not replace foo by ., as (sun) System V make
                   3825:  *     does.
                   3826:  *
1.70      wiz      3827:  * Input:
                   3828:  *     file            Filename to manipulate
                   3829:  *
1.1       cgd      3830:  * Results:
                   3831:  *     The leading components.
                   3832:  *
                   3833:  * Side Effects:
                   3834:  *     None.
                   3835:  *
                   3836:  *-----------------------------------------------------------------------
                   3837:  */
                   3838: char *
1.70      wiz      3839: Var_GetHead(char *file)
1.1       cgd      3840: {
1.115     dsl      3841:     return(VarModify(file, VarHead, NULL));
1.1       cgd      3842: }
1.61      explorer 3843: #endif
1.1       cgd      3844:
                   3845: /*-
                   3846:  *-----------------------------------------------------------------------
                   3847:  * Var_Init --
                   3848:  *     Initialize the module
                   3849:  *
                   3850:  * Results:
                   3851:  *     None
                   3852:  *
                   3853:  * Side Effects:
1.15      christos 3854:  *     The VAR_CMD and VAR_GLOBAL contexts are created
1.1       cgd      3855:  *-----------------------------------------------------------------------
                   3856:  */
                   3857: void
1.70      wiz      3858: Var_Init(void)
1.1       cgd      3859: {
1.92      christos 3860:     VAR_GLOBAL = Targ_NewGN("Global");
                   3861:     VAR_CMD = Targ_NewGN("Command");
1.6       jtc      3862:
                   3863: }
                   3864:
1.1       cgd      3865:
1.6       jtc      3866: void
1.70      wiz      3867: Var_End(void)
1.6       jtc      3868: {
1.1       cgd      3869: }
1.15      christos 3870:
1.1       cgd      3871:
                   3872: /****************** PRINT DEBUGGING INFO *****************/
1.36      mycroft  3873: static void
1.70      wiz      3874: VarPrintVar(ClientData vp)
1.1       cgd      3875: {
1.99      christos 3876:     Var    *v = (Var *)vp;
1.114     dsl      3877:     fprintf(debug_file, "%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, NULL));
1.1       cgd      3878: }
                   3879:
                   3880: /*-
                   3881:  *-----------------------------------------------------------------------
                   3882:  * Var_Dump --
                   3883:  *     print all variables in a context
                   3884:  *-----------------------------------------------------------------------
                   3885:  */
1.5       cgd      3886: void
1.70      wiz      3887: Var_Dump(GNode *ctxt)
1.1       cgd      3888: {
1.36      mycroft  3889:     Hash_Search search;
                   3890:     Hash_Entry *h;
                   3891:
                   3892:     for (h = Hash_EnumFirst(&ctxt->context, &search);
                   3893:         h != NULL;
                   3894:         h = Hash_EnumNext(&search)) {
                   3895:            VarPrintVar(Hash_GetValue(h));
                   3896:     }
1.1       cgd      3897: }

CVSweb <webmaster@jp.NetBSD.org>