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