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