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