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