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