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