Mon Jul 27 22:50:01 2020 UTC ()
make(1): replace comment in ApplyModifier_Match with code


(rillig)
diff -r1.344 -r1.345 src/usr.bin/make/var.c

cvs diff -r1.344 -r1.345 src/usr.bin/make/var.c (switch to unified diff)

--- src/usr.bin/make/var.c 2020/07/27 22:30:00 1.344
+++ src/usr.bin/make/var.c 2020/07/27 22:50:01 1.345
@@ -1,1078 +1,1078 @@ @@ -1,1078 +1,1078 @@
1/* $NetBSD: var.c,v 1.344 2020/07/27 22:30:00 rillig Exp $ */ 1/* $NetBSD: var.c,v 1.345 2020/07/27 22:50:01 rillig Exp $ */
2 2
3/* 3/*
4 * Copyright (c) 1988, 1989, 1990, 1993 4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved. 5 * The Regents of the University of California. All rights reserved.
6 * 6 *
7 * This code is derived from software contributed to Berkeley by 7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor. 8 * Adam de Boor.
9 * 9 *
10 * Redistribution and use in source and binary forms, with or without 10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions 11 * modification, are permitted provided that the following conditions
12 * are met: 12 * are met:
13 * 1. Redistributions of source code must retain the above copyright 13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer. 14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright 15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the 16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution. 17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors 18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software 19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission. 20 * without specific prior written permission.
21 * 21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE. 32 * SUCH DAMAGE.
33 */ 33 */
34 34
35/* 35/*
36 * Copyright (c) 1989 by Berkeley Softworks 36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved. 37 * All rights reserved.
38 * 38 *
39 * This code is derived from software contributed to Berkeley by 39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor. 40 * Adam de Boor.
41 * 41 *
42 * Redistribution and use in source and binary forms, with or without 42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions 43 * modification, are permitted provided that the following conditions
44 * are met: 44 * are met:
45 * 1. Redistributions of source code must retain the above copyright 45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer. 46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright 47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the 48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution. 49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software 50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement: 51 * must display the following acknowledgement:
52 * This product includes software developed by the University of 52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors. 53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors 54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software 55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission. 56 * without specific prior written permission.
57 * 57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE. 68 * SUCH DAMAGE.
69 */ 69 */
70 70
71#ifndef MAKE_NATIVE 71#ifndef MAKE_NATIVE
72static char rcsid[] = "$NetBSD: var.c,v 1.344 2020/07/27 22:30:00 rillig Exp $"; 72static char rcsid[] = "$NetBSD: var.c,v 1.345 2020/07/27 22:50:01 rillig Exp $";
73#else 73#else
74#include <sys/cdefs.h> 74#include <sys/cdefs.h>
75#ifndef lint 75#ifndef lint
76#if 0 76#if 0
77static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94"; 77static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
78#else 78#else
79__RCSID("$NetBSD: var.c,v 1.344 2020/07/27 22:30:00 rillig Exp $"); 79__RCSID("$NetBSD: var.c,v 1.345 2020/07/27 22:50:01 rillig Exp $");
80#endif 80#endif
81#endif /* not lint */ 81#endif /* not lint */
82#endif 82#endif
83 83
84/*- 84/*-
85 * var.c -- 85 * var.c --
86 * Variable-handling functions 86 * Variable-handling functions
87 * 87 *
88 * Interface: 88 * Interface:
89 * Var_Set Set the value of a variable in the given 89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't 90 * context. The variable is created if it doesn't
91 * yet exist. 91 * yet exist.
92 * 92 *
93 * Var_Append Append more characters to an existing variable 93 * Var_Append Append more characters to an existing variable
94 * in the given context. The variable needn't 94 * in the given context. The variable needn't
95 * exist already -- it will be created if it doesn't. 95 * exist already -- it will be created if it doesn't.
96 * A space is placed between the old value and the 96 * A space is placed between the old value and the
97 * new one. 97 * new one.
98 * 98 *
99 * Var_Exists See if a variable exists. 99 * Var_Exists See if a variable exists.
100 * 100 *
101 * Var_Value Return the unexpanded value of a variable in a 101 * Var_Value Return the unexpanded value of a variable in a
102 * context or NULL if the variable is undefined. 102 * context or NULL if the variable is undefined.
103 * 103 *
104 * Var_Subst Substitute either a single variable or all 104 * Var_Subst Substitute either a single variable or all
105 * variables in a string, using the given context. 105 * variables in a string, using the given context.
106 * 106 *
107 * Var_Parse Parse a variable expansion from a string and 107 * Var_Parse Parse a variable expansion from a string and
108 * return the result and the number of characters 108 * return the result and the number of characters
109 * consumed. 109 * consumed.
110 * 110 *
111 * Var_Delete Delete a variable in a context. 111 * Var_Delete Delete a variable in a context.
112 * 112 *
113 * Var_Init Initialize this module. 113 * Var_Init Initialize this module.
114 * 114 *
115 * Debugging: 115 * Debugging:
116 * Var_Dump Print out all variables defined in the given 116 * Var_Dump Print out all variables defined in the given
117 * context. 117 * context.
118 * 118 *
119 * XXX: There's a lot of duplication in these functions. 119 * XXX: There's a lot of duplication in these functions.
120 */ 120 */
121 121
122#include <sys/stat.h> 122#include <sys/stat.h>
123#ifndef NO_REGEX 123#ifndef NO_REGEX
124#include <sys/types.h> 124#include <sys/types.h>
125#include <regex.h> 125#include <regex.h>
126#endif 126#endif
127#include <ctype.h> 127#include <ctype.h>
128#include <inttypes.h> 128#include <inttypes.h>
129#include <limits.h> 129#include <limits.h>
130#include <stdlib.h> 130#include <stdlib.h>
131#include <time.h> 131#include <time.h>
132 132
133#include "make.h" 133#include "make.h"
134#include "buf.h" 134#include "buf.h"
135#include "dir.h" 135#include "dir.h"
136#include "job.h" 136#include "job.h"
137#include "metachar.h" 137#include "metachar.h"
138 138
139#define VAR_DEBUG(fmt, ...) \ 139#define VAR_DEBUG(fmt, ...) \
140 if (!DEBUG(VAR)) \ 140 if (!DEBUG(VAR)) \
141 (void) 0; \ 141 (void) 0; \
142 else \ 142 else \
143 fprintf(debug_file, fmt, __VA_ARGS__) 143 fprintf(debug_file, fmt, __VA_ARGS__)
144 144
145/* 145/*
146 * This lets us tell if we have replaced the original environ 146 * This lets us tell if we have replaced the original environ
147 * (which we cannot free). 147 * (which we cannot free).
148 */ 148 */
149char **savedEnv = NULL; 149char **savedEnv = NULL;
150 150
151/* 151/*
152 * This is a harmless return value for Var_Parse that can be used by Var_Subst 152 * This is a harmless return value for Var_Parse that can be used by Var_Subst
153 * to determine if there was an error in parsing -- easier than returning 153 * to determine if there was an error in parsing -- easier than returning
154 * a flag, as things outside this module don't give a hoot. 154 * a flag, as things outside this module don't give a hoot.
155 */ 155 */
156char var_Error[] = ""; 156char var_Error[] = "";
157 157
158/* 158/*
159 * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for 159 * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for
160 * Var_Parse is not set. Why not just use a constant? Well, GCC likes 160 * Var_Parse is not set. Why not just use a constant? Well, GCC likes
161 * to condense identical string instances... 161 * to condense identical string instances...
162 */ 162 */
163static char varNoError[] = ""; 163static char varNoError[] = "";
164 164
165/* 165/*
166 * Traditionally we consume $$ during := like any other expansion. 166 * Traditionally we consume $$ during := like any other expansion.
167 * Other make's do not. 167 * Other make's do not.
168 * This knob allows controlling the behavior. 168 * This knob allows controlling the behavior.
169 * FALSE to consume $$ during := assignment. 169 * FALSE to consume $$ during := assignment.
170 * TRUE to preserve $$ during := assignment. 170 * TRUE to preserve $$ during := assignment.
171 */ 171 */
172#define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS" 172#define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
173static Boolean save_dollars = TRUE; 173static Boolean save_dollars = TRUE;
174 174
175/* 175/*
176 * Internally, variables are contained in four different contexts. 176 * Internally, variables are contained in four different contexts.
177 * 1) the environment. They cannot be changed. If an environment 177 * 1) the environment. They cannot be changed. If an environment
178 * variable is appended to, the result is placed in the global 178 * variable is appended to, the result is placed in the global
179 * context. 179 * context.
180 * 2) the global context. Variables set in the Makefile are located in 180 * 2) the global context. Variables set in the Makefile are located in
181 * the global context. 181 * the global context.
182 * 3) the command-line context. All variables set on the command line 182 * 3) the command-line context. All variables set on the command line
183 * are placed in this context. They are UNALTERABLE once placed here. 183 * are placed in this context. They are UNALTERABLE once placed here.
184 * 4) the local context. Each target has associated with it a context 184 * 4) the local context. Each target has associated with it a context
185 * list. On this list are located the structures describing such 185 * list. On this list are located the structures describing such
186 * local variables as $(@) and $(*) 186 * local variables as $(@) and $(*)
187 * The four contexts are searched in the reverse order from which they are 187 * The four contexts are searched in the reverse order from which they are
188 * listed (but see checkEnvFirst). 188 * listed (but see checkEnvFirst).
189 */ 189 */
190GNode *VAR_INTERNAL; /* variables from make itself */ 190GNode *VAR_INTERNAL; /* variables from make itself */
191GNode *VAR_GLOBAL; /* variables from the makefile */ 191GNode *VAR_GLOBAL; /* variables from the makefile */
192GNode *VAR_CMD; /* variables defined on the command-line */ 192GNode *VAR_CMD; /* variables defined on the command-line */
193 193
194typedef enum { 194typedef enum {
195 FIND_CMD = 0x01, /* look in VAR_CMD when searching */ 195 FIND_CMD = 0x01, /* look in VAR_CMD when searching */
196 FIND_GLOBAL = 0x02, /* look in VAR_GLOBAL as well */ 196 FIND_GLOBAL = 0x02, /* look in VAR_GLOBAL as well */
197 FIND_ENV = 0x04 /* look in the environment also */ 197 FIND_ENV = 0x04 /* look in the environment also */
198} VarFindFlags; 198} VarFindFlags;
199 199
200typedef enum { 200typedef enum {
201 VAR_IN_USE = 0x01, /* Variable's value is currently being used 201 VAR_IN_USE = 0x01, /* Variable's value is currently being used
202 * by Var_Parse or Var_Subst. 202 * by Var_Parse or Var_Subst.
203 * Used to avoid endless recursion */ 203 * Used to avoid endless recursion */
204 VAR_FROM_ENV = 0x02, /* Variable comes from the environment */ 204 VAR_FROM_ENV = 0x02, /* Variable comes from the environment */
205 VAR_JUNK = 0x04, /* Variable is a junk variable that 205 VAR_JUNK = 0x04, /* Variable is a junk variable that
206 * should be destroyed when done with 206 * should be destroyed when done with
207 * it. Used by Var_Parse for undefined, 207 * it. Used by Var_Parse for undefined,
208 * modified variables */ 208 * modified variables */
209 VAR_KEEP = 0x08, /* Variable is VAR_JUNK, but we found 209 VAR_KEEP = 0x08, /* Variable is VAR_JUNK, but we found
210 * a use for it in some modifier and 210 * a use for it in some modifier and
211 * the value is therefore valid */ 211 * the value is therefore valid */
212 VAR_EXPORTED = 0x10, /* Variable is exported */ 212 VAR_EXPORTED = 0x10, /* Variable is exported */
213 VAR_REEXPORT = 0x20, /* Indicate if var needs re-export. 213 VAR_REEXPORT = 0x20, /* Indicate if var needs re-export.
214 * This would be true if it contains $'s */ 214 * This would be true if it contains $'s */
215 VAR_FROM_CMD = 0x40 /* Variable came from command line */ 215 VAR_FROM_CMD = 0x40 /* Variable came from command line */
216} Var_Flags; 216} Var_Flags;
217 217
218typedef struct Var { 218typedef struct Var {
219 char *name; /* the variable's name */ 219 char *name; /* the variable's name */
220 Buffer val; /* its value */ 220 Buffer val; /* its value */
221 Var_Flags flags; /* miscellaneous status flags */ 221 Var_Flags flags; /* miscellaneous status flags */
222} Var; 222} Var;
223 223
224/* 224/*
225 * Exporting vars is expensive so skip it if we can 225 * Exporting vars is expensive so skip it if we can
226 */ 226 */
227typedef enum { 227typedef enum {
228 VAR_EXPORTED_NONE, 228 VAR_EXPORTED_NONE,
229 VAR_EXPORTED_YES, 229 VAR_EXPORTED_YES,
230 VAR_EXPORTED_ALL 230 VAR_EXPORTED_ALL
231} VarExportedMode; 231} VarExportedMode;
232static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE; 232static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
233 233
234typedef enum { 234typedef enum {
235 /* 235 /*
236 * We pass this to Var_Export when doing the initial export 236 * We pass this to Var_Export when doing the initial export
237 * or after updating an exported var. 237 * or after updating an exported var.
238 */ 238 */
239 VAR_EXPORT_PARENT = 0x01, 239 VAR_EXPORT_PARENT = 0x01,
240 /* 240 /*
241 * We pass this to Var_Export1 to tell it to leave the value alone. 241 * We pass this to Var_Export1 to tell it to leave the value alone.
242 */ 242 */
243 VAR_EXPORT_LITERAL = 0x02 243 VAR_EXPORT_LITERAL = 0x02
244} VarExportFlags; 244} VarExportFlags;
245 245
246/* Flags for pattern matching in the :S and :C modifiers */ 246/* Flags for pattern matching in the :S and :C modifiers */
247typedef enum { 247typedef enum {
248 VARP_SUB_GLOBAL = 0x01, /* Apply substitution globally */ 248 VARP_SUB_GLOBAL = 0x01, /* Apply substitution globally */
249 VARP_SUB_ONE = 0x02, /* Apply substitution to one word */ 249 VARP_SUB_ONE = 0x02, /* Apply substitution to one word */
250 VARP_SUB_MATCHED = 0x04, /* There was a match */ 250 VARP_SUB_MATCHED = 0x04, /* There was a match */
251 VARP_ANCHOR_START = 0x08, /* Match at start of word */ 251 VARP_ANCHOR_START = 0x08, /* Match at start of word */
252 VARP_ANCHOR_END = 0x10 /* Match at end of word */ 252 VARP_ANCHOR_END = 0x10 /* Match at end of word */
253} VarPatternFlags; 253} VarPatternFlags;
254 254
255typedef enum { 255typedef enum {
256 VAR_NO_EXPORT = 0x01 /* do not export */ 256 VAR_NO_EXPORT = 0x01 /* do not export */
257} VarSet_Flags; 257} VarSet_Flags;
258 258
259#define BROPEN '{' 259#define BROPEN '{'
260#define BRCLOSE '}' 260#define BRCLOSE '}'
261#define PROPEN '(' 261#define PROPEN '('
262#define PRCLOSE ')' 262#define PRCLOSE ')'
263 263
264/*- 264/*-
265 *----------------------------------------------------------------------- 265 *-----------------------------------------------------------------------
266 * VarFind -- 266 * VarFind --
267 * Find the given variable in the given context and any other contexts 267 * Find the given variable in the given context and any other contexts
268 * indicated. 268 * indicated.
269 * 269 *
270 * Input: 270 * Input:
271 * name name to find 271 * name name to find
272 * ctxt context in which to find it 272 * ctxt context in which to find it
273 * flags FIND_GLOBAL look in VAR_GLOBAL as well 273 * flags FIND_GLOBAL look in VAR_GLOBAL as well
274 * FIND_CMD look in VAR_CMD as well 274 * FIND_CMD look in VAR_CMD as well
275 * FIND_ENV look in the environment as well 275 * FIND_ENV look in the environment as well
276 * 276 *
277 * Results: 277 * Results:
278 * A pointer to the structure describing the desired variable or 278 * A pointer to the structure describing the desired variable or
279 * NULL if the variable does not exist. 279 * NULL if the variable does not exist.
280 * 280 *
281 * Side Effects: 281 * Side Effects:
282 * None 282 * None
283 *----------------------------------------------------------------------- 283 *-----------------------------------------------------------------------
284 */ 284 */
285static Var * 285static Var *
286VarFind(const char *name, GNode *ctxt, VarFindFlags flags) 286VarFind(const char *name, GNode *ctxt, VarFindFlags flags)
287{ 287{
288 /* 288 /*
289 * If the variable name begins with a '.', it could very well be one of 289 * If the variable name begins with a '.', it could very well be one of
290 * the local ones. We check the name against all the local variables 290 * the local ones. We check the name against all the local variables
291 * and substitute the short version in for 'name' if it matches one of 291 * and substitute the short version in for 'name' if it matches one of
292 * them. 292 * them.
293 */ 293 */
294 if (*name == '.' && isupper((unsigned char) name[1])) { 294 if (*name == '.' && isupper((unsigned char) name[1])) {
295 switch (name[1]) { 295 switch (name[1]) {
296 case 'A': 296 case 'A':
297 if (strcmp(name, ".ALLSRC") == 0) 297 if (strcmp(name, ".ALLSRC") == 0)
298 name = ALLSRC; 298 name = ALLSRC;
299 if (strcmp(name, ".ARCHIVE") == 0) 299 if (strcmp(name, ".ARCHIVE") == 0)
300 name = ARCHIVE; 300 name = ARCHIVE;
301 break; 301 break;
302 case 'I': 302 case 'I':
303 if (strcmp(name, ".IMPSRC") == 0) 303 if (strcmp(name, ".IMPSRC") == 0)
304 name = IMPSRC; 304 name = IMPSRC;
305 break; 305 break;
306 case 'M': 306 case 'M':
307 if (strcmp(name, ".MEMBER") == 0) 307 if (strcmp(name, ".MEMBER") == 0)
308 name = MEMBER; 308 name = MEMBER;
309 break; 309 break;
310 case 'O': 310 case 'O':
311 if (strcmp(name, ".OODATE") == 0) 311 if (strcmp(name, ".OODATE") == 0)
312 name = OODATE; 312 name = OODATE;
313 break; 313 break;
314 case 'P': 314 case 'P':
315 if (strcmp(name, ".PREFIX") == 0) 315 if (strcmp(name, ".PREFIX") == 0)
316 name = PREFIX; 316 name = PREFIX;
317 break; 317 break;
318 case 'T': 318 case 'T':
319 if (strcmp(name, ".TARGET") == 0) 319 if (strcmp(name, ".TARGET") == 0)
320 name = TARGET; 320 name = TARGET;
321 break; 321 break;
322 } 322 }
323 } 323 }
324 324
325#ifdef notyet 325#ifdef notyet
326 /* for compatibility with gmake */ 326 /* for compatibility with gmake */
327 if (name[0] == '^' && name[1] == '\0') 327 if (name[0] == '^' && name[1] == '\0')
328 name = ALLSRC; 328 name = ALLSRC;
329#endif 329#endif
330 330
331 /* 331 /*
332 * First look for the variable in the given context. If it's not there, 332 * First look for the variable in the given context. If it's not there,
333 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order, 333 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
334 * depending on the FIND_* flags in 'flags' 334 * depending on the FIND_* flags in 'flags'
335 */ 335 */
336 Hash_Entry *var = Hash_FindEntry(&ctxt->context, name); 336 Hash_Entry *var = Hash_FindEntry(&ctxt->context, name);
337 337
338 if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD) { 338 if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD) {
339 var = Hash_FindEntry(&VAR_CMD->context, name); 339 var = Hash_FindEntry(&VAR_CMD->context, name);
340 } 340 }
341 if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) && 341 if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) &&
342 ctxt != VAR_GLOBAL) 342 ctxt != VAR_GLOBAL)
343 { 343 {
344 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 344 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
345 if (var == NULL && ctxt != VAR_INTERNAL) { 345 if (var == NULL && ctxt != VAR_INTERNAL) {
346 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */ 346 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
347 var = Hash_FindEntry(&VAR_INTERNAL->context, name); 347 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
348 } 348 }
349 } 349 }
350 if (var == NULL && (flags & FIND_ENV)) { 350 if (var == NULL && (flags & FIND_ENV)) {
351 char *env; 351 char *env;
352 352
353 if ((env = getenv(name)) != NULL) { 353 if ((env = getenv(name)) != NULL) {
354 Var *v = bmake_malloc(sizeof(Var)); 354 Var *v = bmake_malloc(sizeof(Var));
355 v->name = bmake_strdup(name); 355 v->name = bmake_strdup(name);
356 356
357 int len = (int)strlen(env); 357 int len = (int)strlen(env);
358 Buf_Init(&v->val, len + 1); 358 Buf_Init(&v->val, len + 1);
359 Buf_AddBytes(&v->val, len, env); 359 Buf_AddBytes(&v->val, len, env);
360 360
361 v->flags = VAR_FROM_ENV; 361 v->flags = VAR_FROM_ENV;
362 return v; 362 return v;
363 } else if (checkEnvFirst && (flags & FIND_GLOBAL) && 363 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
364 ctxt != VAR_GLOBAL) 364 ctxt != VAR_GLOBAL)
365 { 365 {
366 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 366 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
367 if (var == NULL && ctxt != VAR_INTERNAL) { 367 if (var == NULL && ctxt != VAR_INTERNAL) {
368 var = Hash_FindEntry(&VAR_INTERNAL->context, name); 368 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
369 } 369 }
370 if (var == NULL) { 370 if (var == NULL) {
371 return NULL; 371 return NULL;
372 } else { 372 } else {
373 return (Var *)Hash_GetValue(var); 373 return (Var *)Hash_GetValue(var);
374 } 374 }
375 } else { 375 } else {
376 return NULL; 376 return NULL;
377 } 377 }
378 } else if (var == NULL) { 378 } else if (var == NULL) {
379 return NULL; 379 return NULL;
380 } else { 380 } else {
381 return (Var *)Hash_GetValue(var); 381 return (Var *)Hash_GetValue(var);
382 } 382 }
383} 383}
384 384
385/*- 385/*-
386 *----------------------------------------------------------------------- 386 *-----------------------------------------------------------------------
387 * VarFreeEnv -- 387 * VarFreeEnv --
388 * If the variable is an environment variable, free it 388 * If the variable is an environment variable, free it
389 * 389 *
390 * Input: 390 * Input:
391 * v the variable 391 * v the variable
392 * destroy true if the value buffer should be destroyed. 392 * destroy true if the value buffer should be destroyed.
393 * 393 *
394 * Results: 394 * Results:
395 * 1 if it is an environment variable 0 ow. 395 * 1 if it is an environment variable 0 ow.
396 * 396 *
397 * Side Effects: 397 * Side Effects:
398 * The variable is free'ed if it is an environent variable. 398 * The variable is free'ed if it is an environent variable.
399 *----------------------------------------------------------------------- 399 *-----------------------------------------------------------------------
400 */ 400 */
401static Boolean 401static Boolean
402VarFreeEnv(Var *v, Boolean destroy) 402VarFreeEnv(Var *v, Boolean destroy)
403{ 403{
404 if (!(v->flags & VAR_FROM_ENV)) 404 if (!(v->flags & VAR_FROM_ENV))
405 return FALSE; 405 return FALSE;
406 free(v->name); 406 free(v->name);
407 Buf_Destroy(&v->val, destroy); 407 Buf_Destroy(&v->val, destroy);
408 free(v); 408 free(v);
409 return TRUE; 409 return TRUE;
410} 410}
411 411
412/*- 412/*-
413 *----------------------------------------------------------------------- 413 *-----------------------------------------------------------------------
414 * VarAdd -- 414 * VarAdd --
415 * Add a new variable of name name and value val to the given context 415 * Add a new variable of name name and value val to the given context
416 * 416 *
417 * Input: 417 * Input:
418 * name name of variable to add 418 * name name of variable to add
419 * val value to set it to 419 * val value to set it to
420 * ctxt context in which to set it 420 * ctxt context in which to set it
421 * 421 *
422 * Side Effects: 422 * Side Effects:
423 * The new variable is placed at the front of the given context 423 * The new variable is placed at the front of the given context
424 * The name and val arguments are duplicated so they may 424 * The name and val arguments are duplicated so they may
425 * safely be freed. 425 * safely be freed.
426 *----------------------------------------------------------------------- 426 *-----------------------------------------------------------------------
427 */ 427 */
428static void 428static void
429VarAdd(const char *name, const char *val, GNode *ctxt) 429VarAdd(const char *name, const char *val, GNode *ctxt)
430{ 430{
431 Var *v = bmake_malloc(sizeof(Var)); 431 Var *v = bmake_malloc(sizeof(Var));
432 432
433 int len = val != NULL ? (int)strlen(val) : 0; 433 int len = val != NULL ? (int)strlen(val) : 0;
434 Buf_Init(&v->val, len + 1); 434 Buf_Init(&v->val, len + 1);
435 Buf_AddBytes(&v->val, len, val); 435 Buf_AddBytes(&v->val, len, val);
436 436
437 v->flags = 0; 437 v->flags = 0;
438 438
439 Hash_Entry *h = Hash_CreateEntry(&ctxt->context, name, NULL); 439 Hash_Entry *h = Hash_CreateEntry(&ctxt->context, name, NULL);
440 Hash_SetValue(h, v); 440 Hash_SetValue(h, v);
441 v->name = h->name; 441 v->name = h->name;
442 if (DEBUG(VAR) && !(ctxt->flags & INTERNAL)) { 442 if (DEBUG(VAR) && !(ctxt->flags & INTERNAL)) {
443 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 443 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
444 } 444 }
445} 445}
446 446
447/*- 447/*-
448 *----------------------------------------------------------------------- 448 *-----------------------------------------------------------------------
449 * Var_Delete -- 449 * Var_Delete --
450 * Remove a variable from a context. 450 * Remove a variable from a context.
451 * 451 *
452 * Side Effects: 452 * Side Effects:
453 * The Var structure is removed and freed. 453 * The Var structure is removed and freed.
454 * 454 *
455 *----------------------------------------------------------------------- 455 *-----------------------------------------------------------------------
456 */ 456 */
457void 457void
458Var_Delete(const char *name, GNode *ctxt) 458Var_Delete(const char *name, GNode *ctxt)
459{ 459{
460 Hash_Entry *ln; 460 Hash_Entry *ln;
461 char *cp; 461 char *cp;
462 462
463 if (strchr(name, '$') != NULL) { 463 if (strchr(name, '$') != NULL) {
464 cp = Var_Subst(NULL, name, VAR_GLOBAL, VARE_WANTRES); 464 cp = Var_Subst(NULL, name, VAR_GLOBAL, VARE_WANTRES);
465 } else { 465 } else {
466 cp = UNCONST(name); 466 cp = UNCONST(name);
467 } 467 }
468 ln = Hash_FindEntry(&ctxt->context, cp); 468 ln = Hash_FindEntry(&ctxt->context, cp);
469 if (DEBUG(VAR)) { 469 if (DEBUG(VAR)) {
470 fprintf(debug_file, "%s:delete %s%s\n", 470 fprintf(debug_file, "%s:delete %s%s\n",
471 ctxt->name, cp, ln ? "" : " (not found)"); 471 ctxt->name, cp, ln ? "" : " (not found)");
472 } 472 }
473 if (cp != name) 473 if (cp != name)
474 free(cp); 474 free(cp);
475 if (ln != NULL) { 475 if (ln != NULL) {
476 Var *v = (Var *)Hash_GetValue(ln); 476 Var *v = (Var *)Hash_GetValue(ln);
477 if (v->flags & VAR_EXPORTED) 477 if (v->flags & VAR_EXPORTED)
478 unsetenv(v->name); 478 unsetenv(v->name);
479 if (strcmp(MAKE_EXPORTED, v->name) == 0) 479 if (strcmp(MAKE_EXPORTED, v->name) == 0)
480 var_exportedVars = VAR_EXPORTED_NONE; 480 var_exportedVars = VAR_EXPORTED_NONE;
481 if (v->name != ln->name) 481 if (v->name != ln->name)
482 free(v->name); 482 free(v->name);
483 Hash_DeleteEntry(&ctxt->context, ln); 483 Hash_DeleteEntry(&ctxt->context, ln);
484 Buf_Destroy(&v->val, TRUE); 484 Buf_Destroy(&v->val, TRUE);
485 free(v); 485 free(v);
486 } 486 }
487} 487}
488 488
489 489
490/* 490/*
491 * Export a var. 491 * Export a var.
492 * We ignore make internal variables (those which start with '.') 492 * We ignore make internal variables (those which start with '.')
493 * Also we jump through some hoops to avoid calling setenv 493 * Also we jump through some hoops to avoid calling setenv
494 * more than necessary since it can leak. 494 * more than necessary since it can leak.
495 * We only manipulate flags of vars if 'parent' is set. 495 * We only manipulate flags of vars if 'parent' is set.
496 */ 496 */
497static int 497static int
498Var_Export1(const char *name, VarExportFlags flags) 498Var_Export1(const char *name, VarExportFlags flags)
499{ 499{
500 char tmp[BUFSIZ]; 500 char tmp[BUFSIZ];
501 Var *v; 501 Var *v;
502 char *val = NULL; 502 char *val = NULL;
503 int n; 503 int n;
504 VarExportFlags parent = flags & VAR_EXPORT_PARENT; 504 VarExportFlags parent = flags & VAR_EXPORT_PARENT;
505 505
506 if (*name == '.') 506 if (*name == '.')
507 return 0; /* skip internals */ 507 return 0; /* skip internals */
508 if (!name[1]) { 508 if (!name[1]) {
509 /* 509 /*
510 * A single char. 510 * A single char.
511 * If it is one of the vars that should only appear in 511 * If it is one of the vars that should only appear in
512 * local context, skip it, else we can get Var_Subst 512 * local context, skip it, else we can get Var_Subst
513 * into a loop. 513 * into a loop.
514 */ 514 */
515 switch (name[0]) { 515 switch (name[0]) {
516 case '@': 516 case '@':
517 case '%': 517 case '%':
518 case '*': 518 case '*':
519 case '!': 519 case '!':
520 return 0; 520 return 0;
521 } 521 }
522 } 522 }
523 v = VarFind(name, VAR_GLOBAL, 0); 523 v = VarFind(name, VAR_GLOBAL, 0);
524 if (v == NULL) 524 if (v == NULL)
525 return 0; 525 return 0;
526 if (!parent && 526 if (!parent &&
527 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) { 527 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) {
528 return 0; /* nothing to do */ 528 return 0; /* nothing to do */
529 } 529 }
530 val = Buf_GetAll(&v->val, NULL); 530 val = Buf_GetAll(&v->val, NULL);
531 if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) { 531 if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) {
532 if (parent) { 532 if (parent) {
533 /* 533 /*
534 * Flag this as something we need to re-export. 534 * Flag this as something we need to re-export.
535 * No point actually exporting it now though, 535 * No point actually exporting it now though,
536 * the child can do it at the last minute. 536 * the child can do it at the last minute.
537 */ 537 */
538 v->flags |= (VAR_EXPORTED | VAR_REEXPORT); 538 v->flags |= (VAR_EXPORTED | VAR_REEXPORT);
539 return 1; 539 return 1;
540 } 540 }
541 if (v->flags & VAR_IN_USE) { 541 if (v->flags & VAR_IN_USE) {
542 /* 542 /*
543 * We recursed while exporting in a child. 543 * We recursed while exporting in a child.
544 * This isn't going to end well, just skip it. 544 * This isn't going to end well, just skip it.
545 */ 545 */
546 return 0; 546 return 0;
547 } 547 }
548 n = snprintf(tmp, sizeof(tmp), "${%s}", name); 548 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
549 if (n < (int)sizeof(tmp)) { 549 if (n < (int)sizeof(tmp)) {
550 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 550 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
551 setenv(name, val, 1); 551 setenv(name, val, 1);
552 free(val); 552 free(val);
553 } 553 }
554 } else { 554 } else {
555 if (parent) 555 if (parent)
556 v->flags &= ~VAR_REEXPORT; /* once will do */ 556 v->flags &= ~VAR_REEXPORT; /* once will do */
557 if (parent || !(v->flags & VAR_EXPORTED)) 557 if (parent || !(v->flags & VAR_EXPORTED))
558 setenv(name, val, 1); 558 setenv(name, val, 1);
559 } 559 }
560 /* 560 /*
561 * This is so Var_Set knows to call Var_Export again... 561 * This is so Var_Set knows to call Var_Export again...
562 */ 562 */
563 if (parent) { 563 if (parent) {
564 v->flags |= VAR_EXPORTED; 564 v->flags |= VAR_EXPORTED;
565 } 565 }
566 return 1; 566 return 1;
567} 567}
568 568
569static void 569static void
570Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED) 570Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED)
571{ 571{
572 Var *var = entry; 572 Var *var = entry;
573 Var_Export1(var->name, 0); 573 Var_Export1(var->name, 0);
574} 574}
575 575
576/* 576/*
577 * This gets called from our children. 577 * This gets called from our children.
578 */ 578 */
579void 579void
580Var_ExportVars(void) 580Var_ExportVars(void)
581{ 581{
582 char tmp[BUFSIZ]; 582 char tmp[BUFSIZ];
583 char *val; 583 char *val;
584 int n; 584 int n;
585 585
586 /* 586 /*
587 * Several make's support this sort of mechanism for tracking 587 * Several make's support this sort of mechanism for tracking
588 * recursion - but each uses a different name. 588 * recursion - but each uses a different name.
589 * We allow the makefiles to update MAKELEVEL and ensure 589 * We allow the makefiles to update MAKELEVEL and ensure
590 * children see a correctly incremented value. 590 * children see a correctly incremented value.
591 */ 591 */
592 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1); 592 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
593 setenv(MAKE_LEVEL_ENV, tmp, 1); 593 setenv(MAKE_LEVEL_ENV, tmp, 1);
594 594
595 if (VAR_EXPORTED_NONE == var_exportedVars) 595 if (VAR_EXPORTED_NONE == var_exportedVars)
596 return; 596 return;
597 597
598 if (VAR_EXPORTED_ALL == var_exportedVars) { 598 if (VAR_EXPORTED_ALL == var_exportedVars) {
599 /* Ouch! This is crazy... */ 599 /* Ouch! This is crazy... */
600 Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL); 600 Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL);
601 return; 601 return;
602 } 602 }
603 /* 603 /*
604 * We have a number of exported vars, 604 * We have a number of exported vars,
605 */ 605 */
606 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}"); 606 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
607 if (n < (int)sizeof(tmp)) { 607 if (n < (int)sizeof(tmp)) {
608 char **av; 608 char **av;
609 char *as; 609 char *as;
610 int ac; 610 int ac;
611 int i; 611 int i;
612 612
613 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 613 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
614 if (*val) { 614 if (*val) {
615 av = brk_string(val, &ac, FALSE, &as); 615 av = brk_string(val, &ac, FALSE, &as);
616 for (i = 0; i < ac; i++) 616 for (i = 0; i < ac; i++)
617 Var_Export1(av[i], 0); 617 Var_Export1(av[i], 0);
618 free(as); 618 free(as);
619 free(av); 619 free(av);
620 } 620 }
621 free(val); 621 free(val);
622 } 622 }
623} 623}
624 624
625/* 625/*
626 * This is called when .export is seen or 626 * This is called when .export is seen or
627 * .MAKE.EXPORTED is modified. 627 * .MAKE.EXPORTED is modified.
628 * It is also called when any exported var is modified. 628 * It is also called when any exported var is modified.
629 */ 629 */
630void 630void
631Var_Export(char *str, int isExport) 631Var_Export(char *str, int isExport)
632{ 632{
633 char **av; 633 char **av;
634 char *as; 634 char *as;
635 VarExportFlags flags; 635 VarExportFlags flags;
636 int ac; 636 int ac;
637 int i; 637 int i;
638 638
639 if (isExport && (!str || !str[0])) { 639 if (isExport && (!str || !str[0])) {
640 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */ 640 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
641 return; 641 return;
642 } 642 }
643 643
644 flags = 0; 644 flags = 0;
645 if (strncmp(str, "-env", 4) == 0) { 645 if (strncmp(str, "-env", 4) == 0) {
646 str += 4; 646 str += 4;
647 } else if (strncmp(str, "-literal", 8) == 0) { 647 } else if (strncmp(str, "-literal", 8) == 0) {
648 str += 8; 648 str += 8;
649 flags |= VAR_EXPORT_LITERAL; 649 flags |= VAR_EXPORT_LITERAL;
650 } else { 650 } else {
651 flags |= VAR_EXPORT_PARENT; 651 flags |= VAR_EXPORT_PARENT;
652 } 652 }
653 653
654 char *val = Var_Subst(NULL, str, VAR_GLOBAL, VARE_WANTRES); 654 char *val = Var_Subst(NULL, str, VAR_GLOBAL, VARE_WANTRES);
655 if (*val) { 655 if (*val) {
656 av = brk_string(val, &ac, FALSE, &as); 656 av = brk_string(val, &ac, FALSE, &as);
657 for (i = 0; i < ac; i++) { 657 for (i = 0; i < ac; i++) {
658 const char *name = av[i]; 658 const char *name = av[i];
659 if (!name[1]) { 659 if (!name[1]) {
660 /* 660 /*
661 * A single char. 661 * A single char.
662 * If it is one of the vars that should only appear in 662 * If it is one of the vars that should only appear in
663 * local context, skip it, else we can get Var_Subst 663 * local context, skip it, else we can get Var_Subst
664 * into a loop. 664 * into a loop.
665 */ 665 */
666 switch (name[0]) { 666 switch (name[0]) {
667 case '@': 667 case '@':
668 case '%': 668 case '%':
669 case '*': 669 case '*':
670 case '!': 670 case '!':
671 continue; 671 continue;
672 } 672 }
673 } 673 }
674 if (Var_Export1(name, flags)) { 674 if (Var_Export1(name, flags)) {
675 if (VAR_EXPORTED_ALL != var_exportedVars) 675 if (VAR_EXPORTED_ALL != var_exportedVars)
676 var_exportedVars = VAR_EXPORTED_YES; 676 var_exportedVars = VAR_EXPORTED_YES;
677 if (isExport && (flags & VAR_EXPORT_PARENT)) { 677 if (isExport && (flags & VAR_EXPORT_PARENT)) {
678 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL); 678 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
679 } 679 }
680 } 680 }
681 } 681 }
682 free(as); 682 free(as);
683 free(av); 683 free(av);
684 } 684 }
685 free(val); 685 free(val);
686} 686}
687 687
688 688
689extern char **environ; 689extern char **environ;
690 690
691/* 691/*
692 * This is called when .unexport[-env] is seen. 692 * This is called when .unexport[-env] is seen.
693 * 693 *
694 * str must have the form "unexport[-env] varname...". 694 * str must have the form "unexport[-env] varname...".
695 */ 695 */
696void 696void
697Var_UnExport(char *str) 697Var_UnExport(char *str)
698{ 698{
699 char tmp[BUFSIZ]; 699 char tmp[BUFSIZ];
700 char *vlist; 700 char *vlist;
701 char *cp; 701 char *cp;
702 Boolean unexport_env; 702 Boolean unexport_env;
703 int n; 703 int n;
704 704
705 vlist = NULL; 705 vlist = NULL;
706 706
707 str += strlen("unexport"); 707 str += strlen("unexport");
708 unexport_env = (strncmp(str, "-env", 4) == 0); 708 unexport_env = (strncmp(str, "-env", 4) == 0);
709 if (unexport_env) { 709 if (unexport_env) {
710 char **newenv; 710 char **newenv;
711 711
712 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */ 712 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
713 if (environ == savedEnv) { 713 if (environ == savedEnv) {
714 /* we have been here before! */ 714 /* we have been here before! */
715 newenv = bmake_realloc(environ, 2 * sizeof(char *)); 715 newenv = bmake_realloc(environ, 2 * sizeof(char *));
716 } else { 716 } else {
717 if (savedEnv) { 717 if (savedEnv) {
718 free(savedEnv); 718 free(savedEnv);
719 savedEnv = NULL; 719 savedEnv = NULL;
720 } 720 }
721 newenv = bmake_malloc(2 * sizeof(char *)); 721 newenv = bmake_malloc(2 * sizeof(char *));
722 } 722 }
723 if (!newenv) 723 if (!newenv)
724 return; 724 return;
725 /* Note: we cannot safely free() the original environ. */ 725 /* Note: we cannot safely free() the original environ. */
726 environ = savedEnv = newenv; 726 environ = savedEnv = newenv;
727 newenv[0] = NULL; 727 newenv[0] = NULL;
728 newenv[1] = NULL; 728 newenv[1] = NULL;
729 if (cp && *cp) 729 if (cp && *cp)
730 setenv(MAKE_LEVEL_ENV, cp, 1); 730 setenv(MAKE_LEVEL_ENV, cp, 1);
731 } else { 731 } else {
732 for (; *str != '\n' && isspace((unsigned char) *str); str++) 732 for (; *str != '\n' && isspace((unsigned char) *str); str++)
733 continue; 733 continue;
734 if (str[0] && str[0] != '\n') { 734 if (str[0] && str[0] != '\n') {
735 vlist = str; 735 vlist = str;
736 } 736 }
737 } 737 }
738 738
739 if (!vlist) { 739 if (!vlist) {
740 /* Using .MAKE.EXPORTED */ 740 /* Using .MAKE.EXPORTED */
741 vlist = Var_Subst(NULL, "${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL, 741 vlist = Var_Subst(NULL, "${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL,
742 VARE_WANTRES); 742 VARE_WANTRES);
743 } 743 }
744 if (vlist) { 744 if (vlist) {
745 Var *v; 745 Var *v;
746 char **av; 746 char **av;
747 char *as; 747 char *as;
748 int ac; 748 int ac;
749 int i; 749 int i;
750 750
751 av = brk_string(vlist, &ac, FALSE, &as); 751 av = brk_string(vlist, &ac, FALSE, &as);
752 for (i = 0; i < ac; i++) { 752 for (i = 0; i < ac; i++) {
753 v = VarFind(av[i], VAR_GLOBAL, 0); 753 v = VarFind(av[i], VAR_GLOBAL, 0);
754 if (!v) 754 if (!v)
755 continue; 755 continue;
756 if (!unexport_env && 756 if (!unexport_env &&
757 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) 757 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED)
758 unsetenv(v->name); 758 unsetenv(v->name);
759 v->flags &= ~(VAR_EXPORTED | VAR_REEXPORT); 759 v->flags &= ~(VAR_EXPORTED | VAR_REEXPORT);
760 /* 760 /*
761 * If we are unexporting a list, 761 * If we are unexporting a list,
762 * remove each one from .MAKE.EXPORTED. 762 * remove each one from .MAKE.EXPORTED.
763 * If we are removing them all, 763 * If we are removing them all,
764 * just delete .MAKE.EXPORTED below. 764 * just delete .MAKE.EXPORTED below.
765 */ 765 */
766 if (vlist == str) { 766 if (vlist == str) {
767 n = snprintf(tmp, sizeof(tmp), 767 n = snprintf(tmp, sizeof(tmp),
768 "${" MAKE_EXPORTED ":N%s}", v->name); 768 "${" MAKE_EXPORTED ":N%s}", v->name);
769 if (n < (int)sizeof(tmp)) { 769 if (n < (int)sizeof(tmp)) {
770 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 770 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
771 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL); 771 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL);
772 free(cp); 772 free(cp);
773 } 773 }
774 } 774 }
775 } 775 }
776 free(as); 776 free(as);
777 free(av); 777 free(av);
778 if (vlist != str) { 778 if (vlist != str) {
779 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL); 779 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
780 free(vlist); 780 free(vlist);
781 } 781 }
782 } 782 }
783} 783}
784 784
785static void 785static void
786Var_Set_with_flags(const char *name, const char *val, GNode *ctxt, 786Var_Set_with_flags(const char *name, const char *val, GNode *ctxt,
787 VarSet_Flags flags) 787 VarSet_Flags flags)
788{ 788{
789 Var *v; 789 Var *v;
790 char *expanded_name = NULL; 790 char *expanded_name = NULL;
791 791
792 /* 792 /*
793 * We only look for a variable in the given context since anything set 793 * We only look for a variable in the given context since anything set
794 * here will override anything in a lower context, so there's not much 794 * here will override anything in a lower context, so there's not much
795 * point in searching them all just to save a bit of memory... 795 * point in searching them all just to save a bit of memory...
796 */ 796 */
797 if (strchr(name, '$') != NULL) { 797 if (strchr(name, '$') != NULL) {
798 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 798 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
799 if (expanded_name[0] == '\0') { 799 if (expanded_name[0] == '\0') {
800 if (DEBUG(VAR)) { 800 if (DEBUG(VAR)) {
801 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) " 801 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
802 "name expands to empty string - ignored\n", 802 "name expands to empty string - ignored\n",
803 name, val); 803 name, val);
804 } 804 }
805 free(expanded_name); 805 free(expanded_name);
806 return; 806 return;
807 } 807 }
808 name = expanded_name; 808 name = expanded_name;
809 } 809 }
810 if (ctxt == VAR_GLOBAL) { 810 if (ctxt == VAR_GLOBAL) {
811 v = VarFind(name, VAR_CMD, 0); 811 v = VarFind(name, VAR_CMD, 0);
812 if (v != NULL) { 812 if (v != NULL) {
813 if ((v->flags & VAR_FROM_CMD)) { 813 if ((v->flags & VAR_FROM_CMD)) {
814 if (DEBUG(VAR)) { 814 if (DEBUG(VAR)) {
815 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val); 815 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
816 } 816 }
817 goto out; 817 goto out;
818 } 818 }
819 VarFreeEnv(v, TRUE); 819 VarFreeEnv(v, TRUE);
820 } 820 }
821 } 821 }
822 v = VarFind(name, ctxt, 0); 822 v = VarFind(name, ctxt, 0);
823 if (v == NULL) { 823 if (v == NULL) {
824 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { 824 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
825 /* 825 /*
826 * This var would normally prevent the same name being added 826 * This var would normally prevent the same name being added
827 * to VAR_GLOBAL, so delete it from there if needed. 827 * to VAR_GLOBAL, so delete it from there if needed.
828 * Otherwise -V name may show the wrong value. 828 * Otherwise -V name may show the wrong value.
829 */ 829 */
830 Var_Delete(name, VAR_GLOBAL); 830 Var_Delete(name, VAR_GLOBAL);
831 } 831 }
832 VarAdd(name, val, ctxt); 832 VarAdd(name, val, ctxt);
833 } else { 833 } else {
834 Buf_Empty(&v->val); 834 Buf_Empty(&v->val);
835 if (val) 835 if (val)
836 Buf_AddStr(&v->val, val); 836 Buf_AddStr(&v->val, val);
837 837
838 if (DEBUG(VAR)) { 838 if (DEBUG(VAR)) {
839 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 839 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
840 } 840 }
841 if ((v->flags & VAR_EXPORTED)) { 841 if ((v->flags & VAR_EXPORTED)) {
842 Var_Export1(name, VAR_EXPORT_PARENT); 842 Var_Export1(name, VAR_EXPORT_PARENT);
843 } 843 }
844 } 844 }
845 /* 845 /*
846 * Any variables given on the command line are automatically exported 846 * Any variables given on the command line are automatically exported
847 * to the environment (as per POSIX standard) 847 * to the environment (as per POSIX standard)
848 */ 848 */
849 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { 849 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
850 if (v == NULL) { 850 if (v == NULL) {
851 /* we just added it */ 851 /* we just added it */
852 v = VarFind(name, ctxt, 0); 852 v = VarFind(name, ctxt, 0);
853 } 853 }
854 if (v != NULL) 854 if (v != NULL)
855 v->flags |= VAR_FROM_CMD; 855 v->flags |= VAR_FROM_CMD;
856 /* 856 /*
857 * If requested, don't export these in the environment 857 * If requested, don't export these in the environment
858 * individually. We still put them in MAKEOVERRIDES so 858 * individually. We still put them in MAKEOVERRIDES so
859 * that the command-line settings continue to override 859 * that the command-line settings continue to override
860 * Makefile settings. 860 * Makefile settings.
861 */ 861 */
862 if (varNoExportEnv != TRUE) 862 if (varNoExportEnv != TRUE)
863 setenv(name, val ? val : "", 1); 863 setenv(name, val ? val : "", 1);
864 864
865 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL); 865 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
866 } 866 }
867 if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0) 867 if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0)
868 save_dollars = s2Boolean(val, save_dollars); 868 save_dollars = s2Boolean(val, save_dollars);
869 869
870out: 870out:
871 free(expanded_name); 871 free(expanded_name);
872 if (v != NULL) 872 if (v != NULL)
873 VarFreeEnv(v, TRUE); 873 VarFreeEnv(v, TRUE);
874} 874}
875 875
876/*- 876/*-
877 *----------------------------------------------------------------------- 877 *-----------------------------------------------------------------------
878 * Var_Set -- 878 * Var_Set --
879 * Set the variable name to the value val in the given context. 879 * Set the variable name to the value val in the given context.
880 * 880 *
881 * Input: 881 * Input:
882 * name name of variable to set 882 * name name of variable to set
883 * val value to give to the variable 883 * val value to give to the variable
884 * ctxt context in which to set it 884 * ctxt context in which to set it
885 * 885 *
886 * Side Effects: 886 * Side Effects:
887 * If the variable doesn't yet exist, a new record is created for it. 887 * If the variable doesn't yet exist, a new record is created for it.
888 * Else the old value is freed and the new one stuck in its place 888 * Else the old value is freed and the new one stuck in its place
889 * 889 *
890 * Notes: 890 * Notes:
891 * The variable is searched for only in its context before being 891 * The variable is searched for only in its context before being
892 * created in that context. I.e. if the context is VAR_GLOBAL, 892 * created in that context. I.e. if the context is VAR_GLOBAL,
893 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only 893 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
894 * VAR_CMD->context is searched. This is done to avoid the literally 894 * VAR_CMD->context is searched. This is done to avoid the literally
895 * thousands of unnecessary strcmp's that used to be done to 895 * thousands of unnecessary strcmp's that used to be done to
896 * set, say, $(@) or $(<). 896 * set, say, $(@) or $(<).
897 * If the context is VAR_GLOBAL though, we check if the variable 897 * If the context is VAR_GLOBAL though, we check if the variable
898 * was set in VAR_CMD from the command line and skip it if so. 898 * was set in VAR_CMD from the command line and skip it if so.
899 *----------------------------------------------------------------------- 899 *-----------------------------------------------------------------------
900 */ 900 */
901void 901void
902Var_Set(const char *name, const char *val, GNode *ctxt) 902Var_Set(const char *name, const char *val, GNode *ctxt)
903{ 903{
904 Var_Set_with_flags(name, val, ctxt, 0); 904 Var_Set_with_flags(name, val, ctxt, 0);
905} 905}
906 906
907/*- 907/*-
908 *----------------------------------------------------------------------- 908 *-----------------------------------------------------------------------
909 * Var_Append -- 909 * Var_Append --
910 * The variable of the given name has the given value appended to it in 910 * The variable of the given name has the given value appended to it in
911 * the given context. 911 * the given context.
912 * 912 *
913 * Input: 913 * Input:
914 * name name of variable to modify 914 * name name of variable to modify
915 * val String to append to it 915 * val String to append to it
916 * ctxt Context in which this should occur 916 * ctxt Context in which this should occur
917 * 917 *
918 * Side Effects: 918 * Side Effects:
919 * If the variable doesn't exist, it is created. Else the strings 919 * If the variable doesn't exist, it is created. Else the strings
920 * are concatenated (with a space in between). 920 * are concatenated (with a space in between).
921 * 921 *
922 * Notes: 922 * Notes:
923 * Only if the variable is being sought in the global context is the 923 * Only if the variable is being sought in the global context is the
924 * environment searched. 924 * environment searched.
925 * XXX: Knows its calling circumstances in that if called with ctxt 925 * XXX: Knows its calling circumstances in that if called with ctxt
926 * an actual target, it will only search that context since only 926 * an actual target, it will only search that context since only
927 * a local variable could be being appended to. This is actually 927 * a local variable could be being appended to. This is actually
928 * a big win and must be tolerated. 928 * a big win and must be tolerated.
929 *----------------------------------------------------------------------- 929 *-----------------------------------------------------------------------
930 */ 930 */
931void 931void
932Var_Append(const char *name, const char *val, GNode *ctxt) 932Var_Append(const char *name, const char *val, GNode *ctxt)
933{ 933{
934 Var *v; 934 Var *v;
935 Hash_Entry *h; 935 Hash_Entry *h;
936 char *expanded_name = NULL; 936 char *expanded_name = NULL;
937 937
938 if (strchr(name, '$') != NULL) { 938 if (strchr(name, '$') != NULL) {
939 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 939 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
940 if (expanded_name[0] == '\0') { 940 if (expanded_name[0] == '\0') {
941 if (DEBUG(VAR)) { 941 if (DEBUG(VAR)) {
942 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) " 942 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
943 "name expands to empty string - ignored\n", 943 "name expands to empty string - ignored\n",
944 name, val); 944 name, val);
945 } 945 }
946 free(expanded_name); 946 free(expanded_name);
947 return; 947 return;
948 } 948 }
949 name = expanded_name; 949 name = expanded_name;
950 } 950 }
951 951
952 v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0); 952 v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0);
953 953
954 if (v == NULL) { 954 if (v == NULL) {
955 Var_Set(name, val, ctxt); 955 Var_Set(name, val, ctxt);
956 } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) { 956 } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) {
957 Buf_AddByte(&v->val, ' '); 957 Buf_AddByte(&v->val, ' ');
958 Buf_AddStr(&v->val, val); 958 Buf_AddStr(&v->val, val);
959 959
960 if (DEBUG(VAR)) { 960 if (DEBUG(VAR)) {
961 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, 961 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
962 Buf_GetAll(&v->val, NULL)); 962 Buf_GetAll(&v->val, NULL));
963 } 963 }
964 964
965 if (v->flags & VAR_FROM_ENV) { 965 if (v->flags & VAR_FROM_ENV) {
966 /* 966 /*
967 * If the original variable came from the environment, we 967 * If the original variable came from the environment, we
968 * have to install it in the global context (we could place 968 * have to install it in the global context (we could place
969 * it in the environment, but then we should provide a way to 969 * it in the environment, but then we should provide a way to
970 * export other variables...) 970 * export other variables...)
971 */ 971 */
972 v->flags &= ~VAR_FROM_ENV; 972 v->flags &= ~VAR_FROM_ENV;
973 h = Hash_CreateEntry(&ctxt->context, name, NULL); 973 h = Hash_CreateEntry(&ctxt->context, name, NULL);
974 Hash_SetValue(h, v); 974 Hash_SetValue(h, v);
975 } 975 }
976 } 976 }
977 free(expanded_name); 977 free(expanded_name);
978} 978}
979 979
980/*- 980/*-
981 *----------------------------------------------------------------------- 981 *-----------------------------------------------------------------------
982 * Var_Exists -- 982 * Var_Exists --
983 * See if the given variable exists. 983 * See if the given variable exists.
984 * 984 *
985 * Input: 985 * Input:
986 * name Variable to find 986 * name Variable to find
987 * ctxt Context in which to start search 987 * ctxt Context in which to start search
988 * 988 *
989 * Results: 989 * Results:
990 * TRUE if it does, FALSE if it doesn't 990 * TRUE if it does, FALSE if it doesn't
991 * 991 *
992 * Side Effects: 992 * Side Effects:
993 * None. 993 * None.
994 * 994 *
995 *----------------------------------------------------------------------- 995 *-----------------------------------------------------------------------
996 */ 996 */
997Boolean 997Boolean
998Var_Exists(const char *name, GNode *ctxt) 998Var_Exists(const char *name, GNode *ctxt)
999{ 999{
1000 Var *v; 1000 Var *v;
1001 char *cp; 1001 char *cp;
1002 1002
1003 if ((cp = strchr(name, '$')) != NULL) 1003 if ((cp = strchr(name, '$')) != NULL)
1004 cp = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 1004 cp = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
1005 v = VarFind(cp ? cp : name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV); 1005 v = VarFind(cp ? cp : name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
1006 free(cp); 1006 free(cp);
1007 if (v == NULL) 1007 if (v == NULL)
1008 return FALSE; 1008 return FALSE;
1009 1009
1010 (void)VarFreeEnv(v, TRUE); 1010 (void)VarFreeEnv(v, TRUE);
1011 return TRUE; 1011 return TRUE;
1012} 1012}
1013 1013
1014/*- 1014/*-
1015 *----------------------------------------------------------------------- 1015 *-----------------------------------------------------------------------
1016 * Var_Value -- 1016 * Var_Value --
1017 * Return the unexpanded value of the given variable in the given 1017 * Return the unexpanded value of the given variable in the given
1018 * context. 1018 * context.
1019 * 1019 *
1020 * Input: 1020 * Input:
1021 * name name to find 1021 * name name to find
1022 * ctxt context in which to search for it 1022 * ctxt context in which to search for it
1023 * 1023 *
1024 * Results: 1024 * Results:
1025 * The value if the variable exists, NULL if it doesn't. 1025 * The value if the variable exists, NULL if it doesn't.
1026 * If the returned value is not NULL, the caller must free *freeIt 1026 * If the returned value is not NULL, the caller must free *freeIt
1027 * as soon as the returned value is no longer needed. 1027 * as soon as the returned value is no longer needed.
1028 *----------------------------------------------------------------------- 1028 *-----------------------------------------------------------------------
1029 */ 1029 */
1030char * 1030char *
1031Var_Value(const char *name, GNode *ctxt, char **freeIt) 1031Var_Value(const char *name, GNode *ctxt, char **freeIt)
1032{ 1032{
1033 Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); 1033 Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1034 *freeIt = NULL; 1034 *freeIt = NULL;
1035 if (v == NULL) 1035 if (v == NULL)
1036 return NULL; 1036 return NULL;
1037 1037
1038 char *p = Buf_GetAll(&v->val, NULL); 1038 char *p = Buf_GetAll(&v->val, NULL);
1039 if (VarFreeEnv(v, FALSE)) 1039 if (VarFreeEnv(v, FALSE))
1040 *freeIt = p; 1040 *freeIt = p;
1041 return p; 1041 return p;
1042} 1042}
1043 1043
1044 1044
1045/* SepBuf is a string being built from "words", interleaved with separators. */ 1045/* SepBuf is a string being built from "words", interleaved with separators. */
1046typedef struct { 1046typedef struct {
1047 Buffer buf; 1047 Buffer buf;
1048 Boolean needSep; 1048 Boolean needSep;
1049 char sep; 1049 char sep;
1050} SepBuf; 1050} SepBuf;
1051 1051
1052static void 1052static void
1053SepBuf_Init(SepBuf *buf, char sep) 1053SepBuf_Init(SepBuf *buf, char sep)
1054{ 1054{
1055 Buf_Init(&buf->buf, 32 /* bytes */); 1055 Buf_Init(&buf->buf, 32 /* bytes */);
1056 buf->needSep = FALSE; 1056 buf->needSep = FALSE;
1057 buf->sep = sep; 1057 buf->sep = sep;
1058} 1058}
1059 1059
1060static void 1060static void
1061SepBuf_Sep(SepBuf *buf) 1061SepBuf_Sep(SepBuf *buf)
1062{ 1062{
1063 buf->needSep = TRUE; 1063 buf->needSep = TRUE;
1064} 1064}
1065 1065
1066static void 1066static void
1067SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size) 1067SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
1068{ 1068{
1069 if (mem_size == 0) 1069 if (mem_size == 0)
1070 return; 1070 return;
1071 if (buf->needSep && buf->sep != '\0') { 1071 if (buf->needSep && buf->sep != '\0') {
1072 Buf_AddByte(&buf->buf, buf->sep); 1072 Buf_AddByte(&buf->buf, buf->sep);
1073 buf->needSep = FALSE; 1073 buf->needSep = FALSE;
1074 } 1074 }
1075 Buf_AddBytes(&buf->buf, mem_size, mem); 1075 Buf_AddBytes(&buf->buf, mem_size, mem);
1076} 1076}
1077 1077
1078static void 1078static void
@@ -1355,2011 +1355,2006 @@ ModifyWord_Subst(const char *word, SepBu @@ -1355,2011 +1355,2006 @@ ModifyWord_Subst(const char *word, SepBu
1355nosub: 1355nosub:
1356 SepBuf_AddBytes(buf, word, wordLen); 1356 SepBuf_AddBytes(buf, word, wordLen);
1357} 1357}
1358 1358
1359#ifndef NO_REGEX 1359#ifndef NO_REGEX
1360/*- 1360/*-
1361 *----------------------------------------------------------------------- 1361 *-----------------------------------------------------------------------
1362 * VarREError -- 1362 * VarREError --
1363 * Print the error caused by a regcomp or regexec call. 1363 * Print the error caused by a regcomp or regexec call.
1364 * 1364 *
1365 * Side Effects: 1365 * Side Effects:
1366 * An error gets printed. 1366 * An error gets printed.
1367 * 1367 *
1368 *----------------------------------------------------------------------- 1368 *-----------------------------------------------------------------------
1369 */ 1369 */
1370static void 1370static void
1371VarREError(int reerr, regex_t *pat, const char *str) 1371VarREError(int reerr, regex_t *pat, const char *str)
1372{ 1372{
1373 char *errbuf; 1373 char *errbuf;
1374 int errlen; 1374 int errlen;
1375 1375
1376 errlen = regerror(reerr, pat, 0, 0); 1376 errlen = regerror(reerr, pat, 0, 0);
1377 errbuf = bmake_malloc(errlen); 1377 errbuf = bmake_malloc(errlen);
1378 regerror(reerr, pat, errbuf, errlen); 1378 regerror(reerr, pat, errbuf, errlen);
1379 Error("%s: %s", str, errbuf); 1379 Error("%s: %s", str, errbuf);
1380 free(errbuf); 1380 free(errbuf);
1381} 1381}
1382 1382
1383typedef struct { 1383typedef struct {
1384 regex_t re; 1384 regex_t re;
1385 int nsub; 1385 int nsub;
1386 char *replace; 1386 char *replace;
1387 VarPatternFlags pflags; 1387 VarPatternFlags pflags;
1388} ModifyWord_SubstRegexArgs; 1388} ModifyWord_SubstRegexArgs;
1389 1389
1390/* Callback for ModifyWords to implement the :C/from/to/ modifier. 1390/* Callback for ModifyWords to implement the :C/from/to/ modifier.
1391 * Perform a regex substitution on the given word. */ 1391 * Perform a regex substitution on the given word. */
1392static void 1392static void
1393ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data) 1393ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
1394{ 1394{
1395 ModifyWord_SubstRegexArgs *args = data; 1395 ModifyWord_SubstRegexArgs *args = data;
1396 int xrv; 1396 int xrv;
1397 const char *wp = word; 1397 const char *wp = word;
1398 char *rp; 1398 char *rp;
1399 int flags = 0; 1399 int flags = 0;
1400 regmatch_t m[10]; 1400 regmatch_t m[10];
1401 1401
1402 if ((args->pflags & VARP_SUB_ONE) && (args->pflags & VARP_SUB_MATCHED)) 1402 if ((args->pflags & VARP_SUB_ONE) && (args->pflags & VARP_SUB_MATCHED))
1403 goto nosub; 1403 goto nosub;
1404 1404
1405tryagain: 1405tryagain:
1406 xrv = regexec(&args->re, wp, args->nsub, m, flags); 1406 xrv = regexec(&args->re, wp, args->nsub, m, flags);
1407 1407
1408 switch (xrv) { 1408 switch (xrv) {
1409 case 0: 1409 case 0:
1410 args->pflags |= VARP_SUB_MATCHED; 1410 args->pflags |= VARP_SUB_MATCHED;
1411 SepBuf_AddBytes(buf, wp, m[0].rm_so); 1411 SepBuf_AddBytes(buf, wp, m[0].rm_so);
1412 1412
1413 for (rp = args->replace; *rp; rp++) { 1413 for (rp = args->replace; *rp; rp++) {
1414 if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) { 1414 if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
1415 SepBuf_AddBytes(buf, rp + 1, 1); 1415 SepBuf_AddBytes(buf, rp + 1, 1);
1416 rp++; 1416 rp++;
1417 } else if (*rp == '&' || 1417 } else if (*rp == '&' ||
1418 (*rp == '\\' && isdigit((unsigned char)rp[1]))) { 1418 (*rp == '\\' && isdigit((unsigned char)rp[1]))) {
1419 int n; 1419 int n;
1420 char errstr[3]; 1420 char errstr[3];
1421 1421
1422 if (*rp == '&') { 1422 if (*rp == '&') {
1423 n = 0; 1423 n = 0;
1424 errstr[0] = '&'; 1424 errstr[0] = '&';
1425 errstr[1] = '\0'; 1425 errstr[1] = '\0';
1426 } else { 1426 } else {
1427 n = rp[1] - '0'; 1427 n = rp[1] - '0';
1428 errstr[0] = '\\'; 1428 errstr[0] = '\\';
1429 errstr[1] = rp[1]; 1429 errstr[1] = rp[1];
1430 errstr[2] = '\0'; 1430 errstr[2] = '\0';
1431 rp++; 1431 rp++;
1432 } 1432 }
1433 1433
1434 if (n >= args->nsub) { 1434 if (n >= args->nsub) {
1435 Error("No subexpression %s", errstr); 1435 Error("No subexpression %s", errstr);
1436 } else if (m[n].rm_so == -1 && m[n].rm_eo == -1) { 1436 } else if (m[n].rm_so == -1 && m[n].rm_eo == -1) {
1437 Error("No match for subexpression %s", errstr); 1437 Error("No match for subexpression %s", errstr);
1438 } else { 1438 } else {
1439 SepBuf_AddBytesBetween(buf, wp + m[n].rm_so, 1439 SepBuf_AddBytesBetween(buf, wp + m[n].rm_so,
1440 wp + m[n].rm_eo); 1440 wp + m[n].rm_eo);
1441 } 1441 }
1442 1442
1443 } else { 1443 } else {
1444 SepBuf_AddBytes(buf, rp, 1); 1444 SepBuf_AddBytes(buf, rp, 1);
1445 } 1445 }
1446 } 1446 }
1447 wp += m[0].rm_eo; 1447 wp += m[0].rm_eo;
1448 if (args->pflags & VARP_SUB_GLOBAL) { 1448 if (args->pflags & VARP_SUB_GLOBAL) {
1449 flags |= REG_NOTBOL; 1449 flags |= REG_NOTBOL;
1450 if (m[0].rm_so == 0 && m[0].rm_eo == 0) { 1450 if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
1451 SepBuf_AddBytes(buf, wp, 1); 1451 SepBuf_AddBytes(buf, wp, 1);
1452 wp++; 1452 wp++;
1453 } 1453 }
1454 if (*wp) 1454 if (*wp)
1455 goto tryagain; 1455 goto tryagain;
1456 } 1456 }
1457 if (*wp) { 1457 if (*wp) {
1458 SepBuf_AddStr(buf, wp); 1458 SepBuf_AddStr(buf, wp);
1459 } 1459 }
1460 break; 1460 break;
1461 default: 1461 default:
1462 VarREError(xrv, &args->re, "Unexpected regex error"); 1462 VarREError(xrv, &args->re, "Unexpected regex error");
1463 /* fall through */ 1463 /* fall through */
1464 case REG_NOMATCH: 1464 case REG_NOMATCH:
1465 nosub: 1465 nosub:
1466 SepBuf_AddStr(buf, wp); 1466 SepBuf_AddStr(buf, wp);
1467 break; 1467 break;
1468 } 1468 }
1469} 1469}
1470#endif 1470#endif
1471 1471
1472 1472
1473typedef struct { 1473typedef struct {
1474 GNode *ctx; 1474 GNode *ctx;
1475 char *tvar; /* name of temporary variable */ 1475 char *tvar; /* name of temporary variable */
1476 char *str; /* string to expand */ 1476 char *str; /* string to expand */
1477 VarEvalFlags eflags; 1477 VarEvalFlags eflags;
1478} ModifyWord_LoopArgs; 1478} ModifyWord_LoopArgs;
1479 1479
1480/* Callback for ModifyWords to implement the :@var@...@ modifier of ODE make. */ 1480/* Callback for ModifyWords to implement the :@var@...@ modifier of ODE make. */
1481static void 1481static void
1482ModifyWord_Loop(const char *word, SepBuf *buf, void *data) 1482ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
1483{ 1483{
1484 if (word[0] == '\0') 1484 if (word[0] == '\0')
1485 return; 1485 return;
1486 1486
1487 const ModifyWord_LoopArgs *args = data; 1487 const ModifyWord_LoopArgs *args = data;
1488 Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT); 1488 Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT);
1489 char *s = Var_Subst(NULL, args->str, args->ctx, args->eflags); 1489 char *s = Var_Subst(NULL, args->str, args->ctx, args->eflags);
1490 if (DEBUG(VAR)) { 1490 if (DEBUG(VAR)) {
1491 fprintf(debug_file, 1491 fprintf(debug_file,
1492 "ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" " 1492 "ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" "
1493 "to \"%s\"\n", 1493 "to \"%s\"\n",
1494 word, args->tvar, args->str, s ? s : "(null)"); 1494 word, args->tvar, args->str, s ? s : "(null)");
1495 } 1495 }
1496 1496
1497 if (s != NULL && s[0] != '\0') { 1497 if (s != NULL && s[0] != '\0') {
1498 if (s[0] == '\n' || (buf->buf.count > 0 && 1498 if (s[0] == '\n' || (buf->buf.count > 0 &&
1499 buf->buf.buffer[buf->buf.count - 1] == '\n')) 1499 buf->buf.buffer[buf->buf.count - 1] == '\n'))
1500 buf->needSep = FALSE; 1500 buf->needSep = FALSE;
1501 SepBuf_AddStr(buf, s); 1501 SepBuf_AddStr(buf, s);
1502 } 1502 }
1503 free(s); 1503 free(s);
1504} 1504}
1505 1505
1506 1506
1507/*- 1507/*-
1508 * Implements the :[first..last] modifier. 1508 * Implements the :[first..last] modifier.
1509 * This is a special case of ModifyWords since we want to be able 1509 * This is a special case of ModifyWords since we want to be able
1510 * to scan the list backwards if first > last. 1510 * to scan the list backwards if first > last.
1511 */ 1511 */
1512static char * 1512static char *
1513VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first, 1513VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first,
1514 int last) 1514 int last)
1515{ 1515{
1516 SepBuf buf; 1516 SepBuf buf;
1517 char **av; /* word list */ 1517 char **av; /* word list */
1518 char *as; /* word list memory */ 1518 char *as; /* word list memory */
1519 int ac, i; 1519 int ac, i;
1520 int start, end, step; 1520 int start, end, step;
1521 1521
1522 SepBuf_Init(&buf, sep); 1522 SepBuf_Init(&buf, sep);
1523 1523
1524 if (oneBigWord) { 1524 if (oneBigWord) {
1525 /* fake what brk_string() would do if there were only one word */ 1525 /* fake what brk_string() would do if there were only one word */
1526 ac = 1; 1526 ac = 1;
1527 av = bmake_malloc((ac + 1) * sizeof(char *)); 1527 av = bmake_malloc((ac + 1) * sizeof(char *));
1528 as = bmake_strdup(str); 1528 as = bmake_strdup(str);
1529 av[0] = as; 1529 av[0] = as;
1530 av[1] = NULL; 1530 av[1] = NULL;
1531 } else { 1531 } else {
1532 av = brk_string(str, &ac, FALSE, &as); 1532 av = brk_string(str, &ac, FALSE, &as);
1533 } 1533 }
1534 1534
1535 /* 1535 /*
1536 * Now sanitize seldata. 1536 * Now sanitize seldata.
1537 * If seldata->start or seldata->end are negative, convert them to 1537 * If seldata->start or seldata->end are negative, convert them to
1538 * the positive equivalents (-1 gets converted to argc, -2 gets 1538 * the positive equivalents (-1 gets converted to argc, -2 gets
1539 * converted to (argc-1), etc.). 1539 * converted to (argc-1), etc.).
1540 */ 1540 */
1541 if (first < 0) 1541 if (first < 0)
1542 first += ac + 1; 1542 first += ac + 1;
1543 if (last < 0) 1543 if (last < 0)
1544 last += ac + 1; 1544 last += ac + 1;
1545 1545
1546 /* 1546 /*
1547 * We avoid scanning more of the list than we need to. 1547 * We avoid scanning more of the list than we need to.
1548 */ 1548 */
1549 if (first > last) { 1549 if (first > last) {
1550 start = MIN(ac, first) - 1; 1550 start = MIN(ac, first) - 1;
1551 end = MAX(0, last - 1); 1551 end = MAX(0, last - 1);
1552 step = -1; 1552 step = -1;
1553 } else { 1553 } else {
1554 start = MAX(0, first - 1); 1554 start = MAX(0, first - 1);
1555 end = MIN(ac, last); 1555 end = MIN(ac, last);
1556 step = 1; 1556 step = 1;
1557 } 1557 }
1558 1558
1559 for (i = start; (step < 0) == (i >= end); i += step) { 1559 for (i = start; (step < 0) == (i >= end); i += step) {
1560 SepBuf_AddStr(&buf, av[i]); 1560 SepBuf_AddStr(&buf, av[i]);
1561 SepBuf_Sep(&buf); 1561 SepBuf_Sep(&buf);
1562 } 1562 }
1563 1563
1564 free(as); 1564 free(as);
1565 free(av); 1565 free(av);
1566 1566
1567 return SepBuf_Destroy(&buf, FALSE); 1567 return SepBuf_Destroy(&buf, FALSE);
1568} 1568}
1569 1569
1570 1570
1571/* Callback for ModifyWords to implement the :tA modifier. 1571/* Callback for ModifyWords to implement the :tA modifier.
1572 * Replace each word with the result of realpath() if successful. */ 1572 * Replace each word with the result of realpath() if successful. */
1573static void 1573static void
1574ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED) 1574ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
1575{ 1575{
1576 struct stat st; 1576 struct stat st;
1577 char rbuf[MAXPATHLEN]; 1577 char rbuf[MAXPATHLEN];
1578 1578
1579 const char *rp = cached_realpath(word, rbuf); 1579 const char *rp = cached_realpath(word, rbuf);
1580 if (rp != NULL && *rp == '/' && stat(rp, &st) == 0) 1580 if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
1581 word = rp; 1581 word = rp;
1582 1582
1583 SepBuf_AddStr(buf, word); 1583 SepBuf_AddStr(buf, word);
1584} 1584}
1585 1585
1586/*- 1586/*-
1587 *----------------------------------------------------------------------- 1587 *-----------------------------------------------------------------------
1588 * Modify each of the words of the passed string using the given function. 1588 * Modify each of the words of the passed string using the given function.
1589 * 1589 *
1590 * Input: 1590 * Input:
1591 * str String whose words should be modified 1591 * str String whose words should be modified
1592 * modifyWord Function that modifies a single word 1592 * modifyWord Function that modifies a single word
1593 * data Custom data for modifyWord 1593 * data Custom data for modifyWord
1594 * 1594 *
1595 * Results: 1595 * Results:
1596 * A string of all the words modified appropriately. 1596 * A string of all the words modified appropriately.
1597 *----------------------------------------------------------------------- 1597 *-----------------------------------------------------------------------
1598 */ 1598 */
1599static char * 1599static char *
1600ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord, 1600ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord,
1601 const char *str, ModifyWordsCallback modifyWord, void *data) 1601 const char *str, ModifyWordsCallback modifyWord, void *data)
1602{ 1602{
1603 if (oneBigWord) { 1603 if (oneBigWord) {
1604 SepBuf result; 1604 SepBuf result;
1605 SepBuf_Init(&result, sep); 1605 SepBuf_Init(&result, sep);
1606 modifyWord(str, &result, data); 1606 modifyWord(str, &result, data);
1607 return SepBuf_Destroy(&result, FALSE); 1607 return SepBuf_Destroy(&result, FALSE);
1608 } 1608 }
1609 1609
1610 SepBuf result; 1610 SepBuf result;
1611 char **av; /* word list */ 1611 char **av; /* word list */
1612 char *as; /* word list memory */ 1612 char *as; /* word list memory */
1613 int ac, i; 1613 int ac, i;
1614 1614
1615 SepBuf_Init(&result, sep); 1615 SepBuf_Init(&result, sep);
1616 1616
1617 av = brk_string(str, &ac, FALSE, &as); 1617 av = brk_string(str, &ac, FALSE, &as);
1618 1618
1619 if (DEBUG(VAR)) { 1619 if (DEBUG(VAR)) {
1620 fprintf(debug_file, "ModifyWords: split \"%s\" into %d words\n", 1620 fprintf(debug_file, "ModifyWords: split \"%s\" into %d words\n",
1621 str, ac); 1621 str, ac);
1622 } 1622 }
1623 1623
1624 for (i = 0; i < ac; i++) { 1624 for (i = 0; i < ac; i++) {
1625 size_t orig_count = result.buf.count; 1625 size_t orig_count = result.buf.count;
1626 modifyWord(av[i], &result, data); 1626 modifyWord(av[i], &result, data);
1627 size_t count = result.buf.count; 1627 size_t count = result.buf.count;
1628 if (count != orig_count) 1628 if (count != orig_count)
1629 SepBuf_Sep(&result); 1629 SepBuf_Sep(&result);
1630 } 1630 }
1631 1631
1632 free(as); 1632 free(as);
1633 free(av); 1633 free(av);
1634 1634
1635 return SepBuf_Destroy(&result, FALSE); 1635 return SepBuf_Destroy(&result, FALSE);
1636} 1636}
1637 1637
1638 1638
1639static int 1639static int
1640VarWordCompare(const void *a, const void *b) 1640VarWordCompare(const void *a, const void *b)
1641{ 1641{
1642 int r = strcmp(*(const char * const *)a, *(const char * const *)b); 1642 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1643 return r; 1643 return r;
1644} 1644}
1645 1645
1646static int 1646static int
1647VarWordCompareReverse(const void *a, const void *b) 1647VarWordCompareReverse(const void *a, const void *b)
1648{ 1648{
1649 int r = strcmp(*(const char * const *)b, *(const char * const *)a); 1649 int r = strcmp(*(const char * const *)b, *(const char * const *)a);
1650 return r; 1650 return r;
1651} 1651}
1652 1652
1653/*- 1653/*-
1654 *----------------------------------------------------------------------- 1654 *-----------------------------------------------------------------------
1655 * VarOrder -- 1655 * VarOrder --
1656 * Order the words in the string. 1656 * Order the words in the string.
1657 * 1657 *
1658 * Input: 1658 * Input:
1659 * str String whose words should be sorted. 1659 * str String whose words should be sorted.
1660 * otype How to order: s - sort, x - random. 1660 * otype How to order: s - sort, x - random.
1661 * 1661 *
1662 * Results: 1662 * Results:
1663 * A string containing the words ordered. 1663 * A string containing the words ordered.
1664 * 1664 *
1665 * Side Effects: 1665 * Side Effects:
1666 * None. 1666 * None.
1667 * 1667 *
1668 *----------------------------------------------------------------------- 1668 *-----------------------------------------------------------------------
1669 */ 1669 */
1670static char * 1670static char *
1671VarOrder(const char *str, const char otype) 1671VarOrder(const char *str, const char otype)
1672{ 1672{
1673 Buffer buf; /* Buffer for the new string */ 1673 Buffer buf; /* Buffer for the new string */
1674 char **av; /* word list */ 1674 char **av; /* word list */
1675 char *as; /* word list memory */ 1675 char *as; /* word list memory */
1676 int ac, i; 1676 int ac, i;
1677 1677
1678 Buf_Init(&buf, 0); 1678 Buf_Init(&buf, 0);
1679 1679
1680 av = brk_string(str, &ac, FALSE, &as); 1680 av = brk_string(str, &ac, FALSE, &as);
1681 1681
1682 if (ac > 0) { 1682 if (ac > 0) {
1683 switch (otype) { 1683 switch (otype) {
1684 case 'r': /* reverse sort alphabetically */ 1684 case 'r': /* reverse sort alphabetically */
1685 qsort(av, ac, sizeof(char *), VarWordCompareReverse); 1685 qsort(av, ac, sizeof(char *), VarWordCompareReverse);
1686 break; 1686 break;
1687 case 's': /* sort alphabetically */ 1687 case 's': /* sort alphabetically */
1688 qsort(av, ac, sizeof(char *), VarWordCompare); 1688 qsort(av, ac, sizeof(char *), VarWordCompare);
1689 break; 1689 break;
1690 case 'x': /* randomize */ 1690 case 'x': /* randomize */
1691 /* 1691 /*
1692 * We will use [ac..2] range for mod factors. This will produce 1692 * We will use [ac..2] range for mod factors. This will produce
1693 * random numbers in [(ac-1)..0] interval, and minimal 1693 * random numbers in [(ac-1)..0] interval, and minimal
1694 * reasonable value for mod factor is 2 (the mod 1 will produce 1694 * reasonable value for mod factor is 2 (the mod 1 will produce
1695 * 0 with probability 1). 1695 * 0 with probability 1).
1696 */ 1696 */
1697 for (i = ac - 1; i > 0; i--) { 1697 for (i = ac - 1; i > 0; i--) {
1698 int rndidx = random() % (i + 1); 1698 int rndidx = random() % (i + 1);
1699 char *t = av[i]; 1699 char *t = av[i];
1700 av[i] = av[rndidx]; 1700 av[i] = av[rndidx];
1701 av[rndidx] = t; 1701 av[rndidx] = t;
1702 } 1702 }
1703 } 1703 }
1704 } 1704 }
1705 1705
1706 for (i = 0; i < ac; i++) { 1706 for (i = 0; i < ac; i++) {
1707 if (i != 0) 1707 if (i != 0)
1708 Buf_AddByte(&buf, ' '); 1708 Buf_AddByte(&buf, ' ');
1709 Buf_AddStr(&buf, av[i]); 1709 Buf_AddStr(&buf, av[i]);
1710 } 1710 }
1711 1711
1712 free(as); 1712 free(as);
1713 free(av); 1713 free(av);
1714 1714
1715 return Buf_Destroy(&buf, FALSE); 1715 return Buf_Destroy(&buf, FALSE);
1716} 1716}
1717 1717
1718 1718
1719/* Remove adjacent duplicate words. */ 1719/* Remove adjacent duplicate words. */
1720static char * 1720static char *
1721VarUniq(const char *str) 1721VarUniq(const char *str)
1722{ 1722{
1723 Buffer buf; /* Buffer for new string */ 1723 Buffer buf; /* Buffer for new string */
1724 char **av; /* List of words to affect */ 1724 char **av; /* List of words to affect */
1725 char *as; /* Word list memory */ 1725 char *as; /* Word list memory */
1726 int ac, i, j; 1726 int ac, i, j;
1727 1727
1728 Buf_Init(&buf, 0); 1728 Buf_Init(&buf, 0);
1729 av = brk_string(str, &ac, FALSE, &as); 1729 av = brk_string(str, &ac, FALSE, &as);
1730 1730
1731 if (ac > 1) { 1731 if (ac > 1) {
1732 for (j = 0, i = 1; i < ac; i++) 1732 for (j = 0, i = 1; i < ac; i++)
1733 if (strcmp(av[i], av[j]) != 0 && (++j != i)) 1733 if (strcmp(av[i], av[j]) != 0 && (++j != i))
1734 av[j] = av[i]; 1734 av[j] = av[i];
1735 ac = j + 1; 1735 ac = j + 1;
1736 } 1736 }
1737 1737
1738 for (i = 0; i < ac; i++) { 1738 for (i = 0; i < ac; i++) {
1739 if (i != 0) 1739 if (i != 0)
1740 Buf_AddByte(&buf, ' '); 1740 Buf_AddByte(&buf, ' ');
1741 Buf_AddStr(&buf, av[i]); 1741 Buf_AddStr(&buf, av[i]);
1742 } 1742 }
1743 1743
1744 free(as); 1744 free(as);
1745 free(av); 1745 free(av);
1746 1746
1747 return Buf_Destroy(&buf, FALSE); 1747 return Buf_Destroy(&buf, FALSE);
1748} 1748}
1749 1749
1750/*- 1750/*-
1751 *----------------------------------------------------------------------- 1751 *-----------------------------------------------------------------------
1752 * VarRange -- 1752 * VarRange --
1753 * Return an integer sequence 1753 * Return an integer sequence
1754 * 1754 *
1755 * Input: 1755 * Input:
1756 * str String whose words provide default range 1756 * str String whose words provide default range
1757 * ac range length, if 0 use str words 1757 * ac range length, if 0 use str words
1758 * 1758 *
1759 * Side Effects: 1759 * Side Effects:
1760 * None. 1760 * None.
1761 * 1761 *
1762 *----------------------------------------------------------------------- 1762 *-----------------------------------------------------------------------
1763 */ 1763 */
1764static char * 1764static char *
1765VarRange(const char *str, int ac) 1765VarRange(const char *str, int ac)
1766{ 1766{
1767 Buffer buf; /* Buffer for new string */ 1767 Buffer buf; /* Buffer for new string */
1768 char **av; /* List of words to affect */ 1768 char **av; /* List of words to affect */
1769 char *as; /* Word list memory */ 1769 char *as; /* Word list memory */
1770 int i; 1770 int i;
1771 1771
1772 Buf_Init(&buf, 0); 1772 Buf_Init(&buf, 0);
1773 if (ac > 0) { 1773 if (ac > 0) {
1774 as = NULL; 1774 as = NULL;
1775 av = NULL; 1775 av = NULL;
1776 } else { 1776 } else {
1777 av = brk_string(str, &ac, FALSE, &as); 1777 av = brk_string(str, &ac, FALSE, &as);
1778 } 1778 }
1779 for (i = 0; i < ac; i++) { 1779 for (i = 0; i < ac; i++) {
1780 if (i != 0) 1780 if (i != 0)
1781 Buf_AddByte(&buf, ' '); 1781 Buf_AddByte(&buf, ' ');
1782 Buf_AddInt(&buf, 1 + i); 1782 Buf_AddInt(&buf, 1 + i);
1783 } 1783 }
1784 1784
1785 free(as); 1785 free(as);
1786 free(av); 1786 free(av);
1787 1787
1788 return Buf_Destroy(&buf, FALSE); 1788 return Buf_Destroy(&buf, FALSE);
1789} 1789}
1790 1790
1791 1791
1792/*- 1792/*-
1793 * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/ 1793 * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/
1794 * or the :@ modifier, until the next unescaped delimiter. The delimiter, as 1794 * or the :@ modifier, until the next unescaped delimiter. The delimiter, as
1795 * well as the backslash or the dollar, can be escaped with a backslash. 1795 * well as the backslash or the dollar, can be escaped with a backslash.
1796 * 1796 *
1797 * Return the parsed (and possibly expanded) string, or NULL if no delimiter 1797 * Return the parsed (and possibly expanded) string, or NULL if no delimiter
1798 * was found. 1798 * was found.
1799 * 1799 *
1800 * Nested variables in the text are expanded unless VARE_NOSUBST is set. 1800 * Nested variables in the text are expanded unless VARE_NOSUBST is set.
1801 * 1801 *
1802 * If out_length is specified, store the length of the returned string, just 1802 * If out_length is specified, store the length of the returned string, just
1803 * to save another strlen call. 1803 * to save another strlen call.
1804 * 1804 *
1805 * If out_pflags is specified and the last character of the pattern is a $, 1805 * If out_pflags is specified and the last character of the pattern is a $,
1806 * set the VARP_ANCHOR_END bit of mpflags (for the first part of the :S 1806 * set the VARP_ANCHOR_END bit of mpflags (for the first part of the :S
1807 * modifier). 1807 * modifier).
1808 * 1808 *
1809 * If subst is specified, handle escaped ampersands and replace unescaped 1809 * If subst is specified, handle escaped ampersands and replace unescaped
1810 * ampersands with the lhs of the pattern (for the second part of the :S 1810 * ampersands with the lhs of the pattern (for the second part of the :S
1811 * modifier). 1811 * modifier).
1812 */ 1812 */
1813static char * 1813static char *
1814ParseModifierPart(const char **tstr, int delim, VarEvalFlags eflags, 1814ParseModifierPart(const char **tstr, int delim, VarEvalFlags eflags,
1815 GNode *ctxt, size_t *out_length, 1815 GNode *ctxt, size_t *out_length,
1816 VarPatternFlags *out_pflags, ModifyWord_SubstArgs *subst) 1816 VarPatternFlags *out_pflags, ModifyWord_SubstArgs *subst)
1817{ 1817{
1818 const char *cp; 1818 const char *cp;
1819 char *rstr; 1819 char *rstr;
1820 Buffer buf; 1820 Buffer buf;
1821 VarEvalFlags errnum = eflags & VARE_UNDEFERR; 1821 VarEvalFlags errnum = eflags & VARE_UNDEFERR;
1822 1822
1823 Buf_Init(&buf, 0); 1823 Buf_Init(&buf, 0);
1824 1824
1825 /* 1825 /*
1826 * Skim through until the matching delimiter is found; 1826 * Skim through until the matching delimiter is found;
1827 * pick up variable substitutions on the way. Also allow 1827 * pick up variable substitutions on the way. Also allow
1828 * backslashes to quote the delimiter, $, and \, but don't 1828 * backslashes to quote the delimiter, $, and \, but don't
1829 * touch other backslashes. 1829 * touch other backslashes.
1830 */ 1830 */
1831 for (cp = *tstr; *cp != '\0' && *cp != delim; cp++) { 1831 for (cp = *tstr; *cp != '\0' && *cp != delim; cp++) {
1832 Boolean is_escaped = cp[0] == '\\' && ( 1832 Boolean is_escaped = cp[0] == '\\' && (
1833 cp[1] == delim || cp[1] == '\\' || cp[1] == '$' || 1833 cp[1] == delim || cp[1] == '\\' || cp[1] == '$' ||
1834 (cp[1] == '&' && subst != NULL)); 1834 (cp[1] == '&' && subst != NULL));
1835 if (is_escaped) { 1835 if (is_escaped) {
1836 Buf_AddByte(&buf, cp[1]); 1836 Buf_AddByte(&buf, cp[1]);
1837 cp++; 1837 cp++;
1838 } else if (*cp == '$') { 1838 } else if (*cp == '$') {
1839 if (cp[1] == delim) { /* Unescaped $ at end of pattern */ 1839 if (cp[1] == delim) { /* Unescaped $ at end of pattern */
1840 if (out_pflags != NULL) 1840 if (out_pflags != NULL)
1841 *out_pflags |= VARP_ANCHOR_END; 1841 *out_pflags |= VARP_ANCHOR_END;
1842 else 1842 else
1843 Buf_AddByte(&buf, *cp); 1843 Buf_AddByte(&buf, *cp);
1844 } else { 1844 } else {
1845 if (eflags & VARE_WANTRES) { 1845 if (eflags & VARE_WANTRES) {
1846 const char *cp2; 1846 const char *cp2;
1847 int len; 1847 int len;
1848 void *freeIt; 1848 void *freeIt;
1849 1849
1850 /* 1850 /*
1851 * If unescaped dollar sign not before the 1851 * If unescaped dollar sign not before the
1852 * delimiter, assume it's a variable 1852 * delimiter, assume it's a variable
1853 * substitution and recurse. 1853 * substitution and recurse.
1854 */ 1854 */
1855 cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES), 1855 cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES),
1856 &len, &freeIt); 1856 &len, &freeIt);
1857 Buf_AddStr(&buf, cp2); 1857 Buf_AddStr(&buf, cp2);
1858 free(freeIt); 1858 free(freeIt);
1859 cp += len - 1; 1859 cp += len - 1;
1860 } else { 1860 } else {
1861 const char *cp2 = &cp[1]; 1861 const char *cp2 = &cp[1];
1862 1862
1863 if (*cp2 == PROPEN || *cp2 == BROPEN) { 1863 if (*cp2 == PROPEN || *cp2 == BROPEN) {
1864 /* 1864 /*
1865 * Find the end of this variable reference 1865 * Find the end of this variable reference
1866 * and suck it in without further ado. 1866 * and suck it in without further ado.
1867 * It will be interpreted later. 1867 * It will be interpreted later.
1868 */ 1868 */
1869 int have = *cp2; 1869 int have = *cp2;
1870 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE; 1870 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
1871 int depth = 1; 1871 int depth = 1;
1872 1872
1873 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) { 1873 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
1874 if (cp2[-1] != '\\') { 1874 if (cp2[-1] != '\\') {
1875 if (*cp2 == have) 1875 if (*cp2 == have)
1876 ++depth; 1876 ++depth;
1877 if (*cp2 == want) 1877 if (*cp2 == want)
1878 --depth; 1878 --depth;
1879 } 1879 }
1880 } 1880 }
1881 Buf_AddBytesBetween(&buf, cp, cp2); 1881 Buf_AddBytesBetween(&buf, cp, cp2);
1882 cp = --cp2; 1882 cp = --cp2;
1883 } else 1883 } else
1884 Buf_AddByte(&buf, *cp); 1884 Buf_AddByte(&buf, *cp);
1885 } 1885 }
1886 } 1886 }
1887 } else if (subst != NULL && *cp == '&') 1887 } else if (subst != NULL && *cp == '&')
1888 Buf_AddBytes(&buf, subst->lhsLen, subst->lhs); 1888 Buf_AddBytes(&buf, subst->lhsLen, subst->lhs);
1889 else 1889 else
1890 Buf_AddByte(&buf, *cp); 1890 Buf_AddByte(&buf, *cp);
1891 } 1891 }
1892 1892
1893 if (*cp != delim) { 1893 if (*cp != delim) {
1894 *tstr = cp; 1894 *tstr = cp;
1895 return NULL; 1895 return NULL;
1896 } 1896 }
1897 1897
1898 *tstr = ++cp; 1898 *tstr = ++cp;
1899 if (out_length != NULL) 1899 if (out_length != NULL)
1900 *out_length = Buf_Size(&buf); 1900 *out_length = Buf_Size(&buf);
1901 rstr = Buf_Destroy(&buf, FALSE); 1901 rstr = Buf_Destroy(&buf, FALSE);
1902 if (DEBUG(VAR)) 1902 if (DEBUG(VAR))
1903 fprintf(debug_file, "Modifier part: \"%s\"\n", rstr); 1903 fprintf(debug_file, "Modifier part: \"%s\"\n", rstr);
1904 return rstr; 1904 return rstr;
1905} 1905}
1906 1906
1907/*- 1907/*-
1908 *----------------------------------------------------------------------- 1908 *-----------------------------------------------------------------------
1909 * VarQuote -- 1909 * VarQuote --
1910 * Quote shell meta-characters and space characters in the string 1910 * Quote shell meta-characters and space characters in the string
1911 * if quoteDollar is set, also quote and double any '$' characters. 1911 * if quoteDollar is set, also quote and double any '$' characters.
1912 * 1912 *
1913 * Results: 1913 * Results:
1914 * The quoted string 1914 * The quoted string
1915 * 1915 *
1916 * Side Effects: 1916 * Side Effects:
1917 * None. 1917 * None.
1918 * 1918 *
1919 *----------------------------------------------------------------------- 1919 *-----------------------------------------------------------------------
1920 */ 1920 */
1921static char * 1921static char *
1922VarQuote(char *str, Boolean quoteDollar) 1922VarQuote(char *str, Boolean quoteDollar)
1923{ 1923{
1924 Buffer buf; 1924 Buffer buf;
1925 Buf_Init(&buf, 0); 1925 Buf_Init(&buf, 0);
1926 1926
1927 for (; *str != '\0'; str++) { 1927 for (; *str != '\0'; str++) {
1928 if (*str == '\n') { 1928 if (*str == '\n') {
1929 const char *newline = Shell_GetNewline(); 1929 const char *newline = Shell_GetNewline();
1930 if (newline == NULL) 1930 if (newline == NULL)
1931 newline = "\\\n"; 1931 newline = "\\\n";
1932 Buf_AddStr(&buf, newline); 1932 Buf_AddStr(&buf, newline);
1933 continue; 1933 continue;
1934 } 1934 }
1935 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str)) 1935 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
1936 Buf_AddByte(&buf, '\\'); 1936 Buf_AddByte(&buf, '\\');
1937 Buf_AddByte(&buf, *str); 1937 Buf_AddByte(&buf, *str);
1938 if (quoteDollar && *str == '$') 1938 if (quoteDollar && *str == '$')
1939 Buf_AddStr(&buf, "\\$"); 1939 Buf_AddStr(&buf, "\\$");
1940 } 1940 }
1941 1941
1942 str = Buf_Destroy(&buf, FALSE); 1942 str = Buf_Destroy(&buf, FALSE);
1943 if (DEBUG(VAR)) 1943 if (DEBUG(VAR))
1944 fprintf(debug_file, "QuoteMeta: [%s]\n", str); 1944 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
1945 return str; 1945 return str;
1946} 1946}
1947 1947
1948/*- 1948/*-
1949 *----------------------------------------------------------------------- 1949 *-----------------------------------------------------------------------
1950 * VarHash -- 1950 * VarHash --
1951 * Hash the string using the MurmurHash3 algorithm. 1951 * Hash the string using the MurmurHash3 algorithm.
1952 * Output is computed using 32bit Little Endian arithmetic. 1952 * Output is computed using 32bit Little Endian arithmetic.
1953 * 1953 *
1954 * Input: 1954 * Input:
1955 * str String to modify 1955 * str String to modify
1956 * 1956 *
1957 * Results: 1957 * Results:
1958 * Hash value of str, encoded as 8 hex digits. 1958 * Hash value of str, encoded as 8 hex digits.
1959 * 1959 *
1960 * Side Effects: 1960 * Side Effects:
1961 * None. 1961 * None.
1962 * 1962 *
1963 *----------------------------------------------------------------------- 1963 *-----------------------------------------------------------------------
1964 */ 1964 */
1965static char * 1965static char *
1966VarHash(const char *str) 1966VarHash(const char *str)
1967{ 1967{
1968 static const char hexdigits[16] = "0123456789abcdef"; 1968 static const char hexdigits[16] = "0123456789abcdef";
1969 Buffer buf; 1969 Buffer buf;
1970 size_t len, len2; 1970 size_t len, len2;
1971 const unsigned char *ustr = (const unsigned char *)str; 1971 const unsigned char *ustr = (const unsigned char *)str;
1972 uint32_t h, k, c1, c2; 1972 uint32_t h, k, c1, c2;
1973 1973
1974 h = 0x971e137bU; 1974 h = 0x971e137bU;
1975 c1 = 0x95543787U; 1975 c1 = 0x95543787U;
1976 c2 = 0x2ad7eb25U; 1976 c2 = 0x2ad7eb25U;
1977 len2 = strlen(str); 1977 len2 = strlen(str);
1978 1978
1979 for (len = len2; len; ) { 1979 for (len = len2; len; ) {
1980 k = 0; 1980 k = 0;
1981 switch (len) { 1981 switch (len) {
1982 default: 1982 default:
1983 k = ((uint32_t)ustr[3] << 24) | 1983 k = ((uint32_t)ustr[3] << 24) |
1984 ((uint32_t)ustr[2] << 16) | 1984 ((uint32_t)ustr[2] << 16) |
1985 ((uint32_t)ustr[1] << 8) | 1985 ((uint32_t)ustr[1] << 8) |
1986 (uint32_t)ustr[0]; 1986 (uint32_t)ustr[0];
1987 len -= 4; 1987 len -= 4;
1988 ustr += 4; 1988 ustr += 4;
1989 break; 1989 break;
1990 case 3: 1990 case 3:
1991 k |= (uint32_t)ustr[2] << 16; 1991 k |= (uint32_t)ustr[2] << 16;
1992 /* FALLTHROUGH */ 1992 /* FALLTHROUGH */
1993 case 2: 1993 case 2:
1994 k |= (uint32_t)ustr[1] << 8; 1994 k |= (uint32_t)ustr[1] << 8;
1995 /* FALLTHROUGH */ 1995 /* FALLTHROUGH */
1996 case 1: 1996 case 1:
1997 k |= (uint32_t)ustr[0]; 1997 k |= (uint32_t)ustr[0];
1998 len = 0; 1998 len = 0;
1999 } 1999 }
2000 c1 = c1 * 5 + 0x7b7d159cU; 2000 c1 = c1 * 5 + 0x7b7d159cU;
2001 c2 = c2 * 5 + 0x6bce6396U; 2001 c2 = c2 * 5 + 0x6bce6396U;
2002 k *= c1; 2002 k *= c1;
2003 k = (k << 11) ^ (k >> 21); 2003 k = (k << 11) ^ (k >> 21);
2004 k *= c2; 2004 k *= c2;
2005 h = (h << 13) ^ (h >> 19); 2005 h = (h << 13) ^ (h >> 19);
2006 h = h * 5 + 0x52dce729U; 2006 h = h * 5 + 0x52dce729U;
2007 h ^= k; 2007 h ^= k;
2008 } 2008 }
2009 h ^= len2; 2009 h ^= len2;
2010 h *= 0x85ebca6b; 2010 h *= 0x85ebca6b;
2011 h ^= h >> 13; 2011 h ^= h >> 13;
2012 h *= 0xc2b2ae35; 2012 h *= 0xc2b2ae35;
2013 h ^= h >> 16; 2013 h ^= h >> 16;
2014 2014
2015 Buf_Init(&buf, 0); 2015 Buf_Init(&buf, 0);
2016 for (len = 0; len < 8; ++len) { 2016 for (len = 0; len < 8; ++len) {
2017 Buf_AddByte(&buf, hexdigits[h & 15]); 2017 Buf_AddByte(&buf, hexdigits[h & 15]);
2018 h >>= 4; 2018 h >>= 4;
2019 } 2019 }
2020 2020
2021 return Buf_Destroy(&buf, FALSE); 2021 return Buf_Destroy(&buf, FALSE);
2022} 2022}
2023 2023
2024static char * 2024static char *
2025VarStrftime(const char *fmt, int zulu, time_t utc) 2025VarStrftime(const char *fmt, int zulu, time_t utc)
2026{ 2026{
2027 char buf[BUFSIZ]; 2027 char buf[BUFSIZ];
2028 2028
2029 if (!utc) 2029 if (!utc)
2030 time(&utc); 2030 time(&utc);
2031 if (!*fmt) 2031 if (!*fmt)
2032 fmt = "%c"; 2032 fmt = "%c";
2033 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc)); 2033 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2034 2034
2035 buf[sizeof(buf) - 1] = '\0'; 2035 buf[sizeof(buf) - 1] = '\0';
2036 return bmake_strdup(buf); 2036 return bmake_strdup(buf);
2037} 2037}
2038 2038
2039typedef struct { 2039typedef struct {
2040 /* const parameters */ 2040 /* const parameters */
2041 int startc; /* '\0' or '{' or '(' */ 2041 int startc; /* '\0' or '{' or '(' */
2042 int endc; 2042 int endc;
2043 Var *v; 2043 Var *v;
2044 GNode *ctxt; 2044 GNode *ctxt;
2045 VarEvalFlags eflags; 2045 VarEvalFlags eflags;
2046 2046
2047 /* read-write */ 2047 /* read-write */
2048 char *nstr; 2048 char *nstr;
2049 const char *cp; /* The position where parsing continues 2049 const char *cp; /* The position where parsing continues
2050 * after the current modifier. */ 2050 * after the current modifier. */
2051 char termc; /* Character which terminated scan */ 2051 char termc; /* Character which terminated scan */
2052 char missing_delim; /* For error reporting */ 2052 char missing_delim; /* For error reporting */
2053 2053
2054 Byte sep; /* Word separator in expansions */ 2054 Byte sep; /* Word separator in expansions */
2055 Boolean oneBigWord; /* TRUE if we will treat the variable as a 2055 Boolean oneBigWord; /* TRUE if we will treat the variable as a
2056 * single big word, even if it contains 2056 * single big word, even if it contains
2057 * embedded spaces (as opposed to the 2057 * embedded spaces (as opposed to the
2058 * usual behaviour of treating it as 2058 * usual behaviour of treating it as
2059 * several space-separated words). */ 2059 * several space-separated words). */
2060 2060
2061 /* result */ 2061 /* result */
2062 char *newStr; /* New value to return */ 2062 char *newStr; /* New value to return */
2063} ApplyModifiersState; 2063} ApplyModifiersState;
2064 2064
2065/* we now have some modifiers with long names */ 2065/* we now have some modifiers with long names */
2066static Boolean 2066static Boolean
2067ModMatch(const char *mod, const char *modname, char endc) 2067ModMatch(const char *mod, const char *modname, char endc)
2068{ 2068{
2069 size_t n = strlen(modname); 2069 size_t n = strlen(modname);
2070 return strncmp(mod, modname, n) == 0 && 2070 return strncmp(mod, modname, n) == 0 &&
2071 (mod[n] == endc || mod[n] == ':'); 2071 (mod[n] == endc || mod[n] == ':');
2072} 2072}
2073 2073
2074static inline Boolean 2074static inline Boolean
2075ModMatchEq(const char *mod, const char *modname, char endc) 2075ModMatchEq(const char *mod, const char *modname, char endc)
2076{ 2076{
2077 size_t n = strlen(modname); 2077 size_t n = strlen(modname);
2078 return strncmp(mod, modname, n) == 0 && 2078 return strncmp(mod, modname, n) == 0 &&
2079 (mod[n] == endc || mod[n] == ':' || mod[n] == '='); 2079 (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
2080} 2080}
2081 2081
2082/* :@var@...${var}...@ */ 2082/* :@var@...${var}...@ */
2083static Boolean 2083static Boolean
2084ApplyModifier_Loop(const char *mod, ApplyModifiersState *st) { 2084ApplyModifier_Loop(const char *mod, ApplyModifiersState *st) {
2085 ModifyWord_LoopArgs args; 2085 ModifyWord_LoopArgs args;
2086 2086
2087 args.ctx = st->ctxt; 2087 args.ctx = st->ctxt;
2088 st->cp = mod + 1; 2088 st->cp = mod + 1;
2089 char delim = '@'; 2089 char delim = '@';
2090 args.tvar = ParseModifierPart(&st->cp, delim, st->eflags & ~VARE_WANTRES, 2090 args.tvar = ParseModifierPart(&st->cp, delim, st->eflags & ~VARE_WANTRES,
2091 st->ctxt, NULL, NULL, NULL); 2091 st->ctxt, NULL, NULL, NULL);
2092 if (args.tvar == NULL) { 2092 if (args.tvar == NULL) {
2093 st->missing_delim = delim; 2093 st->missing_delim = delim;
2094 return FALSE; 2094 return FALSE;
2095 } 2095 }
2096 2096
2097 args.str = ParseModifierPart(&st->cp, delim, st->eflags & ~VARE_WANTRES, 2097 args.str = ParseModifierPart(&st->cp, delim, st->eflags & ~VARE_WANTRES,
2098 st->ctxt, NULL, NULL, NULL); 2098 st->ctxt, NULL, NULL, NULL);
2099 if (args.str == NULL) { 2099 if (args.str == NULL) {
2100 st->missing_delim = delim; 2100 st->missing_delim = delim;
2101 return FALSE; 2101 return FALSE;
2102 } 2102 }
2103 2103
2104 st->termc = *st->cp; 2104 st->termc = *st->cp;
2105 2105
2106 args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES); 2106 args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES);
2107 int prev_sep = st->sep; 2107 int prev_sep = st->sep;
2108 st->sep = ' '; /* XXX: this is inconsistent */ 2108 st->sep = ' '; /* XXX: this is inconsistent */
2109 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr, 2109 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr,
2110 ModifyWord_Loop, &args); 2110 ModifyWord_Loop, &args);
2111 st->sep = prev_sep; 2111 st->sep = prev_sep;
2112 Var_Delete(args.tvar, st->ctxt); 2112 Var_Delete(args.tvar, st->ctxt);
2113 free(args.tvar); 2113 free(args.tvar);
2114 free(args.str); 2114 free(args.str);
2115 return TRUE; 2115 return TRUE;
2116} 2116}
2117 2117
2118/* :Ddefined or :Uundefined */ 2118/* :Ddefined or :Uundefined */
2119static void 2119static void
2120ApplyModifier_Defined(const char *mod, ApplyModifiersState *st) 2120ApplyModifier_Defined(const char *mod, ApplyModifiersState *st)
2121{ 2121{
2122 Buffer buf; /* Buffer for patterns */ 2122 Buffer buf; /* Buffer for patterns */
2123 VarEvalFlags neflags; 2123 VarEvalFlags neflags;
2124 2124
2125 if (st->eflags & VARE_WANTRES) { 2125 if (st->eflags & VARE_WANTRES) {
2126 Boolean wantres; 2126 Boolean wantres;
2127 if (*mod == 'U') 2127 if (*mod == 'U')
2128 wantres = ((st->v->flags & VAR_JUNK) != 0); 2128 wantres = ((st->v->flags & VAR_JUNK) != 0);
2129 else 2129 else
2130 wantres = ((st->v->flags & VAR_JUNK) == 0); 2130 wantres = ((st->v->flags & VAR_JUNK) == 0);
2131 neflags = st->eflags & ~VARE_WANTRES; 2131 neflags = st->eflags & ~VARE_WANTRES;
2132 if (wantres) 2132 if (wantres)
2133 neflags |= VARE_WANTRES; 2133 neflags |= VARE_WANTRES;
2134 } else 2134 } else
2135 neflags = st->eflags; 2135 neflags = st->eflags;
2136 2136
2137 /* 2137 /*
2138 * Pass through mod looking for 1) escaped delimiters, 2138 * Pass through mod looking for 1) escaped delimiters,
2139 * '$'s and backslashes (place the escaped character in 2139 * '$'s and backslashes (place the escaped character in
2140 * uninterpreted) and 2) unescaped $'s that aren't before 2140 * uninterpreted) and 2) unescaped $'s that aren't before
2141 * the delimiter (expand the variable substitution). 2141 * the delimiter (expand the variable substitution).
2142 * The result is left in the Buffer buf. 2142 * The result is left in the Buffer buf.
2143 */ 2143 */
2144 Buf_Init(&buf, 0); 2144 Buf_Init(&buf, 0);
2145 const char *p = mod + 1; 2145 const char *p = mod + 1;
2146 while (*p != st->endc && *p != ':' && *p != '\0') { 2146 while (*p != st->endc && *p != ':' && *p != '\0') {
2147 if (*p == '\\' && 2147 if (*p == '\\' &&
2148 (p[1] == ':' || p[1] == '$' || p[1] == st->endc || p[1] == '\\')) { 2148 (p[1] == ':' || p[1] == '$' || p[1] == st->endc || p[1] == '\\')) {
2149 Buf_AddByte(&buf, p[1]); 2149 Buf_AddByte(&buf, p[1]);
2150 p += 2; 2150 p += 2;
2151 } else if (*p == '$') { 2151 } else if (*p == '$') {
2152 /* 2152 /*
2153 * If unescaped dollar sign, assume it's a 2153 * If unescaped dollar sign, assume it's a
2154 * variable substitution and recurse. 2154 * variable substitution and recurse.
2155 */ 2155 */
2156 const char *cp2; 2156 const char *cp2;
2157 int len; 2157 int len;
2158 void *freeIt; 2158 void *freeIt;
2159 2159
2160 cp2 = Var_Parse(p, st->ctxt, neflags, &len, &freeIt); 2160 cp2 = Var_Parse(p, st->ctxt, neflags, &len, &freeIt);
2161 Buf_AddStr(&buf, cp2); 2161 Buf_AddStr(&buf, cp2);
2162 free(freeIt); 2162 free(freeIt);
2163 p += len; 2163 p += len;
2164 } else { 2164 } else {
2165 Buf_AddByte(&buf, *p); 2165 Buf_AddByte(&buf, *p);
2166 p++; 2166 p++;
2167 } 2167 }
2168 } 2168 }
2169 2169
2170 st->cp = p; 2170 st->cp = p;
2171 st->termc = *st->cp; 2171 st->termc = *st->cp;
2172 2172
2173 if (st->v->flags & VAR_JUNK) 2173 if (st->v->flags & VAR_JUNK)
2174 st->v->flags |= VAR_KEEP; 2174 st->v->flags |= VAR_KEEP;
2175 if (neflags & VARE_WANTRES) { 2175 if (neflags & VARE_WANTRES) {
2176 st->newStr = Buf_Destroy(&buf, FALSE); 2176 st->newStr = Buf_Destroy(&buf, FALSE);
2177 } else { 2177 } else {
2178 st->newStr = st->nstr; 2178 st->newStr = st->nstr;
2179 Buf_Destroy(&buf, TRUE); 2179 Buf_Destroy(&buf, TRUE);
2180 } 2180 }
2181} 2181}
2182 2182
2183/* :gmtime */ 2183/* :gmtime */
2184static Boolean 2184static Boolean
2185ApplyModifier_Gmtime(const char *mod, ApplyModifiersState *st) 2185ApplyModifier_Gmtime(const char *mod, ApplyModifiersState *st)
2186{ 2186{
2187 if (!ModMatchEq(mod, "gmtime", st->endc)) { 2187 if (!ModMatchEq(mod, "gmtime", st->endc)) {
2188 st->cp = mod + 1; 2188 st->cp = mod + 1;
2189 return FALSE; 2189 return FALSE;
2190 } 2190 }
2191 2191
2192 time_t utc; 2192 time_t utc;
2193 if (mod[6] == '=') { 2193 if (mod[6] == '=') {
2194 char *ep; 2194 char *ep;
2195 utc = strtoul(mod + 7, &ep, 10); 2195 utc = strtoul(mod + 7, &ep, 10);
2196 st->cp = ep; 2196 st->cp = ep;
2197 } else { 2197 } else {
2198 utc = 0; 2198 utc = 0;
2199 st->cp = mod + 6; 2199 st->cp = mod + 6;
2200 } 2200 }
2201 st->newStr = VarStrftime(st->nstr, 1, utc); 2201 st->newStr = VarStrftime(st->nstr, 1, utc);
2202 st->termc = *st->cp; 2202 st->termc = *st->cp;
2203 return TRUE; 2203 return TRUE;
2204} 2204}
2205 2205
2206/* :localtime */ 2206/* :localtime */
2207static Boolean 2207static Boolean
2208ApplyModifier_Localtime(const char *mod, ApplyModifiersState *st) 2208ApplyModifier_Localtime(const char *mod, ApplyModifiersState *st)
2209{ 2209{
2210 if (!ModMatchEq(mod, "localtime", st->endc)) { 2210 if (!ModMatchEq(mod, "localtime", st->endc)) {
2211 st->cp = mod + 1; 2211 st->cp = mod + 1;
2212 return FALSE; 2212 return FALSE;
2213 } 2213 }
2214 2214
2215 time_t utc; 2215 time_t utc;
2216 if (mod[9] == '=') { 2216 if (mod[9] == '=') {
2217 char *ep; 2217 char *ep;
2218 utc = strtoul(mod + 10, &ep, 10); 2218 utc = strtoul(mod + 10, &ep, 10);
2219 st->cp = ep; 2219 st->cp = ep;
2220 } else { 2220 } else {
2221 utc = 0; 2221 utc = 0;
2222 st->cp = mod + 9; 2222 st->cp = mod + 9;
2223 } 2223 }
2224 st->newStr = VarStrftime(st->nstr, 0, utc); 2224 st->newStr = VarStrftime(st->nstr, 0, utc);
2225 st->termc = *st->cp; 2225 st->termc = *st->cp;
2226 return TRUE; 2226 return TRUE;
2227} 2227}
2228 2228
2229/* :hash */ 2229/* :hash */
2230static Boolean 2230static Boolean
2231ApplyModifier_Hash(const char *mod, ApplyModifiersState *st) 2231ApplyModifier_Hash(const char *mod, ApplyModifiersState *st)
2232{ 2232{
2233 if (!ModMatch(mod, "hash", st->endc)) { 2233 if (!ModMatch(mod, "hash", st->endc)) {
2234 st->cp = mod + 1; 2234 st->cp = mod + 1;
2235 return FALSE; 2235 return FALSE;
2236 } 2236 }
2237 2237
2238 st->newStr = VarHash(st->nstr); 2238 st->newStr = VarHash(st->nstr);
2239 st->cp = mod + 4; 2239 st->cp = mod + 4;
2240 st->termc = *st->cp; 2240 st->termc = *st->cp;
2241 return TRUE; 2241 return TRUE;
2242} 2242}
2243 2243
2244/* :P */ 2244/* :P */
2245static void 2245static void
2246ApplyModifier_Path(const char *mod, ApplyModifiersState *st) 2246ApplyModifier_Path(const char *mod, ApplyModifiersState *st)
2247{ 2247{
2248 if (st->v->flags & VAR_JUNK) 2248 if (st->v->flags & VAR_JUNK)
2249 st->v->flags |= VAR_KEEP; 2249 st->v->flags |= VAR_KEEP;
2250 GNode *gn = Targ_FindNode(st->v->name, TARG_NOCREATE); 2250 GNode *gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
2251 if (gn == NULL || gn->type & OP_NOPATH) { 2251 if (gn == NULL || gn->type & OP_NOPATH) {
2252 st->newStr = NULL; 2252 st->newStr = NULL;
2253 } else if (gn->path) { 2253 } else if (gn->path) {
2254 st->newStr = bmake_strdup(gn->path); 2254 st->newStr = bmake_strdup(gn->path);
2255 } else { 2255 } else {
2256 st->newStr = Dir_FindFile(st->v->name, Suff_FindPath(gn)); 2256 st->newStr = Dir_FindFile(st->v->name, Suff_FindPath(gn));
2257 } 2257 }
2258 if (!st->newStr) 2258 if (!st->newStr)
2259 st->newStr = bmake_strdup(st->v->name); 2259 st->newStr = bmake_strdup(st->v->name);
2260 st->cp = mod + 1; 2260 st->cp = mod + 1;
2261 st->termc = *st->cp; 2261 st->termc = *st->cp;
2262} 2262}
2263 2263
2264/* :!cmd! */ 2264/* :!cmd! */
2265static Boolean 2265static Boolean
2266ApplyModifier_Exclam(const char *mod, ApplyModifiersState *st) 2266ApplyModifier_Exclam(const char *mod, ApplyModifiersState *st)
2267{ 2267{
2268 st->cp = mod + 1; 2268 st->cp = mod + 1;
2269 char delim = '!'; 2269 char delim = '!';
2270 char *cmd = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2270 char *cmd = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2271 NULL, NULL, NULL); 2271 NULL, NULL, NULL);
2272 if (cmd == NULL) { 2272 if (cmd == NULL) {
2273 st->missing_delim = delim; 2273 st->missing_delim = delim;
2274 return FALSE; 2274 return FALSE;
2275 } 2275 }
2276 2276
2277 const char *emsg = NULL; 2277 const char *emsg = NULL;
2278 if (st->eflags & VARE_WANTRES) 2278 if (st->eflags & VARE_WANTRES)
2279 st->newStr = Cmd_Exec(cmd, &emsg); 2279 st->newStr = Cmd_Exec(cmd, &emsg);
2280 else 2280 else
2281 st->newStr = varNoError; 2281 st->newStr = varNoError;
2282 free(cmd); 2282 free(cmd);
2283 2283
2284 if (emsg) 2284 if (emsg)
2285 Error(emsg, st->nstr); 2285 Error(emsg, st->nstr);
2286 2286
2287 st->termc = *st->cp; 2287 st->termc = *st->cp;
2288 if (st->v->flags & VAR_JUNK) 2288 if (st->v->flags & VAR_JUNK)
2289 st->v->flags |= VAR_KEEP; 2289 st->v->flags |= VAR_KEEP;
2290 return TRUE; 2290 return TRUE;
2291} 2291}
2292 2292
2293/* :range */ 2293/* :range */
2294static Boolean 2294static Boolean
2295ApplyModifier_Range(const char *mod, ApplyModifiersState *st) 2295ApplyModifier_Range(const char *mod, ApplyModifiersState *st)
2296{ 2296{
2297 if (!ModMatchEq(mod, "range", st->endc)) { 2297 if (!ModMatchEq(mod, "range", st->endc)) {
2298 st->cp = mod + 1; 2298 st->cp = mod + 1;
2299 return FALSE; 2299 return FALSE;
2300 } 2300 }
2301 2301
2302 int n; 2302 int n;
2303 if (mod[5] == '=') { 2303 if (mod[5] == '=') {
2304 char *ep; 2304 char *ep;
2305 n = strtoul(mod + 6, &ep, 10); 2305 n = strtoul(mod + 6, &ep, 10);
2306 st->cp = ep; 2306 st->cp = ep;
2307 } else { 2307 } else {
2308 n = 0; 2308 n = 0;
2309 st->cp = mod + 5; 2309 st->cp = mod + 5;
2310 } 2310 }
2311 st->newStr = VarRange(st->nstr, n); 2311 st->newStr = VarRange(st->nstr, n);
2312 st->termc = *st->cp; 2312 st->termc = *st->cp;
2313 return TRUE; 2313 return TRUE;
2314} 2314}
2315 2315
2316/* :Mpattern or :Npattern */ 2316/* :Mpattern or :Npattern */
2317static void 2317static void
2318ApplyModifier_Match(const char *mod, ApplyModifiersState *st) 2318ApplyModifier_Match(const char *mod, ApplyModifiersState *st)
2319{ 2319{
2320 Boolean copy = FALSE; /* pattern should be, or has been, copied */ 2320 Boolean copy = FALSE; /* pattern should be, or has been, copied */
2321 Boolean needSubst = FALSE; 2321 Boolean needSubst = FALSE;
2322 /* 2322 /*
2323 * In the loop below, ignore ':' unless we are at (or back to) the 2323 * In the loop below, ignore ':' unless we are at (or back to) the
2324 * original brace level. 2324 * original brace level.
2325 * XXX This will likely not work right if $() and ${} are intermixed. 2325 * XXX This will likely not work right if $() and ${} are intermixed.
2326 */ 2326 */
2327 int nest = 1; 2327 int nest = 1;
2328 for (st->cp = mod + 1; 2328 for (st->cp = mod + 1;
2329 *st->cp != '\0' && !(*st->cp == ':' && nest == 1); 2329 *st->cp != '\0' && !(*st->cp == ':' && nest == 1);
2330 st->cp++) { 2330 st->cp++) {
2331 if (*st->cp == '\\' && 2331 if (*st->cp == '\\' &&
2332 (st->cp[1] == ':' || st->cp[1] == st->endc || 2332 (st->cp[1] == ':' || st->cp[1] == st->endc ||
2333 st->cp[1] == st->startc)) { 2333 st->cp[1] == st->startc)) {
2334 if (!needSubst) 2334 if (!needSubst)
2335 copy = TRUE; 2335 copy = TRUE;
2336 st->cp++; 2336 st->cp++;
2337 continue; 2337 continue;
2338 } 2338 }
2339 if (*st->cp == '$') 2339 if (*st->cp == '$')
2340 needSubst = TRUE; 2340 needSubst = TRUE;
2341 if (*st->cp == '(' || *st->cp == '{') 2341 if (*st->cp == '(' || *st->cp == '{')
2342 ++nest; 2342 ++nest;
2343 if (*st->cp == ')' || *st->cp == '}') { 2343 if (*st->cp == ')' || *st->cp == '}') {
2344 --nest; 2344 --nest;
2345 if (nest == 0) 2345 if (nest == 0)
2346 break; 2346 break;
2347 } 2347 }
2348 } 2348 }
2349 st->termc = *st->cp; 2349 st->termc = *st->cp;
2350 const char *endpat = st->cp; 2350 const char *endpat = st->cp;
2351 2351
2352 char *pattern = NULL; 2352 char *pattern = NULL;
2353 if (copy) { 2353 if (copy) {
2354 /* 2354 /* Compress the \:'s out of the pattern. */
2355 * Need to compress the \:'s out of the pattern, so 2355 pattern = bmake_malloc(st->cp - (mod + 1) + 1);
2356 * allocate enough room to hold the uncompressed 
2357 * pattern (note that st->cp started at mod+1, so 
2358 * st->cp - mod takes the null byte into account) and 
2359 * compress the pattern into the space. 
2360 */ 
2361 pattern = bmake_malloc(st->cp - mod); 
2362 char *cp2; 2356 char *cp2;
2363 for (cp2 = pattern, st->cp = mod + 1; 2357 for (cp2 = pattern, st->cp = mod + 1;
2364 st->cp < endpat; 2358 st->cp < endpat;
2365 st->cp++, cp2++) { 2359 st->cp++, cp2++) {
2366 if ((*st->cp == '\\') && (st->cp+1 < endpat) && 2360 if ((*st->cp == '\\') && (st->cp+1 < endpat) &&
 2361 /* XXX: st->startc is missing here; see above */
2367 (st->cp[1] == ':' || st->cp[1] == st->endc)) 2362 (st->cp[1] == ':' || st->cp[1] == st->endc))
2368 st->cp++; 2363 st->cp++;
2369 *cp2 = *st->cp; 2364 *cp2 = *st->cp;
2370 } 2365 }
2371 *cp2 = '\0'; 2366 *cp2 = '\0';
2372 endpat = cp2; 2367 endpat = cp2;
2373 } else { 2368 } else {
2374 /* 2369 /*
2375 * Either Var_Subst or ModifyWords will need a 2370 * Either Var_Subst or ModifyWords will need a
2376 * nul-terminated string soon, so construct one now. 2371 * nul-terminated string soon, so construct one now.
2377 */ 2372 */
2378 pattern = bmake_strndup(mod + 1, endpat - (mod + 1)); 2373 pattern = bmake_strndup(mod + 1, endpat - (mod + 1));
2379 } 2374 }
2380 if (needSubst) { 2375 if (needSubst) {
2381 /* pattern contains embedded '$', so use Var_Subst to expand it. */ 2376 /* pattern contains embedded '$', so use Var_Subst to expand it. */
2382 char *old_pattern = pattern; 2377 char *old_pattern = pattern;
2383 pattern = Var_Subst(NULL, pattern, st->ctxt, st->eflags); 2378 pattern = Var_Subst(NULL, pattern, st->ctxt, st->eflags);
2384 free(old_pattern); 2379 free(old_pattern);
2385 } 2380 }
2386 if (DEBUG(VAR)) 2381 if (DEBUG(VAR))
2387 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n", 2382 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
2388 st->v->name, st->nstr, pattern); 2383 st->v->name, st->nstr, pattern);
2389 ModifyWordsCallback callback = mod[0] == 'M' 2384 ModifyWordsCallback callback = mod[0] == 'M'
2390 ? ModifyWord_Match : ModifyWord_NoMatch; 2385 ? ModifyWord_Match : ModifyWord_NoMatch;
2391 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr, 2386 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr,
2392 callback, pattern); 2387 callback, pattern);
2393 free(pattern); 2388 free(pattern);
2394} 2389}
2395 2390
2396/* :S,from,to, */ 2391/* :S,from,to, */
2397static Boolean 2392static Boolean
2398ApplyModifier_Subst(const char * const mod, ApplyModifiersState *st) 2393ApplyModifier_Subst(const char * const mod, ApplyModifiersState *st)
2399{ 2394{
2400 ModifyWord_SubstArgs args; 2395 ModifyWord_SubstArgs args;
2401 Boolean oneBigWord = st->oneBigWord; 2396 Boolean oneBigWord = st->oneBigWord;
2402 char delim = mod[1]; 2397 char delim = mod[1];
2403 2398
2404 st->cp = mod + 2; 2399 st->cp = mod + 2;
2405 2400
2406 /* 2401 /*
2407 * If pattern begins with '^', it is anchored to the 2402 * If pattern begins with '^', it is anchored to the
2408 * start of the word -- skip over it and flag pattern. 2403 * start of the word -- skip over it and flag pattern.
2409 */ 2404 */
2410 args.pflags = 0; 2405 args.pflags = 0;
2411 if (*st->cp == '^') { 2406 if (*st->cp == '^') {
2412 args.pflags |= VARP_ANCHOR_START; 2407 args.pflags |= VARP_ANCHOR_START;
2413 st->cp++; 2408 st->cp++;
2414 } 2409 }
2415 2410
2416 char *lhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2411 char *lhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2417 &args.lhsLen, &args.pflags, NULL); 2412 &args.lhsLen, &args.pflags, NULL);
2418 if (lhs == NULL) { 2413 if (lhs == NULL) {
2419 st->missing_delim = delim; 2414 st->missing_delim = delim;
2420 return FALSE; 2415 return FALSE;
2421 } 2416 }
2422 args.lhs = lhs; 2417 args.lhs = lhs;
2423 2418
2424 char *rhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2419 char *rhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2425 &args.rhsLen, NULL, &args); 2420 &args.rhsLen, NULL, &args);
2426 if (rhs == NULL) { 2421 if (rhs == NULL) {
2427 st->missing_delim = delim; 2422 st->missing_delim = delim;
2428 return FALSE; 2423 return FALSE;
2429 } 2424 }
2430 args.rhs = rhs; 2425 args.rhs = rhs;
2431 2426
2432 /* 2427 /*
2433 * Check for global substitution. If 'g' after the final 2428 * Check for global substitution. If 'g' after the final
2434 * delimiter, substitution is global and is marked that 2429 * delimiter, substitution is global and is marked that
2435 * way. 2430 * way.
2436 */ 2431 */
2437 for (;; st->cp++) { 2432 for (;; st->cp++) {
2438 switch (*st->cp) { 2433 switch (*st->cp) {
2439 case 'g': 2434 case 'g':
2440 args.pflags |= VARP_SUB_GLOBAL; 2435 args.pflags |= VARP_SUB_GLOBAL;
2441 continue; 2436 continue;
2442 case '1': 2437 case '1':
2443 args.pflags |= VARP_SUB_ONE; 2438 args.pflags |= VARP_SUB_ONE;
2444 continue; 2439 continue;
2445 case 'W': 2440 case 'W':
2446 oneBigWord = TRUE; 2441 oneBigWord = TRUE;
2447 continue; 2442 continue;
2448 } 2443 }
2449 break; 2444 break;
2450 } 2445 }
2451 2446
2452 st->termc = *st->cp; 2447 st->termc = *st->cp;
2453 st->newStr = ModifyWords(st->ctxt, st->sep, oneBigWord, st->nstr, 2448 st->newStr = ModifyWords(st->ctxt, st->sep, oneBigWord, st->nstr,
2454 ModifyWord_Subst, &args); 2449 ModifyWord_Subst, &args);
2455 2450
2456 free(lhs); 2451 free(lhs);
2457 free(rhs); 2452 free(rhs);
2458 return TRUE; 2453 return TRUE;
2459} 2454}
2460 2455
2461#ifndef NO_REGEX 2456#ifndef NO_REGEX
2462 2457
2463/* :C,from,to, */ 2458/* :C,from,to, */
2464static Boolean 2459static Boolean
2465ApplyModifier_Regex(const char *mod, ApplyModifiersState *st) 2460ApplyModifier_Regex(const char *mod, ApplyModifiersState *st)
2466{ 2461{
2467 ModifyWord_SubstRegexArgs args; 2462 ModifyWord_SubstRegexArgs args;
2468 2463
2469 args.pflags = 0; 2464 args.pflags = 0;
2470 Boolean oneBigWord = st->oneBigWord; 2465 Boolean oneBigWord = st->oneBigWord;
2471 char delim = mod[1]; 2466 char delim = mod[1];
2472 2467
2473 st->cp = mod + 2; 2468 st->cp = mod + 2;
2474 2469
2475 char *re = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2470 char *re = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2476 NULL, NULL, NULL); 2471 NULL, NULL, NULL);
2477 if (re == NULL) { 2472 if (re == NULL) {
2478 st->missing_delim = delim; 2473 st->missing_delim = delim;
2479 return FALSE; 2474 return FALSE;
2480 } 2475 }
2481 2476
2482 args.replace = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2477 args.replace = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2483 NULL, NULL, NULL); 2478 NULL, NULL, NULL);
2484 if (args.replace == NULL) { 2479 if (args.replace == NULL) {
2485 free(re); 2480 free(re);
2486 st->missing_delim = delim; 2481 st->missing_delim = delim;
2487 return FALSE; 2482 return FALSE;
2488 } 2483 }
2489 2484
2490 for (;; st->cp++) { 2485 for (;; st->cp++) {
2491 switch (*st->cp) { 2486 switch (*st->cp) {
2492 case 'g': 2487 case 'g':
2493 args.pflags |= VARP_SUB_GLOBAL; 2488 args.pflags |= VARP_SUB_GLOBAL;
2494 continue; 2489 continue;
2495 case '1': 2490 case '1':
2496 args.pflags |= VARP_SUB_ONE; 2491 args.pflags |= VARP_SUB_ONE;
2497 continue; 2492 continue;
2498 case 'W': 2493 case 'W':
2499 oneBigWord = TRUE; 2494 oneBigWord = TRUE;
2500 continue; 2495 continue;
2501 } 2496 }
2502 break; 2497 break;
2503 } 2498 }
2504 2499
2505 st->termc = *st->cp; 2500 st->termc = *st->cp;
2506 2501
2507 int error = regcomp(&args.re, re, REG_EXTENDED); 2502 int error = regcomp(&args.re, re, REG_EXTENDED);
2508 free(re); 2503 free(re);
2509 if (error) { 2504 if (error) {
2510 VarREError(error, &args.re, "RE substitution error"); 2505 VarREError(error, &args.re, "RE substitution error");
2511 free(args.replace); 2506 free(args.replace);
2512 return FALSE; 2507 return FALSE;
2513 } 2508 }
2514 2509
2515 args.nsub = args.re.re_nsub + 1; 2510 args.nsub = args.re.re_nsub + 1;
2516 if (args.nsub < 1) 2511 if (args.nsub < 1)
2517 args.nsub = 1; 2512 args.nsub = 1;
2518 if (args.nsub > 10) 2513 if (args.nsub > 10)
2519 args.nsub = 10; 2514 args.nsub = 10;
2520 st->newStr = ModifyWords(st->ctxt, st->sep, oneBigWord, st->nstr, 2515 st->newStr = ModifyWords(st->ctxt, st->sep, oneBigWord, st->nstr,
2521 ModifyWord_SubstRegex, &args); 2516 ModifyWord_SubstRegex, &args);
2522 regfree(&args.re); 2517 regfree(&args.re);
2523 free(args.replace); 2518 free(args.replace);
2524 return TRUE; 2519 return TRUE;
2525} 2520}
2526#endif 2521#endif
2527 2522
2528static void 2523static void
2529ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED) 2524ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
2530{ 2525{
2531 SepBuf_AddStr(buf, word); 2526 SepBuf_AddStr(buf, word);
2532} 2527}
2533 2528
2534/* :ts<separator> */ 2529/* :ts<separator> */
2535static Boolean 2530static Boolean
2536ApplyModifier_ToSep(const char *sep, ApplyModifiersState *st) 2531ApplyModifier_ToSep(const char *sep, ApplyModifiersState *st)
2537{ 2532{
2538 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) { 2533 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
2539 /* ":ts<unrecognised><endc>" or ":ts<unrecognised>:" */ 2534 /* ":ts<unrecognised><endc>" or ":ts<unrecognised>:" */
2540 st->sep = sep[0]; 2535 st->sep = sep[0];
2541 st->cp = sep + 1; 2536 st->cp = sep + 1;
2542 } else if (sep[0] == st->endc || sep[0] == ':') { 2537 } else if (sep[0] == st->endc || sep[0] == ':') {
2543 /* ":ts<endc>" or ":ts:" */ 2538 /* ":ts<endc>" or ":ts:" */
2544 st->sep = '\0'; /* no separator */ 2539 st->sep = '\0'; /* no separator */
2545 st->cp = sep; 2540 st->cp = sep;
2546 } else if (sep[0] == '\\') { 2541 } else if (sep[0] == '\\') {
2547 const char *xp = sep + 1; 2542 const char *xp = sep + 1;
2548 int base = 8; /* assume octal */ 2543 int base = 8; /* assume octal */
2549 2544
2550 switch (sep[1]) { 2545 switch (sep[1]) {
2551 case 'n': 2546 case 'n':
2552 st->sep = '\n'; 2547 st->sep = '\n';
2553 st->cp = sep + 2; 2548 st->cp = sep + 2;
2554 break; 2549 break;
2555 case 't': 2550 case 't':
2556 st->sep = '\t'; 2551 st->sep = '\t';
2557 st->cp = sep + 2; 2552 st->cp = sep + 2;
2558 break; 2553 break;
2559 case 'x': 2554 case 'x':
2560 base = 16; 2555 base = 16;
2561 xp++; 2556 xp++;
2562 goto get_numeric; 2557 goto get_numeric;
2563 case '0': 2558 case '0':
2564 base = 0; 2559 base = 0;
2565 goto get_numeric; 2560 goto get_numeric;
2566 default: 2561 default:
2567 if (!isdigit((unsigned char)sep[1])) 2562 if (!isdigit((unsigned char)sep[1]))
2568 return FALSE; /* ":ts<backslash><unrecognised>". */ 2563 return FALSE; /* ":ts<backslash><unrecognised>". */
2569 2564
2570 char *end; 2565 char *end;
2571 get_numeric: 2566 get_numeric:
2572 st->sep = strtoul(sep + 1 + (sep[1] == 'x'), &end, base); 2567 st->sep = strtoul(sep + 1 + (sep[1] == 'x'), &end, base);
2573 if (*end != ':' && *end != st->endc) 2568 if (*end != ':' && *end != st->endc)
2574 return FALSE; 2569 return FALSE;
2575 st->cp = end; 2570 st->cp = end;
2576 break; 2571 break;
2577 } 2572 }
2578 } else { 2573 } else {
2579 return FALSE; /* Found ":ts<unrecognised><unrecognised>". */ 2574 return FALSE; /* Found ":ts<unrecognised><unrecognised>". */
2580 } 2575 }
2581 2576
2582 st->termc = *st->cp; 2577 st->termc = *st->cp;
2583 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr, 2578 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr,
2584 ModifyWord_Copy, NULL); 2579 ModifyWord_Copy, NULL);
2585 return TRUE; 2580 return TRUE;
2586} 2581}
2587 2582
2588/* :tA, :tu, :tl, :ts<separator>, etc. */ 2583/* :tA, :tu, :tl, :ts<separator>, etc. */
2589static Boolean 2584static Boolean
2590ApplyModifier_To(const char *mod, ApplyModifiersState *st) 2585ApplyModifier_To(const char *mod, ApplyModifiersState *st)
2591{ 2586{
2592 st->cp = mod + 1; /* make sure it is set */ 2587 st->cp = mod + 1; /* make sure it is set */
2593 if (mod[1] == st->endc || mod[1] == ':') 2588 if (mod[1] == st->endc || mod[1] == ':')
2594 return FALSE; /* Found ":t<endc>" or ":t:". */ 2589 return FALSE; /* Found ":t<endc>" or ":t:". */
2595 2590
2596 if (mod[1] == 's') 2591 if (mod[1] == 's')
2597 return ApplyModifier_ToSep(mod + 2, st); 2592 return ApplyModifier_ToSep(mod + 2, st);
2598 2593
2599 if (mod[2] != st->endc && mod[2] != ':') 2594 if (mod[2] != st->endc && mod[2] != ':')
2600 return FALSE; /* Found ":t<unrecognised><unrecognised>". */ 2595 return FALSE; /* Found ":t<unrecognised><unrecognised>". */
2601 2596
2602 /* Check for two-character options: ":tu", ":tl" */ 2597 /* Check for two-character options: ":tu", ":tl" */
2603 if (mod[1] == 'A') { /* absolute path */ 2598 if (mod[1] == 'A') { /* absolute path */
2604 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr, 2599 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr,
2605 ModifyWord_Realpath, NULL); 2600 ModifyWord_Realpath, NULL);
2606 st->cp = mod + 2; 2601 st->cp = mod + 2;
2607 st->termc = *st->cp; 2602 st->termc = *st->cp;
2608 } else if (mod[1] == 'u') { 2603 } else if (mod[1] == 'u') {
2609 char *dp = bmake_strdup(st->nstr); 2604 char *dp = bmake_strdup(st->nstr);
2610 for (st->newStr = dp; *dp; dp++) 2605 for (st->newStr = dp; *dp; dp++)
2611 *dp = toupper((unsigned char)*dp); 2606 *dp = toupper((unsigned char)*dp);
2612 st->cp = mod + 2; 2607 st->cp = mod + 2;
2613 st->termc = *st->cp; 2608 st->termc = *st->cp;
2614 } else if (mod[1] == 'l') { 2609 } else if (mod[1] == 'l') {
2615 char *dp = bmake_strdup(st->nstr); 2610 char *dp = bmake_strdup(st->nstr);
2616 for (st->newStr = dp; *dp; dp++) 2611 for (st->newStr = dp; *dp; dp++)
2617 *dp = tolower((unsigned char)*dp); 2612 *dp = tolower((unsigned char)*dp);
2618 st->cp = mod + 2; 2613 st->cp = mod + 2;
2619 st->termc = *st->cp; 2614 st->termc = *st->cp;
2620 } else if (mod[1] == 'W' || mod[1] == 'w') { 2615 } else if (mod[1] == 'W' || mod[1] == 'w') {
2621 st->oneBigWord = mod[1] == 'W'; 2616 st->oneBigWord = mod[1] == 'W';
2622 st->newStr = st->nstr; 2617 st->newStr = st->nstr;
2623 st->cp = mod + 2; 2618 st->cp = mod + 2;
2624 st->termc = *st->cp; 2619 st->termc = *st->cp;
2625 } else { 2620 } else {
2626 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */ 2621 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
2627 return FALSE; 2622 return FALSE;
2628 } 2623 }
2629 return TRUE; 2624 return TRUE;
2630} 2625}
2631 2626
2632/* :[#], :[1], etc. */ 2627/* :[#], :[1], etc. */
2633static int 2628static int
2634ApplyModifier_Words(const char *mod, ApplyModifiersState *st) 2629ApplyModifier_Words(const char *mod, ApplyModifiersState *st)
2635{ 2630{
2636 st->cp = mod + 1; /* point to char after '[' */ 2631 st->cp = mod + 1; /* point to char after '[' */
2637 char delim = ']'; /* look for closing ']' */ 2632 char delim = ']'; /* look for closing ']' */
2638 char *estr = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2633 char *estr = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2639 NULL, NULL, NULL); 2634 NULL, NULL, NULL);
2640 if (estr == NULL) { 2635 if (estr == NULL) {
2641 st->missing_delim = delim; 2636 st->missing_delim = delim;
2642 return 'c'; 2637 return 'c';
2643 } 2638 }
2644 2639
2645 /* now st->cp points just after the closing ']' */ 2640 /* now st->cp points just after the closing ']' */
2646 if (st->cp[0] != ':' && st->cp[0] != st->endc) 2641 if (st->cp[0] != ':' && st->cp[0] != st->endc)
2647 goto bad_modifier; /* Found junk after ']' */ 2642 goto bad_modifier; /* Found junk after ']' */
2648 2643
2649 if (estr[0] == '\0') 2644 if (estr[0] == '\0')
2650 goto bad_modifier; /* empty square brackets in ":[]". */ 2645 goto bad_modifier; /* empty square brackets in ":[]". */
2651 2646
2652 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */ 2647 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
2653 if (st->oneBigWord) { 2648 if (st->oneBigWord) {
2654 st->newStr = bmake_strdup("1"); 2649 st->newStr = bmake_strdup("1");
2655 } else { 2650 } else {
2656 /* XXX: brk_string() is a rather expensive 2651 /* XXX: brk_string() is a rather expensive
2657 * way of counting words. */ 2652 * way of counting words. */
2658 char *as; 2653 char *as;
2659 int ac; 2654 int ac;
2660 char **av = brk_string(st->nstr, &ac, FALSE, &as); 2655 char **av = brk_string(st->nstr, &ac, FALSE, &as);
2661 free(as); 2656 free(as);
2662 free(av); 2657 free(av);
2663 2658
2664 Buffer buf; 2659 Buffer buf;
2665 Buf_Init(&buf, 4); /* 3 digits + '\0' */ 2660 Buf_Init(&buf, 4); /* 3 digits + '\0' */
2666 Buf_AddInt(&buf, ac); 2661 Buf_AddInt(&buf, ac);
2667 st->newStr = Buf_Destroy(&buf, FALSE); 2662 st->newStr = Buf_Destroy(&buf, FALSE);
2668 } 2663 }
2669 goto ok; 2664 goto ok;
2670 } 2665 }
2671 2666
2672 if (estr[0] == '*' && estr[1] == '\0') { 2667 if (estr[0] == '*' && estr[1] == '\0') {
2673 /* Found ":[*]" */ 2668 /* Found ":[*]" */
2674 st->oneBigWord = TRUE; 2669 st->oneBigWord = TRUE;
2675 st->newStr = st->nstr; 2670 st->newStr = st->nstr;
2676 goto ok; 2671 goto ok;
2677 } 2672 }
2678 2673
2679 if (estr[0] == '@' && estr[1] == '\0') { 2674 if (estr[0] == '@' && estr[1] == '\0') {
2680 /* Found ":[@]" */ 2675 /* Found ":[@]" */
2681 st->oneBigWord = FALSE; 2676 st->oneBigWord = FALSE;
2682 st->newStr = st->nstr; 2677 st->newStr = st->nstr;
2683 goto ok; 2678 goto ok;
2684 } 2679 }
2685 2680
2686 /* 2681 /*
2687 * We expect estr to contain a single integer for :[N], or two integers 2682 * We expect estr to contain a single integer for :[N], or two integers
2688 * separated by ".." for :[start..end]. 2683 * separated by ".." for :[start..end].
2689 */ 2684 */
2690 char *ep; 2685 char *ep;
2691 int first = strtol(estr, &ep, 0); 2686 int first = strtol(estr, &ep, 0);
2692 int last; 2687 int last;
2693 if (ep == estr) /* Found junk instead of a number */ 2688 if (ep == estr) /* Found junk instead of a number */
2694 goto bad_modifier; 2689 goto bad_modifier;
2695 2690
2696 if (ep[0] == '\0') { /* Found only one integer in :[N] */ 2691 if (ep[0] == '\0') { /* Found only one integer in :[N] */
2697 last = first; 2692 last = first;
2698 } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') { 2693 } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') {
2699 /* Expecting another integer after ".." */ 2694 /* Expecting another integer after ".." */
2700 ep += 2; 2695 ep += 2;
2701 last = strtol(ep, &ep, 0); 2696 last = strtol(ep, &ep, 0);
2702 if (ep[0] != '\0') /* Found junk after ".." */ 2697 if (ep[0] != '\0') /* Found junk after ".." */
2703 goto bad_modifier; 2698 goto bad_modifier;
2704 } else 2699 } else
2705 goto bad_modifier; /* Found junk instead of ".." */ 2700 goto bad_modifier; /* Found junk instead of ".." */
2706 2701
2707 /* 2702 /*
2708 * Now seldata is properly filled in, but we still have to check for 0 as 2703 * Now seldata is properly filled in, but we still have to check for 0 as
2709 * a special case. 2704 * a special case.
2710 */ 2705 */
2711 if (first == 0 && last == 0) { 2706 if (first == 0 && last == 0) {
2712 /* ":[0]" or perhaps ":[0..0]" */ 2707 /* ":[0]" or perhaps ":[0..0]" */
2713 st->oneBigWord = TRUE; 2708 st->oneBigWord = TRUE;
2714 st->newStr = st->nstr; 2709 st->newStr = st->nstr;
2715 goto ok; 2710 goto ok;
2716 } 2711 }
2717 2712
2718 /* ":[0..N]" or ":[N..0]" */ 2713 /* ":[0..N]" or ":[N..0]" */
2719 if (first == 0 || last == 0) 2714 if (first == 0 || last == 0)
2720 goto bad_modifier; 2715 goto bad_modifier;
2721 2716
2722 /* Normal case: select the words described by seldata. */ 2717 /* Normal case: select the words described by seldata. */
2723 st->newStr = VarSelectWords(st->sep, st->oneBigWord, st->nstr, first, last); 2718 st->newStr = VarSelectWords(st->sep, st->oneBigWord, st->nstr, first, last);
2724 2719
2725ok: 2720ok:
2726 st->termc = *st->cp; 2721 st->termc = *st->cp;
2727 free(estr); 2722 free(estr);
2728 return 0; 2723 return 0;
2729 2724
2730bad_modifier: 2725bad_modifier:
2731 free(estr); 2726 free(estr);
2732 return 'b'; 2727 return 'b';
2733} 2728}
2734 2729
2735/* :O or :Ox */ 2730/* :O or :Ox */
2736static Boolean 2731static Boolean
2737ApplyModifier_Order(const char *mod, ApplyModifiersState *st) 2732ApplyModifier_Order(const char *mod, ApplyModifiersState *st)
2738{ 2733{
2739 char otype; 2734 char otype;
2740 2735
2741 st->cp = mod + 1; /* skip to the rest in any case */ 2736 st->cp = mod + 1; /* skip to the rest in any case */
2742 if (mod[1] == st->endc || mod[1] == ':') { 2737 if (mod[1] == st->endc || mod[1] == ':') {
2743 otype = 's'; 2738 otype = 's';
2744 st->termc = *st->cp; 2739 st->termc = *st->cp;
2745 } else if ((mod[1] == 'r' || mod[1] == 'x') && 2740 } else if ((mod[1] == 'r' || mod[1] == 'x') &&
2746 (mod[2] == st->endc || mod[2] == ':')) { 2741 (mod[2] == st->endc || mod[2] == ':')) {
2747 otype = mod[1]; 2742 otype = mod[1];
2748 st->cp = mod + 2; 2743 st->cp = mod + 2;
2749 st->termc = *st->cp; 2744 st->termc = *st->cp;
2750 } else { 2745 } else {
2751 return FALSE; 2746 return FALSE;
2752 } 2747 }
2753 st->newStr = VarOrder(st->nstr, otype); 2748 st->newStr = VarOrder(st->nstr, otype);
2754 return TRUE; 2749 return TRUE;
2755} 2750}
2756 2751
2757/* :? then : else */ 2752/* :? then : else */
2758static Boolean 2753static Boolean
2759ApplyModifier_IfElse(const char *mod, ApplyModifiersState *st) 2754ApplyModifier_IfElse(const char *mod, ApplyModifiersState *st)
2760{ 2755{
2761 Boolean value = FALSE; 2756 Boolean value = FALSE;
2762 int cond_rc = 0; 2757 int cond_rc = 0;
2763 VarEvalFlags then_eflags = st->eflags & ~VARE_WANTRES; 2758 VarEvalFlags then_eflags = st->eflags & ~VARE_WANTRES;
2764 VarEvalFlags else_eflags = st->eflags & ~VARE_WANTRES; 2759 VarEvalFlags else_eflags = st->eflags & ~VARE_WANTRES;
2765 2760
2766 if (st->eflags & VARE_WANTRES) { 2761 if (st->eflags & VARE_WANTRES) {
2767 cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE); 2762 cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE);
2768 if (cond_rc != COND_INVALID && value) 2763 if (cond_rc != COND_INVALID && value)
2769 then_eflags |= VARE_WANTRES; 2764 then_eflags |= VARE_WANTRES;
2770 if (cond_rc != COND_INVALID && !value) 2765 if (cond_rc != COND_INVALID && !value)
2771 else_eflags |= VARE_WANTRES; 2766 else_eflags |= VARE_WANTRES;
2772 } 2767 }
2773 2768
2774 st->cp = mod + 1; 2769 st->cp = mod + 1;
2775 char delim = ':'; 2770 char delim = ':';
2776 char *then_expr = ParseModifierPart(&st->cp, delim, then_eflags, st->ctxt, 2771 char *then_expr = ParseModifierPart(&st->cp, delim, then_eflags, st->ctxt,
2777 NULL, NULL, NULL); 2772 NULL, NULL, NULL);
2778 if (then_expr == NULL) { 2773 if (then_expr == NULL) {
2779 st->missing_delim = delim; 2774 st->missing_delim = delim;
2780 return FALSE; 2775 return FALSE;
2781 } 2776 }
2782 2777
2783 delim = st->endc; /* BRCLOSE or PRCLOSE */ 2778 delim = st->endc; /* BRCLOSE or PRCLOSE */
2784 char *else_expr = ParseModifierPart(&st->cp, delim, else_eflags, st->ctxt, 2779 char *else_expr = ParseModifierPart(&st->cp, delim, else_eflags, st->ctxt,
2785 NULL, NULL, NULL); 2780 NULL, NULL, NULL);
2786 if (else_expr == NULL) { 2781 if (else_expr == NULL) {
2787 st->missing_delim = delim; 2782 st->missing_delim = delim;
2788 return FALSE; 2783 return FALSE;
2789 } 2784 }
2790 2785
2791 st->termc = *--st->cp; 2786 st->termc = *--st->cp;
2792 if (cond_rc == COND_INVALID) { 2787 if (cond_rc == COND_INVALID) {
2793 Error("Bad conditional expression `%s' in %s?%s:%s", 2788 Error("Bad conditional expression `%s' in %s?%s:%s",
2794 st->v->name, st->v->name, then_expr, else_expr); 2789 st->v->name, st->v->name, then_expr, else_expr);
2795 return FALSE; 2790 return FALSE;
2796 } 2791 }
2797 2792
2798 if (value) { 2793 if (value) {
2799 st->newStr = then_expr; 2794 st->newStr = then_expr;
2800 free(else_expr); 2795 free(else_expr);
2801 } else { 2796 } else {
2802 st->newStr = else_expr; 2797 st->newStr = else_expr;
2803 free(then_expr); 2798 free(then_expr);
2804 } 2799 }
2805 if (st->v->flags & VAR_JUNK) 2800 if (st->v->flags & VAR_JUNK)
2806 st->v->flags |= VAR_KEEP; 2801 st->v->flags |= VAR_KEEP;
2807 return TRUE; 2802 return TRUE;
2808} 2803}
2809 2804
2810/* 2805/*
2811 * The ::= modifiers actually assign a value to the variable. 2806 * The ::= modifiers actually assign a value to the variable.
2812 * Their main purpose is in supporting modifiers of .for loop 2807 * Their main purpose is in supporting modifiers of .for loop
2813 * iterators and other obscure uses. They always expand to 2808 * iterators and other obscure uses. They always expand to
2814 * nothing. In a target rule that would otherwise expand to an 2809 * nothing. In a target rule that would otherwise expand to an
2815 * empty line they can be preceded with @: to keep make happy. 2810 * empty line they can be preceded with @: to keep make happy.
2816 * Eg. 2811 * Eg.
2817 * 2812 *
2818 * foo: .USE 2813 * foo: .USE
2819 * .for i in ${.TARGET} ${.TARGET:R}.gz 2814 * .for i in ${.TARGET} ${.TARGET:R}.gz
2820 * @: ${t::=$i} 2815 * @: ${t::=$i}
2821 * @echo blah ${t:T} 2816 * @echo blah ${t:T}
2822 * .endfor 2817 * .endfor
2823 * 2818 *
2824 * ::=<str> Assigns <str> as the new value of variable. 2819 * ::=<str> Assigns <str> as the new value of variable.
2825 * ::?=<str> Assigns <str> as value of variable if 2820 * ::?=<str> Assigns <str> as value of variable if
2826 * it was not already set. 2821 * it was not already set.
2827 * ::+=<str> Appends <str> to variable. 2822 * ::+=<str> Appends <str> to variable.
2828 * ::!=<cmd> Assigns output of <cmd> as the new value of 2823 * ::!=<cmd> Assigns output of <cmd> as the new value of
2829 * variable. 2824 * variable.
2830 */ 2825 */
2831static int 2826static int
2832ApplyModifier_Assign(const char *mod, ApplyModifiersState *st) 2827ApplyModifier_Assign(const char *mod, ApplyModifiersState *st)
2833{ 2828{
2834 const char *op = mod + 1; 2829 const char *op = mod + 1;
2835 if (!(op[0] == '=' || 2830 if (!(op[0] == '=' ||
2836 (op[1] == '=' && 2831 (op[1] == '=' &&
2837 (op[0] == '!' || op[0] == '+' || op[0] == '?')))) 2832 (op[0] == '!' || op[0] == '+' || op[0] == '?'))))
2838 return 'd'; /* "::<unrecognised>" */ 2833 return 'd'; /* "::<unrecognised>" */
2839 2834
2840 GNode *v_ctxt; /* context where v belongs */ 2835 GNode *v_ctxt; /* context where v belongs */
2841 2836
2842 if (st->v->name[0] == 0) 2837 if (st->v->name[0] == 0)
2843 return 'b'; 2838 return 'b';
2844 2839
2845 v_ctxt = st->ctxt; 2840 v_ctxt = st->ctxt;
2846 char *sv_name = NULL; 2841 char *sv_name = NULL;
2847 if (st->v->flags & VAR_JUNK) { 2842 if (st->v->flags & VAR_JUNK) {
2848 /* 2843 /*
2849 * We need to bmake_strdup() it incase ParseModifierPart() recurses. 2844 * We need to bmake_strdup() it incase ParseModifierPart() recurses.
2850 */ 2845 */
2851 sv_name = st->v->name; 2846 sv_name = st->v->name;
2852 st->v->name = bmake_strdup(st->v->name); 2847 st->v->name = bmake_strdup(st->v->name);
2853 } else if (st->ctxt != VAR_GLOBAL) { 2848 } else if (st->ctxt != VAR_GLOBAL) {
2854 Var *gv = VarFind(st->v->name, st->ctxt, 0); 2849 Var *gv = VarFind(st->v->name, st->ctxt, 0);
2855 if (gv == NULL) 2850 if (gv == NULL)
2856 v_ctxt = VAR_GLOBAL; 2851 v_ctxt = VAR_GLOBAL;
2857 else 2852 else
2858 VarFreeEnv(gv, TRUE); 2853 VarFreeEnv(gv, TRUE);
2859 } 2854 }
2860 2855
2861 switch (op[0]) { 2856 switch (op[0]) {
2862 case '+': 2857 case '+':
2863 case '?': 2858 case '?':
2864 case '!': 2859 case '!':
2865 st->cp = mod + 3; 2860 st->cp = mod + 3;
2866 break; 2861 break;
2867 default: 2862 default:
2868 st->cp = mod + 2; 2863 st->cp = mod + 2;
2869 break; 2864 break;
2870 } 2865 }
2871 2866
2872 char delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE; 2867 char delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE;
2873 char *val = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2868 char *val = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2874 NULL, NULL, NULL); 2869 NULL, NULL, NULL);
2875 if (st->v->flags & VAR_JUNK) { 2870 if (st->v->flags & VAR_JUNK) {
2876 /* restore original name */ 2871 /* restore original name */
2877 free(st->v->name); 2872 free(st->v->name);
2878 st->v->name = sv_name; 2873 st->v->name = sv_name;
2879 } 2874 }
2880 if (val == NULL) { 2875 if (val == NULL) {
2881 st->missing_delim = delim; 2876 st->missing_delim = delim;
2882 return 'c'; 2877 return 'c';
2883 } 2878 }
2884 2879
2885 st->termc = *--st->cp; 2880 st->termc = *--st->cp;
2886 2881
2887 if (st->eflags & VARE_WANTRES) { 2882 if (st->eflags & VARE_WANTRES) {
2888 switch (op[0]) { 2883 switch (op[0]) {
2889 case '+': 2884 case '+':
2890 Var_Append(st->v->name, val, v_ctxt); 2885 Var_Append(st->v->name, val, v_ctxt);
2891 break; 2886 break;
2892 case '!': { 2887 case '!': {
2893 const char *emsg; 2888 const char *emsg;
2894 st->newStr = Cmd_Exec(val, &emsg); 2889 st->newStr = Cmd_Exec(val, &emsg);
2895 if (emsg) 2890 if (emsg)
2896 Error(emsg, st->nstr); 2891 Error(emsg, st->nstr);
2897 else 2892 else
2898 Var_Set(st->v->name, st->newStr, v_ctxt); 2893 Var_Set(st->v->name, st->newStr, v_ctxt);
2899 free(st->newStr); 2894 free(st->newStr);
2900 break; 2895 break;
2901 } 2896 }
2902 case '?': 2897 case '?':
2903 if (!(st->v->flags & VAR_JUNK)) 2898 if (!(st->v->flags & VAR_JUNK))
2904 break; 2899 break;
2905 /* FALLTHROUGH */ 2900 /* FALLTHROUGH */
2906 default: 2901 default:
2907 Var_Set(st->v->name, val, v_ctxt); 2902 Var_Set(st->v->name, val, v_ctxt);
2908 break; 2903 break;
2909 } 2904 }
2910 } 2905 }
2911 free(val); 2906 free(val);
2912 st->newStr = varNoError; 2907 st->newStr = varNoError;
2913 return 0; 2908 return 0;
2914} 2909}
2915 2910
2916/* remember current value */ 2911/* remember current value */
2917static Boolean 2912static Boolean
2918ApplyModifier_Remember(const char *mod, ApplyModifiersState *st) 2913ApplyModifier_Remember(const char *mod, ApplyModifiersState *st)
2919{ 2914{
2920 if (!ModMatchEq(mod, "_", st->endc)) { 2915 if (!ModMatchEq(mod, "_", st->endc)) {
2921 st->cp = mod + 1; 2916 st->cp = mod + 1;
2922 return FALSE; 2917 return FALSE;
2923 } 2918 }
2924 2919
2925 if (mod[1] == '=') { 2920 if (mod[1] == '=') {
2926 size_t n = strcspn(mod + 2, ":)}"); 2921 size_t n = strcspn(mod + 2, ":)}");
2927 char *name = bmake_strndup(mod + 2, n); 2922 char *name = bmake_strndup(mod + 2, n);
2928 Var_Set(name, st->nstr, st->ctxt); 2923 Var_Set(name, st->nstr, st->ctxt);
2929 free(name); 2924 free(name);
2930 st->cp = mod + 2 + n; 2925 st->cp = mod + 2 + n;
2931 } else { 2926 } else {
2932 Var_Set("_", st->nstr, st->ctxt); 2927 Var_Set("_", st->nstr, st->ctxt);
2933 st->cp = mod + 1; 2928 st->cp = mod + 1;
2934 } 2929 }
2935 st->newStr = st->nstr; 2930 st->newStr = st->nstr;
2936 st->termc = *st->cp; 2931 st->termc = *st->cp;
2937 return TRUE; 2932 return TRUE;
2938} 2933}
2939 2934
2940#ifdef SYSVVARSUB 2935#ifdef SYSVVARSUB
2941/* :from=to */ 2936/* :from=to */
2942static int 2937static int
2943ApplyModifier_SysV(const char *mod, ApplyModifiersState *st) 2938ApplyModifier_SysV(const char *mod, ApplyModifiersState *st)
2944{ 2939{
2945 Boolean eqFound = FALSE; 2940 Boolean eqFound = FALSE;
2946 2941
2947 /* 2942 /*
2948 * First we make a pass through the string trying 2943 * First we make a pass through the string trying
2949 * to verify it is a SYSV-make-style translation: 2944 * to verify it is a SYSV-make-style translation:
2950 * it must be: <string1>=<string2>) 2945 * it must be: <string1>=<string2>)
2951 */ 2946 */
2952 st->cp = mod; 2947 st->cp = mod;
2953 int nest = 1; 2948 int nest = 1;
2954 while (*st->cp != '\0' && nest > 0) { 2949 while (*st->cp != '\0' && nest > 0) {
2955 if (*st->cp == '=') { 2950 if (*st->cp == '=') {
2956 eqFound = TRUE; 2951 eqFound = TRUE;
2957 /* continue looking for st->endc */ 2952 /* continue looking for st->endc */
2958 } else if (*st->cp == st->endc) 2953 } else if (*st->cp == st->endc)
2959 nest--; 2954 nest--;
2960 else if (*st->cp == st->startc) 2955 else if (*st->cp == st->startc)
2961 nest++; 2956 nest++;
2962 if (nest > 0) 2957 if (nest > 0)
2963 st->cp++; 2958 st->cp++;
2964 } 2959 }
2965 if (*st->cp != st->endc || !eqFound) 2960 if (*st->cp != st->endc || !eqFound)
2966 return 0; 2961 return 0;
2967 2962
2968 char delim = '='; 2963 char delim = '=';
2969 st->cp = mod; 2964 st->cp = mod;
2970 char *lhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2965 char *lhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2971 NULL, NULL, NULL); 2966 NULL, NULL, NULL);
2972 if (lhs == NULL) { 2967 if (lhs == NULL) {
2973 st->missing_delim = delim; 2968 st->missing_delim = delim;
2974 return 'c'; 2969 return 'c';
2975 } 2970 }
2976 2971
2977 delim = st->endc; 2972 delim = st->endc;
2978 char *rhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt, 2973 char *rhs = ParseModifierPart(&st->cp, delim, st->eflags, st->ctxt,
2979 NULL, NULL, NULL); 2974 NULL, NULL, NULL);
2980 if (rhs == NULL) { 2975 if (rhs == NULL) {
2981 st->missing_delim = delim; 2976 st->missing_delim = delim;
2982 return 'c'; 2977 return 'c';
2983 } 2978 }
2984 2979
2985 /* 2980 /*
2986 * SYSV modifications happen through the whole 2981 * SYSV modifications happen through the whole
2987 * string. Note the pattern is anchored at the end. 2982 * string. Note the pattern is anchored at the end.
2988 */ 2983 */
2989 st->termc = *--st->cp; 2984 st->termc = *--st->cp;
2990 if (lhs[0] == '\0' && *st->nstr == '\0') { 2985 if (lhs[0] == '\0' && *st->nstr == '\0') {
2991 st->newStr = st->nstr; /* special case */ 2986 st->newStr = st->nstr; /* special case */
2992 } else { 2987 } else {
2993 ModifyWord_SYSVSubstArgs args = { st->ctxt, lhs, rhs }; 2988 ModifyWord_SYSVSubstArgs args = { st->ctxt, lhs, rhs };
2994 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr, 2989 st->newStr = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->nstr,
2995 ModifyWord_SYSVSubst, &args); 2990 ModifyWord_SYSVSubst, &args);
2996 } 2991 }
2997 free(lhs); 2992 free(lhs);
2998 free(rhs); 2993 free(rhs);
2999 return '='; 2994 return '=';
3000} 2995}
3001#endif 2996#endif
3002 2997
3003/* 2998/*
3004 * Now we need to apply any modifiers the user wants applied. 2999 * Now we need to apply any modifiers the user wants applied.
3005 * These are: 3000 * These are:
3006 * :M<pattern> words which match the given <pattern>. 3001 * :M<pattern> words which match the given <pattern>.
3007 * <pattern> is of the standard file 3002 * <pattern> is of the standard file
3008 * wildcarding form. 3003 * wildcarding form.
3009 * :N<pattern> words which do not match the given <pattern>. 3004 * :N<pattern> words which do not match the given <pattern>.
3010 * :S<d><pat1><d><pat2><d>[1gW] 3005 * :S<d><pat1><d><pat2><d>[1gW]
3011 * Substitute <pat2> for <pat1> in the value 3006 * Substitute <pat2> for <pat1> in the value
3012 * :C<d><pat1><d><pat2><d>[1gW] 3007 * :C<d><pat1><d><pat2><d>[1gW]
3013 * Substitute <pat2> for regex <pat1> in the value 3008 * Substitute <pat2> for regex <pat1> in the value
3014 * :H Substitute the head of each word 3009 * :H Substitute the head of each word
3015 * :T Substitute the tail of each word 3010 * :T Substitute the tail of each word
3016 * :E Substitute the extension (minus '.') of 3011 * :E Substitute the extension (minus '.') of
3017 * each word 3012 * each word
3018 * :R Substitute the root of each word 3013 * :R Substitute the root of each word
3019 * (pathname minus the suffix). 3014 * (pathname minus the suffix).
3020 * :O ("Order") Alphabeticaly sort words in variable. 3015 * :O ("Order") Alphabeticaly sort words in variable.
3021 * :Ox ("intermiX") Randomize words in variable. 3016 * :Ox ("intermiX") Randomize words in variable.
3022 * :u ("uniq") Remove adjacent duplicate words. 3017 * :u ("uniq") Remove adjacent duplicate words.
3023 * :tu Converts the variable contents to uppercase. 3018 * :tu Converts the variable contents to uppercase.
3024 * :tl Converts the variable contents to lowercase. 3019 * :tl Converts the variable contents to lowercase.
3025 * :ts[c] Sets varSpace - the char used to 3020 * :ts[c] Sets varSpace - the char used to
3026 * separate words to 'c'. If 'c' is 3021 * separate words to 'c'. If 'c' is
3027 * omitted then no separation is used. 3022 * omitted then no separation is used.
3028 * :tW Treat the variable contents as a single 3023 * :tW Treat the variable contents as a single
3029 * word, even if it contains spaces. 3024 * word, even if it contains spaces.
3030 * (Mnemonic: one big 'W'ord.) 3025 * (Mnemonic: one big 'W'ord.)
3031 * :tw Treat the variable contents as multiple 3026 * :tw Treat the variable contents as multiple
3032 * space-separated words. 3027 * space-separated words.
3033 * (Mnemonic: many small 'w'ords.) 3028 * (Mnemonic: many small 'w'ords.)
3034 * :[index] Select a single word from the value. 3029 * :[index] Select a single word from the value.
3035 * :[start..end] Select multiple words from the value. 3030 * :[start..end] Select multiple words from the value.
3036 * :[*] or :[0] Select the entire value, as a single 3031 * :[*] or :[0] Select the entire value, as a single
3037 * word. Equivalent to :tW. 3032 * word. Equivalent to :tW.
3038 * :[@] Select the entire value, as multiple 3033 * :[@] Select the entire value, as multiple
3039 * words. Undoes the effect of :[*]. 3034 * words. Undoes the effect of :[*].
3040 * Equivalent to :tw. 3035 * Equivalent to :tw.
3041 * :[#] Returns the number of words in the value. 3036 * :[#] Returns the number of words in the value.
3042 * 3037 *
3043 * :?<true-value>:<false-value> 3038 * :?<true-value>:<false-value>
3044 * If the variable evaluates to true, return 3039 * If the variable evaluates to true, return
3045 * true value, else return the second value. 3040 * true value, else return the second value.
3046 * :lhs=rhs Like :S, but the rhs goes to the end of 3041 * :lhs=rhs Like :S, but the rhs goes to the end of
3047 * the invocation. 3042 * the invocation.
3048 * :sh Treat the current value as a command 3043 * :sh Treat the current value as a command
3049 * to be run, new value is its output. 3044 * to be run, new value is its output.
3050 * The following added so we can handle ODE makefiles. 3045 * The following added so we can handle ODE makefiles.
3051 * :@<tmpvar>@<newval>@ 3046 * :@<tmpvar>@<newval>@
3052 * Assign a temporary local variable <tmpvar> 3047 * Assign a temporary local variable <tmpvar>
3053 * to the current value of each word in turn 3048 * to the current value of each word in turn
3054 * and replace each word with the result of 3049 * and replace each word with the result of
3055 * evaluating <newval> 3050 * evaluating <newval>
3056 * :D<newval> Use <newval> as value if variable defined 3051 * :D<newval> Use <newval> as value if variable defined
3057 * :U<newval> Use <newval> as value if variable undefined 3052 * :U<newval> Use <newval> as value if variable undefined
3058 * :L Use the name of the variable as the value. 3053 * :L Use the name of the variable as the value.
3059 * :P Use the path of the node that has the same 3054 * :P Use the path of the node that has the same
3060 * name as the variable as the value. This 3055 * name as the variable as the value. This
3061 * basically includes an implied :L so that 3056 * basically includes an implied :L so that
3062 * the common method of refering to the path 3057 * the common method of refering to the path
3063 * of your dependent 'x' in a rule is to use 3058 * of your dependent 'x' in a rule is to use
3064 * the form '${x:P}'. 3059 * the form '${x:P}'.
3065 * :!<cmd>! Run cmd much the same as :sh run's the 3060 * :!<cmd>! Run cmd much the same as :sh run's the
3066 * current value of the variable. 3061 * current value of the variable.
3067 * Assignment operators (see ApplyModifier_Assign). 3062 * Assignment operators (see ApplyModifier_Assign).
3068 */ 3063 */
3069static char * 3064static char *
3070ApplyModifiers(char *nstr, const char * const tstr, 3065ApplyModifiers(char *nstr, const char * const tstr,
3071 int const startc, int const endc, 3066 int const startc, int const endc,
3072 Var * const v, GNode * const ctxt, VarEvalFlags const eflags, 3067 Var * const v, GNode * const ctxt, VarEvalFlags const eflags,
3073 int * const lengthPtr, void ** const freePtr) 3068 int * const lengthPtr, void ** const freePtr)
3074{ 3069{
3075 ApplyModifiersState st = { 3070 ApplyModifiersState st = {
3076 startc, endc, v, ctxt, eflags, 3071 startc, endc, v, ctxt, eflags,
3077 nstr, tstr, '\0', '\0', ' ', FALSE, NULL 3072 nstr, tstr, '\0', '\0', ' ', FALSE, NULL
3078 }; 3073 };
3079 3074
3080 const char *p = tstr; 3075 const char *p = tstr;
3081 while (*p != '\0' && *p != endc) { 3076 while (*p != '\0' && *p != endc) {
3082 3077
3083 if (*p == '$') { 3078 if (*p == '$') {
3084 /* 3079 /*
3085 * We may have some complex modifiers in a variable. 3080 * We may have some complex modifiers in a variable.
3086 */ 3081 */
3087 void *freeIt; 3082 void *freeIt;
3088 const char *rval; 3083 const char *rval;
3089 int rlen; 3084 int rlen;
3090 int c; 3085 int c;
3091 3086
3092 rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt); 3087 rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt);
3093 3088
3094 /* 3089 /*
3095 * If we have not parsed up to st.endc or ':', 3090 * If we have not parsed up to st.endc or ':',
3096 * we are not interested. 3091 * we are not interested.
3097 */ 3092 */
3098 if (rval != NULL && *rval && 3093 if (rval != NULL && *rval &&
3099 (c = p[rlen]) != '\0' && 3094 (c = p[rlen]) != '\0' &&
3100 c != ':' && 3095 c != ':' &&
3101 c != st.endc) { 3096 c != st.endc) {
3102 free(freeIt); 3097 free(freeIt);
3103 goto apply_mods; 3098 goto apply_mods;
3104 } 3099 }
3105 3100
3106 if (DEBUG(VAR)) { 3101 if (DEBUG(VAR)) {
3107 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n", 3102 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
3108 rval, rlen, p, rlen, p + rlen); 3103 rval, rlen, p, rlen, p + rlen);
3109 } 3104 }
3110 3105
3111 p += rlen; 3106 p += rlen;
3112 3107
3113 if (rval != NULL && *rval) { 3108 if (rval != NULL && *rval) {
3114 int used; 3109 int used;
3115 3110
3116 st.nstr = ApplyModifiers(st.nstr, rval, 0, 0, st.v, 3111 st.nstr = ApplyModifiers(st.nstr, rval, 0, 0, st.v,
3117 st.ctxt, st.eflags, &used, freePtr); 3112 st.ctxt, st.eflags, &used, freePtr);
3118 if (st.nstr == var_Error 3113 if (st.nstr == var_Error
3119 || (st.nstr == varNoError && (st.eflags & VARE_UNDEFERR) == 0) 3114 || (st.nstr == varNoError && (st.eflags & VARE_UNDEFERR) == 0)
3120 || strlen(rval) != (size_t) used) { 3115 || strlen(rval) != (size_t) used) {
3121 free(freeIt); 3116 free(freeIt);
3122 goto out; /* error already reported */ 3117 goto out; /* error already reported */
3123 } 3118 }
3124 } 3119 }
3125 free(freeIt); 3120 free(freeIt);
3126 if (*p == ':') 3121 if (*p == ':')
3127 p++; 3122 p++;
3128 else if (*p == '\0' && endc != '\0') { 3123 else if (*p == '\0' && endc != '\0') {
3129 Error("Unclosed variable specification after complex " 3124 Error("Unclosed variable specification after complex "
3130 "modifier (expecting '%c') for %s", st.endc, st.v->name); 3125 "modifier (expecting '%c') for %s", st.endc, st.v->name);
3131 goto out; 3126 goto out;
3132 } 3127 }
3133 continue; 3128 continue;
3134 } 3129 }
3135 apply_mods: 3130 apply_mods:
3136 if (DEBUG(VAR)) { 3131 if (DEBUG(VAR)) {
3137 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", st.v->name, 3132 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", st.v->name,
3138 *p, st.nstr); 3133 *p, st.nstr);
3139 } 3134 }
3140 st.newStr = var_Error; 3135 st.newStr = var_Error;
3141 char modifier = *p; 3136 char modifier = *p;
3142 switch (modifier) { 3137 switch (modifier) {
3143 case ':': 3138 case ':':
3144 { 3139 {
3145 int res = ApplyModifier_Assign(p, &st); 3140 int res = ApplyModifier_Assign(p, &st);
3146 if (res == 'b') 3141 if (res == 'b')
3147 goto bad_modifier; 3142 goto bad_modifier;
3148 if (res == 'c') 3143 if (res == 'c')
3149 goto cleanup; 3144 goto cleanup;
3150 if (res == 'd') 3145 if (res == 'd')
3151 goto default_case; 3146 goto default_case;
3152 break; 3147 break;
3153 } 3148 }
3154 case '@': 3149 case '@':
3155 if (!ApplyModifier_Loop(p, &st)) 3150 if (!ApplyModifier_Loop(p, &st))
3156 goto cleanup; 3151 goto cleanup;
3157 break; 3152 break;
3158 case '_': 3153 case '_':
3159 if (!ApplyModifier_Remember(p, &st)) 3154 if (!ApplyModifier_Remember(p, &st))
3160 goto default_case; 3155 goto default_case;
3161 break; 3156 break;
3162 case 'D': 3157 case 'D':
3163 case 'U': 3158 case 'U':
3164 ApplyModifier_Defined(p, &st); 3159 ApplyModifier_Defined(p, &st);
3165 break; 3160 break;
3166 case 'L': 3161 case 'L':
3167 { 3162 {
3168 if (st.v->flags & VAR_JUNK) 3163 if (st.v->flags & VAR_JUNK)
3169 st.v->flags |= VAR_KEEP; 3164 st.v->flags |= VAR_KEEP;
3170 st.newStr = bmake_strdup(st.v->name); 3165 st.newStr = bmake_strdup(st.v->name);
3171 st.cp = p + 1; 3166 st.cp = p + 1;
3172 st.termc = *st.cp; 3167 st.termc = *st.cp;
3173 break; 3168 break;
3174 } 3169 }
3175 case 'P': 3170 case 'P':
3176 ApplyModifier_Path(p, &st); 3171 ApplyModifier_Path(p, &st);
3177 break; 3172 break;
3178 case '!': 3173 case '!':
3179 if (!ApplyModifier_Exclam(p, &st)) 3174 if (!ApplyModifier_Exclam(p, &st))
3180 goto cleanup; 3175 goto cleanup;
3181 break; 3176 break;
3182 case '[': 3177 case '[':
3183 { 3178 {
3184 int res = ApplyModifier_Words(p, &st); 3179 int res = ApplyModifier_Words(p, &st);
3185 if (res == 'b') 3180 if (res == 'b')
3186 goto bad_modifier; 3181 goto bad_modifier;
3187 if (res == 'c') 3182 if (res == 'c')
3188 goto cleanup; 3183 goto cleanup;
3189 break; 3184 break;
3190 } 3185 }
3191 case 'g': 3186 case 'g':
3192 if (!ApplyModifier_Gmtime(p, &st)) 3187 if (!ApplyModifier_Gmtime(p, &st))
3193 goto default_case; 3188 goto default_case;
3194 break; 3189 break;
3195 case 'h': 3190 case 'h':
3196 if (!ApplyModifier_Hash(p, &st)) 3191 if (!ApplyModifier_Hash(p, &st))
3197 goto default_case; 3192 goto default_case;
3198 break; 3193 break;
3199 case 'l': 3194 case 'l':
3200 if (!ApplyModifier_Localtime(p, &st)) 3195 if (!ApplyModifier_Localtime(p, &st))
3201 goto default_case; 3196 goto default_case;
3202 break; 3197 break;
3203 case 't': 3198 case 't':
3204 if (!ApplyModifier_To(p, &st)) 3199 if (!ApplyModifier_To(p, &st))
3205 goto bad_modifier; 3200 goto bad_modifier;
3206 break; 3201 break;
3207 case 'N': 3202 case 'N':
3208 case 'M': 3203 case 'M':
3209 ApplyModifier_Match(p, &st); 3204 ApplyModifier_Match(p, &st);
3210 break; 3205 break;
3211 case 'S': 3206 case 'S':
3212 if (!ApplyModifier_Subst(p, &st)) 3207 if (!ApplyModifier_Subst(p, &st))
3213 goto cleanup; 3208 goto cleanup;
3214 break; 3209 break;
3215 case '?': 3210 case '?':
3216 if (!ApplyModifier_IfElse(p, &st)) 3211 if (!ApplyModifier_IfElse(p, &st))
3217 goto cleanup; 3212 goto cleanup;
3218 break; 3213 break;
3219#ifndef NO_REGEX 3214#ifndef NO_REGEX
3220 case 'C': 3215 case 'C':
3221 if (!ApplyModifier_Regex(p, &st)) 3216 if (!ApplyModifier_Regex(p, &st))
3222 goto cleanup; 3217 goto cleanup;
3223 break; 3218 break;
3224#endif 3219#endif
3225 case 'q': 3220 case 'q':
3226 case 'Q': 3221 case 'Q':
3227 if (p[1] == st.endc || p[1] == ':') { 3222 if (p[1] == st.endc || p[1] == ':') {
3228 st.newStr = VarQuote(st.nstr, modifier == 'q'); 3223 st.newStr = VarQuote(st.nstr, modifier == 'q');
3229 st.cp = p + 1; 3224 st.cp = p + 1;
3230 st.termc = *st.cp; 3225 st.termc = *st.cp;
3231 break; 3226 break;
3232 } 3227 }
3233 goto default_case; 3228 goto default_case;
3234 case 'T': 3229 case 'T':
3235 if (p[1] == st.endc || p[1] == ':') { 3230 if (p[1] == st.endc || p[1] == ':') {
3236 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord, 3231 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3237 st.nstr, ModifyWord_Tail, NULL); 3232 st.nstr, ModifyWord_Tail, NULL);
3238 st.cp = p + 1; 3233 st.cp = p + 1;
3239 st.termc = *st.cp; 3234 st.termc = *st.cp;
3240 break; 3235 break;
3241 } 3236 }
3242 goto default_case; 3237 goto default_case;
3243 case 'H': 3238 case 'H':
3244 if (p[1] == st.endc || p[1] == ':') { 3239 if (p[1] == st.endc || p[1] == ':') {
3245 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord, 3240 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3246 st.nstr, ModifyWord_Head, NULL); 3241 st.nstr, ModifyWord_Head, NULL);
3247 st.cp = p + 1; 3242 st.cp = p + 1;
3248 st.termc = *st.cp; 3243 st.termc = *st.cp;
3249 break; 3244 break;
3250 } 3245 }
3251 goto default_case; 3246 goto default_case;
3252 case 'E': 3247 case 'E':
3253 if (p[1] == st.endc || p[1] == ':') { 3248 if (p[1] == st.endc || p[1] == ':') {
3254 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord, 3249 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3255 st.nstr, ModifyWord_Suffix, NULL); 3250 st.nstr, ModifyWord_Suffix, NULL);
3256 st.cp = p + 1; 3251 st.cp = p + 1;
3257 st.termc = *st.cp; 3252 st.termc = *st.cp;
3258 break; 3253 break;
3259 } 3254 }
3260 goto default_case; 3255 goto default_case;
3261 case 'R': 3256 case 'R':
3262 if (p[1] == st.endc || p[1] == ':') { 3257 if (p[1] == st.endc || p[1] == ':') {
3263 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord, 3258 st.newStr = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3264 st.nstr, ModifyWord_Root, NULL); 3259 st.nstr, ModifyWord_Root, NULL);
3265 st.cp = p + 1; 3260 st.cp = p + 1;
3266 st.termc = *st.cp; 3261 st.termc = *st.cp;
3267 break; 3262 break;
3268 } 3263 }
3269 goto default_case; 3264 goto default_case;
3270 case 'r': 3265 case 'r':
3271 if (!ApplyModifier_Range(p, &st)) 3266 if (!ApplyModifier_Range(p, &st))
3272 goto default_case; 3267 goto default_case;
3273 break; 3268 break;
3274 case 'O': 3269 case 'O':
3275 if (!ApplyModifier_Order(p, &st)) 3270 if (!ApplyModifier_Order(p, &st))
3276 goto bad_modifier; 3271 goto bad_modifier;
3277 break; 3272 break;
3278 case 'u': 3273 case 'u':
3279 if (p[1] == st.endc || p[1] == ':') { 3274 if (p[1] == st.endc || p[1] == ':') {
3280 st.newStr = VarUniq(st.nstr); 3275 st.newStr = VarUniq(st.nstr);
3281 st.cp = p + 1; 3276 st.cp = p + 1;
3282 st.termc = *st.cp; 3277 st.termc = *st.cp;
3283 break; 3278 break;
3284 } 3279 }
3285 goto default_case; 3280 goto default_case;
3286#ifdef SUNSHCMD 3281#ifdef SUNSHCMD
3287 case 's': 3282 case 's':
3288 if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) { 3283 if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
3289 const char *emsg; 3284 const char *emsg;
3290 if (st.eflags & VARE_WANTRES) { 3285 if (st.eflags & VARE_WANTRES) {
3291 st.newStr = Cmd_Exec(st.nstr, &emsg); 3286 st.newStr = Cmd_Exec(st.nstr, &emsg);
3292 if (emsg) 3287 if (emsg)
3293 Error(emsg, st.nstr); 3288 Error(emsg, st.nstr);
3294 } else 3289 } else
3295 st.newStr = varNoError; 3290 st.newStr = varNoError;
3296 st.cp = p + 2; 3291 st.cp = p + 2;
3297 st.termc = *st.cp; 3292 st.termc = *st.cp;
3298 break; 3293 break;
3299 } 3294 }
3300 goto default_case; 3295 goto default_case;
3301#endif 3296#endif
3302 default: 3297 default:
3303 default_case: 3298 default_case:
3304 { 3299 {
3305#ifdef SYSVVARSUB 3300#ifdef SYSVVARSUB
3306 int res = ApplyModifier_SysV(p, &st); 3301 int res = ApplyModifier_SysV(p, &st);
3307 if (res == 'c') 3302 if (res == 'c')
3308 goto cleanup; 3303 goto cleanup;
3309 if (res != '=') 3304 if (res != '=')
3310#endif 3305#endif
3311 { 3306 {
3312 Error("Unknown modifier '%c'", *p); 3307 Error("Unknown modifier '%c'", *p);
3313 for (st.cp = p + 1; 3308 for (st.cp = p + 1;
3314 *st.cp != ':' && *st.cp != st.endc && *st.cp != '\0'; 3309 *st.cp != ':' && *st.cp != st.endc && *st.cp != '\0';
3315 st.cp++) 3310 st.cp++)
3316 continue; 3311 continue;
3317 st.termc = *st.cp; 3312 st.termc = *st.cp;
3318 st.newStr = var_Error; 3313 st.newStr = var_Error;
3319 } 3314 }
3320 } 3315 }
3321 } 3316 }
3322 if (DEBUG(VAR)) { 3317 if (DEBUG(VAR)) {
3323 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n", 3318 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3324 st.v->name, modifier, st.newStr); 3319 st.v->name, modifier, st.newStr);
3325 } 3320 }
3326 3321
3327 if (st.newStr != st.nstr) { 3322 if (st.newStr != st.nstr) {
3328 if (*freePtr) { 3323 if (*freePtr) {
3329 free(st.nstr); 3324 free(st.nstr);
3330 *freePtr = NULL; 3325 *freePtr = NULL;
3331 } 3326 }
3332 st.nstr = st.newStr; 3327 st.nstr = st.newStr;
3333 if (st.nstr != var_Error && st.nstr != varNoError) { 3328 if (st.nstr != var_Error && st.nstr != varNoError) {
3334 *freePtr = st.nstr; 3329 *freePtr = st.nstr;
3335 } 3330 }
3336 } 3331 }
3337 if (st.termc == '\0' && st.endc != '\0') { 3332 if (st.termc == '\0' && st.endc != '\0') {
3338 Error("Unclosed variable specification (expecting '%c') " 3333 Error("Unclosed variable specification (expecting '%c') "
3339 "for \"%s\" (value \"%s\") modifier %c", 3334 "for \"%s\" (value \"%s\") modifier %c",
3340 st.endc, st.v->name, st.nstr, modifier); 3335 st.endc, st.v->name, st.nstr, modifier);
3341 } else if (st.termc == ':') { 3336 } else if (st.termc == ':') {
3342 st.cp++; 3337 st.cp++;
3343 } 3338 }
3344 p = st.cp; 3339 p = st.cp;
3345 } 3340 }
3346out: 3341out:
3347 *lengthPtr = p - tstr; 3342 *lengthPtr = p - tstr;
3348 return st.nstr; 3343 return st.nstr;
3349 3344
3350bad_modifier: 3345bad_modifier:
3351 Error("Bad modifier `:%.*s' for %s", 3346 Error("Bad modifier `:%.*s' for %s",
3352 (int)strcspn(p, ":)}"), p, st.v->name); 3347 (int)strcspn(p, ":)}"), p, st.v->name);
3353 3348
3354cleanup: 3349cleanup:
3355 *lengthPtr = st.cp - tstr; 3350 *lengthPtr = st.cp - tstr;
3356 if (st.missing_delim != '\0') 3351 if (st.missing_delim != '\0')
3357 Error("Unclosed substitution for %s (%c missing)", 3352 Error("Unclosed substitution for %s (%c missing)",
3358 st.v->name, st.missing_delim); 3353 st.v->name, st.missing_delim);
3359 free(*freePtr); 3354 free(*freePtr);
3360 *freePtr = NULL; 3355 *freePtr = NULL;
3361 return var_Error; 3356 return var_Error;
3362} 3357}
3363 3358
3364static Boolean 3359static Boolean
3365VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen) 3360VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)