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