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