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