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