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