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