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