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