var.c revision 1.914 1 1.914 rillig /* $NetBSD: var.c,v 1.914 2021/04/10 22:35:02 rillig Exp $ */
2 1.11 christos
3 1.1 cgd /*
4 1.15 christos * Copyright (c) 1988, 1989, 1990, 1993
5 1.15 christos * The Regents of the University of California. All rights reserved.
6 1.80 agc *
7 1.80 agc * This code is derived from software contributed to Berkeley by
8 1.80 agc * Adam de Boor.
9 1.80 agc *
10 1.80 agc * Redistribution and use in source and binary forms, with or without
11 1.80 agc * modification, are permitted provided that the following conditions
12 1.80 agc * are met:
13 1.80 agc * 1. Redistributions of source code must retain the above copyright
14 1.80 agc * notice, this list of conditions and the following disclaimer.
15 1.80 agc * 2. Redistributions in binary form must reproduce the above copyright
16 1.80 agc * notice, this list of conditions and the following disclaimer in the
17 1.80 agc * documentation and/or other materials provided with the distribution.
18 1.80 agc * 3. Neither the name of the University nor the names of its contributors
19 1.80 agc * may be used to endorse or promote products derived from this software
20 1.80 agc * without specific prior written permission.
21 1.80 agc *
22 1.80 agc * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 1.80 agc * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 1.80 agc * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 1.80 agc * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 1.80 agc * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 1.80 agc * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 1.80 agc * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 1.80 agc * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 1.80 agc * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 1.80 agc * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 1.80 agc * SUCH DAMAGE.
33 1.80 agc */
34 1.80 agc
35 1.80 agc /*
36 1.1 cgd * Copyright (c) 1989 by Berkeley Softworks
37 1.1 cgd * All rights reserved.
38 1.1 cgd *
39 1.1 cgd * This code is derived from software contributed to Berkeley by
40 1.1 cgd * Adam de Boor.
41 1.1 cgd *
42 1.1 cgd * Redistribution and use in source and binary forms, with or without
43 1.1 cgd * modification, are permitted provided that the following conditions
44 1.1 cgd * are met:
45 1.1 cgd * 1. Redistributions of source code must retain the above copyright
46 1.1 cgd * notice, this list of conditions and the following disclaimer.
47 1.1 cgd * 2. Redistributions in binary form must reproduce the above copyright
48 1.1 cgd * notice, this list of conditions and the following disclaimer in the
49 1.1 cgd * documentation and/or other materials provided with the distribution.
50 1.1 cgd * 3. All advertising materials mentioning features or use of this software
51 1.1 cgd * must display the following acknowledgement:
52 1.1 cgd * This product includes software developed by the University of
53 1.1 cgd * California, Berkeley and its contributors.
54 1.1 cgd * 4. Neither the name of the University nor the names of its contributors
55 1.1 cgd * may be used to endorse or promote products derived from this software
56 1.1 cgd * without specific prior written permission.
57 1.1 cgd *
58 1.1 cgd * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 1.1 cgd * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 1.1 cgd * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 1.1 cgd * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 1.1 cgd * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 1.1 cgd * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 1.1 cgd * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 1.1 cgd * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 1.1 cgd * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 1.1 cgd * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 1.1 cgd * SUCH DAMAGE.
69 1.1 cgd */
70 1.1 cgd
71 1.592 rillig /*
72 1.592 rillig * Handling of variables and the expressions formed from them.
73 1.592 rillig *
74 1.592 rillig * Variables are set using lines of the form VAR=value. Both the variable
75 1.592 rillig * name and the value can contain references to other variables, by using
76 1.592 rillig * expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
77 1.1 cgd *
78 1.1 cgd * Interface:
79 1.592 rillig * Var_Init Initialize this module.
80 1.592 rillig *
81 1.592 rillig * Var_End Clean up the module.
82 1.592 rillig *
83 1.798 rillig * Var_Set
84 1.798 rillig * Var_SetExpand
85 1.798 rillig * Set the value of the variable, creating it if
86 1.592 rillig * necessary.
87 1.592 rillig *
88 1.794 rillig * Var_Append
89 1.794 rillig * Var_AppendExpand
90 1.794 rillig * Append more characters to the variable, creating it if
91 1.592 rillig * necessary. A space is placed between the old value and
92 1.592 rillig * the new one.
93 1.1 cgd *
94 1.796 rillig * Var_Exists
95 1.796 rillig * Var_ExistsExpand
96 1.796 rillig * See if a variable exists.
97 1.1 cgd *
98 1.592 rillig * Var_Value Return the unexpanded value of a variable, or NULL if
99 1.592 rillig * the variable is undefined.
100 1.592 rillig *
101 1.592 rillig * Var_Subst Substitute all variable expressions in a string.
102 1.592 rillig *
103 1.592 rillig * Var_Parse Parse a variable expression such as ${VAR:Mpattern}.
104 1.1 cgd *
105 1.797 rillig * Var_Delete
106 1.797 rillig * Var_DeleteExpand
107 1.797 rillig * Delete a variable.
108 1.1 cgd *
109 1.725 rillig * Var_ReexportVars
110 1.725 rillig * Export some or even all variables to the environment
111 1.592 rillig * of this process and its child processes.
112 1.1 cgd *
113 1.592 rillig * Var_Export Export the variable to the environment of this process
114 1.592 rillig * and its child processes.
115 1.1 cgd *
116 1.592 rillig * Var_UnExport Don't export the variable anymore.
117 1.1 cgd *
118 1.1 cgd * Debugging:
119 1.592 rillig * Var_Stats Print out hashing statistics if in -dh mode.
120 1.592 rillig *
121 1.802 rillig * Var_Dump Print out all variables defined in the given scope.
122 1.1 cgd *
123 1.827 rillig * XXX: There's a lot of almost duplicate code in these functions that only
124 1.827 rillig * differs in subtle details that are not mentioned in the manual page.
125 1.1 cgd */
126 1.1 cgd
127 1.630 rillig #include <sys/stat.h>
128 1.31 gwr #ifndef NO_REGEX
129 1.630 rillig #include <sys/types.h>
130 1.630 rillig #include <regex.h>
131 1.17 christos #endif
132 1.631 rillig #include <errno.h>
133 1.630 rillig #include <inttypes.h>
134 1.630 rillig #include <limits.h>
135 1.630 rillig #include <time.h>
136 1.630 rillig
137 1.630 rillig #include "make.h"
138 1.630 rillig #include "dir.h"
139 1.630 rillig #include "job.h"
140 1.630 rillig #include "metachar.h"
141 1.1 cgd
142 1.512 rillig /* "@(#)var.c 8.3 (Berkeley) 3/19/94" */
143 1.914 rillig MAKE_RCSID("$NetBSD: var.c,v 1.914 2021/04/10 22:35:02 rillig Exp $");
144 1.228 rillig
145 1.778 rillig /*
146 1.778 rillig * Variables are defined using one of the VAR=value assignments. Their
147 1.570 rillig * value can be queried by expressions such as $V, ${VAR}, or with modifiers
148 1.570 rillig * such as ${VAR:S,from,to,g:Q}.
149 1.570 rillig *
150 1.802 rillig * There are 3 kinds of variables: scope variables, environment variables,
151 1.570 rillig * undefined variables.
152 1.570 rillig *
153 1.802 rillig * Scope variables are stored in a GNode.scope. The only way to undefine
154 1.802 rillig * a scope variable is using the .undef directive. In particular, it must
155 1.570 rillig * not be possible to undefine a variable during the evaluation of an
156 1.570 rillig * expression, or Var.name might point nowhere.
157 1.570 rillig *
158 1.570 rillig * Environment variables are temporary. They are returned by VarFind, and
159 1.570 rillig * after using them, they must be freed using VarFreeEnv.
160 1.570 rillig *
161 1.570 rillig * Undefined variables occur during evaluation of variable expressions such
162 1.570 rillig * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
163 1.570 rillig */
164 1.1 cgd typedef struct Var {
165 1.703 rillig /*
166 1.703 rillig * The name of the variable, once set, doesn't change anymore.
167 1.802 rillig * For scope variables, it aliases the corresponding HashEntry name.
168 1.703 rillig * For environment and undefined variables, it is allocated.
169 1.703 rillig */
170 1.711 rillig FStr name;
171 1.570 rillig
172 1.703 rillig /* The unexpanded value of the variable. */
173 1.703 rillig Buffer val;
174 1.902 rillig
175 1.902 rillig /* The variable came from the command line. */
176 1.902 rillig bool fromCmd: 1;
177 1.902 rillig
178 1.902 rillig /*
179 1.902 rillig * The variable comes from the environment.
180 1.902 rillig * These variables are not registered in any GNode, therefore they
181 1.902 rillig * must be freed as soon as they are not used anymore.
182 1.902 rillig */
183 1.902 rillig bool fromEnv: 1;
184 1.902 rillig
185 1.902 rillig /*
186 1.902 rillig * The variable value cannot be changed anymore, and the variable
187 1.902 rillig * cannot be deleted. Any attempts to do so are silently ignored,
188 1.902 rillig * they are logged with -dv though.
189 1.902 rillig *
190 1.902 rillig * See VAR_SET_READONLY.
191 1.902 rillig */
192 1.902 rillig bool readOnly: 1;
193 1.902 rillig
194 1.902 rillig /*
195 1.902 rillig * The variable's value is currently being used by Var_Parse or
196 1.902 rillig * Var_Subst. This marker is used to avoid endless recursion.
197 1.902 rillig */
198 1.902 rillig bool inUse: 1;
199 1.902 rillig
200 1.902 rillig /*
201 1.902 rillig * The variable is exported to the environment, to be used by child
202 1.902 rillig * processes.
203 1.902 rillig */
204 1.902 rillig bool exported: 1;
205 1.902 rillig
206 1.902 rillig /*
207 1.902 rillig * At the point where this variable was exported, it contained an
208 1.902 rillig * unresolved reference to another variable. Before any child
209 1.902 rillig * process is started, it needs to be exported again, in the hope
210 1.902 rillig * that the referenced variable can then be resolved.
211 1.902 rillig */
212 1.902 rillig bool reexport: 1;
213 1.417 rillig } Var;
214 1.1 cgd
215 1.710 rillig /*
216 1.830 rillig * Exporting variables is expensive and may leak memory, so skip it if we
217 1.830 rillig * can.
218 1.830 rillig *
219 1.830 rillig * To avoid this, it might be worth encapsulating the environment variables
220 1.830 rillig * in a separate data structure called EnvVars.
221 1.710 rillig */
222 1.710 rillig typedef enum VarExportedMode {
223 1.710 rillig VAR_EXPORTED_NONE,
224 1.710 rillig VAR_EXPORTED_SOME,
225 1.710 rillig VAR_EXPORTED_ALL
226 1.710 rillig } VarExportedMode;
227 1.710 rillig
228 1.713 rillig typedef enum UnexportWhat {
229 1.830 rillig /* Unexport the variables given by name. */
230 1.713 rillig UNEXPORT_NAMED,
231 1.830 rillig /*
232 1.830 rillig * Unexport all globals previously exported, but keep the environment
233 1.830 rillig * inherited from the parent.
234 1.830 rillig */
235 1.713 rillig UNEXPORT_ALL,
236 1.830 rillig /*
237 1.830 rillig * Unexport all globals previously exported and clear the environment
238 1.830 rillig * inherited from the parent.
239 1.830 rillig */
240 1.713 rillig UNEXPORT_ENV
241 1.713 rillig } UnexportWhat;
242 1.713 rillig
243 1.261 rillig /* Flags for pattern matching in the :S and :C modifiers */
244 1.788 rillig typedef struct VarPatternFlags {
245 1.903 rillig bool subGlobal: 1; /* 'g': replace as often as possible */
246 1.903 rillig bool subOnce: 1; /* '1': replace only once */
247 1.903 rillig bool anchorStart: 1; /* '^': match only at start of word */
248 1.903 rillig bool anchorEnd: 1; /* '$': match only at end of word */
249 1.261 rillig } VarPatternFlags;
250 1.16 christos
251 1.830 rillig /* SepBuf builds a string from words interleaved with separators. */
252 1.710 rillig typedef struct SepBuf {
253 1.710 rillig Buffer buf;
254 1.895 rillig bool needSep;
255 1.710 rillig /* Usually ' ', but see the ':ts' modifier. */
256 1.710 rillig char sep;
257 1.710 rillig } SepBuf;
258 1.710 rillig
259 1.710 rillig
260 1.710 rillig /*
261 1.710 rillig * This lets us tell if we have replaced the original environ
262 1.710 rillig * (which we cannot free).
263 1.710 rillig */
264 1.710 rillig char **savedEnv = NULL;
265 1.710 rillig
266 1.778 rillig /*
267 1.778 rillig * Special return value for Var_Parse, indicating a parse error. It may be
268 1.710 rillig * caused by an undefined variable, a syntax error in a modifier or
269 1.778 rillig * something entirely different.
270 1.778 rillig */
271 1.710 rillig char var_Error[] = "";
272 1.710 rillig
273 1.778 rillig /*
274 1.778 rillig * Special return value for Var_Parse, indicating an undefined variable in
275 1.885 rillig * a case where VarEvalFlags.undefErr is not set. This undefined variable is
276 1.710 rillig * typically a dynamic variable such as ${.TARGET}, whose expansion needs to
277 1.778 rillig * be deferred until it is defined in an actual target.
278 1.830 rillig *
279 1.885 rillig * See VarEvalFlags.keepUndef.
280 1.778 rillig */
281 1.710 rillig static char varUndefined[] = "";
282 1.710 rillig
283 1.710 rillig /*
284 1.710 rillig * Traditionally this make consumed $$ during := like any other expansion.
285 1.710 rillig * Other make's do not, and this make follows straight since 2016-01-09.
286 1.710 rillig *
287 1.895 rillig * This knob allows controlling the behavior:
288 1.895 rillig * false to consume $$ during := assignment.
289 1.895 rillig * true to preserve $$ during := assignment.
290 1.710 rillig */
291 1.710 rillig #define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
292 1.895 rillig static bool save_dollars = true;
293 1.710 rillig
294 1.710 rillig /*
295 1.807 rillig * A scope collects variable names and their values.
296 1.807 rillig *
297 1.807 rillig * The main scope is SCOPE_GLOBAL, which contains the variables that are set
298 1.807 rillig * in the makefiles. SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
299 1.807 rillig * contains some internal make variables. These internal variables can thus
300 1.807 rillig * be overridden, they can also be restored by undefining the overriding
301 1.807 rillig * variable.
302 1.807 rillig *
303 1.807 rillig * SCOPE_CMDLINE contains variables from the command line arguments. These
304 1.807 rillig * override variables from SCOPE_GLOBAL.
305 1.807 rillig *
306 1.807 rillig * There is no scope for environment variables, these are generated on-the-fly
307 1.807 rillig * whenever they are referenced. If there were such a scope, each change to
308 1.807 rillig * environment variables would have to be reflected in that scope, which may
309 1.807 rillig * be simpler or more complex than the current implementation.
310 1.807 rillig *
311 1.807 rillig * Each target has its own scope, containing the 7 target-local variables
312 1.807 rillig * .TARGET, .ALLSRC, etc. No other variables are in these scopes.
313 1.807 rillig */
314 1.807 rillig
315 1.807 rillig GNode *SCOPE_CMDLINE;
316 1.807 rillig GNode *SCOPE_GLOBAL;
317 1.807 rillig GNode *SCOPE_INTERNAL;
318 1.710 rillig
319 1.710 rillig static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
320 1.710 rillig
321 1.906 rillig static const char *VarEvalMode_Name[] = {
322 1.906 rillig "parse-only",
323 1.906 rillig "eval",
324 1.906 rillig "eval-defined",
325 1.906 rillig "eval-keep-dollar",
326 1.906 rillig "eval-keep-undefined",
327 1.906 rillig "eval-keep-dollar-and-undefined",
328 1.906 rillig };
329 1.711 rillig
330 1.904 rillig
331 1.569 rillig static Var *
332 1.901 rillig VarNew(FStr name, const char *value, bool fromEnv, bool readOnly)
333 1.569 rillig {
334 1.703 rillig size_t value_len = strlen(value);
335 1.703 rillig Var *var = bmake_malloc(sizeof *var);
336 1.744 rillig var->name = name;
337 1.703 rillig Buf_InitSize(&var->val, value_len + 1);
338 1.703 rillig Buf_AddBytes(&var->val, value, value_len);
339 1.902 rillig var->fromCmd = false;
340 1.902 rillig var->fromEnv = fromEnv;
341 1.902 rillig var->readOnly = readOnly;
342 1.902 rillig var->inUse = false;
343 1.902 rillig var->exported = false;
344 1.902 rillig var->reexport = false;
345 1.703 rillig return var;
346 1.569 rillig }
347 1.569 rillig
348 1.580 rillig static const char *
349 1.580 rillig CanonicalVarname(const char *name)
350 1.1 cgd {
351 1.703 rillig if (*name == '.' && ch_isupper(name[1])) {
352 1.703 rillig switch (name[1]) {
353 1.703 rillig case 'A':
354 1.703 rillig if (strcmp(name, ".ALLSRC") == 0)
355 1.703 rillig name = ALLSRC;
356 1.703 rillig if (strcmp(name, ".ARCHIVE") == 0)
357 1.703 rillig name = ARCHIVE;
358 1.703 rillig break;
359 1.703 rillig case 'I':
360 1.703 rillig if (strcmp(name, ".IMPSRC") == 0)
361 1.703 rillig name = IMPSRC;
362 1.703 rillig break;
363 1.703 rillig case 'M':
364 1.703 rillig if (strcmp(name, ".MEMBER") == 0)
365 1.703 rillig name = MEMBER;
366 1.703 rillig break;
367 1.703 rillig case 'O':
368 1.703 rillig if (strcmp(name, ".OODATE") == 0)
369 1.703 rillig name = OODATE;
370 1.703 rillig break;
371 1.703 rillig case 'P':
372 1.703 rillig if (strcmp(name, ".PREFIX") == 0)
373 1.703 rillig name = PREFIX;
374 1.703 rillig break;
375 1.703 rillig case 'S':
376 1.703 rillig if (strcmp(name, ".SHELL") == 0) {
377 1.780 rillig if (shellPath == NULL)
378 1.703 rillig Shell_Init();
379 1.703 rillig }
380 1.703 rillig break;
381 1.703 rillig case 'T':
382 1.703 rillig if (strcmp(name, ".TARGET") == 0)
383 1.703 rillig name = TARGET;
384 1.703 rillig break;
385 1.703 rillig }
386 1.242 rillig }
387 1.242 rillig
388 1.703 rillig /* GNU make has an additional alias $^ == ${.ALLSRC}. */
389 1.580 rillig
390 1.703 rillig return name;
391 1.580 rillig }
392 1.580 rillig
393 1.587 rillig static Var *
394 1.802 rillig GNode_FindVar(GNode *scope, const char *varname, unsigned int hash)
395 1.587 rillig {
396 1.802 rillig return HashTable_FindValueHash(&scope->vars, varname, hash);
397 1.587 rillig }
398 1.587 rillig
399 1.778 rillig /*
400 1.802 rillig * Find the variable in the scope, and maybe in other scopes as well.
401 1.580 rillig *
402 1.580 rillig * Input:
403 1.607 rillig * name name to find, is not expanded any further
404 1.802 rillig * scope scope in which to look first
405 1.895 rillig * elsewhere true to look in other scopes as well
406 1.580 rillig *
407 1.580 rillig * Results:
408 1.605 rillig * The found variable, or NULL if the variable does not exist.
409 1.605 rillig * If the variable is an environment variable, it must be freed using
410 1.605 rillig * VarFreeEnv after use.
411 1.580 rillig */
412 1.580 rillig static Var *
413 1.895 rillig VarFind(const char *name, GNode *scope, bool elsewhere)
414 1.580 rillig {
415 1.703 rillig Var *var;
416 1.703 rillig unsigned int nameHash;
417 1.703 rillig
418 1.830 rillig /* Replace '.TARGET' with '@', likewise for other local variables. */
419 1.703 rillig name = CanonicalVarname(name);
420 1.703 rillig nameHash = Hash_Hash(name);
421 1.580 rillig
422 1.802 rillig var = GNode_FindVar(scope, name, nameHash);
423 1.703 rillig if (!elsewhere)
424 1.703 rillig return var;
425 1.160 christos
426 1.802 rillig if (var == NULL && scope != SCOPE_CMDLINE)
427 1.801 rillig var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
428 1.1 cgd
429 1.802 rillig if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
430 1.801 rillig var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
431 1.802 rillig if (var == NULL && scope != SCOPE_INTERNAL) {
432 1.801 rillig /* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
433 1.801 rillig var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
434 1.703 rillig }
435 1.184 sjg }
436 1.399 rillig
437 1.703 rillig if (var == NULL) {
438 1.703 rillig char *env;
439 1.703 rillig
440 1.913 rillig /*
441 1.913 rillig * TODO: try setting an environment variable with the empty
442 1.913 rillig * name, which should be technically possible, just to see
443 1.913 rillig * how make reacts. All .for loops should be broken then.
444 1.913 rillig */
445 1.703 rillig if ((env = getenv(name)) != NULL) {
446 1.703 rillig char *varname = bmake_strdup(name);
447 1.901 rillig return VarNew(FStr_InitOwn(varname), env, true, false);
448 1.703 rillig }
449 1.1 cgd
450 1.802 rillig if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
451 1.801 rillig var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
452 1.802 rillig if (var == NULL && scope != SCOPE_INTERNAL)
453 1.801 rillig var = GNode_FindVar(SCOPE_INTERNAL, name,
454 1.703 rillig nameHash);
455 1.703 rillig return var;
456 1.703 rillig }
457 1.399 rillig
458 1.703 rillig return NULL;
459 1.1 cgd }
460 1.399 rillig
461 1.703 rillig return var;
462 1.1 cgd }
463 1.1 cgd
464 1.883 rillig /* If the variable is an environment variable, free it, including its value. */
465 1.837 rillig static void
466 1.837 rillig VarFreeEnv(Var *v)
467 1.105 christos {
468 1.902 rillig if (!v->fromEnv)
469 1.837 rillig return;
470 1.605 rillig
471 1.711 rillig FStr_Done(&v->name);
472 1.837 rillig Buf_Done(&v->val);
473 1.703 rillig free(v);
474 1.105 christos }
475 1.105 christos
476 1.831 rillig /* Add a new variable of the given name and value to the given scope. */
477 1.833 rillig static Var *
478 1.831 rillig VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
479 1.1 cgd {
480 1.802 rillig HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
481 1.831 rillig Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
482 1.901 rillig false, (flags & VAR_SET_READONLY) != 0);
483 1.703 rillig HashEntry_Set(he, v);
484 1.911 rillig DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, value);
485 1.833 rillig return v;
486 1.1 cgd }
487 1.1 cgd
488 1.736 rillig /*
489 1.802 rillig * Remove a variable from a scope, freeing all related memory as well.
490 1.736 rillig * The variable name is kept as-is, it is not expanded.
491 1.736 rillig */
492 1.736 rillig void
493 1.805 rillig Var_Delete(GNode *scope, const char *varname)
494 1.736 rillig {
495 1.802 rillig HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
496 1.736 rillig Var *v;
497 1.736 rillig
498 1.736 rillig if (he == NULL) {
499 1.802 rillig DEBUG2(VAR, "%s:delete %s (not found)\n", scope->name, varname);
500 1.736 rillig return;
501 1.736 rillig }
502 1.736 rillig
503 1.802 rillig DEBUG2(VAR, "%s:delete %s\n", scope->name, varname);
504 1.831 rillig v = he->value;
505 1.902 rillig if (v->exported)
506 1.736 rillig unsetenv(v->name.str);
507 1.736 rillig if (strcmp(v->name.str, MAKE_EXPORTED) == 0)
508 1.736 rillig var_exportedVars = VAR_EXPORTED_NONE;
509 1.736 rillig assert(v->name.freeIt == NULL);
510 1.802 rillig HashTable_DeleteEntry(&scope->vars, he);
511 1.784 rillig Buf_Done(&v->val);
512 1.736 rillig free(v);
513 1.736 rillig }
514 1.736 rillig
515 1.778 rillig /*
516 1.802 rillig * Remove a variable from a scope, freeing all related memory as well.
517 1.778 rillig * The variable name is expanded once.
518 1.778 rillig */
519 1.1 cgd void
520 1.805 rillig Var_DeleteExpand(GNode *scope, const char *name)
521 1.1 cgd {
522 1.746 rillig FStr varname = FStr_InitRefer(name);
523 1.412 rillig
524 1.746 rillig if (strchr(varname.str, '$') != NULL) {
525 1.746 rillig char *expanded;
526 1.801 rillig (void)Var_Subst(varname.str, SCOPE_GLOBAL, VARE_WANTRES,
527 1.746 rillig &expanded);
528 1.703 rillig /* TODO: handle errors */
529 1.746 rillig varname = FStr_InitOwn(expanded);
530 1.703 rillig }
531 1.397 rillig
532 1.805 rillig Var_Delete(scope, varname.str);
533 1.746 rillig FStr_Done(&varname);
534 1.1 cgd }
535 1.1 cgd
536 1.737 rillig /*
537 1.762 rillig * Undefine one or more variables from the global scope.
538 1.762 rillig * The argument is expanded exactly once and then split into words.
539 1.737 rillig */
540 1.735 rillig void
541 1.762 rillig Var_Undef(const char *arg)
542 1.735 rillig {
543 1.762 rillig VarParseResult vpr;
544 1.762 rillig char *expanded;
545 1.762 rillig Words varnames;
546 1.762 rillig size_t i;
547 1.762 rillig
548 1.762 rillig if (arg[0] == '\0') {
549 1.762 rillig Parse_Error(PARSE_FATAL,
550 1.762 rillig "The .undef directive requires an argument");
551 1.762 rillig return;
552 1.762 rillig }
553 1.735 rillig
554 1.801 rillig vpr = Var_Subst(arg, SCOPE_GLOBAL, VARE_WANTRES, &expanded);
555 1.762 rillig if (vpr != VPR_OK) {
556 1.737 rillig Parse_Error(PARSE_FATAL,
557 1.762 rillig "Error in variable names to be undefined");
558 1.762 rillig return;
559 1.762 rillig }
560 1.762 rillig
561 1.895 rillig varnames = Str_Words(expanded, false);
562 1.762 rillig if (varnames.len == 1 && varnames.words[0][0] == '\0')
563 1.762 rillig varnames.len = 0;
564 1.762 rillig
565 1.762 rillig for (i = 0; i < varnames.len; i++) {
566 1.762 rillig const char *varname = varnames.words[i];
567 1.804 rillig Global_Delete(varname);
568 1.737 rillig }
569 1.735 rillig
570 1.762 rillig Words_Free(varnames);
571 1.763 rillig free(expanded);
572 1.735 rillig }
573 1.735 rillig
574 1.895 rillig static bool
575 1.598 rillig MayExport(const char *name)
576 1.118 sjg {
577 1.703 rillig if (name[0] == '.')
578 1.895 rillig return false; /* skip internals */
579 1.703 rillig if (name[0] == '-')
580 1.895 rillig return false; /* skip misnamed variables */
581 1.703 rillig if (name[1] == '\0') {
582 1.703 rillig /*
583 1.703 rillig * A single char.
584 1.802 rillig * If it is one of the variables that should only appear in
585 1.802 rillig * local scope, skip it, else we can get Var_Subst
586 1.703 rillig * into a loop.
587 1.703 rillig */
588 1.703 rillig switch (name[0]) {
589 1.703 rillig case '@':
590 1.703 rillig case '%':
591 1.703 rillig case '*':
592 1.703 rillig case '!':
593 1.895 rillig return false;
594 1.703 rillig }
595 1.118 sjg }
596 1.895 rillig return true;
597 1.598 rillig }
598 1.598 rillig
599 1.895 rillig static bool
600 1.776 rillig ExportVarEnv(Var *v)
601 1.776 rillig {
602 1.776 rillig const char *name = v->name.str;
603 1.777 rillig char *val = v->val.data;
604 1.777 rillig char *expr;
605 1.776 rillig
606 1.902 rillig if (v->exported && !v->reexport)
607 1.895 rillig return false; /* nothing to do */
608 1.776 rillig
609 1.777 rillig if (strchr(val, '$') == NULL) {
610 1.902 rillig if (!v->exported)
611 1.776 rillig setenv(name, val, 1);
612 1.895 rillig return true;
613 1.776 rillig }
614 1.776 rillig
615 1.902 rillig if (v->inUse) {
616 1.777 rillig /*
617 1.777 rillig * We recursed while exporting in a child.
618 1.777 rillig * This isn't going to end well, just skip it.
619 1.777 rillig */
620 1.895 rillig return false;
621 1.777 rillig }
622 1.776 rillig
623 1.777 rillig /* XXX: name is injected without escaping it */
624 1.777 rillig expr = str_concat3("${", name, "}");
625 1.801 rillig (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &val);
626 1.777 rillig /* TODO: handle errors */
627 1.777 rillig setenv(name, val, 1);
628 1.777 rillig free(val);
629 1.777 rillig free(expr);
630 1.895 rillig return true;
631 1.776 rillig }
632 1.776 rillig
633 1.895 rillig static bool
634 1.776 rillig ExportVarPlain(Var *v)
635 1.598 rillig {
636 1.777 rillig if (strchr(v->val.data, '$') == NULL) {
637 1.777 rillig setenv(v->name.str, v->val.data, 1);
638 1.902 rillig v->exported = true;
639 1.902 rillig v->reexport = false;
640 1.895 rillig return true;
641 1.776 rillig }
642 1.776 rillig
643 1.777 rillig /*
644 1.777 rillig * Flag the variable as something we need to re-export.
645 1.777 rillig * No point actually exporting it now though,
646 1.777 rillig * the child process can do it at the last minute.
647 1.830 rillig * Avoid calling setenv more often than necessary since it can leak.
648 1.777 rillig */
649 1.902 rillig v->exported = true;
650 1.902 rillig v->reexport = true;
651 1.895 rillig return true;
652 1.776 rillig }
653 1.401 rillig
654 1.895 rillig static bool
655 1.776 rillig ExportVarLiteral(Var *v)
656 1.776 rillig {
657 1.902 rillig if (v->exported && !v->reexport)
658 1.895 rillig return false;
659 1.401 rillig
660 1.902 rillig if (!v->exported)
661 1.777 rillig setenv(v->name.str, v->val.data, 1);
662 1.605 rillig
663 1.895 rillig return true;
664 1.118 sjg }
665 1.118 sjg
666 1.118 sjg /*
667 1.830 rillig * Mark a single variable to be exported later for subprocesses.
668 1.776 rillig *
669 1.830 rillig * Internal variables (those starting with '.') are not exported.
670 1.776 rillig */
671 1.895 rillig static bool
672 1.776 rillig ExportVar(const char *name, VarExportMode mode)
673 1.776 rillig {
674 1.776 rillig Var *v;
675 1.776 rillig
676 1.776 rillig if (!MayExport(name))
677 1.895 rillig return false;
678 1.776 rillig
679 1.895 rillig v = VarFind(name, SCOPE_GLOBAL, false);
680 1.776 rillig if (v == NULL)
681 1.895 rillig return false;
682 1.776 rillig
683 1.776 rillig if (mode == VEM_ENV)
684 1.776 rillig return ExportVarEnv(v);
685 1.776 rillig else if (mode == VEM_PLAIN)
686 1.776 rillig return ExportVarPlain(v);
687 1.776 rillig else
688 1.776 rillig return ExportVarLiteral(v);
689 1.776 rillig }
690 1.776 rillig
691 1.776 rillig /*
692 1.765 rillig * Actually export the variables that have been marked as needing to be
693 1.765 rillig * re-exported.
694 1.118 sjg */
695 1.118 sjg void
696 1.725 rillig Var_ReexportVars(void)
697 1.118 sjg {
698 1.775 rillig char *xvarnames;
699 1.412 rillig
700 1.703 rillig /*
701 1.703 rillig * Several make implementations support this sort of mechanism for
702 1.703 rillig * tracking recursion - but each uses a different name.
703 1.703 rillig * We allow the makefiles to update MAKELEVEL and ensure
704 1.703 rillig * children see a correctly incremented value.
705 1.703 rillig */
706 1.831 rillig char tmp[21];
707 1.703 rillig snprintf(tmp, sizeof tmp, "%d", makelevel + 1);
708 1.703 rillig setenv(MAKE_LEVEL_ENV, tmp, 1);
709 1.182 christos
710 1.703 rillig if (var_exportedVars == VAR_EXPORTED_NONE)
711 1.703 rillig return;
712 1.118 sjg
713 1.703 rillig if (var_exportedVars == VAR_EXPORTED_ALL) {
714 1.703 rillig HashIter hi;
715 1.575 rillig
716 1.831 rillig /* Ouch! Exporting all variables at once is crazy. */
717 1.801 rillig HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
718 1.703 rillig while (HashIter_Next(&hi) != NULL) {
719 1.703 rillig Var *var = hi.entry->value;
720 1.765 rillig ExportVar(var->name.str, VEM_ENV);
721 1.703 rillig }
722 1.703 rillig return;
723 1.575 rillig }
724 1.369 rillig
725 1.801 rillig (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL, VARE_WANTRES,
726 1.775 rillig &xvarnames);
727 1.703 rillig /* TODO: handle errors */
728 1.775 rillig if (xvarnames[0] != '\0') {
729 1.895 rillig Words varnames = Str_Words(xvarnames, false);
730 1.703 rillig size_t i;
731 1.703 rillig
732 1.775 rillig for (i = 0; i < varnames.len; i++)
733 1.775 rillig ExportVar(varnames.words[i], VEM_ENV);
734 1.775 rillig Words_Free(varnames);
735 1.703 rillig }
736 1.775 rillig free(xvarnames);
737 1.118 sjg }
738 1.118 sjg
739 1.726 rillig static void
740 1.895 rillig ExportVars(const char *varnames, bool isExport, VarExportMode mode)
741 1.831 rillig /* TODO: try to combine the parameters 'isExport' and 'mode'. */
742 1.726 rillig {
743 1.895 rillig Words words = Str_Words(varnames, false);
744 1.727 rillig size_t i;
745 1.727 rillig
746 1.727 rillig if (words.len == 1 && words.words[0][0] == '\0')
747 1.727 rillig words.len = 0;
748 1.727 rillig
749 1.727 rillig for (i = 0; i < words.len; i++) {
750 1.727 rillig const char *varname = words.words[i];
751 1.730 rillig if (!ExportVar(varname, mode))
752 1.727 rillig continue;
753 1.727 rillig
754 1.727 rillig if (var_exportedVars == VAR_EXPORTED_NONE)
755 1.727 rillig var_exportedVars = VAR_EXPORTED_SOME;
756 1.726 rillig
757 1.765 rillig if (isExport && mode == VEM_PLAIN)
758 1.795 rillig Global_Append(MAKE_EXPORTED, varname);
759 1.726 rillig }
760 1.727 rillig Words_Free(words);
761 1.726 rillig }
762 1.726 rillig
763 1.728 rillig static void
764 1.895 rillig ExportVarsExpand(const char *uvarnames, bool isExport, VarExportMode mode)
765 1.728 rillig {
766 1.728 rillig char *xvarnames;
767 1.728 rillig
768 1.801 rillig (void)Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_WANTRES, &xvarnames);
769 1.728 rillig /* TODO: handle errors */
770 1.730 rillig ExportVars(xvarnames, isExport, mode);
771 1.728 rillig free(xvarnames);
772 1.728 rillig }
773 1.728 rillig
774 1.731 rillig /* Export the named variables, or all variables. */
775 1.118 sjg void
776 1.731 rillig Var_Export(VarExportMode mode, const char *varnames)
777 1.118 sjg {
778 1.765 rillig if (mode == VEM_PLAIN && varnames[0] == '\0') {
779 1.703 rillig var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
780 1.703 rillig return;
781 1.703 rillig }
782 1.118 sjg
783 1.895 rillig ExportVarsExpand(varnames, true, mode);
784 1.729 rillig }
785 1.729 rillig
786 1.729 rillig void
787 1.729 rillig Var_ExportVars(const char *varnames)
788 1.729 rillig {
789 1.895 rillig ExportVarsExpand(varnames, false, VEM_PLAIN);
790 1.118 sjg }
791 1.118 sjg
792 1.155 sjg
793 1.257 rillig extern char **environ;
794 1.257 rillig
795 1.700 rillig static void
796 1.714 rillig ClearEnv(void)
797 1.701 rillig {
798 1.701 rillig const char *cp;
799 1.701 rillig char **newenv;
800 1.701 rillig
801 1.701 rillig cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
802 1.701 rillig if (environ == savedEnv) {
803 1.701 rillig /* we have been here before! */
804 1.701 rillig newenv = bmake_realloc(environ, 2 * sizeof(char *));
805 1.701 rillig } else {
806 1.701 rillig if (savedEnv != NULL) {
807 1.701 rillig free(savedEnv);
808 1.701 rillig savedEnv = NULL;
809 1.701 rillig }
810 1.701 rillig newenv = bmake_malloc(2 * sizeof(char *));
811 1.701 rillig }
812 1.701 rillig
813 1.701 rillig /* Note: we cannot safely free() the original environ. */
814 1.701 rillig environ = savedEnv = newenv;
815 1.701 rillig newenv[0] = NULL;
816 1.701 rillig newenv[1] = NULL;
817 1.780 rillig if (cp != NULL && *cp != '\0')
818 1.701 rillig setenv(MAKE_LEVEL_ENV, cp, 1);
819 1.701 rillig }
820 1.701 rillig
821 1.701 rillig static void
822 1.895 rillig GetVarnamesToUnexport(bool isEnv, const char *arg,
823 1.715 rillig FStr *out_varnames, UnexportWhat *out_what)
824 1.714 rillig {
825 1.714 rillig UnexportWhat what;
826 1.739 rillig FStr varnames = FStr_InitRefer("");
827 1.714 rillig
828 1.732 rillig if (isEnv) {
829 1.732 rillig if (arg[0] != '\0') {
830 1.723 rillig Parse_Error(PARSE_FATAL,
831 1.723 rillig "The directive .unexport-env does not take "
832 1.723 rillig "arguments");
833 1.830 rillig /* continue anyway */
834 1.723 rillig }
835 1.714 rillig what = UNEXPORT_ENV;
836 1.723 rillig
837 1.732 rillig } else {
838 1.732 rillig what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
839 1.714 rillig if (what == UNEXPORT_NAMED)
840 1.739 rillig varnames = FStr_InitRefer(arg);
841 1.714 rillig }
842 1.714 rillig
843 1.714 rillig if (what != UNEXPORT_NAMED) {
844 1.714 rillig char *expanded;
845 1.714 rillig /* Using .MAKE.EXPORTED */
846 1.801 rillig (void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL,
847 1.714 rillig VARE_WANTRES, &expanded);
848 1.714 rillig /* TODO: handle errors */
849 1.739 rillig varnames = FStr_InitOwn(expanded);
850 1.714 rillig }
851 1.714 rillig
852 1.714 rillig *out_varnames = varnames;
853 1.714 rillig *out_what = what;
854 1.714 rillig }
855 1.714 rillig
856 1.714 rillig static void
857 1.713 rillig UnexportVar(const char *varname, UnexportWhat what)
858 1.700 rillig {
859 1.895 rillig Var *v = VarFind(varname, SCOPE_GLOBAL, false);
860 1.700 rillig if (v == NULL) {
861 1.708 rillig DEBUG1(VAR, "Not unexporting \"%s\" (not found)\n", varname);
862 1.700 rillig return;
863 1.700 rillig }
864 1.700 rillig
865 1.708 rillig DEBUG1(VAR, "Unexporting \"%s\"\n", varname);
866 1.902 rillig if (what != UNEXPORT_ENV && v->exported && !v->reexport)
867 1.711 rillig unsetenv(v->name.str);
868 1.902 rillig v->exported = false;
869 1.902 rillig v->reexport = false;
870 1.700 rillig
871 1.713 rillig if (what == UNEXPORT_NAMED) {
872 1.713 rillig /* Remove the variable names from .MAKE.EXPORTED. */
873 1.700 rillig /* XXX: v->name is injected without escaping it */
874 1.711 rillig char *expr = str_concat3("${" MAKE_EXPORTED ":N",
875 1.711 rillig v->name.str, "}");
876 1.700 rillig char *cp;
877 1.801 rillig (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &cp);
878 1.700 rillig /* TODO: handle errors */
879 1.792 rillig Global_Set(MAKE_EXPORTED, cp);
880 1.700 rillig free(cp);
881 1.700 rillig free(expr);
882 1.700 rillig }
883 1.700 rillig }
884 1.700 rillig
885 1.716 rillig static void
886 1.716 rillig UnexportVars(FStr *varnames, UnexportWhat what)
887 1.716 rillig {
888 1.716 rillig size_t i;
889 1.717 rillig Words words;
890 1.717 rillig
891 1.717 rillig if (what == UNEXPORT_ENV)
892 1.717 rillig ClearEnv();
893 1.716 rillig
894 1.895 rillig words = Str_Words(varnames->str, false);
895 1.716 rillig for (i = 0; i < words.len; i++) {
896 1.716 rillig const char *varname = words.words[i];
897 1.716 rillig UnexportVar(varname, what);
898 1.716 rillig }
899 1.716 rillig Words_Free(words);
900 1.716 rillig
901 1.716 rillig if (what != UNEXPORT_NAMED)
902 1.804 rillig Global_Delete(MAKE_EXPORTED);
903 1.716 rillig }
904 1.716 rillig
905 1.155 sjg /*
906 1.155 sjg * This is called when .unexport[-env] is seen.
907 1.338 rillig *
908 1.338 rillig * str must have the form "unexport[-env] varname...".
909 1.155 sjg */
910 1.155 sjg void
911 1.895 rillig Var_UnExport(bool isEnv, const char *arg)
912 1.155 sjg {
913 1.713 rillig UnexportWhat what;
914 1.714 rillig FStr varnames;
915 1.155 sjg
916 1.732 rillig GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
917 1.716 rillig UnexportVars(&varnames, what);
918 1.712 rillig FStr_Done(&varnames);
919 1.155 sjg }
920 1.155 sjg
921 1.834 rillig /*
922 1.834 rillig * When there is a variable of the same name in the command line scope, the
923 1.834 rillig * global variable would not be visible anywhere. Therefore there is no
924 1.834 rillig * point in setting it at all.
925 1.834 rillig *
926 1.834 rillig * See 'scope == SCOPE_CMDLINE' in Var_SetWithFlags.
927 1.834 rillig */
928 1.895 rillig static bool
929 1.834 rillig ExistsInCmdline(const char *name, const char *val)
930 1.834 rillig {
931 1.834 rillig Var *v;
932 1.834 rillig
933 1.895 rillig v = VarFind(name, SCOPE_CMDLINE, false);
934 1.834 rillig if (v == NULL)
935 1.895 rillig return false;
936 1.834 rillig
937 1.902 rillig if (v->fromCmd) {
938 1.911 rillig DEBUG3(VAR, "%s: %s = %s ignored!\n",
939 1.834 rillig SCOPE_GLOBAL->name, name, val);
940 1.895 rillig return true;
941 1.834 rillig }
942 1.834 rillig
943 1.837 rillig VarFreeEnv(v);
944 1.895 rillig return false;
945 1.834 rillig }
946 1.834 rillig
947 1.747 rillig /* Set the variable to the value; the name is not expanded. */
948 1.800 rillig void
949 1.805 rillig Var_SetWithFlags(GNode *scope, const char *name, const char *val,
950 1.800 rillig VarSetFlags flags)
951 1.1 cgd {
952 1.704 rillig Var *v;
953 1.142 dsl
954 1.793 rillig assert(val != NULL);
955 1.793 rillig if (name[0] == '\0') {
956 1.793 rillig DEBUG0(VAR, "SetVar: variable name is empty - ignored\n");
957 1.793 rillig return;
958 1.793 rillig }
959 1.793 rillig
960 1.834 rillig if (scope == SCOPE_GLOBAL && ExistsInCmdline(name, val))
961 1.834 rillig return;
962 1.400 rillig
963 1.704 rillig /*
964 1.802 rillig * Only look for a variable in the given scope since anything set
965 1.802 rillig * here will override anything in a lower scope, so there's not much
966 1.830 rillig * point in searching them all.
967 1.704 rillig */
968 1.895 rillig v = VarFind(name, scope, false);
969 1.704 rillig if (v == NULL) {
970 1.802 rillig if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
971 1.704 rillig /*
972 1.704 rillig * This var would normally prevent the same name being
973 1.801 rillig * added to SCOPE_GLOBAL, so delete it from there if
974 1.704 rillig * needed. Otherwise -V name may show the wrong value.
975 1.832 rillig *
976 1.835 rillig * See ExistsInCmdline.
977 1.704 rillig */
978 1.835 rillig Var_Delete(SCOPE_GLOBAL, name);
979 1.704 rillig }
980 1.833 rillig v = VarAdd(name, val, scope, flags);
981 1.704 rillig } else {
982 1.902 rillig if (v->readOnly && !(flags & VAR_SET_READONLY)) {
983 1.911 rillig DEBUG3(VAR, "%s: %s = %s ignored (read-only)\n",
984 1.802 rillig scope->name, name, val);
985 1.747 rillig return;
986 1.704 rillig }
987 1.704 rillig Buf_Empty(&v->val);
988 1.704 rillig Buf_AddStr(&v->val, val);
989 1.704 rillig
990 1.911 rillig DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, val);
991 1.902 rillig if (v->exported)
992 1.765 rillig ExportVar(name, VEM_PLAIN);
993 1.183 sjg }
994 1.833 rillig
995 1.71 thorpej /*
996 1.704 rillig * Any variables given on the command line are automatically exported
997 1.833 rillig * to the environment (as per POSIX standard), except for internals.
998 1.71 thorpej */
999 1.802 rillig if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT) &&
1000 1.704 rillig name[0] != '.') {
1001 1.902 rillig v->fromCmd = true;
1002 1.704 rillig
1003 1.704 rillig /*
1004 1.704 rillig * If requested, don't export these in the environment
1005 1.704 rillig * individually. We still put them in MAKEOVERRIDES so
1006 1.704 rillig * that the command-line settings continue to override
1007 1.704 rillig * Makefile settings.
1008 1.704 rillig */
1009 1.704 rillig if (!opts.varNoExportEnv)
1010 1.704 rillig setenv(name, val, 1);
1011 1.836 rillig /* XXX: What about .MAKE.EXPORTED? */
1012 1.836 rillig /* XXX: Why not just mark the variable for needing export,
1013 1.836 rillig * as in ExportVarPlain? */
1014 1.62 sjg
1015 1.795 rillig Global_Append(MAKEOVERRIDES, name);
1016 1.704 rillig }
1017 1.833 rillig
1018 1.704 rillig if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0)
1019 1.704 rillig save_dollars = ParseBoolean(val, save_dollars);
1020 1.205 sjg
1021 1.704 rillig if (v != NULL)
1022 1.837 rillig VarFreeEnv(v);
1023 1.1 cgd }
1024 1.1 cgd
1025 1.747 rillig /* See Var_Set for documentation. */
1026 1.747 rillig void
1027 1.805 rillig Var_SetExpandWithFlags(GNode *scope, const char *name, const char *val,
1028 1.805 rillig VarSetFlags flags)
1029 1.747 rillig {
1030 1.747 rillig const char *unexpanded_name = name;
1031 1.748 rillig FStr varname = FStr_InitRefer(name);
1032 1.747 rillig
1033 1.747 rillig assert(val != NULL);
1034 1.747 rillig
1035 1.748 rillig if (strchr(varname.str, '$') != NULL) {
1036 1.748 rillig char *expanded;
1037 1.802 rillig (void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
1038 1.747 rillig /* TODO: handle errors */
1039 1.748 rillig varname = FStr_InitOwn(expanded);
1040 1.747 rillig }
1041 1.747 rillig
1042 1.748 rillig if (varname.str[0] == '\0') {
1043 1.914 rillig DEBUG2(VAR,
1044 1.914 rillig "Var_SetExpand: variable name \"%s\" expands "
1045 1.914 rillig "to empty string, with value \"%s\" - ignored\n",
1046 1.747 rillig unexpanded_name, val);
1047 1.748 rillig } else
1048 1.805 rillig Var_SetWithFlags(scope, varname.str, val, flags);
1049 1.747 rillig
1050 1.748 rillig FStr_Done(&varname);
1051 1.747 rillig }
1052 1.747 rillig
1053 1.798 rillig void
1054 1.805 rillig Var_Set(GNode *scope, const char *name, const char *val)
1055 1.798 rillig {
1056 1.805 rillig Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
1057 1.798 rillig }
1058 1.798 rillig
1059 1.718 rillig /*
1060 1.802 rillig * Set the variable name to the value val in the given scope.
1061 1.230 rillig *
1062 1.718 rillig * If the variable doesn't yet exist, it is created.
1063 1.718 rillig * Otherwise the new value overwrites and replaces the old value.
1064 1.483 rillig *
1065 1.230 rillig * Input:
1066 1.607 rillig * name name of the variable to set, is expanded once
1067 1.230 rillig * val value to give to the variable
1068 1.802 rillig * scope scope in which to set it
1069 1.230 rillig */
1070 1.230 rillig void
1071 1.805 rillig Var_SetExpand(GNode *scope, const char *name, const char *val)
1072 1.230 rillig {
1073 1.805 rillig Var_SetExpandWithFlags(scope, name, val, VAR_SET_NONE);
1074 1.230 rillig }
1075 1.230 rillig
1076 1.791 rillig void
1077 1.792 rillig Global_Set(const char *name, const char *value)
1078 1.792 rillig {
1079 1.805 rillig Var_Set(SCOPE_GLOBAL, name, value);
1080 1.792 rillig }
1081 1.792 rillig
1082 1.792 rillig void
1083 1.791 rillig Global_SetExpand(const char *name, const char *value)
1084 1.791 rillig {
1085 1.805 rillig Var_SetExpand(SCOPE_GLOBAL, name, value);
1086 1.791 rillig }
1087 1.791 rillig
1088 1.804 rillig void
1089 1.804 rillig Global_Delete(const char *name)
1090 1.804 rillig {
1091 1.805 rillig Var_Delete(SCOPE_GLOBAL, name);
1092 1.804 rillig }
1093 1.804 rillig
1094 1.718 rillig /*
1095 1.794 rillig * Append the value to the named variable.
1096 1.794 rillig *
1097 1.794 rillig * If the variable doesn't exist, it is created. Otherwise a single space
1098 1.794 rillig * and the given value are appended.
1099 1.794 rillig */
1100 1.794 rillig void
1101 1.805 rillig Var_Append(GNode *scope, const char *name, const char *val)
1102 1.794 rillig {
1103 1.794 rillig Var *v;
1104 1.794 rillig
1105 1.802 rillig v = VarFind(name, scope, scope == SCOPE_GLOBAL);
1106 1.794 rillig
1107 1.794 rillig if (v == NULL) {
1108 1.805 rillig Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
1109 1.902 rillig } else if (v->readOnly) {
1110 1.794 rillig DEBUG1(VAR, "Ignoring append to %s since it is read-only\n",
1111 1.794 rillig name);
1112 1.902 rillig } else if (scope == SCOPE_CMDLINE || !v->fromCmd) {
1113 1.794 rillig Buf_AddByte(&v->val, ' ');
1114 1.794 rillig Buf_AddStr(&v->val, val);
1115 1.794 rillig
1116 1.911 rillig DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, v->val.data);
1117 1.794 rillig
1118 1.902 rillig if (v->fromEnv) {
1119 1.794 rillig /*
1120 1.794 rillig * If the original variable came from the environment,
1121 1.802 rillig * we have to install it in the global scope (we
1122 1.794 rillig * could place it in the environment, but then we
1123 1.794 rillig * should provide a way to export other variables...)
1124 1.794 rillig */
1125 1.902 rillig v->fromEnv = false;
1126 1.794 rillig /*
1127 1.794 rillig * This is the only place where a variable is
1128 1.794 rillig * created whose v->name is not the same as
1129 1.802 rillig * scope->vars->key.
1130 1.794 rillig */
1131 1.802 rillig HashTable_Set(&scope->vars, name, v);
1132 1.794 rillig }
1133 1.794 rillig }
1134 1.794 rillig }
1135 1.794 rillig
1136 1.794 rillig /*
1137 1.718 rillig * The variable of the given name has the given value appended to it in the
1138 1.802 rillig * given scope.
1139 1.1 cgd *
1140 1.718 rillig * If the variable doesn't exist, it is created. Otherwise the strings are
1141 1.718 rillig * concatenated, with a space in between.
1142 1.483 rillig *
1143 1.70 wiz * Input:
1144 1.607 rillig * name name of the variable to modify, is expanded once
1145 1.400 rillig * val string to append to it
1146 1.802 rillig * scope scope in which this should occur
1147 1.70 wiz *
1148 1.1 cgd * Notes:
1149 1.802 rillig * Only if the variable is being sought in the global scope is the
1150 1.1 cgd * environment searched.
1151 1.802 rillig * XXX: Knows its calling circumstances in that if called with scope
1152 1.802 rillig * an actual target, it will only search that scope since only
1153 1.1 cgd * a local variable could be being appended to. This is actually
1154 1.1 cgd * a big win and must be tolerated.
1155 1.1 cgd */
1156 1.1 cgd void
1157 1.805 rillig Var_AppendExpand(GNode *scope, const char *name, const char *val)
1158 1.1 cgd {
1159 1.838 rillig FStr xname = FStr_InitRefer(name);
1160 1.1 cgd
1161 1.704 rillig assert(val != NULL);
1162 1.460 rillig
1163 1.704 rillig if (strchr(name, '$') != NULL) {
1164 1.838 rillig char *expanded;
1165 1.838 rillig (void)Var_Subst(name, scope, VARE_WANTRES, &expanded);
1166 1.704 rillig /* TODO: handle errors */
1167 1.838 rillig xname = FStr_InitOwn(expanded);
1168 1.838 rillig if (expanded[0] == '\0') {
1169 1.914 rillig DEBUG2(VAR,
1170 1.914 rillig "Var_AppendExpand: variable name \"%s\" expands "
1171 1.914 rillig "to empty string, with value \"%s\" - ignored\n",
1172 1.838 rillig name, val);
1173 1.838 rillig FStr_Done(&xname);
1174 1.704 rillig return;
1175 1.704 rillig }
1176 1.139 dsl }
1177 1.142 dsl
1178 1.838 rillig Var_Append(scope, xname.str, val);
1179 1.1 cgd
1180 1.838 rillig FStr_Done(&xname);
1181 1.1 cgd }
1182 1.1 cgd
1183 1.791 rillig void
1184 1.795 rillig Global_Append(const char *name, const char *value)
1185 1.791 rillig {
1186 1.805 rillig Var_Append(SCOPE_GLOBAL, name, value);
1187 1.791 rillig }
1188 1.791 rillig
1189 1.895 rillig bool
1190 1.805 rillig Var_Exists(GNode *scope, const char *name)
1191 1.796 rillig {
1192 1.895 rillig Var *v = VarFind(name, scope, true);
1193 1.796 rillig if (v == NULL)
1194 1.895 rillig return false;
1195 1.796 rillig
1196 1.837 rillig VarFreeEnv(v);
1197 1.895 rillig return true;
1198 1.796 rillig }
1199 1.796 rillig
1200 1.778 rillig /*
1201 1.802 rillig * See if the given variable exists, in the given scope or in other
1202 1.802 rillig * fallback scopes.
1203 1.1 cgd *
1204 1.70 wiz * Input:
1205 1.607 rillig * name Variable to find, is expanded once
1206 1.802 rillig * scope Scope in which to start search
1207 1.1 cgd */
1208 1.895 rillig bool
1209 1.805 rillig Var_ExistsExpand(GNode *scope, const char *name)
1210 1.1 cgd {
1211 1.747 rillig FStr varname = FStr_InitRefer(name);
1212 1.895 rillig bool exists;
1213 1.412 rillig
1214 1.747 rillig if (strchr(varname.str, '$') != NULL) {
1215 1.747 rillig char *expanded;
1216 1.802 rillig (void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
1217 1.703 rillig /* TODO: handle errors */
1218 1.747 rillig varname = FStr_InitOwn(expanded);
1219 1.703 rillig }
1220 1.1 cgd
1221 1.805 rillig exists = Var_Exists(scope, varname.str);
1222 1.747 rillig FStr_Done(&varname);
1223 1.796 rillig return exists;
1224 1.1 cgd }
1225 1.1 cgd
1226 1.718 rillig /*
1227 1.802 rillig * Return the unexpanded value of the given variable in the given scope,
1228 1.802 rillig * or the usual scopes.
1229 1.1 cgd *
1230 1.70 wiz * Input:
1231 1.607 rillig * name name to find, is not expanded any further
1232 1.802 rillig * scope scope in which to search for it
1233 1.70 wiz *
1234 1.1 cgd * Results:
1235 1.337 rillig * The value if the variable exists, NULL if it doesn't.
1236 1.830 rillig * The value is valid until the next modification to any variable.
1237 1.1 cgd */
1238 1.745 rillig FStr
1239 1.805 rillig Var_Value(GNode *scope, const char *name)
1240 1.1 cgd {
1241 1.895 rillig Var *v = VarFind(name, scope, true);
1242 1.703 rillig char *value;
1243 1.703 rillig
1244 1.703 rillig if (v == NULL)
1245 1.745 rillig return FStr_InitRefer(NULL);
1246 1.412 rillig
1247 1.902 rillig if (!v->fromEnv)
1248 1.837 rillig return FStr_InitRefer(v->val.data);
1249 1.837 rillig
1250 1.837 rillig /* Since environment variables are short-lived, free it now. */
1251 1.837 rillig FStr_Done(&v->name);
1252 1.837 rillig value = Buf_DoneData(&v->val);
1253 1.837 rillig free(v);
1254 1.837 rillig return FStr_InitOwn(value);
1255 1.1 cgd }
1256 1.1 cgd
1257 1.778 rillig /*
1258 1.778 rillig * Return the unexpanded variable value from this node, without trying to look
1259 1.802 rillig * up the variable in any other scope.
1260 1.778 rillig */
1261 1.616 rillig const char *
1262 1.803 rillig GNode_ValueDirect(GNode *gn, const char *name)
1263 1.616 rillig {
1264 1.895 rillig Var *v = VarFind(name, gn, false);
1265 1.785 rillig return v != NULL ? v->val.data : NULL;
1266 1.616 rillig }
1267 1.616 rillig
1268 1.906 rillig static VarEvalMode
1269 1.906 rillig VarEvalMode_WithoutKeepDollar(VarEvalMode emode)
1270 1.906 rillig {
1271 1.906 rillig if (emode == VARE_KEEP_DOLLAR_UNDEF)
1272 1.906 rillig return VARE_EVAL_KEEP_UNDEF;
1273 1.906 rillig if (emode == VARE_EVAL_KEEP_DOLLAR)
1274 1.906 rillig return VARE_WANTRES;
1275 1.906 rillig return emode;
1276 1.906 rillig }
1277 1.906 rillig
1278 1.906 rillig static VarEvalMode
1279 1.906 rillig VarEvalMode_UndefOk(VarEvalMode emode)
1280 1.906 rillig {
1281 1.906 rillig return emode == VARE_UNDEFERR ? VARE_WANTRES : emode;
1282 1.906 rillig }
1283 1.244 rillig
1284 1.905 rillig static bool
1285 1.906 rillig VarEvalMode_ShouldEval(VarEvalMode emode)
1286 1.905 rillig {
1287 1.906 rillig return emode != VARE_PARSE_ONLY;
1288 1.906 rillig }
1289 1.906 rillig
1290 1.906 rillig static bool
1291 1.906 rillig VarEvalMode_ShouldKeepUndef(VarEvalMode emode)
1292 1.906 rillig {
1293 1.906 rillig return emode == VARE_EVAL_KEEP_UNDEF ||
1294 1.906 rillig emode == VARE_KEEP_DOLLAR_UNDEF;
1295 1.906 rillig }
1296 1.906 rillig
1297 1.906 rillig static bool
1298 1.906 rillig VarEvalMode_ShouldKeepDollar(VarEvalMode emode)
1299 1.906 rillig {
1300 1.906 rillig return emode == VARE_EVAL_KEEP_DOLLAR ||
1301 1.906 rillig emode == VARE_KEEP_DOLLAR_UNDEF;
1302 1.905 rillig }
1303 1.905 rillig
1304 1.905 rillig
1305 1.278 rillig static void
1306 1.278 rillig SepBuf_Init(SepBuf *buf, char sep)
1307 1.278 rillig {
1308 1.703 rillig Buf_InitSize(&buf->buf, 32);
1309 1.895 rillig buf->needSep = false;
1310 1.703 rillig buf->sep = sep;
1311 1.278 rillig }
1312 1.278 rillig
1313 1.278 rillig static void
1314 1.278 rillig SepBuf_Sep(SepBuf *buf)
1315 1.278 rillig {
1316 1.895 rillig buf->needSep = true;
1317 1.278 rillig }
1318 1.278 rillig
1319 1.278 rillig static void
1320 1.314 rillig SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
1321 1.278 rillig {
1322 1.703 rillig if (mem_size == 0)
1323 1.703 rillig return;
1324 1.703 rillig if (buf->needSep && buf->sep != '\0') {
1325 1.703 rillig Buf_AddByte(&buf->buf, buf->sep);
1326 1.895 rillig buf->needSep = false;
1327 1.703 rillig }
1328 1.703 rillig Buf_AddBytes(&buf->buf, mem, mem_size);
1329 1.278 rillig }
1330 1.278 rillig
1331 1.314 rillig static void
1332 1.314 rillig SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
1333 1.314 rillig {
1334 1.703 rillig SepBuf_AddBytes(buf, start, (size_t)(end - start));
1335 1.314 rillig }
1336 1.314 rillig
1337 1.314 rillig static void
1338 1.314 rillig SepBuf_AddStr(SepBuf *buf, const char *str)
1339 1.314 rillig {
1340 1.703 rillig SepBuf_AddBytes(buf, str, strlen(str));
1341 1.314 rillig }
1342 1.314 rillig
1343 1.278 rillig static char *
1344 1.784 rillig SepBuf_DoneData(SepBuf *buf)
1345 1.278 rillig {
1346 1.784 rillig return Buf_DoneData(&buf->buf);
1347 1.278 rillig }
1348 1.278 rillig
1349 1.278 rillig
1350 1.778 rillig /*
1351 1.778 rillig * This callback for ModifyWords gets a single word from a variable expression
1352 1.609 rillig * and typically adds a modification of this word to the buffer. It may also
1353 1.609 rillig * do nothing or add several words.
1354 1.609 rillig *
1355 1.822 rillig * For example, when evaluating the modifier ':M*b' in ${:Ua b c:M*b}, the
1356 1.822 rillig * callback is called 3 times, once for "a", "b" and "c".
1357 1.778 rillig */
1358 1.822 rillig typedef void (*ModifyWordProc)(const char *word, SepBuf *buf, void *data);
1359 1.244 rillig
1360 1.244 rillig
1361 1.778 rillig /*
1362 1.778 rillig * Callback for ModifyWords to implement the :H modifier.
1363 1.778 rillig * Add the dirname of the given word to the buffer.
1364 1.778 rillig */
1365 1.779 rillig /*ARGSUSED*/
1366 1.278 rillig static void
1367 1.295 rillig ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1368 1.1 cgd {
1369 1.703 rillig const char *slash = strrchr(word, '/');
1370 1.703 rillig if (slash != NULL)
1371 1.703 rillig SepBuf_AddBytesBetween(buf, word, slash);
1372 1.703 rillig else
1373 1.703 rillig SepBuf_AddStr(buf, ".");
1374 1.1 cgd }
1375 1.1 cgd
1376 1.778 rillig /*
1377 1.778 rillig * Callback for ModifyWords to implement the :T modifier.
1378 1.778 rillig * Add the basename of the given word to the buffer.
1379 1.778 rillig */
1380 1.779 rillig /*ARGSUSED*/
1381 1.278 rillig static void
1382 1.295 rillig ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1383 1.1 cgd {
1384 1.733 rillig SepBuf_AddStr(buf, str_basename(word));
1385 1.1 cgd }
1386 1.1 cgd
1387 1.778 rillig /*
1388 1.778 rillig * Callback for ModifyWords to implement the :E modifier.
1389 1.778 rillig * Add the filename suffix of the given word to the buffer, if it exists.
1390 1.778 rillig */
1391 1.779 rillig /*ARGSUSED*/
1392 1.278 rillig static void
1393 1.295 rillig ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1394 1.1 cgd {
1395 1.703 rillig const char *lastDot = strrchr(word, '.');
1396 1.703 rillig if (lastDot != NULL)
1397 1.703 rillig SepBuf_AddStr(buf, lastDot + 1);
1398 1.1 cgd }
1399 1.1 cgd
1400 1.778 rillig /*
1401 1.778 rillig * Callback for ModifyWords to implement the :R modifier.
1402 1.830 rillig * Add the filename without extension of the given word to the buffer.
1403 1.778 rillig */
1404 1.779 rillig /*ARGSUSED*/
1405 1.278 rillig static void
1406 1.295 rillig ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1407 1.1 cgd {
1408 1.703 rillig const char *lastDot = strrchr(word, '.');
1409 1.703 rillig size_t len = lastDot != NULL ? (size_t)(lastDot - word) : strlen(word);
1410 1.703 rillig SepBuf_AddBytes(buf, word, len);
1411 1.1 cgd }
1412 1.1 cgd
1413 1.778 rillig /*
1414 1.778 rillig * Callback for ModifyWords to implement the :M modifier.
1415 1.778 rillig * Place the word in the buffer if it matches the given pattern.
1416 1.778 rillig */
1417 1.278 rillig static void
1418 1.295 rillig ModifyWord_Match(const char *word, SepBuf *buf, void *data)
1419 1.1 cgd {
1420 1.703 rillig const char *pattern = data;
1421 1.908 rillig
1422 1.703 rillig if (Str_Match(word, pattern))
1423 1.703 rillig SepBuf_AddStr(buf, word);
1424 1.1 cgd }
1425 1.1 cgd
1426 1.778 rillig /*
1427 1.778 rillig * Callback for ModifyWords to implement the :N modifier.
1428 1.778 rillig * Place the word in the buffer if it doesn't match the given pattern.
1429 1.778 rillig */
1430 1.291 rillig static void
1431 1.295 rillig ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data)
1432 1.291 rillig {
1433 1.703 rillig const char *pattern = data;
1434 1.908 rillig
1435 1.703 rillig if (!Str_Match(word, pattern))
1436 1.703 rillig SepBuf_AddStr(buf, word);
1437 1.291 rillig }
1438 1.291 rillig
1439 1.13 christos #ifdef SYSVVARSUB
1440 1.703 rillig
1441 1.778 rillig /*
1442 1.778 rillig * Check word against pattern for a match (% is a wildcard).
1443 1.256 rillig *
1444 1.256 rillig * Input:
1445 1.256 rillig * word Word to examine
1446 1.256 rillig * pattern Pattern to examine against
1447 1.256 rillig *
1448 1.256 rillig * Results:
1449 1.377 rillig * Returns the start of the match, or NULL.
1450 1.610 rillig * out_match_len returns the length of the match, if any.
1451 1.610 rillig * out_hasPercent returns whether the pattern contains a percent.
1452 1.256 rillig */
1453 1.277 rillig static const char *
1454 1.610 rillig SysVMatch(const char *word, const char *pattern,
1455 1.895 rillig size_t *out_match_len, bool *out_hasPercent)
1456 1.256 rillig {
1457 1.703 rillig const char *p = pattern;
1458 1.703 rillig const char *w = word;
1459 1.703 rillig const char *percent;
1460 1.703 rillig size_t w_len;
1461 1.703 rillig size_t p_len;
1462 1.703 rillig const char *w_tail;
1463 1.703 rillig
1464 1.895 rillig *out_hasPercent = false;
1465 1.703 rillig percent = strchr(p, '%');
1466 1.830 rillig if (percent != NULL) { /* ${VAR:...%...=...} */
1467 1.895 rillig *out_hasPercent = true;
1468 1.703 rillig if (w[0] == '\0')
1469 1.703 rillig return NULL; /* empty word does not match pattern */
1470 1.703 rillig
1471 1.703 rillig /* check that the prefix matches */
1472 1.703 rillig for (; p != percent && *w != '\0' && *w == *p; w++, p++)
1473 1.703 rillig continue;
1474 1.703 rillig if (p != percent)
1475 1.703 rillig return NULL; /* No match */
1476 1.703 rillig
1477 1.703 rillig p++; /* Skip the percent */
1478 1.703 rillig if (*p == '\0') {
1479 1.703 rillig /* No more pattern, return the rest of the string */
1480 1.703 rillig *out_match_len = strlen(w);
1481 1.703 rillig return w;
1482 1.703 rillig }
1483 1.256 rillig }
1484 1.256 rillig
1485 1.703 rillig /* Test whether the tail matches */
1486 1.703 rillig w_len = strlen(w);
1487 1.703 rillig p_len = strlen(p);
1488 1.703 rillig if (w_len < p_len)
1489 1.703 rillig return NULL;
1490 1.703 rillig
1491 1.703 rillig w_tail = w + w_len - p_len;
1492 1.703 rillig if (memcmp(p, w_tail, p_len) != 0)
1493 1.703 rillig return NULL;
1494 1.256 rillig
1495 1.703 rillig *out_match_len = (size_t)(w_tail - w);
1496 1.703 rillig return w;
1497 1.256 rillig }
1498 1.256 rillig
1499 1.541 rillig struct ModifyWord_SYSVSubstArgs {
1500 1.806 rillig GNode *scope;
1501 1.703 rillig const char *lhs;
1502 1.703 rillig const char *rhs;
1503 1.541 rillig };
1504 1.276 rillig
1505 1.291 rillig /* Callback for ModifyWords to implement the :%.from=%.to modifier. */
1506 1.278 rillig static void
1507 1.295 rillig ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data)
1508 1.5 cgd {
1509 1.703 rillig const struct ModifyWord_SYSVSubstArgs *args = data;
1510 1.703 rillig char *rhs_expanded;
1511 1.703 rillig const char *rhs;
1512 1.703 rillig const char *percent;
1513 1.703 rillig
1514 1.703 rillig size_t match_len;
1515 1.895 rillig bool lhsPercent;
1516 1.703 rillig const char *match = SysVMatch(word, args->lhs, &match_len, &lhsPercent);
1517 1.703 rillig if (match == NULL) {
1518 1.703 rillig SepBuf_AddStr(buf, word);
1519 1.703 rillig return;
1520 1.703 rillig }
1521 1.379 rillig
1522 1.703 rillig /*
1523 1.703 rillig * Append rhs to the buffer, substituting the first '%' with the
1524 1.703 rillig * match, but only if the lhs had a '%' as well.
1525 1.703 rillig */
1526 1.379 rillig
1527 1.806 rillig (void)Var_Subst(args->rhs, args->scope, VARE_WANTRES, &rhs_expanded);
1528 1.703 rillig /* TODO: handle errors */
1529 1.379 rillig
1530 1.703 rillig rhs = rhs_expanded;
1531 1.703 rillig percent = strchr(rhs, '%');
1532 1.379 rillig
1533 1.703 rillig if (percent != NULL && lhsPercent) {
1534 1.703 rillig /* Copy the prefix of the replacement pattern */
1535 1.703 rillig SepBuf_AddBytesBetween(buf, rhs, percent);
1536 1.703 rillig rhs = percent + 1;
1537 1.703 rillig }
1538 1.703 rillig if (percent != NULL || !lhsPercent)
1539 1.703 rillig SepBuf_AddBytes(buf, match, match_len);
1540 1.379 rillig
1541 1.703 rillig /* Append the suffix of the replacement pattern */
1542 1.703 rillig SepBuf_AddStr(buf, rhs);
1543 1.379 rillig
1544 1.703 rillig free(rhs_expanded);
1545 1.5 cgd }
1546 1.13 christos #endif
1547 1.5 cgd
1548 1.1 cgd
1549 1.541 rillig struct ModifyWord_SubstArgs {
1550 1.703 rillig const char *lhs;
1551 1.703 rillig size_t lhsLen;
1552 1.703 rillig const char *rhs;
1553 1.703 rillig size_t rhsLen;
1554 1.703 rillig VarPatternFlags pflags;
1555 1.895 rillig bool matched;
1556 1.541 rillig };
1557 1.291 rillig
1558 1.778 rillig /*
1559 1.778 rillig * Callback for ModifyWords to implement the :S,from,to, modifier.
1560 1.778 rillig * Perform a string substitution on the given word.
1561 1.778 rillig */
1562 1.278 rillig static void
1563 1.295 rillig ModifyWord_Subst(const char *word, SepBuf *buf, void *data)
1564 1.1 cgd {
1565 1.703 rillig size_t wordLen = strlen(word);
1566 1.703 rillig struct ModifyWord_SubstArgs *args = data;
1567 1.703 rillig const char *match;
1568 1.703 rillig
1569 1.788 rillig if (args->pflags.subOnce && args->matched)
1570 1.703 rillig goto nosub;
1571 1.703 rillig
1572 1.788 rillig if (args->pflags.anchorStart) {
1573 1.703 rillig if (wordLen < args->lhsLen ||
1574 1.703 rillig memcmp(word, args->lhs, args->lhsLen) != 0)
1575 1.703 rillig goto nosub;
1576 1.703 rillig
1577 1.839 rillig if (args->pflags.anchorEnd && wordLen != args->lhsLen)
1578 1.703 rillig goto nosub;
1579 1.703 rillig
1580 1.703 rillig /* :S,^prefix,replacement, or :S,^whole$,replacement, */
1581 1.703 rillig SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1582 1.839 rillig SepBuf_AddBytesBetween(buf,
1583 1.839 rillig word + args->lhsLen, word + wordLen);
1584 1.895 rillig args->matched = true;
1585 1.703 rillig return;
1586 1.703 rillig }
1587 1.1 cgd
1588 1.788 rillig if (args->pflags.anchorEnd) {
1589 1.703 rillig const char *start;
1590 1.279 rillig
1591 1.703 rillig if (wordLen < args->lhsLen)
1592 1.703 rillig goto nosub;
1593 1.412 rillig
1594 1.703 rillig start = word + (wordLen - args->lhsLen);
1595 1.703 rillig if (memcmp(start, args->lhs, args->lhsLen) != 0)
1596 1.703 rillig goto nosub;
1597 1.703 rillig
1598 1.703 rillig /* :S,suffix$,replacement, */
1599 1.703 rillig SepBuf_AddBytesBetween(buf, word, start);
1600 1.703 rillig SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1601 1.895 rillig args->matched = true;
1602 1.703 rillig return;
1603 1.703 rillig }
1604 1.315 rillig
1605 1.703 rillig if (args->lhs[0] == '\0')
1606 1.703 rillig goto nosub;
1607 1.279 rillig
1608 1.703 rillig /* unanchored case, may match more than once */
1609 1.703 rillig while ((match = strstr(word, args->lhs)) != NULL) {
1610 1.703 rillig SepBuf_AddBytesBetween(buf, word, match);
1611 1.703 rillig SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1612 1.895 rillig args->matched = true;
1613 1.703 rillig wordLen -= (size_t)(match - word) + args->lhsLen;
1614 1.703 rillig word += (size_t)(match - word) + args->lhsLen;
1615 1.788 rillig if (wordLen == 0 || !args->pflags.subGlobal)
1616 1.703 rillig break;
1617 1.703 rillig }
1618 1.242 rillig nosub:
1619 1.703 rillig SepBuf_AddBytes(buf, word, wordLen);
1620 1.1 cgd }
1621 1.1 cgd
1622 1.31 gwr #ifndef NO_REGEX
1623 1.400 rillig /* Print the error caused by a regcomp or regexec call. */
1624 1.16 christos static void
1625 1.672 rillig VarREError(int reerr, const regex_t *pat, const char *str)
1626 1.16 christos {
1627 1.703 rillig size_t errlen = regerror(reerr, pat, NULL, 0);
1628 1.703 rillig char *errbuf = bmake_malloc(errlen);
1629 1.703 rillig regerror(reerr, pat, errbuf, errlen);
1630 1.703 rillig Error("%s: %s", str, errbuf);
1631 1.703 rillig free(errbuf);
1632 1.16 christos }
1633 1.16 christos
1634 1.541 rillig struct ModifyWord_SubstRegexArgs {
1635 1.703 rillig regex_t re;
1636 1.703 rillig size_t nsub;
1637 1.703 rillig char *replace;
1638 1.703 rillig VarPatternFlags pflags;
1639 1.895 rillig bool matched;
1640 1.541 rillig };
1641 1.291 rillig
1642 1.778 rillig /*
1643 1.778 rillig * Callback for ModifyWords to implement the :C/from/to/ modifier.
1644 1.778 rillig * Perform a regex substitution on the given word.
1645 1.778 rillig */
1646 1.278 rillig static void
1647 1.295 rillig ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
1648 1.16 christos {
1649 1.704 rillig struct ModifyWord_SubstRegexArgs *args = data;
1650 1.704 rillig int xrv;
1651 1.704 rillig const char *wp = word;
1652 1.704 rillig char *rp;
1653 1.704 rillig int flags = 0;
1654 1.704 rillig regmatch_t m[10];
1655 1.16 christos
1656 1.788 rillig if (args->pflags.subOnce && args->matched)
1657 1.704 rillig goto nosub;
1658 1.307 rillig
1659 1.307 rillig tryagain:
1660 1.704 rillig xrv = regexec(&args->re, wp, args->nsub, m, flags);
1661 1.16 christos
1662 1.704 rillig switch (xrv) {
1663 1.704 rillig case 0:
1664 1.895 rillig args->matched = true;
1665 1.704 rillig SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
1666 1.704 rillig
1667 1.830 rillig /*
1668 1.830 rillig * Replacement of regular expressions is not specified by
1669 1.830 rillig * POSIX, therefore implement it here.
1670 1.830 rillig */
1671 1.830 rillig
1672 1.781 rillig for (rp = args->replace; *rp != '\0'; rp++) {
1673 1.704 rillig if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
1674 1.704 rillig SepBuf_AddBytes(buf, rp + 1, 1);
1675 1.704 rillig rp++;
1676 1.704 rillig continue;
1677 1.704 rillig }
1678 1.445 rillig
1679 1.704 rillig if (*rp == '&') {
1680 1.704 rillig SepBuf_AddBytesBetween(buf,
1681 1.704 rillig wp + m[0].rm_so, wp + m[0].rm_eo);
1682 1.704 rillig continue;
1683 1.704 rillig }
1684 1.445 rillig
1685 1.704 rillig if (*rp != '\\' || !ch_isdigit(rp[1])) {
1686 1.704 rillig SepBuf_AddBytes(buf, rp, 1);
1687 1.704 rillig continue;
1688 1.704 rillig }
1689 1.445 rillig
1690 1.704 rillig { /* \0 to \9 backreference */
1691 1.704 rillig size_t n = (size_t)(rp[1] - '0');
1692 1.704 rillig rp++;
1693 1.704 rillig
1694 1.704 rillig if (n >= args->nsub) {
1695 1.734 rillig Error("No subexpression \\%u",
1696 1.734 rillig (unsigned)n);
1697 1.704 rillig } else if (m[n].rm_so == -1) {
1698 1.704 rillig Error(
1699 1.734 rillig "No match for subexpression \\%u",
1700 1.734 rillig (unsigned)n);
1701 1.704 rillig } else {
1702 1.704 rillig SepBuf_AddBytesBetween(buf,
1703 1.704 rillig wp + m[n].rm_so, wp + m[n].rm_eo);
1704 1.704 rillig }
1705 1.704 rillig }
1706 1.16 christos }
1707 1.445 rillig
1708 1.704 rillig wp += m[0].rm_eo;
1709 1.788 rillig if (args->pflags.subGlobal) {
1710 1.704 rillig flags |= REG_NOTBOL;
1711 1.704 rillig if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
1712 1.704 rillig SepBuf_AddBytes(buf, wp, 1);
1713 1.704 rillig wp++;
1714 1.704 rillig }
1715 1.704 rillig if (*wp != '\0')
1716 1.704 rillig goto tryagain;
1717 1.704 rillig }
1718 1.704 rillig if (*wp != '\0')
1719 1.704 rillig SepBuf_AddStr(buf, wp);
1720 1.704 rillig break;
1721 1.704 rillig default:
1722 1.704 rillig VarREError(xrv, &args->re, "Unexpected regex error");
1723 1.704 rillig /* FALLTHROUGH */
1724 1.704 rillig case REG_NOMATCH:
1725 1.704 rillig nosub:
1726 1.704 rillig SepBuf_AddStr(buf, wp);
1727 1.704 rillig break;
1728 1.20 christos }
1729 1.16 christos }
1730 1.17 christos #endif
1731 1.16 christos
1732 1.16 christos
1733 1.541 rillig struct ModifyWord_LoopArgs {
1734 1.806 rillig GNode *scope;
1735 1.703 rillig char *tvar; /* name of temporary variable */
1736 1.703 rillig char *str; /* string to expand */
1737 1.906 rillig VarEvalMode emode;
1738 1.541 rillig };
1739 1.291 rillig
1740 1.291 rillig /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
1741 1.278 rillig static void
1742 1.295 rillig ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
1743 1.40 sjg {
1744 1.703 rillig const struct ModifyWord_LoopArgs *args;
1745 1.703 rillig char *s;
1746 1.412 rillig
1747 1.703 rillig if (word[0] == '\0')
1748 1.703 rillig return;
1749 1.278 rillig
1750 1.703 rillig args = data;
1751 1.907 rillig Var_SetWithFlags(args->scope, args->tvar, word, VAR_SET_NO_EXPORT);
1752 1.906 rillig (void)Var_Subst(args->str, args->scope, args->emode, &s);
1753 1.703 rillig /* TODO: handle errors */
1754 1.64 sjg
1755 1.708 rillig DEBUG4(VAR, "ModifyWord_Loop: "
1756 1.708 rillig "in \"%s\", replace \"%s\" with \"%s\" to \"%s\"\n",
1757 1.703 rillig word, args->tvar, args->str, s);
1758 1.703 rillig
1759 1.703 rillig if (s[0] == '\n' || Buf_EndsWith(&buf->buf, '\n'))
1760 1.895 rillig buf->needSep = false;
1761 1.703 rillig SepBuf_AddStr(buf, s);
1762 1.703 rillig free(s);
1763 1.40 sjg }
1764 1.40 sjg
1765 1.81 sjg
1766 1.778 rillig /*
1767 1.778 rillig * The :[first..last] modifier selects words from the expression.
1768 1.778 rillig * It can also reverse the words.
1769 1.778 rillig */
1770 1.81 sjg static char *
1771 1.840 rillig VarSelectWords(const char *str, int first, int last,
1772 1.895 rillig char sep, bool oneBigWord)
1773 1.81 sjg {
1774 1.703 rillig Words words;
1775 1.703 rillig int len, start, end, step;
1776 1.703 rillig int i;
1777 1.703 rillig
1778 1.703 rillig SepBuf buf;
1779 1.703 rillig SepBuf_Init(&buf, sep);
1780 1.703 rillig
1781 1.703 rillig if (oneBigWord) {
1782 1.703 rillig /* fake what Str_Words() would do if there were only one word */
1783 1.703 rillig words.len = 1;
1784 1.703 rillig words.words = bmake_malloc(
1785 1.703 rillig (words.len + 1) * sizeof(words.words[0]));
1786 1.703 rillig words.freeIt = bmake_strdup(str);
1787 1.703 rillig words.words[0] = words.freeIt;
1788 1.703 rillig words.words[1] = NULL;
1789 1.703 rillig } else {
1790 1.895 rillig words = Str_Words(str, false);
1791 1.703 rillig }
1792 1.81 sjg
1793 1.703 rillig /*
1794 1.703 rillig * Now sanitize the given range. If first or last are negative,
1795 1.703 rillig * convert them to the positive equivalents (-1 gets converted to len,
1796 1.703 rillig * -2 gets converted to (len - 1), etc.).
1797 1.703 rillig */
1798 1.703 rillig len = (int)words.len;
1799 1.703 rillig if (first < 0)
1800 1.703 rillig first += len + 1;
1801 1.703 rillig if (last < 0)
1802 1.703 rillig last += len + 1;
1803 1.703 rillig
1804 1.703 rillig /* We avoid scanning more of the list than we need to. */
1805 1.703 rillig if (first > last) {
1806 1.703 rillig start = (first > len ? len : first) - 1;
1807 1.703 rillig end = last < 1 ? 0 : last - 1;
1808 1.703 rillig step = -1;
1809 1.703 rillig } else {
1810 1.703 rillig start = first < 1 ? 0 : first - 1;
1811 1.703 rillig end = last > len ? len : last;
1812 1.703 rillig step = 1;
1813 1.703 rillig }
1814 1.81 sjg
1815 1.703 rillig for (i = start; (step < 0) == (i >= end); i += step) {
1816 1.703 rillig SepBuf_AddStr(&buf, words.words[i]);
1817 1.703 rillig SepBuf_Sep(&buf);
1818 1.703 rillig }
1819 1.81 sjg
1820 1.703 rillig Words_Free(words);
1821 1.81 sjg
1822 1.784 rillig return SepBuf_DoneData(&buf);
1823 1.81 sjg }
1824 1.81 sjg
1825 1.156 sjg
1826 1.778 rillig /*
1827 1.778 rillig * Callback for ModifyWords to implement the :tA modifier.
1828 1.778 rillig * Replace each word with the result of realpath() if successful.
1829 1.778 rillig */
1830 1.779 rillig /*ARGSUSED*/
1831 1.278 rillig static void
1832 1.295 rillig ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
1833 1.156 sjg {
1834 1.703 rillig struct stat st;
1835 1.703 rillig char rbuf[MAXPATHLEN];
1836 1.231 rillig
1837 1.703 rillig const char *rp = cached_realpath(word, rbuf);
1838 1.703 rillig if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
1839 1.703 rillig word = rp;
1840 1.231 rillig
1841 1.703 rillig SepBuf_AddStr(buf, word);
1842 1.156 sjg }
1843 1.156 sjg
1844 1.35 christos
1845 1.403 rillig static char *
1846 1.479 rillig Words_JoinFree(Words words)
1847 1.403 rillig {
1848 1.703 rillig Buffer buf;
1849 1.703 rillig size_t i;
1850 1.412 rillig
1851 1.703 rillig Buf_Init(&buf);
1852 1.403 rillig
1853 1.703 rillig for (i = 0; i < words.len; i++) {
1854 1.703 rillig if (i != 0) {
1855 1.891 rillig /* XXX: Use ch->sep instead of ' ', for consistency. */
1856 1.703 rillig Buf_AddByte(&buf, ' ');
1857 1.703 rillig }
1858 1.703 rillig Buf_AddStr(&buf, words.words[i]);
1859 1.703 rillig }
1860 1.403 rillig
1861 1.703 rillig Words_Free(words);
1862 1.403 rillig
1863 1.784 rillig return Buf_DoneData(&buf);
1864 1.403 rillig }
1865 1.403 rillig
1866 1.319 rillig /* Remove adjacent duplicate words. */
1867 1.55 christos static char *
1868 1.73 christos VarUniq(const char *str)
1869 1.55 christos {
1870 1.895 rillig Words words = Str_Words(str, false);
1871 1.55 christos
1872 1.703 rillig if (words.len > 1) {
1873 1.703 rillig size_t i, j;
1874 1.703 rillig for (j = 0, i = 1; i < words.len; i++)
1875 1.703 rillig if (strcmp(words.words[i], words.words[j]) != 0 &&
1876 1.703 rillig (++j != i))
1877 1.703 rillig words.words[j] = words.words[i];
1878 1.703 rillig words.len = j + 1;
1879 1.703 rillig }
1880 1.55 christos
1881 1.703 rillig return Words_JoinFree(words);
1882 1.55 christos }
1883 1.55 christos
1884 1.55 christos
1885 1.778 rillig /*
1886 1.778 rillig * Quote shell meta-characters and space characters in the string.
1887 1.778 rillig * If quoteDollar is set, also quote and double any '$' characters.
1888 1.778 rillig */
1889 1.16 christos static char *
1890 1.895 rillig VarQuote(const char *str, bool quoteDollar)
1891 1.16 christos {
1892 1.703 rillig Buffer buf;
1893 1.703 rillig Buf_Init(&buf);
1894 1.193 christos
1895 1.703 rillig for (; *str != '\0'; str++) {
1896 1.703 rillig if (*str == '\n') {
1897 1.703 rillig const char *newline = Shell_GetNewline();
1898 1.703 rillig if (newline == NULL)
1899 1.703 rillig newline = "\\\n";
1900 1.703 rillig Buf_AddStr(&buf, newline);
1901 1.703 rillig continue;
1902 1.703 rillig }
1903 1.703 rillig if (ch_isspace(*str) || is_shell_metachar((unsigned char)*str))
1904 1.703 rillig Buf_AddByte(&buf, '\\');
1905 1.703 rillig Buf_AddByte(&buf, *str);
1906 1.703 rillig if (quoteDollar && *str == '$')
1907 1.703 rillig Buf_AddStr(&buf, "\\$");
1908 1.193 christos }
1909 1.193 christos
1910 1.784 rillig return Buf_DoneData(&buf);
1911 1.16 christos }
1912 1.16 christos
1913 1.778 rillig /*
1914 1.778 rillig * Compute the 32-bit hash of the given string, using the MurmurHash3
1915 1.778 rillig * algorithm. Output is encoded as 8 hex digits, in Little Endian order.
1916 1.778 rillig */
1917 1.163 joerg static char *
1918 1.252 rillig VarHash(const char *str)
1919 1.163 joerg {
1920 1.703 rillig static const char hexdigits[16] = "0123456789abcdef";
1921 1.703 rillig const unsigned char *ustr = (const unsigned char *)str;
1922 1.703 rillig
1923 1.703 rillig uint32_t h = 0x971e137bU;
1924 1.703 rillig uint32_t c1 = 0x95543787U;
1925 1.703 rillig uint32_t c2 = 0x2ad7eb25U;
1926 1.703 rillig size_t len2 = strlen(str);
1927 1.163 joerg
1928 1.703 rillig char *buf;
1929 1.703 rillig size_t i;
1930 1.703 rillig
1931 1.703 rillig size_t len;
1932 1.781 rillig for (len = len2; len != 0;) {
1933 1.703 rillig uint32_t k = 0;
1934 1.703 rillig switch (len) {
1935 1.703 rillig default:
1936 1.703 rillig k = ((uint32_t)ustr[3] << 24) |
1937 1.703 rillig ((uint32_t)ustr[2] << 16) |
1938 1.703 rillig ((uint32_t)ustr[1] << 8) |
1939 1.703 rillig (uint32_t)ustr[0];
1940 1.703 rillig len -= 4;
1941 1.703 rillig ustr += 4;
1942 1.703 rillig break;
1943 1.703 rillig case 3:
1944 1.703 rillig k |= (uint32_t)ustr[2] << 16;
1945 1.703 rillig /* FALLTHROUGH */
1946 1.703 rillig case 2:
1947 1.703 rillig k |= (uint32_t)ustr[1] << 8;
1948 1.703 rillig /* FALLTHROUGH */
1949 1.703 rillig case 1:
1950 1.703 rillig k |= (uint32_t)ustr[0];
1951 1.703 rillig len = 0;
1952 1.703 rillig }
1953 1.703 rillig c1 = c1 * 5 + 0x7b7d159cU;
1954 1.703 rillig c2 = c2 * 5 + 0x6bce6396U;
1955 1.703 rillig k *= c1;
1956 1.703 rillig k = (k << 11) ^ (k >> 21);
1957 1.703 rillig k *= c2;
1958 1.703 rillig h = (h << 13) ^ (h >> 19);
1959 1.703 rillig h = h * 5 + 0x52dce729U;
1960 1.703 rillig h ^= k;
1961 1.703 rillig }
1962 1.703 rillig h ^= (uint32_t)len2;
1963 1.703 rillig h *= 0x85ebca6b;
1964 1.703 rillig h ^= h >> 13;
1965 1.703 rillig h *= 0xc2b2ae35;
1966 1.703 rillig h ^= h >> 16;
1967 1.703 rillig
1968 1.703 rillig buf = bmake_malloc(9);
1969 1.703 rillig for (i = 0; i < 8; i++) {
1970 1.703 rillig buf[i] = hexdigits[h & 0x0f];
1971 1.703 rillig h >>= 4;
1972 1.703 rillig }
1973 1.703 rillig buf[8] = '\0';
1974 1.703 rillig return buf;
1975 1.163 joerg }
1976 1.163 joerg
1977 1.164 sjg static char *
1978 1.895 rillig VarStrftime(const char *fmt, bool zulu, time_t tim)
1979 1.164 sjg {
1980 1.703 rillig char buf[BUFSIZ];
1981 1.164 sjg
1982 1.703 rillig if (tim == 0)
1983 1.703 rillig time(&tim);
1984 1.703 rillig if (*fmt == '\0')
1985 1.703 rillig fmt = "%c";
1986 1.703 rillig strftime(buf, sizeof buf, fmt, zulu ? gmtime(&tim) : localtime(&tim));
1987 1.235 rillig
1988 1.703 rillig buf[sizeof buf - 1] = '\0';
1989 1.703 rillig return bmake_strdup(buf);
1990 1.164 sjg }
1991 1.164 sjg
1992 1.687 rillig /*
1993 1.687 rillig * The ApplyModifier functions take an expression that is being evaluated.
1994 1.830 rillig * Their task is to apply a single modifier to the expression. This involves
1995 1.830 rillig * parsing the modifier, evaluating it and finally updating the value of the
1996 1.830 rillig * expression.
1997 1.467 rillig *
1998 1.467 rillig * Parsing the modifier
1999 1.467 rillig *
2000 1.467 rillig * If parsing succeeds, the parsing position *pp is updated to point to the
2001 1.467 rillig * first character following the modifier, which typically is either ':' or
2002 1.891 rillig * ch->endc. The modifier doesn't have to check for this delimiter character,
2003 1.687 rillig * this is done by ApplyModifiers.
2004 1.687 rillig *
2005 1.687 rillig * XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
2006 1.687 rillig * need to be followed by a ':' or endc; this was an unintended mistake.
2007 1.467 rillig *
2008 1.467 rillig * If parsing fails because of a missing delimiter (as in the :S, :C or :@
2009 1.530 rillig * modifiers), return AMR_CLEANUP.
2010 1.467 rillig *
2011 1.467 rillig * If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
2012 1.467 rillig * try the SysV modifier ${VAR:from=to} as fallback. This should only be
2013 1.467 rillig * done as long as there have been no side effects from evaluating nested
2014 1.467 rillig * variables, to avoid evaluating them more than once. In this case, the
2015 1.687 rillig * parsing position may or may not be updated. (XXX: Why not? The original
2016 1.687 rillig * parsing position is well-known in ApplyModifiers.)
2017 1.467 rillig *
2018 1.467 rillig * If parsing fails and the SysV modifier ${VAR:from=to} should not be used
2019 1.467 rillig * as a fallback, either issue an error message using Error or Parse_Error
2020 1.467 rillig * and then return AMR_CLEANUP, or return AMR_BAD for the default error
2021 1.467 rillig * message. Both of these return values will stop processing the variable
2022 1.467 rillig * expression. (XXX: As of 2020-08-23, evaluation of the whole string
2023 1.467 rillig * continues nevertheless after skipping a few bytes, which essentially is
2024 1.830 rillig * undefined behavior. Not in the sense of C, but still the resulting string
2025 1.830 rillig * is garbage.)
2026 1.467 rillig *
2027 1.467 rillig * Evaluating the modifier
2028 1.467 rillig *
2029 1.467 rillig * After parsing, the modifier is evaluated. The side effects from evaluating
2030 1.467 rillig * nested variable expressions in the modifier text often already happen
2031 1.830 rillig * during parsing though. For most modifiers this doesn't matter since their
2032 1.830 rillig * only noticeable effect is that the update the value of the expression.
2033 1.830 rillig * Some modifiers such as ':sh' or '::=' have noticeable side effects though.
2034 1.467 rillig *
2035 1.467 rillig * Evaluating the modifier usually takes the current value of the variable
2036 1.891 rillig * expression from ch->expr->value, or the variable name from ch->var->name
2037 1.824 rillig * and stores the result back in expr->value via Expr_SetValueOwn or
2038 1.821 rillig * Expr_SetValueRefer.
2039 1.467 rillig *
2040 1.467 rillig * If evaluating fails (as of 2020-08-23), an error message is printed using
2041 1.467 rillig * Error. This function has no side-effects, it really just prints the error
2042 1.467 rillig * message. Processing the expression continues as if everything were ok.
2043 1.467 rillig * XXX: This should be fixed by adding proper error handling to Var_Subst,
2044 1.467 rillig * Var_Parse, ApplyModifiers and ModifyWords.
2045 1.467 rillig *
2046 1.467 rillig * Housekeeping
2047 1.467 rillig *
2048 1.528 rillig * Some modifiers such as :D and :U turn undefined expressions into defined
2049 1.821 rillig * expressions (see Expr_Define).
2050 1.467 rillig *
2051 1.467 rillig * Some modifiers need to free some memory.
2052 1.350 rillig */
2053 1.409 rillig
2054 1.825 rillig typedef enum ExprDefined {
2055 1.816 rillig /* The variable expression is based on a regular, defined variable. */
2056 1.825 rillig DEF_REGULAR,
2057 1.703 rillig /* The variable expression is based on an undefined variable. */
2058 1.825 rillig DEF_UNDEF,
2059 1.703 rillig /*
2060 1.703 rillig * The variable expression started as an undefined expression, but one
2061 1.825 rillig * of the modifiers (such as ':D' or ':U') has turned the expression
2062 1.825 rillig * from undefined to defined.
2063 1.703 rillig */
2064 1.825 rillig DEF_DEFINED
2065 1.825 rillig } ExprDefined;
2066 1.527 rillig
2067 1.825 rillig static const char *const ExprDefined_Name[] = {
2068 1.826 rillig "regular",
2069 1.826 rillig "undefined",
2070 1.826 rillig "defined"
2071 1.789 rillig };
2072 1.527 rillig
2073 1.897 rillig #if __STDC_VERSION__ >= 199901L
2074 1.897 rillig #define const_member const
2075 1.897 rillig #else
2076 1.897 rillig #define const_member /* no const possible */
2077 1.897 rillig #endif
2078 1.897 rillig
2079 1.823 rillig /* A variable expression such as $@ or ${VAR:Mpattern:Q}. */
2080 1.823 rillig typedef struct Expr {
2081 1.898 rillig const char *name;
2082 1.823 rillig FStr value;
2083 1.906 rillig VarEvalMode const_member emode;
2084 1.897 rillig GNode *const_member scope;
2085 1.825 rillig ExprDefined defined;
2086 1.823 rillig } Expr;
2087 1.823 rillig
2088 1.823 rillig /*
2089 1.890 rillig * The status of applying a chain of modifiers to an expression.
2090 1.823 rillig *
2091 1.890 rillig * The modifiers of an expression are broken into chains of modifiers,
2092 1.892 rillig * starting a new nested chain whenever an indirect modifier starts. There
2093 1.892 rillig * are at most 2 nesting levels: the outer one for the direct modifiers, and
2094 1.892 rillig * the inner one for the indirect modifiers.
2095 1.890 rillig *
2096 1.892 rillig * For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 3 chains of
2097 1.889 rillig * modifiers:
2098 1.889 rillig *
2099 1.892 rillig * Chain 1 starts with the single modifier ':M*'.
2100 1.892 rillig * Chain 2 starts with all modifiers from ${IND1}.
2101 1.892 rillig * Chain 2 ends at the ':' between ${IND1} and ${IND2}.
2102 1.893 rillig * Chain 3 starts with all modifiers from ${IND2}.
2103 1.893 rillig * Chain 3 ends at the ':' after ${IND2}.
2104 1.892 rillig * Chain 1 continues with the the 2 modifiers ':O' and ':u'.
2105 1.892 rillig * Chain 1 ends at the final '}' of the expression.
2106 1.890 rillig *
2107 1.892 rillig * After such a chain ends, its properties no longer have any effect.
2108 1.889 rillig *
2109 1.887 rillig * It may or may not have been intended that 'defined' has scope Expr while
2110 1.887 rillig * 'sep' and 'oneBigWord' have smaller scope.
2111 1.823 rillig *
2112 1.823 rillig * See varmod-indirect.mk.
2113 1.823 rillig */
2114 1.891 rillig typedef struct ModChain {
2115 1.823 rillig Expr *expr;
2116 1.703 rillig /* '\0' or '{' or '(' */
2117 1.897 rillig char const_member startc;
2118 1.703 rillig /* '\0' or '}' or ')' */
2119 1.897 rillig char const_member endc;
2120 1.703 rillig /* Word separator in expansions (see the :ts modifier). */
2121 1.703 rillig char sep;
2122 1.703 rillig /*
2123 1.895 rillig * True if some modifiers that otherwise split the variable value
2124 1.703 rillig * into words, like :S and :C, treat the variable value as a single
2125 1.703 rillig * big word, possibly containing spaces.
2126 1.703 rillig */
2127 1.895 rillig bool oneBigWord;
2128 1.891 rillig } ModChain;
2129 1.236 rillig
2130 1.525 rillig static void
2131 1.812 rillig Expr_Define(Expr *expr)
2132 1.525 rillig {
2133 1.825 rillig if (expr->defined == DEF_UNDEF)
2134 1.825 rillig expr->defined = DEF_DEFINED;
2135 1.525 rillig }
2136 1.525 rillig
2137 1.813 rillig static void
2138 1.813 rillig Expr_SetValueOwn(Expr *expr, char *value)
2139 1.813 rillig {
2140 1.821 rillig FStr_Done(&expr->value);
2141 1.821 rillig expr->value = FStr_InitOwn(value);
2142 1.813 rillig }
2143 1.813 rillig
2144 1.813 rillig static void
2145 1.813 rillig Expr_SetValueRefer(Expr *expr, const char *value)
2146 1.813 rillig {
2147 1.821 rillig FStr_Done(&expr->value);
2148 1.821 rillig expr->value = FStr_InitRefer(value);
2149 1.813 rillig }
2150 1.813 rillig
2151 1.905 rillig static bool
2152 1.905 rillig Expr_ShouldEval(const Expr *expr)
2153 1.905 rillig {
2154 1.906 rillig return VarEvalMode_ShouldEval(expr->emode);
2155 1.905 rillig }
2156 1.905 rillig
2157 1.905 rillig static bool
2158 1.905 rillig ModChain_ShouldEval(const ModChain *ch)
2159 1.905 rillig {
2160 1.905 rillig return Expr_ShouldEval(ch->expr);
2161 1.905 rillig }
2162 1.905 rillig
2163 1.905 rillig
2164 1.578 rillig typedef enum ApplyModifierResult {
2165 1.703 rillig /* Continue parsing */
2166 1.703 rillig AMR_OK,
2167 1.830 rillig /* Not a match, try other modifiers as well. */
2168 1.703 rillig AMR_UNKNOWN,
2169 1.830 rillig /* Error out with "Bad modifier" message. */
2170 1.703 rillig AMR_BAD,
2171 1.830 rillig /* Error out without the standard error message. */
2172 1.703 rillig AMR_CLEANUP
2173 1.356 rillig } ApplyModifierResult;
2174 1.356 rillig
2175 1.703 rillig /*
2176 1.703 rillig * Allow backslashes to escape the delimiter, $, and \, but don't touch other
2177 1.703 rillig * backslashes.
2178 1.703 rillig */
2179 1.895 rillig static bool
2180 1.620 rillig IsEscapedModifierPart(const char *p, char delim,
2181 1.620 rillig struct ModifyWord_SubstArgs *subst)
2182 1.620 rillig {
2183 1.703 rillig if (p[0] != '\\')
2184 1.895 rillig return false;
2185 1.703 rillig if (p[1] == delim || p[1] == '\\' || p[1] == '$')
2186 1.895 rillig return true;
2187 1.703 rillig return p[1] == '&' && subst != NULL;
2188 1.620 rillig }
2189 1.620 rillig
2190 1.760 rillig /* See ParseModifierPart */
2191 1.531 rillig static VarParseResult
2192 1.760 rillig ParseModifierPartSubst(
2193 1.703 rillig const char **pp,
2194 1.703 rillig char delim,
2195 1.906 rillig VarEvalMode emode,
2196 1.891 rillig ModChain *ch,
2197 1.531 rillig char **out_part,
2198 1.703 rillig /* Optionally stores the length of the returned string, just to save
2199 1.703 rillig * another strlen call. */
2200 1.703 rillig size_t *out_length,
2201 1.703 rillig /* For the first part of the :S modifier, sets the VARP_ANCHOR_END flag
2202 1.703 rillig * if the last character of the pattern is a $. */
2203 1.703 rillig VarPatternFlags *out_pflags,
2204 1.703 rillig /* For the second part of the :S modifier, allow ampersands to be
2205 1.703 rillig * escaped and replace unescaped ampersands with subst->lhs. */
2206 1.541 rillig struct ModifyWord_SubstArgs *subst
2207 1.704 rillig )
2208 1.704 rillig {
2209 1.704 rillig Buffer buf;
2210 1.704 rillig const char *p;
2211 1.704 rillig
2212 1.704 rillig Buf_Init(&buf);
2213 1.704 rillig
2214 1.704 rillig /*
2215 1.704 rillig * Skim through until the matching delimiter is found; pick up
2216 1.704 rillig * variable expressions on the way.
2217 1.704 rillig */
2218 1.704 rillig p = *pp;
2219 1.704 rillig while (*p != '\0' && *p != delim) {
2220 1.704 rillig const char *varstart;
2221 1.704 rillig
2222 1.704 rillig if (IsEscapedModifierPart(p, delim, subst)) {
2223 1.704 rillig Buf_AddByte(&buf, p[1]);
2224 1.704 rillig p += 2;
2225 1.704 rillig continue;
2226 1.704 rillig }
2227 1.704 rillig
2228 1.704 rillig if (*p != '$') { /* Unescaped, simple text */
2229 1.704 rillig if (subst != NULL && *p == '&')
2230 1.704 rillig Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
2231 1.704 rillig else
2232 1.704 rillig Buf_AddByte(&buf, *p);
2233 1.704 rillig p++;
2234 1.704 rillig continue;
2235 1.704 rillig }
2236 1.529 rillig
2237 1.704 rillig if (p[1] == delim) { /* Unescaped $ at end of pattern */
2238 1.704 rillig if (out_pflags != NULL)
2239 1.895 rillig out_pflags->anchorEnd = true;
2240 1.704 rillig else
2241 1.704 rillig Buf_AddByte(&buf, *p);
2242 1.704 rillig p++;
2243 1.704 rillig continue;
2244 1.704 rillig }
2245 1.529 rillig
2246 1.906 rillig if (VarEvalMode_ShouldEval(emode)) {
2247 1.906 rillig /* Nested variable, evaluated */
2248 1.704 rillig const char *nested_p = p;
2249 1.743 rillig FStr nested_val;
2250 1.529 rillig
2251 1.891 rillig (void)Var_Parse(&nested_p, ch->expr->scope,
2252 1.906 rillig VarEvalMode_WithoutKeepDollar(emode), &nested_val);
2253 1.704 rillig /* TODO: handle errors */
2254 1.743 rillig Buf_AddStr(&buf, nested_val.str);
2255 1.743 rillig FStr_Done(&nested_val);
2256 1.704 rillig p += nested_p - p;
2257 1.704 rillig continue;
2258 1.704 rillig }
2259 1.704 rillig
2260 1.705 rillig /*
2261 1.705 rillig * XXX: This whole block is very similar to Var_Parse without
2262 1.885 rillig * VarEvalFlags.wantRes. There may be subtle edge cases
2263 1.885 rillig * though that are not yet covered in the unit tests and that
2264 1.885 rillig * are parsed differently, depending on whether they are
2265 1.885 rillig * evaluated or not.
2266 1.704 rillig *
2267 1.704 rillig * This subtle difference is not documented in the manual
2268 1.704 rillig * page, neither is the difference between parsing :D and
2269 1.704 rillig * :M documented. No code should ever depend on these
2270 1.704 rillig * details, but who knows.
2271 1.704 rillig */
2272 1.704 rillig
2273 1.705 rillig varstart = p; /* Nested variable, only parsed */
2274 1.704 rillig if (p[1] == '(' || p[1] == '{') {
2275 1.704 rillig /*
2276 1.704 rillig * Find the end of this variable reference
2277 1.704 rillig * and suck it in without further ado.
2278 1.704 rillig * It will be interpreted later.
2279 1.704 rillig */
2280 1.704 rillig char startc = p[1];
2281 1.704 rillig int endc = startc == '(' ? ')' : '}';
2282 1.704 rillig int depth = 1;
2283 1.704 rillig
2284 1.704 rillig for (p += 2; *p != '\0' && depth > 0; p++) {
2285 1.704 rillig if (p[-1] != '\\') {
2286 1.704 rillig if (*p == startc)
2287 1.704 rillig depth++;
2288 1.704 rillig if (*p == endc)
2289 1.704 rillig depth--;
2290 1.704 rillig }
2291 1.704 rillig }
2292 1.704 rillig Buf_AddBytesBetween(&buf, varstart, p);
2293 1.704 rillig } else {
2294 1.704 rillig Buf_AddByte(&buf, *varstart);
2295 1.704 rillig p++;
2296 1.529 rillig }
2297 1.529 rillig }
2298 1.529 rillig
2299 1.704 rillig if (*p != delim) {
2300 1.704 rillig *pp = p;
2301 1.842 rillig Error("Unfinished modifier for \"%s\" ('%c' missing)",
2302 1.898 rillig ch->expr->name, delim);
2303 1.704 rillig *out_part = NULL;
2304 1.767 rillig return VPR_ERR;
2305 1.704 rillig }
2306 1.704 rillig
2307 1.787 rillig *pp = p + 1;
2308 1.704 rillig if (out_length != NULL)
2309 1.786 rillig *out_length = buf.len;
2310 1.529 rillig
2311 1.784 rillig *out_part = Buf_DoneData(&buf);
2312 1.708 rillig DEBUG1(VAR, "Modifier part: \"%s\"\n", *out_part);
2313 1.704 rillig return VPR_OK;
2314 1.529 rillig }
2315 1.529 rillig
2316 1.760 rillig /*
2317 1.760 rillig * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
2318 1.760 rillig * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
2319 1.760 rillig * including the next unescaped delimiter. The delimiter, as well as the
2320 1.760 rillig * backslash or the dollar, can be escaped with a backslash.
2321 1.760 rillig *
2322 1.760 rillig * Return the parsed (and possibly expanded) string, or NULL if no delimiter
2323 1.760 rillig * was found. On successful return, the parsing position pp points right
2324 1.760 rillig * after the delimiter. The delimiter is not included in the returned
2325 1.760 rillig * value though.
2326 1.760 rillig */
2327 1.760 rillig static VarParseResult
2328 1.760 rillig ParseModifierPart(
2329 1.760 rillig /* The parsing position, updated upon return */
2330 1.760 rillig const char **pp,
2331 1.760 rillig /* Parsing stops at this delimiter */
2332 1.760 rillig char delim,
2333 1.906 rillig /* Mode for evaluating nested variables. */
2334 1.906 rillig VarEvalMode emode,
2335 1.891 rillig ModChain *ch,
2336 1.760 rillig char **out_part
2337 1.760 rillig )
2338 1.760 rillig {
2339 1.906 rillig return ParseModifierPartSubst(pp, delim, emode, ch, out_part,
2340 1.760 rillig NULL, NULL, NULL);
2341 1.760 rillig }
2342 1.760 rillig
2343 1.895 rillig MAKE_INLINE bool
2344 1.891 rillig IsDelimiter(char c, const ModChain *ch)
2345 1.859 rillig {
2346 1.891 rillig return c == ':' || c == ch->endc;
2347 1.859 rillig }
2348 1.859 rillig
2349 1.400 rillig /* Test whether mod starts with modname, followed by a delimiter. */
2350 1.895 rillig MAKE_INLINE bool
2351 1.891 rillig ModMatch(const char *mod, const char *modname, const ModChain *ch)
2352 1.340 rillig {
2353 1.703 rillig size_t n = strlen(modname);
2354 1.891 rillig return strncmp(mod, modname, n) == 0 && IsDelimiter(mod[n], ch);
2355 1.340 rillig }
2356 1.340 rillig
2357 1.400 rillig /* Test whether mod starts with modname, followed by a delimiter or '='. */
2358 1.895 rillig MAKE_INLINE bool
2359 1.891 rillig ModMatchEq(const char *mod, const char *modname, const ModChain *ch)
2360 1.340 rillig {
2361 1.703 rillig size_t n = strlen(modname);
2362 1.703 rillig return strncmp(mod, modname, n) == 0 &&
2363 1.891 rillig (IsDelimiter(mod[n], ch) || mod[n] == '=');
2364 1.340 rillig }
2365 1.236 rillig
2366 1.895 rillig static bool
2367 1.635 rillig TryParseIntBase0(const char **pp, int *out_num)
2368 1.635 rillig {
2369 1.703 rillig char *end;
2370 1.703 rillig long n;
2371 1.635 rillig
2372 1.703 rillig errno = 0;
2373 1.703 rillig n = strtol(*pp, &end, 0);
2374 1.865 rillig
2375 1.865 rillig if (end == *pp)
2376 1.895 rillig return false;
2377 1.703 rillig if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
2378 1.895 rillig return false;
2379 1.703 rillig if (n < INT_MIN || n > INT_MAX)
2380 1.895 rillig return false;
2381 1.635 rillig
2382 1.703 rillig *pp = end;
2383 1.703 rillig *out_num = (int)n;
2384 1.895 rillig return true;
2385 1.635 rillig }
2386 1.635 rillig
2387 1.895 rillig static bool
2388 1.635 rillig TryParseSize(const char **pp, size_t *out_num)
2389 1.635 rillig {
2390 1.703 rillig char *end;
2391 1.703 rillig unsigned long n;
2392 1.635 rillig
2393 1.703 rillig if (!ch_isdigit(**pp))
2394 1.895 rillig return false;
2395 1.635 rillig
2396 1.703 rillig errno = 0;
2397 1.703 rillig n = strtoul(*pp, &end, 10);
2398 1.703 rillig if (n == ULONG_MAX && errno == ERANGE)
2399 1.895 rillig return false;
2400 1.703 rillig if (n > SIZE_MAX)
2401 1.895 rillig return false;
2402 1.635 rillig
2403 1.703 rillig *pp = end;
2404 1.703 rillig *out_num = (size_t)n;
2405 1.895 rillig return true;
2406 1.635 rillig }
2407 1.635 rillig
2408 1.895 rillig static bool
2409 1.635 rillig TryParseChar(const char **pp, int base, char *out_ch)
2410 1.635 rillig {
2411 1.703 rillig char *end;
2412 1.703 rillig unsigned long n;
2413 1.635 rillig
2414 1.703 rillig if (!ch_isalnum(**pp))
2415 1.895 rillig return false;
2416 1.635 rillig
2417 1.703 rillig errno = 0;
2418 1.703 rillig n = strtoul(*pp, &end, base);
2419 1.703 rillig if (n == ULONG_MAX && errno == ERANGE)
2420 1.895 rillig return false;
2421 1.703 rillig if (n > UCHAR_MAX)
2422 1.895 rillig return false;
2423 1.635 rillig
2424 1.703 rillig *pp = end;
2425 1.703 rillig *out_ch = (char)n;
2426 1.895 rillig return true;
2427 1.635 rillig }
2428 1.635 rillig
2429 1.820 rillig /*
2430 1.822 rillig * Modify each word of the expression using the given function and place the
2431 1.822 rillig * result back in the expression.
2432 1.820 rillig */
2433 1.820 rillig static void
2434 1.891 rillig ModifyWords(ModChain *ch,
2435 1.822 rillig ModifyWordProc modifyWord, void *modifyWord_args,
2436 1.895 rillig bool oneBigWord)
2437 1.820 rillig {
2438 1.891 rillig Expr *expr = ch->expr;
2439 1.823 rillig const char *val = expr->value.str;
2440 1.820 rillig SepBuf result;
2441 1.820 rillig Words words;
2442 1.820 rillig size_t i;
2443 1.820 rillig
2444 1.820 rillig if (oneBigWord) {
2445 1.891 rillig SepBuf_Init(&result, ch->sep);
2446 1.823 rillig modifyWord(val, &result, modifyWord_args);
2447 1.820 rillig goto done;
2448 1.820 rillig }
2449 1.820 rillig
2450 1.895 rillig words = Str_Words(val, false);
2451 1.820 rillig
2452 1.820 rillig DEBUG2(VAR, "ModifyWords: split \"%s\" into %u words\n",
2453 1.823 rillig val, (unsigned)words.len);
2454 1.820 rillig
2455 1.891 rillig SepBuf_Init(&result, ch->sep);
2456 1.820 rillig for (i = 0; i < words.len; i++) {
2457 1.820 rillig modifyWord(words.words[i], &result, modifyWord_args);
2458 1.820 rillig if (result.buf.len > 0)
2459 1.820 rillig SepBuf_Sep(&result);
2460 1.820 rillig }
2461 1.820 rillig
2462 1.820 rillig Words_Free(words);
2463 1.820 rillig
2464 1.820 rillig done:
2465 1.823 rillig Expr_SetValueOwn(expr, SepBuf_DoneData(&result));
2466 1.820 rillig }
2467 1.820 rillig
2468 1.236 rillig /* :@var (at) ...${var}...@ */
2469 1.356 rillig static ApplyModifierResult
2470 1.891 rillig ApplyModifier_Loop(const char **pp, ModChain *ch)
2471 1.417 rillig {
2472 1.891 rillig Expr *expr = ch->expr;
2473 1.703 rillig struct ModifyWord_LoopArgs args;
2474 1.703 rillig char prev_sep;
2475 1.703 rillig VarParseResult res;
2476 1.703 rillig
2477 1.823 rillig args.scope = expr->scope;
2478 1.703 rillig
2479 1.703 rillig (*pp)++; /* Skip the first '@' */
2480 1.891 rillig res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, ch, &args.tvar);
2481 1.703 rillig if (res != VPR_OK)
2482 1.703 rillig return AMR_CLEANUP;
2483 1.907 rillig if (strchr(args.tvar, '$') != NULL) {
2484 1.703 rillig Parse_Error(PARSE_FATAL,
2485 1.410 rillig "In the :@ modifier of \"%s\", the variable name \"%s\" "
2486 1.410 rillig "must not contain a dollar.",
2487 1.898 rillig expr->name, args.tvar);
2488 1.703 rillig return AMR_CLEANUP;
2489 1.703 rillig }
2490 1.236 rillig
2491 1.891 rillig res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, ch, &args.str);
2492 1.703 rillig if (res != VPR_OK)
2493 1.703 rillig return AMR_CLEANUP;
2494 1.703 rillig
2495 1.906 rillig if (!Expr_ShouldEval(expr))
2496 1.870 rillig goto done;
2497 1.870 rillig
2498 1.906 rillig args.emode = VarEvalMode_WithoutKeepDollar(expr->emode);
2499 1.891 rillig prev_sep = ch->sep;
2500 1.891 rillig ch->sep = ' '; /* XXX: should be ch->sep for consistency */
2501 1.891 rillig ModifyWords(ch, ModifyWord_Loop, &args, ch->oneBigWord);
2502 1.891 rillig ch->sep = prev_sep;
2503 1.703 rillig /* XXX: Consider restoring the previous variable instead of deleting. */
2504 1.907 rillig Var_Delete(expr->scope, args.tvar);
2505 1.870 rillig
2506 1.870 rillig done:
2507 1.703 rillig free(args.tvar);
2508 1.703 rillig free(args.str);
2509 1.703 rillig return AMR_OK;
2510 1.236 rillig }
2511 1.236 rillig
2512 1.236 rillig /* :Ddefined or :Uundefined */
2513 1.356 rillig static ApplyModifierResult
2514 1.891 rillig ApplyModifier_Defined(const char **pp, ModChain *ch)
2515 1.236 rillig {
2516 1.891 rillig Expr *expr = ch->expr;
2517 1.703 rillig Buffer buf;
2518 1.703 rillig const char *p;
2519 1.412 rillig
2520 1.906 rillig VarEvalMode emode = VARE_PARSE_ONLY;
2521 1.906 rillig if (Expr_ShouldEval(expr))
2522 1.825 rillig if ((**pp == 'D') == (expr->defined == DEF_REGULAR))
2523 1.906 rillig emode = expr->emode;
2524 1.703 rillig
2525 1.703 rillig Buf_Init(&buf);
2526 1.703 rillig p = *pp + 1;
2527 1.891 rillig while (!IsDelimiter(*p, ch) && *p != '\0') {
2528 1.703 rillig
2529 1.703 rillig /* XXX: This code is similar to the one in Var_Parse.
2530 1.703 rillig * See if the code can be merged.
2531 1.830 rillig * See also ApplyModifier_Match and ParseModifierPart. */
2532 1.703 rillig
2533 1.703 rillig /* Escaped delimiter or other special character */
2534 1.830 rillig /* See Buf_AddEscaped in for.c. */
2535 1.703 rillig if (*p == '\\') {
2536 1.703 rillig char c = p[1];
2537 1.891 rillig if (IsDelimiter(c, ch) || c == '$' || c == '\\') {
2538 1.703 rillig Buf_AddByte(&buf, c);
2539 1.703 rillig p += 2;
2540 1.703 rillig continue;
2541 1.703 rillig }
2542 1.703 rillig }
2543 1.236 rillig
2544 1.703 rillig /* Nested variable expression */
2545 1.703 rillig if (*p == '$') {
2546 1.743 rillig FStr nested_val;
2547 1.466 rillig
2548 1.906 rillig (void)Var_Parse(&p, expr->scope, emode, &nested_val);
2549 1.703 rillig /* TODO: handle errors */
2550 1.906 rillig if (Expr_ShouldEval(expr))
2551 1.871 rillig Buf_AddStr(&buf, nested_val.str);
2552 1.743 rillig FStr_Done(&nested_val);
2553 1.703 rillig continue;
2554 1.703 rillig }
2555 1.687 rillig
2556 1.703 rillig /* Ordinary text */
2557 1.703 rillig Buf_AddByte(&buf, *p);
2558 1.703 rillig p++;
2559 1.466 rillig }
2560 1.703 rillig *pp = p;
2561 1.466 rillig
2562 1.823 rillig Expr_Define(expr);
2563 1.236 rillig
2564 1.906 rillig if (VarEvalMode_ShouldEval(emode))
2565 1.823 rillig Expr_SetValueOwn(expr, Buf_DoneData(&buf));
2566 1.821 rillig else
2567 1.784 rillig Buf_Done(&buf);
2568 1.821 rillig
2569 1.703 rillig return AMR_OK;
2570 1.236 rillig }
2571 1.236 rillig
2572 1.567 rillig /* :L */
2573 1.567 rillig static ApplyModifierResult
2574 1.891 rillig ApplyModifier_Literal(const char **pp, ModChain *ch)
2575 1.567 rillig {
2576 1.891 rillig Expr *expr = ch->expr;
2577 1.864 rillig
2578 1.864 rillig (*pp)++;
2579 1.864 rillig
2580 1.905 rillig if (Expr_ShouldEval(expr)) {
2581 1.872 rillig Expr_Define(expr);
2582 1.898 rillig Expr_SetValueOwn(expr, bmake_strdup(expr->name));
2583 1.872 rillig }
2584 1.864 rillig
2585 1.703 rillig return AMR_OK;
2586 1.567 rillig }
2587 1.567 rillig
2588 1.895 rillig static bool
2589 1.633 rillig TryParseTime(const char **pp, time_t *out_time)
2590 1.631 rillig {
2591 1.703 rillig char *end;
2592 1.703 rillig unsigned long n;
2593 1.631 rillig
2594 1.703 rillig if (!ch_isdigit(**pp))
2595 1.895 rillig return false;
2596 1.631 rillig
2597 1.703 rillig errno = 0;
2598 1.703 rillig n = strtoul(*pp, &end, 10);
2599 1.703 rillig if (n == ULONG_MAX && errno == ERANGE)
2600 1.895 rillig return false;
2601 1.631 rillig
2602 1.703 rillig *pp = end;
2603 1.703 rillig *out_time = (time_t)n; /* ignore possible truncation for now */
2604 1.895 rillig return true;
2605 1.631 rillig }
2606 1.631 rillig
2607 1.236 rillig /* :gmtime */
2608 1.356 rillig static ApplyModifierResult
2609 1.891 rillig ApplyModifier_Gmtime(const char **pp, ModChain *ch)
2610 1.236 rillig {
2611 1.703 rillig time_t utc;
2612 1.412 rillig
2613 1.703 rillig const char *mod = *pp;
2614 1.891 rillig if (!ModMatchEq(mod, "gmtime", ch))
2615 1.703 rillig return AMR_UNKNOWN;
2616 1.703 rillig
2617 1.703 rillig if (mod[6] == '=') {
2618 1.843 rillig const char *p = mod + 7;
2619 1.843 rillig if (!TryParseTime(&p, &utc)) {
2620 1.703 rillig Parse_Error(PARSE_FATAL,
2621 1.761 rillig "Invalid time value: %s", mod + 7);
2622 1.703 rillig return AMR_CLEANUP;
2623 1.703 rillig }
2624 1.843 rillig *pp = p;
2625 1.703 rillig } else {
2626 1.703 rillig utc = 0;
2627 1.703 rillig *pp = mod + 6;
2628 1.631 rillig }
2629 1.864 rillig
2630 1.905 rillig if (ModChain_ShouldEval(ch))
2631 1.891 rillig Expr_SetValueOwn(ch->expr,
2632 1.895 rillig VarStrftime(ch->expr->value.str, true, utc));
2633 1.864 rillig
2634 1.703 rillig return AMR_OK;
2635 1.236 rillig }
2636 1.236 rillig
2637 1.236 rillig /* :localtime */
2638 1.505 rillig static ApplyModifierResult
2639 1.891 rillig ApplyModifier_Localtime(const char **pp, ModChain *ch)
2640 1.236 rillig {
2641 1.703 rillig time_t utc;
2642 1.412 rillig
2643 1.703 rillig const char *mod = *pp;
2644 1.891 rillig if (!ModMatchEq(mod, "localtime", ch))
2645 1.703 rillig return AMR_UNKNOWN;
2646 1.703 rillig
2647 1.703 rillig if (mod[9] == '=') {
2648 1.843 rillig const char *p = mod + 10;
2649 1.843 rillig if (!TryParseTime(&p, &utc)) {
2650 1.703 rillig Parse_Error(PARSE_FATAL,
2651 1.761 rillig "Invalid time value: %s", mod + 10);
2652 1.703 rillig return AMR_CLEANUP;
2653 1.703 rillig }
2654 1.843 rillig *pp = p;
2655 1.703 rillig } else {
2656 1.703 rillig utc = 0;
2657 1.703 rillig *pp = mod + 9;
2658 1.631 rillig }
2659 1.864 rillig
2660 1.905 rillig if (ModChain_ShouldEval(ch))
2661 1.891 rillig Expr_SetValueOwn(ch->expr,
2662 1.895 rillig VarStrftime(ch->expr->value.str, false, utc));
2663 1.864 rillig
2664 1.703 rillig return AMR_OK;
2665 1.236 rillig }
2666 1.236 rillig
2667 1.236 rillig /* :hash */
2668 1.356 rillig static ApplyModifierResult
2669 1.891 rillig ApplyModifier_Hash(const char **pp, ModChain *ch)
2670 1.236 rillig {
2671 1.891 rillig if (!ModMatch(*pp, "hash", ch))
2672 1.703 rillig return AMR_UNKNOWN;
2673 1.864 rillig *pp += 4;
2674 1.340 rillig
2675 1.905 rillig if (ModChain_ShouldEval(ch))
2676 1.891 rillig Expr_SetValueOwn(ch->expr, VarHash(ch->expr->value.str));
2677 1.864 rillig
2678 1.703 rillig return AMR_OK;
2679 1.236 rillig }
2680 1.236 rillig
2681 1.236 rillig /* :P */
2682 1.356 rillig static ApplyModifierResult
2683 1.891 rillig ApplyModifier_Path(const char **pp, ModChain *ch)
2684 1.236 rillig {
2685 1.891 rillig Expr *expr = ch->expr;
2686 1.703 rillig GNode *gn;
2687 1.703 rillig char *path;
2688 1.412 rillig
2689 1.864 rillig (*pp)++;
2690 1.864 rillig
2691 1.905 rillig if (!ModChain_ShouldEval(ch))
2692 1.873 rillig return AMR_OK;
2693 1.873 rillig
2694 1.823 rillig Expr_Define(expr);
2695 1.409 rillig
2696 1.898 rillig gn = Targ_FindNode(expr->name);
2697 1.703 rillig if (gn == NULL || gn->type & OP_NOPATH) {
2698 1.703 rillig path = NULL;
2699 1.703 rillig } else if (gn->path != NULL) {
2700 1.703 rillig path = bmake_strdup(gn->path);
2701 1.703 rillig } else {
2702 1.703 rillig SearchPath *searchPath = Suff_FindPath(gn);
2703 1.898 rillig path = Dir_FindFile(expr->name, searchPath);
2704 1.703 rillig }
2705 1.703 rillig if (path == NULL)
2706 1.898 rillig path = bmake_strdup(expr->name);
2707 1.823 rillig Expr_SetValueOwn(expr, path);
2708 1.409 rillig
2709 1.703 rillig return AMR_OK;
2710 1.236 rillig }
2711 1.236 rillig
2712 1.236 rillig /* :!cmd! */
2713 1.356 rillig static ApplyModifierResult
2714 1.891 rillig ApplyModifier_ShellCommand(const char **pp, ModChain *ch)
2715 1.236 rillig {
2716 1.891 rillig Expr *expr = ch->expr;
2717 1.703 rillig char *cmd;
2718 1.703 rillig const char *errfmt;
2719 1.703 rillig VarParseResult res;
2720 1.703 rillig
2721 1.703 rillig (*pp)++;
2722 1.906 rillig res = ParseModifierPart(pp, '!', expr->emode, ch, &cmd);
2723 1.703 rillig if (res != VPR_OK)
2724 1.703 rillig return AMR_CLEANUP;
2725 1.703 rillig
2726 1.703 rillig errfmt = NULL;
2727 1.905 rillig if (Expr_ShouldEval(expr))
2728 1.823 rillig Expr_SetValueOwn(expr, Cmd_Exec(cmd, &errfmt));
2729 1.703 rillig else
2730 1.823 rillig Expr_SetValueRefer(expr, "");
2731 1.703 rillig if (errfmt != NULL)
2732 1.703 rillig Error(errfmt, cmd); /* XXX: why still return AMR_OK? */
2733 1.703 rillig free(cmd);
2734 1.864 rillig Expr_Define(expr);
2735 1.274 rillig
2736 1.703 rillig return AMR_OK;
2737 1.236 rillig }
2738 1.236 rillig
2739 1.778 rillig /*
2740 1.778 rillig * The :range modifier generates an integer sequence as long as the words.
2741 1.778 rillig * The :range=7 modifier generates an integer sequence from 1 to 7.
2742 1.778 rillig */
2743 1.356 rillig static ApplyModifierResult
2744 1.891 rillig ApplyModifier_Range(const char **pp, ModChain *ch)
2745 1.236 rillig {
2746 1.703 rillig size_t n;
2747 1.703 rillig Buffer buf;
2748 1.703 rillig size_t i;
2749 1.412 rillig
2750 1.703 rillig const char *mod = *pp;
2751 1.891 rillig if (!ModMatchEq(mod, "range", ch))
2752 1.703 rillig return AMR_UNKNOWN;
2753 1.703 rillig
2754 1.703 rillig if (mod[5] == '=') {
2755 1.703 rillig const char *p = mod + 6;
2756 1.703 rillig if (!TryParseSize(&p, &n)) {
2757 1.703 rillig Parse_Error(PARSE_FATAL,
2758 1.844 rillig "Invalid number \"%s\" for ':range' modifier",
2759 1.844 rillig mod + 6);
2760 1.703 rillig return AMR_CLEANUP;
2761 1.703 rillig }
2762 1.703 rillig *pp = p;
2763 1.703 rillig } else {
2764 1.703 rillig n = 0;
2765 1.703 rillig *pp = mod + 5;
2766 1.635 rillig }
2767 1.386 rillig
2768 1.905 rillig if (!ModChain_ShouldEval(ch))
2769 1.873 rillig return AMR_OK;
2770 1.873 rillig
2771 1.703 rillig if (n == 0) {
2772 1.895 rillig Words words = Str_Words(ch->expr->value.str, false);
2773 1.703 rillig n = words.len;
2774 1.703 rillig Words_Free(words);
2775 1.703 rillig }
2776 1.386 rillig
2777 1.703 rillig Buf_Init(&buf);
2778 1.386 rillig
2779 1.703 rillig for (i = 0; i < n; i++) {
2780 1.703 rillig if (i != 0) {
2781 1.891 rillig /* XXX: Use ch->sep instead of ' ', for consistency. */
2782 1.703 rillig Buf_AddByte(&buf, ' ');
2783 1.703 rillig }
2784 1.703 rillig Buf_AddInt(&buf, 1 + (int)i);
2785 1.703 rillig }
2786 1.386 rillig
2787 1.891 rillig Expr_SetValueOwn(ch->expr, Buf_DoneData(&buf));
2788 1.703 rillig return AMR_OK;
2789 1.236 rillig }
2790 1.236 rillig
2791 1.845 rillig /* Parse a ':M' or ':N' modifier. */
2792 1.845 rillig static void
2793 1.891 rillig ParseModifier_Match(const char **pp, const ModChain *ch,
2794 1.845 rillig char **out_pattern)
2795 1.236 rillig {
2796 1.845 rillig const char *mod = *pp;
2797 1.891 rillig Expr *expr = ch->expr;
2798 1.895 rillig bool copy = false; /* pattern should be, or has been, copied */
2799 1.895 rillig bool needSubst = false;
2800 1.703 rillig const char *endpat;
2801 1.703 rillig char *pattern;
2802 1.412 rillig
2803 1.703 rillig /*
2804 1.703 rillig * In the loop below, ignore ':' unless we are at (or back to) the
2805 1.703 rillig * original brace level.
2806 1.703 rillig * XXX: This will likely not work right if $() and ${} are intermixed.
2807 1.703 rillig */
2808 1.845 rillig /*
2809 1.845 rillig * XXX: This code is similar to the one in Var_Parse.
2810 1.703 rillig * See if the code can be merged.
2811 1.845 rillig * See also ApplyModifier_Defined.
2812 1.845 rillig */
2813 1.703 rillig int nest = 0;
2814 1.703 rillig const char *p;
2815 1.703 rillig for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
2816 1.703 rillig if (*p == '\\' &&
2817 1.891 rillig (IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
2818 1.703 rillig if (!needSubst)
2819 1.895 rillig copy = true;
2820 1.703 rillig p++;
2821 1.703 rillig continue;
2822 1.703 rillig }
2823 1.703 rillig if (*p == '$')
2824 1.895 rillig needSubst = true;
2825 1.703 rillig if (*p == '(' || *p == '{')
2826 1.703 rillig nest++;
2827 1.703 rillig if (*p == ')' || *p == '}') {
2828 1.703 rillig nest--;
2829 1.703 rillig if (nest < 0)
2830 1.703 rillig break;
2831 1.703 rillig }
2832 1.236 rillig }
2833 1.703 rillig *pp = p;
2834 1.703 rillig endpat = p;
2835 1.703 rillig
2836 1.703 rillig if (copy) {
2837 1.703 rillig char *dst;
2838 1.703 rillig const char *src;
2839 1.703 rillig
2840 1.703 rillig /* Compress the \:'s out of the pattern. */
2841 1.703 rillig pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
2842 1.703 rillig dst = pattern;
2843 1.703 rillig src = mod + 1;
2844 1.703 rillig for (; src < endpat; src++, dst++) {
2845 1.703 rillig if (src[0] == '\\' && src + 1 < endpat &&
2846 1.891 rillig /* XXX: ch->startc is missing here; see above */
2847 1.891 rillig IsDelimiter(src[1], ch))
2848 1.703 rillig src++;
2849 1.703 rillig *dst = *src;
2850 1.703 rillig }
2851 1.703 rillig *dst = '\0';
2852 1.703 rillig } else {
2853 1.703 rillig pattern = bmake_strsedup(mod + 1, endpat);
2854 1.236 rillig }
2855 1.288 rillig
2856 1.703 rillig if (needSubst) {
2857 1.703 rillig char *old_pattern = pattern;
2858 1.906 rillig (void)Var_Subst(pattern, expr->scope, expr->emode, &pattern);
2859 1.703 rillig /* TODO: handle errors */
2860 1.703 rillig free(old_pattern);
2861 1.236 rillig }
2862 1.346 rillig
2863 1.908 rillig DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
2864 1.346 rillig
2865 1.845 rillig *out_pattern = pattern;
2866 1.845 rillig }
2867 1.845 rillig
2868 1.845 rillig /* :Mpattern or :Npattern */
2869 1.845 rillig static ApplyModifierResult
2870 1.891 rillig ApplyModifier_Match(const char **pp, ModChain *ch)
2871 1.845 rillig {
2872 1.876 rillig const char mod = **pp;
2873 1.845 rillig char *pattern;
2874 1.845 rillig
2875 1.891 rillig ParseModifier_Match(pp, ch, &pattern);
2876 1.845 rillig
2877 1.905 rillig if (ModChain_ShouldEval(ch)) {
2878 1.876 rillig ModifyWordProc modifyWord =
2879 1.876 rillig mod == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
2880 1.891 rillig ModifyWords(ch, modifyWord, pattern, ch->oneBigWord);
2881 1.876 rillig }
2882 1.876 rillig
2883 1.703 rillig free(pattern);
2884 1.703 rillig return AMR_OK;
2885 1.236 rillig }
2886 1.236 rillig
2887 1.860 rillig static void
2888 1.895 rillig ParsePatternFlags(const char **pp, VarPatternFlags *pflags, bool *oneBigWord)
2889 1.860 rillig {
2890 1.860 rillig for (;; (*pp)++) {
2891 1.860 rillig if (**pp == 'g')
2892 1.895 rillig pflags->subGlobal = true;
2893 1.860 rillig else if (**pp == '1')
2894 1.895 rillig pflags->subOnce = true;
2895 1.860 rillig else if (**pp == 'W')
2896 1.895 rillig *oneBigWord = true;
2897 1.860 rillig else
2898 1.860 rillig break;
2899 1.860 rillig }
2900 1.860 rillig }
2901 1.860 rillig
2902 1.897 rillig #if __STDC_VERSION__ >= 199901L
2903 1.897 rillig #define VarPatternFlags_Literal() (VarPatternFlags) { false, false, false, false }
2904 1.897 rillig #else
2905 1.897 rillig MAKE_INLINE VarPatternFlags
2906 1.897 rillig VarPatternFlags_Literal(void)
2907 1.897 rillig {
2908 1.897 rillig VarPatternFlags pflags = { false, false, false, false };
2909 1.897 rillig return pflags;
2910 1.897 rillig }
2911 1.897 rillig #endif
2912 1.897 rillig
2913 1.236 rillig /* :S,from,to, */
2914 1.356 rillig static ApplyModifierResult
2915 1.891 rillig ApplyModifier_Subst(const char **pp, ModChain *ch)
2916 1.236 rillig {
2917 1.703 rillig struct ModifyWord_SubstArgs args;
2918 1.703 rillig char *lhs, *rhs;
2919 1.895 rillig bool oneBigWord;
2920 1.703 rillig VarParseResult res;
2921 1.299 rillig
2922 1.703 rillig char delim = (*pp)[1];
2923 1.703 rillig if (delim == '\0') {
2924 1.846 rillig Error("Missing delimiter for modifier ':S'");
2925 1.703 rillig (*pp)++;
2926 1.703 rillig return AMR_CLEANUP;
2927 1.703 rillig }
2928 1.236 rillig
2929 1.703 rillig *pp += 2;
2930 1.236 rillig
2931 1.897 rillig args.pflags = VarPatternFlags_Literal();
2932 1.895 rillig args.matched = false;
2933 1.236 rillig
2934 1.703 rillig if (**pp == '^') {
2935 1.895 rillig args.pflags.anchorStart = true;
2936 1.703 rillig (*pp)++;
2937 1.703 rillig }
2938 1.703 rillig
2939 1.906 rillig res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &lhs,
2940 1.760 rillig &args.lhsLen, &args.pflags, NULL);
2941 1.703 rillig if (res != VPR_OK)
2942 1.703 rillig return AMR_CLEANUP;
2943 1.703 rillig args.lhs = lhs;
2944 1.703 rillig
2945 1.906 rillig res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &rhs,
2946 1.760 rillig &args.rhsLen, NULL, &args);
2947 1.703 rillig if (res != VPR_OK)
2948 1.703 rillig return AMR_CLEANUP;
2949 1.703 rillig args.rhs = rhs;
2950 1.703 rillig
2951 1.891 rillig oneBigWord = ch->oneBigWord;
2952 1.860 rillig ParsePatternFlags(pp, &args.pflags, &oneBigWord);
2953 1.236 rillig
2954 1.891 rillig ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
2955 1.236 rillig
2956 1.703 rillig free(lhs);
2957 1.703 rillig free(rhs);
2958 1.703 rillig return AMR_OK;
2959 1.236 rillig }
2960 1.236 rillig
2961 1.236 rillig #ifndef NO_REGEX
2962 1.291 rillig
2963 1.236 rillig /* :C,from,to, */
2964 1.356 rillig static ApplyModifierResult
2965 1.891 rillig ApplyModifier_Regex(const char **pp, ModChain *ch)
2966 1.236 rillig {
2967 1.703 rillig char *re;
2968 1.703 rillig struct ModifyWord_SubstRegexArgs args;
2969 1.895 rillig bool oneBigWord;
2970 1.703 rillig int error;
2971 1.703 rillig VarParseResult res;
2972 1.703 rillig
2973 1.703 rillig char delim = (*pp)[1];
2974 1.703 rillig if (delim == '\0') {
2975 1.703 rillig Error("Missing delimiter for :C modifier");
2976 1.703 rillig (*pp)++;
2977 1.703 rillig return AMR_CLEANUP;
2978 1.703 rillig }
2979 1.703 rillig
2980 1.703 rillig *pp += 2;
2981 1.236 rillig
2982 1.906 rillig res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &re);
2983 1.703 rillig if (res != VPR_OK)
2984 1.703 rillig return AMR_CLEANUP;
2985 1.703 rillig
2986 1.906 rillig res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &args.replace);
2987 1.703 rillig if (args.replace == NULL) {
2988 1.703 rillig free(re);
2989 1.703 rillig return AMR_CLEANUP;
2990 1.703 rillig }
2991 1.703 rillig
2992 1.897 rillig args.pflags = VarPatternFlags_Literal();
2993 1.895 rillig args.matched = false;
2994 1.891 rillig oneBigWord = ch->oneBigWord;
2995 1.860 rillig ParsePatternFlags(pp, &args.pflags, &oneBigWord);
2996 1.236 rillig
2997 1.905 rillig if (!ModChain_ShouldEval(ch)) {
2998 1.856 rillig free(args.replace);
2999 1.856 rillig free(re);
3000 1.856 rillig return AMR_OK;
3001 1.856 rillig }
3002 1.856 rillig
3003 1.703 rillig error = regcomp(&args.re, re, REG_EXTENDED);
3004 1.236 rillig free(re);
3005 1.703 rillig if (error != 0) {
3006 1.703 rillig VarREError(error, &args.re, "Regex compilation error");
3007 1.703 rillig free(args.replace);
3008 1.703 rillig return AMR_CLEANUP;
3009 1.236 rillig }
3010 1.236 rillig
3011 1.703 rillig args.nsub = args.re.re_nsub + 1;
3012 1.703 rillig if (args.nsub > 10)
3013 1.703 rillig args.nsub = 10;
3014 1.820 rillig
3015 1.891 rillig ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
3016 1.820 rillig
3017 1.703 rillig regfree(&args.re);
3018 1.291 rillig free(args.replace);
3019 1.703 rillig return AMR_OK;
3020 1.703 rillig }
3021 1.236 rillig
3022 1.236 rillig #endif
3023 1.236 rillig
3024 1.555 rillig /* :Q, :q */
3025 1.555 rillig static ApplyModifierResult
3026 1.891 rillig ApplyModifier_Quote(const char **pp, ModChain *ch)
3027 1.555 rillig {
3028 1.895 rillig bool quoteDollar = **pp == 'q';
3029 1.891 rillig if (!IsDelimiter((*pp)[1], ch))
3030 1.703 rillig return AMR_UNKNOWN;
3031 1.861 rillig (*pp)++;
3032 1.861 rillig
3033 1.905 rillig if (ModChain_ShouldEval(ch))
3034 1.891 rillig Expr_SetValueOwn(ch->expr,
3035 1.891 rillig VarQuote(ch->expr->value.str, quoteDollar));
3036 1.861 rillig
3037 1.861 rillig return AMR_OK;
3038 1.555 rillig }
3039 1.555 rillig
3040 1.779 rillig /*ARGSUSED*/
3041 1.278 rillig static void
3042 1.295 rillig ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
3043 1.278 rillig {
3044 1.703 rillig SepBuf_AddStr(buf, word);
3045 1.275 rillig }
3046 1.275 rillig
3047 1.289 rillig /* :ts<separator> */
3048 1.356 rillig static ApplyModifierResult
3049 1.891 rillig ApplyModifier_ToSep(const char **pp, ModChain *ch)
3050 1.289 rillig {
3051 1.703 rillig const char *sep = *pp + 2;
3052 1.703 rillig
3053 1.873 rillig /*
3054 1.885 rillig * Even in parse-only mode, proceed as normal since there is
3055 1.873 rillig * neither any observable side effect nor a performance penalty.
3056 1.885 rillig * Checking for wantRes for every single piece of code in here
3057 1.873 rillig * would make the code in this function too hard to read.
3058 1.873 rillig */
3059 1.873 rillig
3060 1.703 rillig /* ":ts<any><endc>" or ":ts<any>:" */
3061 1.891 rillig if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
3062 1.864 rillig *pp = sep + 1;
3063 1.891 rillig ch->sep = sep[0];
3064 1.703 rillig goto ok;
3065 1.703 rillig }
3066 1.468 rillig
3067 1.703 rillig /* ":ts<endc>" or ":ts:" */
3068 1.891 rillig if (IsDelimiter(sep[0], ch)) {
3069 1.864 rillig *pp = sep;
3070 1.891 rillig ch->sep = '\0'; /* no separator */
3071 1.703 rillig goto ok;
3072 1.703 rillig }
3073 1.468 rillig
3074 1.703 rillig /* ":ts<unrecognised><unrecognised>". */
3075 1.703 rillig if (sep[0] != '\\') {
3076 1.703 rillig (*pp)++; /* just for backwards compatibility */
3077 1.703 rillig return AMR_BAD;
3078 1.703 rillig }
3079 1.468 rillig
3080 1.703 rillig /* ":ts\n" */
3081 1.703 rillig if (sep[1] == 'n') {
3082 1.864 rillig *pp = sep + 2;
3083 1.891 rillig ch->sep = '\n';
3084 1.703 rillig goto ok;
3085 1.703 rillig }
3086 1.468 rillig
3087 1.703 rillig /* ":ts\t" */
3088 1.703 rillig if (sep[1] == 't') {
3089 1.864 rillig *pp = sep + 2;
3090 1.891 rillig ch->sep = '\t';
3091 1.703 rillig goto ok;
3092 1.703 rillig }
3093 1.468 rillig
3094 1.703 rillig /* ":ts\x40" or ":ts\100" */
3095 1.703 rillig {
3096 1.703 rillig const char *p = sep + 1;
3097 1.703 rillig int base = 8; /* assume octal */
3098 1.468 rillig
3099 1.703 rillig if (sep[1] == 'x') {
3100 1.703 rillig base = 16;
3101 1.703 rillig p++;
3102 1.703 rillig } else if (!ch_isdigit(sep[1])) {
3103 1.703 rillig (*pp)++; /* just for backwards compatibility */
3104 1.703 rillig return AMR_BAD; /* ":ts<backslash><unrecognised>". */
3105 1.703 rillig }
3106 1.289 rillig
3107 1.891 rillig if (!TryParseChar(&p, base, &ch->sep)) {
3108 1.703 rillig Parse_Error(PARSE_FATAL,
3109 1.761 rillig "Invalid character number: %s", p);
3110 1.703 rillig return AMR_CLEANUP;
3111 1.703 rillig }
3112 1.891 rillig if (!IsDelimiter(*p, ch)) {
3113 1.703 rillig (*pp)++; /* just for backwards compatibility */
3114 1.703 rillig return AMR_BAD;
3115 1.703 rillig }
3116 1.468 rillig
3117 1.703 rillig *pp = p;
3118 1.556 rillig }
3119 1.635 rillig
3120 1.468 rillig ok:
3121 1.891 rillig ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
3122 1.703 rillig return AMR_OK;
3123 1.289 rillig }
3124 1.289 rillig
3125 1.738 rillig static char *
3126 1.738 rillig str_toupper(const char *str)
3127 1.738 rillig {
3128 1.738 rillig char *res;
3129 1.738 rillig size_t i, len;
3130 1.738 rillig
3131 1.738 rillig len = strlen(str);
3132 1.738 rillig res = bmake_malloc(len + 1);
3133 1.738 rillig for (i = 0; i < len + 1; i++)
3134 1.738 rillig res[i] = ch_toupper(str[i]);
3135 1.738 rillig
3136 1.738 rillig return res;
3137 1.738 rillig }
3138 1.738 rillig
3139 1.738 rillig static char *
3140 1.738 rillig str_tolower(const char *str)
3141 1.738 rillig {
3142 1.738 rillig char *res;
3143 1.738 rillig size_t i, len;
3144 1.738 rillig
3145 1.738 rillig len = strlen(str);
3146 1.738 rillig res = bmake_malloc(len + 1);
3147 1.738 rillig for (i = 0; i < len + 1; i++)
3148 1.738 rillig res[i] = ch_tolower(str[i]);
3149 1.738 rillig
3150 1.738 rillig return res;
3151 1.738 rillig }
3152 1.738 rillig
3153 1.289 rillig /* :tA, :tu, :tl, :ts<separator>, etc. */
3154 1.356 rillig static ApplyModifierResult
3155 1.891 rillig ApplyModifier_To(const char **pp, ModChain *ch)
3156 1.236 rillig {
3157 1.891 rillig Expr *expr = ch->expr;
3158 1.703 rillig const char *mod = *pp;
3159 1.703 rillig assert(mod[0] == 't');
3160 1.363 rillig
3161 1.891 rillig if (IsDelimiter(mod[1], ch) || mod[1] == '\0') {
3162 1.703 rillig *pp = mod + 1;
3163 1.703 rillig return AMR_BAD; /* Found ":t<endc>" or ":t:". */
3164 1.703 rillig }
3165 1.289 rillig
3166 1.703 rillig if (mod[1] == 's')
3167 1.891 rillig return ApplyModifier_ToSep(pp, ch);
3168 1.289 rillig
3169 1.891 rillig if (!IsDelimiter(mod[2], ch)) { /* :t<unrecognized> */
3170 1.703 rillig *pp = mod + 1;
3171 1.810 rillig return AMR_BAD;
3172 1.703 rillig }
3173 1.236 rillig
3174 1.810 rillig if (mod[1] == 'A') { /* :tA */
3175 1.864 rillig *pp = mod + 2;
3176 1.891 rillig ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
3177 1.703 rillig return AMR_OK;
3178 1.703 rillig }
3179 1.475 rillig
3180 1.810 rillig if (mod[1] == 'u') { /* :tu */
3181 1.864 rillig *pp = mod + 2;
3182 1.905 rillig if (ModChain_ShouldEval(ch))
3183 1.873 rillig Expr_SetValueOwn(expr, str_toupper(expr->value.str));
3184 1.703 rillig return AMR_OK;
3185 1.703 rillig }
3186 1.475 rillig
3187 1.810 rillig if (mod[1] == 'l') { /* :tl */
3188 1.864 rillig *pp = mod + 2;
3189 1.905 rillig if (ModChain_ShouldEval(ch))
3190 1.873 rillig Expr_SetValueOwn(expr, str_tolower(expr->value.str));
3191 1.703 rillig return AMR_OK;
3192 1.703 rillig }
3193 1.475 rillig
3194 1.810 rillig if (mod[1] == 'W' || mod[1] == 'w') { /* :tW, :tw */
3195 1.864 rillig *pp = mod + 2;
3196 1.891 rillig ch->oneBigWord = mod[1] == 'W';
3197 1.703 rillig return AMR_OK;
3198 1.703 rillig }
3199 1.475 rillig
3200 1.703 rillig /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
3201 1.864 rillig *pp = mod + 1; /* XXX: unnecessary but observable */
3202 1.703 rillig return AMR_BAD;
3203 1.236 rillig }
3204 1.236 rillig
3205 1.634 rillig /* :[#], :[1], :[-1..1], etc. */
3206 1.356 rillig static ApplyModifierResult
3207 1.891 rillig ApplyModifier_Words(const char **pp, ModChain *ch)
3208 1.236 rillig {
3209 1.891 rillig Expr *expr = ch->expr;
3210 1.703 rillig char *estr;
3211 1.703 rillig int first, last;
3212 1.703 rillig VarParseResult res;
3213 1.703 rillig const char *p;
3214 1.412 rillig
3215 1.703 rillig (*pp)++; /* skip the '[' */
3216 1.906 rillig res = ParseModifierPart(pp, ']', expr->emode, ch, &estr);
3217 1.703 rillig if (res != VPR_OK)
3218 1.703 rillig return AMR_CLEANUP;
3219 1.703 rillig
3220 1.891 rillig if (!IsDelimiter(**pp, ch))
3221 1.810 rillig goto bad_modifier; /* Found junk after ']' */
3222 1.703 rillig
3223 1.905 rillig if (!ModChain_ShouldEval(ch))
3224 1.877 rillig goto ok;
3225 1.877 rillig
3226 1.703 rillig if (estr[0] == '\0')
3227 1.810 rillig goto bad_modifier; /* Found ":[]". */
3228 1.703 rillig
3229 1.810 rillig if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
3230 1.891 rillig if (ch->oneBigWord) {
3231 1.823 rillig Expr_SetValueRefer(expr, "1");
3232 1.703 rillig } else {
3233 1.703 rillig Buffer buf;
3234 1.412 rillig
3235 1.895 rillig Words words = Str_Words(expr->value.str, false);
3236 1.703 rillig size_t ac = words.len;
3237 1.703 rillig Words_Free(words);
3238 1.703 rillig
3239 1.703 rillig /* 3 digits + '\0' is usually enough */
3240 1.703 rillig Buf_InitSize(&buf, 4);
3241 1.703 rillig Buf_AddInt(&buf, (int)ac);
3242 1.823 rillig Expr_SetValueOwn(expr, Buf_DoneData(&buf));
3243 1.703 rillig }
3244 1.703 rillig goto ok;
3245 1.703 rillig }
3246 1.494 rillig
3247 1.810 rillig if (estr[0] == '*' && estr[1] == '\0') { /* Found ":[*]" */
3248 1.895 rillig ch->oneBigWord = true;
3249 1.703 rillig goto ok;
3250 1.236 rillig }
3251 1.288 rillig
3252 1.810 rillig if (estr[0] == '@' && estr[1] == '\0') { /* Found ":[@]" */
3253 1.895 rillig ch->oneBigWord = false;
3254 1.703 rillig goto ok;
3255 1.703 rillig }
3256 1.288 rillig
3257 1.703 rillig /*
3258 1.703 rillig * We expect estr to contain a single integer for :[N], or two
3259 1.703 rillig * integers separated by ".." for :[start..end].
3260 1.703 rillig */
3261 1.703 rillig p = estr;
3262 1.703 rillig if (!TryParseIntBase0(&p, &first))
3263 1.703 rillig goto bad_modifier; /* Found junk instead of a number */
3264 1.703 rillig
3265 1.703 rillig if (p[0] == '\0') { /* Found only one integer in :[N] */
3266 1.703 rillig last = first;
3267 1.703 rillig } else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
3268 1.703 rillig /* Expecting another integer after ".." */
3269 1.703 rillig p += 2;
3270 1.703 rillig if (!TryParseIntBase0(&p, &last) || *p != '\0')
3271 1.703 rillig goto bad_modifier; /* Found junk after ".." */
3272 1.703 rillig } else
3273 1.703 rillig goto bad_modifier; /* Found junk instead of ".." */
3274 1.288 rillig
3275 1.703 rillig /*
3276 1.703 rillig * Now first and last are properly filled in, but we still have to
3277 1.703 rillig * check for 0 as a special case.
3278 1.703 rillig */
3279 1.703 rillig if (first == 0 && last == 0) {
3280 1.703 rillig /* ":[0]" or perhaps ":[0..0]" */
3281 1.895 rillig ch->oneBigWord = true;
3282 1.703 rillig goto ok;
3283 1.703 rillig }
3284 1.288 rillig
3285 1.703 rillig /* ":[0..N]" or ":[N..0]" */
3286 1.703 rillig if (first == 0 || last == 0)
3287 1.703 rillig goto bad_modifier;
3288 1.703 rillig
3289 1.703 rillig /* Normal case: select the words described by first and last. */
3290 1.823 rillig Expr_SetValueOwn(expr,
3291 1.840 rillig VarSelectWords(expr->value.str, first, last,
3292 1.891 rillig ch->sep, ch->oneBigWord));
3293 1.288 rillig
3294 1.288 rillig ok:
3295 1.703 rillig free(estr);
3296 1.703 rillig return AMR_OK;
3297 1.288 rillig
3298 1.288 rillig bad_modifier:
3299 1.703 rillig free(estr);
3300 1.703 rillig return AMR_BAD;
3301 1.236 rillig }
3302 1.236 rillig
3303 1.404 rillig static int
3304 1.404 rillig str_cmp_asc(const void *a, const void *b)
3305 1.404 rillig {
3306 1.703 rillig return strcmp(*(const char *const *)a, *(const char *const *)b);
3307 1.404 rillig }
3308 1.404 rillig
3309 1.404 rillig static int
3310 1.404 rillig str_cmp_desc(const void *a, const void *b)
3311 1.404 rillig {
3312 1.703 rillig return strcmp(*(const char *const *)b, *(const char *const *)a);
3313 1.404 rillig }
3314 1.404 rillig
3315 1.705 rillig static void
3316 1.705 rillig ShuffleStrings(char **strs, size_t n)
3317 1.705 rillig {
3318 1.705 rillig size_t i;
3319 1.705 rillig
3320 1.705 rillig for (i = n - 1; i > 0; i--) {
3321 1.705 rillig size_t rndidx = (size_t)random() % (i + 1);
3322 1.705 rillig char *t = strs[i];
3323 1.705 rillig strs[i] = strs[rndidx];
3324 1.705 rillig strs[rndidx] = t;
3325 1.705 rillig }
3326 1.705 rillig }
3327 1.705 rillig
3328 1.402 rillig /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
3329 1.356 rillig static ApplyModifierResult
3330 1.891 rillig ApplyModifier_Order(const char **pp, ModChain *ch)
3331 1.236 rillig {
3332 1.705 rillig const char *mod = (*pp)++; /* skip past the 'O' in any case */
3333 1.878 rillig Words words;
3334 1.878 rillig enum SortMode {
3335 1.878 rillig ASC, DESC, SHUFFLE
3336 1.878 rillig } mode;
3337 1.401 rillig
3338 1.891 rillig if (IsDelimiter(mod[1], ch)) {
3339 1.878 rillig mode = ASC;
3340 1.705 rillig } else if ((mod[1] == 'r' || mod[1] == 'x') &&
3341 1.891 rillig IsDelimiter(mod[2], ch)) {
3342 1.705 rillig (*pp)++;
3343 1.878 rillig mode = mod[1] == 'r' ? DESC : SHUFFLE;
3344 1.878 rillig } else
3345 1.705 rillig return AMR_BAD;
3346 1.402 rillig
3347 1.905 rillig if (!ModChain_ShouldEval(ch))
3348 1.879 rillig return AMR_OK;
3349 1.879 rillig
3350 1.895 rillig words = Str_Words(ch->expr->value.str, false);
3351 1.878 rillig if (mode == SHUFFLE)
3352 1.878 rillig ShuffleStrings(words.words, words.len);
3353 1.878 rillig else
3354 1.878 rillig qsort(words.words, words.len, sizeof words.words[0],
3355 1.878 rillig mode == ASC ? str_cmp_asc : str_cmp_desc);
3356 1.891 rillig Expr_SetValueOwn(ch->expr, Words_JoinFree(words));
3357 1.878 rillig
3358 1.705 rillig return AMR_OK;
3359 1.236 rillig }
3360 1.236 rillig
3361 1.236 rillig /* :? then : else */
3362 1.356 rillig static ApplyModifierResult
3363 1.891 rillig ApplyModifier_IfElse(const char **pp, ModChain *ch)
3364 1.236 rillig {
3365 1.891 rillig Expr *expr = ch->expr;
3366 1.703 rillig char *then_expr, *else_expr;
3367 1.703 rillig VarParseResult res;
3368 1.412 rillig
3369 1.895 rillig bool value = false;
3370 1.906 rillig VarEvalMode then_emode = VARE_PARSE_ONLY;
3371 1.906 rillig VarEvalMode else_emode = VARE_PARSE_ONLY;
3372 1.236 rillig
3373 1.703 rillig int cond_rc = COND_PARSE; /* anything other than COND_INVALID */
3374 1.905 rillig if (Expr_ShouldEval(expr)) {
3375 1.898 rillig cond_rc = Cond_EvalCondition(expr->name, &value);
3376 1.703 rillig if (cond_rc != COND_INVALID && value)
3377 1.906 rillig then_emode = expr->emode;
3378 1.703 rillig if (cond_rc != COND_INVALID && !value)
3379 1.906 rillig else_emode = expr->emode;
3380 1.703 rillig }
3381 1.703 rillig
3382 1.703 rillig (*pp)++; /* skip past the '?' */
3383 1.906 rillig res = ParseModifierPart(pp, ':', then_emode, ch, &then_expr);
3384 1.703 rillig if (res != VPR_OK)
3385 1.703 rillig return AMR_CLEANUP;
3386 1.703 rillig
3387 1.906 rillig res = ParseModifierPart(pp, ch->endc, else_emode, ch, &else_expr);
3388 1.703 rillig if (res != VPR_OK)
3389 1.703 rillig return AMR_CLEANUP;
3390 1.703 rillig
3391 1.891 rillig (*pp)--; /* Go back to the ch->endc. */
3392 1.809 rillig
3393 1.703 rillig if (cond_rc == COND_INVALID) {
3394 1.703 rillig Error("Bad conditional expression `%s' in %s?%s:%s",
3395 1.898 rillig expr->name, expr->name, then_expr, else_expr);
3396 1.703 rillig return AMR_CLEANUP;
3397 1.703 rillig }
3398 1.703 rillig
3399 1.905 rillig if (!ModChain_ShouldEval(ch)) {
3400 1.875 rillig free(then_expr);
3401 1.875 rillig free(else_expr);
3402 1.875 rillig } else if (value) {
3403 1.823 rillig Expr_SetValueOwn(expr, then_expr);
3404 1.703 rillig free(else_expr);
3405 1.703 rillig } else {
3406 1.823 rillig Expr_SetValueOwn(expr, else_expr);
3407 1.703 rillig free(then_expr);
3408 1.703 rillig }
3409 1.823 rillig Expr_Define(expr);
3410 1.703 rillig return AMR_OK;
3411 1.236 rillig }
3412 1.236 rillig
3413 1.283 rillig /*
3414 1.808 rillig * The ::= modifiers are special in that they do not read the variable value
3415 1.808 rillig * but instead assign to that variable. They always expand to an empty
3416 1.808 rillig * string.
3417 1.808 rillig *
3418 1.808 rillig * Their main purpose is in supporting .for loops that generate shell commands
3419 1.808 rillig * since an ordinary variable assignment at that point would terminate the
3420 1.808 rillig * dependency group for these targets. For example:
3421 1.283 rillig *
3422 1.808 rillig * list-targets: .USE
3423 1.283 rillig * .for i in ${.TARGET} ${.TARGET:R}.gz
3424 1.808 rillig * @${t::=$i}
3425 1.808 rillig * @echo 'The target is ${t:T}.'
3426 1.283 rillig * .endfor
3427 1.283 rillig *
3428 1.283 rillig * ::=<str> Assigns <str> as the new value of variable.
3429 1.283 rillig * ::?=<str> Assigns <str> as value of variable if
3430 1.283 rillig * it was not already set.
3431 1.283 rillig * ::+=<str> Appends <str> to variable.
3432 1.283 rillig * ::!=<cmd> Assigns output of <cmd> as the new value of
3433 1.283 rillig * variable.
3434 1.283 rillig */
3435 1.356 rillig static ApplyModifierResult
3436 1.891 rillig ApplyModifier_Assign(const char **pp, ModChain *ch)
3437 1.236 rillig {
3438 1.891 rillig Expr *expr = ch->expr;
3439 1.802 rillig GNode *scope;
3440 1.703 rillig char *val;
3441 1.703 rillig VarParseResult res;
3442 1.272 rillig
3443 1.703 rillig const char *mod = *pp;
3444 1.703 rillig const char *op = mod + 1;
3445 1.272 rillig
3446 1.703 rillig if (op[0] == '=')
3447 1.703 rillig goto ok;
3448 1.703 rillig if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
3449 1.703 rillig goto ok;
3450 1.703 rillig return AMR_UNKNOWN; /* "::<unrecognised>" */
3451 1.862 rillig
3452 1.703 rillig ok:
3453 1.898 rillig if (expr->name[0] == '\0') {
3454 1.703 rillig *pp = mod + 1;
3455 1.703 rillig return AMR_BAD;
3456 1.703 rillig }
3457 1.272 rillig
3458 1.273 rillig switch (op[0]) {
3459 1.236 rillig case '+':
3460 1.272 rillig case '?':
3461 1.703 rillig case '!':
3462 1.703 rillig *pp = mod + 3;
3463 1.272 rillig break;
3464 1.236 rillig default:
3465 1.703 rillig *pp = mod + 2;
3466 1.703 rillig break;
3467 1.703 rillig }
3468 1.703 rillig
3469 1.906 rillig res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &val);
3470 1.703 rillig if (res != VPR_OK)
3471 1.703 rillig return AMR_CLEANUP;
3472 1.703 rillig
3473 1.891 rillig (*pp)--; /* Go back to the ch->endc. */
3474 1.703 rillig
3475 1.905 rillig if (!Expr_ShouldEval(expr))
3476 1.882 rillig goto done;
3477 1.882 rillig
3478 1.881 rillig scope = expr->scope; /* scope where v belongs */
3479 1.881 rillig if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) {
3480 1.898 rillig Var *gv = VarFind(expr->name, expr->scope, false);
3481 1.881 rillig if (gv == NULL)
3482 1.881 rillig scope = SCOPE_GLOBAL;
3483 1.881 rillig else
3484 1.881 rillig VarFreeEnv(gv);
3485 1.881 rillig }
3486 1.881 rillig
3487 1.882 rillig switch (op[0]) {
3488 1.882 rillig case '+':
3489 1.898 rillig Var_Append(scope, expr->name, val);
3490 1.882 rillig break;
3491 1.882 rillig case '!': {
3492 1.882 rillig const char *errfmt;
3493 1.882 rillig char *cmd_output = Cmd_Exec(val, &errfmt);
3494 1.882 rillig if (errfmt != NULL)
3495 1.882 rillig Error(errfmt, val);
3496 1.882 rillig else
3497 1.898 rillig Var_Set(scope, expr->name, cmd_output);
3498 1.882 rillig free(cmd_output);
3499 1.882 rillig break;
3500 1.882 rillig }
3501 1.882 rillig case '?':
3502 1.882 rillig if (expr->defined == DEF_REGULAR)
3503 1.703 rillig break;
3504 1.882 rillig /* FALLTHROUGH */
3505 1.882 rillig default:
3506 1.898 rillig Var_Set(scope, expr->name, val);
3507 1.882 rillig break;
3508 1.236 rillig }
3509 1.882 rillig Expr_SetValueRefer(expr, "");
3510 1.882 rillig
3511 1.882 rillig done:
3512 1.703 rillig free(val);
3513 1.703 rillig return AMR_OK;
3514 1.236 rillig }
3515 1.236 rillig
3516 1.778 rillig /*
3517 1.778 rillig * :_=...
3518 1.778 rillig * remember current value
3519 1.778 rillig */
3520 1.356 rillig static ApplyModifierResult
3521 1.891 rillig ApplyModifier_Remember(const char **pp, ModChain *ch)
3522 1.236 rillig {
3523 1.891 rillig Expr *expr = ch->expr;
3524 1.703 rillig const char *mod = *pp;
3525 1.868 rillig FStr name;
3526 1.866 rillig
3527 1.891 rillig if (!ModMatchEq(mod, "_", ch))
3528 1.703 rillig return AMR_UNKNOWN;
3529 1.703 rillig
3530 1.868 rillig name = FStr_InitRefer("_");
3531 1.703 rillig if (mod[1] == '=') {
3532 1.847 rillig /*
3533 1.847 rillig * XXX: This ad-hoc call to strcspn deviates from the usual
3534 1.847 rillig * behavior defined in ParseModifierPart. This creates an
3535 1.847 rillig * unnecessary, undocumented inconsistency in make.
3536 1.847 rillig */
3537 1.869 rillig const char *arg = mod + 2;
3538 1.869 rillig size_t argLen = strcspn(arg, ":)}");
3539 1.869 rillig *pp = arg + argLen;
3540 1.869 rillig name = FStr_InitOwn(bmake_strldup(arg, argLen));
3541 1.868 rillig } else
3542 1.868 rillig *pp = mod + 1;
3543 1.864 rillig
3544 1.905 rillig if (Expr_ShouldEval(expr))
3545 1.868 rillig Var_Set(expr->scope, name.str, expr->value.str);
3546 1.868 rillig FStr_Done(&name);
3547 1.864 rillig
3548 1.703 rillig return AMR_OK;
3549 1.236 rillig }
3550 1.236 rillig
3551 1.778 rillig /*
3552 1.778 rillig * Apply the given function to each word of the variable value,
3553 1.778 rillig * for a single-letter modifier such as :H, :T.
3554 1.778 rillig */
3555 1.434 rillig static ApplyModifierResult
3556 1.891 rillig ApplyModifier_WordFunc(const char **pp, ModChain *ch,
3557 1.822 rillig ModifyWordProc modifyWord)
3558 1.434 rillig {
3559 1.891 rillig if (!IsDelimiter((*pp)[1], ch))
3560 1.703 rillig return AMR_UNKNOWN;
3561 1.864 rillig (*pp)++;
3562 1.703 rillig
3563 1.905 rillig if (ModChain_ShouldEval(ch))
3564 1.891 rillig ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
3565 1.864 rillig
3566 1.703 rillig return AMR_OK;
3567 1.434 rillig }
3568 1.434 rillig
3569 1.567 rillig static ApplyModifierResult
3570 1.891 rillig ApplyModifier_Unique(const char **pp, ModChain *ch)
3571 1.567 rillig {
3572 1.891 rillig if (!IsDelimiter((*pp)[1], ch))
3573 1.703 rillig return AMR_UNKNOWN;
3574 1.862 rillig (*pp)++;
3575 1.862 rillig
3576 1.905 rillig if (ModChain_ShouldEval(ch))
3577 1.891 rillig Expr_SetValueOwn(ch->expr, VarUniq(ch->expr->value.str));
3578 1.862 rillig
3579 1.862 rillig return AMR_OK;
3580 1.567 rillig }
3581 1.567 rillig
3582 1.236 rillig #ifdef SYSVVARSUB
3583 1.236 rillig /* :from=to */
3584 1.356 rillig static ApplyModifierResult
3585 1.891 rillig ApplyModifier_SysV(const char **pp, ModChain *ch)
3586 1.236 rillig {
3587 1.891 rillig Expr *expr = ch->expr;
3588 1.703 rillig char *lhs, *rhs;
3589 1.703 rillig VarParseResult res;
3590 1.412 rillig
3591 1.703 rillig const char *mod = *pp;
3592 1.895 rillig bool eqFound = false;
3593 1.245 rillig
3594 1.703 rillig /*
3595 1.703 rillig * First we make a pass through the string trying to verify it is a
3596 1.703 rillig * SysV-make-style translation. It must be: <lhs>=<rhs>
3597 1.703 rillig */
3598 1.703 rillig int depth = 1;
3599 1.703 rillig const char *p = mod;
3600 1.703 rillig while (*p != '\0' && depth > 0) {
3601 1.703 rillig if (*p == '=') { /* XXX: should also test depth == 1 */
3602 1.895 rillig eqFound = true;
3603 1.891 rillig /* continue looking for ch->endc */
3604 1.891 rillig } else if (*p == ch->endc)
3605 1.703 rillig depth--;
3606 1.891 rillig else if (*p == ch->startc)
3607 1.703 rillig depth++;
3608 1.703 rillig if (depth > 0)
3609 1.703 rillig p++;
3610 1.703 rillig }
3611 1.891 rillig if (*p != ch->endc || !eqFound)
3612 1.703 rillig return AMR_UNKNOWN;
3613 1.236 rillig
3614 1.906 rillig res = ParseModifierPart(pp, '=', expr->emode, ch, &lhs);
3615 1.703 rillig if (res != VPR_OK)
3616 1.703 rillig return AMR_CLEANUP;
3617 1.703 rillig
3618 1.703 rillig /* The SysV modifier lasts until the end of the variable expression. */
3619 1.906 rillig res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &rhs);
3620 1.703 rillig if (res != VPR_OK)
3621 1.703 rillig return AMR_CLEANUP;
3622 1.703 rillig
3623 1.891 rillig (*pp)--; /* Go back to the ch->endc. */
3624 1.809 rillig
3625 1.823 rillig if (lhs[0] == '\0' && expr->value.str[0] == '\0') {
3626 1.821 rillig /* Do not turn an empty expression into non-empty. */
3627 1.703 rillig } else {
3628 1.897 rillig struct ModifyWord_SYSVSubstArgs args;
3629 1.897 rillig
3630 1.897 rillig args.scope = expr->scope;
3631 1.897 rillig args.lhs = lhs;
3632 1.897 rillig args.rhs = rhs;
3633 1.891 rillig ModifyWords(ch, ModifyWord_SYSVSubst, &args, ch->oneBigWord);
3634 1.703 rillig }
3635 1.703 rillig free(lhs);
3636 1.703 rillig free(rhs);
3637 1.703 rillig return AMR_OK;
3638 1.236 rillig }
3639 1.236 rillig #endif
3640 1.236 rillig
3641 1.548 rillig #ifdef SUNSHCMD
3642 1.548 rillig /* :sh */
3643 1.548 rillig static ApplyModifierResult
3644 1.891 rillig ApplyModifier_SunShell(const char **pp, ModChain *ch)
3645 1.548 rillig {
3646 1.891 rillig Expr *expr = ch->expr;
3647 1.703 rillig const char *p = *pp;
3648 1.891 rillig if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
3649 1.703 rillig return AMR_UNKNOWN;
3650 1.864 rillig *pp = p + 2;
3651 1.863 rillig
3652 1.905 rillig if (Expr_ShouldEval(expr)) {
3653 1.863 rillig const char *errfmt;
3654 1.863 rillig char *output = Cmd_Exec(expr->value.str, &errfmt);
3655 1.863 rillig if (errfmt != NULL)
3656 1.863 rillig Error(errfmt, expr->value.str);
3657 1.863 rillig Expr_SetValueOwn(expr, output);
3658 1.863 rillig }
3659 1.864 rillig
3660 1.863 rillig return AMR_OK;
3661 1.548 rillig }
3662 1.548 rillig #endif
3663 1.548 rillig
3664 1.549 rillig static void
3665 1.891 rillig LogBeforeApply(const ModChain *ch, const char *mod)
3666 1.549 rillig {
3667 1.891 rillig const Expr *expr = ch->expr;
3668 1.895 rillig bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
3669 1.703 rillig
3670 1.909 rillig /*
3671 1.909 rillig * At this point, only the first character of the modifier can
3672 1.909 rillig * be used since the end of the modifier is not yet known.
3673 1.909 rillig */
3674 1.909 rillig
3675 1.909 rillig if (!Expr_ShouldEval(expr)) {
3676 1.909 rillig debug_printf("Parsing modifier ${%s:%c%s}\n",
3677 1.909 rillig expr->name, mod[0], is_single_char ? "" : "...");
3678 1.909 rillig return;
3679 1.909 rillig }
3680 1.909 rillig
3681 1.910 rillig if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
3682 1.910 rillig expr->defined == DEF_REGULAR) {
3683 1.910 rillig debug_printf(
3684 1.910 rillig "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
3685 1.910 rillig expr->name, mod[0], is_single_char ? "" : "...",
3686 1.910 rillig expr->value.str);
3687 1.910 rillig return;
3688 1.910 rillig }
3689 1.910 rillig
3690 1.909 rillig debug_printf(
3691 1.909 rillig "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
3692 1.909 rillig expr->name, mod[0], is_single_char ? "" : "...", expr->value.str,
3693 1.910 rillig VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
3694 1.549 rillig }
3695 1.549 rillig
3696 1.549 rillig static void
3697 1.891 rillig LogAfterApply(const ModChain *ch, const char *p, const char *mod)
3698 1.549 rillig {
3699 1.891 rillig const Expr *expr = ch->expr;
3700 1.823 rillig const char *value = expr->value.str;
3701 1.823 rillig const char *quot = value == var_Error ? "" : "\"";
3702 1.703 rillig
3703 1.912 rillig if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
3704 1.912 rillig expr->defined == DEF_REGULAR) {
3705 1.912 rillig
3706 1.912 rillig debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
3707 1.912 rillig expr->name, (int)(p - mod), mod,
3708 1.912 rillig quot, value == var_Error ? "error" : value, quot);
3709 1.912 rillig return;
3710 1.912 rillig }
3711 1.912 rillig
3712 1.899 rillig debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
3713 1.898 rillig expr->name, (int)(p - mod), mod,
3714 1.823 rillig quot, value == var_Error ? "error" : value, quot,
3715 1.906 rillig VarEvalMode_Name[expr->emode],
3716 1.825 rillig ExprDefined_Name[expr->defined]);
3717 1.549 rillig }
3718 1.549 rillig
3719 1.551 rillig static ApplyModifierResult
3720 1.891 rillig ApplyModifier(const char **pp, ModChain *ch)
3721 1.551 rillig {
3722 1.703 rillig switch (**pp) {
3723 1.857 rillig case '!':
3724 1.891 rillig return ApplyModifier_ShellCommand(pp, ch);
3725 1.703 rillig case ':':
3726 1.891 rillig return ApplyModifier_Assign(pp, ch);
3727 1.857 rillig case '?':
3728 1.891 rillig return ApplyModifier_IfElse(pp, ch);
3729 1.703 rillig case '@':
3730 1.891 rillig return ApplyModifier_Loop(pp, ch);
3731 1.857 rillig case '[':
3732 1.891 rillig return ApplyModifier_Words(pp, ch);
3733 1.703 rillig case '_':
3734 1.891 rillig return ApplyModifier_Remember(pp, ch);
3735 1.857 rillig #ifndef NO_REGEX
3736 1.857 rillig case 'C':
3737 1.891 rillig return ApplyModifier_Regex(pp, ch);
3738 1.857 rillig #endif
3739 1.703 rillig case 'D':
3740 1.891 rillig return ApplyModifier_Defined(pp, ch);
3741 1.857 rillig case 'E':
3742 1.891 rillig return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
3743 1.703 rillig case 'g':
3744 1.891 rillig return ApplyModifier_Gmtime(pp, ch);
3745 1.857 rillig case 'H':
3746 1.891 rillig return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
3747 1.703 rillig case 'h':
3748 1.891 rillig return ApplyModifier_Hash(pp, ch);
3749 1.857 rillig case 'L':
3750 1.891 rillig return ApplyModifier_Literal(pp, ch);
3751 1.703 rillig case 'l':
3752 1.891 rillig return ApplyModifier_Localtime(pp, ch);
3753 1.857 rillig case 'M':
3754 1.703 rillig case 'N':
3755 1.891 rillig return ApplyModifier_Match(pp, ch);
3756 1.857 rillig case 'O':
3757 1.891 rillig return ApplyModifier_Order(pp, ch);
3758 1.857 rillig case 'P':
3759 1.891 rillig return ApplyModifier_Path(pp, ch);
3760 1.857 rillig case 'Q':
3761 1.703 rillig case 'q':
3762 1.891 rillig return ApplyModifier_Quote(pp, ch);
3763 1.703 rillig case 'R':
3764 1.891 rillig return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
3765 1.703 rillig case 'r':
3766 1.891 rillig return ApplyModifier_Range(pp, ch);
3767 1.857 rillig case 'S':
3768 1.891 rillig return ApplyModifier_Subst(pp, ch);
3769 1.551 rillig #ifdef SUNSHCMD
3770 1.703 rillig case 's':
3771 1.891 rillig return ApplyModifier_SunShell(pp, ch);
3772 1.551 rillig #endif
3773 1.857 rillig case 'T':
3774 1.891 rillig return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
3775 1.857 rillig case 't':
3776 1.891 rillig return ApplyModifier_To(pp, ch);
3777 1.857 rillig case 'U':
3778 1.891 rillig return ApplyModifier_Defined(pp, ch);
3779 1.857 rillig case 'u':
3780 1.891 rillig return ApplyModifier_Unique(pp, ch);
3781 1.703 rillig default:
3782 1.703 rillig return AMR_UNKNOWN;
3783 1.703 rillig }
3784 1.551 rillig }
3785 1.551 rillig
3786 1.823 rillig static void ApplyModifiers(Expr *, const char **, char, char);
3787 1.641 rillig
3788 1.641 rillig typedef enum ApplyModifiersIndirectResult {
3789 1.752 rillig /* The indirect modifiers have been applied successfully. */
3790 1.703 rillig AMIR_CONTINUE,
3791 1.752 rillig /* Fall back to the SysV modifier. */
3792 1.849 rillig AMIR_SYSV,
3793 1.752 rillig /* Error out. */
3794 1.703 rillig AMIR_OUT
3795 1.641 rillig } ApplyModifiersIndirectResult;
3796 1.641 rillig
3797 1.752 rillig /*
3798 1.752 rillig * While expanding a variable expression, expand and apply indirect modifiers,
3799 1.752 rillig * such as in ${VAR:${M_indirect}}.
3800 1.752 rillig *
3801 1.752 rillig * All indirect modifiers of a group must come from a single variable
3802 1.752 rillig * expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
3803 1.752 rillig *
3804 1.752 rillig * Multiple groups of indirect modifiers can be chained by separating them
3805 1.752 rillig * with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
3806 1.752 rillig *
3807 1.891 rillig * If the variable expression is not followed by ch->endc or ':', fall
3808 1.752 rillig * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
3809 1.752 rillig */
3810 1.641 rillig static ApplyModifiersIndirectResult
3811 1.891 rillig ApplyModifiersIndirect(ModChain *ch, const char **pp)
3812 1.703 rillig {
3813 1.891 rillig Expr *expr = ch->expr;
3814 1.721 rillig const char *p = *pp;
3815 1.743 rillig FStr mods;
3816 1.641 rillig
3817 1.906 rillig (void)Var_Parse(&p, expr->scope, expr->emode, &mods);
3818 1.703 rillig /* TODO: handle errors */
3819 1.641 rillig
3820 1.891 rillig if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, ch)) {
3821 1.743 rillig FStr_Done(&mods);
3822 1.849 rillig return AMIR_SYSV;
3823 1.703 rillig }
3824 1.703 rillig
3825 1.708 rillig DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
3826 1.743 rillig mods.str, (int)(p - *pp), *pp);
3827 1.703 rillig
3828 1.743 rillig if (mods.str[0] != '\0') {
3829 1.743 rillig const char *modsp = mods.str;
3830 1.823 rillig ApplyModifiers(expr, &modsp, '\0', '\0');
3831 1.823 rillig if (expr->value.str == var_Error || *modsp != '\0') {
3832 1.743 rillig FStr_Done(&mods);
3833 1.721 rillig *pp = p;
3834 1.703 rillig return AMIR_OUT; /* error already reported */
3835 1.703 rillig }
3836 1.703 rillig }
3837 1.743 rillig FStr_Done(&mods);
3838 1.641 rillig
3839 1.703 rillig if (*p == ':')
3840 1.703 rillig p++;
3841 1.891 rillig else if (*p == '\0' && ch->endc != '\0') {
3842 1.852 rillig Error("Unclosed variable expression after indirect "
3843 1.852 rillig "modifier, expecting '%c' for variable \"%s\"",
3844 1.898 rillig ch->endc, expr->name);
3845 1.721 rillig *pp = p;
3846 1.703 rillig return AMIR_OUT;
3847 1.641 rillig }
3848 1.641 rillig
3849 1.721 rillig *pp = p;
3850 1.703 rillig return AMIR_CONTINUE;
3851 1.641 rillig }
3852 1.641 rillig
3853 1.750 rillig static ApplyModifierResult
3854 1.891 rillig ApplySingleModifier(const char **pp, ModChain *ch)
3855 1.750 rillig {
3856 1.750 rillig ApplyModifierResult res;
3857 1.850 rillig const char *mod = *pp;
3858 1.750 rillig const char *p = *pp;
3859 1.750 rillig
3860 1.750 rillig if (DEBUG(VAR))
3861 1.891 rillig LogBeforeApply(ch, mod);
3862 1.750 rillig
3863 1.891 rillig res = ApplyModifier(&p, ch);
3864 1.750 rillig
3865 1.750 rillig #ifdef SYSVVARSUB
3866 1.750 rillig if (res == AMR_UNKNOWN) {
3867 1.750 rillig assert(p == mod);
3868 1.891 rillig res = ApplyModifier_SysV(&p, ch);
3869 1.750 rillig }
3870 1.750 rillig #endif
3871 1.750 rillig
3872 1.750 rillig if (res == AMR_UNKNOWN) {
3873 1.750 rillig /*
3874 1.750 rillig * Guess the end of the current modifier.
3875 1.750 rillig * XXX: Skipping the rest of the modifier hides
3876 1.750 rillig * errors and leads to wrong results.
3877 1.750 rillig * Parsing should rather stop here.
3878 1.750 rillig */
3879 1.891 rillig for (p++; !IsDelimiter(*p, ch) && *p != '\0'; p++)
3880 1.750 rillig continue;
3881 1.851 rillig Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
3882 1.851 rillig (int)(p - mod), mod);
3883 1.891 rillig Expr_SetValueRefer(ch->expr, var_Error);
3884 1.750 rillig }
3885 1.750 rillig if (res == AMR_CLEANUP || res == AMR_BAD) {
3886 1.750 rillig *pp = p;
3887 1.750 rillig return res;
3888 1.750 rillig }
3889 1.750 rillig
3890 1.750 rillig if (DEBUG(VAR))
3891 1.891 rillig LogAfterApply(ch, p, mod);
3892 1.750 rillig
3893 1.891 rillig if (*p == '\0' && ch->endc != '\0') {
3894 1.750 rillig Error(
3895 1.852 rillig "Unclosed variable expression, expecting '%c' for "
3896 1.852 rillig "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
3897 1.891 rillig ch->endc,
3898 1.852 rillig (int)(p - mod), mod,
3899 1.898 rillig ch->expr->name, ch->expr->value.str);
3900 1.750 rillig } else if (*p == ':') {
3901 1.750 rillig p++;
3902 1.891 rillig } else if (opts.strict && *p != '\0' && *p != ch->endc) {
3903 1.750 rillig Parse_Error(PARSE_FATAL,
3904 1.750 rillig "Missing delimiter ':' after modifier \"%.*s\"",
3905 1.750 rillig (int)(p - mod), mod);
3906 1.750 rillig /*
3907 1.750 rillig * TODO: propagate parse error to the enclosing
3908 1.750 rillig * expression
3909 1.750 rillig */
3910 1.750 rillig }
3911 1.750 rillig *pp = p;
3912 1.750 rillig return AMR_OK;
3913 1.750 rillig }
3914 1.750 rillig
3915 1.897 rillig #if __STDC_VERSION__ >= 199901L
3916 1.897 rillig #define ModChain_Literal(expr, startc, endc, sep, oneBigWord) \
3917 1.897 rillig (ModChain) { expr, startc, endc, sep, oneBigWord }
3918 1.897 rillig #else
3919 1.897 rillig MAKE_INLINE ModChain
3920 1.897 rillig ModChain_Literal(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
3921 1.897 rillig {
3922 1.897 rillig ModChain ch;
3923 1.897 rillig ch.expr = expr;
3924 1.897 rillig ch.startc = startc;
3925 1.897 rillig ch.endc = endc;
3926 1.897 rillig ch.sep = sep;
3927 1.897 rillig ch.oneBigWord = oneBigWord;
3928 1.897 rillig return ch;
3929 1.897 rillig }
3930 1.897 rillig #endif
3931 1.897 rillig
3932 1.419 rillig /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
3933 1.823 rillig static void
3934 1.357 rillig ApplyModifiers(
3935 1.823 rillig Expr *expr,
3936 1.821 rillig const char **pp, /* the parsing position, updated upon return */
3937 1.821 rillig char startc, /* '(' or '{'; or '\0' for indirect modifiers */
3938 1.823 rillig char endc /* ')' or '}'; or '\0' for indirect modifiers */
3939 1.703 rillig )
3940 1.703 rillig {
3941 1.897 rillig ModChain ch = ModChain_Literal(expr, startc, endc, ' ', false);
3942 1.703 rillig const char *p;
3943 1.703 rillig const char *mod;
3944 1.703 rillig
3945 1.703 rillig assert(startc == '(' || startc == '{' || startc == '\0');
3946 1.703 rillig assert(endc == ')' || endc == '}' || endc == '\0');
3947 1.823 rillig assert(expr->value.str != NULL);
3948 1.703 rillig
3949 1.703 rillig p = *pp;
3950 1.703 rillig
3951 1.703 rillig if (*p == '\0' && endc != '\0') {
3952 1.703 rillig Error(
3953 1.703 rillig "Unclosed variable expression (expecting '%c') for \"%s\"",
3954 1.898 rillig ch.endc, expr->name);
3955 1.703 rillig goto cleanup;
3956 1.703 rillig }
3957 1.703 rillig
3958 1.703 rillig while (*p != '\0' && *p != endc) {
3959 1.750 rillig ApplyModifierResult res;
3960 1.703 rillig
3961 1.703 rillig if (*p == '$') {
3962 1.849 rillig ApplyModifiersIndirectResult amir =
3963 1.891 rillig ApplyModifiersIndirect(&ch, &p);
3964 1.703 rillig if (amir == AMIR_CONTINUE)
3965 1.703 rillig continue;
3966 1.703 rillig if (amir == AMIR_OUT)
3967 1.752 rillig break;
3968 1.849 rillig /*
3969 1.849 rillig * It's neither '${VAR}:' nor '${VAR}}'. Try to parse
3970 1.849 rillig * it as a SysV modifier, as that is the only modifier
3971 1.849 rillig * that can start with '$'.
3972 1.849 rillig */
3973 1.703 rillig }
3974 1.752 rillig
3975 1.703 rillig mod = p;
3976 1.649 rillig
3977 1.891 rillig res = ApplySingleModifier(&p, &ch);
3978 1.703 rillig if (res == AMR_CLEANUP)
3979 1.703 rillig goto cleanup;
3980 1.703 rillig if (res == AMR_BAD)
3981 1.703 rillig goto bad_modifier;
3982 1.356 rillig }
3983 1.752 rillig
3984 1.703 rillig *pp = p;
3985 1.823 rillig assert(expr->value.str != NULL); /* Use var_Error or varUndefined. */
3986 1.823 rillig return;
3987 1.25 christos
3988 1.240 rillig bad_modifier:
3989 1.703 rillig /* XXX: The modifier end is only guessed. */
3990 1.853 rillig Error("Bad modifier \":%.*s\" for variable \"%s\"",
3991 1.898 rillig (int)strcspn(mod, ":)}"), mod, expr->name);
3992 1.25 christos
3993 1.240 rillig cleanup:
3994 1.858 rillig /*
3995 1.858 rillig * TODO: Use p + strlen(p) instead, to stop parsing immediately.
3996 1.858 rillig *
3997 1.858 rillig * In the unit tests, this generates a few unterminated strings in the
3998 1.858 rillig * shell commands though. Instead of producing these unfinished
3999 1.858 rillig * strings, commands with evaluation errors should not be run at all.
4000 1.858 rillig *
4001 1.858 rillig * To make that happen, Var_Subst must report the actual errors
4002 1.858 rillig * instead of returning VPR_OK unconditionally.
4003 1.858 rillig */
4004 1.703 rillig *pp = p;
4005 1.823 rillig Expr_SetValueRefer(expr, var_Error);
4006 1.108 sjg }
4007 1.25 christos
4008 1.778 rillig /*
4009 1.778 rillig * Only four of the local variables are treated specially as they are the
4010 1.778 rillig * only four that will be set when dynamic sources are expanded.
4011 1.778 rillig */
4012 1.895 rillig static bool
4013 1.626 rillig VarnameIsDynamic(const char *name, size_t len)
4014 1.335 rillig {
4015 1.703 rillig if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
4016 1.703 rillig switch (name[0]) {
4017 1.703 rillig case '@':
4018 1.703 rillig case '%':
4019 1.703 rillig case '*':
4020 1.703 rillig case '!':
4021 1.895 rillig return true;
4022 1.703 rillig }
4023 1.895 rillig return false;
4024 1.335 rillig }
4025 1.335 rillig
4026 1.703 rillig if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
4027 1.703 rillig return strcmp(name, ".TARGET") == 0 ||
4028 1.703 rillig strcmp(name, ".ARCHIVE") == 0 ||
4029 1.703 rillig strcmp(name, ".PREFIX") == 0 ||
4030 1.703 rillig strcmp(name, ".MEMBER") == 0;
4031 1.703 rillig }
4032 1.335 rillig
4033 1.895 rillig return false;
4034 1.335 rillig }
4035 1.335 rillig
4036 1.502 rillig static const char *
4037 1.802 rillig UndefinedShortVarValue(char varname, const GNode *scope)
4038 1.502 rillig {
4039 1.802 rillig if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
4040 1.703 rillig /*
4041 1.802 rillig * If substituting a local variable in a non-local scope,
4042 1.703 rillig * assume it's for dynamic source stuff. We have to handle
4043 1.703 rillig * this specially and return the longhand for the variable
4044 1.703 rillig * with the dollar sign escaped so it makes it back to the
4045 1.703 rillig * caller. Only four of the local variables are treated
4046 1.703 rillig * specially as they are the only four that will be set
4047 1.703 rillig * when dynamic sources are expanded.
4048 1.703 rillig */
4049 1.703 rillig switch (varname) {
4050 1.703 rillig case '@':
4051 1.703 rillig return "$(.TARGET)";
4052 1.703 rillig case '%':
4053 1.703 rillig return "$(.MEMBER)";
4054 1.703 rillig case '*':
4055 1.703 rillig return "$(.PREFIX)";
4056 1.703 rillig case '!':
4057 1.703 rillig return "$(.ARCHIVE)";
4058 1.703 rillig }
4059 1.502 rillig }
4060 1.769 rillig return NULL;
4061 1.502 rillig }
4062 1.502 rillig
4063 1.778 rillig /*
4064 1.778 rillig * Parse a variable name, until the end character or a colon, whichever
4065 1.778 rillig * comes first.
4066 1.778 rillig */
4067 1.504 rillig static char *
4068 1.501 rillig ParseVarname(const char **pp, char startc, char endc,
4069 1.906 rillig GNode *scope, VarEvalMode emode,
4070 1.504 rillig size_t *out_varname_len)
4071 1.501 rillig {
4072 1.703 rillig Buffer buf;
4073 1.703 rillig const char *p = *pp;
4074 1.854 rillig int depth = 0; /* Track depth so we can spot parse errors. */
4075 1.703 rillig
4076 1.703 rillig Buf_Init(&buf);
4077 1.703 rillig
4078 1.703 rillig while (*p != '\0') {
4079 1.854 rillig if ((*p == endc || *p == ':') && depth == 0)
4080 1.854 rillig break;
4081 1.703 rillig if (*p == startc)
4082 1.703 rillig depth++;
4083 1.854 rillig if (*p == endc)
4084 1.854 rillig depth--;
4085 1.501 rillig
4086 1.703 rillig /* A variable inside a variable, expand. */
4087 1.703 rillig if (*p == '$') {
4088 1.743 rillig FStr nested_val;
4089 1.906 rillig (void)Var_Parse(&p, scope, emode, &nested_val);
4090 1.703 rillig /* TODO: handle errors */
4091 1.743 rillig Buf_AddStr(&buf, nested_val.str);
4092 1.743 rillig FStr_Done(&nested_val);
4093 1.703 rillig } else {
4094 1.703 rillig Buf_AddByte(&buf, *p);
4095 1.703 rillig p++;
4096 1.703 rillig }
4097 1.501 rillig }
4098 1.703 rillig *pp = p;
4099 1.786 rillig *out_varname_len = buf.len;
4100 1.784 rillig return Buf_DoneData(&buf);
4101 1.501 rillig }
4102 1.501 rillig
4103 1.652 rillig static VarParseResult
4104 1.507 rillig ValidShortVarname(char varname, const char *start)
4105 1.507 rillig {
4106 1.818 rillig if (varname != '$' && varname != ':' && varname != '}' &&
4107 1.818 rillig varname != ')' && varname != '\0')
4108 1.703 rillig return VPR_OK;
4109 1.507 rillig
4110 1.771 rillig if (!opts.strict)
4111 1.771 rillig return VPR_ERR; /* XXX: Missing error message */
4112 1.507 rillig
4113 1.703 rillig if (varname == '$')
4114 1.703 rillig Parse_Error(PARSE_FATAL,
4115 1.507 rillig "To escape a dollar, use \\$, not $$, at \"%s\"", start);
4116 1.703 rillig else if (varname == '\0')
4117 1.703 rillig Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
4118 1.703 rillig else
4119 1.703 rillig Parse_Error(PARSE_FATAL,
4120 1.507 rillig "Invalid variable name '%c', at \"%s\"", varname, start);
4121 1.507 rillig
4122 1.767 rillig return VPR_ERR;
4123 1.507 rillig }
4124 1.507 rillig
4125 1.778 rillig /*
4126 1.817 rillig * Parse a single-character variable name such as in $V or $@.
4127 1.778 rillig * Return whether to continue parsing.
4128 1.778 rillig */
4129 1.895 rillig static bool
4130 1.817 rillig ParseVarnameShort(char varname, const char **pp, GNode *scope,
4131 1.906 rillig VarEvalMode emode,
4132 1.896 rillig VarParseResult *out_false_res, const char **out_false_val,
4133 1.896 rillig Var **out_true_var)
4134 1.667 rillig {
4135 1.703 rillig char name[2];
4136 1.703 rillig Var *v;
4137 1.703 rillig VarParseResult vpr;
4138 1.622 rillig
4139 1.817 rillig vpr = ValidShortVarname(varname, *pp);
4140 1.703 rillig if (vpr != VPR_OK) {
4141 1.703 rillig (*pp)++;
4142 1.896 rillig *out_false_res = vpr;
4143 1.896 rillig *out_false_val = var_Error;
4144 1.895 rillig return false;
4145 1.703 rillig }
4146 1.622 rillig
4147 1.817 rillig name[0] = varname;
4148 1.703 rillig name[1] = '\0';
4149 1.895 rillig v = VarFind(name, scope, true);
4150 1.703 rillig if (v == NULL) {
4151 1.770 rillig const char *val;
4152 1.703 rillig *pp += 2;
4153 1.622 rillig
4154 1.817 rillig val = UndefinedShortVarValue(varname, scope);
4155 1.770 rillig if (val == NULL)
4156 1.906 rillig val = emode == VARE_UNDEFERR
4157 1.906 rillig ? var_Error : varUndefined;
4158 1.769 rillig
4159 1.770 rillig if (opts.strict && val == var_Error) {
4160 1.703 rillig Parse_Error(PARSE_FATAL,
4161 1.703 rillig "Variable \"%s\" is undefined", name);
4162 1.896 rillig *out_false_res = VPR_ERR;
4163 1.896 rillig *out_false_val = val;
4164 1.895 rillig return false;
4165 1.703 rillig }
4166 1.767 rillig
4167 1.767 rillig /*
4168 1.767 rillig * XXX: This looks completely wrong.
4169 1.767 rillig *
4170 1.767 rillig * If undefined expressions are not allowed, this should
4171 1.767 rillig * rather be VPR_ERR instead of VPR_UNDEF, together with an
4172 1.767 rillig * error message.
4173 1.767 rillig *
4174 1.767 rillig * If undefined expressions are allowed, this should rather
4175 1.767 rillig * be VPR_UNDEF instead of VPR_OK.
4176 1.767 rillig */
4177 1.906 rillig *out_false_res = emode == VARE_UNDEFERR
4178 1.906 rillig ? VPR_UNDEF : VPR_OK;
4179 1.896 rillig *out_false_val = val;
4180 1.895 rillig return false;
4181 1.622 rillig }
4182 1.622 rillig
4183 1.896 rillig *out_true_var = v;
4184 1.895 rillig return true;
4185 1.622 rillig }
4186 1.622 rillig
4187 1.662 rillig /* Find variables like @F or <D. */
4188 1.662 rillig static Var *
4189 1.802 rillig FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope,
4190 1.662 rillig const char **out_extraModifiers)
4191 1.662 rillig {
4192 1.802 rillig /* Only resolve these variables if scope is a "real" target. */
4193 1.802 rillig if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
4194 1.703 rillig return NULL;
4195 1.703 rillig
4196 1.703 rillig if (namelen != 2)
4197 1.703 rillig return NULL;
4198 1.703 rillig if (varname[1] != 'F' && varname[1] != 'D')
4199 1.703 rillig return NULL;
4200 1.703 rillig if (strchr("@%?*!<>", varname[0]) == NULL)
4201 1.703 rillig return NULL;
4202 1.703 rillig
4203 1.703 rillig {
4204 1.897 rillig char name[2];
4205 1.897 rillig Var *v;
4206 1.897 rillig
4207 1.897 rillig name[0] = varname[0];
4208 1.897 rillig name[1] = '\0';
4209 1.897 rillig v = VarFind(name, scope, false);
4210 1.703 rillig
4211 1.703 rillig if (v != NULL) {
4212 1.703 rillig if (varname[1] == 'D') {
4213 1.703 rillig *out_extraModifiers = "H:";
4214 1.703 rillig } else { /* F */
4215 1.703 rillig *out_extraModifiers = "T:";
4216 1.703 rillig }
4217 1.703 rillig }
4218 1.703 rillig return v;
4219 1.662 rillig }
4220 1.662 rillig }
4221 1.662 rillig
4222 1.663 rillig static VarParseResult
4223 1.895 rillig EvalUndefined(bool dynamic, const char *start, const char *p, char *varname,
4224 1.906 rillig VarEvalMode emode,
4225 1.740 rillig FStr *out_val)
4226 1.667 rillig {
4227 1.703 rillig if (dynamic) {
4228 1.740 rillig *out_val = FStr_InitOwn(bmake_strsedup(start, p));
4229 1.703 rillig free(varname);
4230 1.703 rillig return VPR_OK;
4231 1.703 rillig }
4232 1.703 rillig
4233 1.906 rillig if (emode == VARE_UNDEFERR && opts.strict) {
4234 1.703 rillig Parse_Error(PARSE_FATAL,
4235 1.703 rillig "Variable \"%s\" is undefined", varname);
4236 1.703 rillig free(varname);
4237 1.740 rillig *out_val = FStr_InitRefer(var_Error);
4238 1.767 rillig return VPR_ERR;
4239 1.703 rillig }
4240 1.703 rillig
4241 1.906 rillig if (emode == VARE_UNDEFERR) {
4242 1.703 rillig free(varname);
4243 1.740 rillig *out_val = FStr_InitRefer(var_Error);
4244 1.767 rillig return VPR_UNDEF; /* XXX: Should be VPR_ERR instead. */
4245 1.703 rillig }
4246 1.703 rillig
4247 1.663 rillig free(varname);
4248 1.740 rillig *out_val = FStr_InitRefer(varUndefined);
4249 1.663 rillig return VPR_OK;
4250 1.663 rillig }
4251 1.663 rillig
4252 1.778 rillig /*
4253 1.778 rillig * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
4254 1.623 rillig * or ${VAR}, up to the closing brace or parenthesis, or in the case of
4255 1.623 rillig * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
4256 1.778 rillig * Return whether to continue parsing.
4257 1.778 rillig */
4258 1.895 rillig static bool
4259 1.623 rillig ParseVarnameLong(
4260 1.664 rillig const char *p,
4261 1.624 rillig char startc,
4262 1.802 rillig GNode *scope,
4263 1.906 rillig VarEvalMode emode,
4264 1.624 rillig
4265 1.896 rillig const char **out_false_pp,
4266 1.896 rillig VarParseResult *out_false_res,
4267 1.896 rillig FStr *out_false_val,
4268 1.896 rillig
4269 1.896 rillig char *out_true_endc,
4270 1.896 rillig const char **out_true_p,
4271 1.896 rillig Var **out_true_v,
4272 1.896 rillig bool *out_true_haveModifier,
4273 1.896 rillig const char **out_true_extraModifiers,
4274 1.896 rillig bool *out_true_dynamic,
4275 1.896 rillig ExprDefined *out_true_exprDefined
4276 1.703 rillig )
4277 1.703 rillig {
4278 1.703 rillig size_t namelen;
4279 1.703 rillig char *varname;
4280 1.703 rillig Var *v;
4281 1.895 rillig bool haveModifier;
4282 1.895 rillig bool dynamic = false;
4283 1.703 rillig
4284 1.703 rillig const char *const start = p;
4285 1.703 rillig char endc = startc == '(' ? ')' : '}';
4286 1.703 rillig
4287 1.703 rillig p += 2; /* skip "${" or "$(" or "y(" */
4288 1.906 rillig varname = ParseVarname(&p, startc, endc, scope, emode, &namelen);
4289 1.703 rillig
4290 1.703 rillig if (*p == ':') {
4291 1.895 rillig haveModifier = true;
4292 1.703 rillig } else if (*p == endc) {
4293 1.895 rillig haveModifier = false;
4294 1.703 rillig } else {
4295 1.703 rillig Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
4296 1.703 rillig free(varname);
4297 1.896 rillig *out_false_pp = p;
4298 1.896 rillig *out_false_val = FStr_InitRefer(var_Error);
4299 1.896 rillig *out_false_res = VPR_ERR;
4300 1.895 rillig return false;
4301 1.703 rillig }
4302 1.623 rillig
4303 1.895 rillig v = VarFind(varname, scope, true);
4304 1.623 rillig
4305 1.703 rillig /* At this point, p points just after the variable name,
4306 1.703 rillig * either at ':' or at endc. */
4307 1.623 rillig
4308 1.703 rillig if (v == NULL) {
4309 1.802 rillig v = FindLocalLegacyVar(varname, namelen, scope,
4310 1.896 rillig out_true_extraModifiers);
4311 1.703 rillig }
4312 1.623 rillig
4313 1.703 rillig if (v == NULL) {
4314 1.703 rillig /*
4315 1.703 rillig * Defer expansion of dynamic variables if they appear in
4316 1.802 rillig * non-local scope since they are not defined there.
4317 1.703 rillig */
4318 1.703 rillig dynamic = VarnameIsDynamic(varname, namelen) &&
4319 1.802 rillig (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
4320 1.703 rillig
4321 1.703 rillig if (!haveModifier) {
4322 1.703 rillig p++; /* skip endc */
4323 1.896 rillig *out_false_pp = p;
4324 1.896 rillig *out_false_res = EvalUndefined(dynamic, start, p,
4325 1.906 rillig varname, emode, out_false_val);
4326 1.895 rillig return false;
4327 1.703 rillig }
4328 1.623 rillig
4329 1.703 rillig /*
4330 1.703 rillig * The variable expression is based on an undefined variable.
4331 1.703 rillig * Nevertheless it needs a Var, for modifiers that access the
4332 1.703 rillig * variable name, such as :L or :?.
4333 1.703 rillig *
4334 1.703 rillig * Most modifiers leave this expression in the "undefined"
4335 1.821 rillig * state (VES_UNDEF), only a few modifiers like :D, :U, :L,
4336 1.703 rillig * :P turn this undefined expression into a defined
4337 1.821 rillig * expression (VES_DEF).
4338 1.703 rillig *
4339 1.830 rillig * In the end, after applying all modifiers, if the expression
4340 1.703 rillig * is still undefined, Var_Parse will return an empty string
4341 1.703 rillig * instead of the actually computed value.
4342 1.703 rillig */
4343 1.901 rillig v = VarNew(FStr_InitOwn(varname), "", false, false);
4344 1.896 rillig *out_true_exprDefined = DEF_UNDEF;
4345 1.703 rillig } else
4346 1.703 rillig free(varname);
4347 1.623 rillig
4348 1.896 rillig *out_true_endc = endc;
4349 1.896 rillig *out_true_p = p;
4350 1.896 rillig *out_true_v = v;
4351 1.896 rillig *out_true_haveModifier = haveModifier;
4352 1.896 rillig *out_true_dynamic = dynamic;
4353 1.895 rillig return true;
4354 1.623 rillig }
4355 1.623 rillig
4356 1.709 rillig /* Free the environment variable now since we own it. */
4357 1.709 rillig static void
4358 1.838 rillig FreeEnvVar(Var *v, FStr *inout_val)
4359 1.709 rillig {
4360 1.784 rillig char *varValue = Buf_DoneData(&v->val);
4361 1.838 rillig if (inout_val->str == varValue)
4362 1.838 rillig inout_val->freeIt = varValue;
4363 1.709 rillig else
4364 1.709 rillig free(varValue);
4365 1.709 rillig
4366 1.711 rillig FStr_Done(&v->name);
4367 1.709 rillig free(v);
4368 1.709 rillig }
4369 1.709 rillig
4370 1.897 rillig #if __STDC_VERSION__ >= 199901L
4371 1.900 rillig #define Expr_Literal(name, value, eflags, scope, defined) \
4372 1.900 rillig { name, value, eflags, scope, defined }
4373 1.897 rillig #else
4374 1.897 rillig MAKE_INLINE Expr
4375 1.900 rillig Expr_Literal(const char *name, FStr value,
4376 1.898 rillig VarEvalFlags eflags, GNode *scope, ExprDefined defined)
4377 1.897 rillig {
4378 1.897 rillig Expr expr;
4379 1.897 rillig
4380 1.898 rillig expr.name = name;
4381 1.897 rillig expr.value = value;
4382 1.897 rillig expr.eflags = eflags;
4383 1.897 rillig expr.scope = scope;
4384 1.897 rillig expr.defined = defined;
4385 1.897 rillig return expr;
4386 1.897 rillig }
4387 1.897 rillig #endif
4388 1.897 rillig
4389 1.666 rillig /*
4390 1.913 rillig * Expressions of the form ${:U...} with a trivial value are often generated
4391 1.913 rillig * by .for loops and are boring, therefore parse and evaluate them in a fast
4392 1.913 rillig * lane without debug logging.
4393 1.913 rillig */
4394 1.913 rillig static bool
4395 1.913 rillig Var_Parse_FastLane(const char **pp, VarEvalMode emode, FStr *out_value)
4396 1.913 rillig {
4397 1.913 rillig const char *p;
4398 1.913 rillig
4399 1.913 rillig p = *pp;
4400 1.913 rillig if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
4401 1.913 rillig return false;
4402 1.913 rillig
4403 1.913 rillig p += 4;
4404 1.913 rillig while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' && *p != '}')
4405 1.913 rillig p++;
4406 1.913 rillig if (*p != '}')
4407 1.913 rillig return false;
4408 1.913 rillig
4409 1.913 rillig if (emode == VARE_PARSE_ONLY)
4410 1.913 rillig *out_value = FStr_InitRefer("");
4411 1.913 rillig else
4412 1.913 rillig *out_value = FStr_InitOwn(bmake_strsedup(*pp + 4, p));
4413 1.913 rillig *pp = p + 1;
4414 1.913 rillig return true;
4415 1.913 rillig }
4416 1.913 rillig
4417 1.913 rillig /*
4418 1.666 rillig * Given the start of a variable expression (such as $v, $(VAR),
4419 1.666 rillig * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
4420 1.666 rillig * if any. While doing that, apply the modifiers to the value of the
4421 1.666 rillig * expression, forming its final value. A few of the modifiers such as :!cmd!
4422 1.666 rillig * or ::= have side effects.
4423 1.579 rillig *
4424 1.108 sjg * Input:
4425 1.666 rillig * *pp The string to parse.
4426 1.666 rillig * When parsing a condition in ParseEmptyArg, it may also
4427 1.666 rillig * point to the "y" of "empty(VARNAME:Modifiers)", which
4428 1.666 rillig * is syntactically the same.
4429 1.802 rillig * scope The scope for finding variables
4430 1.666 rillig * eflags Control the exact details of parsing
4431 1.666 rillig *
4432 1.666 rillig * Output:
4433 1.666 rillig * *pp The position where to continue parsing.
4434 1.666 rillig * TODO: After a parse error, the value of *pp is
4435 1.666 rillig * unspecified. It may not have been updated at all,
4436 1.666 rillig * point to some random character in the string, to the
4437 1.666 rillig * location of the parse error, or at the end of the
4438 1.666 rillig * string.
4439 1.666 rillig * *out_val The value of the variable expression, never NULL.
4440 1.666 rillig * *out_val var_Error if there was a parse error.
4441 1.666 rillig * *out_val var_Error if the base variable of the expression was
4442 1.885 rillig * undefined, eflags has undefErr set, and none of
4443 1.666 rillig * the modifiers turned the undefined expression into a
4444 1.666 rillig * defined expression.
4445 1.666 rillig * XXX: It is not guaranteed that an error message has
4446 1.666 rillig * been printed.
4447 1.666 rillig * *out_val varUndefined if the base variable of the expression
4448 1.885 rillig * was undefined, eflags did not have undefErr set,
4449 1.666 rillig * and none of the modifiers turned the undefined
4450 1.666 rillig * expression into a defined expression.
4451 1.666 rillig * XXX: It is not guaranteed that an error message has
4452 1.666 rillig * been printed.
4453 1.108 sjg */
4454 1.526 rillig VarParseResult
4455 1.906 rillig Var_Parse(const char **pp, GNode *scope, VarEvalMode emode, FStr *out_val)
4456 1.108 sjg {
4457 1.703 rillig const char *p = *pp;
4458 1.703 rillig const char *const start = p;
4459 1.895 rillig /* true if have modifiers for the variable. */
4460 1.895 rillig bool haveModifier;
4461 1.703 rillig /* Starting character if variable in parens or braces. */
4462 1.703 rillig char startc;
4463 1.703 rillig /* Ending character if variable in parens or braces. */
4464 1.703 rillig char endc;
4465 1.703 rillig /*
4466 1.895 rillig * true if the variable is local and we're expanding it in a
4467 1.802 rillig * non-local scope. This is done to support dynamic sources.
4468 1.703 rillig * The result is just the expression, unaltered.
4469 1.703 rillig */
4470 1.895 rillig bool dynamic;
4471 1.703 rillig const char *extramodifiers;
4472 1.703 rillig Var *v;
4473 1.906 rillig Expr expr = Expr_Literal(NULL, FStr_InitRefer(NULL), emode,
4474 1.898 rillig scope, DEF_REGULAR);
4475 1.703 rillig
4476 1.913 rillig if (Var_Parse_FastLane(pp, emode, out_val))
4477 1.913 rillig return VPR_OK;
4478 1.913 rillig
4479 1.906 rillig DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
4480 1.703 rillig
4481 1.743 rillig *out_val = FStr_InitRefer(NULL);
4482 1.703 rillig extramodifiers = NULL; /* extra modifiers to apply first */
4483 1.895 rillig dynamic = false;
4484 1.473 rillig
4485 1.703 rillig /*
4486 1.703 rillig * Appease GCC, which thinks that the variable might not be
4487 1.703 rillig * initialized.
4488 1.703 rillig */
4489 1.703 rillig endc = '\0';
4490 1.108 sjg
4491 1.703 rillig startc = p[1];
4492 1.703 rillig if (startc != '(' && startc != '{') {
4493 1.703 rillig VarParseResult res;
4494 1.906 rillig if (!ParseVarnameShort(startc, pp, scope, emode, &res,
4495 1.898 rillig &out_val->str, &v))
4496 1.703 rillig return res;
4497 1.895 rillig haveModifier = false;
4498 1.703 rillig p++;
4499 1.703 rillig } else {
4500 1.703 rillig VarParseResult res;
4501 1.906 rillig if (!ParseVarnameLong(p, startc, scope, emode,
4502 1.743 rillig pp, &res, out_val,
4503 1.898 rillig &endc, &p, &v, &haveModifier, &extramodifiers,
4504 1.825 rillig &dynamic, &expr.defined))
4505 1.703 rillig return res;
4506 1.703 rillig }
4507 1.401 rillig
4508 1.898 rillig expr.name = v->name.str;
4509 1.902 rillig if (v->inUse)
4510 1.711 rillig Fatal("Variable %s is recursive.", v->name.str);
4511 1.187 christos
4512 1.703 rillig /*
4513 1.703 rillig * XXX: This assignment creates an alias to the current value of the
4514 1.703 rillig * variable. This means that as long as the value of the expression
4515 1.703 rillig * stays the same, the value of the variable must not change.
4516 1.703 rillig * Using the '::=' modifier, it could be possible to do exactly this.
4517 1.703 rillig * At the bottom of this function, the resulting value is compared to
4518 1.703 rillig * the then-current value of the variable. This might also invoke
4519 1.703 rillig * undefined behavior.
4520 1.703 rillig */
4521 1.823 rillig expr.value = FStr_InitRefer(v->val.data);
4522 1.108 sjg
4523 1.703 rillig /*
4524 1.703 rillig * Before applying any modifiers, expand any nested expressions from
4525 1.703 rillig * the variable value.
4526 1.703 rillig */
4527 1.906 rillig if (strchr(expr.value.str, '$') != NULL &&
4528 1.906 rillig VarEvalMode_ShouldEval(emode)) {
4529 1.743 rillig char *expanded;
4530 1.906 rillig VarEvalMode nested_emode = emode;
4531 1.764 rillig if (opts.strict)
4532 1.906 rillig nested_emode = VarEvalMode_UndefOk(nested_emode);
4533 1.902 rillig v->inUse = true;
4534 1.906 rillig (void)Var_Subst(expr.value.str, scope, nested_emode,
4535 1.823 rillig &expanded);
4536 1.902 rillig v->inUse = false;
4537 1.703 rillig /* TODO: handle errors */
4538 1.823 rillig Expr_SetValueOwn(&expr, expanded);
4539 1.191 dholland }
4540 1.191 dholland
4541 1.855 rillig if (extramodifiers != NULL) {
4542 1.855 rillig const char *em = extramodifiers;
4543 1.855 rillig ApplyModifiers(&expr, &em, '\0', '\0');
4544 1.855 rillig }
4545 1.191 dholland
4546 1.855 rillig if (haveModifier) {
4547 1.855 rillig p++; /* Skip initial colon. */
4548 1.855 rillig ApplyModifiers(&expr, &p, startc, endc);
4549 1.191 dholland }
4550 1.438 rillig
4551 1.703 rillig if (*p != '\0') /* Skip past endc if possible. */
4552 1.703 rillig p++;
4553 1.519 rillig
4554 1.703 rillig *pp = p;
4555 1.15 christos
4556 1.902 rillig if (v->fromEnv) {
4557 1.838 rillig FreeEnvVar(v, &expr.value);
4558 1.703 rillig
4559 1.825 rillig } else if (expr.defined != DEF_REGULAR) {
4560 1.825 rillig if (expr.defined == DEF_UNDEF) {
4561 1.703 rillig if (dynamic) {
4562 1.823 rillig Expr_SetValueOwn(&expr,
4563 1.823 rillig bmake_strsedup(start, p));
4564 1.703 rillig } else {
4565 1.703 rillig /*
4566 1.703 rillig * The expression is still undefined,
4567 1.703 rillig * therefore discard the actual value and
4568 1.703 rillig * return an error marker instead.
4569 1.703 rillig */
4570 1.823 rillig Expr_SetValueRefer(&expr,
4571 1.906 rillig emode == VARE_UNDEFERR
4572 1.823 rillig ? var_Error : varUndefined);
4573 1.703 rillig }
4574 1.703 rillig }
4575 1.823 rillig /* XXX: This is not standard memory management. */
4576 1.823 rillig if (expr.value.str != v->val.data)
4577 1.784 rillig Buf_Done(&v->val);
4578 1.711 rillig FStr_Done(&v->name);
4579 1.703 rillig free(v);
4580 1.34 christos }
4581 1.823 rillig *out_val = expr.value;
4582 1.766 rillig return VPR_OK; /* XXX: Is not correct in all cases */
4583 1.1 cgd }
4584 1.1 cgd
4585 1.678 rillig static void
4586 1.906 rillig VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
4587 1.768 rillig {
4588 1.830 rillig /* A dollar sign may be escaped with another dollar sign. */
4589 1.906 rillig if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
4590 1.768 rillig Buf_AddByte(res, '$');
4591 1.768 rillig Buf_AddByte(res, '$');
4592 1.768 rillig *pp += 2;
4593 1.768 rillig }
4594 1.768 rillig
4595 1.768 rillig static void
4596 1.802 rillig VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
4597 1.906 rillig VarEvalMode emode, bool *inout_errorReported)
4598 1.678 rillig {
4599 1.703 rillig const char *p = *pp;
4600 1.703 rillig const char *nested_p = p;
4601 1.743 rillig FStr val;
4602 1.703 rillig
4603 1.906 rillig (void)Var_Parse(&nested_p, scope, emode, &val);
4604 1.703 rillig /* TODO: handle errors */
4605 1.678 rillig
4606 1.743 rillig if (val.str == var_Error || val.str == varUndefined) {
4607 1.906 rillig if (!VarEvalMode_ShouldKeepUndef(emode)) {
4608 1.703 rillig p = nested_p;
4609 1.906 rillig } else if (emode == VARE_UNDEFERR || val.str == var_Error) {
4610 1.703 rillig
4611 1.703 rillig /*
4612 1.703 rillig * XXX: This condition is wrong. If val == var_Error,
4613 1.703 rillig * this doesn't necessarily mean there was an undefined
4614 1.703 rillig * variable. It could equally well be a parse error;
4615 1.703 rillig * see unit-tests/varmod-order.exp.
4616 1.703 rillig */
4617 1.703 rillig
4618 1.703 rillig /*
4619 1.703 rillig * If variable is undefined, complain and skip the
4620 1.703 rillig * variable. The complaint will stop us from doing
4621 1.703 rillig * anything when the file is parsed.
4622 1.703 rillig */
4623 1.703 rillig if (!*inout_errorReported) {
4624 1.703 rillig Parse_Error(PARSE_FATAL,
4625 1.703 rillig "Undefined variable \"%.*s\"",
4626 1.703 rillig (int)(size_t)(nested_p - p), p);
4627 1.703 rillig }
4628 1.703 rillig p = nested_p;
4629 1.895 rillig *inout_errorReported = true;
4630 1.703 rillig } else {
4631 1.703 rillig /* Copy the initial '$' of the undefined expression,
4632 1.703 rillig * thereby deferring expansion of the expression, but
4633 1.703 rillig * expand nested expressions if already possible.
4634 1.703 rillig * See unit-tests/varparse-undef-partial.mk. */
4635 1.703 rillig Buf_AddByte(buf, *p);
4636 1.703 rillig p++;
4637 1.703 rillig }
4638 1.678 rillig } else {
4639 1.703 rillig p = nested_p;
4640 1.743 rillig Buf_AddStr(buf, val.str);
4641 1.678 rillig }
4642 1.678 rillig
4643 1.743 rillig FStr_Done(&val);
4644 1.678 rillig
4645 1.703 rillig *pp = p;
4646 1.678 rillig }
4647 1.678 rillig
4648 1.768 rillig /*
4649 1.768 rillig * Skip as many characters as possible -- either to the end of the string
4650 1.768 rillig * or to the next dollar sign (variable expression).
4651 1.768 rillig */
4652 1.768 rillig static void
4653 1.768 rillig VarSubstPlain(const char **pp, Buffer *res)
4654 1.768 rillig {
4655 1.768 rillig const char *p = *pp;
4656 1.768 rillig const char *start = p;
4657 1.768 rillig
4658 1.768 rillig for (p++; *p != '$' && *p != '\0'; p++)
4659 1.768 rillig continue;
4660 1.768 rillig Buf_AddBytesBetween(res, start, p);
4661 1.768 rillig *pp = p;
4662 1.768 rillig }
4663 1.768 rillig
4664 1.778 rillig /*
4665 1.778 rillig * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
4666 1.660 rillig * given string.
4667 1.1 cgd *
4668 1.70 wiz * Input:
4669 1.660 rillig * str The string in which the variable expressions are
4670 1.660 rillig * expanded.
4671 1.802 rillig * scope The scope in which to start searching for
4672 1.802 rillig * variables. The other scopes are searched as well.
4673 1.677 rillig * eflags Special effects during expansion.
4674 1.1 cgd */
4675 1.533 rillig VarParseResult
4676 1.906 rillig Var_Subst(const char *str, GNode *scope, VarEvalMode emode, char **out_res)
4677 1.1 cgd {
4678 1.703 rillig const char *p = str;
4679 1.703 rillig Buffer res;
4680 1.1 cgd
4681 1.703 rillig /* Set true if an error has already been reported,
4682 1.703 rillig * to prevent a plethora of messages when recursing */
4683 1.703 rillig /* XXX: Why is the 'static' necessary here? */
4684 1.895 rillig static bool errorReported;
4685 1.703 rillig
4686 1.703 rillig Buf_Init(&res);
4687 1.895 rillig errorReported = false;
4688 1.703 rillig
4689 1.703 rillig while (*p != '\0') {
4690 1.768 rillig if (p[0] == '$' && p[1] == '$')
4691 1.906 rillig VarSubstDollarDollar(&p, &res, emode);
4692 1.768 rillig else if (p[0] == '$')
4693 1.906 rillig VarSubstExpr(&p, &res, scope, emode, &errorReported);
4694 1.768 rillig else
4695 1.768 rillig VarSubstPlain(&p, &res);
4696 1.1 cgd }
4697 1.15 christos
4698 1.784 rillig *out_res = Buf_DoneDataCompact(&res);
4699 1.703 rillig return VPR_OK;
4700 1.1 cgd }
4701 1.1 cgd
4702 1.572 rillig /* Initialize the variables module. */
4703 1.1 cgd void
4704 1.70 wiz Var_Init(void)
4705 1.1 cgd {
4706 1.801 rillig SCOPE_INTERNAL = GNode_New("Internal");
4707 1.801 rillig SCOPE_GLOBAL = GNode_New("Global");
4708 1.801 rillig SCOPE_CMDLINE = GNode_New("Command");
4709 1.6 jtc }
4710 1.6 jtc
4711 1.572 rillig /* Clean up the variables module. */
4712 1.6 jtc void
4713 1.70 wiz Var_End(void)
4714 1.6 jtc {
4715 1.703 rillig Var_Stats();
4716 1.286 sjg }
4717 1.286 sjg
4718 1.286 sjg void
4719 1.286 sjg Var_Stats(void)
4720 1.286 sjg {
4721 1.802 rillig HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
4722 1.1 cgd }
4723 1.15 christos
4724 1.802 rillig /* Print all variables in a scope, sorted by name. */
4725 1.5 cgd void
4726 1.802 rillig Var_Dump(GNode *scope)
4727 1.1 cgd {
4728 1.703 rillig Vector /* of const char * */ vec;
4729 1.703 rillig HashIter hi;
4730 1.703 rillig size_t i;
4731 1.703 rillig const char **varnames;
4732 1.703 rillig
4733 1.703 rillig Vector_Init(&vec, sizeof(const char *));
4734 1.703 rillig
4735 1.802 rillig HashIter_Init(&hi, &scope->vars);
4736 1.703 rillig while (HashIter_Next(&hi) != NULL)
4737 1.703 rillig *(const char **)Vector_Push(&vec) = hi.entry->key;
4738 1.703 rillig varnames = vec.items;
4739 1.703 rillig
4740 1.703 rillig qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
4741 1.703 rillig
4742 1.703 rillig for (i = 0; i < vec.len; i++) {
4743 1.703 rillig const char *varname = varnames[i];
4744 1.802 rillig Var *var = HashTable_FindValue(&scope->vars, varname);
4745 1.785 rillig debug_printf("%-16s = %s\n", varname, var->val.data);
4746 1.703 rillig }
4747 1.573 rillig
4748 1.703 rillig Vector_Done(&vec);
4749 1.1 cgd }
4750