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