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