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