Home | History | Annotate | Line # | Download | only in make
var.c revision 1.466
      1 /*	$NetBSD: var.c,v 1.466 2020/08/23 20:57:02 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 #ifndef MAKE_NATIVE
     72 static char rcsid[] = "$NetBSD: var.c,v 1.466 2020/08/23 20:57:02 rillig Exp $";
     73 #else
     74 #include <sys/cdefs.h>
     75 #ifndef lint
     76 #if 0
     77 static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 3/19/94";
     78 #else
     79 __RCSID("$NetBSD: var.c,v 1.466 2020/08/23 20:57:02 rillig Exp $");
     80 #endif
     81 #endif /* not lint */
     82 #endif
     83 
     84 /*-
     85  * var.c --
     86  *	Variable-handling functions
     87  *
     88  * Interface:
     89  *	Var_Set		    Set the value of a variable in the given
     90  *			    context. The variable is created if it doesn't
     91  *			    yet exist.
     92  *
     93  *	Var_Append	    Append more characters to an existing variable
     94  *			    in the given context. The variable needn't
     95  *			    exist already -- it will be created if it doesn't.
     96  *			    A space is placed between the old value and the
     97  *			    new one.
     98  *
     99  *	Var_Exists	    See if a variable exists.
    100  *
    101  *	Var_Value 	    Return the unexpanded value of a variable in a
    102  *			    context or NULL if the variable is undefined.
    103  *
    104  *	Var_Subst 	    Substitute either a single variable or all
    105  *			    variables in a string, using the given context.
    106  *
    107  *	Var_Parse 	    Parse a variable expansion from a string and
    108  *			    return the result and the number of characters
    109  *			    consumed.
    110  *
    111  *	Var_Delete	    Delete a variable in a context.
    112  *
    113  *	Var_Init  	    Initialize this module.
    114  *
    115  * Debugging:
    116  *	Var_Dump  	    Print out all variables defined in the given
    117  *			    context.
    118  *
    119  * XXX: There's a lot of duplication in these functions.
    120  */
    121 
    122 #include    <sys/stat.h>
    123 #ifndef NO_REGEX
    124 #include    <sys/types.h>
    125 #include    <regex.h>
    126 #endif
    127 #include    <inttypes.h>
    128 #include    <limits.h>
    129 #include    <time.h>
    130 
    131 #include    "make.h"
    132 #include    "enum.h"
    133 #include    "dir.h"
    134 #include    "job.h"
    135 #include    "metachar.h"
    136 
    137 #define VAR_DEBUG_IF(cond, fmt, ...)	\
    138     if (!(DEBUG(VAR) && (cond)))	\
    139 	(void) 0;			\
    140     else				\
    141 	fprintf(debug_file, fmt, __VA_ARGS__)
    142 
    143 #define VAR_DEBUG(fmt, ...) VAR_DEBUG_IF(TRUE, fmt, __VA_ARGS__)
    144 
    145 ENUM_RTTI_3(VarEvalFlags,
    146 	   VARE_UNDEFERR,
    147 	   VARE_WANTRES,
    148 	   VARE_ASSIGN);
    149 
    150 /*
    151  * This lets us tell if we have replaced the original environ
    152  * (which we cannot free).
    153  */
    154 char **savedEnv = NULL;
    155 
    156 /*
    157  * This is a harmless return value for Var_Parse that can be used by Var_Subst
    158  * to determine if there was an error in parsing -- easier than returning
    159  * a flag, as things outside this module don't give a hoot.
    160  */
    161 char var_Error[] = "";
    162 
    163 /*
    164  * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for
    165  * Var_Parse is not set. Why not just use a constant? Well, GCC likes
    166  * to condense identical string instances...
    167  */
    168 static char varNoError[] = "";
    169 
    170 /*
    171  * Traditionally we consume $$ during := like any other expansion.
    172  * Other make's do not.
    173  * This knob allows controlling the behavior.
    174  * FALSE to consume $$ during := assignment.
    175  * TRUE to preserve $$ during := assignment.
    176  */
    177 #define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
    178 static Boolean save_dollars = TRUE;
    179 
    180 /*
    181  * Internally, variables are contained in four different contexts.
    182  *	1) the environment. They cannot be changed. If an environment
    183  *	    variable is appended to, the result is placed in the global
    184  *	    context.
    185  *	2) the global context. Variables set in the Makefile are located in
    186  *	    the global context.
    187  *	3) the command-line context. All variables set on the command line
    188  *	   are placed in this context. They are UNALTERABLE once placed here.
    189  *	4) the local context. Each target has associated with it a context
    190  *	   list. On this list are located the structures describing such
    191  *	   local variables as $(@) and $(*)
    192  * The four contexts are searched in the reverse order from which they are
    193  * listed (but see checkEnvFirst).
    194  */
    195 GNode          *VAR_INTERNAL;	/* variables from make itself */
    196 GNode          *VAR_GLOBAL;	/* variables from the makefile */
    197 GNode          *VAR_CMD;	/* variables defined on the command-line */
    198 
    199 typedef enum {
    200     FIND_CMD		= 0x01,	/* look in VAR_CMD when searching */
    201     FIND_GLOBAL		= 0x02,	/* look in VAR_GLOBAL as well */
    202     FIND_ENV		= 0x04	/* look in the environment also */
    203 } VarFindFlags;
    204 
    205 typedef enum {
    206     /* The variable's value is currently being used by Var_Parse or Var_Subst.
    207      * This marker is used to avoid endless recursion. */
    208     VAR_IN_USE = 0x01,
    209     /* The variable comes from the environment.
    210      * These variables are not registered in any GNode, therefore they must
    211      * be freed as soon as they are not used anymore. */
    212     VAR_FROM_ENV = 0x02,
    213     /* The variable is a junk variable that should be destroyed when done with
    214      * it.  Used by Var_Parse for undefined, modified variables. */
    215     VAR_JUNK = 0x04,
    216     /* Variable is VAR_JUNK, but we found a use for it in some modifier and
    217      * the value is therefore valid. */
    218     VAR_KEEP = 0x08,
    219     /* The variable is exported to the environment, to be used by child
    220      * processes. */
    221     VAR_EXPORTED = 0x10,
    222     /* At the point where this variable was exported, it contained an
    223      * unresolved reference to another variable.  Before any child process is
    224      * started, it needs to be exported again, in the hope that the referenced
    225      * variable can then be resolved. */
    226     VAR_REEXPORT = 0x20,
    227     /* The variable came from command line. */
    228     VAR_FROM_CMD = 0x40,
    229     VAR_READONLY = 0x80
    230 } VarFlags;
    231 
    232 ENUM_RTTI_8(VarFlags,
    233 	    VAR_IN_USE,
    234 	    VAR_FROM_ENV,
    235 	    VAR_JUNK,
    236 	    VAR_KEEP,
    237 	    VAR_EXPORTED,
    238 	    VAR_REEXPORT,
    239 	    VAR_FROM_CMD,
    240 	    VAR_READONLY);
    241 
    242 typedef struct Var {
    243     char          *name;	/* the variable's name; it is allocated for
    244 				 * environment variables and aliased to the
    245 				 * Hash_Entry name for all other variables,
    246 				 * and thus must not be modified */
    247     Buffer	  val;		/* its value */
    248     VarFlags	  flags;    	/* miscellaneous status flags */
    249 } Var;
    250 
    251 /*
    252  * Exporting vars is expensive so skip it if we can
    253  */
    254 typedef enum {
    255     VAR_EXPORTED_NONE,
    256     VAR_EXPORTED_YES,
    257     VAR_EXPORTED_ALL
    258 } VarExportedMode;
    259 
    260 static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
    261 
    262 typedef enum {
    263     /*
    264      * We pass this to Var_Export when doing the initial export
    265      * or after updating an exported var.
    266      */
    267     VAR_EXPORT_PARENT	= 0x01,
    268     /*
    269      * We pass this to Var_Export1 to tell it to leave the value alone.
    270      */
    271     VAR_EXPORT_LITERAL	= 0x02
    272 } VarExportFlags;
    273 
    274 /* Flags for pattern matching in the :S and :C modifiers */
    275 typedef enum {
    276     VARP_SUB_GLOBAL	= 0x01,	/* Apply substitution globally */
    277     VARP_SUB_ONE	= 0x02,	/* Apply substitution to one word */
    278     VARP_ANCHOR_START	= 0x04,	/* Match at start of word */
    279     VARP_ANCHOR_END	= 0x08	/* Match at end of word */
    280 } VarPatternFlags;
    281 
    282 #define BROPEN	'{'
    283 #define BRCLOSE	'}'
    284 #define PROPEN	'('
    285 #define PRCLOSE	')'
    286 
    287 /*-
    288  *-----------------------------------------------------------------------
    289  * VarFind --
    290  *	Find the given variable in the given context and any other contexts
    291  *	indicated.
    292  *
    293  * Input:
    294  *	name		name to find
    295  *	ctxt		context in which to find it
    296  *	flags		FIND_GLOBAL	look in VAR_GLOBAL as well
    297  *			FIND_CMD	look in VAR_CMD as well
    298  *			FIND_ENV	look in the environment as well
    299  *
    300  * Results:
    301  *	A pointer to the structure describing the desired variable or
    302  *	NULL if the variable does not exist.
    303  *
    304  * Side Effects:
    305  *	None
    306  *-----------------------------------------------------------------------
    307  */
    308 static Var *
    309 VarFind(const char *name, GNode *ctxt, VarFindFlags flags)
    310 {
    311     Hash_Entry *var;
    312 
    313     /*
    314      * If the variable name begins with a '.', it could very well be one of
    315      * the local ones.  We check the name against all the local variables
    316      * and substitute the short version in for 'name' if it matches one of
    317      * them.
    318      */
    319     if (*name == '.' && isupper((unsigned char)name[1])) {
    320 	switch (name[1]) {
    321 	case 'A':
    322 	    if (strcmp(name, ".ALLSRC") == 0)
    323 		name = ALLSRC;
    324 	    if (strcmp(name, ".ARCHIVE") == 0)
    325 		name = ARCHIVE;
    326 	    break;
    327 	case 'I':
    328 	    if (strcmp(name, ".IMPSRC") == 0)
    329 		name = IMPSRC;
    330 	    break;
    331 	case 'M':
    332 	    if (strcmp(name, ".MEMBER") == 0)
    333 		name = MEMBER;
    334 	    break;
    335 	case 'O':
    336 	    if (strcmp(name, ".OODATE") == 0)
    337 		name = OODATE;
    338 	    break;
    339 	case 'P':
    340 	    if (strcmp(name, ".PREFIX") == 0)
    341 		name = PREFIX;
    342 	    break;
    343 	case 'S':
    344 	    if (strcmp(name, ".SHELL") == 0 ) {
    345 		if (!shellPath)
    346 		    Shell_Init();
    347 	    }
    348 	    break;
    349 	case 'T':
    350 	    if (strcmp(name, ".TARGET") == 0)
    351 		name = TARGET;
    352 	    break;
    353 	}
    354     }
    355 
    356 #ifdef notyet
    357     /* for compatibility with gmake */
    358     if (name[0] == '^' && name[1] == '\0')
    359 	name = ALLSRC;
    360 #endif
    361 
    362     /*
    363      * First look for the variable in the given context. If it's not there,
    364      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
    365      * depending on the FIND_* flags in 'flags'
    366      */
    367     var = Hash_FindEntry(&ctxt->context, name);
    368 
    369     if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD)
    370 	var = Hash_FindEntry(&VAR_CMD->context, name);
    371 
    372     if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) &&
    373 	ctxt != VAR_GLOBAL)
    374     {
    375 	var = Hash_FindEntry(&VAR_GLOBAL->context, name);
    376 	if (var == NULL && ctxt != VAR_INTERNAL) {
    377 	    /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
    378 	    var = Hash_FindEntry(&VAR_INTERNAL->context, name);
    379 	}
    380     }
    381 
    382     if (var == NULL && (flags & FIND_ENV)) {
    383 	char *env;
    384 
    385 	if ((env = getenv(name)) != NULL) {
    386 	    Var *v = bmake_malloc(sizeof(Var));
    387 	    size_t len;
    388 	    v->name = bmake_strdup(name);
    389 
    390 	    len = strlen(env);
    391 	    Buf_Init(&v->val, len + 1);
    392 	    Buf_AddBytes(&v->val, env, len);
    393 
    394 	    v->flags = VAR_FROM_ENV;
    395 	    return v;
    396 	}
    397 
    398 	if (checkEnvFirst && (flags & FIND_GLOBAL) && ctxt != VAR_GLOBAL) {
    399 	    var = Hash_FindEntry(&VAR_GLOBAL->context, name);
    400 	    if (var == NULL && ctxt != VAR_INTERNAL)
    401 		var = Hash_FindEntry(&VAR_INTERNAL->context, name);
    402 	    if (var == NULL)
    403 		return NULL;
    404 	    else
    405 		return (Var *)Hash_GetValue(var);
    406 	}
    407 
    408 	return NULL;
    409     }
    410 
    411     if (var == NULL)
    412 	return NULL;
    413     else
    414 	return (Var *)Hash_GetValue(var);
    415 }
    416 
    417 /*-
    418  *-----------------------------------------------------------------------
    419  * VarFreeEnv  --
    420  *	If the variable is an environment variable, free it
    421  *
    422  * Input:
    423  *	v		the variable
    424  *	destroy		true if the value buffer should be destroyed.
    425  *
    426  * Results:
    427  *	TRUE if it is an environment variable, FALSE otherwise.
    428  *-----------------------------------------------------------------------
    429  */
    430 static Boolean
    431 VarFreeEnv(Var *v, Boolean destroy)
    432 {
    433     if (!(v->flags & VAR_FROM_ENV))
    434 	return FALSE;
    435     free(v->name);
    436     Buf_Destroy(&v->val, destroy);
    437     free(v);
    438     return TRUE;
    439 }
    440 
    441 /* Add a new variable of the given name and value to the given context.
    442  * The name and val arguments are duplicated so they may safely be freed. */
    443 static void
    444 VarAdd(const char *name, const char *val, GNode *ctxt, VarSet_Flags flags)
    445 {
    446     Var *v = bmake_malloc(sizeof(Var));
    447     size_t len = strlen(val);
    448     Hash_Entry *he;
    449 
    450     Buf_Init(&v->val, len + 1);
    451     Buf_AddBytes(&v->val, val, len);
    452 
    453     v->flags = 0;
    454     if (flags & VAR_SET_READONLY)
    455 	v->flags |= VAR_READONLY;
    456 
    457     he = Hash_CreateEntry(&ctxt->context, name, NULL);
    458     Hash_SetValue(he, v);
    459     v->name = he->name;
    460     VAR_DEBUG_IF(!(ctxt->flags & INTERNAL),
    461 		 "%s:%s = %s\n", ctxt->name, name, val);
    462 }
    463 
    464 /* Remove a variable from a context, freeing the Var structure as well. */
    465 void
    466 Var_Delete(const char *name, GNode *ctxt)
    467 {
    468     char *name_freeIt = NULL;
    469     Hash_Entry *he;
    470 
    471     if (strchr(name, '$') != NULL)
    472 	name = name_freeIt = Var_Subst(name, VAR_GLOBAL, VARE_WANTRES);
    473     he = Hash_FindEntry(&ctxt->context, name);
    474     VAR_DEBUG("%s:delete %s%s\n",
    475 	      ctxt->name, name, he != NULL ? "" : " (not found)");
    476     free(name_freeIt);
    477 
    478     if (he != NULL) {
    479 	Var *v = (Var *)Hash_GetValue(he);
    480 	if (v->flags & VAR_EXPORTED)
    481 	    unsetenv(v->name);
    482 	if (strcmp(v->name, MAKE_EXPORTED) == 0)
    483 	    var_exportedVars = VAR_EXPORTED_NONE;
    484 	if (v->name != he->name)
    485 	    free(v->name);
    486 	Hash_DeleteEntry(&ctxt->context, he);
    487 	Buf_Destroy(&v->val, TRUE);
    488 	free(v);
    489     }
    490 }
    491 
    492 
    493 /*
    494  * Export a single variable.
    495  * We ignore make internal variables (those which start with '.').
    496  * Also we jump through some hoops to avoid calling setenv
    497  * more than necessary since it can leak.
    498  * We only manipulate flags of vars if 'parent' is set.
    499  */
    500 static Boolean
    501 Var_Export1(const char *name, VarExportFlags flags)
    502 {
    503     VarExportFlags parent = flags & VAR_EXPORT_PARENT;
    504     Var *v;
    505     char *val;
    506 
    507     if (name[0] == '.')
    508 	return FALSE;		/* skip internals */
    509     if (name[1] == '\0') {
    510 	/*
    511 	 * A single char.
    512 	 * If it is one of the vars that should only appear in
    513 	 * local context, skip it, else we can get Var_Subst
    514 	 * into a loop.
    515 	 */
    516 	switch (name[0]) {
    517 	case '@':
    518 	case '%':
    519 	case '*':
    520 	case '!':
    521 	    return FALSE;
    522 	}
    523     }
    524 
    525     v = VarFind(name, VAR_GLOBAL, 0);
    526     if (v == NULL)
    527 	return FALSE;
    528 
    529     if (!parent && (v->flags & VAR_EXPORTED) && !(v->flags & VAR_REEXPORT))
    530 	return FALSE;		/* nothing to do */
    531 
    532     val = Buf_GetAll(&v->val, NULL);
    533     if (!(flags & VAR_EXPORT_LITERAL) && strchr(val, '$') != NULL) {
    534 	char *expr;
    535 
    536 	if (parent) {
    537 	    /*
    538 	     * Flag this as something we need to re-export.
    539 	     * No point actually exporting it now though,
    540 	     * the child can do it at the last minute.
    541 	     */
    542 	    v->flags |= VAR_EXPORTED | VAR_REEXPORT;
    543 	    return TRUE;
    544 	}
    545 	if (v->flags & VAR_IN_USE) {
    546 	    /*
    547 	     * We recursed while exporting in a child.
    548 	     * This isn't going to end well, just skip it.
    549 	     */
    550 	    return FALSE;
    551 	}
    552 
    553 	expr = str_concat3("${", name, "}");
    554 	val = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
    555 	setenv(name, val, 1);
    556 	free(val);
    557 	free(expr);
    558     } else {
    559 	if (parent)
    560 	    v->flags &= ~(unsigned)VAR_REEXPORT;	/* once will do */
    561 	if (parent || !(v->flags & VAR_EXPORTED))
    562 	    setenv(name, val, 1);
    563     }
    564     /*
    565      * This is so Var_Set knows to call Var_Export again...
    566      */
    567     if (parent) {
    568 	v->flags |= VAR_EXPORTED;
    569     }
    570     return TRUE;
    571 }
    572 
    573 static void
    574 Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED)
    575 {
    576     Var *var = entry;
    577     Var_Export1(var->name, 0);
    578 }
    579 
    580 /*
    581  * This gets called from our children.
    582  */
    583 void
    584 Var_ExportVars(void)
    585 {
    586     char *val;
    587 
    588     /*
    589      * Several make's support this sort of mechanism for tracking
    590      * recursion - but each uses a different name.
    591      * We allow the makefiles to update MAKELEVEL and ensure
    592      * children see a correctly incremented value.
    593      */
    594     char tmp[BUFSIZ];
    595     snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
    596     setenv(MAKE_LEVEL_ENV, tmp, 1);
    597 
    598     if (var_exportedVars == VAR_EXPORTED_NONE)
    599 	return;
    600 
    601     if (var_exportedVars == VAR_EXPORTED_ALL) {
    602 	/* Ouch! This is crazy... */
    603 	Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL);
    604 	return;
    605     }
    606 
    607     val = Var_Subst("${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL, VARE_WANTRES);
    608     if (*val) {
    609 	char **av;
    610 	char *as;
    611 	size_t ac;
    612 	size_t i;
    613 
    614 	av = brk_string(val, FALSE, &ac, &as);
    615 	for (i = 0; i < ac; i++)
    616 	    Var_Export1(av[i], 0);
    617 	free(as);
    618 	free(av);
    619     }
    620     free(val);
    621 }
    622 
    623 /*
    624  * This is called when .export is seen or .MAKE.EXPORTED is modified.
    625  *
    626  * It is also called when any exported variable is modified.
    627  * XXX: Is it really?
    628  *
    629  * str has the format "[-env|-literal] varname...".
    630  */
    631 void
    632 Var_Export(const char *str, Boolean isExport)
    633 {
    634     VarExportFlags flags;
    635     char *val;
    636 
    637     if (isExport && str[0] == '\0') {
    638 	var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
    639 	return;
    640     }
    641 
    642     flags = 0;
    643     if (strncmp(str, "-env", 4) == 0) {
    644 	str += 4;
    645     } else if (strncmp(str, "-literal", 8) == 0) {
    646 	str += 8;
    647 	flags |= VAR_EXPORT_LITERAL;
    648     } else {
    649 	flags |= VAR_EXPORT_PARENT;
    650     }
    651 
    652     val = Var_Subst(str, VAR_GLOBAL, VARE_WANTRES);
    653     if (val[0] != '\0') {
    654 	char *as;
    655 	size_t ac;
    656 	char **av = brk_string(val, FALSE, &ac, &as);
    657 
    658 	size_t i;
    659 	for (i = 0; i < ac; i++) {
    660 	    const char *name = av[i];
    661 	    if (Var_Export1(name, flags)) {
    662 		if (var_exportedVars != VAR_EXPORTED_ALL)
    663 		    var_exportedVars = VAR_EXPORTED_YES;
    664 		if (isExport && (flags & VAR_EXPORT_PARENT)) {
    665 		    Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
    666 		}
    667 	    }
    668 	}
    669 	free(as);
    670 	free(av);
    671     }
    672     free(val);
    673 }
    674 
    675 
    676 extern char **environ;
    677 
    678 /*
    679  * This is called when .unexport[-env] is seen.
    680  *
    681  * str must have the form "unexport[-env] varname...".
    682  */
    683 void
    684 Var_UnExport(const char *str)
    685 {
    686     const char *varnames;
    687     char *varnames_freeIt;
    688     Boolean unexport_env;
    689 
    690     varnames = NULL;
    691     varnames_freeIt = NULL;
    692 
    693     str += strlen("unexport");
    694     unexport_env = strncmp(str, "-env", 4) == 0;
    695     if (unexport_env) {
    696 	const char *cp;
    697 	char **newenv;
    698 
    699 	cp = getenv(MAKE_LEVEL_ENV);	/* we should preserve this */
    700 	if (environ == savedEnv) {
    701 	    /* we have been here before! */
    702 	    newenv = bmake_realloc(environ, 2 * sizeof(char *));
    703 	} else {
    704 	    if (savedEnv) {
    705 		free(savedEnv);
    706 		savedEnv = NULL;
    707 	    }
    708 	    newenv = bmake_malloc(2 * sizeof(char *));
    709 	}
    710 
    711 	/* Note: we cannot safely free() the original environ. */
    712 	environ = savedEnv = newenv;
    713 	newenv[0] = NULL;
    714 	newenv[1] = NULL;
    715 	if (cp && *cp)
    716 	    setenv(MAKE_LEVEL_ENV, cp, 1);
    717     } else {
    718 	for (; isspace((unsigned char)*str); str++)
    719 	    continue;
    720 	if (str[0] != '\0')
    721 	    varnames = str;
    722     }
    723 
    724     if (varnames == NULL) {
    725 	/* Using .MAKE.EXPORTED */
    726 	varnames = varnames_freeIt = Var_Subst("${" MAKE_EXPORTED ":O:u}",
    727 					       VAR_GLOBAL, VARE_WANTRES);
    728     }
    729 
    730     if (TRUE) {
    731 	Var *v;
    732 	char **av;
    733 	char *as;
    734 	size_t ac;
    735 	size_t i;
    736 
    737 	av = brk_string(varnames, FALSE, &ac, &as);
    738 	for (i = 0; i < ac; i++) {
    739 	    v = VarFind(av[i], VAR_GLOBAL, 0);
    740 	    if (v == NULL) {
    741 		VAR_DEBUG("Not unexporting \"%s\" (not found)\n", av[i]);
    742 		continue;
    743 	    }
    744 
    745 	    VAR_DEBUG("Unexporting \"%s\"\n", av[i]);
    746 	    if (!unexport_env && (v->flags & VAR_EXPORTED) &&
    747 		!(v->flags & VAR_REEXPORT))
    748 		unsetenv(v->name);
    749 	    v->flags &= ~(unsigned)(VAR_EXPORTED | VAR_REEXPORT);
    750 
    751 	    /*
    752 	     * If we are unexporting a list,
    753 	     * remove each one from .MAKE.EXPORTED.
    754 	     * If we are removing them all,
    755 	     * just delete .MAKE.EXPORTED below.
    756 	     */
    757 	    if (varnames == str) {
    758 		char *expr = str_concat3("${" MAKE_EXPORTED ":N", v->name, "}");
    759 		char *cp = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
    760 		Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL);
    761 		free(cp);
    762 		free(expr);
    763 	    }
    764 	}
    765 	free(as);
    766 	free(av);
    767 	if (varnames != str) {
    768 	    Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
    769 	    free(varnames_freeIt);
    770 	}
    771     }
    772 }
    773 
    774 /* See Var_Set for documentation. */
    775 void
    776 Var_Set_with_flags(const char *name, const char *val, GNode *ctxt,
    777 		   VarSet_Flags flags)
    778 {
    779     const char *unexpanded_name = name;
    780     char *name_freeIt = NULL;
    781     Var *v;
    782 
    783     assert(val != NULL);
    784 
    785     /*
    786      * We only look for a variable in the given context since anything set
    787      * here will override anything in a lower context, so there's not much
    788      * point in searching them all just to save a bit of memory...
    789      */
    790     if (strchr(name, '$') != NULL)
    791 	name = name_freeIt = Var_Subst(name, ctxt, VARE_WANTRES);
    792 
    793     if (name[0] == '\0') {
    794 	VAR_DEBUG("Var_Set(\"%s\", \"%s\", ...) "
    795 		  "name expands to empty string - ignored\n",
    796 		  unexpanded_name, val);
    797 	free(name_freeIt);
    798 	return;
    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, flags);
    823     } else {
    824 	if ((v->flags & VAR_READONLY) && !(flags & VAR_SET_READONLY)) {
    825 	    VAR_DEBUG("%s:%s = %s ignored (read-only)\n",
    826 	      ctxt->name, name, val);
    827 	    goto out;
    828 	}
    829 	Buf_Empty(&v->val);
    830 	if (val)
    831 	    Buf_AddStr(&v->val, val);
    832 
    833 	VAR_DEBUG("%s:%s = %s\n", ctxt->name, name, val);
    834 	if (v->flags & VAR_EXPORTED) {
    835 	    Var_Export1(name, VAR_EXPORT_PARENT);
    836 	}
    837     }
    838     /*
    839      * Any variables given on the command line are automatically exported
    840      * to the environment (as per POSIX standard)
    841      * Other than internals.
    842      */
    843     if (ctxt == VAR_CMD && !(flags & VAR_NO_EXPORT) && name[0] != '.') {
    844 	if (v == NULL) {
    845 	    /* we just added it */
    846 	    v = VarFind(name, ctxt, 0);
    847 	}
    848 	if (v != NULL)
    849 	    v->flags |= VAR_FROM_CMD;
    850 	/*
    851 	 * If requested, don't export these in the environment
    852 	 * individually.  We still put them in MAKEOVERRIDES so
    853 	 * that the command-line settings continue to override
    854 	 * Makefile settings.
    855 	 */
    856 	if (!varNoExportEnv)
    857 	    setenv(name, val ? val : "", 1);
    858 
    859 	Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
    860     }
    861     if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0)
    862 	save_dollars = s2Boolean(val, save_dollars);
    863 
    864 out:
    865     free(name_freeIt);
    866     if (v != NULL)
    867 	VarFreeEnv(v, TRUE);
    868 }
    869 
    870 /*-
    871  *-----------------------------------------------------------------------
    872  * Var_Set --
    873  *	Set the variable name to the value val in the given context.
    874  *
    875  * Input:
    876  *	name		name of variable to set
    877  *	val		value to give to the variable
    878  *	ctxt		context in which to set it
    879  *
    880  * Side Effects:
    881  *	If the variable doesn't yet exist, it is created.
    882  *	Otherwise the new value overwrites and replaces the old value.
    883  *
    884  * Notes:
    885  *	The variable is searched for only in its context before being
    886  *	created in that context. I.e. if the context is VAR_GLOBAL,
    887  *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
    888  *	VAR_CMD->context is searched. This is done to avoid the literally
    889  *	thousands of unnecessary strcmp's that used to be done to
    890  *	set, say, $(@) or $(<).
    891  *	If the context is VAR_GLOBAL though, we check if the variable
    892  *	was set in VAR_CMD from the command line and skip it if so.
    893  *-----------------------------------------------------------------------
    894  */
    895 void
    896 Var_Set(const char *name, const char *val, GNode *ctxt)
    897 {
    898     Var_Set_with_flags(name, val, ctxt, 0);
    899 }
    900 
    901 /*-
    902  *-----------------------------------------------------------------------
    903  * Var_Append --
    904  *	The variable of the given name has the given value appended to it in
    905  *	the given context.
    906  *
    907  * Input:
    908  *	name		name of variable to modify
    909  *	val		string to append to it
    910  *	ctxt		context in which this should occur
    911  *
    912  * Side Effects:
    913  *	If the variable doesn't exist, it is created. Otherwise the strings
    914  *	are concatenated, with a space in between.
    915  *
    916  * Notes:
    917  *	Only if the variable is being sought in the global context is the
    918  *	environment searched.
    919  *	XXX: Knows its calling circumstances in that if called with ctxt
    920  *	an actual target, it will only search that context since only
    921  *	a local variable could be being appended to. This is actually
    922  *	a big win and must be tolerated.
    923  *-----------------------------------------------------------------------
    924  */
    925 void
    926 Var_Append(const char *name, const char *val, GNode *ctxt)
    927 {
    928     char *name_freeIt = NULL;
    929     Var *v;
    930 
    931     assert(val != NULL);
    932 
    933     if (strchr(name, '$') != NULL) {
    934 	const char *unexpanded_name = name;
    935 	name = name_freeIt = Var_Subst(name, ctxt, VARE_WANTRES);
    936 	if (name[0] == '\0') {
    937 	    VAR_DEBUG("Var_Append(\"%s\", \"%s\", ...) "
    938 		      "name expands to empty string - ignored\n",
    939 		      unexpanded_name, val);
    940 	    free(name_freeIt);
    941 	    return;
    942 	}
    943     }
    944 
    945     v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0);
    946 
    947     if (v == NULL) {
    948 	Var_Set(name, val, ctxt);
    949     } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) {
    950 	Buf_AddByte(&v->val, ' ');
    951 	Buf_AddStr(&v->val, val);
    952 
    953 	VAR_DEBUG("%s:%s = %s\n", ctxt->name, name,
    954 		  Buf_GetAll(&v->val, NULL));
    955 
    956 	if (v->flags & VAR_FROM_ENV) {
    957 	    Hash_Entry *h;
    958 
    959 	    /*
    960 	     * If the original variable came from the environment, we
    961 	     * have to install it in the global context (we could place
    962 	     * it in the environment, but then we should provide a way to
    963 	     * export other variables...)
    964 	     */
    965 	    v->flags &= ~(unsigned)VAR_FROM_ENV;
    966 	    h = Hash_CreateEntry(&ctxt->context, name, NULL);
    967 	    Hash_SetValue(h, v);
    968 	}
    969     }
    970     free(name_freeIt);
    971 }
    972 
    973 /*-
    974  *-----------------------------------------------------------------------
    975  * Var_Exists --
    976  *	See if the given variable exists.
    977  *
    978  * Input:
    979  *	name		Variable to find
    980  *	ctxt		Context in which to start search
    981  *
    982  * Results:
    983  *	TRUE if it does, FALSE if it doesn't
    984  *
    985  * Side Effects:
    986  *	None.
    987  *
    988  *-----------------------------------------------------------------------
    989  */
    990 Boolean
    991 Var_Exists(const char *name, GNode *ctxt)
    992 {
    993     char *name_freeIt = NULL;
    994     Var *v;
    995 
    996     if (strchr(name, '$') != NULL)
    997 	name = name_freeIt = Var_Subst(name, ctxt, VARE_WANTRES);
    998 
    999     v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
   1000     free(name_freeIt);
   1001     if (v == NULL)
   1002 	return FALSE;
   1003 
   1004     (void)VarFreeEnv(v, TRUE);
   1005     return TRUE;
   1006 }
   1007 
   1008 /*-
   1009  *-----------------------------------------------------------------------
   1010  * Var_Value --
   1011  *	Return the unexpanded value of the given variable in the given
   1012  *	context, or the usual contexts.
   1013  *
   1014  * Input:
   1015  *	name		name to find
   1016  *	ctxt		context in which to search for it
   1017  *
   1018  * Results:
   1019  *	The value if the variable exists, NULL if it doesn't.
   1020  *	If the returned value is not NULL, the caller must free *freeIt
   1021  *	as soon as the returned value is no longer needed.
   1022  *-----------------------------------------------------------------------
   1023  */
   1024 const char *
   1025 Var_Value(const char *name, GNode *ctxt, char **freeIt)
   1026 {
   1027     Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1028     char *p;
   1029 
   1030     *freeIt = NULL;
   1031     if (v == NULL)
   1032 	return NULL;
   1033 
   1034     p = Buf_GetAll(&v->val, NULL);
   1035     if (VarFreeEnv(v, FALSE))
   1036 	*freeIt = p;
   1037     return p;
   1038 }
   1039 
   1040 
   1041 /* SepBuf is a string being built from "words", interleaved with separators. */
   1042 typedef struct {
   1043     Buffer buf;
   1044     Boolean needSep;
   1045     char sep;			/* usually ' ', but see the :ts modifier */
   1046 } SepBuf;
   1047 
   1048 static void
   1049 SepBuf_Init(SepBuf *buf, char sep)
   1050 {
   1051     Buf_Init(&buf->buf, 32 /* bytes */);
   1052     buf->needSep = FALSE;
   1053     buf->sep = sep;
   1054 }
   1055 
   1056 static void
   1057 SepBuf_Sep(SepBuf *buf)
   1058 {
   1059     buf->needSep = TRUE;
   1060 }
   1061 
   1062 static void
   1063 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
   1064 {
   1065     if (mem_size == 0)
   1066 	return;
   1067     if (buf->needSep && buf->sep != '\0') {
   1068 	Buf_AddByte(&buf->buf, buf->sep);
   1069 	buf->needSep = FALSE;
   1070     }
   1071     Buf_AddBytes(&buf->buf, mem, mem_size);
   1072 }
   1073 
   1074 static void
   1075 SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
   1076 {
   1077     SepBuf_AddBytes(buf, start, (size_t)(end - start));
   1078 }
   1079 
   1080 static void
   1081 SepBuf_AddStr(SepBuf *buf, const char *str)
   1082 {
   1083     SepBuf_AddBytes(buf, str, strlen(str));
   1084 }
   1085 
   1086 static char *
   1087 SepBuf_Destroy(SepBuf *buf, Boolean free_buf)
   1088 {
   1089     return Buf_Destroy(&buf->buf, free_buf);
   1090 }
   1091 
   1092 
   1093 /* This callback for ModifyWords gets a single word from an expression and
   1094  * typically adds a modification of this word to the buffer. It may also do
   1095  * nothing or add several words. */
   1096 typedef void (*ModifyWordsCallback)(const char *word, SepBuf *buf, void *data);
   1097 
   1098 
   1099 /* Callback for ModifyWords to implement the :H modifier.
   1100  * Add the dirname of the given word to the buffer. */
   1101 static void
   1102 ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1103 {
   1104     const char *slash = strrchr(word, '/');
   1105     if (slash != NULL)
   1106 	SepBuf_AddBytesBetween(buf, word, slash);
   1107     else
   1108 	SepBuf_AddStr(buf, ".");
   1109 }
   1110 
   1111 /* Callback for ModifyWords to implement the :T modifier.
   1112  * Add the basename of the given word to the buffer. */
   1113 static void
   1114 ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1115 {
   1116     const char *slash = strrchr(word, '/');
   1117     const char *base = slash != NULL ? slash + 1 : word;
   1118     SepBuf_AddStr(buf, base);
   1119 }
   1120 
   1121 /* Callback for ModifyWords to implement the :E modifier.
   1122  * Add the filename suffix of the given word to the buffer, if it exists. */
   1123 static void
   1124 ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1125 {
   1126     const char *dot = strrchr(word, '.');
   1127     if (dot != NULL)
   1128 	SepBuf_AddStr(buf, dot + 1);
   1129 }
   1130 
   1131 /* Callback for ModifyWords to implement the :R modifier.
   1132  * Add the basename of the given word to the buffer. */
   1133 static void
   1134 ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1135 {
   1136     const char *dot = strrchr(word, '.');
   1137     size_t len = dot != NULL ? (size_t)(dot - word) : strlen(word);
   1138     SepBuf_AddBytes(buf, word, len);
   1139 }
   1140 
   1141 /* Callback for ModifyWords to implement the :M modifier.
   1142  * Place the word in the buffer if it matches the given pattern. */
   1143 static void
   1144 ModifyWord_Match(const char *word, SepBuf *buf, void *data)
   1145 {
   1146     const char *pattern = data;
   1147     VAR_DEBUG("VarMatch [%s] [%s]\n", word, pattern);
   1148     if (Str_Match(word, pattern))
   1149 	SepBuf_AddStr(buf, word);
   1150 }
   1151 
   1152 /* Callback for ModifyWords to implement the :N modifier.
   1153  * Place the word in the buffer if it doesn't match the given pattern. */
   1154 static void
   1155 ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data)
   1156 {
   1157     const char *pattern = data;
   1158     if (!Str_Match(word, pattern))
   1159 	SepBuf_AddStr(buf, word);
   1160 }
   1161 
   1162 #ifdef SYSVVARSUB
   1163 /*-
   1164  *-----------------------------------------------------------------------
   1165  * Str_SYSVMatch --
   1166  *	Check word against pattern for a match (% is wild),
   1167  *
   1168  * Input:
   1169  *	word		Word to examine
   1170  *	pattern		Pattern to examine against
   1171  *
   1172  * Results:
   1173  *	Returns the start of the match, or NULL.
   1174  *	*match_len returns the length of the match, if any.
   1175  *	*hasPercent returns whether the pattern contains a percent.
   1176  *-----------------------------------------------------------------------
   1177  */
   1178 static const char *
   1179 Str_SYSVMatch(const char *word, const char *pattern, size_t *match_len,
   1180 	      Boolean *hasPercent)
   1181 {
   1182     const char *p = pattern;
   1183     const char *w = word;
   1184     const char *percent;
   1185     size_t w_len;
   1186     size_t p_len;
   1187     const char *w_tail;
   1188 
   1189     *hasPercent = FALSE;
   1190     if (*p == '\0') {		/* ${VAR:=suffix} */
   1191 	*match_len = strlen(w);	/* Null pattern is the whole string */
   1192 	return w;
   1193     }
   1194 
   1195     percent = strchr(p, '%');
   1196     if (percent != NULL) {	/* ${VAR:...%...=...} */
   1197 	*hasPercent = TRUE;
   1198 	if (*w == '\0')
   1199 	    return NULL;	/* empty word does not match pattern */
   1200 
   1201 	/* check that the prefix matches */
   1202 	for (; p != percent && *w != '\0' && *w == *p; w++, p++)
   1203 	    continue;
   1204 	if (p != percent)
   1205 	    return NULL;	/* No match */
   1206 
   1207 	p++;			/* Skip the percent */
   1208 	if (*p == '\0') {
   1209 	    /* No more pattern, return the rest of the string */
   1210 	    *match_len = strlen(w);
   1211 	    return w;
   1212 	}
   1213     }
   1214 
   1215     /* Test whether the tail matches */
   1216     w_len = strlen(w);
   1217     p_len = strlen(p);
   1218     if (w_len < p_len)
   1219 	return NULL;
   1220 
   1221     w_tail = w + w_len - p_len;
   1222     if (memcmp(p, w_tail, p_len) != 0)
   1223 	return NULL;
   1224 
   1225     *match_len = (size_t)(w_tail - w);
   1226     return w;
   1227 }
   1228 
   1229 typedef struct {
   1230     GNode *ctx;
   1231     const char *lhs;
   1232     const char *rhs;
   1233 } ModifyWord_SYSVSubstArgs;
   1234 
   1235 /* Callback for ModifyWords to implement the :%.from=%.to modifier. */
   1236 static void
   1237 ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data)
   1238 {
   1239     const ModifyWord_SYSVSubstArgs *args = data;
   1240     char *rhs_expanded;
   1241     const char *rhs;
   1242     const char *percent;
   1243 
   1244     size_t match_len;
   1245     Boolean lhsPercent;
   1246     const char *match = Str_SYSVMatch(word, args->lhs, &match_len, &lhsPercent);
   1247     if (match == NULL) {
   1248 	SepBuf_AddStr(buf, word);
   1249 	return;
   1250     }
   1251 
   1252     /* Append rhs to the buffer, substituting the first '%' with the
   1253      * match, but only if the lhs had a '%' as well. */
   1254 
   1255     rhs_expanded = Var_Subst(args->rhs, args->ctx, VARE_WANTRES);
   1256 
   1257     rhs = rhs_expanded;
   1258     percent = strchr(rhs, '%');
   1259 
   1260     if (percent != NULL && lhsPercent) {
   1261 	/* Copy the prefix of the replacement pattern */
   1262 	SepBuf_AddBytesBetween(buf, rhs, percent);
   1263 	rhs = percent + 1;
   1264     }
   1265     if (percent != NULL || !lhsPercent)
   1266 	SepBuf_AddBytes(buf, match, match_len);
   1267 
   1268     /* Append the suffix of the replacement pattern */
   1269     SepBuf_AddStr(buf, rhs);
   1270 
   1271     free(rhs_expanded);
   1272 }
   1273 #endif
   1274 
   1275 
   1276 typedef struct {
   1277     const char	*lhs;
   1278     size_t	lhsLen;
   1279     const char	*rhs;
   1280     size_t	rhsLen;
   1281     VarPatternFlags pflags;
   1282     Boolean	matched;
   1283 } ModifyWord_SubstArgs;
   1284 
   1285 /* Callback for ModifyWords to implement the :S,from,to, modifier.
   1286  * Perform a string substitution on the given word. */
   1287 static void
   1288 ModifyWord_Subst(const char *word, SepBuf *buf, void *data)
   1289 {
   1290     size_t wordLen = strlen(word);
   1291     ModifyWord_SubstArgs *args = data;
   1292     const char *match;
   1293 
   1294     if ((args->pflags & VARP_SUB_ONE) && args->matched)
   1295 	goto nosub;
   1296 
   1297     if (args->pflags & VARP_ANCHOR_START) {
   1298 	if (wordLen < args->lhsLen ||
   1299 	    memcmp(word, args->lhs, args->lhsLen) != 0)
   1300 	    goto nosub;
   1301 
   1302 	if (args->pflags & VARP_ANCHOR_END) {
   1303 	    if (wordLen != args->lhsLen)
   1304 		goto nosub;
   1305 
   1306 	    SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1307 	    args->matched = TRUE;
   1308 	} else {
   1309 	    SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1310 	    SepBuf_AddBytes(buf, word + args->lhsLen, wordLen - args->lhsLen);
   1311 	    args->matched = TRUE;
   1312 	}
   1313 	return;
   1314     }
   1315 
   1316     if (args->pflags & VARP_ANCHOR_END) {
   1317 	const char *start;
   1318 
   1319 	if (wordLen < args->lhsLen)
   1320 	    goto nosub;
   1321 
   1322 	start = word + (wordLen - args->lhsLen);
   1323 	if (memcmp(start, args->lhs, args->lhsLen) != 0)
   1324 	    goto nosub;
   1325 
   1326 	SepBuf_AddBytesBetween(buf, word, start);
   1327 	SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1328 	args->matched = TRUE;
   1329 	return;
   1330     }
   1331 
   1332     /* unanchored case, may match more than once */
   1333     while ((match = Str_FindSubstring(word, args->lhs)) != NULL) {
   1334 	SepBuf_AddBytesBetween(buf, word, match);
   1335 	SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1336 	args->matched = TRUE;
   1337 	wordLen -= (size_t)(match - word) + args->lhsLen;
   1338 	word += (size_t)(match - word) + args->lhsLen;
   1339 	if (wordLen == 0 || !(args->pflags & VARP_SUB_GLOBAL))
   1340 	    break;
   1341     }
   1342 nosub:
   1343     SepBuf_AddBytes(buf, word, wordLen);
   1344 }
   1345 
   1346 #ifndef NO_REGEX
   1347 /* Print the error caused by a regcomp or regexec call. */
   1348 static void
   1349 VarREError(int reerr, regex_t *pat, const char *str)
   1350 {
   1351     size_t errlen = regerror(reerr, pat, 0, 0);
   1352     char *errbuf = bmake_malloc(errlen);
   1353     regerror(reerr, pat, errbuf, errlen);
   1354     Error("%s: %s", str, errbuf);
   1355     free(errbuf);
   1356 }
   1357 
   1358 typedef struct {
   1359     regex_t	   re;
   1360     size_t	   nsub;
   1361     char 	  *replace;
   1362     VarPatternFlags pflags;
   1363     Boolean	   matched;
   1364 } ModifyWord_SubstRegexArgs;
   1365 
   1366 /* Callback for ModifyWords to implement the :C/from/to/ modifier.
   1367  * Perform a regex substitution on the given word. */
   1368 static void
   1369 ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
   1370 {
   1371     ModifyWord_SubstRegexArgs *args = data;
   1372     int xrv;
   1373     const char *wp = word;
   1374     char *rp;
   1375     int flags = 0;
   1376     regmatch_t m[10];
   1377 
   1378     if ((args->pflags & VARP_SUB_ONE) && args->matched)
   1379 	goto nosub;
   1380 
   1381 tryagain:
   1382     xrv = regexec(&args->re, wp, args->nsub, m, flags);
   1383 
   1384     switch (xrv) {
   1385     case 0:
   1386 	args->matched = TRUE;
   1387 	SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
   1388 
   1389 	for (rp = args->replace; *rp; rp++) {
   1390 	    if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
   1391 		SepBuf_AddBytes(buf, rp + 1, 1);
   1392 		rp++;
   1393 		continue;
   1394 	    }
   1395 
   1396 	    if (*rp == '&') {
   1397 		SepBuf_AddBytesBetween(buf, wp + m[0].rm_so, wp + m[0].rm_eo);
   1398 		continue;
   1399 	    }
   1400 
   1401 	    if (*rp != '\\' || !isdigit((unsigned char)rp[1])) {
   1402 		SepBuf_AddBytes(buf, rp, 1);
   1403 		continue;
   1404 	    }
   1405 
   1406 	    {			/* \0 to \9 backreference */
   1407 		size_t n = (size_t)(rp[1] - '0');
   1408 		rp++;
   1409 
   1410 		if (n >= args->nsub) {
   1411 		    Error("No subexpression \\%zu", n);
   1412 		} else if (m[n].rm_so == -1 && m[n].rm_eo == -1) {
   1413 		    Error("No match for subexpression \\%zu", n);
   1414 		} else {
   1415 		    SepBuf_AddBytesBetween(buf, wp + m[n].rm_so,
   1416 					   wp + m[n].rm_eo);
   1417 		}
   1418 	    }
   1419 	}
   1420 
   1421 	wp += m[0].rm_eo;
   1422 	if (args->pflags & VARP_SUB_GLOBAL) {
   1423 	    flags |= REG_NOTBOL;
   1424 	    if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
   1425 		SepBuf_AddBytes(buf, wp, 1);
   1426 		wp++;
   1427 	    }
   1428 	    if (*wp)
   1429 		goto tryagain;
   1430 	}
   1431 	if (*wp) {
   1432 	    SepBuf_AddStr(buf, wp);
   1433 	}
   1434 	break;
   1435     default:
   1436 	VarREError(xrv, &args->re, "Unexpected regex error");
   1437 	/* fall through */
   1438     case REG_NOMATCH:
   1439     nosub:
   1440 	SepBuf_AddStr(buf, wp);
   1441 	break;
   1442     }
   1443 }
   1444 #endif
   1445 
   1446 
   1447 typedef struct {
   1448     GNode	*ctx;
   1449     char	*tvar;		/* name of temporary variable */
   1450     char	*str;		/* string to expand */
   1451     VarEvalFlags eflags;
   1452 } ModifyWord_LoopArgs;
   1453 
   1454 /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
   1455 static void
   1456 ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
   1457 {
   1458     const ModifyWord_LoopArgs *args;
   1459     char *s;
   1460 
   1461     if (word[0] == '\0')
   1462 	return;
   1463 
   1464     args = data;
   1465     Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT);
   1466     s = Var_Subst(args->str, args->ctx, args->eflags);
   1467 
   1468     VAR_DEBUG("ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" "
   1469 	      "to \"%s\"\n",
   1470 	      word, args->tvar, args->str, s ? s : "(null)");
   1471 
   1472     if (s != NULL && s[0] != '\0') {
   1473 	if (s[0] == '\n' || (buf->buf.count > 0 &&
   1474 			     buf->buf.buffer[buf->buf.count - 1] == '\n'))
   1475 	    buf->needSep = FALSE;
   1476 	SepBuf_AddStr(buf, s);
   1477     }
   1478     free(s);
   1479 }
   1480 
   1481 
   1482 /*-
   1483  * Implements the :[first..last] modifier.
   1484  * This is a special case of ModifyWords since we want to be able
   1485  * to scan the list backwards if first > last.
   1486  */
   1487 static char *
   1488 VarSelectWords(char sep, Boolean oneBigWord, const char *str, int first,
   1489 	       int last)
   1490 {
   1491     char **av;			/* word list */
   1492     char *as;			/* word list memory */
   1493     size_t ac;
   1494     int start, end, step;
   1495     int i;
   1496 
   1497     SepBuf buf;
   1498     SepBuf_Init(&buf, sep);
   1499 
   1500     if (oneBigWord) {
   1501 	/* fake what brk_string() would do if there were only one word */
   1502 	ac = 1;
   1503 	av = bmake_malloc((ac + 1) * sizeof(char *));
   1504 	as = bmake_strdup(str);
   1505 	av[0] = as;
   1506 	av[1] = NULL;
   1507     } else {
   1508 	av = brk_string(str, FALSE, &ac, &as);
   1509     }
   1510 
   1511     /*
   1512      * Now sanitize the given range.
   1513      * If first or last are negative, convert them to the positive equivalents
   1514      * (-1 gets converted to ac, -2 gets converted to (ac - 1), etc.).
   1515      */
   1516     if (first < 0)
   1517 	first += (int)ac + 1;
   1518     if (last < 0)
   1519 	last += (int)ac + 1;
   1520 
   1521     /*
   1522      * We avoid scanning more of the list than we need to.
   1523      */
   1524     if (first > last) {
   1525 	start = MIN((int)ac, first) - 1;
   1526 	end = MAX(0, last - 1);
   1527 	step = -1;
   1528     } else {
   1529 	start = MAX(0, first - 1);
   1530 	end = MIN((int)ac, last);
   1531 	step = 1;
   1532     }
   1533 
   1534     for (i = start; (step < 0) == (i >= end); i += step) {
   1535 	SepBuf_AddStr(&buf, av[i]);
   1536 	SepBuf_Sep(&buf);
   1537     }
   1538 
   1539     free(as);
   1540     free(av);
   1541 
   1542     return SepBuf_Destroy(&buf, FALSE);
   1543 }
   1544 
   1545 
   1546 /* Callback for ModifyWords to implement the :tA modifier.
   1547  * Replace each word with the result of realpath() if successful. */
   1548 static void
   1549 ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   1550 {
   1551     struct stat st;
   1552     char rbuf[MAXPATHLEN];
   1553 
   1554     const char *rp = cached_realpath(word, rbuf);
   1555     if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
   1556 	word = rp;
   1557 
   1558     SepBuf_AddStr(buf, word);
   1559 }
   1560 
   1561 /*-
   1562  *-----------------------------------------------------------------------
   1563  * Modify each of the words of the passed string using the given function.
   1564  *
   1565  * Input:
   1566  *	str		String whose words should be modified
   1567  *	modifyWord	Function that modifies a single word
   1568  *	modifyWord_args Custom arguments for modifyWord
   1569  *
   1570  * Results:
   1571  *	A string of all the words modified appropriately.
   1572  *-----------------------------------------------------------------------
   1573  */
   1574 static char *
   1575 ModifyWords(GNode *ctx, char sep, Boolean oneBigWord, const char *str,
   1576 	    ModifyWordsCallback modifyWord, void *modifyWord_args)
   1577 {
   1578     SepBuf result;
   1579     char **av;			/* word list */
   1580     char *as;			/* word list memory */
   1581     size_t ac;
   1582     size_t i;
   1583 
   1584     if (oneBigWord) {
   1585 	SepBuf_Init(&result, sep);
   1586 	modifyWord(str, &result, modifyWord_args);
   1587 	return SepBuf_Destroy(&result, FALSE);
   1588     }
   1589 
   1590     SepBuf_Init(&result, sep);
   1591 
   1592     av = brk_string(str, FALSE, &ac, &as);
   1593 
   1594     VAR_DEBUG("ModifyWords: split \"%s\" into %zu words\n", str, ac);
   1595 
   1596     for (i = 0; i < ac; i++) {
   1597 	modifyWord(av[i], &result, modifyWord_args);
   1598 	if (result.buf.count > 0)
   1599 	    SepBuf_Sep(&result);
   1600     }
   1601 
   1602     free(as);
   1603     free(av);
   1604 
   1605     return SepBuf_Destroy(&result, FALSE);
   1606 }
   1607 
   1608 
   1609 static char *
   1610 WordList_JoinFree(char **av, size_t ac, char *as)
   1611 {
   1612     Buffer buf;
   1613     size_t i;
   1614 
   1615     Buf_Init(&buf, 0);
   1616 
   1617     for (i = 0; i < ac; i++) {
   1618 	if (i != 0)
   1619 	    Buf_AddByte(&buf, ' ');	/* XXX: st->sep, for consistency */
   1620 	Buf_AddStr(&buf, av[i]);
   1621     }
   1622 
   1623     free(av);
   1624     free(as);
   1625 
   1626     return Buf_Destroy(&buf, FALSE);
   1627 }
   1628 
   1629 /* Remove adjacent duplicate words. */
   1630 static char *
   1631 VarUniq(const char *str)
   1632 {
   1633     char *as;			/* Word list memory */
   1634     size_t ac;
   1635     char **av = brk_string(str, FALSE, &ac, &as);
   1636 
   1637     if (ac > 1) {
   1638 	size_t i, j;
   1639 	for (j = 0, i = 1; i < ac; i++)
   1640 	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
   1641 		av[j] = av[i];
   1642 	ac = j + 1;
   1643     }
   1644 
   1645     return WordList_JoinFree(av, ac, as);
   1646 }
   1647 
   1648 
   1649 /*-
   1650  * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/
   1651  * or the :@ modifier, until the next unescaped delimiter.  The delimiter, as
   1652  * well as the backslash or the dollar, can be escaped with a backslash.
   1653  *
   1654  * Return the parsed (and possibly expanded) string, or NULL if no delimiter
   1655  * was found.  On successful return, the parsing position pp points right
   1656  * after the delimiter.  The delimiter is not included in the returned
   1657  * value though.
   1658  */
   1659 static char *
   1660 ParseModifierPart(
   1661     const char **pp,		/* The parsing position, updated upon return */
   1662     int delim,			/* Parsing stops at this delimiter */
   1663     VarEvalFlags eflags,	/* Flags for evaluating nested variables;
   1664 				 * if VARE_WANTRES is not set, the text is
   1665 				 * only parsed */
   1666     GNode *ctxt,		/* For looking up nested variables */
   1667     size_t *out_length,		/* Optionally stores the length of the returned
   1668 				 * string, just to save another strlen call. */
   1669     VarPatternFlags *out_pflags,/* For the first part of the :S modifier,
   1670 				 * sets the VARP_ANCHOR_END flag if the last
   1671 				 * character of the pattern is a $. */
   1672     ModifyWord_SubstArgs *subst	/* For the second part of the :S modifier,
   1673 				 * allow ampersands to be escaped and replace
   1674 				 * unescaped ampersands with subst->lhs. */
   1675 ) {
   1676     Buffer buf;
   1677     const char *p;
   1678     char *rstr;
   1679 
   1680     Buf_Init(&buf, 0);
   1681 
   1682     /*
   1683      * Skim through until the matching delimiter is found;
   1684      * pick up variable substitutions on the way. Also allow
   1685      * backslashes to quote the delimiter, $, and \, but don't
   1686      * touch other backslashes.
   1687      */
   1688     p = *pp;
   1689     while (*p != '\0' && *p != delim) {
   1690 	const char *varstart;
   1691 
   1692 	Boolean is_escaped = p[0] == '\\' && (
   1693 	    p[1] == delim || p[1] == '\\' || p[1] == '$' ||
   1694 	    (p[1] == '&' && subst != NULL));
   1695 	if (is_escaped) {
   1696 	    Buf_AddByte(&buf, p[1]);
   1697 	    p += 2;
   1698 	    continue;
   1699 	}
   1700 
   1701 	if (*p != '$') {	/* Unescaped, simple text */
   1702 	    if (subst != NULL && *p == '&')
   1703 		Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
   1704 	    else
   1705 		Buf_AddByte(&buf, *p);
   1706 	    p++;
   1707 	    continue;
   1708 	}
   1709 
   1710 	if (p[1] == delim) {	/* Unescaped $ at end of pattern */
   1711 	    if (out_pflags != NULL)
   1712 		*out_pflags |= VARP_ANCHOR_END;
   1713 	    else
   1714 		Buf_AddByte(&buf, *p);
   1715 	    p++;
   1716 	    continue;
   1717 	}
   1718 
   1719 	if (eflags & VARE_WANTRES) {	/* Nested variable, evaluated */
   1720 	    const char *cp2;
   1721 	    int len;
   1722 	    void *freeIt;
   1723 	    VarEvalFlags nested_eflags = eflags & ~(unsigned)VARE_ASSIGN;
   1724 
   1725 	    cp2 = Var_Parse(p, ctxt, nested_eflags, &len, &freeIt);
   1726 	    Buf_AddStr(&buf, cp2);
   1727 	    free(freeIt);
   1728 	    p += len;
   1729 	    continue;
   1730 	}
   1731 
   1732 	/* XXX: This whole block is very similar to Var_Parse without
   1733 	 * VARE_WANTRES.  There may be subtle edge cases though that are
   1734 	 * not yet covered in the unit tests and that are parsed differently,
   1735 	 * depending on whether they are evaluated or not.
   1736 	 *
   1737 	 * This subtle difference is not documented in the manual page,
   1738 	 * neither is the difference between parsing :D and :M documented.
   1739 	 * No code should ever depend on these details, but who knows. */
   1740 
   1741 	varstart = p;		/* Nested variable, only parsed */
   1742 	if (p[1] == PROPEN || p[1] == BROPEN) {
   1743 	    /*
   1744 	     * Find the end of this variable reference
   1745 	     * and suck it in without further ado.
   1746 	     * It will be interpreted later.
   1747 	     */
   1748 	    int have = p[1];
   1749 	    int want = have == PROPEN ? PRCLOSE : BRCLOSE;
   1750 	    int depth = 1;
   1751 
   1752 	    for (p += 2; *p != '\0' && depth > 0; p++) {
   1753 		if (p[-1] != '\\') {
   1754 		    if (*p == have)
   1755 			depth++;
   1756 		    if (*p == want)
   1757 			depth--;
   1758 		}
   1759 	    }
   1760 	    Buf_AddBytesBetween(&buf, varstart, p);
   1761 	} else {
   1762 	    Buf_AddByte(&buf, *varstart);
   1763 	    p++;
   1764 	}
   1765     }
   1766 
   1767     if (*p != delim) {
   1768 	*pp = p;
   1769 	return NULL;
   1770     }
   1771 
   1772     *pp = ++p;
   1773     if (out_length != NULL)
   1774 	*out_length = Buf_Size(&buf);
   1775 
   1776     rstr = Buf_Destroy(&buf, FALSE);
   1777     VAR_DEBUG("Modifier part: \"%s\"\n", rstr);
   1778     return rstr;
   1779 }
   1780 
   1781 /*-
   1782  *-----------------------------------------------------------------------
   1783  * VarQuote --
   1784  *	Quote shell meta-characters and space characters in the string
   1785  *	if quoteDollar is set, also quote and double any '$' characters.
   1786  *
   1787  * Results:
   1788  *	The quoted string
   1789  *
   1790  * Side Effects:
   1791  *	None.
   1792  *
   1793  *-----------------------------------------------------------------------
   1794  */
   1795 static char *
   1796 VarQuote(char *str, Boolean quoteDollar)
   1797 {
   1798     Buffer buf;
   1799     Buf_Init(&buf, 0);
   1800 
   1801     for (; *str != '\0'; str++) {
   1802 	if (*str == '\n') {
   1803 	    const char *newline = Shell_GetNewline();
   1804 	    if (newline == NULL)
   1805 		newline = "\\\n";
   1806 	    Buf_AddStr(&buf, newline);
   1807 	    continue;
   1808 	}
   1809 	if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
   1810 	    Buf_AddByte(&buf, '\\');
   1811 	Buf_AddByte(&buf, *str);
   1812 	if (quoteDollar && *str == '$')
   1813 	    Buf_AddStr(&buf, "\\$");
   1814     }
   1815 
   1816     str = Buf_Destroy(&buf, FALSE);
   1817     VAR_DEBUG("QuoteMeta: [%s]\n", str);
   1818     return str;
   1819 }
   1820 
   1821 /* Compute the 32-bit hash of the given string, using the MurmurHash3
   1822  * algorithm. Output is encoded as 8 hex digits, in Little Endian order. */
   1823 static char *
   1824 VarHash(const char *str)
   1825 {
   1826     static const char    hexdigits[16] = "0123456789abcdef";
   1827     const unsigned char *ustr = (const unsigned char *)str;
   1828 
   1829     uint32_t h  = 0x971e137bU;
   1830     uint32_t c1 = 0x95543787U;
   1831     uint32_t c2 = 0x2ad7eb25U;
   1832     size_t len2 = strlen(str);
   1833 
   1834     char *buf;
   1835     size_t i;
   1836 
   1837     size_t len;
   1838     for (len = len2; len; ) {
   1839 	uint32_t k = 0;
   1840 	switch (len) {
   1841 	default:
   1842 	    k = ((uint32_t)ustr[3] << 24) |
   1843 		((uint32_t)ustr[2] << 16) |
   1844 		((uint32_t)ustr[1] << 8) |
   1845 		(uint32_t)ustr[0];
   1846 	    len -= 4;
   1847 	    ustr += 4;
   1848 	    break;
   1849 	case 3:
   1850 	    k |= (uint32_t)ustr[2] << 16;
   1851 	    /* FALLTHROUGH */
   1852 	case 2:
   1853 	    k |= (uint32_t)ustr[1] << 8;
   1854 	    /* FALLTHROUGH */
   1855 	case 1:
   1856 	    k |= (uint32_t)ustr[0];
   1857 	    len = 0;
   1858 	}
   1859 	c1 = c1 * 5 + 0x7b7d159cU;
   1860 	c2 = c2 * 5 + 0x6bce6396U;
   1861 	k *= c1;
   1862 	k = (k << 11) ^ (k >> 21);
   1863 	k *= c2;
   1864 	h = (h << 13) ^ (h >> 19);
   1865 	h = h * 5 + 0x52dce729U;
   1866 	h ^= k;
   1867     }
   1868     h ^= (uint32_t)len2;
   1869     h *= 0x85ebca6b;
   1870     h ^= h >> 13;
   1871     h *= 0xc2b2ae35;
   1872     h ^= h >> 16;
   1873 
   1874     buf = bmake_malloc(9);
   1875     for (i = 0; i < 8; i++) {
   1876 	buf[i] = hexdigits[h & 0x0f];
   1877 	h >>= 4;
   1878     }
   1879     buf[8] = '\0';
   1880     return buf;
   1881 }
   1882 
   1883 static char *
   1884 VarStrftime(const char *fmt, Boolean zulu, time_t tim)
   1885 {
   1886     char buf[BUFSIZ];
   1887 
   1888     if (!tim)
   1889 	time(&tim);
   1890     if (!*fmt)
   1891 	fmt = "%c";
   1892     strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&tim) : localtime(&tim));
   1893 
   1894     buf[sizeof(buf) - 1] = '\0';
   1895     return bmake_strdup(buf);
   1896 }
   1897 
   1898 /* The ApplyModifier functions all work in the same way.  They get the
   1899  * current parsing position (pp) and parse the modifier from there.  The
   1900  * modifier typically lasts until the next ':', or a closing '}', ')'
   1901  * (taken from st->endc), or the end of the string (parse error).
   1902  *
   1903  * After parsing, no matter whether successful or not, they set the parsing
   1904  * position to the character after the modifier, or in case of parse errors,
   1905  * just increment the parsing position.  (That's how it is right now, it
   1906  * shouldn't hurt to keep the parsing position as-is in case of parse errors.)
   1907  *
   1908  * On success, an ApplyModifier function:
   1909  *	* sets the parsing position *pp to the first character following the
   1910  *	  current modifier
   1911  *	* processes the current variable value from st->val to produce the
   1912  *	  modified variable value and stores it in st->newVal
   1913  *	* returns AMR_OK
   1914  *
   1915  * On parse errors, an ApplyModifier function:
   1916  *	* either issues a custom error message and then returns AMR_CLEANUP
   1917  *	* or returns AMR_BAD to issue the standard "Bad modifier" error message
   1918  *	In both of these cases, it updates the parsing position.
   1919  *	Modifiers that use ParseModifierPart typically set st->missing_delim
   1920  *	and then return AMR_CLEANUP to issue the standard error message.
   1921  *
   1922  * If the expected modifier was not found, several modifiers return AMR_UNKNOWN
   1923  * to fall back to the SysV modifier ${VAR:from=to}.  This is especially
   1924  * useful for newly added long-name modifiers, to avoid breaking any existing
   1925  * code.  In such a case the parsing position must not be changed.
   1926  */
   1927 
   1928 typedef struct {
   1929     const char startc;		/* '\0' or '{' or '(' */
   1930     const char endc;		/* '\0' or '}' or ')' */
   1931     Var * const v;
   1932     GNode * const ctxt;
   1933     const VarEvalFlags eflags;
   1934 
   1935     char *val;			/* The old value of the expression,
   1936 				 * before applying the modifier, never NULL */
   1937     char *newVal;		/* The new value of the expression,
   1938 				 * after applying the modifier, never NULL */
   1939     char missing_delim;		/* For error reporting */
   1940 
   1941     char sep;			/* Word separator in expansions
   1942 				 * (see the :ts modifier) */
   1943     Boolean oneBigWord;		/* TRUE if some modifiers that otherwise split
   1944 				 * the variable value into words, like :S and
   1945 				 * :C, treat the variable value as a single big
   1946 				 * word, possibly containing spaces. */
   1947 } ApplyModifiersState;
   1948 
   1949 typedef enum {
   1950     AMR_OK,			/* Continue parsing */
   1951     AMR_UNKNOWN,		/* Not a match, try other modifiers as well */
   1952     AMR_BAD,			/* Error out with "Bad modifier" message */
   1953     AMR_CLEANUP			/* Error out, with "Unfinished modifier"
   1954 				 * if st->missing_delim is set. */
   1955 } ApplyModifierResult;
   1956 
   1957 /* Test whether mod starts with modname, followed by a delimiter. */
   1958 static Boolean
   1959 ModMatch(const char *mod, const char *modname, char endc)
   1960 {
   1961     size_t n = strlen(modname);
   1962     return strncmp(mod, modname, n) == 0 &&
   1963 	   (mod[n] == endc || mod[n] == ':');
   1964 }
   1965 
   1966 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   1967 static inline Boolean
   1968 ModMatchEq(const char *mod, const char *modname, char endc)
   1969 {
   1970     size_t n = strlen(modname);
   1971     return strncmp(mod, modname, n) == 0 &&
   1972 	   (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
   1973 }
   1974 
   1975 /* :@var (at) ...${var}...@ */
   1976 static ApplyModifierResult
   1977 ApplyModifier_Loop(const char **pp, ApplyModifiersState *st)
   1978 {
   1979     ModifyWord_LoopArgs args;
   1980     char delim;
   1981     char prev_sep;
   1982     VarEvalFlags eflags = st->eflags & ~(unsigned)VARE_WANTRES;
   1983 
   1984     args.ctx = st->ctxt;
   1985 
   1986     (*pp)++;			/* Skip the first '@' */
   1987     delim = '@';
   1988     args.tvar = ParseModifierPart(pp, delim, eflags,
   1989 				  st->ctxt, NULL, NULL, NULL);
   1990     if (args.tvar == NULL) {
   1991 	st->missing_delim = delim;
   1992 	return AMR_CLEANUP;
   1993     }
   1994     if (DEBUG(LINT) && strchr(args.tvar, '$') != NULL) {
   1995 	Parse_Error(PARSE_FATAL,
   1996 		    "In the :@ modifier of \"%s\", the variable name \"%s\" "
   1997 		    "must not contain a dollar.",
   1998 		    st->v->name, args.tvar);
   1999 	return AMR_CLEANUP;
   2000     }
   2001 
   2002     args.str = ParseModifierPart(pp, delim, eflags,
   2003 				 st->ctxt, NULL, NULL, NULL);
   2004     if (args.str == NULL) {
   2005 	st->missing_delim = delim;
   2006 	return AMR_CLEANUP;
   2007     }
   2008 
   2009     args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES);
   2010     prev_sep = st->sep;
   2011     st->sep = ' ';		/* XXX: should be st->sep for consistency */
   2012     st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2013 			     ModifyWord_Loop, &args);
   2014     st->sep = prev_sep;
   2015     Var_Delete(args.tvar, st->ctxt);
   2016     free(args.tvar);
   2017     free(args.str);
   2018     return AMR_OK;
   2019 }
   2020 
   2021 /* :Ddefined or :Uundefined */
   2022 static ApplyModifierResult
   2023 ApplyModifier_Defined(const char **pp, ApplyModifiersState *st)
   2024 {
   2025     Buffer buf;			/* Buffer for patterns */
   2026     const char *p;
   2027 
   2028     VarEvalFlags eflags = st->eflags & ~(unsigned)VARE_WANTRES;
   2029     if (st->eflags & VARE_WANTRES) {
   2030 	if ((**pp == 'D') == !(st->v->flags & VAR_JUNK))
   2031 	    eflags |= VARE_WANTRES;
   2032     }
   2033 
   2034     Buf_Init(&buf, 0);
   2035     p = *pp + 1;
   2036     while (*p != st->endc && *p != ':' && *p != '\0') {
   2037 
   2038         /* Escaped delimiter or other special character */
   2039 	if (*p == '\\') {
   2040 	    char c = p[1];
   2041 	    if (c == st->endc || c == ':' || c == '$' || c == '\\') {
   2042 		Buf_AddByte(&buf, c);
   2043 		p += 2;
   2044 		continue;
   2045 	    }
   2046 	}
   2047 
   2048 	/* Nested variable expressions */
   2049 	if (*p == '$') {
   2050 	    const char *cp2;
   2051 	    int len;
   2052 	    void *freeIt;
   2053 
   2054 	    cp2 = Var_Parse(p, st->ctxt, eflags, &len, &freeIt);
   2055 	    Buf_AddStr(&buf, cp2);
   2056 	    free(freeIt);
   2057 	    p += len;
   2058 	    continue;
   2059 	}
   2060 
   2061 	/* Ordinary text */
   2062 	Buf_AddByte(&buf, *p);
   2063 	p++;
   2064     }
   2065     *pp = p;
   2066 
   2067     if (st->v->flags & VAR_JUNK)
   2068 	st->v->flags |= VAR_KEEP;
   2069     if (eflags & VARE_WANTRES) {
   2070 	st->newVal = Buf_Destroy(&buf, FALSE);
   2071     } else {
   2072 	st->newVal = st->val;
   2073 	Buf_Destroy(&buf, TRUE);
   2074     }
   2075     return AMR_OK;
   2076 }
   2077 
   2078 /* :gmtime */
   2079 static ApplyModifierResult
   2080 ApplyModifier_Gmtime(const char **pp, ApplyModifiersState *st)
   2081 {
   2082     time_t utc;
   2083 
   2084     const char *mod = *pp;
   2085     if (!ModMatchEq(mod, "gmtime", st->endc))
   2086 	return AMR_UNKNOWN;
   2087 
   2088     if (mod[6] == '=') {
   2089 	char *ep;
   2090 	utc = (time_t)strtoul(mod + 7, &ep, 10);
   2091 	*pp = ep;
   2092     } else {
   2093 	utc = 0;
   2094 	*pp = mod + 6;
   2095     }
   2096     st->newVal = VarStrftime(st->val, TRUE, utc);
   2097     return AMR_OK;
   2098 }
   2099 
   2100 /* :localtime */
   2101 static Boolean
   2102 ApplyModifier_Localtime(const char **pp, ApplyModifiersState *st)
   2103 {
   2104     time_t utc;
   2105 
   2106     const char *mod = *pp;
   2107     if (!ModMatchEq(mod, "localtime", st->endc))
   2108 	return AMR_UNKNOWN;
   2109 
   2110     if (mod[9] == '=') {
   2111 	char *ep;
   2112 	utc = (time_t)strtoul(mod + 10, &ep, 10);
   2113 	*pp = ep;
   2114     } else {
   2115 	utc = 0;
   2116 	*pp = mod + 9;
   2117     }
   2118     st->newVal = VarStrftime(st->val, FALSE, utc);
   2119     return AMR_OK;
   2120 }
   2121 
   2122 /* :hash */
   2123 static ApplyModifierResult
   2124 ApplyModifier_Hash(const char **pp, ApplyModifiersState *st)
   2125 {
   2126     if (!ModMatch(*pp, "hash", st->endc))
   2127 	return AMR_UNKNOWN;
   2128 
   2129     st->newVal = VarHash(st->val);
   2130     *pp += 4;
   2131     return AMR_OK;
   2132 }
   2133 
   2134 /* :P */
   2135 static ApplyModifierResult
   2136 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
   2137 {
   2138     GNode *gn;
   2139     char *path;
   2140 
   2141     if (st->v->flags & VAR_JUNK)
   2142 	st->v->flags |= VAR_KEEP;
   2143 
   2144     gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
   2145     if (gn == NULL || gn->type & OP_NOPATH) {
   2146 	path = NULL;
   2147     } else if (gn->path) {
   2148 	path = bmake_strdup(gn->path);
   2149     } else {
   2150 	Lst searchPath = Suff_FindPath(gn);
   2151 	path = Dir_FindFile(st->v->name, searchPath);
   2152     }
   2153     if (path == NULL)
   2154 	path = bmake_strdup(st->v->name);
   2155     st->newVal = path;
   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     size_t n;
   2199     Buffer buf;
   2200     size_t 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 = (size_t)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, FALSE, &n, &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 + (int)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 	    size_t ac;
   2602 	    char **av = brk_string(st->val, FALSE, &ac, &as);
   2603 	    free(as);
   2604 	    free(av);
   2605 
   2606 	    Buf_Init(&buf, 4);	/* 3 digits + '\0' */
   2607 	    Buf_AddInt(&buf, (int)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     size_t ac;
   2693     char **av = brk_string(st->val, FALSE, &ac, &as);
   2694 
   2695     if (mod[1] == st->endc || mod[1] == ':') {
   2696 	/* :O sorts ascending */
   2697 	qsort(av, 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, 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 	    size_t i;
   2716 	    for (i = ac - 1; i > 0; i--) {
   2717 		size_t rndidx = (size_t)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 	var_Error,		/* .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     assert(val != NULL);
   3029 
   3030     p = *pp;
   3031     while (*p != '\0' && *p != endc) {
   3032 
   3033 	if (*p == '$') {
   3034 	    /*
   3035 	     * We may have some complex modifiers in a variable.
   3036 	     */
   3037 	    int rlen;
   3038 	    void *freeIt;
   3039 	    const char *rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt);
   3040 
   3041 	    /*
   3042 	     * If we have not parsed up to st.endc or ':',
   3043 	     * we are not interested.
   3044 	     */
   3045 	    int c;
   3046 	    assert(rval != NULL);
   3047 	    if (rval[0] != '\0' &&
   3048 		(c = p[rlen]) != '\0' && c != ':' && c != st.endc) {
   3049 		free(freeIt);
   3050 		goto apply_mods;
   3051 	    }
   3052 
   3053 	    VAR_DEBUG("Indirect modifier \"%s\" from \"%.*s\"\n",
   3054 		      rval, rlen, p);
   3055 
   3056 	    p += rlen;
   3057 
   3058 	    if (rval[0] != '\0') {
   3059 		const char *rval_pp = rval;
   3060 		st.val = ApplyModifiers(&rval_pp, st.val, '\0', '\0', v,
   3061 					ctxt, eflags, freePtr);
   3062 		if (st.val == var_Error
   3063 		    || (st.val == varNoError && !(st.eflags & VARE_UNDEFERR))
   3064 		    || *rval_pp != '\0') {
   3065 		    free(freeIt);
   3066 		    goto out;	/* error already reported */
   3067 		}
   3068 	    }
   3069 	    free(freeIt);
   3070 	    if (*p == ':')
   3071 		p++;
   3072 	    else if (*p == '\0' && endc != '\0') {
   3073 		Error("Unclosed variable specification after complex "
   3074 		      "modifier (expecting '%c') for %s", st.endc, st.v->name);
   3075 		goto out;
   3076 	    }
   3077 	    continue;
   3078 	}
   3079     apply_mods:
   3080 	st.newVal = var_Error;	/* default value, in case of errors */
   3081 	res = AMR_BAD;		/* just a safe fallback */
   3082 	mod = p;
   3083 
   3084 	if (DEBUG(VAR)) {
   3085 	    char eflags_str[VarEvalFlags_ToStringSize];
   3086 	    char vflags_str[VarFlags_ToStringSize];
   3087 	    Boolean is_single_char = mod[0] != '\0' &&
   3088 		(mod[1] == endc || mod[1] == ':');
   3089 
   3090 	    /* At this point, only the first character of the modifier can
   3091 	     * be used since the end of the modifier is not yet known. */
   3092 	    VAR_DEBUG("Applying ${%s:%c%s} to \"%s\" "
   3093 		      "(eflags = %s, vflags = %s)\n",
   3094 		      st.v->name, mod[0], is_single_char ? "" : "...", st.val,
   3095 		      Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
   3096 				    VarEvalFlags_ToStringSpecs),
   3097 		      Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
   3098 				    VarFlags_ToStringSpecs));
   3099 	}
   3100 
   3101 	switch (*mod) {
   3102 	case ':':
   3103 	    res = ApplyModifier_Assign(&p, &st);
   3104 	    break;
   3105 	case '@':
   3106 	    res = ApplyModifier_Loop(&p, &st);
   3107 	    break;
   3108 	case '_':
   3109 	    res = ApplyModifier_Remember(&p, &st);
   3110 	    break;
   3111 	case 'D':
   3112 	case 'U':
   3113 	    res = ApplyModifier_Defined(&p, &st);
   3114 	    break;
   3115 	case 'L':
   3116 	    if (st.v->flags & VAR_JUNK)
   3117 		st.v->flags |= VAR_KEEP;
   3118 	    st.newVal = bmake_strdup(st.v->name);
   3119 	    p++;
   3120 	    res = AMR_OK;
   3121 	    break;
   3122 	case 'P':
   3123 	    res = ApplyModifier_Path(&p, &st);
   3124 	    break;
   3125 	case '!':
   3126 	    res = ApplyModifier_Exclam(&p, &st);
   3127 	    break;
   3128 	case '[':
   3129 	    res = ApplyModifier_Words(&p, &st);
   3130 	    break;
   3131 	case 'g':
   3132 	    res = ApplyModifier_Gmtime(&p, &st);
   3133 	    break;
   3134 	case 'h':
   3135 	    res = ApplyModifier_Hash(&p, &st);
   3136 	    break;
   3137 	case 'l':
   3138 	    res = ApplyModifier_Localtime(&p, &st);
   3139 	    break;
   3140 	case 't':
   3141 	    res = ApplyModifier_To(&p, &st);
   3142 	    break;
   3143 	case 'N':
   3144 	case 'M':
   3145 	    res = ApplyModifier_Match(&p, &st);
   3146 	    break;
   3147 	case 'S':
   3148 	    res = ApplyModifier_Subst(&p, &st);
   3149 	    break;
   3150 	case '?':
   3151 	    res = ApplyModifier_IfElse(&p, &st);
   3152 	    break;
   3153 #ifndef NO_REGEX
   3154 	case 'C':
   3155 	    res = ApplyModifier_Regex(&p, &st);
   3156 	    break;
   3157 #endif
   3158 	case 'q':
   3159 	case 'Q':
   3160 	    if (p[1] == st.endc || p[1] == ':') {
   3161 		st.newVal = VarQuote(st.val, *mod == 'q');
   3162 		p++;
   3163 		res = AMR_OK;
   3164 	    } else
   3165 		res = AMR_UNKNOWN;
   3166 	    break;
   3167 	case 'T':
   3168 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Tail);
   3169 	    break;
   3170 	case 'H':
   3171 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Head);
   3172 	    break;
   3173 	case 'E':
   3174 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Suffix);
   3175 	    break;
   3176 	case 'R':
   3177 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Root);
   3178 	    break;
   3179 	case 'r':
   3180 	    res = ApplyModifier_Range(&p, &st);
   3181 	    break;
   3182 	case 'O':
   3183 	    res = ApplyModifier_Order(&p, &st);
   3184 	    break;
   3185 	case 'u':
   3186 	    if (p[1] == st.endc || p[1] == ':') {
   3187 		st.newVal = VarUniq(st.val);
   3188 		p++;
   3189 		res = AMR_OK;
   3190 	    } else
   3191 		res = AMR_UNKNOWN;
   3192 	    break;
   3193 #ifdef SUNSHCMD
   3194 	case 's':
   3195 	    if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
   3196 		if (st.eflags & VARE_WANTRES) {
   3197 		    const char *errfmt;
   3198 		    st.newVal = Cmd_Exec(st.val, &errfmt);
   3199 		    if (errfmt)
   3200 			Error(errfmt, st.val);
   3201 		} else
   3202 		    st.newVal = varNoError;
   3203 		p += 2;
   3204 		res = AMR_OK;
   3205 	    } else
   3206 		res = AMR_UNKNOWN;
   3207 	    break;
   3208 #endif
   3209 	default:
   3210 	    res = AMR_UNKNOWN;
   3211 	}
   3212 
   3213 #ifdef SYSVVARSUB
   3214 	if (res == AMR_UNKNOWN) {
   3215 	    assert(p == mod);
   3216 	    res = ApplyModifier_SysV(&p, &st);
   3217 	}
   3218 #endif
   3219 
   3220 	if (res == AMR_UNKNOWN) {
   3221 	    Error("Unknown modifier '%c'", *mod);
   3222 	    for (p++; *p != ':' && *p != st.endc && *p != '\0'; p++)
   3223 		continue;
   3224 	    st.newVal = var_Error;
   3225 	}
   3226 	if (res == AMR_CLEANUP)
   3227 	    goto cleanup;
   3228 	if (res == AMR_BAD)
   3229 	    goto bad_modifier;
   3230 
   3231 	if (DEBUG(VAR)) {
   3232 	    char eflags_str[VarEvalFlags_ToStringSize];
   3233 	    char vflags_str[VarFlags_ToStringSize];
   3234 	    const char *quot = st.newVal == var_Error ? "" : "\"";
   3235 	    const char *newVal = st.newVal == var_Error ? "error" : st.newVal;
   3236 
   3237 	    VAR_DEBUG("Result of ${%s:%.*s} is %s%s%s "
   3238 		      "(eflags = %s, vflags = %s)\n",
   3239 		      st.v->name, (int)(p - mod), mod, quot, newVal, quot,
   3240 		      Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
   3241 				    VarEvalFlags_ToStringSpecs),
   3242 		      Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
   3243 				    VarFlags_ToStringSpecs));
   3244 	}
   3245 
   3246 	if (st.newVal != st.val) {
   3247 	    if (*freePtr) {
   3248 		free(st.val);
   3249 		*freePtr = NULL;
   3250 	    }
   3251 	    st.val = st.newVal;
   3252 	    if (st.val != var_Error && st.val != varNoError) {
   3253 		*freePtr = st.val;
   3254 	    }
   3255 	}
   3256 	if (*p == '\0' && st.endc != '\0') {
   3257 	    Error("Unclosed variable specification (expecting '%c') "
   3258 		  "for \"%s\" (value \"%s\") modifier %c",
   3259 		  st.endc, st.v->name, st.val, *mod);
   3260 	} else if (*p == ':') {
   3261 	    p++;
   3262 	}
   3263 	mod = p;
   3264     }
   3265 out:
   3266     *pp = p;
   3267     assert(st.val != NULL);	/* Use var_Error or varNoError instead. */
   3268     return st.val;
   3269 
   3270 bad_modifier:
   3271     Error("Bad modifier `:%.*s' for %s",
   3272 	  (int)strcspn(mod, ":)}"), mod, st.v->name);
   3273 
   3274 cleanup:
   3275     *pp = p;
   3276     if (st.missing_delim != '\0')
   3277 	Error("Unfinished modifier for %s ('%c' missing)",
   3278 	      st.v->name, st.missing_delim);
   3279     free(*freePtr);
   3280     *freePtr = NULL;
   3281     return var_Error;
   3282 }
   3283 
   3284 static Boolean
   3285 VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)
   3286 {
   3287     if ((namelen == 1 ||
   3288 	 (namelen == 2 && (varname[1] == 'F' || varname[1] == 'D'))) &&
   3289 	(ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
   3290     {
   3291 	/*
   3292 	 * If substituting a local variable in a non-local context,
   3293 	 * assume it's for dynamic source stuff. We have to handle
   3294 	 * this specially and return the longhand for the variable
   3295 	 * with the dollar sign escaped so it makes it back to the
   3296 	 * caller. Only four of the local variables are treated
   3297 	 * specially as they are the only four that will be set
   3298 	 * when dynamic sources are expanded.
   3299 	 */
   3300 	switch (varname[0]) {
   3301 	case '@':
   3302 	case '%':
   3303 	case '*':
   3304 	case '!':
   3305 	    return TRUE;
   3306 	}
   3307 	return FALSE;
   3308     }
   3309 
   3310     if ((namelen == 7 || namelen == 8) && varname[0] == '.' &&
   3311 	isupper((unsigned char)varname[1]) &&
   3312 	(ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
   3313     {
   3314 	return strcmp(varname, ".TARGET") == 0 ||
   3315 	       strcmp(varname, ".ARCHIVE") == 0 ||
   3316 	       strcmp(varname, ".PREFIX") == 0 ||
   3317 	       strcmp(varname, ".MEMBER") == 0;
   3318     }
   3319 
   3320     return FALSE;
   3321 }
   3322 
   3323 /*-
   3324  *-----------------------------------------------------------------------
   3325  * Var_Parse --
   3326  *	Given the start of a variable invocation (such as $v, $(VAR),
   3327  *	${VAR:Mpattern}), extract the variable name, possibly some
   3328  *	modifiers and find its value by applying the modifiers to the
   3329  *	original value.
   3330  *
   3331  * Input:
   3332  *	str		The string to parse
   3333  *	ctxt		The context for the variable
   3334  *	flags		VARE_UNDEFERR	if undefineds are an error
   3335  *			VARE_WANTRES	if we actually want the result
   3336  *			VARE_ASSIGN	if we are in a := assignment
   3337  *	lengthPtr	OUT: The length of the specification
   3338  *	freePtr		OUT: Non-NULL if caller should free *freePtr
   3339  *
   3340  * Results:
   3341  *	Returns the value of the variable expression.
   3342  *	var_Error if there was a parse error and VARE_UNDEFERR was set.
   3343  *	varNoError if there was a parse error and VARE_UNDEFERR was not set.
   3344  *
   3345  *	Parsing should continue at str + *lengthPtr.
   3346  *
   3347  *	After using the returned value, *freePtr must be freed, preferably
   3348  *	using bmake_free since it is NULL in most cases.
   3349  *
   3350  * Side Effects:
   3351  *	Any effects from the modifiers, such as :!cmd! or ::=value.
   3352  *-----------------------------------------------------------------------
   3353  */
   3354 /* coverity[+alloc : arg-*4] */
   3355 const char *
   3356 Var_Parse(const char * const str, GNode *ctxt, VarEvalFlags eflags,
   3357 	  int *lengthPtr, void **freePtr)
   3358 {
   3359     const char	*tstr;		/* Pointer into str */
   3360     Boolean 	 haveModifier;	/* TRUE if have modifiers for the variable */
   3361     char	 startc;	/* Starting character if variable in parens
   3362 				 * or braces */
   3363     char	 endc;		/* Ending character if variable in parens
   3364 				 * or braces */
   3365     Boolean	 dynamic;	/* TRUE if the variable is local and we're
   3366 				 * expanding it in a non-local context. This
   3367 				 * is done to support dynamic sources. The
   3368 				 * result is just the invocation, unaltered */
   3369     const char *extramodifiers;
   3370     Var *v;
   3371     char *nstr;
   3372     char eflags_str[VarEvalFlags_ToStringSize];
   3373 
   3374     VAR_DEBUG("%s: %s with %s\n", __func__, str,
   3375 	      Enum_ToString(eflags_str, sizeof eflags_str, eflags,
   3376 			    VarEvalFlags_ToStringSpecs));
   3377 
   3378     *freePtr = NULL;
   3379     extramodifiers = NULL;	/* extra modifiers to apply first */
   3380     dynamic = FALSE;
   3381 
   3382     startc = str[1];
   3383     if (startc != PROPEN && startc != BROPEN) {
   3384 	char name[2];
   3385 
   3386 	/*
   3387 	 * If it's not bounded by braces of some sort, life is much simpler.
   3388 	 * We just need to check for the first character and return the
   3389 	 * value if it exists.
   3390 	 */
   3391 
   3392 	/* Error out some really stupid names */
   3393 	if (startc == '\0' || strchr(")}:$", startc)) {
   3394 	    *lengthPtr = 1;
   3395 	    return var_Error;
   3396 	}
   3397 
   3398 	name[0] = startc;
   3399 	name[1] = '\0';
   3400 	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3401 	if (v == NULL) {
   3402 	    *lengthPtr = 2;
   3403 
   3404 	    if (ctxt == VAR_CMD || ctxt == VAR_GLOBAL) {
   3405 		/*
   3406 		 * If substituting a local variable in a non-local context,
   3407 		 * assume it's for dynamic source stuff. We have to handle
   3408 		 * this specially and return the longhand for the variable
   3409 		 * with the dollar sign escaped so it makes it back to the
   3410 		 * caller. Only four of the local variables are treated
   3411 		 * specially as they are the only four that will be set
   3412 		 * when dynamic sources are expanded.
   3413 		 */
   3414 		switch (str[1]) {
   3415 		case '@':
   3416 		    return "$(.TARGET)";
   3417 		case '%':
   3418 		    return "$(.MEMBER)";
   3419 		case '*':
   3420 		    return "$(.PREFIX)";
   3421 		case '!':
   3422 		    return "$(.ARCHIVE)";
   3423 		}
   3424 	    }
   3425 	    return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3426 	} else {
   3427 	    haveModifier = FALSE;
   3428 	    tstr = str + 1;
   3429 	}
   3430     } else {
   3431 	Buffer namebuf;		/* Holds the variable name */
   3432 	int depth;
   3433 	size_t namelen;
   3434 	char *varname;
   3435 
   3436 	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
   3437 
   3438 	Buf_Init(&namebuf, 0);
   3439 
   3440 	/*
   3441 	 * Skip to the end character or a colon, whichever comes first.
   3442 	 */
   3443 	depth = 1;
   3444 	for (tstr = str + 2; *tstr != '\0'; tstr++) {
   3445 	    /* Track depth so we can spot parse errors. */
   3446 	    if (*tstr == startc)
   3447 		depth++;
   3448 	    if (*tstr == endc) {
   3449 		if (--depth == 0)
   3450 		    break;
   3451 	    }
   3452 	    if (*tstr == ':' && depth == 1)
   3453 		break;
   3454 	    /* A variable inside a variable, expand. */
   3455 	    if (*tstr == '$') {
   3456 		int rlen;
   3457 		void *freeIt;
   3458 		const char *rval = Var_Parse(tstr, ctxt, eflags, &rlen,
   3459 					     &freeIt);
   3460 		if (rval != NULL)
   3461 		    Buf_AddStr(&namebuf, rval);
   3462 		free(freeIt);
   3463 		tstr += rlen - 1;
   3464 	    } else
   3465 		Buf_AddByte(&namebuf, *tstr);
   3466 	}
   3467 	if (*tstr == ':') {
   3468 	    haveModifier = TRUE;
   3469 	} else if (*tstr == endc) {
   3470 	    haveModifier = FALSE;
   3471 	} else {
   3472 	    Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"",
   3473 			Buf_GetAll(&namebuf, NULL));
   3474 	    /*
   3475 	     * If we never did find the end character, return NULL
   3476 	     * right now, setting the length to be the distance to
   3477 	     * the end of the string, since that's what make does.
   3478 	     */
   3479 	    *lengthPtr = (int)(size_t)(tstr - str);
   3480 	    Buf_Destroy(&namebuf, TRUE);
   3481 	    return var_Error;
   3482 	}
   3483 
   3484 	varname = Buf_GetAll(&namebuf, &namelen);
   3485 
   3486 	/*
   3487 	 * At this point, varname points into newly allocated memory from
   3488 	 * namebuf, containing only the name of the variable.
   3489 	 *
   3490 	 * start and tstr point into the const string that was pointed
   3491 	 * to by the original value of the str parameter.  start points
   3492 	 * to the '$' at the beginning of the string, while tstr points
   3493 	 * to the char just after the end of the variable name -- this
   3494 	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
   3495 	 */
   3496 
   3497 	v = VarFind(varname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3498 	/*
   3499 	 * Check also for bogus D and F forms of local variables since we're
   3500 	 * in a local context and the name is the right length.
   3501 	 */
   3502 	if (v == NULL && ctxt != VAR_CMD && ctxt != VAR_GLOBAL &&
   3503 	    namelen == 2 && (varname[1] == 'F' || varname[1] == 'D') &&
   3504 	    strchr("@%?*!<>", varname[0]) != NULL)
   3505 	{
   3506 	    /*
   3507 	     * Well, it's local -- go look for it.
   3508 	     */
   3509 	    char name[] = { varname[0], '\0' };
   3510 	    v = VarFind(name, ctxt, 0);
   3511 
   3512 	    if (v != NULL) {
   3513 		if (varname[1] == 'D') {
   3514 		    extramodifiers = "H:";
   3515 		} else { /* F */
   3516 		    extramodifiers = "T:";
   3517 		}
   3518 	    }
   3519 	}
   3520 
   3521 	if (v == NULL) {
   3522 	    dynamic = VarIsDynamic(ctxt, varname, namelen);
   3523 
   3524 	    if (!haveModifier) {
   3525 		/*
   3526 		 * No modifiers -- have specification length so we can return
   3527 		 * now.
   3528 		 */
   3529 		*lengthPtr = (int)(size_t)(tstr - str) + 1;
   3530 		if (dynamic) {
   3531 		    char *pstr = bmake_strldup(str, (size_t)*lengthPtr);
   3532 		    *freePtr = pstr;
   3533 		    Buf_Destroy(&namebuf, TRUE);
   3534 		    return pstr;
   3535 		} else {
   3536 		    Buf_Destroy(&namebuf, TRUE);
   3537 		    return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3538 		}
   3539 	    } else {
   3540 		/*
   3541 		 * Still need to get to the end of the variable specification,
   3542 		 * so kludge up a Var structure for the modifications
   3543 		 */
   3544 		v = bmake_malloc(sizeof(Var));
   3545 		v->name = varname;
   3546 		Buf_Init(&v->val, 1);
   3547 		v->flags = VAR_JUNK;
   3548 		Buf_Destroy(&namebuf, FALSE);
   3549 	    }
   3550 	} else
   3551 	    Buf_Destroy(&namebuf, TRUE);
   3552     }
   3553 
   3554     if (v->flags & VAR_IN_USE) {
   3555 	Fatal("Variable %s is recursive.", v->name);
   3556 	/*NOTREACHED*/
   3557     } else {
   3558 	v->flags |= VAR_IN_USE;
   3559     }
   3560 
   3561     /*
   3562      * Before doing any modification, we have to make sure the value
   3563      * has been fully expanded. If it looks like recursion might be
   3564      * necessary (there's a dollar sign somewhere in the variable's value)
   3565      * we just call Var_Subst to do any other substitutions that are
   3566      * necessary. Note that the value returned by Var_Subst will have
   3567      * been dynamically-allocated, so it will need freeing when we
   3568      * return.
   3569      */
   3570     nstr = Buf_GetAll(&v->val, NULL);
   3571     if (strchr(nstr, '$') != NULL && (eflags & VARE_WANTRES) != 0) {
   3572 	nstr = Var_Subst(nstr, ctxt, eflags);
   3573 	*freePtr = nstr;
   3574 	assert(nstr != NULL);
   3575     }
   3576 
   3577     v->flags &= ~(unsigned)VAR_IN_USE;
   3578 
   3579     if (haveModifier || extramodifiers != NULL) {
   3580 	void *extraFree;
   3581 
   3582 	extraFree = NULL;
   3583 	if (extramodifiers != NULL) {
   3584 	    const char *em = extramodifiers;
   3585 	    nstr = ApplyModifiers(&em, nstr, '(', ')',
   3586 				  v, ctxt, eflags, &extraFree);
   3587 	}
   3588 
   3589 	if (haveModifier) {
   3590 	    /* Skip initial colon. */
   3591 	    tstr++;
   3592 
   3593 	    nstr = ApplyModifiers(&tstr, nstr, startc, endc,
   3594 				  v, ctxt, eflags, freePtr);
   3595 	    free(extraFree);
   3596 	} else {
   3597 	    *freePtr = extraFree;
   3598 	}
   3599     }
   3600 
   3601     /* Skip past endc if possible. */
   3602     *lengthPtr = (int)(size_t)(tstr + (*tstr ? 1 : 0) - str);
   3603 
   3604     if (v->flags & VAR_FROM_ENV) {
   3605 	Boolean destroy = nstr != Buf_GetAll(&v->val, NULL);
   3606 	if (!destroy) {
   3607 	    /*
   3608 	     * Returning the value unmodified, so tell the caller to free
   3609 	     * the thing.
   3610 	     */
   3611 	    *freePtr = nstr;
   3612 	}
   3613 	(void)VarFreeEnv(v, destroy);
   3614     } else if (v->flags & VAR_JUNK) {
   3615 	/*
   3616 	 * Perform any freeing needed and set *freePtr to NULL so the caller
   3617 	 * doesn't try to free a static pointer.
   3618 	 * If VAR_KEEP is also set then we want to keep str(?) as is.
   3619 	 */
   3620 	if (!(v->flags & VAR_KEEP)) {
   3621 	    if (*freePtr != NULL) {
   3622 		free(*freePtr);
   3623 		*freePtr = NULL;
   3624 	    }
   3625 	    if (dynamic) {
   3626 		nstr = bmake_strldup(str, (size_t)*lengthPtr);
   3627 		*freePtr = nstr;
   3628 	    } else {
   3629 		nstr = (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3630 	    }
   3631 	}
   3632 	if (nstr != Buf_GetAll(&v->val, NULL))
   3633 	    Buf_Destroy(&v->val, TRUE);
   3634 	free(v->name);
   3635 	free(v);
   3636     }
   3637     return nstr;
   3638 }
   3639 
   3640 /*-
   3641  *-----------------------------------------------------------------------
   3642  * Var_Subst  --
   3643  *	Substitute for all variables in the given string in the given context.
   3644  *	If eflags & VARE_UNDEFERR, Parse_Error will be called when an undefined
   3645  *	variable is encountered.
   3646  *
   3647  * Input:
   3648  *	var		Named variable || NULL for all
   3649  *	str		the string which to substitute
   3650  *	ctxt		the context wherein to find variables
   3651  *	eflags		VARE_UNDEFERR	if undefineds are an error
   3652  *			VARE_WANTRES	if we actually want the result
   3653  *			VARE_ASSIGN	if we are in a := assignment
   3654  *
   3655  * Results:
   3656  *	The resulting string.
   3657  *
   3658  * Side Effects:
   3659  *	Any effects from the modifiers, such as ::=, :sh or !cmd!,
   3660  *	if eflags contains VARE_WANTRES.
   3661  *-----------------------------------------------------------------------
   3662  */
   3663 char *
   3664 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags)
   3665 {
   3666     Buffer buf;			/* Buffer for forming things */
   3667     Boolean trailingBslash;
   3668 
   3669     /* Set true if an error has already been reported,
   3670      * to prevent a plethora of messages when recursing */
   3671     static Boolean errorReported;
   3672 
   3673     Buf_Init(&buf, 0);
   3674     errorReported = FALSE;
   3675     trailingBslash = FALSE;	/* variable ends in \ */
   3676 
   3677     while (*str) {
   3678 	if (*str == '\n' && trailingBslash)
   3679 	    Buf_AddByte(&buf, ' ');
   3680 
   3681 	if (*str == '$' && str[1] == '$') {
   3682 	    /*
   3683 	     * A dollar sign may be escaped with another dollar sign.
   3684 	     * In such a case, we skip over the escape character and store the
   3685 	     * dollar sign into the buffer directly.
   3686 	     */
   3687 	    if (save_dollars && (eflags & VARE_ASSIGN))
   3688 		Buf_AddByte(&buf, '$');
   3689 	    Buf_AddByte(&buf, '$');
   3690 	    str += 2;
   3691 	} else if (*str != '$') {
   3692 	    /*
   3693 	     * Skip as many characters as possible -- either to the end of
   3694 	     * the string or to the next dollar sign (variable invocation).
   3695 	     */
   3696 	    const char *cp;
   3697 
   3698 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   3699 		continue;
   3700 	    Buf_AddBytesBetween(&buf, cp, str);
   3701 	} else {
   3702 	    int length;
   3703 	    void *freeIt;
   3704 	    const char *val = Var_Parse(str, ctxt, eflags, &length, &freeIt);
   3705 
   3706 	    if (val == var_Error || val == varNoError) {
   3707 		/*
   3708 		 * If performing old-time variable substitution, skip over
   3709 		 * the variable and continue with the substitution. Otherwise,
   3710 		 * store the dollar sign and advance str so we continue with
   3711 		 * the string...
   3712 		 */
   3713 		if (oldVars) {
   3714 		    str += length;
   3715 		} else if ((eflags & VARE_UNDEFERR) || val == var_Error) {
   3716 		    /*
   3717 		     * If variable is undefined, complain and skip the
   3718 		     * variable. The complaint will stop us from doing anything
   3719 		     * when the file is parsed.
   3720 		     */
   3721 		    if (!errorReported) {
   3722 			Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
   3723 				    length, str);
   3724 		    }
   3725 		    str += length;
   3726 		    errorReported = TRUE;
   3727 		} else {
   3728 		    Buf_AddByte(&buf, *str);
   3729 		    str += 1;
   3730 		}
   3731 	    } else {
   3732 		size_t val_len;
   3733 
   3734 		str += length;
   3735 
   3736 		val_len = strlen(val);
   3737 		Buf_AddBytes(&buf, val, val_len);
   3738 		trailingBslash = val_len > 0 && val[val_len - 1] == '\\';
   3739 	    }
   3740 	    free(freeIt);
   3741 	    freeIt = NULL;
   3742 	}
   3743     }
   3744 
   3745     return Buf_DestroyCompact(&buf);
   3746 }
   3747 
   3748 /* Initialize the module. */
   3749 void
   3750 Var_Init(void)
   3751 {
   3752     VAR_INTERNAL = Targ_NewGN("Internal");
   3753     VAR_GLOBAL = Targ_NewGN("Global");
   3754     VAR_CMD = Targ_NewGN("Command");
   3755 }
   3756 
   3757 
   3758 void
   3759 Var_End(void)
   3760 {
   3761     Var_Stats();
   3762 }
   3763 
   3764 void
   3765 Var_Stats(void)
   3766 {
   3767     Hash_DebugStats(&VAR_GLOBAL->context, "VAR_GLOBAL");
   3768 }
   3769 
   3770 
   3771 /****************** PRINT DEBUGGING INFO *****************/
   3772 static void
   3773 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
   3774 {
   3775     Var *v = (Var *)vp;
   3776     fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
   3777 }
   3778 
   3779 /* Print all variables in a context, unordered. */
   3780 void
   3781 Var_Dump(GNode *ctxt)
   3782 {
   3783     Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
   3784 }
   3785