Tue Mar 30 14:58:17 2021 UTC ()
make: remove workaround for bug in lint

The bug has been fixed in lint.

No functional change.


(rillig)
diff -r1.893 -r1.894 src/usr.bin/make/var.c

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

--- src/usr.bin/make/var.c 2021/03/21 23:03:33 1.893
+++ src/usr.bin/make/var.c 2021/03/30 14:58:17 1.894
@@ -1,1142 +1,1142 @@ @@ -1,1142 +1,1142 @@
1/* $NetBSD: var.c,v 1.893 2021/03/21 23:03:33 rillig Exp $ */ 1/* $NetBSD: var.c,v 1.894 2021/03/30 14:58:17 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/* 71/*
72 * Handling of variables and the expressions formed from them. 72 * Handling of variables and the expressions formed from them.
73 * 73 *
74 * Variables are set using lines of the form VAR=value. Both the variable 74 * Variables are set using lines of the form VAR=value. Both the variable
75 * name and the value can contain references to other variables, by using 75 * name and the value can contain references to other variables, by using
76 * expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}. 76 * expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
77 * 77 *
78 * Interface: 78 * Interface:
79 * Var_Init Initialize this module. 79 * Var_Init Initialize this module.
80 * 80 *
81 * Var_End Clean up the module. 81 * Var_End Clean up the module.
82 * 82 *
83 * Var_Set 83 * Var_Set
84 * Var_SetExpand 84 * Var_SetExpand
85 * Set the value of the variable, creating it if 85 * Set the value of the variable, creating it if
86 * necessary. 86 * necessary.
87 * 87 *
88 * Var_Append 88 * Var_Append
89 * Var_AppendExpand 89 * Var_AppendExpand
90 * Append more characters to the variable, creating it if 90 * Append more characters to the variable, creating it if
91 * necessary. A space is placed between the old value and 91 * necessary. A space is placed between the old value and
92 * the new one. 92 * the new one.
93 * 93 *
94 * Var_Exists 94 * Var_Exists
95 * Var_ExistsExpand 95 * Var_ExistsExpand
96 * See if a variable exists. 96 * See if a variable exists.
97 * 97 *
98 * Var_Value Return the unexpanded value of a variable, or NULL if 98 * Var_Value Return the unexpanded value of a variable, or NULL if
99 * the variable is undefined. 99 * the variable is undefined.
100 * 100 *
101 * Var_Subst Substitute all variable expressions in a string. 101 * Var_Subst Substitute all variable expressions in a string.
102 * 102 *
103 * Var_Parse Parse a variable expression such as ${VAR:Mpattern}. 103 * Var_Parse Parse a variable expression such as ${VAR:Mpattern}.
104 * 104 *
105 * Var_Delete 105 * Var_Delete
106 * Var_DeleteExpand 106 * Var_DeleteExpand
107 * Delete a variable. 107 * Delete a variable.
108 * 108 *
109 * Var_ReexportVars 109 * Var_ReexportVars
110 * Export some or even all variables to the environment 110 * Export some or even all variables to the environment
111 * of this process and its child processes. 111 * of this process and its child processes.
112 * 112 *
113 * Var_Export Export the variable to the environment of this process 113 * Var_Export Export the variable to the environment of this process
114 * and its child processes. 114 * and its child processes.
115 * 115 *
116 * Var_UnExport Don't export the variable anymore. 116 * Var_UnExport Don't export the variable anymore.
117 * 117 *
118 * Debugging: 118 * Debugging:
119 * Var_Stats Print out hashing statistics if in -dh mode. 119 * Var_Stats Print out hashing statistics if in -dh mode.
120 * 120 *
121 * Var_Dump Print out all variables defined in the given scope. 121 * Var_Dump Print out all variables defined in the given scope.
122 * 122 *
123 * XXX: There's a lot of almost duplicate code in these functions that only 123 * XXX: There's a lot of almost duplicate code in these functions that only
124 * differs in subtle details that are not mentioned in the manual page. 124 * differs in subtle details that are not mentioned in the manual page.
125 */ 125 */
126 126
127#include <sys/stat.h> 127#include <sys/stat.h>
128#ifndef NO_REGEX 128#ifndef NO_REGEX
129#include <sys/types.h> 129#include <sys/types.h>
130#include <regex.h> 130#include <regex.h>
131#endif 131#endif
132#include <errno.h> 132#include <errno.h>
133#include <inttypes.h> 133#include <inttypes.h>
134#include <limits.h> 134#include <limits.h>
135#include <time.h> 135#include <time.h>
136 136
137#include "make.h" 137#include "make.h"
138#include "dir.h" 138#include "dir.h"
139#include "job.h" 139#include "job.h"
140#include "metachar.h" 140#include "metachar.h"
141 141
142/* "@(#)var.c 8.3 (Berkeley) 3/19/94" */ 142/* "@(#)var.c 8.3 (Berkeley) 3/19/94" */
143MAKE_RCSID("$NetBSD: var.c,v 1.893 2021/03/21 23:03:33 rillig Exp $"); 143MAKE_RCSID("$NetBSD: var.c,v 1.894 2021/03/30 14:58:17 rillig Exp $");
144 144
145typedef enum VarFlags { 145typedef enum VarFlags {
146 VFL_NONE = 0, 146 VFL_NONE = 0,
147 147
148 /* 148 /*
149 * The variable's value is currently being used by Var_Parse or 149 * The variable's value is currently being used by Var_Parse or
150 * Var_Subst. This marker is used to avoid endless recursion. 150 * Var_Subst. This marker is used to avoid endless recursion.
151 */ 151 */
152 VFL_IN_USE = 1 << 0, 152 VFL_IN_USE = 1 << 0,
153 153
154 /* 154 /*
155 * The variable comes from the environment. 155 * The variable comes from the environment.
156 * These variables are not registered in any GNode, therefore they 156 * These variables are not registered in any GNode, therefore they
157 * must be freed as soon as they are not used anymore. 157 * must be freed as soon as they are not used anymore.
158 */ 158 */
159 VFL_FROM_ENV = 1 << 1, 159 VFL_FROM_ENV = 1 << 1,
160 160
161 /* 161 /*
162 * The variable is exported to the environment, to be used by child 162 * The variable is exported to the environment, to be used by child
163 * processes. 163 * processes.
164 */ 164 */
165 VFL_EXPORTED = 1 << 2, 165 VFL_EXPORTED = 1 << 2,
166 166
167 /* 167 /*
168 * At the point where this variable was exported, it contained an 168 * At the point where this variable was exported, it contained an
169 * unresolved reference to another variable. Before any child 169 * unresolved reference to another variable. Before any child
170 * process is started, it needs to be exported again, in the hope 170 * process is started, it needs to be exported again, in the hope
171 * that the referenced variable can then be resolved. 171 * that the referenced variable can then be resolved.
172 */ 172 */
173 VFL_REEXPORT = 1 << 3, 173 VFL_REEXPORT = 1 << 3,
174 174
175 /* The variable came from the command line. */ 175 /* The variable came from the command line. */
176 VFL_FROM_CMD = 1 << 4, 176 VFL_FROM_CMD = 1 << 4,
177 177
178 /* 178 /*
179 * The variable value cannot be changed anymore, and the variable 179 * The variable value cannot be changed anymore, and the variable
180 * cannot be deleted. Any attempts to do so are silently ignored, 180 * cannot be deleted. Any attempts to do so are silently ignored,
181 * they are logged with -dv though. 181 * they are logged with -dv though.
182 * 182 *
183 * See VAR_SET_READONLY. 183 * See VAR_SET_READONLY.
184 */ 184 */
185 VFL_READONLY = 1 << 5 185 VFL_READONLY = 1 << 5
186} VarFlags; 186} VarFlags;
187 187
188/* 188/*
189 * Variables are defined using one of the VAR=value assignments. Their 189 * Variables are defined using one of the VAR=value assignments. Their
190 * value can be queried by expressions such as $V, ${VAR}, or with modifiers 190 * value can be queried by expressions such as $V, ${VAR}, or with modifiers
191 * such as ${VAR:S,from,to,g:Q}. 191 * such as ${VAR:S,from,to,g:Q}.
192 * 192 *
193 * There are 3 kinds of variables: scope variables, environment variables, 193 * There are 3 kinds of variables: scope variables, environment variables,
194 * undefined variables. 194 * undefined variables.
195 * 195 *
196 * Scope variables are stored in a GNode.scope. The only way to undefine 196 * Scope variables are stored in a GNode.scope. The only way to undefine
197 * a scope variable is using the .undef directive. In particular, it must 197 * a scope variable is using the .undef directive. In particular, it must
198 * not be possible to undefine a variable during the evaluation of an 198 * not be possible to undefine a variable during the evaluation of an
199 * expression, or Var.name might point nowhere. 199 * expression, or Var.name might point nowhere.
200 * 200 *
201 * Environment variables are temporary. They are returned by VarFind, and 201 * Environment variables are temporary. They are returned by VarFind, and
202 * after using them, they must be freed using VarFreeEnv. 202 * after using them, they must be freed using VarFreeEnv.
203 * 203 *
204 * Undefined variables occur during evaluation of variable expressions such 204 * Undefined variables occur during evaluation of variable expressions such
205 * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers. 205 * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
206 */ 206 */
207typedef struct Var { 207typedef struct Var {
208 /* 208 /*
209 * The name of the variable, once set, doesn't change anymore. 209 * The name of the variable, once set, doesn't change anymore.
210 * For scope variables, it aliases the corresponding HashEntry name. 210 * For scope variables, it aliases the corresponding HashEntry name.
211 * For environment and undefined variables, it is allocated. 211 * For environment and undefined variables, it is allocated.
212 */ 212 */
213 FStr name; 213 FStr name;
214 214
215 /* The unexpanded value of the variable. */ 215 /* The unexpanded value of the variable. */
216 Buffer val; 216 Buffer val;
217 /* Miscellaneous status flags. */ 217 /* Miscellaneous status flags. */
218 VarFlags flags; 218 VarFlags flags;
219} Var; 219} Var;
220 220
221/* 221/*
222 * Exporting variables is expensive and may leak memory, so skip it if we 222 * Exporting variables is expensive and may leak memory, so skip it if we
223 * can. 223 * can.
224 * 224 *
225 * To avoid this, it might be worth encapsulating the environment variables 225 * To avoid this, it might be worth encapsulating the environment variables
226 * in a separate data structure called EnvVars. 226 * in a separate data structure called EnvVars.
227 */ 227 */
228typedef enum VarExportedMode { 228typedef enum VarExportedMode {
229 VAR_EXPORTED_NONE, 229 VAR_EXPORTED_NONE,
230 VAR_EXPORTED_SOME, 230 VAR_EXPORTED_SOME,
231 VAR_EXPORTED_ALL 231 VAR_EXPORTED_ALL
232} VarExportedMode; 232} VarExportedMode;
233 233
234typedef enum UnexportWhat { 234typedef enum UnexportWhat {
235 /* Unexport the variables given by name. */ 235 /* Unexport the variables given by name. */
236 UNEXPORT_NAMED, 236 UNEXPORT_NAMED,
237 /* 237 /*
238 * Unexport all globals previously exported, but keep the environment 238 * Unexport all globals previously exported, but keep the environment
239 * inherited from the parent. 239 * inherited from the parent.
240 */ 240 */
241 UNEXPORT_ALL, 241 UNEXPORT_ALL,
242 /* 242 /*
243 * Unexport all globals previously exported and clear the environment 243 * Unexport all globals previously exported and clear the environment
244 * inherited from the parent. 244 * inherited from the parent.
245 */ 245 */
246 UNEXPORT_ENV 246 UNEXPORT_ENV
247} UnexportWhat; 247} UnexportWhat;
248 248
249/* Flags for pattern matching in the :S and :C modifiers */ 249/* Flags for pattern matching in the :S and :C modifiers */
250typedef struct VarPatternFlags { 250typedef struct VarPatternFlags {
251 251
252 /* Replace as often as possible ('g') */ 252 /* Replace as often as possible ('g') */
253 Boolean subGlobal: 1; 253 Boolean subGlobal: 1;
254 /* Replace only once ('1') */ 254 /* Replace only once ('1') */
255 Boolean subOnce: 1; 255 Boolean subOnce: 1;
256 /* Match at start of word ('^') */ 256 /* Match at start of word ('^') */
257 Boolean anchorStart: 1; 257 Boolean anchorStart: 1;
258 /* Match at end of word ('$') */ 258 /* Match at end of word ('$') */
259 Boolean anchorEnd: 1; 259 Boolean anchorEnd: 1;
260} VarPatternFlags; 260} VarPatternFlags;
261 261
262/* SepBuf builds a string from words interleaved with separators. */ 262/* SepBuf builds a string from words interleaved with separators. */
263typedef struct SepBuf { 263typedef struct SepBuf {
264 Buffer buf; 264 Buffer buf;
265 Boolean needSep; 265 Boolean needSep;
266 /* Usually ' ', but see the ':ts' modifier. */ 266 /* Usually ' ', but see the ':ts' modifier. */
267 char sep; 267 char sep;
268} SepBuf; 268} SepBuf;
269 269
270static const char * 270static const char *
271VarEvalFlags_ToString(VarEvalFlags eflags) 271VarEvalFlags_ToString(VarEvalFlags eflags)
272{ 272{
273 if (!eflags.wantRes) { 273 if (!eflags.wantRes) {
274 assert(!eflags.undefErr); 274 assert(!eflags.undefErr);
275 assert(!eflags.keepDollar && !eflags.keepUndef); 275 assert(!eflags.keepDollar && !eflags.keepUndef);
276 return "parse-only"; 276 return "parse-only";
277 } 277 }
278 if (eflags.undefErr) { 278 if (eflags.undefErr) {
279 assert(!eflags.keepDollar && !eflags.keepUndef); 279 assert(!eflags.keepDollar && !eflags.keepUndef);
280 return "eval-defined"; 280 return "eval-defined";
281 } 281 }
282 if (eflags.keepDollar && eflags.keepUndef) 282 if (eflags.keepDollar && eflags.keepUndef)
283 return "eval-keep-dollar-and-undefined"; 283 return "eval-keep-dollar-and-undefined";
284 if (eflags.keepDollar) 284 if (eflags.keepDollar)
285 return "eval-keep-dollar"; 285 return "eval-keep-dollar";
286 if (eflags.keepUndef) 286 if (eflags.keepUndef)
287 return "eval-keep-undefined"; 287 return "eval-keep-undefined";
288 return "eval"; 288 return "eval";
289} 289}
290 290
291/* 291/*
292 * This lets us tell if we have replaced the original environ 292 * This lets us tell if we have replaced the original environ
293 * (which we cannot free). 293 * (which we cannot free).
294 */ 294 */
295char **savedEnv = NULL; 295char **savedEnv = NULL;
296 296
297/* 297/*
298 * Special return value for Var_Parse, indicating a parse error. It may be 298 * Special return value for Var_Parse, indicating a parse error. It may be
299 * caused by an undefined variable, a syntax error in a modifier or 299 * caused by an undefined variable, a syntax error in a modifier or
300 * something entirely different. 300 * something entirely different.
301 */ 301 */
302char var_Error[] = ""; 302char var_Error[] = "";
303 303
304/* 304/*
305 * Special return value for Var_Parse, indicating an undefined variable in 305 * Special return value for Var_Parse, indicating an undefined variable in
306 * a case where VarEvalFlags.undefErr is not set. This undefined variable is 306 * a case where VarEvalFlags.undefErr is not set. This undefined variable is
307 * typically a dynamic variable such as ${.TARGET}, whose expansion needs to 307 * typically a dynamic variable such as ${.TARGET}, whose expansion needs to
308 * be deferred until it is defined in an actual target. 308 * be deferred until it is defined in an actual target.
309 * 309 *
310 * See VarEvalFlags.keepUndef. 310 * See VarEvalFlags.keepUndef.
311 */ 311 */
312static char varUndefined[] = ""; 312static char varUndefined[] = "";
313 313
314/* 314/*
315 * Traditionally this make consumed $$ during := like any other expansion. 315 * Traditionally this make consumed $$ during := like any other expansion.
316 * Other make's do not, and this make follows straight since 2016-01-09. 316 * Other make's do not, and this make follows straight since 2016-01-09.
317 * 317 *
318 * This knob allows controlling the behavior. 318 * This knob allows controlling the behavior.
319 * FALSE to consume $$ during := assignment. 319 * FALSE to consume $$ during := assignment.
320 * TRUE to preserve $$ during := assignment. 320 * TRUE to preserve $$ during := assignment.
321 */ 321 */
322#define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS" 322#define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
323static Boolean save_dollars = TRUE; 323static Boolean save_dollars = TRUE;
324 324
325/* 325/*
326 * A scope collects variable names and their values. 326 * A scope collects variable names and their values.
327 * 327 *
328 * The main scope is SCOPE_GLOBAL, which contains the variables that are set 328 * The main scope is SCOPE_GLOBAL, which contains the variables that are set
329 * in the makefiles. SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and 329 * in the makefiles. SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
330 * contains some internal make variables. These internal variables can thus 330 * contains some internal make variables. These internal variables can thus
331 * be overridden, they can also be restored by undefining the overriding 331 * be overridden, they can also be restored by undefining the overriding
332 * variable. 332 * variable.
333 * 333 *
334 * SCOPE_CMDLINE contains variables from the command line arguments. These 334 * SCOPE_CMDLINE contains variables from the command line arguments. These
335 * override variables from SCOPE_GLOBAL. 335 * override variables from SCOPE_GLOBAL.
336 * 336 *
337 * There is no scope for environment variables, these are generated on-the-fly 337 * There is no scope for environment variables, these are generated on-the-fly
338 * whenever they are referenced. If there were such a scope, each change to 338 * whenever they are referenced. If there were such a scope, each change to
339 * environment variables would have to be reflected in that scope, which may 339 * environment variables would have to be reflected in that scope, which may
340 * be simpler or more complex than the current implementation. 340 * be simpler or more complex than the current implementation.
341 * 341 *
342 * Each target has its own scope, containing the 7 target-local variables 342 * Each target has its own scope, containing the 7 target-local variables
343 * .TARGET, .ALLSRC, etc. No other variables are in these scopes. 343 * .TARGET, .ALLSRC, etc. No other variables are in these scopes.
344 */ 344 */
345 345
346GNode *SCOPE_CMDLINE; 346GNode *SCOPE_CMDLINE;
347GNode *SCOPE_GLOBAL; 347GNode *SCOPE_GLOBAL;
348GNode *SCOPE_INTERNAL; 348GNode *SCOPE_INTERNAL;
349 349
350ENUM_FLAGS_RTTI_6(VarFlags, 350ENUM_FLAGS_RTTI_6(VarFlags,
351 VFL_IN_USE, VFL_FROM_ENV, 351 VFL_IN_USE, VFL_FROM_ENV,
352 VFL_EXPORTED, VFL_REEXPORT, VFL_FROM_CMD, VFL_READONLY); 352 VFL_EXPORTED, VFL_REEXPORT, VFL_FROM_CMD, VFL_READONLY);
353 353
354static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE; 354static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
355 355
356 356
357static Var * 357static Var *
358VarNew(FStr name, const char *value, VarFlags flags) 358VarNew(FStr name, const char *value, VarFlags flags)
359{ 359{
360 size_t value_len = strlen(value); 360 size_t value_len = strlen(value);
361 Var *var = bmake_malloc(sizeof *var); 361 Var *var = bmake_malloc(sizeof *var);
362 var->name = name; 362 var->name = name;
363 Buf_InitSize(&var->val, value_len + 1); 363 Buf_InitSize(&var->val, value_len + 1);
364 Buf_AddBytes(&var->val, value, value_len); 364 Buf_AddBytes(&var->val, value, value_len);
365 var->flags = flags; 365 var->flags = flags;
366 return var; 366 return var;
367} 367}
368 368
369static const char * 369static const char *
370CanonicalVarname(const char *name) 370CanonicalVarname(const char *name)
371{ 371{
372 if (*name == '.' && ch_isupper(name[1])) { 372 if (*name == '.' && ch_isupper(name[1])) {
373 switch (name[1]) { 373 switch (name[1]) {
374 case 'A': 374 case 'A':
375 if (strcmp(name, ".ALLSRC") == 0) 375 if (strcmp(name, ".ALLSRC") == 0)
376 name = ALLSRC; 376 name = ALLSRC;
377 if (strcmp(name, ".ARCHIVE") == 0) 377 if (strcmp(name, ".ARCHIVE") == 0)
378 name = ARCHIVE; 378 name = ARCHIVE;
379 break; 379 break;
380 case 'I': 380 case 'I':
381 if (strcmp(name, ".IMPSRC") == 0) 381 if (strcmp(name, ".IMPSRC") == 0)
382 name = IMPSRC; 382 name = IMPSRC;
383 break; 383 break;
384 case 'M': 384 case 'M':
385 if (strcmp(name, ".MEMBER") == 0) 385 if (strcmp(name, ".MEMBER") == 0)
386 name = MEMBER; 386 name = MEMBER;
387 break; 387 break;
388 case 'O': 388 case 'O':
389 if (strcmp(name, ".OODATE") == 0) 389 if (strcmp(name, ".OODATE") == 0)
390 name = OODATE; 390 name = OODATE;
391 break; 391 break;
392 case 'P': 392 case 'P':
393 if (strcmp(name, ".PREFIX") == 0) 393 if (strcmp(name, ".PREFIX") == 0)
394 name = PREFIX; 394 name = PREFIX;
395 break; 395 break;
396 case 'S': 396 case 'S':
397 if (strcmp(name, ".SHELL") == 0) { 397 if (strcmp(name, ".SHELL") == 0) {
398 if (shellPath == NULL) 398 if (shellPath == NULL)
399 Shell_Init(); 399 Shell_Init();
400 } 400 }
401 break; 401 break;
402 case 'T': 402 case 'T':
403 if (strcmp(name, ".TARGET") == 0) 403 if (strcmp(name, ".TARGET") == 0)
404 name = TARGET; 404 name = TARGET;
405 break; 405 break;
406 } 406 }
407 } 407 }
408 408
409 /* GNU make has an additional alias $^ == ${.ALLSRC}. */ 409 /* GNU make has an additional alias $^ == ${.ALLSRC}. */
410 410
411 return name; 411 return name;
412} 412}
413 413
414static Var * 414static Var *
415GNode_FindVar(GNode *scope, const char *varname, unsigned int hash) 415GNode_FindVar(GNode *scope, const char *varname, unsigned int hash)
416{ 416{
417 return HashTable_FindValueHash(&scope->vars, varname, hash); 417 return HashTable_FindValueHash(&scope->vars, varname, hash);
418} 418}
419 419
420/* 420/*
421 * Find the variable in the scope, and maybe in other scopes as well. 421 * Find the variable in the scope, and maybe in other scopes as well.
422 * 422 *
423 * Input: 423 * Input:
424 * name name to find, is not expanded any further 424 * name name to find, is not expanded any further
425 * scope scope in which to look first 425 * scope scope in which to look first
426 * elsewhere TRUE to look in other scopes as well 426 * elsewhere TRUE to look in other scopes as well
427 * 427 *
428 * Results: 428 * Results:
429 * The found variable, or NULL if the variable does not exist. 429 * The found variable, or NULL if the variable does not exist.
430 * If the variable is an environment variable, it must be freed using 430 * If the variable is an environment variable, it must be freed using
431 * VarFreeEnv after use. 431 * VarFreeEnv after use.
432 */ 432 */
433static Var * 433static Var *
434VarFind(const char *name, GNode *scope, Boolean elsewhere) 434VarFind(const char *name, GNode *scope, Boolean elsewhere)
435{ 435{
436 Var *var; 436 Var *var;
437 unsigned int nameHash; 437 unsigned int nameHash;
438 438
439 /* Replace '.TARGET' with '@', likewise for other local variables. */ 439 /* Replace '.TARGET' with '@', likewise for other local variables. */
440 name = CanonicalVarname(name); 440 name = CanonicalVarname(name);
441 nameHash = Hash_Hash(name); 441 nameHash = Hash_Hash(name);
442 442
443 var = GNode_FindVar(scope, name, nameHash); 443 var = GNode_FindVar(scope, name, nameHash);
444 if (!elsewhere) 444 if (!elsewhere)
445 return var; 445 return var;
446 446
447 if (var == NULL && scope != SCOPE_CMDLINE) 447 if (var == NULL && scope != SCOPE_CMDLINE)
448 var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash); 448 var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
449 449
450 if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) { 450 if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
451 var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash); 451 var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
452 if (var == NULL && scope != SCOPE_INTERNAL) { 452 if (var == NULL && scope != SCOPE_INTERNAL) {
453 /* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */ 453 /* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
454 var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash); 454 var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
455 } 455 }
456 } 456 }
457 457
458 if (var == NULL) { 458 if (var == NULL) {
459 char *env; 459 char *env;
460 460
461 if ((env = getenv(name)) != NULL) { 461 if ((env = getenv(name)) != NULL) {
462 char *varname = bmake_strdup(name); 462 char *varname = bmake_strdup(name);
463 return VarNew(FStr_InitOwn(varname), env, VFL_FROM_ENV); 463 return VarNew(FStr_InitOwn(varname), env, VFL_FROM_ENV);
464 } 464 }
465 465
466 if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) { 466 if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
467 var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash); 467 var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
468 if (var == NULL && scope != SCOPE_INTERNAL) 468 if (var == NULL && scope != SCOPE_INTERNAL)
469 var = GNode_FindVar(SCOPE_INTERNAL, name, 469 var = GNode_FindVar(SCOPE_INTERNAL, name,
470 nameHash); 470 nameHash);
471 return var; 471 return var;
472 } 472 }
473 473
474 return NULL; 474 return NULL;
475 } 475 }
476 476
477 return var; 477 return var;
478} 478}
479 479
480/* If the variable is an environment variable, free it, including its value. */ 480/* If the variable is an environment variable, free it, including its value. */
481static void 481static void
482VarFreeEnv(Var *v) 482VarFreeEnv(Var *v)
483{ 483{
484 if (!(v->flags & VFL_FROM_ENV)) 484 if (!(v->flags & VFL_FROM_ENV))
485 return; 485 return;
486 486
487 FStr_Done(&v->name); 487 FStr_Done(&v->name);
488 Buf_Done(&v->val); 488 Buf_Done(&v->val);
489 free(v); 489 free(v);
490} 490}
491 491
492/* Add a new variable of the given name and value to the given scope. */ 492/* Add a new variable of the given name and value to the given scope. */
493static Var * 493static Var *
494VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags) 494VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
495{ 495{
496 HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL); 496 HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
497 Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value, 497 Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
498 flags & VAR_SET_READONLY ? VFL_READONLY : VFL_NONE); 498 flags & VAR_SET_READONLY ? VFL_READONLY : VFL_NONE);
499 HashEntry_Set(he, v); 499 HashEntry_Set(he, v);
500 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, value); 500 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, value);
501 return v; 501 return v;
502} 502}
503 503
504/* 504/*
505 * Remove a variable from a scope, freeing all related memory as well. 505 * Remove a variable from a scope, freeing all related memory as well.
506 * The variable name is kept as-is, it is not expanded. 506 * The variable name is kept as-is, it is not expanded.
507 */ 507 */
508void 508void
509Var_Delete(GNode *scope, const char *varname) 509Var_Delete(GNode *scope, const char *varname)
510{ 510{
511 HashEntry *he = HashTable_FindEntry(&scope->vars, varname); 511 HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
512 Var *v; 512 Var *v;
513 513
514 if (he == NULL) { 514 if (he == NULL) {
515 DEBUG2(VAR, "%s:delete %s (not found)\n", scope->name, varname); 515 DEBUG2(VAR, "%s:delete %s (not found)\n", scope->name, varname);
516 return; 516 return;
517 } 517 }
518 518
519 DEBUG2(VAR, "%s:delete %s\n", scope->name, varname); 519 DEBUG2(VAR, "%s:delete %s\n", scope->name, varname);
520 v = he->value; 520 v = he->value;
521 if (v->flags & VFL_EXPORTED) 521 if (v->flags & VFL_EXPORTED)
522 unsetenv(v->name.str); 522 unsetenv(v->name.str);
523 if (strcmp(v->name.str, MAKE_EXPORTED) == 0) 523 if (strcmp(v->name.str, MAKE_EXPORTED) == 0)
524 var_exportedVars = VAR_EXPORTED_NONE; 524 var_exportedVars = VAR_EXPORTED_NONE;
525 assert(v->name.freeIt == NULL); 525 assert(v->name.freeIt == NULL);
526 HashTable_DeleteEntry(&scope->vars, he); 526 HashTable_DeleteEntry(&scope->vars, he);
527 Buf_Done(&v->val); 527 Buf_Done(&v->val);
528 free(v); 528 free(v);
529} 529}
530 530
531/* 531/*
532 * Remove a variable from a scope, freeing all related memory as well. 532 * Remove a variable from a scope, freeing all related memory as well.
533 * The variable name is expanded once. 533 * The variable name is expanded once.
534 */ 534 */
535void 535void
536Var_DeleteExpand(GNode *scope, const char *name) 536Var_DeleteExpand(GNode *scope, const char *name)
537{ 537{
538 FStr varname = FStr_InitRefer(name); 538 FStr varname = FStr_InitRefer(name);
539 539
540 if (strchr(varname.str, '$') != NULL) { 540 if (strchr(varname.str, '$') != NULL) {
541 char *expanded; 541 char *expanded;
542 (void)Var_Subst(varname.str, SCOPE_GLOBAL, VARE_WANTRES, 542 (void)Var_Subst(varname.str, SCOPE_GLOBAL, VARE_WANTRES,
543 &expanded); 543 &expanded);
544 /* TODO: handle errors */ 544 /* TODO: handle errors */
545 varname = FStr_InitOwn(expanded); 545 varname = FStr_InitOwn(expanded);
546 } 546 }
547 547
548 Var_Delete(scope, varname.str); 548 Var_Delete(scope, varname.str);
549 FStr_Done(&varname); 549 FStr_Done(&varname);
550} 550}
551 551
552/* 552/*
553 * Undefine one or more variables from the global scope. 553 * Undefine one or more variables from the global scope.
554 * The argument is expanded exactly once and then split into words. 554 * The argument is expanded exactly once and then split into words.
555 */ 555 */
556void 556void
557Var_Undef(const char *arg) 557Var_Undef(const char *arg)
558{ 558{
559 VarParseResult vpr; 559 VarParseResult vpr;
560 char *expanded; 560 char *expanded;
561 Words varnames; 561 Words varnames;
562 size_t i; 562 size_t i;
563 563
564 if (arg[0] == '\0') { 564 if (arg[0] == '\0') {
565 Parse_Error(PARSE_FATAL, 565 Parse_Error(PARSE_FATAL,
566 "The .undef directive requires an argument"); 566 "The .undef directive requires an argument");
567 return; 567 return;
568 } 568 }
569 569
570 vpr = Var_Subst(arg, SCOPE_GLOBAL, VARE_WANTRES, &expanded); 570 vpr = Var_Subst(arg, SCOPE_GLOBAL, VARE_WANTRES, &expanded);
571 if (vpr != VPR_OK) { 571 if (vpr != VPR_OK) {
572 Parse_Error(PARSE_FATAL, 572 Parse_Error(PARSE_FATAL,
573 "Error in variable names to be undefined"); 573 "Error in variable names to be undefined");
574 return; 574 return;
575 } 575 }
576 576
577 varnames = Str_Words(expanded, FALSE); 577 varnames = Str_Words(expanded, FALSE);
578 if (varnames.len == 1 && varnames.words[0][0] == '\0') 578 if (varnames.len == 1 && varnames.words[0][0] == '\0')
579 varnames.len = 0; 579 varnames.len = 0;
580 580
581 for (i = 0; i < varnames.len; i++) { 581 for (i = 0; i < varnames.len; i++) {
582 const char *varname = varnames.words[i]; 582 const char *varname = varnames.words[i];
583 Global_Delete(varname); 583 Global_Delete(varname);
584 } 584 }
585 585
586 Words_Free(varnames); 586 Words_Free(varnames);
587 free(expanded); 587 free(expanded);
588} 588}
589 589
590static Boolean 590static Boolean
591MayExport(const char *name) 591MayExport(const char *name)
592{ 592{
593 if (name[0] == '.') 593 if (name[0] == '.')
594 return FALSE; /* skip internals */ 594 return FALSE; /* skip internals */
595 if (name[0] == '-') 595 if (name[0] == '-')
596 return FALSE; /* skip misnamed variables */ 596 return FALSE; /* skip misnamed variables */
597 if (name[1] == '\0') { 597 if (name[1] == '\0') {
598 /* 598 /*
599 * A single char. 599 * A single char.
600 * If it is one of the variables that should only appear in 600 * If it is one of the variables that should only appear in
601 * local scope, skip it, else we can get Var_Subst 601 * local scope, skip it, else we can get Var_Subst
602 * into a loop. 602 * into a loop.
603 */ 603 */
604 switch (name[0]) { 604 switch (name[0]) {
605 case '@': 605 case '@':
606 case '%': 606 case '%':
607 case '*': 607 case '*':
608 case '!': 608 case '!':
609 return FALSE; 609 return FALSE;
610 } 610 }
611 } 611 }
612 return TRUE; 612 return TRUE;
613} 613}
614 614
615static Boolean 615static Boolean
616ExportVarEnv(Var *v) 616ExportVarEnv(Var *v)
617{ 617{
618 const char *name = v->name.str; 618 const char *name = v->name.str;
619 char *val = v->val.data; 619 char *val = v->val.data;
620 char *expr; 620 char *expr;
621 621
622 if ((v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT)) 622 if ((v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT))
623 return FALSE; /* nothing to do */ 623 return FALSE; /* nothing to do */
624 624
625 if (strchr(val, '$') == NULL) { 625 if (strchr(val, '$') == NULL) {
626 if (!(v->flags & VFL_EXPORTED)) 626 if (!(v->flags & VFL_EXPORTED))
627 setenv(name, val, 1); 627 setenv(name, val, 1);
628 return TRUE; 628 return TRUE;
629 } 629 }
630 630
631 if (v->flags & VFL_IN_USE) { 631 if (v->flags & VFL_IN_USE) {
632 /* 632 /*
633 * We recursed while exporting in a child. 633 * We recursed while exporting in a child.
634 * This isn't going to end well, just skip it. 634 * This isn't going to end well, just skip it.
635 */ 635 */
636 return FALSE; 636 return FALSE;
637 } 637 }
638 638
639 /* XXX: name is injected without escaping it */ 639 /* XXX: name is injected without escaping it */
640 expr = str_concat3("${", name, "}"); 640 expr = str_concat3("${", name, "}");
641 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &val); 641 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &val);
642 /* TODO: handle errors */ 642 /* TODO: handle errors */
643 setenv(name, val, 1); 643 setenv(name, val, 1);
644 free(val); 644 free(val);
645 free(expr); 645 free(expr);
646 return TRUE; 646 return TRUE;
647} 647}
648 648
649static Boolean 649static Boolean
650ExportVarPlain(Var *v) 650ExportVarPlain(Var *v)
651{ 651{
652 if (strchr(v->val.data, '$') == NULL) { 652 if (strchr(v->val.data, '$') == NULL) {
653 setenv(v->name.str, v->val.data, 1); 653 setenv(v->name.str, v->val.data, 1);
654 v->flags |= VFL_EXPORTED; 654 v->flags |= VFL_EXPORTED;
655 v->flags &= ~(unsigned)VFL_REEXPORT; 655 v->flags &= ~(unsigned)VFL_REEXPORT;
656 return TRUE; 656 return TRUE;
657 } 657 }
658 658
659 /* 659 /*
660 * Flag the variable as something we need to re-export. 660 * Flag the variable as something we need to re-export.
661 * No point actually exporting it now though, 661 * No point actually exporting it now though,
662 * the child process can do it at the last minute. 662 * the child process can do it at the last minute.
663 * Avoid calling setenv more often than necessary since it can leak. 663 * Avoid calling setenv more often than necessary since it can leak.
664 */ 664 */
665 v->flags |= VFL_EXPORTED | VFL_REEXPORT; 665 v->flags |= VFL_EXPORTED | VFL_REEXPORT;
666 return TRUE; 666 return TRUE;
667} 667}
668 668
669static Boolean 669static Boolean
670ExportVarLiteral(Var *v) 670ExportVarLiteral(Var *v)
671{ 671{
672 if ((v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT)) 672 if ((v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT))
673 return FALSE; 673 return FALSE;
674 674
675 if (!(v->flags & VFL_EXPORTED)) 675 if (!(v->flags & VFL_EXPORTED))
676 setenv(v->name.str, v->val.data, 1); 676 setenv(v->name.str, v->val.data, 1);
677 677
678 return TRUE; 678 return TRUE;
679} 679}
680 680
681/* 681/*
682 * Mark a single variable to be exported later for subprocesses. 682 * Mark a single variable to be exported later for subprocesses.
683 * 683 *
684 * Internal variables (those starting with '.') are not exported. 684 * Internal variables (those starting with '.') are not exported.
685 */ 685 */
686static Boolean 686static Boolean
687ExportVar(const char *name, VarExportMode mode) 687ExportVar(const char *name, VarExportMode mode)
688{ 688{
689 Var *v; 689 Var *v;
690 690
691 if (!MayExport(name)) 691 if (!MayExport(name))
692 return FALSE; 692 return FALSE;
693 693
694 v = VarFind(name, SCOPE_GLOBAL, FALSE); 694 v = VarFind(name, SCOPE_GLOBAL, FALSE);
695 if (v == NULL) 695 if (v == NULL)
696 return FALSE; 696 return FALSE;
697 697
698 if (mode == VEM_ENV) 698 if (mode == VEM_ENV)
699 return ExportVarEnv(v); 699 return ExportVarEnv(v);
700 else if (mode == VEM_PLAIN) 700 else if (mode == VEM_PLAIN)
701 return ExportVarPlain(v); 701 return ExportVarPlain(v);
702 else 702 else
703 return ExportVarLiteral(v); 703 return ExportVarLiteral(v);
704} 704}
705 705
706/* 706/*
707 * Actually export the variables that have been marked as needing to be 707 * Actually export the variables that have been marked as needing to be
708 * re-exported. 708 * re-exported.
709 */ 709 */
710void 710void
711Var_ReexportVars(void) 711Var_ReexportVars(void)
712{ 712{
713 char *xvarnames; 713 char *xvarnames;
714 714
715 /* 715 /*
716 * Several make implementations support this sort of mechanism for 716 * Several make implementations support this sort of mechanism for
717 * tracking recursion - but each uses a different name. 717 * tracking recursion - but each uses a different name.
718 * We allow the makefiles to update MAKELEVEL and ensure 718 * We allow the makefiles to update MAKELEVEL and ensure
719 * children see a correctly incremented value. 719 * children see a correctly incremented value.
720 */ 720 */
721 char tmp[21]; 721 char tmp[21];
722 snprintf(tmp, sizeof tmp, "%d", makelevel + 1); 722 snprintf(tmp, sizeof tmp, "%d", makelevel + 1);
723 setenv(MAKE_LEVEL_ENV, tmp, 1); 723 setenv(MAKE_LEVEL_ENV, tmp, 1);
724 724
725 if (var_exportedVars == VAR_EXPORTED_NONE) 725 if (var_exportedVars == VAR_EXPORTED_NONE)
726 return; 726 return;
727 727
728 if (var_exportedVars == VAR_EXPORTED_ALL) { 728 if (var_exportedVars == VAR_EXPORTED_ALL) {
729 HashIter hi; 729 HashIter hi;
730 730
731 /* Ouch! Exporting all variables at once is crazy. */ 731 /* Ouch! Exporting all variables at once is crazy. */
732 HashIter_Init(&hi, &SCOPE_GLOBAL->vars); 732 HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
733 while (HashIter_Next(&hi) != NULL) { 733 while (HashIter_Next(&hi) != NULL) {
734 Var *var = hi.entry->value; 734 Var *var = hi.entry->value;
735 ExportVar(var->name.str, VEM_ENV); 735 ExportVar(var->name.str, VEM_ENV);
736 } 736 }
737 return; 737 return;
738 } 738 }
739 739
740 (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL, VARE_WANTRES, 740 (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL, VARE_WANTRES,
741 &xvarnames); 741 &xvarnames);
742 /* TODO: handle errors */ 742 /* TODO: handle errors */
743 if (xvarnames[0] != '\0') { 743 if (xvarnames[0] != '\0') {
744 Words varnames = Str_Words(xvarnames, FALSE); 744 Words varnames = Str_Words(xvarnames, FALSE);
745 size_t i; 745 size_t i;
746 746
747 for (i = 0; i < varnames.len; i++) 747 for (i = 0; i < varnames.len; i++)
748 ExportVar(varnames.words[i], VEM_ENV); 748 ExportVar(varnames.words[i], VEM_ENV);
749 Words_Free(varnames); 749 Words_Free(varnames);
750 } 750 }
751 free(xvarnames); 751 free(xvarnames);
752} 752}
753 753
754static void 754static void
755ExportVars(const char *varnames, Boolean isExport, VarExportMode mode) 755ExportVars(const char *varnames, Boolean isExport, VarExportMode mode)
756/* TODO: try to combine the parameters 'isExport' and 'mode'. */ 756/* TODO: try to combine the parameters 'isExport' and 'mode'. */
757{ 757{
758 Words words = Str_Words(varnames, FALSE); 758 Words words = Str_Words(varnames, FALSE);
759 size_t i; 759 size_t i;
760 760
761 if (words.len == 1 && words.words[0][0] == '\0') 761 if (words.len == 1 && words.words[0][0] == '\0')
762 words.len = 0; 762 words.len = 0;
763 763
764 for (i = 0; i < words.len; i++) { 764 for (i = 0; i < words.len; i++) {
765 const char *varname = words.words[i]; 765 const char *varname = words.words[i];
766 if (!ExportVar(varname, mode)) 766 if (!ExportVar(varname, mode))
767 continue; 767 continue;
768 768
769 if (var_exportedVars == VAR_EXPORTED_NONE) 769 if (var_exportedVars == VAR_EXPORTED_NONE)
770 var_exportedVars = VAR_EXPORTED_SOME; 770 var_exportedVars = VAR_EXPORTED_SOME;
771 771
772 if (isExport && mode == VEM_PLAIN) 772 if (isExport && mode == VEM_PLAIN)
773 Global_Append(MAKE_EXPORTED, varname); 773 Global_Append(MAKE_EXPORTED, varname);
774 } 774 }
775 Words_Free(words); 775 Words_Free(words);
776} 776}
777 777
778static void 778static void
779ExportVarsExpand(const char *uvarnames, Boolean isExport, VarExportMode mode) 779ExportVarsExpand(const char *uvarnames, Boolean isExport, VarExportMode mode)
780{ 780{
781 char *xvarnames; 781 char *xvarnames;
782 782
783 (void)Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_WANTRES, &xvarnames); 783 (void)Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_WANTRES, &xvarnames);
784 /* TODO: handle errors */ 784 /* TODO: handle errors */
785 ExportVars(xvarnames, isExport, mode); 785 ExportVars(xvarnames, isExport, mode);
786 free(xvarnames); 786 free(xvarnames);
787} 787}
788 788
789/* Export the named variables, or all variables. */ 789/* Export the named variables, or all variables. */
790void 790void
791Var_Export(VarExportMode mode, const char *varnames) 791Var_Export(VarExportMode mode, const char *varnames)
792{ 792{
793 if (mode == VEM_PLAIN && varnames[0] == '\0') { 793 if (mode == VEM_PLAIN && varnames[0] == '\0') {
794 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */ 794 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
795 return; 795 return;
796 } 796 }
797 797
798 ExportVarsExpand(varnames, TRUE, mode); 798 ExportVarsExpand(varnames, TRUE, mode);
799} 799}
800 800
801void 801void
802Var_ExportVars(const char *varnames) 802Var_ExportVars(const char *varnames)
803{ 803{
804 ExportVarsExpand(varnames, FALSE, VEM_PLAIN); 804 ExportVarsExpand(varnames, FALSE, VEM_PLAIN);
805} 805}
806 806
807 807
808extern char **environ; 808extern char **environ;
809 809
810static void 810static void
811ClearEnv(void) 811ClearEnv(void)
812{ 812{
813 const char *cp; 813 const char *cp;
814 char **newenv; 814 char **newenv;
815 815
816 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */ 816 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
817 if (environ == savedEnv) { 817 if (environ == savedEnv) {
818 /* we have been here before! */ 818 /* we have been here before! */
819 newenv = bmake_realloc(environ, 2 * sizeof(char *)); 819 newenv = bmake_realloc(environ, 2 * sizeof(char *));
820 } else { 820 } else {
821 if (savedEnv != NULL) { 821 if (savedEnv != NULL) {
822 free(savedEnv); 822 free(savedEnv);
823 savedEnv = NULL; 823 savedEnv = NULL;
824 } 824 }
825 newenv = bmake_malloc(2 * sizeof(char *)); 825 newenv = bmake_malloc(2 * sizeof(char *));
826 } 826 }
827 827
828 /* Note: we cannot safely free() the original environ. */ 828 /* Note: we cannot safely free() the original environ. */
829 environ = savedEnv = newenv; 829 environ = savedEnv = newenv;
830 newenv[0] = NULL; 830 newenv[0] = NULL;
831 newenv[1] = NULL; 831 newenv[1] = NULL;
832 if (cp != NULL && *cp != '\0') 832 if (cp != NULL && *cp != '\0')
833 setenv(MAKE_LEVEL_ENV, cp, 1); 833 setenv(MAKE_LEVEL_ENV, cp, 1);
834} 834}
835 835
836static void 836static void
837GetVarnamesToUnexport(Boolean isEnv, const char *arg, 837GetVarnamesToUnexport(Boolean isEnv, const char *arg,
838 FStr *out_varnames, UnexportWhat *out_what) 838 FStr *out_varnames, UnexportWhat *out_what)
839{ 839{
840 UnexportWhat what; 840 UnexportWhat what;
841 FStr varnames = FStr_InitRefer(""); 841 FStr varnames = FStr_InitRefer("");
842 842
843 if (isEnv) { 843 if (isEnv) {
844 if (arg[0] != '\0') { 844 if (arg[0] != '\0') {
845 Parse_Error(PARSE_FATAL, 845 Parse_Error(PARSE_FATAL,
846 "The directive .unexport-env does not take " 846 "The directive .unexport-env does not take "
847 "arguments"); 847 "arguments");
848 /* continue anyway */ 848 /* continue anyway */
849 } 849 }
850 what = UNEXPORT_ENV; 850 what = UNEXPORT_ENV;
851 851
852 } else { 852 } else {
853 what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL; 853 what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
854 if (what == UNEXPORT_NAMED) 854 if (what == UNEXPORT_NAMED)
855 varnames = FStr_InitRefer(arg); 855 varnames = FStr_InitRefer(arg);
856 } 856 }
857 857
858 if (what != UNEXPORT_NAMED) { 858 if (what != UNEXPORT_NAMED) {
859 char *expanded; 859 char *expanded;
860 /* Using .MAKE.EXPORTED */ 860 /* Using .MAKE.EXPORTED */
861 (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL, 861 (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL,
862 VARE_WANTRES, &expanded); 862 VARE_WANTRES, &expanded);
863 /* TODO: handle errors */ 863 /* TODO: handle errors */
864 varnames = FStr_InitOwn(expanded); 864 varnames = FStr_InitOwn(expanded);
865 } 865 }
866 866
867 *out_varnames = varnames; 867 *out_varnames = varnames;
868 *out_what = what; 868 *out_what = what;
869} 869}
870 870
871static void 871static void
872UnexportVar(const char *varname, UnexportWhat what) 872UnexportVar(const char *varname, UnexportWhat what)
873{ 873{
874 Var *v = VarFind(varname, SCOPE_GLOBAL, FALSE); 874 Var *v = VarFind(varname, SCOPE_GLOBAL, FALSE);
875 if (v == NULL) { 875 if (v == NULL) {
876 DEBUG1(VAR, "Not unexporting \"%s\" (not found)\n", varname); 876 DEBUG1(VAR, "Not unexporting \"%s\" (not found)\n", varname);
877 return; 877 return;
878 } 878 }
879 879
880 DEBUG1(VAR, "Unexporting \"%s\"\n", varname); 880 DEBUG1(VAR, "Unexporting \"%s\"\n", varname);
881 if (what != UNEXPORT_ENV && 881 if (what != UNEXPORT_ENV &&
882 (v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT)) 882 (v->flags & VFL_EXPORTED) && !(v->flags & VFL_REEXPORT))
883 unsetenv(v->name.str); 883 unsetenv(v->name.str);
884 v->flags &= ~(unsigned)(VFL_EXPORTED | VFL_REEXPORT); 884 v->flags &= ~(unsigned)(VFL_EXPORTED | VFL_REEXPORT);
885 885
886 if (what == UNEXPORT_NAMED) { 886 if (what == UNEXPORT_NAMED) {
887 /* Remove the variable names from .MAKE.EXPORTED. */ 887 /* Remove the variable names from .MAKE.EXPORTED. */
888 /* XXX: v->name is injected without escaping it */ 888 /* XXX: v->name is injected without escaping it */
889 char *expr = str_concat3("${" MAKE_EXPORTED ":N", 889 char *expr = str_concat3("${" MAKE_EXPORTED ":N",
890 v->name.str, "}"); 890 v->name.str, "}");
891 char *cp; 891 char *cp;
892 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &cp); 892 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &cp);
893 /* TODO: handle errors */ 893 /* TODO: handle errors */
894 Global_Set(MAKE_EXPORTED, cp); 894 Global_Set(MAKE_EXPORTED, cp);
895 free(cp); 895 free(cp);
896 free(expr); 896 free(expr);
897 } 897 }
898} 898}
899 899
900static void 900static void
901UnexportVars(FStr *varnames, UnexportWhat what) 901UnexportVars(FStr *varnames, UnexportWhat what)
902{ 902{
903 size_t i; 903 size_t i;
904 Words words; 904 Words words;
905 905
906 if (what == UNEXPORT_ENV) 906 if (what == UNEXPORT_ENV)
907 ClearEnv(); 907 ClearEnv();
908 908
909 words = Str_Words(varnames->str, FALSE); 909 words = Str_Words(varnames->str, FALSE);
910 for (i = 0; i < words.len; i++) { 910 for (i = 0; i < words.len; i++) {
911 const char *varname = words.words[i]; 911 const char *varname = words.words[i];
912 UnexportVar(varname, what); 912 UnexportVar(varname, what);
913 } 913 }
914 Words_Free(words); 914 Words_Free(words);
915 915
916 if (what != UNEXPORT_NAMED) 916 if (what != UNEXPORT_NAMED)
917 Global_Delete(MAKE_EXPORTED); 917 Global_Delete(MAKE_EXPORTED);
918} 918}
919 919
920/* 920/*
921 * This is called when .unexport[-env] is seen. 921 * This is called when .unexport[-env] is seen.
922 * 922 *
923 * str must have the form "unexport[-env] varname...". 923 * str must have the form "unexport[-env] varname...".
924 */ 924 */
925void 925void
926Var_UnExport(Boolean isEnv, const char *arg) 926Var_UnExport(Boolean isEnv, const char *arg)
927{ 927{
928 UnexportWhat what; 928 UnexportWhat what;
929 FStr varnames; 929 FStr varnames;
930 930
931 GetVarnamesToUnexport(isEnv, arg, &varnames, &what); 931 GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
932 UnexportVars(&varnames, what); 932 UnexportVars(&varnames, what);
933 FStr_Done(&varnames); 933 FStr_Done(&varnames);
934} 934}
935 935
936/* 936/*
937 * When there is a variable of the same name in the command line scope, the 937 * When there is a variable of the same name in the command line scope, the
938 * global variable would not be visible anywhere. Therefore there is no 938 * global variable would not be visible anywhere. Therefore there is no
939 * point in setting it at all. 939 * point in setting it at all.
940 * 940 *
941 * See 'scope == SCOPE_CMDLINE' in Var_SetWithFlags. 941 * See 'scope == SCOPE_CMDLINE' in Var_SetWithFlags.
942 */ 942 */
943static Boolean 943static Boolean
944ExistsInCmdline(const char *name, const char *val) 944ExistsInCmdline(const char *name, const char *val)
945{ 945{
946 Var *v; 946 Var *v;
947 947
948 v = VarFind(name, SCOPE_CMDLINE, FALSE); 948 v = VarFind(name, SCOPE_CMDLINE, FALSE);
949 if (v == NULL) 949 if (v == NULL)
950 return FALSE; 950 return FALSE;
951 951
952 if (v->flags & VFL_FROM_CMD) { 952 if (v->flags & VFL_FROM_CMD) {
953 DEBUG3(VAR, "%s:%s = %s ignored!\n", 953 DEBUG3(VAR, "%s:%s = %s ignored!\n",
954 SCOPE_GLOBAL->name, name, val); 954 SCOPE_GLOBAL->name, name, val);
955 return TRUE; 955 return TRUE;
956 } 956 }
957 957
958 VarFreeEnv(v); 958 VarFreeEnv(v);
959 return FALSE; 959 return FALSE;
960} 960}
961 961
962/* Set the variable to the value; the name is not expanded. */ 962/* Set the variable to the value; the name is not expanded. */
963void 963void
964Var_SetWithFlags(GNode *scope, const char *name, const char *val, 964Var_SetWithFlags(GNode *scope, const char *name, const char *val,
965 VarSetFlags flags) 965 VarSetFlags flags)
966{ 966{
967 Var *v; 967 Var *v;
968 968
969 assert(val != NULL); 969 assert(val != NULL);
970 if (name[0] == '\0') { 970 if (name[0] == '\0') {
971 DEBUG0(VAR, "SetVar: variable name is empty - ignored\n"); 971 DEBUG0(VAR, "SetVar: variable name is empty - ignored\n");
972 return; 972 return;
973 } 973 }
974 974
975 if (scope == SCOPE_GLOBAL && ExistsInCmdline(name, val)) 975 if (scope == SCOPE_GLOBAL && ExistsInCmdline(name, val))
976 return; 976 return;
977 977
978 /* 978 /*
979 * Only look for a variable in the given scope since anything set 979 * Only look for a variable in the given scope since anything set
980 * here will override anything in a lower scope, so there's not much 980 * here will override anything in a lower scope, so there's not much
981 * point in searching them all. 981 * point in searching them all.
982 */ 982 */
983 v = VarFind(name, scope, FALSE); 983 v = VarFind(name, scope, FALSE);
984 if (v == NULL) { 984 if (v == NULL) {
985 if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) { 985 if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
986 /* 986 /*
987 * This var would normally prevent the same name being 987 * This var would normally prevent the same name being
988 * added to SCOPE_GLOBAL, so delete it from there if 988 * added to SCOPE_GLOBAL, so delete it from there if
989 * needed. Otherwise -V name may show the wrong value. 989 * needed. Otherwise -V name may show the wrong value.
990 * 990 *
991 * See ExistsInCmdline. 991 * See ExistsInCmdline.
992 */ 992 */
993 Var_Delete(SCOPE_GLOBAL, name); 993 Var_Delete(SCOPE_GLOBAL, name);
994 } 994 }
995 v = VarAdd(name, val, scope, flags); 995 v = VarAdd(name, val, scope, flags);
996 } else { 996 } else {
997 if ((v->flags & VFL_READONLY) && !(flags & VAR_SET_READONLY)) { 997 if ((v->flags & VFL_READONLY) && !(flags & VAR_SET_READONLY)) {
998 DEBUG3(VAR, "%s:%s = %s ignored (read-only)\n", 998 DEBUG3(VAR, "%s:%s = %s ignored (read-only)\n",
999 scope->name, name, val); 999 scope->name, name, val);
1000 return; 1000 return;
1001 } 1001 }
1002 Buf_Empty(&v->val); 1002 Buf_Empty(&v->val);
1003 Buf_AddStr(&v->val, val); 1003 Buf_AddStr(&v->val, val);
1004 1004
1005 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, val); 1005 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, val);
1006 if (v->flags & VFL_EXPORTED) 1006 if (v->flags & VFL_EXPORTED)
1007 ExportVar(name, VEM_PLAIN); 1007 ExportVar(name, VEM_PLAIN);
1008 } 1008 }
1009 1009
1010 /* 1010 /*
1011 * Any variables given on the command line are automatically exported 1011 * Any variables given on the command line are automatically exported
1012 * to the environment (as per POSIX standard), except for internals. 1012 * to the environment (as per POSIX standard), except for internals.
1013 */ 1013 */
1014 if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT) && 1014 if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT) &&
1015 name[0] != '.') { 1015 name[0] != '.') {
1016 v->flags |= VFL_FROM_CMD; 1016 v->flags |= VFL_FROM_CMD;
1017 1017
1018 /* 1018 /*
1019 * If requested, don't export these in the environment 1019 * If requested, don't export these in the environment
1020 * individually. We still put them in MAKEOVERRIDES so 1020 * individually. We still put them in MAKEOVERRIDES so
1021 * that the command-line settings continue to override 1021 * that the command-line settings continue to override
1022 * Makefile settings. 1022 * Makefile settings.
1023 */ 1023 */
1024 if (!opts.varNoExportEnv) 1024 if (!opts.varNoExportEnv)
1025 setenv(name, val, 1); 1025 setenv(name, val, 1);
1026 /* XXX: What about .MAKE.EXPORTED? */ 1026 /* XXX: What about .MAKE.EXPORTED? */
1027 /* XXX: Why not just mark the variable for needing export, 1027 /* XXX: Why not just mark the variable for needing export,
1028 * as in ExportVarPlain? */ 1028 * as in ExportVarPlain? */
1029 1029
1030 Global_Append(MAKEOVERRIDES, name); 1030 Global_Append(MAKEOVERRIDES, name);
1031 } 1031 }
1032 1032
1033 if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0) 1033 if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0)
1034 save_dollars = ParseBoolean(val, save_dollars); 1034 save_dollars = ParseBoolean(val, save_dollars);
1035 1035
1036 if (v != NULL) 1036 if (v != NULL)
1037 VarFreeEnv(v); 1037 VarFreeEnv(v);
1038} 1038}
1039 1039
1040/* See Var_Set for documentation. */ 1040/* See Var_Set for documentation. */
1041void 1041void
1042Var_SetExpandWithFlags(GNode *scope, const char *name, const char *val, 1042Var_SetExpandWithFlags(GNode *scope, const char *name, const char *val,
1043 VarSetFlags flags) 1043 VarSetFlags flags)
1044{ 1044{
1045 const char *unexpanded_name = name; 1045 const char *unexpanded_name = name;
1046 FStr varname = FStr_InitRefer(name); 1046 FStr varname = FStr_InitRefer(name);
1047 1047
1048 assert(val != NULL); 1048 assert(val != NULL);
1049 1049
1050 if (strchr(varname.str, '$') != NULL) { 1050 if (strchr(varname.str, '$') != NULL) {
1051 char *expanded; 1051 char *expanded;
1052 (void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded); 1052 (void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
1053 /* TODO: handle errors */ 1053 /* TODO: handle errors */
1054 varname = FStr_InitOwn(expanded); 1054 varname = FStr_InitOwn(expanded);
1055 } 1055 }
1056 1056
1057 if (varname.str[0] == '\0') { 1057 if (varname.str[0] == '\0') {
1058 DEBUG2(VAR, "Var_Set(\"%s\", \"%s\", ...) " 1058 DEBUG2(VAR, "Var_Set(\"%s\", \"%s\", ...) "
1059 "name expands to empty string - ignored\n", 1059 "name expands to empty string - ignored\n",
1060 unexpanded_name, val); 1060 unexpanded_name, val);
1061 } else 1061 } else
1062 Var_SetWithFlags(scope, varname.str, val, flags); 1062 Var_SetWithFlags(scope, varname.str, val, flags);
1063 1063
1064 FStr_Done(&varname); 1064 FStr_Done(&varname);
1065} 1065}
1066 1066
1067void 1067void
1068Var_Set(GNode *scope, const char *name, const char *val) 1068Var_Set(GNode *scope, const char *name, const char *val)
1069{ 1069{
1070 Var_SetWithFlags(scope, name, val, VAR_SET_NONE); 1070 Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
1071} 1071}
1072 1072
1073/* 1073/*
1074 * Set the variable name to the value val in the given scope. 1074 * Set the variable name to the value val in the given scope.
1075 * 1075 *
1076 * If the variable doesn't yet exist, it is created. 1076 * If the variable doesn't yet exist, it is created.
1077 * Otherwise the new value overwrites and replaces the old value. 1077 * Otherwise the new value overwrites and replaces the old value.
1078 * 1078 *
1079 * Input: 1079 * Input:
1080 * name name of the variable to set, is expanded once 1080 * name name of the variable to set, is expanded once
1081 * val value to give to the variable 1081 * val value to give to the variable
1082 * scope scope in which to set it 1082 * scope scope in which to set it
1083 */ 1083 */
1084void 1084void
1085Var_SetExpand(GNode *scope, const char *name, const char *val) 1085Var_SetExpand(GNode *scope, const char *name, const char *val)
1086{ 1086{
1087 Var_SetExpandWithFlags(scope, name, val, VAR_SET_NONE); 1087 Var_SetExpandWithFlags(scope, name, val, VAR_SET_NONE);
1088} 1088}
1089 1089
1090void 1090void
1091Global_Set(const char *name, const char *value) 1091Global_Set(const char *name, const char *value)
1092{ 1092{
1093 Var_Set(SCOPE_GLOBAL, name, value); 1093 Var_Set(SCOPE_GLOBAL, name, value);
1094} 1094}
1095 1095
1096void 1096void
1097Global_SetExpand(const char *name, const char *value) 1097Global_SetExpand(const char *name, const char *value)
1098{ 1098{
1099 Var_SetExpand(SCOPE_GLOBAL, name, value); 1099 Var_SetExpand(SCOPE_GLOBAL, name, value);
1100} 1100}
1101 1101
1102void 1102void
1103Global_Delete(const char *name) 1103Global_Delete(const char *name)
1104{ 1104{
1105 Var_Delete(SCOPE_GLOBAL, name); 1105 Var_Delete(SCOPE_GLOBAL, name);
1106} 1106}
1107 1107
1108/* 1108/*
1109 * Append the value to the named variable. 1109 * Append the value to the named variable.
1110 * 1110 *
1111 * If the variable doesn't exist, it is created. Otherwise a single space 1111 * If the variable doesn't exist, it is created. Otherwise a single space
1112 * and the given value are appended. 1112 * and the given value are appended.
1113 */ 1113 */
1114void 1114void
1115Var_Append(GNode *scope, const char *name, const char *val) 1115Var_Append(GNode *scope, const char *name, const char *val)
1116{ 1116{
1117 Var *v; 1117 Var *v;
1118 1118
1119 v = VarFind(name, scope, scope == SCOPE_GLOBAL); 1119 v = VarFind(name, scope, scope == SCOPE_GLOBAL);
1120 1120
1121 if (v == NULL) { 1121 if (v == NULL) {
1122 Var_SetWithFlags(scope, name, val, VAR_SET_NONE); 1122 Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
1123 } else if (v->flags & VFL_READONLY) { 1123 } else if (v->flags & VFL_READONLY) {
1124 DEBUG1(VAR, "Ignoring append to %s since it is read-only\n", 1124 DEBUG1(VAR, "Ignoring append to %s since it is read-only\n",
1125 name); 1125 name);
1126 } else if (scope == SCOPE_CMDLINE || !(v->flags & VFL_FROM_CMD)) { 1126 } else if (scope == SCOPE_CMDLINE || !(v->flags & VFL_FROM_CMD)) {
1127 Buf_AddByte(&v->val, ' '); 1127 Buf_AddByte(&v->val, ' ');
1128 Buf_AddStr(&v->val, val); 1128 Buf_AddStr(&v->val, val);
1129 1129
1130 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, v->val.data); 1130 DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, v->val.data);
1131 1131
1132 if (v->flags & VFL_FROM_ENV) { 1132 if (v->flags & VFL_FROM_ENV) {
1133 /* 1133 /*
1134 * If the original variable came from the environment, 1134 * If the original variable came from the environment,
1135 * we have to install it in the global scope (we 1135 * we have to install it in the global scope (we
1136 * could place it in the environment, but then we 1136 * could place it in the environment, but then we
1137 * should provide a way to export other variables...) 1137 * should provide a way to export other variables...)
1138 */ 1138 */
1139 v->flags &= ~(unsigned)VFL_FROM_ENV; 1139 v->flags &= ~(unsigned)VFL_FROM_ENV;
1140 /* 1140 /*
1141 * This is the only place where a variable is 1141 * This is the only place where a variable is
1142 * created whose v->name is not the same as 1142 * created whose v->name is not the same as
@@ -3346,1281 +3346,1276 @@ ApplyModifier_IfElse(const char **pp, Mo @@ -3346,1281 +3346,1276 @@ ApplyModifier_IfElse(const char **pp, Mo
3346 3346
3347 (*pp)--; /* Go back to the ch->endc. */ 3347 (*pp)--; /* Go back to the ch->endc. */
3348 3348
3349 if (cond_rc == COND_INVALID) { 3349 if (cond_rc == COND_INVALID) {
3350 Error("Bad conditional expression `%s' in %s?%s:%s", 3350 Error("Bad conditional expression `%s' in %s?%s:%s",
3351 expr->var->name.str, expr->var->name.str, 3351 expr->var->name.str, expr->var->name.str,
3352 then_expr, else_expr); 3352 then_expr, else_expr);
3353 return AMR_CLEANUP; 3353 return AMR_CLEANUP;
3354 } 3354 }
3355 3355
3356 if (!expr->eflags.wantRes) { 3356 if (!expr->eflags.wantRes) {
3357 free(then_expr); 3357 free(then_expr);
3358 free(else_expr); 3358 free(else_expr);
3359 } else if (value) { 3359 } else if (value) {
3360 Expr_SetValueOwn(expr, then_expr); 3360 Expr_SetValueOwn(expr, then_expr);
3361 free(else_expr); 3361 free(else_expr);
3362 } else { 3362 } else {
3363 Expr_SetValueOwn(expr, else_expr); 3363 Expr_SetValueOwn(expr, else_expr);
3364 free(then_expr); 3364 free(then_expr);
3365 } 3365 }
3366 Expr_Define(expr); 3366 Expr_Define(expr);
3367 return AMR_OK; 3367 return AMR_OK;
3368} 3368}
3369 3369
3370/* 3370/*
3371 * The ::= modifiers are special in that they do not read the variable value 3371 * The ::= modifiers are special in that they do not read the variable value
3372 * but instead assign to that variable. They always expand to an empty 3372 * but instead assign to that variable. They always expand to an empty
3373 * string. 3373 * string.
3374 * 3374 *
3375 * Their main purpose is in supporting .for loops that generate shell commands 3375 * Their main purpose is in supporting .for loops that generate shell commands
3376 * since an ordinary variable assignment at that point would terminate the 3376 * since an ordinary variable assignment at that point would terminate the
3377 * dependency group for these targets. For example: 3377 * dependency group for these targets. For example:
3378 * 3378 *
3379 * list-targets: .USE 3379 * list-targets: .USE
3380 * .for i in ${.TARGET} ${.TARGET:R}.gz 3380 * .for i in ${.TARGET} ${.TARGET:R}.gz
3381 * @${t::=$i} 3381 * @${t::=$i}
3382 * @echo 'The target is ${t:T}.' 3382 * @echo 'The target is ${t:T}.'
3383 * .endfor 3383 * .endfor
3384 * 3384 *
3385 * ::=<str> Assigns <str> as the new value of variable. 3385 * ::=<str> Assigns <str> as the new value of variable.
3386 * ::?=<str> Assigns <str> as value of variable if 3386 * ::?=<str> Assigns <str> as value of variable if
3387 * it was not already set. 3387 * it was not already set.
3388 * ::+=<str> Appends <str> to variable. 3388 * ::+=<str> Appends <str> to variable.
3389 * ::!=<cmd> Assigns output of <cmd> as the new value of 3389 * ::!=<cmd> Assigns output of <cmd> as the new value of
3390 * variable. 3390 * variable.
3391 */ 3391 */
3392static ApplyModifierResult 3392static ApplyModifierResult
3393ApplyModifier_Assign(const char **pp, ModChain *ch) 3393ApplyModifier_Assign(const char **pp, ModChain *ch)
3394{ 3394{
3395 Expr *expr = ch->expr; 3395 Expr *expr = ch->expr;
3396 GNode *scope; 3396 GNode *scope;
3397 char *val; 3397 char *val;
3398 VarParseResult res; 3398 VarParseResult res;
3399 3399
3400 const char *mod = *pp; 3400 const char *mod = *pp;
3401 const char *op = mod + 1; 3401 const char *op = mod + 1;
3402 3402
3403 if (op[0] == '=') 3403 if (op[0] == '=')
3404 goto ok; 3404 goto ok;
3405 if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=') 3405 if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
3406 goto ok; 3406 goto ok;
3407 return AMR_UNKNOWN; /* "::<unrecognised>" */ 3407 return AMR_UNKNOWN; /* "::<unrecognised>" */
3408 3408
3409ok: 3409ok:
3410 if (expr->var->name.str[0] == '\0') { 3410 if (expr->var->name.str[0] == '\0') {
3411 *pp = mod + 1; 3411 *pp = mod + 1;
3412 return AMR_BAD; 3412 return AMR_BAD;
3413 } 3413 }
3414 3414
3415 switch (op[0]) { 3415 switch (op[0]) {
3416 case '+': 3416 case '+':
3417 case '?': 3417 case '?':
3418 case '!': 3418 case '!':
3419 *pp = mod + 3; 3419 *pp = mod + 3;
3420 break; 3420 break;
3421 default: 3421 default:
3422 *pp = mod + 2; 3422 *pp = mod + 2;
3423 break; 3423 break;
3424 } 3424 }
3425 3425
3426 res = ParseModifierPart(pp, ch->endc, expr->eflags, ch, &val); 3426 res = ParseModifierPart(pp, ch->endc, expr->eflags, ch, &val);
3427 if (res != VPR_OK) 3427 if (res != VPR_OK)
3428 return AMR_CLEANUP; 3428 return AMR_CLEANUP;
3429 3429
3430 (*pp)--; /* Go back to the ch->endc. */ 3430 (*pp)--; /* Go back to the ch->endc. */
3431 3431
3432 if (!expr->eflags.wantRes) 3432 if (!expr->eflags.wantRes)
3433 goto done; 3433 goto done;
3434 3434
3435 scope = expr->scope; /* scope where v belongs */ 3435 scope = expr->scope; /* scope where v belongs */
3436 if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) { 3436 if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) {
3437 Var *gv = VarFind(expr->var->name.str, expr->scope, FALSE); 3437 Var *gv = VarFind(expr->var->name.str, expr->scope, FALSE);
3438 if (gv == NULL) 3438 if (gv == NULL)
3439 scope = SCOPE_GLOBAL; 3439 scope = SCOPE_GLOBAL;
3440 else 3440 else
3441 VarFreeEnv(gv); 3441 VarFreeEnv(gv);
3442 } 3442 }
3443 3443
3444 switch (op[0]) { 3444 switch (op[0]) {
3445 case '+': 3445 case '+':
3446 Var_Append(scope, expr->var->name.str, val); 3446 Var_Append(scope, expr->var->name.str, val);
3447 break; 3447 break;
3448 case '!': { 3448 case '!': {
3449 const char *errfmt; 3449 const char *errfmt;
3450 char *cmd_output = Cmd_Exec(val, &errfmt); 3450 char *cmd_output = Cmd_Exec(val, &errfmt);
3451 if (errfmt != NULL) 3451 if (errfmt != NULL)
3452 Error(errfmt, val); 3452 Error(errfmt, val);
3453 else 3453 else
3454 Var_Set(scope, expr->var->name.str, cmd_output); 3454 Var_Set(scope, expr->var->name.str, cmd_output);
3455 free(cmd_output); 3455 free(cmd_output);
3456 break; 3456 break;
3457 } 3457 }
3458 case '?': 3458 case '?':
3459 if (expr->defined == DEF_REGULAR) 3459 if (expr->defined == DEF_REGULAR)
3460 break; 3460 break;
3461 /* FALLTHROUGH */ 3461 /* FALLTHROUGH */
3462 default: 3462 default:
3463 Var_Set(scope, expr->var->name.str, val); 3463 Var_Set(scope, expr->var->name.str, val);
3464 break; 3464 break;
3465 } 3465 }
3466 Expr_SetValueRefer(expr, ""); 3466 Expr_SetValueRefer(expr, "");
3467 3467
3468done: 3468done:
3469 free(val); 3469 free(val);
3470 return AMR_OK; 3470 return AMR_OK;
3471} 3471}
3472 3472
3473/* 3473/*
3474 * :_=... 3474 * :_=...
3475 * remember current value 3475 * remember current value
3476 */ 3476 */
3477static ApplyModifierResult 3477static ApplyModifierResult
3478ApplyModifier_Remember(const char **pp, ModChain *ch) 3478ApplyModifier_Remember(const char **pp, ModChain *ch)
3479{ 3479{
3480 Expr *expr = ch->expr; 3480 Expr *expr = ch->expr;
3481 const char *mod = *pp; 3481 const char *mod = *pp;
3482 FStr name; 3482 FStr name;
3483 3483
3484 if (!ModMatchEq(mod, "_", ch)) 3484 if (!ModMatchEq(mod, "_", ch))
3485 return AMR_UNKNOWN; 3485 return AMR_UNKNOWN;
3486 3486
3487 name = FStr_InitRefer("_"); 3487 name = FStr_InitRefer("_");
3488 if (mod[1] == '=') { 3488 if (mod[1] == '=') {
3489 /* 3489 /*
3490 * XXX: This ad-hoc call to strcspn deviates from the usual 3490 * XXX: This ad-hoc call to strcspn deviates from the usual
3491 * behavior defined in ParseModifierPart. This creates an 3491 * behavior defined in ParseModifierPart. This creates an
3492 * unnecessary, undocumented inconsistency in make. 3492 * unnecessary, undocumented inconsistency in make.
3493 */ 3493 */
3494 const char *arg = mod + 2; 3494 const char *arg = mod + 2;
3495 size_t argLen = strcspn(arg, ":)}"); 3495 size_t argLen = strcspn(arg, ":)}");
3496 *pp = arg + argLen; 3496 *pp = arg + argLen;
3497 name = FStr_InitOwn(bmake_strldup(arg, argLen)); 3497 name = FStr_InitOwn(bmake_strldup(arg, argLen));
3498 } else 3498 } else
3499 *pp = mod + 1; 3499 *pp = mod + 1;
3500 3500
3501 if (expr->eflags.wantRes) 3501 if (expr->eflags.wantRes)
3502 Var_Set(expr->scope, name.str, expr->value.str); 3502 Var_Set(expr->scope, name.str, expr->value.str);
3503 FStr_Done(&name); 3503 FStr_Done(&name);
3504 3504
3505 return AMR_OK; 3505 return AMR_OK;
3506} 3506}
3507 3507
3508/* 3508/*
3509 * Apply the given function to each word of the variable value, 3509 * Apply the given function to each word of the variable value,
3510 * for a single-letter modifier such as :H, :T. 3510 * for a single-letter modifier such as :H, :T.
3511 */ 3511 */
3512static ApplyModifierResult 3512static ApplyModifierResult
3513ApplyModifier_WordFunc(const char **pp, ModChain *ch, 3513ApplyModifier_WordFunc(const char **pp, ModChain *ch,
3514 ModifyWordProc modifyWord) 3514 ModifyWordProc modifyWord)
3515{ 3515{
3516 if (!IsDelimiter((*pp)[1], ch)) 3516 if (!IsDelimiter((*pp)[1], ch))
3517 return AMR_UNKNOWN; 3517 return AMR_UNKNOWN;
3518 (*pp)++; 3518 (*pp)++;
3519 3519
3520 if (ch->expr->eflags.wantRes) 3520 if (ch->expr->eflags.wantRes)
3521 ModifyWords(ch, modifyWord, NULL, ch->oneBigWord); 3521 ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
3522 3522
3523 return AMR_OK; 3523 return AMR_OK;
3524} 3524}
3525 3525
3526static ApplyModifierResult 3526static ApplyModifierResult
3527ApplyModifier_Unique(const char **pp, ModChain *ch) 3527ApplyModifier_Unique(const char **pp, ModChain *ch)
3528{ 3528{
3529 if (!IsDelimiter((*pp)[1], ch)) 3529 if (!IsDelimiter((*pp)[1], ch))
3530 return AMR_UNKNOWN; 3530 return AMR_UNKNOWN;
3531 (*pp)++; 3531 (*pp)++;
3532 3532
3533 if (ch->expr->eflags.wantRes) 3533 if (ch->expr->eflags.wantRes)
3534 Expr_SetValueOwn(ch->expr, VarUniq(ch->expr->value.str)); 3534 Expr_SetValueOwn(ch->expr, VarUniq(ch->expr->value.str));
3535 3535
3536 return AMR_OK; 3536 return AMR_OK;
3537} 3537}
3538 3538
3539#ifdef SYSVVARSUB 3539#ifdef SYSVVARSUB
3540/* :from=to */ 3540/* :from=to */
3541static ApplyModifierResult 3541static ApplyModifierResult
3542ApplyModifier_SysV(const char **pp, ModChain *ch) 3542ApplyModifier_SysV(const char **pp, ModChain *ch)
3543{ 3543{
3544 Expr *expr = ch->expr; 3544 Expr *expr = ch->expr;
3545 char *lhs, *rhs; 3545 char *lhs, *rhs;
3546 VarParseResult res; 3546 VarParseResult res;
3547 3547
3548 const char *mod = *pp; 3548 const char *mod = *pp;
3549 Boolean eqFound = FALSE; 3549 Boolean eqFound = FALSE;
3550 3550
3551 /* 3551 /*
3552 * First we make a pass through the string trying to verify it is a 3552 * First we make a pass through the string trying to verify it is a
3553 * SysV-make-style translation. It must be: <lhs>=<rhs> 3553 * SysV-make-style translation. It must be: <lhs>=<rhs>
3554 */ 3554 */
3555 int depth = 1; 3555 int depth = 1;
3556 const char *p = mod; 3556 const char *p = mod;
3557 while (*p != '\0' && depth > 0) { 3557 while (*p != '\0' && depth > 0) {
3558 if (*p == '=') { /* XXX: should also test depth == 1 */ 3558 if (*p == '=') { /* XXX: should also test depth == 1 */
3559 eqFound = TRUE; 3559 eqFound = TRUE;
3560 /* continue looking for ch->endc */ 3560 /* continue looking for ch->endc */
3561 } else if (*p == ch->endc) 3561 } else if (*p == ch->endc)
3562 depth--; 3562 depth--;
3563 else if (*p == ch->startc) 3563 else if (*p == ch->startc)
3564 depth++; 3564 depth++;
3565 if (depth > 0) 3565 if (depth > 0)
3566 p++; 3566 p++;
3567 } 3567 }
3568 if (*p != ch->endc || !eqFound) 3568 if (*p != ch->endc || !eqFound)
3569 return AMR_UNKNOWN; 3569 return AMR_UNKNOWN;
3570 3570
3571 res = ParseModifierPart(pp, '=', expr->eflags, ch, &lhs); 3571 res = ParseModifierPart(pp, '=', expr->eflags, ch, &lhs);
3572 if (res != VPR_OK) 3572 if (res != VPR_OK)
3573 return AMR_CLEANUP; 3573 return AMR_CLEANUP;
3574 3574
3575 /* The SysV modifier lasts until the end of the variable expression. */ 3575 /* The SysV modifier lasts until the end of the variable expression. */
3576 res = ParseModifierPart(pp, ch->endc, expr->eflags, ch, &rhs); 3576 res = ParseModifierPart(pp, ch->endc, expr->eflags, ch, &rhs);
3577 if (res != VPR_OK) 3577 if (res != VPR_OK)
3578 return AMR_CLEANUP; 3578 return AMR_CLEANUP;
3579 3579
3580 (*pp)--; /* Go back to the ch->endc. */ 3580 (*pp)--; /* Go back to the ch->endc. */
3581 3581
3582 if (lhs[0] == '\0' && expr->value.str[0] == '\0') { 3582 if (lhs[0] == '\0' && expr->value.str[0] == '\0') {
3583 /* Do not turn an empty expression into non-empty. */ 3583 /* Do not turn an empty expression into non-empty. */
3584 } else { 3584 } else {
3585 struct ModifyWord_SYSVSubstArgs args = { 3585 struct ModifyWord_SYSVSubstArgs args = {
3586 expr->scope, lhs, rhs 3586 expr->scope, lhs, rhs
3587 }; 3587 };
3588 ModifyWords(ch, ModifyWord_SYSVSubst, &args, ch->oneBigWord); 3588 ModifyWords(ch, ModifyWord_SYSVSubst, &args, ch->oneBigWord);
3589 } 3589 }
3590 free(lhs); 3590 free(lhs);
3591 free(rhs); 3591 free(rhs);
3592 return AMR_OK; 3592 return AMR_OK;
3593} 3593}
3594#endif 3594#endif
3595 3595
3596#ifdef SUNSHCMD 3596#ifdef SUNSHCMD
3597/* :sh */ 3597/* :sh */
3598static ApplyModifierResult 3598static ApplyModifierResult
3599ApplyModifier_SunShell(const char **pp, ModChain *ch) 3599ApplyModifier_SunShell(const char **pp, ModChain *ch)
3600{ 3600{
3601 Expr *expr = ch->expr; 3601 Expr *expr = ch->expr;
3602 const char *p = *pp; 3602 const char *p = *pp;
3603 if (!(p[1] == 'h' && IsDelimiter(p[2], ch))) 3603 if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
3604 return AMR_UNKNOWN; 3604 return AMR_UNKNOWN;
3605 *pp = p + 2; 3605 *pp = p + 2;
3606 3606
3607 if (expr->eflags.wantRes) { 3607 if (expr->eflags.wantRes) {
3608 const char *errfmt; 3608 const char *errfmt;
3609 char *output = Cmd_Exec(expr->value.str, &errfmt); 3609 char *output = Cmd_Exec(expr->value.str, &errfmt);
3610 if (errfmt != NULL) 3610 if (errfmt != NULL)
3611 Error(errfmt, expr->value.str); 3611 Error(errfmt, expr->value.str);
3612 Expr_SetValueOwn(expr, output); 3612 Expr_SetValueOwn(expr, output);
3613 } 3613 }
3614 3614
3615 return AMR_OK; 3615 return AMR_OK;
3616} 3616}
3617#endif 3617#endif
3618 3618
3619static void 3619static void
3620LogBeforeApply(const ModChain *ch, const char *mod) 3620LogBeforeApply(const ModChain *ch, const char *mod)
3621{ 3621{
3622 const Expr *expr = ch->expr; 3622 const Expr *expr = ch->expr;
3623 char vflags_str[VarFlags_ToStringSize]; 3623 char vflags_str[VarFlags_ToStringSize];
3624 Boolean is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch); 3624 Boolean is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
3625 3625
3626 /* At this point, only the first character of the modifier can 3626 /* At this point, only the first character of the modifier can
3627 * be used since the end of the modifier is not yet known. */ 3627 * be used since the end of the modifier is not yet known. */
3628 debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n", 3628 debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n",
3629 expr->var->name.str, mod[0], is_single_char ? "" : "...", 3629 expr->var->name.str, mod[0], is_single_char ? "" : "...",
3630 expr->value.str, 3630 expr->value.str,
3631 VarEvalFlags_ToString(expr->eflags), 3631 VarEvalFlags_ToString(expr->eflags),
3632 VarFlags_ToString(vflags_str, expr->var->flags), 3632 VarFlags_ToString(vflags_str, expr->var->flags),
3633 ExprDefined_Name[expr->defined]); 3633 ExprDefined_Name[expr->defined]);
3634} 3634}
3635 3635
3636static void 3636static void
3637LogAfterApply(const ModChain *ch, const char *p, const char *mod) 3637LogAfterApply(const ModChain *ch, const char *p, const char *mod)
3638{ 3638{
3639 const Expr *expr = ch->expr; 3639 const Expr *expr = ch->expr;
3640 const char *value = expr->value.str; 3640 const char *value = expr->value.str;
3641 char vflags_str[VarFlags_ToStringSize]; 3641 char vflags_str[VarFlags_ToStringSize];
3642 const char *quot = value == var_Error ? "" : "\""; 3642 const char *quot = value == var_Error ? "" : "\"";
3643 3643
3644 debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n", 3644 debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n",
3645 expr->var->name.str, (int)(p - mod), mod, 3645 expr->var->name.str, (int)(p - mod), mod,
3646 quot, value == var_Error ? "error" : value, quot, 3646 quot, value == var_Error ? "error" : value, quot,
3647 VarEvalFlags_ToString(expr->eflags), 3647 VarEvalFlags_ToString(expr->eflags),
3648 VarFlags_ToString(vflags_str, expr->var->flags), 3648 VarFlags_ToString(vflags_str, expr->var->flags),
3649 ExprDefined_Name[expr->defined]); 3649 ExprDefined_Name[expr->defined]);
3650} 3650}
3651 3651
3652static ApplyModifierResult 3652static ApplyModifierResult
3653ApplyModifier(const char **pp, ModChain *ch) 3653ApplyModifier(const char **pp, ModChain *ch)
3654{ 3654{
3655 switch (**pp) { 3655 switch (**pp) {
3656 case '!': 3656 case '!':
3657 return ApplyModifier_ShellCommand(pp, ch); 3657 return ApplyModifier_ShellCommand(pp, ch);
3658 case ':': 3658 case ':':
3659 return ApplyModifier_Assign(pp, ch); 3659 return ApplyModifier_Assign(pp, ch);
3660 case '?': 3660 case '?':
3661 return ApplyModifier_IfElse(pp, ch); 3661 return ApplyModifier_IfElse(pp, ch);
3662 case '@': 3662 case '@':
3663 return ApplyModifier_Loop(pp, ch); 3663 return ApplyModifier_Loop(pp, ch);
3664 case '[': 3664 case '[':
3665 return ApplyModifier_Words(pp, ch); 3665 return ApplyModifier_Words(pp, ch);
3666 case '_': 3666 case '_':
3667 return ApplyModifier_Remember(pp, ch); 3667 return ApplyModifier_Remember(pp, ch);
3668#ifndef NO_REGEX 3668#ifndef NO_REGEX
3669 case 'C': 3669 case 'C':
3670 return ApplyModifier_Regex(pp, ch); 3670 return ApplyModifier_Regex(pp, ch);
3671#endif 3671#endif
3672 case 'D': 3672 case 'D':
3673 return ApplyModifier_Defined(pp, ch); 3673 return ApplyModifier_Defined(pp, ch);
3674 case 'E': 3674 case 'E':
3675 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix); 3675 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
3676 case 'g': 3676 case 'g':
3677 return ApplyModifier_Gmtime(pp, ch); 3677 return ApplyModifier_Gmtime(pp, ch);
3678 case 'H': 3678 case 'H':
3679 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head); 3679 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
3680 case 'h': 3680 case 'h':
3681 return ApplyModifier_Hash(pp, ch); 3681 return ApplyModifier_Hash(pp, ch);
3682 case 'L': 3682 case 'L':
3683 return ApplyModifier_Literal(pp, ch); 3683 return ApplyModifier_Literal(pp, ch);
3684 case 'l': 3684 case 'l':
3685 return ApplyModifier_Localtime(pp, ch); 3685 return ApplyModifier_Localtime(pp, ch);
3686 case 'M': 3686 case 'M':
3687 case 'N': 3687 case 'N':
3688 return ApplyModifier_Match(pp, ch); 3688 return ApplyModifier_Match(pp, ch);
3689 case 'O': 3689 case 'O':
3690 return ApplyModifier_Order(pp, ch); 3690 return ApplyModifier_Order(pp, ch);
3691 case 'P': 3691 case 'P':
3692 return ApplyModifier_Path(pp, ch); 3692 return ApplyModifier_Path(pp, ch);
3693 case 'Q': 3693 case 'Q':
3694 case 'q': 3694 case 'q':
3695 return ApplyModifier_Quote(pp, ch); 3695 return ApplyModifier_Quote(pp, ch);
3696 case 'R': 3696 case 'R':
3697 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root); 3697 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
3698 case 'r': 3698 case 'r':
3699 return ApplyModifier_Range(pp, ch); 3699 return ApplyModifier_Range(pp, ch);
3700 case 'S': 3700 case 'S':
3701 return ApplyModifier_Subst(pp, ch); 3701 return ApplyModifier_Subst(pp, ch);
3702#ifdef SUNSHCMD 3702#ifdef SUNSHCMD
3703 case 's': 3703 case 's':
3704 return ApplyModifier_SunShell(pp, ch); 3704 return ApplyModifier_SunShell(pp, ch);
3705#endif 3705#endif
3706 case 'T': 3706 case 'T':
3707 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail); 3707 return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
3708 case 't': 3708 case 't':
3709 return ApplyModifier_To(pp, ch); 3709 return ApplyModifier_To(pp, ch);
3710 case 'U': 3710 case 'U':
3711 return ApplyModifier_Defined(pp, ch); 3711 return ApplyModifier_Defined(pp, ch);
3712 case 'u': 3712 case 'u':
3713 return ApplyModifier_Unique(pp, ch); 3713 return ApplyModifier_Unique(pp, ch);
3714 default: 3714 default:
3715 return AMR_UNKNOWN; 3715 return AMR_UNKNOWN;
3716 } 3716 }
3717} 3717}
3718 3718
3719static void ApplyModifiers(Expr *, const char **, char, char); 3719static void ApplyModifiers(Expr *, const char **, char, char);
3720 3720
3721typedef enum ApplyModifiersIndirectResult { 3721typedef enum ApplyModifiersIndirectResult {
3722 /* The indirect modifiers have been applied successfully. */ 3722 /* The indirect modifiers have been applied successfully. */
3723 AMIR_CONTINUE, 3723 AMIR_CONTINUE,
3724 /* Fall back to the SysV modifier. */ 3724 /* Fall back to the SysV modifier. */
3725 AMIR_SYSV, 3725 AMIR_SYSV,
3726 /* Error out. */ 3726 /* Error out. */
3727 AMIR_OUT 3727 AMIR_OUT
3728} ApplyModifiersIndirectResult; 3728} ApplyModifiersIndirectResult;
3729 3729
3730/* 3730/*
3731 * While expanding a variable expression, expand and apply indirect modifiers, 3731 * While expanding a variable expression, expand and apply indirect modifiers,
3732 * such as in ${VAR:${M_indirect}}. 3732 * such as in ${VAR:${M_indirect}}.
3733 * 3733 *
3734 * All indirect modifiers of a group must come from a single variable 3734 * All indirect modifiers of a group must come from a single variable
3735 * expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not. 3735 * expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
3736 * 3736 *
3737 * Multiple groups of indirect modifiers can be chained by separating them 3737 * Multiple groups of indirect modifiers can be chained by separating them
3738 * with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers. 3738 * with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
3739 * 3739 *
3740 * If the variable expression is not followed by ch->endc or ':', fall 3740 * If the variable expression is not followed by ch->endc or ':', fall
3741 * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}. 3741 * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
3742 */ 3742 */
3743static ApplyModifiersIndirectResult 3743static ApplyModifiersIndirectResult
3744ApplyModifiersIndirect(ModChain *ch, const char **pp) 3744ApplyModifiersIndirect(ModChain *ch, const char **pp)
3745{ 3745{
3746 Expr *expr = ch->expr; 3746 Expr *expr = ch->expr;
3747 const char *p = *pp; 3747 const char *p = *pp;
3748 FStr mods; 3748 FStr mods;
3749 3749
3750 (void)Var_Parse(&p, expr->scope, expr->eflags, &mods); 3750 (void)Var_Parse(&p, expr->scope, expr->eflags, &mods);
3751 /* TODO: handle errors */ 3751 /* TODO: handle errors */
3752 3752
3753 if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, ch)) { 3753 if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, ch)) {
3754 FStr_Done(&mods); 3754 FStr_Done(&mods);
3755 return AMIR_SYSV; 3755 return AMIR_SYSV;
3756 } 3756 }
3757 3757
3758 DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n", 3758 DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
3759 mods.str, (int)(p - *pp), *pp); 3759 mods.str, (int)(p - *pp), *pp);
3760 3760
3761 if (mods.str[0] != '\0') { 3761 if (mods.str[0] != '\0') {
3762 const char *modsp = mods.str; 3762 const char *modsp = mods.str;
3763 ApplyModifiers(expr, &modsp, '\0', '\0'); 3763 ApplyModifiers(expr, &modsp, '\0', '\0');
3764 if (expr->value.str == var_Error || *modsp != '\0') { 3764 if (expr->value.str == var_Error || *modsp != '\0') {
3765 FStr_Done(&mods); 3765 FStr_Done(&mods);
3766 *pp = p; 3766 *pp = p;
3767 return AMIR_OUT; /* error already reported */ 3767 return AMIR_OUT; /* error already reported */
3768 } 3768 }
3769 } 3769 }
3770 FStr_Done(&mods); 3770 FStr_Done(&mods);
3771 3771
3772 if (*p == ':') 3772 if (*p == ':')
3773 p++; 3773 p++;
3774 else if (*p == '\0' && ch->endc != '\0') { 3774 else if (*p == '\0' && ch->endc != '\0') {
3775 Error("Unclosed variable expression after indirect " 3775 Error("Unclosed variable expression after indirect "
3776 "modifier, expecting '%c' for variable \"%s\"", 3776 "modifier, expecting '%c' for variable \"%s\"",
3777 ch->endc, expr->var->name.str); 3777 ch->endc, expr->var->name.str);
3778 *pp = p; 3778 *pp = p;
3779 return AMIR_OUT; 3779 return AMIR_OUT;
3780 } 3780 }
3781 3781
3782 *pp = p; 3782 *pp = p;
3783 return AMIR_CONTINUE; 3783 return AMIR_CONTINUE;
3784} 3784}
3785 3785
3786static ApplyModifierResult 3786static ApplyModifierResult
3787ApplySingleModifier(const char **pp, ModChain *ch) 3787ApplySingleModifier(const char **pp, ModChain *ch)
3788{ 3788{
3789 ApplyModifierResult res; 3789 ApplyModifierResult res;
3790 const char *mod = *pp; 3790 const char *mod = *pp;
3791 const char *p = *pp; 3791 const char *p = *pp;
3792 3792
3793 if (DEBUG(VAR)) 3793 if (DEBUG(VAR))
3794 LogBeforeApply(ch, mod); 3794 LogBeforeApply(ch, mod);
3795 3795
3796 res = ApplyModifier(&p, ch); 3796 res = ApplyModifier(&p, ch);
3797 3797
3798#ifdef SYSVVARSUB 3798#ifdef SYSVVARSUB
3799 if (res == AMR_UNKNOWN) { 3799 if (res == AMR_UNKNOWN) {
3800 assert(p == mod); 3800 assert(p == mod);
3801 res = ApplyModifier_SysV(&p, ch); 3801 res = ApplyModifier_SysV(&p, ch);
3802 } 3802 }
3803#endif 3803#endif
3804 3804
3805 if (res == AMR_UNKNOWN) { 3805 if (res == AMR_UNKNOWN) {
3806 /* 3806 /*
3807 * Guess the end of the current modifier. 3807 * Guess the end of the current modifier.
3808 * XXX: Skipping the rest of the modifier hides 3808 * XXX: Skipping the rest of the modifier hides
3809 * errors and leads to wrong results. 3809 * errors and leads to wrong results.
3810 * Parsing should rather stop here. 3810 * Parsing should rather stop here.
3811 */ 3811 */
3812 for (p++; !IsDelimiter(*p, ch) && *p != '\0'; p++) 3812 for (p++; !IsDelimiter(*p, ch) && *p != '\0'; p++)
3813 continue; 3813 continue;
3814 Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"", 3814 Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
3815 (int)(p - mod), mod); 3815 (int)(p - mod), mod);
3816 Expr_SetValueRefer(ch->expr, var_Error); 3816 Expr_SetValueRefer(ch->expr, var_Error);
3817 } 3817 }
3818 if (res == AMR_CLEANUP || res == AMR_BAD) { 3818 if (res == AMR_CLEANUP || res == AMR_BAD) {
3819 *pp = p; 3819 *pp = p;
3820 return res; 3820 return res;
3821 } 3821 }
3822 3822
3823 if (DEBUG(VAR)) 3823 if (DEBUG(VAR))
3824 LogAfterApply(ch, p, mod); 3824 LogAfterApply(ch, p, mod);
3825 3825
3826 if (*p == '\0' && ch->endc != '\0') { 3826 if (*p == '\0' && ch->endc != '\0') {
3827 Error( 3827 Error(
3828 "Unclosed variable expression, expecting '%c' for " 3828 "Unclosed variable expression, expecting '%c' for "
3829 "modifier \"%.*s\" of variable \"%s\" with value \"%s\"", 3829 "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
3830 ch->endc, 3830 ch->endc,
3831 (int)(p - mod), mod, 3831 (int)(p - mod), mod,
3832 ch->expr->var->name.str, ch->expr->value.str); 3832 ch->expr->var->name.str, ch->expr->value.str);
3833 } else if (*p == ':') { 3833 } else if (*p == ':') {
3834 p++; 3834 p++;
3835 } else if (opts.strict && *p != '\0' && *p != ch->endc) { 3835 } else if (opts.strict && *p != '\0' && *p != ch->endc) {
3836 Parse_Error(PARSE_FATAL, 3836 Parse_Error(PARSE_FATAL,
3837 "Missing delimiter ':' after modifier \"%.*s\"", 3837 "Missing delimiter ':' after modifier \"%.*s\"",
3838 (int)(p - mod), mod); 3838 (int)(p - mod), mod);
3839 /* 3839 /*
3840 * TODO: propagate parse error to the enclosing 3840 * TODO: propagate parse error to the enclosing
3841 * expression 3841 * expression
3842 */ 3842 */
3843 } 3843 }
3844 *pp = p; 3844 *pp = p;
3845 return AMR_OK; 3845 return AMR_OK;
3846} 3846}
3847 3847
3848/* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */ 3848/* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
3849static void 3849static void
3850ApplyModifiers( 3850ApplyModifiers(
3851 Expr *expr, 3851 Expr *expr,
3852 const char **pp, /* the parsing position, updated upon return */ 3852 const char **pp, /* the parsing position, updated upon return */
3853 char startc, /* '(' or '{'; or '\0' for indirect modifiers */ 3853 char startc, /* '(' or '{'; or '\0' for indirect modifiers */
3854 char endc /* ')' or '}'; or '\0' for indirect modifiers */ 3854 char endc /* ')' or '}'; or '\0' for indirect modifiers */
3855) 3855)
3856{ 3856{
3857 ModChain ch = { 3857 ModChain ch = {
3858 expr, 3858 expr,
3859 startc, 3859 startc,
3860 endc, 3860 endc,
3861 ' ', /* .sep */ 3861 ' ', /* .sep */
3862 FALSE /* .oneBigWord */ 3862 FALSE /* .oneBigWord */
3863 }; 3863 };
3864 const char *p; 3864 const char *p;
3865 const char *mod; 3865 const char *mod;
3866 3866
3867 assert(startc == '(' || startc == '{' || startc == '\0'); 3867 assert(startc == '(' || startc == '{' || startc == '\0');
3868 assert(endc == ')' || endc == '}' || endc == '\0'); 3868 assert(endc == ')' || endc == '}' || endc == '\0');
3869 assert(expr->value.str != NULL); 3869 assert(expr->value.str != NULL);
3870 3870
3871 p = *pp; 3871 p = *pp;
3872 3872
3873 if (*p == '\0' && endc != '\0') { 3873 if (*p == '\0' && endc != '\0') {
3874 Error( 3874 Error(
3875 "Unclosed variable expression (expecting '%c') for \"%s\"", 3875 "Unclosed variable expression (expecting '%c') for \"%s\"",
3876 ch.endc, expr->var->name.str); 3876 ch.endc, expr->var->name.str);
3877 goto cleanup; 3877 goto cleanup;
3878 } 3878 }
3879 3879
3880 while (*p != '\0' && *p != endc) { 3880 while (*p != '\0' && *p != endc) {
3881 ApplyModifierResult res; 3881 ApplyModifierResult res;
3882 3882
3883 if (*p == '$') { 3883 if (*p == '$') {
3884 ApplyModifiersIndirectResult amir = 3884 ApplyModifiersIndirectResult amir =
3885 ApplyModifiersIndirect(&ch, &p); 3885 ApplyModifiersIndirect(&ch, &p);
3886 if (amir == AMIR_CONTINUE) 3886 if (amir == AMIR_CONTINUE)
3887 continue; 3887 continue;
3888 if (amir == AMIR_OUT) 3888 if (amir == AMIR_OUT)
3889 break; 3889 break;
3890 /* 3890 /*
3891 * It's neither '${VAR}:' nor '${VAR}}'. Try to parse 3891 * It's neither '${VAR}:' nor '${VAR}}'. Try to parse
3892 * it as a SysV modifier, as that is the only modifier 3892 * it as a SysV modifier, as that is the only modifier
3893 * that can start with '$'. 3893 * that can start with '$'.
3894 */ 3894 */
3895 } 3895 }
3896 3896
3897 mod = p; 3897 mod = p;
3898 3898
3899 res = ApplySingleModifier(&p, &ch); 3899 res = ApplySingleModifier(&p, &ch);
3900 if (res == AMR_CLEANUP) 3900 if (res == AMR_CLEANUP)
3901 goto cleanup; 3901 goto cleanup;
3902 if (res == AMR_BAD) 3902 if (res == AMR_BAD)
3903 goto bad_modifier; 3903 goto bad_modifier;
3904 } 3904 }
3905 3905
3906 *pp = p; 3906 *pp = p;
3907 assert(expr->value.str != NULL); /* Use var_Error or varUndefined. */ 3907 assert(expr->value.str != NULL); /* Use var_Error or varUndefined. */
3908 return; 3908 return;
3909 3909
3910bad_modifier: 3910bad_modifier:
3911 /* XXX: The modifier end is only guessed. */ 3911 /* XXX: The modifier end is only guessed. */
3912 Error("Bad modifier \":%.*s\" for variable \"%s\"", 3912 Error("Bad modifier \":%.*s\" for variable \"%s\"",
3913 (int)strcspn(mod, ":)}"), mod, expr->var->name.str); 3913 (int)strcspn(mod, ":)}"), mod, expr->var->name.str);
3914 3914
3915cleanup: 3915cleanup:
3916 /* 3916 /*
3917 * TODO: Use p + strlen(p) instead, to stop parsing immediately. 3917 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
3918 * 3918 *
3919 * In the unit tests, this generates a few unterminated strings in the 3919 * In the unit tests, this generates a few unterminated strings in the
3920 * shell commands though. Instead of producing these unfinished 3920 * shell commands though. Instead of producing these unfinished
3921 * strings, commands with evaluation errors should not be run at all. 3921 * strings, commands with evaluation errors should not be run at all.
3922 * 3922 *
3923 * To make that happen, Var_Subst must report the actual errors 3923 * To make that happen, Var_Subst must report the actual errors
3924 * instead of returning VPR_OK unconditionally. 3924 * instead of returning VPR_OK unconditionally.
3925 */ 3925 */
3926 *pp = p; 3926 *pp = p;
3927 Expr_SetValueRefer(expr, var_Error); 3927 Expr_SetValueRefer(expr, var_Error);
3928} 3928}
3929 3929
3930/* 3930/*
3931 * Only four of the local variables are treated specially as they are the 3931 * Only four of the local variables are treated specially as they are the
3932 * only four that will be set when dynamic sources are expanded. 3932 * only four that will be set when dynamic sources are expanded.
3933 */ 3933 */
3934static Boolean 3934static Boolean
3935VarnameIsDynamic(const char *name, size_t len) 3935VarnameIsDynamic(const char *name, size_t len)
3936{ 3936{
3937 if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) { 3937 if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
3938 switch (name[0]) { 3938 switch (name[0]) {
3939 case '@': 3939 case '@':
3940 case '%': 3940 case '%':
3941 case '*': 3941 case '*':
3942 case '!': 3942 case '!':
3943 return TRUE; 3943 return TRUE;
3944 } 3944 }
3945 return FALSE; 3945 return FALSE;
3946 } 3946 }
3947 3947
3948 if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) { 3948 if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
3949 return strcmp(name, ".TARGET") == 0 || 3949 return strcmp(name, ".TARGET") == 0 ||
3950 strcmp(name, ".ARCHIVE") == 0 || 3950 strcmp(name, ".ARCHIVE") == 0 ||
3951 strcmp(name, ".PREFIX") == 0 || 3951 strcmp(name, ".PREFIX") == 0 ||
3952 strcmp(name, ".MEMBER") == 0; 3952 strcmp(name, ".MEMBER") == 0;
3953 } 3953 }
3954 3954
3955 return FALSE; 3955 return FALSE;
3956} 3956}
3957 3957
3958static const char * 3958static const char *
3959UndefinedShortVarValue(char varname, const GNode *scope) 3959UndefinedShortVarValue(char varname, const GNode *scope)
3960{ 3960{
3961 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) { 3961 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
3962 /* 3962 /*
3963 * If substituting a local variable in a non-local scope, 3963 * If substituting a local variable in a non-local scope,
3964 * assume it's for dynamic source stuff. We have to handle 3964 * assume it's for dynamic source stuff. We have to handle
3965 * this specially and return the longhand for the variable 3965 * this specially and return the longhand for the variable
3966 * with the dollar sign escaped so it makes it back to the 3966 * with the dollar sign escaped so it makes it back to the
3967 * caller. Only four of the local variables are treated 3967 * caller. Only four of the local variables are treated
3968 * specially as they are the only four that will be set 3968 * specially as they are the only four that will be set
3969 * when dynamic sources are expanded. 3969 * when dynamic sources are expanded.
3970 */ 3970 */
3971 switch (varname) { 3971 switch (varname) {
3972 case '@': 3972 case '@':
3973 return "$(.TARGET)"; 3973 return "$(.TARGET)";
3974 case '%': 3974 case '%':
3975 return "$(.MEMBER)"; 3975 return "$(.MEMBER)";
3976 case '*': 3976 case '*':
3977 return "$(.PREFIX)"; 3977 return "$(.PREFIX)";
3978 case '!': 3978 case '!':
3979 return "$(.ARCHIVE)"; 3979 return "$(.ARCHIVE)";
3980 } 3980 }
3981 } 3981 }
3982 return NULL; 3982 return NULL;
3983} 3983}
3984 3984
3985/* 3985/*
3986 * Parse a variable name, until the end character or a colon, whichever 3986 * Parse a variable name, until the end character or a colon, whichever
3987 * comes first. 3987 * comes first.
3988 */ 3988 */
3989static char * 3989static char *
3990ParseVarname(const char **pp, char startc, char endc, 3990ParseVarname(const char **pp, char startc, char endc,
3991 GNode *scope, VarEvalFlags eflags, 3991 GNode *scope, VarEvalFlags eflags,
3992 size_t *out_varname_len) 3992 size_t *out_varname_len)
3993{ 3993{
3994 Buffer buf; 3994 Buffer buf;
3995 const char *p = *pp; 3995 const char *p = *pp;
3996 int depth = 0; /* Track depth so we can spot parse errors. */ 3996 int depth = 0; /* Track depth so we can spot parse errors. */
3997 3997
3998 Buf_Init(&buf); 3998 Buf_Init(&buf);
3999 3999
4000 while (*p != '\0') { 4000 while (*p != '\0') {
4001 if ((*p == endc || *p == ':') && depth == 0) 4001 if ((*p == endc || *p == ':') && depth == 0)
4002 break; 4002 break;
4003 if (*p == startc) 4003 if (*p == startc)
4004 depth++; 4004 depth++;
4005 if (*p == endc) 4005 if (*p == endc)
4006 depth--; 4006 depth--;
4007 4007
4008 /* A variable inside a variable, expand. */ 4008 /* A variable inside a variable, expand. */
4009 if (*p == '$') { 4009 if (*p == '$') {
4010 FStr nested_val; 4010 FStr nested_val;
4011 (void)Var_Parse(&p, scope, eflags, &nested_val); 4011 (void)Var_Parse(&p, scope, eflags, &nested_val);
4012 /* TODO: handle errors */ 4012 /* TODO: handle errors */
4013 Buf_AddStr(&buf, nested_val.str); 4013 Buf_AddStr(&buf, nested_val.str);
4014 FStr_Done(&nested_val); 4014 FStr_Done(&nested_val);
4015 } else { 4015 } else {
4016 Buf_AddByte(&buf, *p); 4016 Buf_AddByte(&buf, *p);
4017 p++; 4017 p++;
4018 } 4018 }
4019 } 4019 }
4020 *pp = p; 4020 *pp = p;
4021 *out_varname_len = buf.len; 4021 *out_varname_len = buf.len;
4022 return Buf_DoneData(&buf); 4022 return Buf_DoneData(&buf);
4023} 4023}
4024 4024
4025static VarParseResult 4025static VarParseResult
4026ValidShortVarname(char varname, const char *start) 4026ValidShortVarname(char varname, const char *start)
4027{ 4027{
4028 if (varname != '$' && varname != ':' && varname != '}' && 4028 if (varname != '$' && varname != ':' && varname != '}' &&
4029 varname != ')' && varname != '\0') 4029 varname != ')' && varname != '\0')
4030 return VPR_OK; 4030 return VPR_OK;
4031 4031
4032 if (!opts.strict) 4032 if (!opts.strict)
4033 return VPR_ERR; /* XXX: Missing error message */ 4033 return VPR_ERR; /* XXX: Missing error message */
4034 4034
4035 if (varname == '$') 4035 if (varname == '$')
4036 Parse_Error(PARSE_FATAL, 4036 Parse_Error(PARSE_FATAL,
4037 "To escape a dollar, use \\$, not $$, at \"%s\"", start); 4037 "To escape a dollar, use \\$, not $$, at \"%s\"", start);
4038 else if (varname == '\0') 4038 else if (varname == '\0')
4039 Parse_Error(PARSE_FATAL, "Dollar followed by nothing"); 4039 Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
4040 else 4040 else
4041 Parse_Error(PARSE_FATAL, 4041 Parse_Error(PARSE_FATAL,
4042 "Invalid variable name '%c', at \"%s\"", varname, start); 4042 "Invalid variable name '%c', at \"%s\"", varname, start);
4043 4043
4044 return VPR_ERR; 4044 return VPR_ERR;
4045} 4045}
4046 4046
4047/* 4047/*
4048 * Parse a single-character variable name such as in $V or $@. 4048 * Parse a single-character variable name such as in $V or $@.
4049 * Return whether to continue parsing. 4049 * Return whether to continue parsing.
4050 */ 4050 */
4051static Boolean 4051static Boolean
4052ParseVarnameShort(char varname, const char **pp, GNode *scope, 4052ParseVarnameShort(char varname, const char **pp, GNode *scope,
4053 VarEvalFlags eflags, 4053 VarEvalFlags eflags,
4054 VarParseResult *out_FALSE_res, const char **out_FALSE_val, 4054 VarParseResult *out_FALSE_res, const char **out_FALSE_val,
4055 Var **out_TRUE_var) 4055 Var **out_TRUE_var)
4056{ 4056{
4057 char name[2]; 4057 char name[2];
4058 Var *v; 4058 Var *v;
4059 VarParseResult vpr; 4059 VarParseResult vpr;
4060 4060
4061 vpr = ValidShortVarname(varname, *pp); 4061 vpr = ValidShortVarname(varname, *pp);
4062 if (vpr != VPR_OK) { 4062 if (vpr != VPR_OK) {
4063 (*pp)++; 4063 (*pp)++;
4064 *out_FALSE_res = vpr; 4064 *out_FALSE_res = vpr;
4065 *out_FALSE_val = var_Error; 4065 *out_FALSE_val = var_Error;
4066 return FALSE; 4066 return FALSE;
4067 } 4067 }
4068 4068
4069 name[0] = varname; 4069 name[0] = varname;
4070 name[1] = '\0'; 4070 name[1] = '\0';
4071 v = VarFind(name, scope, TRUE); 4071 v = VarFind(name, scope, TRUE);
4072 if (v == NULL) { 4072 if (v == NULL) {
4073 const char *val; 4073 const char *val;
4074 *pp += 2; 4074 *pp += 2;
4075 4075
4076 val = UndefinedShortVarValue(varname, scope); 4076 val = UndefinedShortVarValue(varname, scope);
4077 if (val == NULL) 4077 if (val == NULL)
4078 val = eflags.undefErr ? var_Error : varUndefined; 4078 val = eflags.undefErr ? var_Error : varUndefined;
4079 4079
4080 if (opts.strict && val == var_Error) { 4080 if (opts.strict && val == var_Error) {
4081 Parse_Error(PARSE_FATAL, 4081 Parse_Error(PARSE_FATAL,
4082 "Variable \"%s\" is undefined", name); 4082 "Variable \"%s\" is undefined", name);
4083 *out_FALSE_res = VPR_ERR; 4083 *out_FALSE_res = VPR_ERR;
4084 *out_FALSE_val = val; 4084 *out_FALSE_val = val;
4085 return FALSE; 4085 return FALSE;
4086 } 4086 }
4087 4087
4088 /* 4088 /*
4089 * XXX: This looks completely wrong. 4089 * XXX: This looks completely wrong.
4090 * 4090 *
4091 * If undefined expressions are not allowed, this should 4091 * If undefined expressions are not allowed, this should
4092 * rather be VPR_ERR instead of VPR_UNDEF, together with an 4092 * rather be VPR_ERR instead of VPR_UNDEF, together with an
4093 * error message. 4093 * error message.
4094 * 4094 *
4095 * If undefined expressions are allowed, this should rather 4095 * If undefined expressions are allowed, this should rather
4096 * be VPR_UNDEF instead of VPR_OK. 4096 * be VPR_UNDEF instead of VPR_OK.
4097 */ 4097 */
4098 *out_FALSE_res = eflags.undefErr ? VPR_UNDEF : VPR_OK; 4098 *out_FALSE_res = eflags.undefErr ? VPR_UNDEF : VPR_OK;
4099 *out_FALSE_val = val; 4099 *out_FALSE_val = val;
4100 return FALSE; 4100 return FALSE;
4101 } 4101 }
4102 4102
4103 *out_TRUE_var = v; 4103 *out_TRUE_var = v;
4104 return TRUE; 4104 return TRUE;
4105} 4105}
4106 4106
4107/* Find variables like @F or <D. */ 4107/* Find variables like @F or <D. */
4108static Var * 4108static Var *
4109FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope, 4109FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope,
4110 const char **out_extraModifiers) 4110 const char **out_extraModifiers)
4111{ 4111{
4112 /* Only resolve these variables if scope is a "real" target. */ 4112 /* Only resolve these variables if scope is a "real" target. */
4113 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) 4113 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
4114 return NULL; 4114 return NULL;
4115 4115
4116 if (namelen != 2) 4116 if (namelen != 2)
4117 return NULL; 4117 return NULL;
4118 if (varname[1] != 'F' && varname[1] != 'D') 4118 if (varname[1] != 'F' && varname[1] != 'D')
4119 return NULL; 4119 return NULL;
4120 if (strchr("@%?*!<>", varname[0]) == NULL) 4120 if (strchr("@%?*!<>", varname[0]) == NULL)
4121 return NULL; 4121 return NULL;
4122 4122
4123 { 4123 {
4124 char name[] = { varname[0], '\0' }; 4124 char name[] = { varname[0], '\0' };
4125 Var *v = VarFind(name, scope, FALSE); 4125 Var *v = VarFind(name, scope, FALSE);
4126 4126
4127 if (v != NULL) { 4127 if (v != NULL) {
4128 if (varname[1] == 'D') { 4128 if (varname[1] == 'D') {
4129 *out_extraModifiers = "H:"; 4129 *out_extraModifiers = "H:";
4130 } else { /* F */ 4130 } else { /* F */
4131 *out_extraModifiers = "T:"; 4131 *out_extraModifiers = "T:";
4132 } 4132 }
4133 } 4133 }
4134 return v; 4134 return v;
4135 } 4135 }
4136} 4136}
4137 4137
4138static VarParseResult 4138static VarParseResult
4139EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname, 4139EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname,
4140 VarEvalFlags eflags, 4140 VarEvalFlags eflags,
4141 FStr *out_val) 4141 FStr *out_val)
4142{ 4142{
4143 if (dynamic) { 4143 if (dynamic) {
4144 *out_val = FStr_InitOwn(bmake_strsedup(start, p)); 4144 *out_val = FStr_InitOwn(bmake_strsedup(start, p));
4145 free(varname); 4145 free(varname);
4146 return VPR_OK; 4146 return VPR_OK;
4147 } 4147 }
4148 4148
4149 if (eflags.undefErr && opts.strict) { 4149 if (eflags.undefErr && opts.strict) {
4150 Parse_Error(PARSE_FATAL, 4150 Parse_Error(PARSE_FATAL,
4151 "Variable \"%s\" is undefined", varname); 4151 "Variable \"%s\" is undefined", varname);
4152 free(varname); 4152 free(varname);
4153 *out_val = FStr_InitRefer(var_Error); 4153 *out_val = FStr_InitRefer(var_Error);
4154 return VPR_ERR; 4154 return VPR_ERR;
4155 } 4155 }
4156 4156
4157 if (eflags.undefErr) { 4157 if (eflags.undefErr) {
4158 free(varname); 4158 free(varname);
4159 *out_val = FStr_InitRefer(var_Error); 4159 *out_val = FStr_InitRefer(var_Error);
4160 return VPR_UNDEF; /* XXX: Should be VPR_ERR instead. */ 4160 return VPR_UNDEF; /* XXX: Should be VPR_ERR instead. */
4161 } 4161 }
4162 4162
4163 free(varname); 4163 free(varname);
4164 *out_val = FStr_InitRefer(varUndefined); 4164 *out_val = FStr_InitRefer(varUndefined);
4165 return VPR_OK; 4165 return VPR_OK;
4166} 4166}
4167 4167
4168/* 4168/*
4169 * Parse a long variable name enclosed in braces or parentheses such as $(VAR) 4169 * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
4170 * or ${VAR}, up to the closing brace or parenthesis, or in the case of 4170 * or ${VAR}, up to the closing brace or parenthesis, or in the case of
4171 * ${VAR:Modifiers}, up to the ':' that starts the modifiers. 4171 * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
4172 * Return whether to continue parsing. 4172 * Return whether to continue parsing.
4173 */ 4173 */
4174static Boolean 4174static Boolean
4175ParseVarnameLong( 4175ParseVarnameLong(
4176 const char *p, 4176 const char *p,
4177 char startc, 4177 char startc,
4178 GNode *scope, 4178 GNode *scope,
4179 VarEvalFlags eflags, 4179 VarEvalFlags eflags,
4180 4180
4181 const char **out_FALSE_pp, 4181 const char **out_FALSE_pp,
4182 VarParseResult *out_FALSE_res, 4182 VarParseResult *out_FALSE_res,
4183 FStr *out_FALSE_val, 4183 FStr *out_FALSE_val,
4184 4184
4185 char *out_TRUE_endc, 4185 char *out_TRUE_endc,
4186 const char **out_TRUE_p, 4186 const char **out_TRUE_p,
4187 Var **out_TRUE_v, 4187 Var **out_TRUE_v,
4188 Boolean *out_TRUE_haveModifier, 4188 Boolean *out_TRUE_haveModifier,
4189 const char **out_TRUE_extraModifiers, 4189 const char **out_TRUE_extraModifiers,
4190 Boolean *out_TRUE_dynamic, 4190 Boolean *out_TRUE_dynamic,
4191 ExprDefined *out_TRUE_exprDefined 4191 ExprDefined *out_TRUE_exprDefined
4192) 4192)
4193{ 4193{
4194 size_t namelen; 4194 size_t namelen;
4195 char *varname; 4195 char *varname;
4196 Var *v; 4196 Var *v;
4197 Boolean haveModifier; 4197 Boolean haveModifier;
4198 Boolean dynamic = FALSE; 4198 Boolean dynamic = FALSE;
4199 4199
4200 const char *const start = p; 4200 const char *const start = p;
4201 char endc = startc == '(' ? ')' : '}'; 4201 char endc = startc == '(' ? ')' : '}';
4202 4202
4203 p += 2; /* skip "${" or "$(" or "y(" */ 4203 p += 2; /* skip "${" or "$(" or "y(" */
4204 varname = ParseVarname(&p, startc, endc, scope, eflags, &namelen); 4204 varname = ParseVarname(&p, startc, endc, scope, eflags, &namelen);
4205 4205
4206 if (*p == ':') { 4206 if (*p == ':') {
4207 haveModifier = TRUE; 4207 haveModifier = TRUE;
4208 } else if (*p == endc) { 4208 } else if (*p == endc) {
4209 haveModifier = FALSE; 4209 haveModifier = FALSE;
4210 } else { 4210 } else {
4211 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname); 4211 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
4212 free(varname); 4212 free(varname);
4213 *out_FALSE_pp = p; 4213 *out_FALSE_pp = p;
4214 *out_FALSE_val = FStr_InitRefer(var_Error); 4214 *out_FALSE_val = FStr_InitRefer(var_Error);
4215 *out_FALSE_res = VPR_ERR; 4215 *out_FALSE_res = VPR_ERR;
4216 return FALSE; 4216 return FALSE;
4217 } 4217 }
4218 4218
4219 v = VarFind(varname, scope, TRUE); 4219 v = VarFind(varname, scope, TRUE);
4220 4220
4221 /* At this point, p points just after the variable name, 4221 /* At this point, p points just after the variable name,
4222 * either at ':' or at endc. */ 4222 * either at ':' or at endc. */
4223 4223
4224 if (v == NULL) { 4224 if (v == NULL) {
4225 v = FindLocalLegacyVar(varname, namelen, scope, 4225 v = FindLocalLegacyVar(varname, namelen, scope,
4226 out_TRUE_extraModifiers); 4226 out_TRUE_extraModifiers);
4227 } 4227 }
4228 4228
4229 if (v == NULL) { 4229 if (v == NULL) {
4230 /* 4230 /*
4231 * Defer expansion of dynamic variables if they appear in 4231 * Defer expansion of dynamic variables if they appear in
4232 * non-local scope since they are not defined there. 4232 * non-local scope since they are not defined there.
4233 */ 4233 */
4234 dynamic = VarnameIsDynamic(varname, namelen) && 4234 dynamic = VarnameIsDynamic(varname, namelen) &&
4235 (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL); 4235 (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
4236 4236
4237 if (!haveModifier) { 4237 if (!haveModifier) {
4238 p++; /* skip endc */ 4238 p++; /* skip endc */
4239 *out_FALSE_pp = p; 4239 *out_FALSE_pp = p;
4240 *out_FALSE_res = EvalUndefined(dynamic, start, p, 4240 *out_FALSE_res = EvalUndefined(dynamic, start, p,
4241 varname, eflags, out_FALSE_val); 4241 varname, eflags, out_FALSE_val);
4242 return FALSE; 4242 return FALSE;
4243 } 4243 }
4244 4244
4245 /* 4245 /*
4246 * The variable expression is based on an undefined variable. 4246 * The variable expression is based on an undefined variable.
4247 * Nevertheless it needs a Var, for modifiers that access the 4247 * Nevertheless it needs a Var, for modifiers that access the
4248 * variable name, such as :L or :?. 4248 * variable name, such as :L or :?.
4249 * 4249 *
4250 * Most modifiers leave this expression in the "undefined" 4250 * Most modifiers leave this expression in the "undefined"
4251 * state (VES_UNDEF), only a few modifiers like :D, :U, :L, 4251 * state (VES_UNDEF), only a few modifiers like :D, :U, :L,
4252 * :P turn this undefined expression into a defined 4252 * :P turn this undefined expression into a defined
4253 * expression (VES_DEF). 4253 * expression (VES_DEF).
4254 * 4254 *
4255 * In the end, after applying all modifiers, if the expression 4255 * In the end, after applying all modifiers, if the expression
4256 * is still undefined, Var_Parse will return an empty string 4256 * is still undefined, Var_Parse will return an empty string
4257 * instead of the actually computed value. 4257 * instead of the actually computed value.
4258 */ 4258 */
4259 v = VarNew(FStr_InitOwn(varname), "", VFL_NONE); 4259 v = VarNew(FStr_InitOwn(varname), "", VFL_NONE);
4260 *out_TRUE_exprDefined = DEF_UNDEF; 4260 *out_TRUE_exprDefined = DEF_UNDEF;
4261 } else 4261 } else
4262 free(varname); 4262 free(varname);
4263 4263
4264 *out_TRUE_endc = endc; 4264 *out_TRUE_endc = endc;
4265 *out_TRUE_p = p; 4265 *out_TRUE_p = p;
4266 *out_TRUE_v = v; 4266 *out_TRUE_v = v;
4267 *out_TRUE_haveModifier = haveModifier; 4267 *out_TRUE_haveModifier = haveModifier;
4268 *out_TRUE_dynamic = dynamic; 4268 *out_TRUE_dynamic = dynamic;
4269 return TRUE; 4269 return TRUE;
4270} 4270}
4271 4271
4272/* Free the environment variable now since we own it. */ 4272/* Free the environment variable now since we own it. */
4273static void 4273static void
4274FreeEnvVar(Var *v, FStr *inout_val) 4274FreeEnvVar(Var *v, FStr *inout_val)
4275{ 4275{
4276 char *varValue = Buf_DoneData(&v->val); 4276 char *varValue = Buf_DoneData(&v->val);
4277 if (inout_val->str == varValue) 4277 if (inout_val->str == varValue)
4278 inout_val->freeIt = varValue; 4278 inout_val->freeIt = varValue;
4279 else 4279 else
4280 free(varValue); 4280 free(varValue);
4281 4281
4282 FStr_Done(&v->name); 4282 FStr_Done(&v->name);
4283 free(v); 4283 free(v);
4284} 4284}
4285 4285
4286/* 4286/*
4287 * Given the start of a variable expression (such as $v, $(VAR), 4287 * Given the start of a variable expression (such as $v, $(VAR),
4288 * ${VAR:Mpattern}), extract the variable name and value, and the modifiers, 4288 * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
4289 * if any. While doing that, apply the modifiers to the value of the 4289 * if any. While doing that, apply the modifiers to the value of the
4290 * expression, forming its final value. A few of the modifiers such as :!cmd! 4290 * expression, forming its final value. A few of the modifiers such as :!cmd!
4291 * or ::= have side effects. 4291 * or ::= have side effects.
4292 * 4292 *
4293 * Input: 4293 * Input:
4294 * *pp The string to parse. 4294 * *pp The string to parse.
4295 * When parsing a condition in ParseEmptyArg, it may also 4295 * When parsing a condition in ParseEmptyArg, it may also
4296 * point to the "y" of "empty(VARNAME:Modifiers)", which 4296 * point to the "y" of "empty(VARNAME:Modifiers)", which
4297 * is syntactically the same. 4297 * is syntactically the same.
4298 * scope The scope for finding variables 4298 * scope The scope for finding variables
4299 * eflags Control the exact details of parsing 4299 * eflags Control the exact details of parsing
4300 * 4300 *
4301 * Output: 4301 * Output:
4302 * *pp The position where to continue parsing. 4302 * *pp The position where to continue parsing.
4303 * TODO: After a parse error, the value of *pp is 4303 * TODO: After a parse error, the value of *pp is
4304 * unspecified. It may not have been updated at all, 4304 * unspecified. It may not have been updated at all,
4305 * point to some random character in the string, to the 4305 * point to some random character in the string, to the
4306 * location of the parse error, or at the end of the 4306 * location of the parse error, or at the end of the
4307 * string. 4307 * string.
4308 * *out_val The value of the variable expression, never NULL. 4308 * *out_val The value of the variable expression, never NULL.
4309 * *out_val var_Error if there was a parse error. 4309 * *out_val var_Error if there was a parse error.
4310 * *out_val var_Error if the base variable of the expression was 4310 * *out_val var_Error if the base variable of the expression was
4311 * undefined, eflags has undefErr set, and none of 4311 * undefined, eflags has undefErr set, and none of
4312 * the modifiers turned the undefined expression into a 4312 * the modifiers turned the undefined expression into a
4313 * defined expression. 4313 * defined expression.
4314 * XXX: It is not guaranteed that an error message has 4314 * XXX: It is not guaranteed that an error message has
4315 * been printed. 4315 * been printed.
4316 * *out_val varUndefined if the base variable of the expression 4316 * *out_val varUndefined if the base variable of the expression
4317 * was undefined, eflags did not have undefErr set, 4317 * was undefined, eflags did not have undefErr set,
4318 * and none of the modifiers turned the undefined 4318 * and none of the modifiers turned the undefined
4319 * expression into a defined expression. 4319 * expression into a defined expression.
4320 * XXX: It is not guaranteed that an error message has 4320 * XXX: It is not guaranteed that an error message has
4321 * been printed. 4321 * been printed.
4322 */ 4322 */
4323VarParseResult 4323VarParseResult
4324Var_Parse(const char **pp, GNode *scope, VarEvalFlags eflags, FStr *out_val) 4324Var_Parse(const char **pp, GNode *scope, VarEvalFlags eflags, FStr *out_val)
4325{ 4325{
4326 const char *p = *pp; 4326 const char *p = *pp;
4327 const char *const start = p; 4327 const char *const start = p;
4328 /* TRUE if have modifiers for the variable. */ 4328 /* TRUE if have modifiers for the variable. */
4329 Boolean haveModifier; 4329 Boolean haveModifier;
4330 /* Starting character if variable in parens or braces. */ 4330 /* Starting character if variable in parens or braces. */
4331 char startc; 4331 char startc;
4332 /* Ending character if variable in parens or braces. */ 4332 /* Ending character if variable in parens or braces. */
4333 char endc; 4333 char endc;
4334 /* 4334 /*
4335 * TRUE if the variable is local and we're expanding it in a 4335 * TRUE if the variable is local and we're expanding it in a
4336 * non-local scope. This is done to support dynamic sources. 4336 * non-local scope. This is done to support dynamic sources.
4337 * The result is just the expression, unaltered. 4337 * The result is just the expression, unaltered.
4338 */ 4338 */
4339 Boolean dynamic; 4339 Boolean dynamic;
4340 const char *extramodifiers; 4340 const char *extramodifiers;
4341 Var *v; 4341 Var *v;
4342 4342
4343 Expr expr = { 4343 Expr expr = {
4344 NULL, 4344 NULL,
4345#if defined(lint) 
4346 /* NetBSD lint cannot fully parse C99 struct initializers. */ 
4347 { NULL, NULL }, 
4348#else 
4349 FStr_InitRefer(NULL), 4345 FStr_InitRefer(NULL),
4350#endif 
4351 eflags, 4346 eflags,
4352 scope, 4347 scope,
4353 DEF_REGULAR 4348 DEF_REGULAR
4354 }; 4349 };
4355 4350
4356 DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, 4351 DEBUG2(VAR, "Var_Parse: %s (%s)\n", start,
4357 VarEvalFlags_ToString(eflags)); 4352 VarEvalFlags_ToString(eflags));
4358 4353
4359 *out_val = FStr_InitRefer(NULL); 4354 *out_val = FStr_InitRefer(NULL);
4360 extramodifiers = NULL; /* extra modifiers to apply first */ 4355 extramodifiers = NULL; /* extra modifiers to apply first */
4361 dynamic = FALSE; 4356 dynamic = FALSE;
4362 4357
4363 /* 4358 /*
4364 * Appease GCC, which thinks that the variable might not be 4359 * Appease GCC, which thinks that the variable might not be
4365 * initialized. 4360 * initialized.
4366 */ 4361 */
4367 endc = '\0'; 4362 endc = '\0';
4368 4363
4369 startc = p[1]; 4364 startc = p[1];
4370 if (startc != '(' && startc != '{') { 4365 if (startc != '(' && startc != '{') {
4371 VarParseResult res; 4366 VarParseResult res;
4372 if (!ParseVarnameShort(startc, pp, scope, eflags, &res, 4367 if (!ParseVarnameShort(startc, pp, scope, eflags, &res,
4373 &out_val->str, &expr.var)) 4368 &out_val->str, &expr.var))
4374 return res; 4369 return res;
4375 haveModifier = FALSE; 4370 haveModifier = FALSE;
4376 p++; 4371 p++;
4377 } else { 4372 } else {
4378 VarParseResult res; 4373 VarParseResult res;
4379 if (!ParseVarnameLong(p, startc, scope, eflags, 4374 if (!ParseVarnameLong(p, startc, scope, eflags,
4380 pp, &res, out_val, 4375 pp, &res, out_val,
4381 &endc, &p, &expr.var, &haveModifier, &extramodifiers, 4376 &endc, &p, &expr.var, &haveModifier, &extramodifiers,
4382 &dynamic, &expr.defined)) 4377 &dynamic, &expr.defined))
4383 return res; 4378 return res;
4384 } 4379 }
4385 4380
4386 v = expr.var; 4381 v = expr.var;
4387 if (v->flags & VFL_IN_USE) 4382 if (v->flags & VFL_IN_USE)
4388 Fatal("Variable %s is recursive.", v->name.str); 4383 Fatal("Variable %s is recursive.", v->name.str);
4389 4384
4390 /* 4385 /*
4391 * XXX: This assignment creates an alias to the current value of the 4386 * XXX: This assignment creates an alias to the current value of the
4392 * variable. This means that as long as the value of the expression 4387 * variable. This means that as long as the value of the expression
4393 * stays the same, the value of the variable must not change. 4388 * stays the same, the value of the variable must not change.
4394 * Using the '::=' modifier, it could be possible to do exactly this. 4389 * Using the '::=' modifier, it could be possible to do exactly this.
4395 * At the bottom of this function, the resulting value is compared to 4390 * At the bottom of this function, the resulting value is compared to
4396 * the then-current value of the variable. This might also invoke 4391 * the then-current value of the variable. This might also invoke
4397 * undefined behavior. 4392 * undefined behavior.
4398 */ 4393 */
4399 expr.value = FStr_InitRefer(v->val.data); 4394 expr.value = FStr_InitRefer(v->val.data);
4400 4395
4401 /* 4396 /*
4402 * Before applying any modifiers, expand any nested expressions from 4397 * Before applying any modifiers, expand any nested expressions from
4403 * the variable value. 4398 * the variable value.
4404 */ 4399 */
4405 if (strchr(expr.value.str, '$') != NULL && eflags.wantRes) { 4400 if (strchr(expr.value.str, '$') != NULL && eflags.wantRes) {
4406 char *expanded; 4401 char *expanded;
4407 VarEvalFlags nested_eflags = eflags; 4402 VarEvalFlags nested_eflags = eflags;
4408 if (opts.strict) 4403 if (opts.strict)
4409 nested_eflags.undefErr = FALSE; 4404 nested_eflags.undefErr = FALSE;
4410 v->flags |= VFL_IN_USE; 4405 v->flags |= VFL_IN_USE;
4411 (void)Var_Subst(expr.value.str, scope, nested_eflags, 4406 (void)Var_Subst(expr.value.str, scope, nested_eflags,
4412 &expanded); 4407 &expanded);
4413 v->flags &= ~(unsigned)VFL_IN_USE; 4408 v->flags &= ~(unsigned)VFL_IN_USE;
4414 /* TODO: handle errors */ 4409 /* TODO: handle errors */
4415 Expr_SetValueOwn(&expr, expanded); 4410 Expr_SetValueOwn(&expr, expanded);
4416 } 4411 }
4417 4412
4418 if (extramodifiers != NULL) { 4413 if (extramodifiers != NULL) {
4419 const char *em = extramodifiers; 4414 const char *em = extramodifiers;
4420 ApplyModifiers(&expr, &em, '\0', '\0'); 4415 ApplyModifiers(&expr, &em, '\0', '\0');
4421 } 4416 }
4422 4417
4423 if (haveModifier) { 4418 if (haveModifier) {
4424 p++; /* Skip initial colon. */ 4419 p++; /* Skip initial colon. */
4425 ApplyModifiers(&expr, &p, startc, endc); 4420 ApplyModifiers(&expr, &p, startc, endc);
4426 } 4421 }
4427 4422
4428 if (*p != '\0') /* Skip past endc if possible. */ 4423 if (*p != '\0') /* Skip past endc if possible. */
4429 p++; 4424 p++;
4430 4425
4431 *pp = p; 4426 *pp = p;
4432 4427
4433 if (v->flags & VFL_FROM_ENV) { 4428 if (v->flags & VFL_FROM_ENV) {
4434 FreeEnvVar(v, &expr.value); 4429 FreeEnvVar(v, &expr.value);
4435 4430
4436 } else if (expr.defined != DEF_REGULAR) { 4431 } else if (expr.defined != DEF_REGULAR) {
4437 if (expr.defined == DEF_UNDEF) { 4432 if (expr.defined == DEF_UNDEF) {
4438 if (dynamic) { 4433 if (dynamic) {
4439 Expr_SetValueOwn(&expr, 4434 Expr_SetValueOwn(&expr,
4440 bmake_strsedup(start, p)); 4435 bmake_strsedup(start, p));
4441 } else { 4436 } else {
4442 /* 4437 /*
4443 * The expression is still undefined, 4438 * The expression is still undefined,
4444 * therefore discard the actual value and 4439 * therefore discard the actual value and
4445 * return an error marker instead. 4440 * return an error marker instead.
4446 */ 4441 */
4447 Expr_SetValueRefer(&expr, 4442 Expr_SetValueRefer(&expr,
4448 eflags.undefErr 4443 eflags.undefErr
4449 ? var_Error : varUndefined); 4444 ? var_Error : varUndefined);
4450 } 4445 }
4451 } 4446 }
4452 /* XXX: This is not standard memory management. */ 4447 /* XXX: This is not standard memory management. */
4453 if (expr.value.str != v->val.data) 4448 if (expr.value.str != v->val.data)
4454 Buf_Done(&v->val); 4449 Buf_Done(&v->val);
4455 FStr_Done(&v->name); 4450 FStr_Done(&v->name);
4456 free(v); 4451 free(v);
4457 } 4452 }
4458 *out_val = expr.value; 4453 *out_val = expr.value;
4459 return VPR_OK; /* XXX: Is not correct in all cases */ 4454 return VPR_OK; /* XXX: Is not correct in all cases */
4460} 4455}
4461 4456
4462static void 4457static void
4463VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalFlags eflags) 4458VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalFlags eflags)
4464{ 4459{
4465 /* A dollar sign may be escaped with another dollar sign. */ 4460 /* A dollar sign may be escaped with another dollar sign. */
4466 if (save_dollars && eflags.keepDollar) 4461 if (save_dollars && eflags.keepDollar)
4467 Buf_AddByte(res, '$'); 4462 Buf_AddByte(res, '$');
4468 Buf_AddByte(res, '$'); 4463 Buf_AddByte(res, '$');
4469 *pp += 2; 4464 *pp += 2;
4470} 4465}
4471 4466
4472static void 4467static void
4473VarSubstExpr(const char **pp, Buffer *buf, GNode *scope, 4468VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
4474 VarEvalFlags eflags, Boolean *inout_errorReported) 4469 VarEvalFlags eflags, Boolean *inout_errorReported)
4475{ 4470{
4476 const char *p = *pp; 4471 const char *p = *pp;
4477 const char *nested_p = p; 4472 const char *nested_p = p;
4478 FStr val; 4473 FStr val;
4479 4474
4480 (void)Var_Parse(&nested_p, scope, eflags, &val); 4475 (void)Var_Parse(&nested_p, scope, eflags, &val);
4481 /* TODO: handle errors */ 4476 /* TODO: handle errors */
4482 4477
4483 if (val.str == var_Error || val.str == varUndefined) { 4478 if (val.str == var_Error || val.str == varUndefined) {
4484 if (!eflags.keepUndef) { 4479 if (!eflags.keepUndef) {
4485 p = nested_p; 4480 p = nested_p;
4486 } else if (eflags.undefErr || val.str == var_Error) { 4481 } else if (eflags.undefErr || val.str == var_Error) {
4487 4482
4488 /* 4483 /*
4489 * XXX: This condition is wrong. If val == var_Error, 4484 * XXX: This condition is wrong. If val == var_Error,
4490 * this doesn't necessarily mean there was an undefined 4485 * this doesn't necessarily mean there was an undefined
4491 * variable. It could equally well be a parse error; 4486 * variable. It could equally well be a parse error;
4492 * see unit-tests/varmod-order.exp. 4487 * see unit-tests/varmod-order.exp.
4493 */ 4488 */
4494 4489
4495 /* 4490 /*
4496 * If variable is undefined, complain and skip the 4491 * If variable is undefined, complain and skip the
4497 * variable. The complaint will stop us from doing 4492 * variable. The complaint will stop us from doing
4498 * anything when the file is parsed. 4493 * anything when the file is parsed.
4499 */ 4494 */
4500 if (!*inout_errorReported) { 4495 if (!*inout_errorReported) {
4501 Parse_Error(PARSE_FATAL, 4496 Parse_Error(PARSE_FATAL,
4502 "Undefined variable \"%.*s\"", 4497 "Undefined variable \"%.*s\"",
4503 (int)(size_t)(nested_p - p), p); 4498 (int)(size_t)(nested_p - p), p);
4504 } 4499 }
4505 p = nested_p; 4500 p = nested_p;
4506 *inout_errorReported = TRUE; 4501 *inout_errorReported = TRUE;
4507 } else { 4502 } else {
4508 /* Copy the initial '$' of the undefined expression, 4503 /* Copy the initial '$' of the undefined expression,
4509 * thereby deferring expansion of the expression, but 4504 * thereby deferring expansion of the expression, but
4510 * expand nested expressions if already possible. 4505 * expand nested expressions if already possible.
4511 * See unit-tests/varparse-undef-partial.mk. */ 4506 * See unit-tests/varparse-undef-partial.mk. */
4512 Buf_AddByte(buf, *p); 4507 Buf_AddByte(buf, *p);
4513 p++; 4508 p++;
4514 } 4509 }
4515 } else { 4510 } else {
4516 p = nested_p; 4511 p = nested_p;
4517 Buf_AddStr(buf, val.str); 4512 Buf_AddStr(buf, val.str);
4518 } 4513 }
4519 4514
4520 FStr_Done(&val); 4515 FStr_Done(&val);
4521 4516
4522 *pp = p; 4517 *pp = p;
4523} 4518}
4524 4519
4525/* 4520/*
4526 * Skip as many characters as possible -- either to the end of the string 4521 * Skip as many characters as possible -- either to the end of the string
4527 * or to the next dollar sign (variable expression). 4522 * or to the next dollar sign (variable expression).
4528 */ 4523 */
4529static void 4524static void
4530VarSubstPlain(const char **pp, Buffer *res) 4525VarSubstPlain(const char **pp, Buffer *res)
4531{ 4526{
4532 const char *p = *pp; 4527 const char *p = *pp;
4533 const char *start = p; 4528 const char *start = p;
4534 4529
4535 for (p++; *p != '$' && *p != '\0'; p++) 4530 for (p++; *p != '$' && *p != '\0'; p++)
4536 continue; 4531 continue;
4537 Buf_AddBytesBetween(res, start, p); 4532 Buf_AddBytesBetween(res, start, p);
4538 *pp = p; 4533 *pp = p;
4539} 4534}
4540 4535
4541/* 4536/*
4542 * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the 4537 * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
4543 * given string. 4538 * given string.
4544 * 4539 *
4545 * Input: 4540 * Input:
4546 * str The string in which the variable expressions are 4541 * str The string in which the variable expressions are
4547 * expanded. 4542 * expanded.
4548 * scope The scope in which to start searching for 4543 * scope The scope in which to start searching for
4549 * variables. The other scopes are searched as well. 4544 * variables. The other scopes are searched as well.
4550 * eflags Special effects during expansion. 4545 * eflags Special effects during expansion.
4551 */ 4546 */
4552VarParseResult 4547VarParseResult
4553Var_Subst(const char *str, GNode *scope, VarEvalFlags eflags, char **out_res) 4548Var_Subst(const char *str, GNode *scope, VarEvalFlags eflags, char **out_res)
4554{ 4549{
4555 const char *p = str; 4550 const char *p = str;
4556 Buffer res; 4551 Buffer res;
4557 4552
4558 /* Set true if an error has already been reported, 4553 /* Set true if an error has already been reported,
4559 * to prevent a plethora of messages when recursing */ 4554 * to prevent a plethora of messages when recursing */
4560 /* XXX: Why is the 'static' necessary here? */ 4555 /* XXX: Why is the 'static' necessary here? */
4561 static Boolean errorReported; 4556 static Boolean errorReported;
4562 4557
4563 Buf_Init(&res); 4558 Buf_Init(&res);
4564 errorReported = FALSE; 4559 errorReported = FALSE;
4565 4560
4566 while (*p != '\0') { 4561 while (*p != '\0') {
4567 if (p[0] == '$' && p[1] == '$') 4562 if (p[0] == '$' && p[1] == '$')
4568 VarSubstDollarDollar(&p, &res, eflags); 4563 VarSubstDollarDollar(&p, &res, eflags);
4569 else if (p[0] == '$') 4564 else if (p[0] == '$')
4570 VarSubstExpr(&p, &res, scope, eflags, &errorReported); 4565 VarSubstExpr(&p, &res, scope, eflags, &errorReported);
4571 else 4566 else
4572 VarSubstPlain(&p, &res); 4567 VarSubstPlain(&p, &res);
4573 } 4568 }
4574 4569
4575 *out_res = Buf_DoneDataCompact(&res); 4570 *out_res = Buf_DoneDataCompact(&res);
4576 return VPR_OK; 4571 return VPR_OK;
4577} 4572}
4578 4573
4579/* Initialize the variables module. */ 4574/* Initialize the variables module. */
4580void 4575void
4581Var_Init(void) 4576Var_Init(void)
4582{ 4577{
4583 SCOPE_INTERNAL = GNode_New("Internal"); 4578 SCOPE_INTERNAL = GNode_New("Internal");
4584 SCOPE_GLOBAL = GNode_New("Global"); 4579 SCOPE_GLOBAL = GNode_New("Global");
4585 SCOPE_CMDLINE = GNode_New("Command"); 4580 SCOPE_CMDLINE = GNode_New("Command");
4586} 4581}
4587 4582
4588/* Clean up the variables module. */ 4583/* Clean up the variables module. */
4589void 4584void
4590Var_End(void) 4585Var_End(void)
4591{ 4586{
4592 Var_Stats(); 4587 Var_Stats();
4593} 4588}
4594 4589
4595void 4590void
4596Var_Stats(void) 4591Var_Stats(void)
4597{ 4592{
4598 HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables"); 4593 HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
4599} 4594}
4600 4595
4601/* Print all variables in a scope, sorted by name. */ 4596/* Print all variables in a scope, sorted by name. */
4602void 4597void
4603Var_Dump(GNode *scope) 4598Var_Dump(GNode *scope)
4604{ 4599{
4605 Vector /* of const char * */ vec; 4600 Vector /* of const char * */ vec;
4606 HashIter hi; 4601 HashIter hi;
4607 size_t i; 4602 size_t i;
4608 const char **varnames; 4603 const char **varnames;
4609 4604
4610 Vector_Init(&vec, sizeof(const char *)); 4605 Vector_Init(&vec, sizeof(const char *));
4611 4606
4612 HashIter_Init(&hi, &scope->vars); 4607 HashIter_Init(&hi, &scope->vars);
4613 while (HashIter_Next(&hi) != NULL) 4608 while (HashIter_Next(&hi) != NULL)
4614 *(const char **)Vector_Push(&vec) = hi.entry->key; 4609 *(const char **)Vector_Push(&vec) = hi.entry->key;
4615 varnames = vec.items; 4610 varnames = vec.items;
4616 4611
4617 qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc); 4612 qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
4618 4613
4619 for (i = 0; i < vec.len; i++) { 4614 for (i = 0; i < vec.len; i++) {
4620 const char *varname = varnames[i]; 4615 const char *varname = varnames[i];
4621 Var *var = HashTable_FindValue(&scope->vars, varname); 4616 Var *var = HashTable_FindValue(&scope->vars, varname);
4622 debug_printf("%-16s = %s\n", varname, var->val.data); 4617 debug_printf("%-16s = %s\n", varname, var->val.data);
4623 } 4618 }
4624 4619
4625 Vector_Done(&vec); 4620 Vector_Done(&vec);
4626} 4621}