var.c revision 1.417 1 /* $NetBSD: var.c,v 1.417 2020/08/07 20:35:03 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.417 2020/08/07 20:35:03 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.417 2020/08/07 20:35:03 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 {
1955 ModifyWord_LoopArgs args;
1956 char delim;
1957 int prev_sep;
1958
1959 args.ctx = st->ctxt;
1960
1961 (*pp)++; /* Skip the first '@' */
1962 delim = '@';
1963 args.tvar = ParseModifierPart(pp, delim, st->eflags & ~VARE_WANTRES,
1964 st->ctxt, NULL, NULL, NULL);
1965 if (args.tvar == NULL) {
1966 st->missing_delim = delim;
1967 return AMR_CLEANUP;
1968 }
1969 if (DEBUG(LINT) && strchr(args.tvar, '$') != NULL) {
1970 Parse_Error(PARSE_FATAL,
1971 "In the :@ modifier of \"%s\", the variable name \"%s\" "
1972 "must not contain a dollar.",
1973 st->v->name, args.tvar);
1974 return AMR_CLEANUP;
1975 }
1976
1977 args.str = ParseModifierPart(pp, delim, st->eflags & ~VARE_WANTRES,
1978 st->ctxt, NULL, NULL, NULL);
1979 if (args.str == NULL) {
1980 st->missing_delim = delim;
1981 return AMR_CLEANUP;
1982 }
1983
1984 args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES);
1985 prev_sep = st->sep;
1986 st->sep = ' '; /* XXX: should be st->sep for consistency */
1987 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
1988 ModifyWord_Loop, &args);
1989 st->sep = prev_sep;
1990 Var_Delete(args.tvar, st->ctxt);
1991 free(args.tvar);
1992 free(args.str);
1993 return AMR_OK;
1994 }
1995
1996 /* :Ddefined or :Uundefined */
1997 static ApplyModifierResult
1998 ApplyModifier_Defined(const char **pp, ApplyModifiersState *st)
1999 {
2000 Buffer buf; /* Buffer for patterns */
2001 const char *p;
2002
2003 VarEvalFlags eflags = st->eflags & ~VARE_WANTRES;
2004 if (st->eflags & VARE_WANTRES) {
2005 if ((**pp == 'D') == !(st->v->flags & VAR_JUNK))
2006 eflags |= VARE_WANTRES;
2007 }
2008
2009 /*
2010 * Pass through mod looking for 1) escaped delimiters,
2011 * '$'s and backslashes (place the escaped character in
2012 * uninterpreted) and 2) unescaped $'s that aren't before
2013 * the delimiter (expand the variable substitution).
2014 * The result is left in the Buffer buf.
2015 */
2016 Buf_InitZ(&buf, 0);
2017 p = *pp + 1;
2018 while (*p != st->endc && *p != ':' && *p != '\0') {
2019 if (*p == '\\' &&
2020 (p[1] == ':' || p[1] == '$' || p[1] == st->endc || p[1] == '\\')) {
2021 Buf_AddByte(&buf, p[1]);
2022 p += 2;
2023 } else if (*p == '$') {
2024 /*
2025 * If unescaped dollar sign, assume it's a
2026 * variable substitution and recurse.
2027 */
2028 const char *cp2;
2029 int len;
2030 void *freeIt;
2031
2032 cp2 = Var_Parse(p, st->ctxt, eflags, &len, &freeIt);
2033 Buf_AddStr(&buf, cp2);
2034 free(freeIt);
2035 p += len;
2036 } else {
2037 Buf_AddByte(&buf, *p);
2038 p++;
2039 }
2040 }
2041 *pp = p;
2042
2043 if (st->v->flags & VAR_JUNK)
2044 st->v->flags |= VAR_KEEP;
2045 if (eflags & VARE_WANTRES) {
2046 st->newVal = Buf_Destroy(&buf, FALSE);
2047 } else {
2048 st->newVal = st->val;
2049 Buf_Destroy(&buf, TRUE);
2050 }
2051 return AMR_OK;
2052 }
2053
2054 /* :gmtime */
2055 static ApplyModifierResult
2056 ApplyModifier_Gmtime(const char **pp, ApplyModifiersState *st)
2057 {
2058 time_t utc;
2059
2060 const char *mod = *pp;
2061 if (!ModMatchEq(mod, "gmtime", st->endc))
2062 return AMR_UNKNOWN;
2063
2064 if (mod[6] == '=') {
2065 char *ep;
2066 utc = strtoul(mod + 7, &ep, 10);
2067 *pp = ep;
2068 } else {
2069 utc = 0;
2070 *pp = mod + 6;
2071 }
2072 st->newVal = VarStrftime(st->val, 1, utc);
2073 return AMR_OK;
2074 }
2075
2076 /* :localtime */
2077 static Boolean
2078 ApplyModifier_Localtime(const char **pp, ApplyModifiersState *st)
2079 {
2080 time_t utc;
2081
2082 const char *mod = *pp;
2083 if (!ModMatchEq(mod, "localtime", st->endc))
2084 return AMR_UNKNOWN;
2085
2086 if (mod[9] == '=') {
2087 char *ep;
2088 utc = strtoul(mod + 10, &ep, 10);
2089 *pp = ep;
2090 } else {
2091 utc = 0;
2092 *pp = mod + 9;
2093 }
2094 st->newVal = VarStrftime(st->val, 0, utc);
2095 return AMR_OK;
2096 }
2097
2098 /* :hash */
2099 static ApplyModifierResult
2100 ApplyModifier_Hash(const char **pp, ApplyModifiersState *st)
2101 {
2102 if (!ModMatch(*pp, "hash", st->endc))
2103 return AMR_UNKNOWN;
2104
2105 st->newVal = VarHash(st->val);
2106 *pp += 4;
2107 return AMR_OK;
2108 }
2109
2110 /* :P */
2111 static ApplyModifierResult
2112 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
2113 {
2114 GNode *gn;
2115
2116 if (st->v->flags & VAR_JUNK)
2117 st->v->flags |= VAR_KEEP;
2118
2119 gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
2120 if (gn == NULL || gn->type & OP_NOPATH) {
2121 st->newVal = NULL;
2122 } else if (gn->path) {
2123 st->newVal = bmake_strdup(gn->path);
2124 } else {
2125 st->newVal = Dir_FindFile(st->v->name, Suff_FindPath(gn));
2126 }
2127 if (st->newVal == NULL)
2128 st->newVal = bmake_strdup(st->v->name);
2129
2130 (*pp)++;
2131 return AMR_OK;
2132 }
2133
2134 /* :!cmd! */
2135 static ApplyModifierResult
2136 ApplyModifier_Exclam(const char **pp, ApplyModifiersState *st)
2137 {
2138 char delim;
2139 char *cmd;
2140 const char *errfmt;
2141
2142 (*pp)++;
2143 delim = '!';
2144 cmd = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
2145 NULL, NULL, NULL);
2146 if (cmd == NULL) {
2147 st->missing_delim = delim;
2148 return AMR_CLEANUP;
2149 }
2150
2151 errfmt = NULL;
2152 if (st->eflags & VARE_WANTRES)
2153 st->newVal = Cmd_Exec(cmd, &errfmt);
2154 else
2155 st->newVal = varNoError;
2156 free(cmd);
2157
2158 if (errfmt != NULL)
2159 Error(errfmt, st->val); /* XXX: why still return AMR_OK? */
2160
2161 if (st->v->flags & VAR_JUNK)
2162 st->v->flags |= VAR_KEEP;
2163 return AMR_OK;
2164 }
2165
2166 /* The :range modifier generates an integer sequence as long as the words.
2167 * The :range=7 modifier generates an integer sequence from 1 to 7. */
2168 static ApplyModifierResult
2169 ApplyModifier_Range(const char **pp, ApplyModifiersState *st)
2170 {
2171 int n;
2172 Buffer buf;
2173 int i;
2174
2175 const char *mod = *pp;
2176 if (!ModMatchEq(mod, "range", st->endc))
2177 return AMR_UNKNOWN;
2178
2179 if (mod[5] == '=') {
2180 char *ep;
2181 n = strtoul(mod + 6, &ep, 10);
2182 *pp = ep;
2183 } else {
2184 n = 0;
2185 *pp = mod + 5;
2186 }
2187
2188 if (n == 0) {
2189 char *as;
2190 char **av = brk_string(st->val, &n, FALSE, &as);
2191 free(as);
2192 free(av);
2193 }
2194
2195 Buf_InitZ(&buf, 0);
2196
2197 for (i = 0; i < n; i++) {
2198 if (i != 0)
2199 Buf_AddByte(&buf, ' ');
2200 Buf_AddInt(&buf, 1 + i);
2201 }
2202
2203 st->newVal = Buf_Destroy(&buf, FALSE);
2204 return AMR_OK;
2205 }
2206
2207 /* :Mpattern or :Npattern */
2208 static ApplyModifierResult
2209 ApplyModifier_Match(const char **pp, ApplyModifiersState *st)
2210 {
2211 const char *mod = *pp;
2212 Boolean copy = FALSE; /* pattern should be, or has been, copied */
2213 Boolean needSubst = FALSE;
2214 const char *endpat;
2215 char *pattern;
2216 ModifyWordsCallback callback;
2217
2218 /*
2219 * In the loop below, ignore ':' unless we are at (or back to) the
2220 * original brace level.
2221 * XXX This will likely not work right if $() and ${} are intermixed.
2222 */
2223 int nest = 0;
2224 const char *p;
2225 for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
2226 if (*p == '\\' &&
2227 (p[1] == ':' || p[1] == st->endc || p[1] == st->startc)) {
2228 if (!needSubst)
2229 copy = TRUE;
2230 p++;
2231 continue;
2232 }
2233 if (*p == '$')
2234 needSubst = TRUE;
2235 if (*p == '(' || *p == '{')
2236 ++nest;
2237 if (*p == ')' || *p == '}') {
2238 --nest;
2239 if (nest < 0)
2240 break;
2241 }
2242 }
2243 *pp = p;
2244 endpat = p;
2245
2246 if (copy) {
2247 char *dst;
2248 const char *src;
2249
2250 /* Compress the \:'s out of the pattern. */
2251 pattern = bmake_malloc(endpat - (mod + 1) + 1);
2252 dst = pattern;
2253 src = mod + 1;
2254 for (; src < endpat; src++, dst++) {
2255 if (src[0] == '\\' && src + 1 < endpat &&
2256 /* XXX: st->startc is missing here; see above */
2257 (src[1] == ':' || src[1] == st->endc))
2258 src++;
2259 *dst = *src;
2260 }
2261 *dst = '\0';
2262 endpat = dst;
2263 } else {
2264 /*
2265 * Either Var_Subst or ModifyWords will need a
2266 * nul-terminated string soon, so construct one now.
2267 */
2268 pattern = bmake_strndup(mod + 1, endpat - (mod + 1));
2269 }
2270
2271 if (needSubst) {
2272 /* pattern contains embedded '$', so use Var_Subst to expand it. */
2273 char *old_pattern = pattern;
2274 pattern = Var_Subst(pattern, st->ctxt, st->eflags);
2275 free(old_pattern);
2276 }
2277
2278 VAR_DEBUG("Pattern[%s] for [%s] is [%s]\n", st->v->name, st->val, pattern);
2279
2280 callback = mod[0] == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
2281 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2282 callback, pattern);
2283 free(pattern);
2284 return AMR_OK;
2285 }
2286
2287 /* :S,from,to, */
2288 static ApplyModifierResult
2289 ApplyModifier_Subst(const char **pp, ApplyModifiersState *st)
2290 {
2291 ModifyWord_SubstArgs args;
2292 char *lhs, *rhs;
2293 Boolean oneBigWord;
2294
2295 char delim = (*pp)[1];
2296 if (delim == '\0') {
2297 Error("Missing delimiter for :S modifier");
2298 (*pp)++;
2299 return AMR_CLEANUP;
2300 }
2301
2302 *pp += 2;
2303
2304 args.pflags = 0;
2305
2306 /*
2307 * If pattern begins with '^', it is anchored to the
2308 * start of the word -- skip over it and flag pattern.
2309 */
2310 if (**pp == '^') {
2311 args.pflags |= VARP_ANCHOR_START;
2312 (*pp)++;
2313 }
2314
2315 lhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
2316 &args.lhsLen, &args.pflags, NULL);
2317 if (lhs == NULL) {
2318 st->missing_delim = delim;
2319 return AMR_CLEANUP;
2320 }
2321 args.lhs = lhs;
2322
2323 rhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
2324 &args.rhsLen, NULL, &args);
2325 if (rhs == NULL) {
2326 st->missing_delim = delim;
2327 return AMR_CLEANUP;
2328 }
2329 args.rhs = rhs;
2330
2331 oneBigWord = st->oneBigWord;
2332 for (;; (*pp)++) {
2333 switch (**pp) {
2334 case 'g':
2335 args.pflags |= VARP_SUB_GLOBAL;
2336 continue;
2337 case '1':
2338 args.pflags |= VARP_SUB_ONE;
2339 continue;
2340 case 'W':
2341 oneBigWord = TRUE;
2342 continue;
2343 }
2344 break;
2345 }
2346
2347 st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
2348 ModifyWord_Subst, &args);
2349
2350 free(lhs);
2351 free(rhs);
2352 return AMR_OK;
2353 }
2354
2355 #ifndef NO_REGEX
2356
2357 /* :C,from,to, */
2358 static ApplyModifierResult
2359 ApplyModifier_Regex(const char **pp, ApplyModifiersState *st)
2360 {
2361 char *re;
2362 ModifyWord_SubstRegexArgs args;
2363 Boolean oneBigWord;
2364 int error;
2365
2366 char delim = (*pp)[1];
2367 if (delim == '\0') {
2368 Error("Missing delimiter for :C modifier");
2369 (*pp)++;
2370 return AMR_CLEANUP;
2371 }
2372
2373 *pp += 2;
2374
2375 re = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
2376 if (re == NULL) {
2377 st->missing_delim = delim;
2378 return AMR_CLEANUP;
2379 }
2380
2381 args.replace = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
2382 NULL, NULL, NULL);
2383 if (args.replace == NULL) {
2384 free(re);
2385 st->missing_delim = delim;
2386 return AMR_CLEANUP;
2387 }
2388
2389 args.pflags = 0;
2390 oneBigWord = st->oneBigWord;
2391 for (;; (*pp)++) {
2392 switch (**pp) {
2393 case 'g':
2394 args.pflags |= VARP_SUB_GLOBAL;
2395 continue;
2396 case '1':
2397 args.pflags |= VARP_SUB_ONE;
2398 continue;
2399 case 'W':
2400 oneBigWord = TRUE;
2401 continue;
2402 }
2403 break;
2404 }
2405
2406 error = regcomp(&args.re, re, REG_EXTENDED);
2407 free(re);
2408 if (error) {
2409 VarREError(error, &args.re, "Regex compilation error");
2410 free(args.replace);
2411 return AMR_CLEANUP;
2412 }
2413
2414 args.nsub = args.re.re_nsub + 1;
2415 if (args.nsub < 1)
2416 args.nsub = 1;
2417 if (args.nsub > 10)
2418 args.nsub = 10;
2419 st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
2420 ModifyWord_SubstRegex, &args);
2421 regfree(&args.re);
2422 free(args.replace);
2423 return AMR_OK;
2424 }
2425 #endif
2426
2427 static void
2428 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
2429 {
2430 SepBuf_AddStr(buf, word);
2431 }
2432
2433 /* :ts<separator> */
2434 static ApplyModifierResult
2435 ApplyModifier_ToSep(const char **pp, ApplyModifiersState *st)
2436 {
2437 /* XXX: pp points to the 's', for historic reasons only.
2438 * Changing this will influence the error messages. */
2439 const char *sep = *pp + 1;
2440 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
2441 /* ":ts<any><endc>" or ":ts<any>:" */
2442 st->sep = sep[0];
2443 *pp = sep + 1;
2444 } else if (sep[0] == st->endc || sep[0] == ':') {
2445 /* ":ts<endc>" or ":ts:" */
2446 st->sep = '\0'; /* no separator */
2447 *pp = sep;
2448 } else if (sep[0] == '\\') {
2449 const char *xp = sep + 1;
2450 int base = 8; /* assume octal */
2451
2452 switch (sep[1]) {
2453 case 'n':
2454 st->sep = '\n';
2455 *pp = sep + 2;
2456 break;
2457 case 't':
2458 st->sep = '\t';
2459 *pp = sep + 2;
2460 break;
2461 case 'x':
2462 base = 16;
2463 xp++;
2464 goto get_numeric;
2465 case '0':
2466 base = 0;
2467 goto get_numeric;
2468 default:
2469 if (!isdigit((unsigned char)sep[1]))
2470 return AMR_BAD; /* ":ts<backslash><unrecognised>". */
2471
2472 get_numeric:
2473 {
2474 char *end;
2475 st->sep = strtoul(xp, &end, base);
2476 if (*end != ':' && *end != st->endc)
2477 return AMR_BAD;
2478 *pp = end;
2479 }
2480 break;
2481 }
2482 } else {
2483 return AMR_BAD; /* Found ":ts<unrecognised><unrecognised>". */
2484 }
2485
2486 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2487 ModifyWord_Copy, NULL);
2488 return AMR_OK;
2489 }
2490
2491 /* :tA, :tu, :tl, :ts<separator>, etc. */
2492 static ApplyModifierResult
2493 ApplyModifier_To(const char **pp, ApplyModifiersState *st)
2494 {
2495 const char *mod = *pp;
2496 assert(mod[0] == 't');
2497
2498 *pp = mod + 1; /* make sure it is set */
2499 if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0')
2500 return AMR_BAD; /* Found ":t<endc>" or ":t:". */
2501
2502 if (mod[1] == 's')
2503 return ApplyModifier_ToSep(pp, st);
2504
2505 if (mod[2] != st->endc && mod[2] != ':')
2506 return AMR_BAD; /* Found ":t<unrecognised><unrecognised>". */
2507
2508 /* Check for two-character options: ":tu", ":tl" */
2509 if (mod[1] == 'A') { /* absolute path */
2510 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2511 ModifyWord_Realpath, NULL);
2512 *pp = mod + 2;
2513 } else if (mod[1] == 'u') {
2514 size_t i;
2515 size_t len = strlen(st->val);
2516 st->newVal = bmake_malloc(len + 1);
2517 for (i = 0; i < len + 1; i++)
2518 st->newVal[i] = toupper((unsigned char)st->val[i]);
2519 *pp = mod + 2;
2520 } else if (mod[1] == 'l') {
2521 size_t i;
2522 size_t len = strlen(st->val);
2523 st->newVal = bmake_malloc(len + 1);
2524 for (i = 0; i < len + 1; i++)
2525 st->newVal[i] = tolower((unsigned char)st->val[i]);
2526 *pp = mod + 2;
2527 } else if (mod[1] == 'W' || mod[1] == 'w') {
2528 st->oneBigWord = mod[1] == 'W';
2529 st->newVal = st->val;
2530 *pp = mod + 2;
2531 } else {
2532 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
2533 return AMR_BAD;
2534 }
2535 return AMR_OK;
2536 }
2537
2538 /* :[#], :[1], etc. */
2539 static ApplyModifierResult
2540 ApplyModifier_Words(const char **pp, ApplyModifiersState *st)
2541 {
2542 char delim;
2543 char *estr;
2544 char *ep;
2545 int first, last;
2546
2547 (*pp)++; /* skip the '[' */
2548 delim = ']'; /* look for closing ']' */
2549 estr = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
2550 NULL, NULL, NULL);
2551 if (estr == NULL) {
2552 st->missing_delim = delim;
2553 return AMR_CLEANUP;
2554 }
2555
2556 /* now *pp points just after the closing ']' */
2557 if (**pp != ':' && **pp != st->endc)
2558 goto bad_modifier; /* Found junk after ']' */
2559
2560 if (estr[0] == '\0')
2561 goto bad_modifier; /* empty square brackets in ":[]". */
2562
2563 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
2564 if (st->oneBigWord) {
2565 st->newVal = bmake_strdup("1");
2566 } else {
2567 Buffer buf;
2568
2569 /* XXX: brk_string() is a rather expensive
2570 * way of counting words. */
2571 char *as;
2572 int ac;
2573 char **av = brk_string(st->val, &ac, FALSE, &as);
2574 free(as);
2575 free(av);
2576
2577 Buf_InitZ(&buf, 4); /* 3 digits + '\0' */
2578 Buf_AddInt(&buf, ac);
2579 st->newVal = Buf_Destroy(&buf, FALSE);
2580 }
2581 goto ok;
2582 }
2583
2584 if (estr[0] == '*' && estr[1] == '\0') {
2585 /* Found ":[*]" */
2586 st->oneBigWord = TRUE;
2587 st->newVal = st->val;
2588 goto ok;
2589 }
2590
2591 if (estr[0] == '@' && estr[1] == '\0') {
2592 /* Found ":[@]" */
2593 st->oneBigWord = FALSE;
2594 st->newVal = st->val;
2595 goto ok;
2596 }
2597
2598 /*
2599 * We expect estr to contain a single integer for :[N], or two integers
2600 * separated by ".." for :[start..end].
2601 */
2602 first = strtol(estr, &ep, 0);
2603 if (ep == estr) /* Found junk instead of a number */
2604 goto bad_modifier;
2605
2606 if (ep[0] == '\0') { /* Found only one integer in :[N] */
2607 last = first;
2608 } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') {
2609 /* Expecting another integer after ".." */
2610 ep += 2;
2611 last = strtol(ep, &ep, 0);
2612 if (ep[0] != '\0') /* Found junk after ".." */
2613 goto bad_modifier;
2614 } else
2615 goto bad_modifier; /* Found junk instead of ".." */
2616
2617 /*
2618 * Now seldata is properly filled in, but we still have to check for 0 as
2619 * a special case.
2620 */
2621 if (first == 0 && last == 0) {
2622 /* ":[0]" or perhaps ":[0..0]" */
2623 st->oneBigWord = TRUE;
2624 st->newVal = st->val;
2625 goto ok;
2626 }
2627
2628 /* ":[0..N]" or ":[N..0]" */
2629 if (first == 0 || last == 0)
2630 goto bad_modifier;
2631
2632 /* Normal case: select the words described by seldata. */
2633 st->newVal = VarSelectWords(st->sep, st->oneBigWord, st->val, first, last);
2634
2635 ok:
2636 free(estr);
2637 return AMR_OK;
2638
2639 bad_modifier:
2640 free(estr);
2641 return AMR_BAD;
2642 }
2643
2644 static int
2645 str_cmp_asc(const void *a, const void *b)
2646 {
2647 return strcmp(*(const char * const *)a, *(const char * const *)b);
2648 }
2649
2650 static int
2651 str_cmp_desc(const void *a, const void *b)
2652 {
2653 return strcmp(*(const char * const *)b, *(const char * const *)a);
2654 }
2655
2656 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
2657 static ApplyModifierResult
2658 ApplyModifier_Order(const char **pp, ApplyModifiersState *st)
2659 {
2660 const char *mod = (*pp)++; /* skip past the 'O' in any case */
2661
2662 char *as; /* word list memory */
2663 int ac;
2664 char **av = brk_string(st->val, &ac, FALSE, &as);
2665
2666 if (mod[1] == st->endc || mod[1] == ':') {
2667 /* :O sorts ascending */
2668 qsort(av, ac, sizeof(char *), str_cmp_asc);
2669
2670 } else if ((mod[1] == 'r' || mod[1] == 'x') &&
2671 (mod[2] == st->endc || mod[2] == ':')) {
2672 (*pp)++;
2673
2674 if (mod[1] == 'r') {
2675 /* :Or sorts descending */
2676 qsort(av, ac, sizeof(char *), str_cmp_desc);
2677
2678 } else {
2679 /* :Ox shuffles
2680 *
2681 * We will use [ac..2] range for mod factors. This will produce
2682 * random numbers in [(ac-1)..0] interval, and minimal
2683 * reasonable value for mod factor is 2 (the mod 1 will produce
2684 * 0 with probability 1).
2685 */
2686 int i;
2687 for (i = ac - 1; i > 0; i--) {
2688 int rndidx = random() % (i + 1);
2689 char *t = av[i];
2690 av[i] = av[rndidx];
2691 av[rndidx] = t;
2692 }
2693 }
2694 } else {
2695 free(as);
2696 free(av);
2697 return AMR_BAD;
2698 }
2699
2700 st->newVal = WordList_JoinFree(av, ac, as);
2701 return AMR_OK;
2702 }
2703
2704 /* :? then : else */
2705 static ApplyModifierResult
2706 ApplyModifier_IfElse(const char **pp, ApplyModifiersState *st)
2707 {
2708 char delim;
2709 char *then_expr, *else_expr;
2710
2711 Boolean value = FALSE;
2712 VarEvalFlags then_eflags = st->eflags & ~VARE_WANTRES;
2713 VarEvalFlags else_eflags = st->eflags & ~VARE_WANTRES;
2714
2715 int cond_rc = COND_PARSE; /* anything other than COND_INVALID */
2716 if (st->eflags & VARE_WANTRES) {
2717 cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE);
2718 if (cond_rc != COND_INVALID && value)
2719 then_eflags |= VARE_WANTRES;
2720 if (cond_rc != COND_INVALID && !value)
2721 else_eflags |= VARE_WANTRES;
2722 }
2723
2724 (*pp)++; /* skip past the '?' */
2725 delim = ':';
2726 then_expr = ParseModifierPart(pp, delim, then_eflags, st->ctxt,
2727 NULL, NULL, NULL);
2728 if (then_expr == NULL) {
2729 st->missing_delim = delim;
2730 return AMR_CLEANUP;
2731 }
2732
2733 delim = st->endc; /* BRCLOSE or PRCLOSE */
2734 else_expr = ParseModifierPart(pp, delim, else_eflags, st->ctxt,
2735 NULL, NULL, NULL);
2736 if (else_expr == NULL) {
2737 st->missing_delim = delim;
2738 return AMR_CLEANUP;
2739 }
2740
2741 (*pp)--;
2742 if (cond_rc == COND_INVALID) {
2743 Error("Bad conditional expression `%s' in %s?%s:%s",
2744 st->v->name, st->v->name, then_expr, else_expr);
2745 return AMR_CLEANUP;
2746 }
2747
2748 if (value) {
2749 st->newVal = then_expr;
2750 free(else_expr);
2751 } else {
2752 st->newVal = else_expr;
2753 free(then_expr);
2754 }
2755 if (st->v->flags & VAR_JUNK)
2756 st->v->flags |= VAR_KEEP;
2757 return AMR_OK;
2758 }
2759
2760 /*
2761 * The ::= modifiers actually assign a value to the variable.
2762 * Their main purpose is in supporting modifiers of .for loop
2763 * iterators and other obscure uses. They always expand to
2764 * nothing. In a target rule that would otherwise expand to an
2765 * empty line they can be preceded with @: to keep make happy.
2766 * Eg.
2767 *
2768 * foo: .USE
2769 * .for i in ${.TARGET} ${.TARGET:R}.gz
2770 * @: ${t::=$i}
2771 * @echo blah ${t:T}
2772 * .endfor
2773 *
2774 * ::=<str> Assigns <str> as the new value of variable.
2775 * ::?=<str> Assigns <str> as value of variable if
2776 * it was not already set.
2777 * ::+=<str> Appends <str> to variable.
2778 * ::!=<cmd> Assigns output of <cmd> as the new value of
2779 * variable.
2780 */
2781 static ApplyModifierResult
2782 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
2783 {
2784 GNode *v_ctxt;
2785 char *sv_name;
2786 char delim;
2787 char *val;
2788
2789 const char *mod = *pp;
2790 const char *op = mod + 1;
2791 if (!(op[0] == '=' ||
2792 (op[1] == '=' &&
2793 (op[0] == '!' || op[0] == '+' || op[0] == '?'))))
2794 return AMR_UNKNOWN; /* "::<unrecognised>" */
2795
2796
2797 if (st->v->name[0] == 0) {
2798 *pp = mod + 1;
2799 return AMR_BAD;
2800 }
2801
2802 v_ctxt = st->ctxt; /* context where v belongs */
2803 sv_name = NULL;
2804 if (st->v->flags & VAR_JUNK) {
2805 /*
2806 * We need to bmake_strdup() it in case ParseModifierPart() recurses.
2807 */
2808 sv_name = st->v->name;
2809 st->v->name = bmake_strdup(st->v->name);
2810 } else if (st->ctxt != VAR_GLOBAL) {
2811 Var *gv = VarFind(st->v->name, st->ctxt, 0);
2812 if (gv == NULL)
2813 v_ctxt = VAR_GLOBAL;
2814 else
2815 VarFreeEnv(gv, TRUE);
2816 }
2817
2818 switch (op[0]) {
2819 case '+':
2820 case '?':
2821 case '!':
2822 *pp = mod + 3;
2823 break;
2824 default:
2825 *pp = mod + 2;
2826 break;
2827 }
2828
2829 delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE;
2830 val = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
2831 if (st->v->flags & VAR_JUNK) {
2832 /* restore original name */
2833 free(st->v->name);
2834 st->v->name = sv_name;
2835 }
2836 if (val == NULL) {
2837 st->missing_delim = delim;
2838 return AMR_CLEANUP;
2839 }
2840
2841 (*pp)--;
2842
2843 if (st->eflags & VARE_WANTRES) {
2844 switch (op[0]) {
2845 case '+':
2846 Var_Append(st->v->name, val, v_ctxt);
2847 break;
2848 case '!': {
2849 const char *errfmt;
2850 char *cmd_output = Cmd_Exec(val, &errfmt);
2851 if (errfmt)
2852 Error(errfmt, st->val);
2853 else
2854 Var_Set(st->v->name, cmd_output, v_ctxt);
2855 free(cmd_output);
2856 break;
2857 }
2858 case '?':
2859 if (!(st->v->flags & VAR_JUNK))
2860 break;
2861 /* FALLTHROUGH */
2862 default:
2863 Var_Set(st->v->name, val, v_ctxt);
2864 break;
2865 }
2866 }
2867 free(val);
2868 st->newVal = varNoError;
2869 return AMR_OK;
2870 }
2871
2872 /* remember current value */
2873 static ApplyModifierResult
2874 ApplyModifier_Remember(const char **pp, ApplyModifiersState *st)
2875 {
2876 const char *mod = *pp;
2877 if (!ModMatchEq(mod, "_", st->endc))
2878 return AMR_UNKNOWN;
2879
2880 if (mod[1] == '=') {
2881 size_t n = strcspn(mod + 2, ":)}");
2882 char *name = bmake_strndup(mod + 2, n);
2883 Var_Set(name, st->val, st->ctxt);
2884 free(name);
2885 *pp = mod + 2 + n;
2886 } else {
2887 Var_Set("_", st->val, st->ctxt);
2888 *pp = mod + 1;
2889 }
2890 st->newVal = st->val;
2891 return AMR_OK;
2892 }
2893
2894 #ifdef SYSVVARSUB
2895 /* :from=to */
2896 static ApplyModifierResult
2897 ApplyModifier_SysV(const char **pp, ApplyModifiersState *st)
2898 {
2899 char delim;
2900 char *lhs, *rhs;
2901
2902 const char *mod = *pp;
2903 Boolean eqFound = FALSE;
2904
2905 /*
2906 * First we make a pass through the string trying
2907 * to verify it is a SYSV-make-style translation:
2908 * it must be: <string1>=<string2>)
2909 */
2910 int nest = 1;
2911 const char *next = mod;
2912 while (*next != '\0' && nest > 0) {
2913 if (*next == '=') {
2914 eqFound = TRUE;
2915 /* continue looking for st->endc */
2916 } else if (*next == st->endc)
2917 nest--;
2918 else if (*next == st->startc)
2919 nest++;
2920 if (nest > 0)
2921 next++;
2922 }
2923 if (*next != st->endc || !eqFound)
2924 return AMR_UNKNOWN;
2925
2926 delim = '=';
2927 *pp = mod;
2928 lhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
2929 if (lhs == NULL) {
2930 st->missing_delim = delim;
2931 return AMR_CLEANUP;
2932 }
2933
2934 delim = st->endc;
2935 rhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
2936 if (rhs == NULL) {
2937 st->missing_delim = delim;
2938 return AMR_CLEANUP;
2939 }
2940
2941 /*
2942 * SYSV modifications happen through the whole
2943 * string. Note the pattern is anchored at the end.
2944 */
2945 (*pp)--;
2946 if (lhs[0] == '\0' && *st->val == '\0') {
2947 st->newVal = st->val; /* special case */
2948 } else {
2949 ModifyWord_SYSVSubstArgs args = {st->ctxt, lhs, rhs};
2950 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2951 ModifyWord_SYSVSubst, &args);
2952 }
2953 free(lhs);
2954 free(rhs);
2955 return AMR_OK;
2956 }
2957 #endif
2958
2959 /*
2960 * Now we need to apply any modifiers the user wants applied.
2961 * These are:
2962 * :M<pattern> words which match the given <pattern>.
2963 * <pattern> is of the standard file
2964 * wildcarding form.
2965 * :N<pattern> words which do not match the given <pattern>.
2966 * :S<d><pat1><d><pat2><d>[1gW]
2967 * Substitute <pat2> for <pat1> in the value
2968 * :C<d><pat1><d><pat2><d>[1gW]
2969 * Substitute <pat2> for regex <pat1> in the value
2970 * :H Substitute the head of each word
2971 * :T Substitute the tail of each word
2972 * :E Substitute the extension (minus '.') of
2973 * each word
2974 * :R Substitute the root of each word
2975 * (pathname minus the suffix).
2976 * :O ("Order") Alphabeticaly sort words in variable.
2977 * :Ox ("intermiX") Randomize words in variable.
2978 * :u ("uniq") Remove adjacent duplicate words.
2979 * :tu Converts the variable contents to uppercase.
2980 * :tl Converts the variable contents to lowercase.
2981 * :ts[c] Sets varSpace - the char used to
2982 * separate words to 'c'. If 'c' is
2983 * omitted then no separation is used.
2984 * :tW Treat the variable contents as a single
2985 * word, even if it contains spaces.
2986 * (Mnemonic: one big 'W'ord.)
2987 * :tw Treat the variable contents as multiple
2988 * space-separated words.
2989 * (Mnemonic: many small 'w'ords.)
2990 * :[index] Select a single word from the value.
2991 * :[start..end] Select multiple words from the value.
2992 * :[*] or :[0] Select the entire value, as a single
2993 * word. Equivalent to :tW.
2994 * :[@] Select the entire value, as multiple
2995 * words. Undoes the effect of :[*].
2996 * Equivalent to :tw.
2997 * :[#] Returns the number of words in the value.
2998 *
2999 * :?<true-value>:<false-value>
3000 * If the variable evaluates to true, return
3001 * true-value, else return false-value.
3002 * :lhs=rhs Similar to :S, but the rhs goes to the end of
3003 * the invocation, including any ':'.
3004 * :sh Treat the current value as a command
3005 * to be run, new value is its output.
3006 * The following added so we can handle ODE makefiles.
3007 * :@<tmpvar>@<newval>@
3008 * Assign a temporary global variable <tmpvar>
3009 * to the current value of each word in turn
3010 * and replace each word with the result of
3011 * evaluating <newval>
3012 * :D<newval> Use <newval> as value if variable defined
3013 * :U<newval> Use <newval> as value if variable undefined
3014 * :L Use the name of the variable as the value.
3015 * :P Use the path of the node that has the same
3016 * name as the variable as the value. This
3017 * basically includes an implied :L so that
3018 * the common method of refering to the path
3019 * of your dependent 'x' in a rule is to use
3020 * the form '${x:P}'.
3021 * :!<cmd>! Run cmd much the same as :sh runs the
3022 * current value of the variable.
3023 * Assignment operators (see ApplyModifier_Assign).
3024 */
3025 static char *
3026 ApplyModifiers(
3027 const char **pp, /* the parsing position, updated upon return */
3028 char *val, /* the current value of the variable */
3029 int const startc, /* '(' or '{' or '\0' */
3030 int const endc, /* ')' or '}' or '\0' */
3031 Var * const v, /* the variable may have its flags changed */
3032 GNode * const ctxt, /* for looking up and modifying variables */
3033 VarEvalFlags const eflags,
3034 void ** const freePtr /* free this after using the return value */
3035 ) {
3036 ApplyModifiersState st = {
3037 startc, endc, v, ctxt, eflags,
3038 val, NULL, '\0', ' ', FALSE
3039 };
3040 const char *p;
3041 const char *mod;
3042 ApplyModifierResult res;
3043
3044 assert(startc == '(' || startc == '{' || startc == '\0');
3045 assert(endc == ')' || endc == '}' || endc == '\0');
3046
3047 p = *pp;
3048 while (*p != '\0' && *p != endc) {
3049
3050 if (*p == '$') {
3051 /*
3052 * We may have some complex modifiers in a variable.
3053 */
3054 int rlen;
3055 void *freeIt;
3056 const char *rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt);
3057
3058 /*
3059 * If we have not parsed up to st.endc or ':',
3060 * we are not interested.
3061 */
3062 int c;
3063 if (rval != NULL && *rval &&
3064 (c = p[rlen]) != '\0' && c != ':' && c != st.endc) {
3065 free(freeIt);
3066 goto apply_mods;
3067 }
3068
3069 VAR_DEBUG("Got '%s' from '%.*s'%.*s\n",
3070 rval, rlen, p, rlen, p + rlen);
3071
3072 p += rlen;
3073
3074 if (rval != NULL && *rval) {
3075 const char *rval_pp = rval;
3076 st.val = ApplyModifiers(&rval_pp, st.val, 0, 0, v,
3077 ctxt, eflags, freePtr);
3078 if (st.val == var_Error
3079 || (st.val == varNoError && !(st.eflags & VARE_UNDEFERR))
3080 || *rval_pp != '\0') {
3081 free(freeIt);
3082 goto out; /* error already reported */
3083 }
3084 }
3085 free(freeIt);
3086 if (*p == ':')
3087 p++;
3088 else if (*p == '\0' && endc != '\0') {
3089 Error("Unclosed variable specification after complex "
3090 "modifier (expecting '%c') for %s", st.endc, st.v->name);
3091 goto out;
3092 }
3093 continue;
3094 }
3095 apply_mods:
3096 VAR_DEBUG("Applying[%s] :%c to \"%s\"\n", st.v->name, *p, st.val);
3097 st.newVal = var_Error; /* default value, in case of errors */
3098 res = AMR_BAD; /* just a safe fallback */
3099 mod = p;
3100 switch (*mod) {
3101 case ':':
3102 res = ApplyModifier_Assign(&p, &st);
3103 break;
3104 case '@':
3105 res = ApplyModifier_Loop(&p, &st);
3106 break;
3107 case '_':
3108 res = ApplyModifier_Remember(&p, &st);
3109 break;
3110 case 'D':
3111 case 'U':
3112 res = ApplyModifier_Defined(&p, &st);
3113 break;
3114 case 'L':
3115 if (st.v->flags & VAR_JUNK)
3116 st.v->flags |= VAR_KEEP;
3117 st.newVal = bmake_strdup(st.v->name);
3118 p++;
3119 res = AMR_OK;
3120 break;
3121 case 'P':
3122 res = ApplyModifier_Path(&p, &st);
3123 break;
3124 case '!':
3125 res = ApplyModifier_Exclam(&p, &st);
3126 break;
3127 case '[':
3128 res = ApplyModifier_Words(&p, &st);
3129 break;
3130 case 'g':
3131 res = ApplyModifier_Gmtime(&p, &st);
3132 break;
3133 case 'h':
3134 res = ApplyModifier_Hash(&p, &st);
3135 break;
3136 case 'l':
3137 res = ApplyModifier_Localtime(&p, &st);
3138 break;
3139 case 't':
3140 res = ApplyModifier_To(&p, &st);
3141 break;
3142 case 'N':
3143 case 'M':
3144 res = ApplyModifier_Match(&p, &st);
3145 break;
3146 case 'S':
3147 res = ApplyModifier_Subst(&p, &st);
3148 break;
3149 case '?':
3150 res = ApplyModifier_IfElse(&p, &st);
3151 break;
3152 #ifndef NO_REGEX
3153 case 'C':
3154 res = ApplyModifier_Regex(&p, &st);
3155 break;
3156 #endif
3157 case 'q':
3158 case 'Q':
3159 if (p[1] == st.endc || p[1] == ':') {
3160 st.newVal = VarQuote(st.val, *mod == 'q');
3161 p++;
3162 res = AMR_OK;
3163 } else
3164 res = AMR_UNKNOWN;
3165 break;
3166 case 'T':
3167 if (p[1] == st.endc || p[1] == ':') {
3168 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3169 st.val, ModifyWord_Tail, NULL);
3170 p++;
3171 res = AMR_OK;
3172 } else
3173 res = AMR_UNKNOWN;
3174 break;
3175 case 'H':
3176 if (p[1] == st.endc || p[1] == ':') {
3177 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3178 st.val, ModifyWord_Head, NULL);
3179 p++;
3180 res = AMR_OK;
3181 } else
3182 res = AMR_UNKNOWN;
3183 break;
3184 case 'E':
3185 if (p[1] == st.endc || p[1] == ':') {
3186 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3187 st.val, ModifyWord_Suffix, NULL);
3188 p++;
3189 res = AMR_OK;
3190 } else
3191 res = AMR_UNKNOWN;
3192 break;
3193 case 'R':
3194 if (p[1] == st.endc || p[1] == ':') {
3195 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3196 st.val, ModifyWord_Root, NULL);
3197 p++;
3198 res = AMR_OK;
3199 } else
3200 res = AMR_UNKNOWN;
3201 break;
3202 case 'r':
3203 res = ApplyModifier_Range(&p, &st);
3204 break;
3205 case 'O':
3206 res = ApplyModifier_Order(&p, &st);
3207 break;
3208 case 'u':
3209 if (p[1] == st.endc || p[1] == ':') {
3210 st.newVal = VarUniq(st.val);
3211 p++;
3212 res = AMR_OK;
3213 } else
3214 res = AMR_UNKNOWN;
3215 break;
3216 #ifdef SUNSHCMD
3217 case 's':
3218 if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
3219 if (st.eflags & VARE_WANTRES) {
3220 const char *errfmt;
3221 st.newVal = Cmd_Exec(st.val, &errfmt);
3222 if (errfmt)
3223 Error(errfmt, st.val);
3224 } else
3225 st.newVal = varNoError;
3226 p += 2;
3227 res = AMR_OK;
3228 } else
3229 res = AMR_UNKNOWN;
3230 break;
3231 #endif
3232 default:
3233 res = AMR_UNKNOWN;
3234 }
3235
3236 #ifdef SYSVVARSUB
3237 if (res == AMR_UNKNOWN) {
3238 assert(p == mod);
3239 res = ApplyModifier_SysV(&p, &st);
3240 }
3241 #endif
3242
3243 if (res == AMR_UNKNOWN) {
3244 Error("Unknown modifier '%c'", *mod);
3245 for (p++; *p != ':' && *p != st.endc && *p != '\0'; p++)
3246 continue;
3247 st.newVal = var_Error;
3248 }
3249 if (res == AMR_CLEANUP)
3250 goto cleanup;
3251 if (res == AMR_BAD)
3252 goto bad_modifier;
3253
3254 VAR_DEBUG("Result[%s] of :%c is \"%s\"\n", st.v->name, *mod, st.newVal);
3255
3256 if (st.newVal != st.val) {
3257 if (*freePtr) {
3258 free(st.val);
3259 *freePtr = NULL;
3260 }
3261 st.val = st.newVal;
3262 if (st.val != var_Error && st.val != varNoError) {
3263 *freePtr = st.val;
3264 }
3265 }
3266 if (*p == '\0' && st.endc != '\0') {
3267 Error("Unclosed variable specification (expecting '%c') "
3268 "for \"%s\" (value \"%s\") modifier %c",
3269 st.endc, st.v->name, st.val, *mod);
3270 } else if (*p == ':') {
3271 p++;
3272 }
3273 mod = p;
3274 }
3275 out:
3276 *pp = p;
3277 return st.val;
3278
3279 bad_modifier:
3280 Error("Bad modifier `:%.*s' for %s",
3281 (int)strcspn(mod, ":)}"), mod, st.v->name);
3282
3283 cleanup:
3284 *pp = p;
3285 if (st.missing_delim != '\0')
3286 Error("Unclosed substitution for %s (%c missing)",
3287 st.v->name, st.missing_delim);
3288 free(*freePtr);
3289 *freePtr = NULL;
3290 return var_Error;
3291 }
3292
3293 static Boolean
3294 VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)
3295 {
3296 if ((namelen == 1 ||
3297 (namelen == 2 && (varname[1] == 'F' || varname[1] == 'D'))) &&
3298 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3299 {
3300 /*
3301 * If substituting a local variable in a non-local context,
3302 * assume it's for dynamic source stuff. We have to handle
3303 * this specially and return the longhand for the variable
3304 * with the dollar sign escaped so it makes it back to the
3305 * caller. Only four of the local variables are treated
3306 * specially as they are the only four that will be set
3307 * when dynamic sources are expanded.
3308 */
3309 switch (varname[0]) {
3310 case '@':
3311 case '%':
3312 case '*':
3313 case '!':
3314 return TRUE;
3315 }
3316 return FALSE;
3317 }
3318
3319 if ((namelen == 7 || namelen == 8) && varname[0] == '.' &&
3320 isupper((unsigned char)varname[1]) &&
3321 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3322 {
3323 return strcmp(varname, ".TARGET") == 0 ||
3324 strcmp(varname, ".ARCHIVE") == 0 ||
3325 strcmp(varname, ".PREFIX") == 0 ||
3326 strcmp(varname, ".MEMBER") == 0;
3327 }
3328
3329 return FALSE;
3330 }
3331
3332 /*-
3333 *-----------------------------------------------------------------------
3334 * Var_Parse --
3335 * Given the start of a variable invocation (such as $v, $(VAR),
3336 * ${VAR:Mpattern}), extract the variable name, possibly some
3337 * modifiers and find its value by applying the modifiers to the
3338 * original value.
3339 *
3340 * Input:
3341 * str The string to parse
3342 * ctxt The context for the variable
3343 * flags VARE_UNDEFERR if undefineds are an error
3344 * VARE_WANTRES if we actually want the result
3345 * VARE_ASSIGN if we are in a := assignment
3346 * lengthPtr OUT: The length of the specification
3347 * freePtr OUT: Non-NULL if caller should free *freePtr
3348 *
3349 * Results:
3350 * The (possibly-modified) value of the variable or var_Error if the
3351 * specification is invalid. The length of the specification is
3352 * placed in *lengthPtr (for invalid specifications, this is just
3353 * 2...?).
3354 * If *freePtr is non-NULL then it's a pointer that the caller
3355 * should pass to free() to free memory used by the result.
3356 *
3357 * Side Effects:
3358 * None.
3359 *
3360 *-----------------------------------------------------------------------
3361 */
3362 /* coverity[+alloc : arg-*4] */
3363 const char *
3364 Var_Parse(const char * const str, GNode *ctxt, VarEvalFlags eflags,
3365 int *lengthPtr, void **freePtr)
3366 {
3367 const char *tstr; /* Pointer into str */
3368 Boolean haveModifier; /* TRUE if have modifiers for the variable */
3369 char startc; /* Starting character when variable in parens
3370 * or braces */
3371 char endc; /* Ending character when variable in parens
3372 * or braces */
3373 Boolean dynamic; /* TRUE if the variable is local and we're
3374 * expanding it in a non-local context. This
3375 * is done to support dynamic sources. The
3376 * result is just the invocation, unaltered */
3377 const char *extramodifiers;
3378 Var *v;
3379 char *nstr;
3380
3381 *freePtr = NULL;
3382 extramodifiers = NULL; /* extra modifiers to apply first */
3383 dynamic = FALSE;
3384
3385 startc = str[1];
3386 if (startc != PROPEN && startc != BROPEN) {
3387 char name[2];
3388
3389 /*
3390 * If it's not bounded by braces of some sort, life is much simpler.
3391 * We just need to check for the first character and return the
3392 * value if it exists.
3393 */
3394
3395 /* Error out some really stupid names */
3396 if (startc == '\0' || strchr(")}:$", startc)) {
3397 *lengthPtr = 1;
3398 return var_Error;
3399 }
3400
3401 name[0] = startc;
3402 name[1] = '\0';
3403 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3404 if (v == NULL) {
3405 *lengthPtr = 2;
3406
3407 if (ctxt == VAR_CMD || ctxt == VAR_GLOBAL) {
3408 /*
3409 * If substituting a local variable in a non-local context,
3410 * assume it's for dynamic source stuff. We have to handle
3411 * this specially and return the longhand for the variable
3412 * with the dollar sign escaped so it makes it back to the
3413 * caller. Only four of the local variables are treated
3414 * specially as they are the only four that will be set
3415 * when dynamic sources are expanded.
3416 */
3417 switch (str[1]) {
3418 case '@':
3419 return "$(.TARGET)";
3420 case '%':
3421 return "$(.MEMBER)";
3422 case '*':
3423 return "$(.PREFIX)";
3424 case '!':
3425 return "$(.ARCHIVE)";
3426 }
3427 }
3428 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3429 } else {
3430 haveModifier = FALSE;
3431 tstr = str + 1;
3432 }
3433 } else {
3434 Buffer namebuf; /* Holds the variable name */
3435 int depth;
3436 size_t namelen;
3437 char *varname;
3438
3439 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3440
3441 Buf_InitZ(&namebuf, 0);
3442
3443 /*
3444 * Skip to the end character or a colon, whichever comes first.
3445 */
3446 depth = 1;
3447 for (tstr = str + 2; *tstr != '\0'; tstr++) {
3448 /* Track depth so we can spot parse errors. */
3449 if (*tstr == startc)
3450 depth++;
3451 if (*tstr == endc) {
3452 if (--depth == 0)
3453 break;
3454 }
3455 if (depth == 1 && *tstr == ':')
3456 break;
3457 /* A variable inside a variable, expand. */
3458 if (*tstr == '$') {
3459 int rlen;
3460 void *freeIt;
3461 const char *rval = Var_Parse(tstr, ctxt, eflags, &rlen,
3462 &freeIt);
3463 if (rval != NULL)
3464 Buf_AddStr(&namebuf, rval);
3465 free(freeIt);
3466 tstr += rlen - 1;
3467 } else
3468 Buf_AddByte(&namebuf, *tstr);
3469 }
3470 if (*tstr == ':') {
3471 haveModifier = TRUE;
3472 } else if (*tstr == endc) {
3473 haveModifier = FALSE;
3474 } else {
3475 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"",
3476 Buf_GetAllZ(&namebuf, NULL));
3477 /*
3478 * If we never did find the end character, return NULL
3479 * right now, setting the length to be the distance to
3480 * the end of the string, since that's what make does.
3481 */
3482 *lengthPtr = tstr - str;
3483 Buf_Destroy(&namebuf, TRUE);
3484 return var_Error;
3485 }
3486
3487 varname = Buf_GetAllZ(&namebuf, &namelen);
3488
3489 /*
3490 * At this point, varname points into newly allocated memory from
3491 * namebuf, containing only the name of the variable.
3492 *
3493 * start and tstr point into the const string that was pointed
3494 * to by the original value of the str parameter. start points
3495 * to the '$' at the beginning of the string, while tstr points
3496 * to the char just after the end of the variable name -- this
3497 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3498 */
3499
3500 v = VarFind(varname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3501 /*
3502 * Check also for bogus D and F forms of local variables since we're
3503 * in a local context and the name is the right length.
3504 */
3505 if (v == NULL && ctxt != VAR_CMD && ctxt != VAR_GLOBAL &&
3506 namelen == 2 && (varname[1] == 'F' || varname[1] == 'D') &&
3507 strchr("@%?*!<>", varname[0]) != NULL)
3508 {
3509 /*
3510 * Well, it's local -- go look for it.
3511 */
3512 char name[] = { varname[0], '\0' };
3513 v = VarFind(name, ctxt, 0);
3514
3515 if (v != NULL) {
3516 if (varname[1] == 'D') {
3517 extramodifiers = "H:";
3518 } else { /* F */
3519 extramodifiers = "T:";
3520 }
3521 }
3522 }
3523
3524 if (v == NULL) {
3525 dynamic = VarIsDynamic(ctxt, varname, namelen);
3526
3527 if (!haveModifier) {
3528 /*
3529 * No modifiers -- have specification length so we can return
3530 * now.
3531 */
3532 *lengthPtr = tstr - str + 1;
3533 if (dynamic) {
3534 char *pstr = bmake_strndup(str, *lengthPtr);
3535 *freePtr = pstr;
3536 Buf_Destroy(&namebuf, TRUE);
3537 return pstr;
3538 } else {
3539 Buf_Destroy(&namebuf, TRUE);
3540 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3541 }
3542 } else {
3543 /*
3544 * Still need to get to the end of the variable specification,
3545 * so kludge up a Var structure for the modifications
3546 */
3547 v = bmake_malloc(sizeof(Var));
3548 v->name = varname;
3549 Buf_InitZ(&v->val, 1);
3550 v->flags = VAR_JUNK;
3551 Buf_Destroy(&namebuf, FALSE);
3552 }
3553 } else
3554 Buf_Destroy(&namebuf, TRUE);
3555 }
3556
3557 if (v->flags & VAR_IN_USE) {
3558 Fatal("Variable %s is recursive.", v->name);
3559 /*NOTREACHED*/
3560 } else {
3561 v->flags |= VAR_IN_USE;
3562 }
3563
3564 /*
3565 * Before doing any modification, we have to make sure the value
3566 * has been fully expanded. If it looks like recursion might be
3567 * necessary (there's a dollar sign somewhere in the variable's value)
3568 * we just call Var_Subst to do any other substitutions that are
3569 * necessary. Note that the value returned by Var_Subst will have
3570 * been dynamically-allocated, so it will need freeing when we
3571 * return.
3572 */
3573 nstr = Buf_GetAllZ(&v->val, NULL);
3574 if (strchr(nstr, '$') != NULL && (eflags & VARE_WANTRES) != 0) {
3575 nstr = Var_Subst(nstr, ctxt, eflags);
3576 *freePtr = nstr;
3577 }
3578
3579 v->flags &= ~VAR_IN_USE;
3580
3581 if (nstr != NULL && (haveModifier || extramodifiers != NULL)) {
3582 void *extraFree;
3583
3584 extraFree = NULL;
3585 if (extramodifiers != NULL) {
3586 const char *em = extramodifiers;
3587 nstr = ApplyModifiers(&em, nstr, '(', ')',
3588 v, ctxt, eflags, &extraFree);
3589 }
3590
3591 if (haveModifier) {
3592 /* Skip initial colon. */
3593 tstr++;
3594
3595 nstr = ApplyModifiers(&tstr, nstr, startc, endc,
3596 v, ctxt, eflags, freePtr);
3597 free(extraFree);
3598 } else {
3599 *freePtr = extraFree;
3600 }
3601 }
3602 *lengthPtr = tstr - str + (*tstr ? 1 : 0);
3603
3604 if (v->flags & VAR_FROM_ENV) {
3605 Boolean destroy = nstr != Buf_GetAllZ(&v->val, NULL);
3606 if (!destroy) {
3607 /*
3608 * Returning the value unmodified, so tell the caller to free
3609 * the thing.
3610 */
3611 *freePtr = nstr;
3612 }
3613 (void)VarFreeEnv(v, destroy);
3614 } else if (v->flags & VAR_JUNK) {
3615 /*
3616 * Perform any free'ing needed and set *freePtr to NULL so the caller
3617 * doesn't try to free a static pointer.
3618 * If VAR_KEEP is also set then we want to keep str(?) as is.
3619 */
3620 if (!(v->flags & VAR_KEEP)) {
3621 if (*freePtr != NULL) {
3622 free(*freePtr);
3623 *freePtr = NULL;
3624 }
3625 if (dynamic) {
3626 nstr = bmake_strndup(str, *lengthPtr);
3627 *freePtr = nstr;
3628 } else {
3629 nstr = (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3630 }
3631 }
3632 if (nstr != Buf_GetAllZ(&v->val, NULL))
3633 Buf_Destroy(&v->val, TRUE);
3634 free(v->name);
3635 free(v);
3636 }
3637 return nstr;
3638 }
3639
3640 /*-
3641 *-----------------------------------------------------------------------
3642 * Var_Subst --
3643 * Substitute for all variables in the given string in the given context.
3644 * If eflags & VARE_UNDEFERR, Parse_Error will be called when an undefined
3645 * variable is encountered.
3646 *
3647 * Input:
3648 * var Named variable || NULL for all
3649 * str the string which to substitute
3650 * ctxt the context wherein to find variables
3651 * eflags VARE_UNDEFERR if undefineds are an error
3652 * VARE_WANTRES if we actually want the result
3653 * VARE_ASSIGN if we are in a := assignment
3654 *
3655 * Results:
3656 * The resulting string.
3657 *
3658 * Side Effects:
3659 * Any effects from the modifiers, such as ::=, :sh or !cmd!,
3660 * if eflags contains VARE_WANTRES.
3661 *-----------------------------------------------------------------------
3662 */
3663 char *
3664 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags)
3665 {
3666 Buffer buf; /* Buffer for forming things */
3667 Boolean trailingBslash;
3668
3669 /* Set true if an error has already been reported,
3670 * to prevent a plethora of messages when recursing */
3671 static Boolean errorReported;
3672
3673 Buf_InitZ(&buf, 0);
3674 errorReported = FALSE;
3675 trailingBslash = FALSE; /* variable ends in \ */
3676
3677 while (*str) {
3678 if (*str == '\n' && trailingBslash)
3679 Buf_AddByte(&buf, ' ');
3680 if (*str == '$' && str[1] == '$') {
3681 /*
3682 * A dollar sign may be escaped with another dollar sign.
3683 * In such a case, we skip over the escape character and store the
3684 * dollar sign into the buffer directly.
3685 */
3686 if (save_dollars && (eflags & VARE_ASSIGN))
3687 Buf_AddByte(&buf, '$');
3688 Buf_AddByte(&buf, '$');
3689 str += 2;
3690 } else if (*str != '$') {
3691 /*
3692 * Skip as many characters as possible -- either to the end of
3693 * the string or to the next dollar sign (variable invocation).
3694 */
3695 const char *cp;
3696
3697 for (cp = str++; *str != '$' && *str != '\0'; str++)
3698 continue;
3699 Buf_AddBytesBetween(&buf, cp, str);
3700 } else {
3701 int length;
3702 void *freeIt;
3703 const char *val = Var_Parse(str, ctxt, eflags, &length, &freeIt);
3704
3705 /*
3706 * When we come down here, val should either point to the
3707 * value of this variable, suitably modified, or be NULL.
3708 * Length should be the total length of the potential
3709 * variable invocation (from $ to end character...)
3710 */
3711 if (val == var_Error || val == varNoError) {
3712 /*
3713 * If performing old-time variable substitution, skip over
3714 * the variable and continue with the substitution. Otherwise,
3715 * store the dollar sign and advance str so we continue with
3716 * the string...
3717 */
3718 if (oldVars) {
3719 str += length;
3720 } else if ((eflags & VARE_UNDEFERR) || val == var_Error) {
3721 /*
3722 * If variable is undefined, complain and skip the
3723 * variable. The complaint will stop us from doing anything
3724 * when the file is parsed.
3725 */
3726 if (!errorReported) {
3727 Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
3728 length, str);
3729 }
3730 str += length;
3731 errorReported = TRUE;
3732 } else {
3733 Buf_AddByte(&buf, *str);
3734 str += 1;
3735 }
3736 } else {
3737 size_t val_len;
3738
3739 str += length;
3740
3741 val_len = strlen(val);
3742 Buf_AddBytesZ(&buf, val, val_len);
3743 trailingBslash = val_len > 0 && val[val_len - 1] == '\\';
3744 }
3745 free(freeIt);
3746 freeIt = NULL;
3747 }
3748 }
3749
3750 return Buf_DestroyCompact(&buf);
3751 }
3752
3753 /* Initialize the module. */
3754 void
3755 Var_Init(void)
3756 {
3757 VAR_INTERNAL = Targ_NewGN("Internal");
3758 VAR_GLOBAL = Targ_NewGN("Global");
3759 VAR_CMD = Targ_NewGN("Command");
3760 }
3761
3762
3763 void
3764 Var_End(void)
3765 {
3766 Var_Stats();
3767 }
3768
3769 void
3770 Var_Stats(void)
3771 {
3772 Hash_DebugStats(&VAR_GLOBAL->context, "VAR_GLOBAL");
3773 }
3774
3775
3776 /****************** PRINT DEBUGGING INFO *****************/
3777 static void
3778 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
3779 {
3780 Var *v = (Var *)vp;
3781 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAllZ(&v->val, NULL));
3782 }
3783
3784 /* Print all variables in a context, unordered. */
3785 void
3786 Var_Dump(GNode *ctxt)
3787 {
3788 Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
3789 }
3790