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