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