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