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

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

1.4     ! briggs      1: /*     $OpenBSD: var.c,v 1.3 1996/06/26 05:36:39 deraadt Exp $ */
        !             2: /*     $NetBSD: var.c,v 1.14 1996/08/13 16:42:25 christos Exp $        */
1.1       deraadt     3:
                      4: /*
                      5:  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
                      6:  * Copyright (c) 1988, 1989 by Adam de Boor
                      7:  * Copyright (c) 1989 by Berkeley Softworks
                      8:  * All rights reserved.
                      9:  *
                     10:  * This code is derived from software contributed to Berkeley by
                     11:  * Adam de Boor.
                     12:  *
                     13:  * Redistribution and use in source and binary forms, with or without
                     14:  * modification, are permitted provided that the following conditions
                     15:  * are met:
                     16:  * 1. Redistributions of source code must retain the above copyright
                     17:  *    notice, this list of conditions and the following disclaimer.
                     18:  * 2. Redistributions in binary form must reproduce the above copyright
                     19:  *    notice, this list of conditions and the following disclaimer in the
                     20:  *    documentation and/or other materials provided with the distribution.
                     21:  * 3. All advertising materials mentioning features or use of this software
                     22:  *    must display the following acknowledgement:
                     23:  *     This product includes software developed by the University of
                     24:  *     California, Berkeley and its contributors.
                     25:  * 4. Neither the name of the University nor the names of its contributors
                     26:  *    may be used to endorse or promote products derived from this software
                     27:  *    without specific prior written permission.
                     28:  *
                     29:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     30:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     31:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     32:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     33:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     34:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     35:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     36:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     37:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     38:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     39:  * SUCH DAMAGE.
                     40:  */
                     41:
                     42: #ifndef lint
                     43: #if 0
                     44: static char sccsid[] = "@(#)var.c      5.7 (Berkeley) 6/1/90";
                     45: #else
1.4     ! briggs     46: static char rcsid[] = "$OpenBSD: var.c,v 1.3 1996/06/26 05:36:39 deraadt Exp $";
1.1       deraadt    47: #endif
                     48: #endif /* not lint */
                     49:
                     50: /*-
                     51:  * var.c --
                     52:  *     Variable-handling functions
                     53:  *
                     54:  * Interface:
                     55:  *     Var_Set             Set the value of a variable in the given
                     56:  *                         context. The variable is created if it doesn't
                     57:  *                         yet exist. The value and variable name need not
                     58:  *                         be preserved.
                     59:  *
                     60:  *     Var_Append          Append more characters to an existing variable
                     61:  *                         in the given context. The variable needn't
                     62:  *                         exist already -- it will be created if it doesn't.
                     63:  *                         A space is placed between the old value and the
                     64:  *                         new one.
                     65:  *
                     66:  *     Var_Exists          See if a variable exists.
                     67:  *
                     68:  *     Var_Value           Return the value of a variable in a context or
                     69:  *                         NULL if the variable is undefined.
                     70:  *
                     71:  *     Var_Subst           Substitute named variable, or all variables if
                     72:  *                         NULL in a string using
                     73:  *                         the given context as the top-most one. If the
                     74:  *                         third argument is non-zero, Parse_Error is
                     75:  *                         called if any variables are undefined.
                     76:  *
                     77:  *     Var_Parse           Parse a variable expansion from a string and
                     78:  *                         return the result and the number of characters
                     79:  *                         consumed.
                     80:  *
                     81:  *     Var_Delete          Delete a variable in a context.
                     82:  *
                     83:  *     Var_Init            Initialize this module.
                     84:  *
                     85:  * Debugging:
                     86:  *     Var_Dump            Print out all variables defined in the given
                     87:  *                         context.
                     88:  *
                     89:  * XXX: There's a lot of duplication in these functions.
                     90:  */
                     91:
                     92: #include    <ctype.h>
                     93: #include    "make.h"
                     94: #include    "buf.h"
                     95:
                     96: /*
                     97:  * This is a harmless return value for Var_Parse that can be used by Var_Subst
                     98:  * to determine if there was an error in parsing -- easier than returning
                     99:  * a flag, as things outside this module don't give a hoot.
                    100:  */
                    101: char   var_Error[] = "";
                    102:
                    103: /*
                    104:  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
                    105:  * set false. Why not just use a constant? Well, gcc likes to condense
                    106:  * identical string instances...
                    107:  */
                    108: static char    varNoError[] = "";
                    109:
                    110: /*
                    111:  * Internally, variables are contained in four different contexts.
                    112:  *     1) the environment. They may not be changed. If an environment
                    113:  *         variable is appended-to, the result is placed in the global
                    114:  *         context.
                    115:  *     2) the global context. Variables set in the Makefile are located in
                    116:  *         the global context. It is the penultimate context searched when
                    117:  *         substituting.
                    118:  *     3) the command-line context. All variables set on the command line
                    119:  *        are placed in this context. They are UNALTERABLE once placed here.
                    120:  *     4) the local context. Each target has associated with it a context
                    121:  *        list. On this list are located the structures describing such
                    122:  *        local variables as $(@) and $(*)
                    123:  * The four contexts are searched in the reverse order from which they are
                    124:  * listed.
                    125:  */
                    126: GNode          *VAR_GLOBAL;   /* variables from the makefile */
                    127: GNode          *VAR_CMD;      /* variables defined on the command-line */
                    128:
                    129: static Lst     allVars;      /* List of all variables */
                    130:
                    131: #define FIND_CMD       0x1   /* look in VAR_CMD when searching */
                    132: #define FIND_GLOBAL    0x2   /* look in VAR_GLOBAL as well */
                    133: #define FIND_ENV       0x4   /* look in the environment also */
                    134:
                    135: typedef struct Var {
                    136:     char          *name;       /* the variable's name */
                    137:     Buffer       val;          /* its value */
                    138:     int                  flags;        /* miscellaneous status flags */
                    139: #define VAR_IN_USE     1           /* Variable's value currently being used.
                    140:                                     * Used to avoid recursion */
                    141: #define VAR_FROM_ENV   2           /* Variable comes from the environment */
                    142: #define VAR_JUNK       4           /* Variable is a junk variable that
                    143:                                     * should be destroyed when done with
                    144:                                     * it. Used by Var_Parse for undefined,
                    145:                                     * modified variables */
                    146: }  Var;
                    147:
                    148: typedef struct {
                    149:     char         *lhs;     /* String to match */
                    150:     int                  leftLen;  /* Length of string */
                    151:     char         *rhs;     /* Replacement string (w/ &'s removed) */
                    152:     int                  rightLen; /* Length of replacement */
                    153:     int                  flags;
                    154: #define VAR_SUB_GLOBAL 1   /* Apply substitution globally */
                    155: #define VAR_MATCH_START        2   /* Match at start of word */
                    156: #define VAR_MATCH_END  4   /* Match at end of word */
                    157: #define VAR_NO_SUB     8   /* Substitution is non-global and already done */
                    158: } VarPattern;
                    159:
                    160: static int VarCmp __P((ClientData, ClientData));
                    161: static Var *VarFind __P((char *, GNode *, int));
                    162: static void VarAdd __P((char *, char *, GNode *));
                    163: static void VarDelete __P((ClientData));
                    164: static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
                    165: static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
                    166: static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
                    167: static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
                    168: static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
1.4     ! briggs    169: #ifdef SYSVVARSUB
1.1       deraadt   170: static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
1.4     ! briggs    171: #endif
1.1       deraadt   172: static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
                    173: static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
                    174: static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
                    175:                                                ClientData),
                    176:                            ClientData));
                    177: static int VarPrintVar __P((ClientData, ClientData));
                    178:
                    179: /*-
                    180:  *-----------------------------------------------------------------------
                    181:  * VarCmp  --
                    182:  *     See if the given variable matches the named one. Called from
                    183:  *     Lst_Find when searching for a variable of a given name.
                    184:  *
                    185:  * Results:
                    186:  *     0 if they match. non-zero otherwise.
                    187:  *
                    188:  * Side Effects:
                    189:  *     none
                    190:  *-----------------------------------------------------------------------
                    191:  */
                    192: static int
                    193: VarCmp (v, name)
                    194:     ClientData     v;          /* VAR structure to compare */
                    195:     ClientData     name;       /* name to look for */
                    196: {
                    197:     return (strcmp ((char *) name, ((Var *) v)->name));
                    198: }
                    199:
                    200: /*-
                    201:  *-----------------------------------------------------------------------
                    202:  * VarFind --
                    203:  *     Find the given variable in the given context and any other contexts
                    204:  *     indicated.
                    205:  *
                    206:  * Results:
                    207:  *     A pointer to the structure describing the desired variable or
                    208:  *     NIL if the variable does not exist.
                    209:  *
                    210:  * Side Effects:
                    211:  *     None
                    212:  *-----------------------------------------------------------------------
                    213:  */
                    214: static Var *
                    215: VarFind (name, ctxt, flags)
                    216:     char               *name;  /* name to find */
                    217:     GNode              *ctxt;  /* context in which to find it */
                    218:     int                flags;  /* FIND_GLOBAL set means to look in the
                    219:                                 * VAR_GLOBAL context as well.
                    220:                                 * FIND_CMD set means to look in the VAR_CMD
                    221:                                 * context also.
                    222:                                 * FIND_ENV set means to look in the
                    223:                                 * environment */
                    224: {
                    225:     LstNode            var;
                    226:     Var                        *v;
                    227:
                    228:        /*
                    229:         * If the variable name begins with a '.', it could very well be one of
                    230:         * the local ones.  We check the name against all the local variables
                    231:         * and substitute the short version in for 'name' if it matches one of
                    232:         * them.
                    233:         */
                    234:        if (*name == '.' && isupper((unsigned char) name[1]))
                    235:                switch (name[1]) {
                    236:                case 'A':
                    237:                        if (!strcmp(name, ".ALLSRC"))
                    238:                                name = ALLSRC;
                    239:                        if (!strcmp(name, ".ARCHIVE"))
                    240:                                name = ARCHIVE;
                    241:                        break;
                    242:                case 'I':
                    243:                        if (!strcmp(name, ".IMPSRC"))
                    244:                                name = IMPSRC;
                    245:                        break;
                    246:                case 'M':
                    247:                        if (!strcmp(name, ".MEMBER"))
                    248:                                name = MEMBER;
                    249:                        break;
                    250:                case 'O':
                    251:                        if (!strcmp(name, ".OODATE"))
                    252:                                name = OODATE;
                    253:                        break;
                    254:                case 'P':
                    255:                        if (!strcmp(name, ".PREFIX"))
                    256:                                name = PREFIX;
                    257:                        break;
                    258:                case 'T':
                    259:                        if (!strcmp(name, ".TARGET"))
                    260:                                name = TARGET;
                    261:                        break;
                    262:                }
                    263:     /*
                    264:      * First look for the variable in the given context. If it's not there,
                    265:      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
                    266:      * depending on the FIND_* flags in 'flags'
                    267:      */
                    268:     var = Lst_Find (ctxt->context, (ClientData)name, VarCmp);
                    269:
                    270:     if ((var == NILLNODE) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
                    271:        var = Lst_Find (VAR_CMD->context, (ClientData)name, VarCmp);
                    272:     }
                    273:     if (!checkEnvFirst && (var == NILLNODE) && (flags & FIND_GLOBAL) &&
                    274:        (ctxt != VAR_GLOBAL))
                    275:     {
                    276:        var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
                    277:     }
                    278:     if ((var == NILLNODE) && (flags & FIND_ENV)) {
                    279:        char *env;
                    280:
                    281:        if ((env = getenv (name)) != NULL) {
                    282:            int         len;
                    283:
                    284:            v = (Var *) emalloc(sizeof(Var));
1.4     ! briggs    285:            v->name = estrdup(name);
1.1       deraadt   286:
                    287:            len = strlen(env);
                    288:
                    289:            v->val = Buf_Init(len);
                    290:            Buf_AddBytes(v->val, len, (Byte *)env);
                    291:
                    292:            v->flags = VAR_FROM_ENV;
                    293:            return (v);
                    294:        } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
                    295:                   (ctxt != VAR_GLOBAL))
                    296:        {
                    297:            var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
                    298:            if (var == NILLNODE) {
                    299:                return ((Var *) NIL);
                    300:            } else {
                    301:                return ((Var *)Lst_Datum(var));
                    302:            }
                    303:        } else {
                    304:            return((Var *)NIL);
                    305:        }
                    306:     } else if (var == NILLNODE) {
                    307:        return ((Var *) NIL);
                    308:     } else {
                    309:        return ((Var *) Lst_Datum (var));
                    310:     }
                    311: }
                    312:
                    313: /*-
                    314:  *-----------------------------------------------------------------------
                    315:  * VarAdd  --
                    316:  *     Add a new variable of name name and value val to the given context
                    317:  *
                    318:  * Results:
                    319:  *     None
                    320:  *
                    321:  * Side Effects:
                    322:  *     The new variable is placed at the front of the given context
                    323:  *     The name and val arguments are duplicated so they may
                    324:  *     safely be freed.
                    325:  *-----------------------------------------------------------------------
                    326:  */
                    327: static void
                    328: VarAdd (name, val, ctxt)
                    329:     char           *name;      /* name of variable to add */
                    330:     char           *val;       /* value to set it to */
                    331:     GNode          *ctxt;      /* context in which to set it */
                    332: {
                    333:     register Var   *v;
                    334:     int                  len;
                    335:
                    336:     v = (Var *) emalloc (sizeof (Var));
                    337:
1.4     ! briggs    338:     v->name = estrdup (name);
1.1       deraadt   339:
                    340:     len = val ? strlen(val) : 0;
                    341:     v->val = Buf_Init(len+1);
                    342:     Buf_AddBytes(v->val, len, (Byte *)val);
                    343:
                    344:     v->flags = 0;
                    345:
                    346:     (void) Lst_AtFront (ctxt->context, (ClientData)v);
                    347:     (void) Lst_AtEnd (allVars, (ClientData) v);
                    348:     if (DEBUG(VAR)) {
                    349:        printf("%s:%s = %s\n", ctxt->name, name, val);
                    350:     }
                    351: }
                    352:
                    353:
                    354: /*-
                    355:  *-----------------------------------------------------------------------
                    356:  * VarDelete  --
                    357:  *     Delete a variable and all the space associated with it.
                    358:  *
                    359:  * Results:
                    360:  *     None
                    361:  *
                    362:  * Side Effects:
                    363:  *     None
                    364:  *-----------------------------------------------------------------------
                    365:  */
                    366: static void
                    367: VarDelete(vp)
                    368:     ClientData vp;
                    369: {
                    370:     Var *v = (Var *) vp;
                    371:     free(v->name);
                    372:     Buf_Destroy(v->val, TRUE);
                    373:     free((Address) v);
                    374: }
                    375:
                    376:
                    377:
                    378: /*-
                    379:  *-----------------------------------------------------------------------
                    380:  * Var_Delete --
                    381:  *     Remove a variable from a context.
                    382:  *
                    383:  * Results:
                    384:  *     None.
                    385:  *
                    386:  * Side Effects:
                    387:  *     The Var structure is removed and freed.
                    388:  *
                    389:  *-----------------------------------------------------------------------
                    390:  */
                    391: void
                    392: Var_Delete(name, ctxt)
                    393:     char         *name;
                    394:     GNode        *ctxt;
                    395: {
                    396:     LstNode      ln;
                    397:
                    398:     if (DEBUG(VAR)) {
                    399:        printf("%s:delete %s\n", ctxt->name, name);
                    400:     }
                    401:     ln = Lst_Find(ctxt->context, (ClientData)name, VarCmp);
                    402:     if (ln != NILLNODE) {
                    403:        register Var      *v;
                    404:
                    405:        v = (Var *)Lst_Datum(ln);
                    406:        Lst_Remove(ctxt->context, ln);
                    407:        ln = Lst_Member(allVars, v);
                    408:        Lst_Remove(allVars, ln);
                    409:        VarDelete((ClientData) v);
                    410:     }
                    411: }
                    412:
                    413: /*-
                    414:  *-----------------------------------------------------------------------
                    415:  * Var_Set --
                    416:  *     Set the variable name to the value val in the given context.
                    417:  *
                    418:  * Results:
                    419:  *     None.
                    420:  *
                    421:  * Side Effects:
                    422:  *     If the variable doesn't yet exist, a new record is created for it.
                    423:  *     Else the old value is freed and the new one stuck in its place
                    424:  *
                    425:  * Notes:
                    426:  *     The variable is searched for only in its context before being
                    427:  *     created in that context. I.e. if the context is VAR_GLOBAL,
                    428:  *     only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
                    429:  *     VAR_CMD->context is searched. This is done to avoid the literally
                    430:  *     thousands of unnecessary strcmp's that used to be done to
                    431:  *     set, say, $(@) or $(<).
                    432:  *-----------------------------------------------------------------------
                    433:  */
                    434: void
                    435: Var_Set (name, val, ctxt)
                    436:     char           *name;      /* name of variable to set */
                    437:     char           *val;       /* value to give to the variable */
                    438:     GNode          *ctxt;      /* context in which to set it */
                    439: {
                    440:     register Var   *v;
                    441:
                    442:     /*
                    443:      * We only look for a variable in the given context since anything set
                    444:      * here will override anything in a lower context, so there's not much
                    445:      * point in searching them all just to save a bit of memory...
                    446:      */
                    447:     v = VarFind (name, ctxt, 0);
                    448:     if (v == (Var *) NIL) {
                    449:        VarAdd (name, val, ctxt);
                    450:     } else {
                    451:        Buf_Discard(v->val, Buf_Size(v->val));
                    452:        Buf_AddBytes(v->val, strlen(val), (Byte *)val);
                    453:
                    454:        if (DEBUG(VAR)) {
                    455:            printf("%s:%s = %s\n", ctxt->name, name, val);
                    456:        }
                    457:     }
                    458:     /*
                    459:      * Any variables given on the command line are automatically exported
                    460:      * to the environment (as per POSIX standard)
                    461:      */
                    462:     if (ctxt == VAR_CMD) {
                    463:        setenv(name, val, 1);
                    464:     }
                    465: }
                    466:
                    467: /*-
                    468:  *-----------------------------------------------------------------------
                    469:  * Var_Append --
                    470:  *     The variable of the given name has the given value appended to it in
                    471:  *     the given context.
                    472:  *
                    473:  * Results:
                    474:  *     None
                    475:  *
                    476:  * Side Effects:
                    477:  *     If the variable doesn't exist, it is created. Else the strings
                    478:  *     are concatenated (with a space in between).
                    479:  *
                    480:  * Notes:
                    481:  *     Only if the variable is being sought in the global context is the
                    482:  *     environment searched.
                    483:  *     XXX: Knows its calling circumstances in that if called with ctxt
                    484:  *     an actual target, it will only search that context since only
                    485:  *     a local variable could be being appended to. This is actually
                    486:  *     a big win and must be tolerated.
                    487:  *-----------------------------------------------------------------------
                    488:  */
                    489: void
                    490: Var_Append (name, val, ctxt)
                    491:     char           *name;      /* Name of variable to modify */
                    492:     char           *val;       /* String to append to it */
                    493:     GNode          *ctxt;      /* Context in which this should occur */
                    494: {
                    495:     register Var   *v;
                    496:
                    497:     v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
                    498:
                    499:     if (v == (Var *) NIL) {
                    500:        VarAdd (name, val, ctxt);
                    501:     } else {
                    502:        Buf_AddByte(v->val, (Byte)' ');
                    503:        Buf_AddBytes(v->val, strlen(val), (Byte *)val);
                    504:
                    505:        if (DEBUG(VAR)) {
                    506:            printf("%s:%s = %s\n", ctxt->name, name,
                    507:                   (char *) Buf_GetAll(v->val, (int *)NULL));
                    508:        }
                    509:
                    510:        if (v->flags & VAR_FROM_ENV) {
                    511:            /*
                    512:             * If the original variable came from the environment, we
                    513:             * have to install it in the global context (we could place
                    514:             * it in the environment, but then we should provide a way to
                    515:             * export other variables...)
                    516:             */
                    517:            v->flags &= ~VAR_FROM_ENV;
                    518:            Lst_AtFront(ctxt->context, (ClientData)v);
                    519:        }
                    520:     }
                    521: }
                    522:
                    523: /*-
                    524:  *-----------------------------------------------------------------------
                    525:  * Var_Exists --
                    526:  *     See if the given variable exists.
                    527:  *
                    528:  * Results:
                    529:  *     TRUE if it does, FALSE if it doesn't
                    530:  *
                    531:  * Side Effects:
                    532:  *     None.
                    533:  *
                    534:  *-----------------------------------------------------------------------
                    535:  */
                    536: Boolean
                    537: Var_Exists(name, ctxt)
                    538:     char         *name;        /* Variable to find */
                    539:     GNode        *ctxt;        /* Context in which to start search */
                    540: {
                    541:     Var                  *v;
                    542:
                    543:     v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
                    544:
                    545:     if (v == (Var *)NIL) {
                    546:        return(FALSE);
                    547:     } else if (v->flags & VAR_FROM_ENV) {
                    548:        free(v->name);
                    549:        Buf_Destroy(v->val, TRUE);
                    550:        free((char *)v);
                    551:     }
                    552:     return(TRUE);
                    553: }
                    554:
                    555: /*-
                    556:  *-----------------------------------------------------------------------
                    557:  * Var_Value --
                    558:  *     Return the value of the named variable in the given context
                    559:  *
                    560:  * Results:
                    561:  *     The value if the variable exists, NULL if it doesn't
                    562:  *
                    563:  * Side Effects:
                    564:  *     None
                    565:  *-----------------------------------------------------------------------
                    566:  */
                    567: char *
                    568: Var_Value (name, ctxt, frp)
                    569:     char           *name;      /* name to find */
                    570:     GNode          *ctxt;      /* context in which to search for it */
                    571:     char          **frp;
                    572: {
                    573:     Var            *v;
                    574:
                    575:     v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
                    576:     *frp = NULL;
                    577:     if (v != (Var *) NIL) {
                    578:        char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
                    579:        if (v->flags & VAR_FROM_ENV) {
                    580:            Buf_Destroy(v->val, FALSE);
                    581:            free((Address) v);
                    582:            *frp = p;
                    583:        }
                    584:        return p;
                    585:     } else {
                    586:        return ((char *) NULL);
                    587:     }
                    588: }
                    589:
                    590: /*-
                    591:  *-----------------------------------------------------------------------
                    592:  * VarHead --
                    593:  *     Remove the tail of the given word and place the result in the given
                    594:  *     buffer.
                    595:  *
                    596:  * Results:
                    597:  *     TRUE if characters were added to the buffer (a space needs to be
                    598:  *     added to the buffer before the next word).
                    599:  *
                    600:  * Side Effects:
                    601:  *     The trimmed word is added to the buffer.
                    602:  *
                    603:  *-----------------------------------------------------------------------
                    604:  */
                    605: static Boolean
                    606: VarHead (word, addSpace, buf, dummy)
                    607:     char         *word;        /* Word to trim */
                    608:     Boolean      addSpace;     /* True if need to add a space to the buffer
                    609:                                 * before sticking in the head */
                    610:     Buffer       buf;          /* Buffer in which to store it */
                    611:     ClientData   dummy;
                    612: {
                    613:     register char *slash;
                    614:
                    615:     slash = strrchr (word, '/');
                    616:     if (slash != (char *)NULL) {
                    617:        if (addSpace) {
                    618:            Buf_AddByte (buf, (Byte)' ');
                    619:        }
                    620:        *slash = '\0';
                    621:        Buf_AddBytes (buf, strlen (word), (Byte *)word);
                    622:        *slash = '/';
                    623:        return (TRUE);
                    624:     } else {
                    625:        /*
                    626:         * If no directory part, give . (q.v. the POSIX standard)
                    627:         */
                    628:        if (addSpace) {
                    629:            Buf_AddBytes(buf, 2, (Byte *)" .");
                    630:        } else {
                    631:            Buf_AddByte(buf, (Byte)'.');
                    632:        }
                    633:     }
                    634:     return(dummy ? TRUE : TRUE);
                    635: }
                    636:
                    637: /*-
                    638:  *-----------------------------------------------------------------------
                    639:  * VarTail --
                    640:  *     Remove the head of the given word and place the result in the given
                    641:  *     buffer.
                    642:  *
                    643:  * Results:
                    644:  *     TRUE if characters were added to the buffer (a space needs to be
                    645:  *     added to the buffer before the next word).
                    646:  *
                    647:  * Side Effects:
                    648:  *     The trimmed word is added to the buffer.
                    649:  *
                    650:  *-----------------------------------------------------------------------
                    651:  */
                    652: static Boolean
                    653: VarTail (word, addSpace, buf, dummy)
                    654:     char         *word;        /* Word to trim */
                    655:     Boolean      addSpace;     /* TRUE if need to stick a space in the
                    656:                                 * buffer before adding the tail */
                    657:     Buffer       buf;          /* Buffer in which to store it */
                    658:     ClientData   dummy;
                    659: {
                    660:     register char *slash;
                    661:
                    662:     if (addSpace) {
                    663:        Buf_AddByte (buf, (Byte)' ');
                    664:     }
                    665:
                    666:     slash = strrchr (word, '/');
                    667:     if (slash != (char *)NULL) {
                    668:        *slash++ = '\0';
                    669:        Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
                    670:        slash[-1] = '/';
                    671:     } else {
                    672:        Buf_AddBytes (buf, strlen(word), (Byte *)word);
                    673:     }
                    674:     return (dummy ? TRUE : TRUE);
                    675: }
                    676:
                    677: /*-
                    678:  *-----------------------------------------------------------------------
                    679:  * VarSuffix --
                    680:  *     Place the suffix of the given word in the given buffer.
                    681:  *
                    682:  * Results:
                    683:  *     TRUE if characters were added to the buffer (a space needs to be
                    684:  *     added to the buffer before the next word).
                    685:  *
                    686:  * Side Effects:
                    687:  *     The suffix from the word is placed in the buffer.
                    688:  *
                    689:  *-----------------------------------------------------------------------
                    690:  */
                    691: static Boolean
                    692: VarSuffix (word, addSpace, buf, dummy)
                    693:     char         *word;        /* Word to trim */
                    694:     Boolean      addSpace;     /* TRUE if need to add a space before placing
                    695:                                 * the suffix in the buffer */
                    696:     Buffer       buf;          /* Buffer in which to store it */
                    697:     ClientData   dummy;
                    698: {
                    699:     register char *dot;
                    700:
                    701:     dot = strrchr (word, '.');
                    702:     if (dot != (char *)NULL) {
                    703:        if (addSpace) {
                    704:            Buf_AddByte (buf, (Byte)' ');
                    705:        }
                    706:        *dot++ = '\0';
                    707:        Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
                    708:        dot[-1] = '.';
                    709:        addSpace = TRUE;
                    710:     }
                    711:     return (dummy ? addSpace : addSpace);
                    712: }
                    713:
                    714: /*-
                    715:  *-----------------------------------------------------------------------
                    716:  * VarRoot --
                    717:  *     Remove the suffix of the given word and place the result in the
                    718:  *     buffer.
                    719:  *
                    720:  * Results:
                    721:  *     TRUE if characters were added to the buffer (a space needs to be
                    722:  *     added to the buffer before the next word).
                    723:  *
                    724:  * Side Effects:
                    725:  *     The trimmed word is added to the buffer.
                    726:  *
                    727:  *-----------------------------------------------------------------------
                    728:  */
                    729: static Boolean
                    730: VarRoot (word, addSpace, buf, dummy)
                    731:     char         *word;        /* Word to trim */
                    732:     Boolean      addSpace;     /* TRUE if need to add a space to the buffer
                    733:                                 * before placing the root in it */
                    734:     Buffer       buf;          /* Buffer in which to store it */
                    735:     ClientData   dummy;
                    736: {
                    737:     register char *dot;
                    738:
                    739:     if (addSpace) {
                    740:        Buf_AddByte (buf, (Byte)' ');
                    741:     }
                    742:
                    743:     dot = strrchr (word, '.');
                    744:     if (dot != (char *)NULL) {
                    745:        *dot = '\0';
                    746:        Buf_AddBytes (buf, strlen (word), (Byte *)word);
                    747:        *dot = '.';
                    748:     } else {
                    749:        Buf_AddBytes (buf, strlen(word), (Byte *)word);
                    750:     }
                    751:     return (dummy ? TRUE : TRUE);
                    752: }
                    753:
                    754: /*-
                    755:  *-----------------------------------------------------------------------
                    756:  * VarMatch --
                    757:  *     Place the word in the buffer if it matches the given pattern.
                    758:  *     Callback function for VarModify to implement the :M modifier.
                    759:  *
                    760:  * Results:
                    761:  *     TRUE if a space should be placed in the buffer before the next
                    762:  *     word.
                    763:  *
                    764:  * Side Effects:
                    765:  *     The word may be copied to the buffer.
                    766:  *
                    767:  *-----------------------------------------------------------------------
                    768:  */
                    769: static Boolean
                    770: VarMatch (word, addSpace, buf, pattern)
                    771:     char         *word;        /* Word to examine */
                    772:     Boolean      addSpace;     /* TRUE if need to add a space to the
                    773:                                 * buffer before adding the word, if it
                    774:                                 * matches */
                    775:     Buffer       buf;          /* Buffer in which to store it */
                    776:     ClientData    pattern;     /* Pattern the word must match */
                    777: {
                    778:     if (Str_Match(word, (char *) pattern)) {
                    779:        if (addSpace) {
                    780:            Buf_AddByte(buf, (Byte)' ');
                    781:        }
                    782:        addSpace = TRUE;
                    783:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
                    784:     }
                    785:     return(addSpace);
                    786: }
                    787:
1.4     ! briggs    788: #ifdef SYSVVARSUB
1.1       deraadt   789: /*-
                    790:  *-----------------------------------------------------------------------
                    791:  * VarSYSVMatch --
                    792:  *     Place the word in the buffer if it matches the given pattern.
                    793:  *     Callback function for VarModify to implement the System V %
                    794:  *     modifiers.
                    795:  *
                    796:  * Results:
                    797:  *     TRUE if a space should be placed in the buffer before the next
                    798:  *     word.
                    799:  *
                    800:  * Side Effects:
                    801:  *     The word may be copied to the buffer.
                    802:  *
                    803:  *-----------------------------------------------------------------------
                    804:  */
                    805: static Boolean
                    806: VarSYSVMatch (word, addSpace, buf, patp)
                    807:     char         *word;        /* Word to examine */
                    808:     Boolean      addSpace;     /* TRUE if need to add a space to the
                    809:                                 * buffer before adding the word, if it
                    810:                                 * matches */
                    811:     Buffer       buf;          /* Buffer in which to store it */
                    812:     ClientData           patp;         /* Pattern the word must match */
                    813: {
                    814:     int len;
                    815:     char *ptr;
                    816:     VarPattern           *pat = (VarPattern *) patp;
                    817:
                    818:     if (addSpace)
                    819:        Buf_AddByte(buf, (Byte)' ');
                    820:
                    821:     addSpace = TRUE;
                    822:
                    823:     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
                    824:        Str_SYSVSubst(buf, pat->rhs, ptr, len);
                    825:     else
                    826:        Buf_AddBytes(buf, strlen(word), (Byte *) word);
                    827:
                    828:     return(addSpace);
                    829: }
1.4     ! briggs    830: #endif
1.1       deraadt   831:
                    832:
                    833: /*-
                    834:  *-----------------------------------------------------------------------
                    835:  * VarNoMatch --
                    836:  *     Place the word in the buffer if it doesn't match the given pattern.
                    837:  *     Callback function for VarModify to implement the :N modifier.
                    838:  *
                    839:  * Results:
                    840:  *     TRUE if a space should be placed in the buffer before the next
                    841:  *     word.
                    842:  *
                    843:  * Side Effects:
                    844:  *     The word may be copied to the buffer.
                    845:  *
                    846:  *-----------------------------------------------------------------------
                    847:  */
                    848: static Boolean
                    849: VarNoMatch (word, addSpace, buf, pattern)
                    850:     char         *word;        /* Word to examine */
                    851:     Boolean      addSpace;     /* TRUE if need to add a space to the
                    852:                                 * buffer before adding the word, if it
                    853:                                 * matches */
                    854:     Buffer       buf;          /* Buffer in which to store it */
                    855:     ClientData    pattern;     /* Pattern the word must match */
                    856: {
                    857:     if (!Str_Match(word, (char *) pattern)) {
                    858:        if (addSpace) {
                    859:            Buf_AddByte(buf, (Byte)' ');
                    860:        }
                    861:        addSpace = TRUE;
                    862:        Buf_AddBytes(buf, strlen(word), (Byte *)word);
                    863:     }
                    864:     return(addSpace);
                    865: }
                    866:
                    867:
                    868: /*-
                    869:  *-----------------------------------------------------------------------
                    870:  * VarSubstitute --
                    871:  *     Perform a string-substitution on the given word, placing the
                    872:  *     result in the passed buffer.
                    873:  *
                    874:  * Results:
                    875:  *     TRUE if a space is needed before more characters are added.
                    876:  *
                    877:  * Side Effects:
                    878:  *     None.
                    879:  *
                    880:  *-----------------------------------------------------------------------
                    881:  */
                    882: static Boolean
                    883: VarSubstitute (word, addSpace, buf, patternp)
                    884:     char               *word;      /* Word to modify */
                    885:     Boolean            addSpace;   /* True if space should be added before
                    886:                                     * other characters */
                    887:     Buffer             buf;        /* Buffer for result */
                    888:     ClientData         patternp;   /* Pattern for substitution */
                    889: {
                    890:     register int       wordLen;    /* Length of word */
                    891:     register char      *cp;        /* General pointer */
                    892:     VarPattern *pattern = (VarPattern *) patternp;
                    893:
                    894:     wordLen = strlen(word);
                    895:     if ((pattern->flags & VAR_NO_SUB) == 0) {
                    896:        /*
                    897:         * Still substituting -- break it down into simple anchored cases
                    898:         * and if none of them fits, perform the general substitution case.
                    899:         */
                    900:        if ((pattern->flags & VAR_MATCH_START) &&
                    901:            (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
                    902:                /*
                    903:                 * Anchored at start and beginning of word matches pattern
                    904:                 */
                    905:                if ((pattern->flags & VAR_MATCH_END) &&
                    906:                    (wordLen == pattern->leftLen)) {
                    907:                        /*
                    908:                         * Also anchored at end and matches to the end (word
                    909:                         * is same length as pattern) add space and rhs only
                    910:                         * if rhs is non-null.
                    911:                         */
                    912:                        if (pattern->rightLen != 0) {
                    913:                            if (addSpace) {
                    914:                                Buf_AddByte(buf, (Byte)' ');
                    915:                            }
                    916:                            addSpace = TRUE;
                    917:                            Buf_AddBytes(buf, pattern->rightLen,
                    918:                                         (Byte *)pattern->rhs);
                    919:                        }
                    920:                } else if (pattern->flags & VAR_MATCH_END) {
                    921:                    /*
                    922:                     * Doesn't match to end -- copy word wholesale
                    923:                     */
                    924:                    goto nosub;
                    925:                } else {
                    926:                    /*
                    927:                     * Matches at start but need to copy in trailing characters
                    928:                     */
                    929:                    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
                    930:                        if (addSpace) {
                    931:                            Buf_AddByte(buf, (Byte)' ');
                    932:                        }
                    933:                        addSpace = TRUE;
                    934:                    }
                    935:                    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
                    936:                    Buf_AddBytes(buf, wordLen - pattern->leftLen,
                    937:                                 (Byte *)(word + pattern->leftLen));
                    938:                }
                    939:        } else if (pattern->flags & VAR_MATCH_START) {
                    940:            /*
                    941:             * Had to match at start of word and didn't -- copy whole word.
                    942:             */
                    943:            goto nosub;
                    944:        } else if (pattern->flags & VAR_MATCH_END) {
                    945:            /*
                    946:             * Anchored at end, Find only place match could occur (leftLen
                    947:             * characters from the end of the word) and see if it does. Note
                    948:             * that because the $ will be left at the end of the lhs, we have
                    949:             * to use strncmp.
                    950:             */
                    951:            cp = word + (wordLen - pattern->leftLen);
                    952:            if ((cp >= word) &&
                    953:                (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
                    954:                /*
                    955:                 * Match found. If we will place characters in the buffer,
                    956:                 * add a space before hand as indicated by addSpace, then
                    957:                 * stuff in the initial, unmatched part of the word followed
                    958:                 * by the right-hand-side.
                    959:                 */
                    960:                if (((cp - word) + pattern->rightLen) != 0) {
                    961:                    if (addSpace) {
                    962:                        Buf_AddByte(buf, (Byte)' ');
                    963:                    }
                    964:                    addSpace = TRUE;
                    965:                }
                    966:                Buf_AddBytes(buf, cp - word, (Byte *)word);
                    967:                Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
                    968:            } else {
                    969:                /*
                    970:                 * Had to match at end and didn't. Copy entire word.
                    971:                 */
                    972:                goto nosub;
                    973:            }
                    974:        } else {
                    975:            /*
                    976:             * Pattern is unanchored: search for the pattern in the word using
                    977:             * String_FindSubstring, copying unmatched portions and the
                    978:             * right-hand-side for each match found, handling non-global
                    979:             * subsititutions correctly, etc. When the loop is done, any
                    980:             * remaining part of the word (word and wordLen are adjusted
                    981:             * accordingly through the loop) is copied straight into the
                    982:             * buffer.
                    983:             * addSpace is set FALSE as soon as a space is added to the
                    984:             * buffer.
                    985:             */
                    986:            register Boolean done;
                    987:            int origSize;
                    988:
                    989:            done = FALSE;
                    990:            origSize = Buf_Size(buf);
                    991:            while (!done) {
                    992:                cp = Str_FindSubstring(word, pattern->lhs);
                    993:                if (cp != (char *)NULL) {
                    994:                    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
                    995:                        Buf_AddByte(buf, (Byte)' ');
                    996:                        addSpace = FALSE;
                    997:                    }
                    998:                    Buf_AddBytes(buf, cp-word, (Byte *)word);
                    999:                    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
                   1000:                    wordLen -= (cp - word) + pattern->leftLen;
                   1001:                    word = cp + pattern->leftLen;
                   1002:                    if (wordLen == 0) {
                   1003:                        done = TRUE;
                   1004:                    }
                   1005:                    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
                   1006:                        done = TRUE;
                   1007:                        pattern->flags |= VAR_NO_SUB;
                   1008:                    }
                   1009:                } else {
                   1010:                    done = TRUE;
                   1011:                }
                   1012:            }
                   1013:            if (wordLen != 0) {
                   1014:                if (addSpace) {
                   1015:                    Buf_AddByte(buf, (Byte)' ');
                   1016:                }
                   1017:                Buf_AddBytes(buf, wordLen, (Byte *)word);
                   1018:            }
                   1019:            /*
                   1020:             * If added characters to the buffer, need to add a space
                   1021:             * before we add any more. If we didn't add any, just return
                   1022:             * the previous value of addSpace.
                   1023:             */
                   1024:            return ((Buf_Size(buf) != origSize) || addSpace);
                   1025:        }
                   1026:        /*
                   1027:         * Common code for anchored substitutions: if performed a substitution
                   1028:         * and it's not supposed to be global, mark the pattern as requiring
                   1029:         * no more substitutions. addSpace was set TRUE if characters were
                   1030:         * added to the buffer.
                   1031:         */
                   1032:        if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
                   1033:            pattern->flags |= VAR_NO_SUB;
                   1034:        }
                   1035:        return (addSpace);
                   1036:     }
                   1037:  nosub:
                   1038:     if (addSpace) {
                   1039:        Buf_AddByte(buf, (Byte)' ');
                   1040:     }
                   1041:     Buf_AddBytes(buf, wordLen, (Byte *)word);
                   1042:     return(TRUE);
                   1043: }
                   1044:
                   1045: /*-
                   1046:  *-----------------------------------------------------------------------
                   1047:  * VarModify --
                   1048:  *     Modify each of the words of the passed string using the given
                   1049:  *     function. Used to implement all modifiers.
                   1050:  *
                   1051:  * Results:
                   1052:  *     A string of all the words modified appropriately.
                   1053:  *
                   1054:  * Side Effects:
                   1055:  *     None.
                   1056:  *
                   1057:  *-----------------------------------------------------------------------
                   1058:  */
                   1059: static char *
                   1060: VarModify (str, modProc, datum)
                   1061:     char         *str;             /* String whose words should be trimmed */
                   1062:                                    /* Function to use to modify them */
                   1063:     Boolean              (*modProc) __P((char *, Boolean, Buffer, ClientData));
                   1064:     ClientData   datum;            /* Datum to pass it */
                   1065: {
                   1066:     Buffer       buf;              /* Buffer for the new string */
                   1067:     Boolean      addSpace;         /* TRUE if need to add a space to the
                   1068:                                     * buffer before adding the trimmed
                   1069:                                     * word */
                   1070:     char **av;                     /* word list [first word does not count] */
                   1071:     int ac, i;
                   1072:
                   1073:     buf = Buf_Init (0);
                   1074:     addSpace = FALSE;
                   1075:
                   1076:     av = brk_string(str, &ac, FALSE);
                   1077:
                   1078:     for (i = 1; i < ac; i++)
                   1079:        addSpace = (*modProc)(av[i], addSpace, buf, datum);
                   1080:
                   1081:     Buf_AddByte (buf, '\0');
                   1082:     str = (char *)Buf_GetAll (buf, (int *)NULL);
                   1083:     Buf_Destroy (buf, FALSE);
                   1084:     return (str);
                   1085: }
                   1086:
                   1087: /*-
                   1088:  *-----------------------------------------------------------------------
                   1089:  * Var_Parse --
                   1090:  *     Given the start of a variable invocation, extract the variable
                   1091:  *     name and find its value, then modify it according to the
                   1092:  *     specification.
                   1093:  *
                   1094:  * Results:
                   1095:  *     The (possibly-modified) value of the variable or var_Error if the
                   1096:  *     specification is invalid. The length of the specification is
                   1097:  *     placed in *lengthPtr (for invalid specifications, this is just
                   1098:  *     2...?).
                   1099:  *     A Boolean in *freePtr telling whether the returned string should
                   1100:  *     be freed by the caller.
                   1101:  *
                   1102:  * Side Effects:
                   1103:  *     None.
                   1104:  *
                   1105:  *-----------------------------------------------------------------------
                   1106:  */
                   1107: char *
                   1108: Var_Parse (str, ctxt, err, lengthPtr, freePtr)
                   1109:     char         *str;         /* The string to parse */
                   1110:     GNode        *ctxt;        /* The context for the variable */
                   1111:     Boolean        err;        /* TRUE if undefined variables are an error */
                   1112:     int                    *lengthPtr; /* OUT: The length of the specification */
                   1113:     Boolean        *freePtr;   /* OUT: TRUE if caller should free result */
                   1114: {
                   1115:     register char   *tstr;     /* Pointer into str */
                   1116:     Var                    *v;         /* Variable in invocation */
                   1117:     register char   *cp;       /* Secondary pointer into str (place marker
                   1118:                                 * for tstr) */
                   1119:     Boolean        haveModifier;/* TRUE if have modifiers for the variable */
                   1120:     register char   endc;      /* Ending character when variable in parens
                   1121:                                 * or braces */
1.2       deraadt  1122:     register char   startc=0;  /* Starting character when variable in parens
1.1       deraadt  1123:                                 * or braces */
                   1124:     int             cnt;       /* Used to count brace pairs when variable in
                   1125:                                 * in parens or braces */
                   1126:     char           *start;
                   1127:     Boolean        dynamic;    /* TRUE if the variable is local and we're
                   1128:                                 * expanding it in a non-local context. This
                   1129:                                 * is done to support dynamic sources. The
                   1130:                                 * result is just the invocation, unaltered */
                   1131:
                   1132:     *freePtr = FALSE;
                   1133:     dynamic = FALSE;
                   1134:     start = str;
                   1135:
                   1136:     if (str[1] != '(' && str[1] != '{') {
                   1137:        /*
                   1138:         * If it's not bounded by braces of some sort, life is much simpler.
                   1139:         * We just need to check for the first character and return the
                   1140:         * value if it exists.
                   1141:         */
                   1142:        char      name[2];
                   1143:
                   1144:        name[0] = str[1];
                   1145:        name[1] = '\0';
                   1146:
                   1147:        v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
                   1148:        if (v == (Var *)NIL) {
                   1149:            *lengthPtr = 2;
                   1150:
                   1151:            if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
                   1152:                /*
                   1153:                 * If substituting a local variable in a non-local context,
                   1154:                 * assume it's for dynamic source stuff. We have to handle
                   1155:                 * this specially and return the longhand for the variable
                   1156:                 * with the dollar sign escaped so it makes it back to the
                   1157:                 * caller. Only four of the local variables are treated
                   1158:                 * specially as they are the only four that will be set
                   1159:                 * when dynamic sources are expanded.
                   1160:                 */
                   1161:                switch (str[1]) {
                   1162:                    case '@':
                   1163:                        return("$(.TARGET)");
                   1164:                    case '%':
                   1165:                        return("$(.ARCHIVE)");
                   1166:                    case '*':
                   1167:                        return("$(.PREFIX)");
                   1168:                    case '!':
                   1169:                        return("$(.MEMBER)");
                   1170:                }
                   1171:            }
                   1172:            /*
                   1173:             * Error
                   1174:             */
                   1175:            return (err ? var_Error : varNoError);
                   1176:        } else {
                   1177:            haveModifier = FALSE;
                   1178:            tstr = &str[1];
                   1179:            endc = str[1];
                   1180:        }
                   1181:     } else {
                   1182:        startc = str[1];
                   1183:        endc = startc == '(' ? ')' : '}';
                   1184:
                   1185:        /*
                   1186:         * Skip to the end character or a colon, whichever comes first.
                   1187:         */
                   1188:        for (tstr = str + 2;
                   1189:             *tstr != '\0' && *tstr != endc && *tstr != ':';
                   1190:             tstr++)
                   1191:        {
                   1192:            continue;
                   1193:        }
                   1194:        if (*tstr == ':') {
                   1195:            haveModifier = TRUE;
                   1196:        } else if (*tstr != '\0') {
                   1197:            haveModifier = FALSE;
                   1198:        } else {
                   1199:            /*
                   1200:             * If we never did find the end character, return NULL
                   1201:             * right now, setting the length to be the distance to
                   1202:             * the end of the string, since that's what make does.
                   1203:             */
                   1204:            *lengthPtr = tstr - str;
                   1205:            return (var_Error);
                   1206:        }
                   1207:        *tstr = '\0';
                   1208:
                   1209:        v = VarFind (str + 2, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
                   1210:        if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
                   1211:            ((tstr-str) == 4) && (str[3] == 'F' || str[3] == 'D'))
                   1212:        {
                   1213:            /*
                   1214:             * Check for bogus D and F forms of local variables since we're
                   1215:             * in a local context and the name is the right length.
                   1216:             */
                   1217:            switch(str[2]) {
                   1218:                case '@':
                   1219:                case '%':
                   1220:                case '*':
                   1221:                case '!':
                   1222:                case '>':
                   1223:                case '<':
                   1224:                {
                   1225:                    char    vname[2];
                   1226:                    char    *val;
                   1227:
                   1228:                    /*
                   1229:                     * Well, it's local -- go look for it.
                   1230:                     */
                   1231:                    vname[0] = str[2];
                   1232:                    vname[1] = '\0';
                   1233:                    v = VarFind(vname, ctxt, 0);
                   1234:
                   1235:                    if (v != (Var *)NIL) {
                   1236:                        /*
                   1237:                         * No need for nested expansion or anything, as we're
                   1238:                         * the only one who sets these things and we sure don't
                   1239:                         * but nested invocations in them...
                   1240:                         */
                   1241:                        val = (char *)Buf_GetAll(v->val, (int *)NULL);
                   1242:
                   1243:                        if (str[3] == 'D') {
                   1244:                            val = VarModify(val, VarHead, (ClientData)0);
                   1245:                        } else {
                   1246:                            val = VarModify(val, VarTail, (ClientData)0);
                   1247:                        }
                   1248:                        /*
                   1249:                         * Resulting string is dynamically allocated, so
                   1250:                         * tell caller to free it.
                   1251:                         */
                   1252:                        *freePtr = TRUE;
                   1253:                        *lengthPtr = tstr-start+1;
                   1254:                        *tstr = endc;
                   1255:                        return(val);
                   1256:                    }
                   1257:                    break;
                   1258:                }
                   1259:            }
                   1260:        }
                   1261:
                   1262:        if (v == (Var *)NIL) {
                   1263:            if ((((tstr-str) == 3) ||
                   1264:                 ((((tstr-str) == 4) && (str[3] == 'F' ||
                   1265:                                         str[3] == 'D')))) &&
                   1266:                ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
                   1267:            {
                   1268:                /*
                   1269:                 * If substituting a local variable in a non-local context,
                   1270:                 * assume it's for dynamic source stuff. We have to handle
                   1271:                 * this specially and return the longhand for the variable
                   1272:                 * with the dollar sign escaped so it makes it back to the
                   1273:                 * caller. Only four of the local variables are treated
                   1274:                 * specially as they are the only four that will be set
                   1275:                 * when dynamic sources are expanded.
                   1276:                 */
                   1277:                switch (str[2]) {
                   1278:                    case '@':
                   1279:                    case '%':
                   1280:                    case '*':
                   1281:                    case '!':
                   1282:                        dynamic = TRUE;
                   1283:                        break;
                   1284:                }
                   1285:            } else if (((tstr-str) > 4) && (str[2] == '.') &&
                   1286:                       isupper((unsigned char) str[3]) &&
                   1287:                       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
                   1288:            {
                   1289:                int     len;
                   1290:
                   1291:                len = (tstr-str) - 3;
                   1292:                if ((strncmp(str+2, ".TARGET", len) == 0) ||
                   1293:                    (strncmp(str+2, ".ARCHIVE", len) == 0) ||
                   1294:                    (strncmp(str+2, ".PREFIX", len) == 0) ||
                   1295:                    (strncmp(str+2, ".MEMBER", len) == 0))
                   1296:                {
                   1297:                    dynamic = TRUE;
                   1298:                }
                   1299:            }
                   1300:
                   1301:            if (!haveModifier) {
                   1302:                /*
                   1303:                 * No modifiers -- have specification length so we can return
                   1304:                 * now.
                   1305:                 */
                   1306:                *lengthPtr = tstr - start + 1;
                   1307:                *tstr = endc;
                   1308:                if (dynamic) {
                   1309:                    str = emalloc(*lengthPtr + 1);
                   1310:                    strncpy(str, start, *lengthPtr);
                   1311:                    str[*lengthPtr] = '\0';
                   1312:                    *freePtr = TRUE;
                   1313:                    return(str);
                   1314:                } else {
                   1315:                    return (err ? var_Error : varNoError);
                   1316:                }
                   1317:            } else {
                   1318:                /*
                   1319:                 * Still need to get to the end of the variable specification,
                   1320:                 * so kludge up a Var structure for the modifications
                   1321:                 */
                   1322:                v = (Var *) emalloc(sizeof(Var));
                   1323:                v->name = &str[1];
                   1324:                v->val = Buf_Init(1);
                   1325:                v->flags = VAR_JUNK;
                   1326:            }
                   1327:        }
                   1328:     }
                   1329:
                   1330:     if (v->flags & VAR_IN_USE) {
                   1331:        Fatal("Variable %s is recursive.", v->name);
                   1332:        /*NOTREACHED*/
                   1333:     } else {
                   1334:        v->flags |= VAR_IN_USE;
                   1335:     }
                   1336:     /*
                   1337:      * Before doing any modification, we have to make sure the value
                   1338:      * has been fully expanded. If it looks like recursion might be
                   1339:      * necessary (there's a dollar sign somewhere in the variable's value)
                   1340:      * we just call Var_Subst to do any other substitutions that are
                   1341:      * necessary. Note that the value returned by Var_Subst will have
                   1342:      * been dynamically-allocated, so it will need freeing when we
                   1343:      * return.
                   1344:      */
                   1345:     str = (char *)Buf_GetAll(v->val, (int *)NULL);
                   1346:     if (strchr (str, '$') != (char *)NULL) {
                   1347:        str = Var_Subst(NULL, str, ctxt, err);
                   1348:        *freePtr = TRUE;
                   1349:     }
                   1350:
                   1351:     v->flags &= ~VAR_IN_USE;
                   1352:
                   1353:     /*
                   1354:      * Now we need to apply any modifiers the user wants applied.
                   1355:      * These are:
                   1356:      *           :M<pattern>   words which match the given <pattern>.
                   1357:      *                         <pattern> is of the standard file
                   1358:      *                         wildcarding form.
                   1359:      *           :S<d><pat1><d><pat2><d>[g]
                   1360:      *                         Substitute <pat2> for <pat1> in the value
                   1361:      *           :H            Substitute the head of each word
                   1362:      *           :T            Substitute the tail of each word
                   1363:      *           :E            Substitute the extension (minus '.') of
                   1364:      *                         each word
                   1365:      *           :R            Substitute the root of each word
                   1366:      *                         (pathname minus the suffix).
                   1367:      *           :lhs=rhs      Like :S, but the rhs goes to the end of
                   1368:      *                         the invocation.
                   1369:      */
                   1370:     if ((str != (char *)NULL) && haveModifier) {
                   1371:        /*
                   1372:         * Skip initial colon while putting it back.
                   1373:         */
                   1374:        *tstr++ = ':';
                   1375:        while (*tstr != endc) {
                   1376:            char        *newStr;    /* New value to return */
                   1377:            char        termc;      /* Character which terminated scan */
                   1378:
                   1379:            if (DEBUG(VAR)) {
                   1380:                printf("Applying :%c to \"%s\"\n", *tstr, str);
                   1381:            }
                   1382:            switch (*tstr) {
                   1383:                case 'N':
                   1384:                case 'M':
                   1385:                {
                   1386:                    char    *pattern;
                   1387:                    char    *cp2;
                   1388:                    Boolean copy;
                   1389:
                   1390:                    copy = FALSE;
                   1391:                    for (cp = tstr + 1;
                   1392:                         *cp != '\0' && *cp != ':' && *cp != endc;
                   1393:                         cp++)
                   1394:                    {
                   1395:                        if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
                   1396:                            copy = TRUE;
                   1397:                            cp++;
                   1398:                        }
                   1399:                    }
                   1400:                    termc = *cp;
                   1401:                    *cp = '\0';
                   1402:                    if (copy) {
                   1403:                        /*
                   1404:                         * Need to compress the \:'s out of the pattern, so
                   1405:                         * allocate enough room to hold the uncompressed
                   1406:                         * pattern (note that cp started at tstr+1, so
                   1407:                         * cp - tstr takes the null byte into account) and
                   1408:                         * compress the pattern into the space.
                   1409:                         */
                   1410:                        pattern = emalloc(cp - tstr);
                   1411:                        for (cp2 = pattern, cp = tstr + 1;
                   1412:                             *cp != '\0';
                   1413:                             cp++, cp2++)
                   1414:                        {
                   1415:                            if ((*cp == '\\') &&
                   1416:                                (cp[1] == ':' || cp[1] == endc)) {
                   1417:                                    cp++;
                   1418:                            }
                   1419:                            *cp2 = *cp;
                   1420:                        }
                   1421:                        *cp2 = '\0';
                   1422:                    } else {
                   1423:                        pattern = &tstr[1];
                   1424:                    }
                   1425:                    if (*tstr == 'M' || *tstr == 'm') {
                   1426:                        newStr = VarModify(str, VarMatch, (ClientData)pattern);
                   1427:                    } else {
                   1428:                        newStr = VarModify(str, VarNoMatch,
                   1429:                                           (ClientData)pattern);
                   1430:                    }
                   1431:                    if (copy) {
                   1432:                        free(pattern);
                   1433:                    }
                   1434:                    break;
                   1435:                }
                   1436:                case 'S':
                   1437:                {
                   1438:                    VarPattern      pattern;
                   1439:                    register char   delim;
                   1440:                    Buffer          buf;        /* Buffer for patterns */
                   1441:
                   1442:                    pattern.flags = 0;
                   1443:                    delim = tstr[1];
                   1444:                    tstr += 2;
                   1445:                    /*
                   1446:                     * If pattern begins with '^', it is anchored to the
                   1447:                     * start of the word -- skip over it and flag pattern.
                   1448:                     */
                   1449:                    if (*tstr == '^') {
                   1450:                        pattern.flags |= VAR_MATCH_START;
                   1451:                        tstr += 1;
                   1452:                    }
                   1453:
                   1454:                    buf = Buf_Init(0);
                   1455:
                   1456:                    /*
                   1457:                     * Pass through the lhs looking for 1) escaped delimiters,
                   1458:                     * '$'s and backslashes (place the escaped character in
                   1459:                     * uninterpreted) and 2) unescaped $'s that aren't before
                   1460:                     * the delimiter (expand the variable substitution).
                   1461:                     * The result is left in the Buffer buf.
                   1462:                     */
                   1463:                    for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
                   1464:                        if ((*cp == '\\') &&
                   1465:                            ((cp[1] == delim) ||
                   1466:                             (cp[1] == '$') ||
                   1467:                             (cp[1] == '\\')))
                   1468:                        {
                   1469:                            Buf_AddByte(buf, (Byte)cp[1]);
                   1470:                            cp++;
                   1471:                        } else if (*cp == '$') {
                   1472:                            if (cp[1] != delim) {
                   1473:                                /*
                   1474:                                 * If unescaped dollar sign not before the
                   1475:                                 * delimiter, assume it's a variable
                   1476:                                 * substitution and recurse.
                   1477:                                 */
                   1478:                                char        *cp2;
                   1479:                                int         len;
                   1480:                                Boolean     freeIt;
                   1481:
                   1482:                                cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
                   1483:                                Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
                   1484:                                if (freeIt) {
                   1485:                                    free(cp2);
                   1486:                                }
                   1487:                                cp += len - 1;
                   1488:                            } else {
                   1489:                                /*
                   1490:                                 * Unescaped $ at end of pattern => anchor
                   1491:                                 * pattern at end.
                   1492:                                 */
                   1493:                                pattern.flags |= VAR_MATCH_END;
                   1494:                            }
                   1495:                        } else {
                   1496:                            Buf_AddByte(buf, (Byte)*cp);
                   1497:                        }
                   1498:                    }
                   1499:
                   1500:                    Buf_AddByte(buf, (Byte)'\0');
                   1501:
                   1502:                    /*
                   1503:                     * If lhs didn't end with the delimiter, complain and
                   1504:                     * return NULL
                   1505:                     */
                   1506:                    if (*cp != delim) {
                   1507:                        *lengthPtr = cp - start + 1;
                   1508:                        if (*freePtr) {
                   1509:                            free(str);
                   1510:                        }
                   1511:                        Buf_Destroy(buf, TRUE);
                   1512:                        Error("Unclosed substitution for %s (%c missing)",
                   1513:                              v->name, delim);
                   1514:                        return (var_Error);
                   1515:                    }
                   1516:
                   1517:                    /*
                   1518:                     * Fetch pattern and destroy buffer, but preserve the data
                   1519:                     * in it, since that's our lhs. Note that Buf_GetAll
                   1520:                     * will return the actual number of bytes, which includes
                   1521:                     * the null byte, so we have to decrement the length by
                   1522:                     * one.
                   1523:                     */
                   1524:                    pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
                   1525:                    pattern.leftLen--;
                   1526:                    Buf_Destroy(buf, FALSE);
                   1527:
                   1528:                    /*
                   1529:                     * Now comes the replacement string. Three things need to
                   1530:                     * be done here: 1) need to compress escaped delimiters and
                   1531:                     * ampersands and 2) need to replace unescaped ampersands
                   1532:                     * with the l.h.s. (since this isn't regexp, we can do
                   1533:                     * it right here) and 3) expand any variable substitutions.
                   1534:                     */
                   1535:                    buf = Buf_Init(0);
                   1536:
                   1537:                    tstr = cp + 1;
                   1538:                    for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
                   1539:                        if ((*cp == '\\') &&
                   1540:                            ((cp[1] == delim) ||
                   1541:                             (cp[1] == '&') ||
                   1542:                             (cp[1] == '\\') ||
                   1543:                             (cp[1] == '$')))
                   1544:                        {
                   1545:                            Buf_AddByte(buf, (Byte)cp[1]);
                   1546:                            cp++;
                   1547:                        } else if ((*cp == '$') && (cp[1] != delim)) {
                   1548:                            char    *cp2;
                   1549:                            int     len;
                   1550:                            Boolean freeIt;
                   1551:
                   1552:                            cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
                   1553:                            Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
                   1554:                            cp += len - 1;
                   1555:                            if (freeIt) {
                   1556:                                free(cp2);
                   1557:                            }
                   1558:                        } else if (*cp == '&') {
                   1559:                            Buf_AddBytes(buf, pattern.leftLen,
                   1560:                                         (Byte *)pattern.lhs);
                   1561:                        } else {
                   1562:                            Buf_AddByte(buf, (Byte)*cp);
                   1563:                        }
                   1564:                    }
                   1565:
                   1566:                    Buf_AddByte(buf, (Byte)'\0');
                   1567:
                   1568:                    /*
                   1569:                     * If didn't end in delimiter character, complain
                   1570:                     */
                   1571:                    if (*cp != delim) {
                   1572:                        *lengthPtr = cp - start + 1;
                   1573:                        if (*freePtr) {
                   1574:                            free(str);
                   1575:                        }
                   1576:                        Buf_Destroy(buf, TRUE);
                   1577:                        Error("Unclosed substitution for %s (%c missing)",
                   1578:                              v->name, delim);
                   1579:                        return (var_Error);
                   1580:                    }
                   1581:
                   1582:                    pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
                   1583:                    pattern.rightLen--;
                   1584:                    Buf_Destroy(buf, FALSE);
                   1585:
                   1586:                    /*
                   1587:                     * Check for global substitution. If 'g' after the final
                   1588:                     * delimiter, substitution is global and is marked that
                   1589:                     * way.
                   1590:                     */
                   1591:                    cp++;
                   1592:                    if (*cp == 'g') {
                   1593:                        pattern.flags |= VAR_SUB_GLOBAL;
                   1594:                        cp++;
                   1595:                    }
                   1596:
                   1597:                    termc = *cp;
                   1598:                    newStr = VarModify(str, VarSubstitute,
                   1599:                                       (ClientData)&pattern);
                   1600:                    /*
                   1601:                     * Free the two strings.
                   1602:                     */
                   1603:                    free(pattern.lhs);
                   1604:                    free(pattern.rhs);
                   1605:                    break;
                   1606:                }
                   1607:                case 'T':
                   1608:                    if (tstr[1] == endc || tstr[1] == ':') {
                   1609:                        newStr = VarModify (str, VarTail, (ClientData)0);
                   1610:                        cp = tstr + 1;
                   1611:                        termc = *cp;
                   1612:                        break;
                   1613:                    }
                   1614:                    /*FALLTHRU*/
                   1615:                case 'H':
                   1616:                    if (tstr[1] == endc || tstr[1] == ':') {
                   1617:                        newStr = VarModify (str, VarHead, (ClientData)0);
                   1618:                        cp = tstr + 1;
                   1619:                        termc = *cp;
                   1620:                        break;
                   1621:                    }
                   1622:                    /*FALLTHRU*/
                   1623:                case 'E':
                   1624:                    if (tstr[1] == endc || tstr[1] == ':') {
                   1625:                        newStr = VarModify (str, VarSuffix, (ClientData)0);
                   1626:                        cp = tstr + 1;
                   1627:                        termc = *cp;
                   1628:                        break;
                   1629:                    }
                   1630:                    /*FALLTHRU*/
                   1631:                case 'R':
                   1632:                    if (tstr[1] == endc || tstr[1] == ':') {
                   1633:                        newStr = VarModify (str, VarRoot, (ClientData)0);
                   1634:                        cp = tstr + 1;
                   1635:                        termc = *cp;
                   1636:                        break;
                   1637:                    }
                   1638:                    /*FALLTHRU*/
1.4     ! briggs   1639: #ifdef SUNSHCMD
        !          1640:                case 's':
        !          1641:                    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
        !          1642:                        char *err;
        !          1643:                        newStr = Cmd_Exec (str, &err);
        !          1644:                        if (err)
        !          1645:                            Error (err, str);
        !          1646:                        cp = tstr + 2;
        !          1647:                        termc = *cp;
        !          1648:                        break;
        !          1649:                    }
        !          1650:                    /*FALLTHRU*/
        !          1651: #endif
        !          1652:                default:
        !          1653:                {
        !          1654: #ifdef SYSVVARSUB
1.1       deraadt  1655:                    /*
                   1656:                     * This can either be a bogus modifier or a System-V
                   1657:                     * substitution command.
                   1658:                     */
                   1659:                    VarPattern      pattern;
                   1660:                    Boolean         eqFound;
                   1661:
                   1662:                    pattern.flags = 0;
                   1663:                    eqFound = FALSE;
                   1664:                    /*
                   1665:                     * First we make a pass through the string trying
                   1666:                     * to verify it is a SYSV-make-style translation:
                   1667:                     * it must be: <string1>=<string2>)
                   1668:                     */
                   1669:                    cp = tstr;
                   1670:                    cnt = 1;
                   1671:                    while (*cp != '\0' && cnt) {
                   1672:                        if (*cp == '=') {
                   1673:                            eqFound = TRUE;
                   1674:                            /* continue looking for endc */
                   1675:                        }
                   1676:                        else if (*cp == endc)
                   1677:                            cnt--;
                   1678:                        else if (*cp == startc)
                   1679:                            cnt++;
                   1680:                        if (cnt)
                   1681:                            cp++;
                   1682:                    }
                   1683:                    if (*cp == endc && eqFound) {
                   1684:
                   1685:                        /*
                   1686:                         * Now we break this sucker into the lhs and
                   1687:                         * rhs. We must null terminate them of course.
                   1688:                         */
                   1689:                        for (cp = tstr; *cp != '='; cp++)
                   1690:                            continue;
                   1691:                        pattern.lhs = tstr;
                   1692:                        pattern.leftLen = cp - tstr;
                   1693:                        *cp++ = '\0';
                   1694:
                   1695:                        pattern.rhs = cp;
                   1696:                        cnt = 1;
                   1697:                        while (cnt) {
                   1698:                            if (*cp == endc)
                   1699:                                cnt--;
                   1700:                            else if (*cp == startc)
                   1701:                                cnt++;
                   1702:                            if (cnt)
                   1703:                                cp++;
                   1704:                        }
                   1705:                        pattern.rightLen = cp - pattern.rhs;
                   1706:                        *cp = '\0';
                   1707:
                   1708:                        /*
                   1709:                         * SYSV modifications happen through the whole
                   1710:                         * string. Note the pattern is anchored at the end.
                   1711:                         */
                   1712:                        newStr = VarModify(str, VarSYSVMatch,
                   1713:                                           (ClientData)&pattern);
                   1714:
                   1715:                        /*
                   1716:                         * Restore the nulled characters
                   1717:                         */
                   1718:                        pattern.lhs[pattern.leftLen] = '=';
                   1719:                        pattern.rhs[pattern.rightLen] = endc;
                   1720:                        termc = endc;
1.4     ! briggs   1721:                    } else
        !          1722: #endif
        !          1723:                    {
1.1       deraadt  1724:                        Error ("Unknown modifier '%c'\n", *tstr);
                   1725:                        for (cp = tstr+1;
                   1726:                             *cp != ':' && *cp != endc && *cp != '\0';
                   1727:                             cp++)
                   1728:                                 continue;
                   1729:                        termc = *cp;
                   1730:                        newStr = var_Error;
                   1731:                    }
                   1732:                }
                   1733:            }
                   1734:            if (DEBUG(VAR)) {
                   1735:                printf("Result is \"%s\"\n", newStr);
                   1736:            }
                   1737:
                   1738:            if (*freePtr) {
                   1739:                free (str);
                   1740:            }
                   1741:            str = newStr;
                   1742:            if (str != var_Error) {
                   1743:                *freePtr = TRUE;
                   1744:            } else {
                   1745:                *freePtr = FALSE;
                   1746:            }
                   1747:            if (termc == '\0') {
                   1748:                Error("Unclosed variable specification for %s", v->name);
                   1749:            } else if (termc == ':') {
                   1750:                *cp++ = termc;
                   1751:            } else {
                   1752:                *cp = termc;
                   1753:            }
                   1754:            tstr = cp;
                   1755:        }
                   1756:        *lengthPtr = tstr - start + 1;
                   1757:     } else {
                   1758:        *lengthPtr = tstr - start + 1;
                   1759:        *tstr = endc;
                   1760:     }
                   1761:
                   1762:     if (v->flags & VAR_FROM_ENV) {
                   1763:        Boolean   destroy = FALSE;
                   1764:
                   1765:        if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
                   1766:            destroy = TRUE;
                   1767:        } else {
                   1768:            /*
                   1769:             * Returning the value unmodified, so tell the caller to free
                   1770:             * the thing.
                   1771:             */
                   1772:            *freePtr = TRUE;
                   1773:        }
                   1774:        Buf_Destroy(v->val, destroy);
                   1775:        free((Address)v);
                   1776:     } else if (v->flags & VAR_JUNK) {
                   1777:        /*
                   1778:         * Perform any free'ing needed and set *freePtr to FALSE so the caller
                   1779:         * doesn't try to free a static pointer.
                   1780:         */
                   1781:        if (*freePtr) {
                   1782:            free(str);
                   1783:        }
                   1784:        *freePtr = FALSE;
                   1785:        Buf_Destroy(v->val, TRUE);
                   1786:        free((Address)v);
                   1787:        if (dynamic) {
                   1788:            str = emalloc(*lengthPtr + 1);
                   1789:            strncpy(str, start, *lengthPtr);
                   1790:            str[*lengthPtr] = '\0';
                   1791:            *freePtr = TRUE;
                   1792:        } else {
                   1793:            str = var_Error;
                   1794:        }
                   1795:     }
                   1796:     return (str);
                   1797: }
                   1798:
                   1799: /*-
                   1800:  *-----------------------------------------------------------------------
                   1801:  * Var_Subst  --
                   1802:  *     Substitute for all variables in the given string in the given context
                   1803:  *     If undefErr is TRUE, Parse_Error will be called when an undefined
                   1804:  *     variable is encountered.
                   1805:  *
                   1806:  * Results:
                   1807:  *     The resulting string.
                   1808:  *
                   1809:  * Side Effects:
                   1810:  *     None. The old string must be freed by the caller
                   1811:  *-----------------------------------------------------------------------
                   1812:  */
                   1813: char *
                   1814: Var_Subst (var, str, ctxt, undefErr)
                   1815:     char         *var;             /* Named variable || NULL for all */
                   1816:     char         *str;             /* the string in which to substitute */
                   1817:     GNode         *ctxt;           /* the context wherein to find variables */
                   1818:     Boolean      undefErr;         /* TRUE if undefineds are an error */
                   1819: {
                   1820:     Buffer       buf;              /* Buffer for forming things */
                   1821:     char         *val;             /* Value to substitute for a variable */
                   1822:     int                  length;           /* Length of the variable invocation */
                   1823:     Boolean      doFree;           /* Set true if val should be freed */
                   1824:     static Boolean errorReported;   /* Set true if an error has already
                   1825:                                     * been reported to prevent a plethora
                   1826:                                     * of messages when recursing */
                   1827:
                   1828:     buf = Buf_Init (MAKE_BSIZE);
                   1829:     errorReported = FALSE;
                   1830:
                   1831:     while (*str) {
                   1832:        if (var == NULL && (*str == '$') && (str[1] == '$')) {
                   1833:            /*
                   1834:             * A dollar sign may be escaped either with another dollar sign.
                   1835:             * In such a case, we skip over the escape character and store the
                   1836:             * dollar sign into the buffer directly.
                   1837:             */
                   1838:            str++;
                   1839:            Buf_AddByte(buf, (Byte)*str);
                   1840:            str++;
                   1841:        } else if (*str != '$') {
                   1842:            /*
                   1843:             * Skip as many characters as possible -- either to the end of
                   1844:             * the string or to the next dollar sign (variable invocation).
                   1845:             */
                   1846:            char  *cp;
                   1847:
                   1848:            for (cp = str++; *str != '$' && *str != '\0'; str++)
                   1849:                continue;
                   1850:            Buf_AddBytes(buf, str - cp, (Byte *)cp);
                   1851:        } else {
                   1852:            if (var != NULL) {
                   1853:                int expand;
                   1854:                for (;;) {
                   1855:                    if (str[1] != '(' && str[1] != '{') {
                   1856:                        if (str[1] != *var) {
                   1857:                            Buf_AddBytes(buf, 2, (Byte *) str);
                   1858:                            str += 2;
                   1859:                            expand = FALSE;
                   1860:                        }
                   1861:                        else
                   1862:                            expand = TRUE;
                   1863:                        break;
                   1864:                    }
                   1865:                    else {
                   1866:                        char *p;
                   1867:
                   1868:                        /*
                   1869:                         * Scan up to the end of the variable name.
                   1870:                         */
                   1871:                        for (p = &str[2]; *p &&
                   1872:                             *p != ':' && *p != ')' && *p != '}'; p++)
                   1873:                            if (*p == '$')
                   1874:                                break;
                   1875:                        /*
                   1876:                         * A variable inside the variable. We cannot expand
                   1877:                         * the external variable yet, so we try again with
                   1878:                         * the nested one
                   1879:                         */
                   1880:                        if (*p == '$') {
                   1881:                            Buf_AddBytes(buf, p - str, (Byte *) str);
                   1882:                            str = p;
                   1883:                            continue;
                   1884:                        }
                   1885:
                   1886:                        if (strncmp(var, str + 2, p - str - 2) != 0 ||
                   1887:                            var[p - str - 2] != '\0') {
                   1888:                            /*
                   1889:                             * Not the variable we want to expand, scan
                   1890:                             * until the next variable
                   1891:                             */
                   1892:                            for (;*p != '$' && *p != '\0'; p++)
                   1893:                                continue;
                   1894:                            Buf_AddBytes(buf, p - str, (Byte *) str);
                   1895:                            str = p;
                   1896:                            expand = FALSE;
                   1897:                        }
                   1898:                        else
                   1899:                            expand = TRUE;
                   1900:                        break;
                   1901:                    }
                   1902:                }
                   1903:                if (!expand)
                   1904:                    continue;
                   1905:            }
                   1906:
                   1907:            val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
                   1908:
                   1909:            /*
                   1910:             * When we come down here, val should either point to the
                   1911:             * value of this variable, suitably modified, or be NULL.
                   1912:             * Length should be the total length of the potential
                   1913:             * variable invocation (from $ to end character...)
                   1914:             */
                   1915:            if (val == var_Error || val == varNoError) {
                   1916:                /*
                   1917:                 * If performing old-time variable substitution, skip over
                   1918:                 * the variable and continue with the substitution. Otherwise,
                   1919:                 * store the dollar sign and advance str so we continue with
                   1920:                 * the string...
                   1921:                 */
                   1922:                if (oldVars) {
                   1923:                    str += length;
                   1924:                } else if (undefErr) {
                   1925:                    /*
                   1926:                     * If variable is undefined, complain and skip the
                   1927:                     * variable. The complaint will stop us from doing anything
                   1928:                     * when the file is parsed.
                   1929:                     */
                   1930:                    if (!errorReported) {
                   1931:                        Parse_Error (PARSE_FATAL,
                   1932:                                     "Undefined variable \"%.*s\"",length,str);
                   1933:                    }
                   1934:                    str += length;
                   1935:                    errorReported = TRUE;
                   1936:                } else {
                   1937:                    Buf_AddByte (buf, (Byte)*str);
                   1938:                    str += 1;
                   1939:                }
                   1940:            } else {
                   1941:                /*
                   1942:                 * We've now got a variable structure to store in. But first,
                   1943:                 * advance the string pointer.
                   1944:                 */
                   1945:                str += length;
                   1946:
                   1947:                /*
                   1948:                 * Copy all the characters from the variable value straight
                   1949:                 * into the new string.
                   1950:                 */
                   1951:                Buf_AddBytes (buf, strlen (val), (Byte *)val);
                   1952:                if (doFree) {
                   1953:                    free ((Address)val);
                   1954:                }
                   1955:            }
                   1956:        }
                   1957:     }
                   1958:
                   1959:     Buf_AddByte (buf, '\0');
                   1960:     str = (char *)Buf_GetAll (buf, (int *)NULL);
                   1961:     Buf_Destroy (buf, FALSE);
                   1962:     return (str);
                   1963: }
                   1964:
                   1965: /*-
                   1966:  *-----------------------------------------------------------------------
                   1967:  * Var_GetTail --
                   1968:  *     Return the tail from each of a list of words. Used to set the
                   1969:  *     System V local variables.
                   1970:  *
                   1971:  * Results:
                   1972:  *     The resulting string.
                   1973:  *
                   1974:  * Side Effects:
                   1975:  *     None.
                   1976:  *
                   1977:  *-----------------------------------------------------------------------
                   1978:  */
                   1979: char *
                   1980: Var_GetTail(file)
                   1981:     char       *file;      /* Filename to modify */
                   1982: {
                   1983:     return(VarModify(file, VarTail, (ClientData)0));
                   1984: }
                   1985:
                   1986: /*-
                   1987:  *-----------------------------------------------------------------------
                   1988:  * Var_GetHead --
                   1989:  *     Find the leading components of a (list of) filename(s).
                   1990:  *     XXX: VarHead does not replace foo by ., as (sun) System V make
                   1991:  *     does.
                   1992:  *
                   1993:  * Results:
                   1994:  *     The leading components.
                   1995:  *
                   1996:  * Side Effects:
                   1997:  *     None.
                   1998:  *
                   1999:  *-----------------------------------------------------------------------
                   2000:  */
                   2001: char *
                   2002: Var_GetHead(file)
                   2003:     char       *file;      /* Filename to manipulate */
                   2004: {
                   2005:     return(VarModify(file, VarHead, (ClientData)0));
                   2006: }
                   2007:
                   2008: /*-
                   2009:  *-----------------------------------------------------------------------
                   2010:  * Var_Init --
                   2011:  *     Initialize the module
                   2012:  *
                   2013:  * Results:
                   2014:  *     None
                   2015:  *
                   2016:  * Side Effects:
                   2017:  *     The VAR_CMD and VAR_GLOBAL contexts are created
                   2018:  *-----------------------------------------------------------------------
                   2019:  */
                   2020: void
                   2021: Var_Init ()
                   2022: {
                   2023:     VAR_GLOBAL = Targ_NewGN ("Global");
                   2024:     VAR_CMD = Targ_NewGN ("Command");
                   2025:     allVars = Lst_Init(FALSE);
                   2026:
                   2027: }
                   2028:
                   2029:
                   2030: void
                   2031: Var_End ()
                   2032: {
                   2033:     Lst_Destroy(allVars, VarDelete);
                   2034: }
                   2035:
                   2036:
                   2037: /****************** PRINT DEBUGGING INFO *****************/
                   2038: static int
                   2039: VarPrintVar (vp, dummy)
                   2040:     ClientData vp;
                   2041:     ClientData dummy;
                   2042: {
                   2043:     Var    *v = (Var *) vp;
                   2044:     printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
                   2045:     return (dummy ? 0 : 0);
                   2046: }
                   2047:
                   2048: /*-
                   2049:  *-----------------------------------------------------------------------
                   2050:  * Var_Dump --
                   2051:  *     print all variables in a context
                   2052:  *-----------------------------------------------------------------------
                   2053:  */
                   2054: void
                   2055: Var_Dump (ctxt)
                   2056:     GNode          *ctxt;
                   2057: {
                   2058:     Lst_ForEach (ctxt->context, VarPrintVar, (ClientData) 0);
                   2059: }