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