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