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