var.c revision 1.446 1 /* $NetBSD: var.c,v 1.446 2020/08/10 20:07:14 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.446 2020/08/10 20:07:14 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.446 2020/08/10 20:07:14 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 if (rval != NULL && *rval &&
3030 (c = p[rlen]) != '\0' && c != ':' && c != st.endc) {
3031 free(freeIt);
3032 goto apply_mods;
3033 }
3034
3035 VAR_DEBUG("Indirect modifier \"%s\" from \"%.*s\"\n", rval, rlen, p);
3036
3037 p += rlen;
3038
3039 if (rval != NULL && *rval) {
3040 const char *rval_pp = rval;
3041 st.val = ApplyModifiers(&rval_pp, st.val, '\0', '\0', v,
3042 ctxt, eflags, freePtr);
3043 if (st.val == var_Error
3044 || (st.val == varNoError && !(st.eflags & VARE_UNDEFERR))
3045 || *rval_pp != '\0') {
3046 free(freeIt);
3047 goto out; /* error already reported */
3048 }
3049 }
3050 free(freeIt);
3051 if (*p == ':')
3052 p++;
3053 else if (*p == '\0' && endc != '\0') {
3054 Error("Unclosed variable specification after complex "
3055 "modifier (expecting '%c') for %s", st.endc, st.v->name);
3056 goto out;
3057 }
3058 continue;
3059 }
3060 apply_mods:
3061 st.newVal = var_Error; /* default value, in case of errors */
3062 res = AMR_BAD; /* just a safe fallback */
3063 mod = p;
3064
3065 if (DEBUG(VAR)) {
3066 char eflags_str[VarEvalFlags_ToStringSize];
3067 char vflags_str[VarFlags_ToStringSize];
3068 Boolean is_single_char = mod[0] != '\0' &&
3069 (mod[1] == endc || mod[1] == ':');
3070
3071 /* At this point, only the first character of the modifier can
3072 * be used since the end of the modifier is not yet known. */
3073 VAR_DEBUG("Applying ${%s:%c%s} to \"%s\" "
3074 "(eflags = %s, vflags = %s)\n",
3075 st.v->name, mod[0], is_single_char ? "" : "...", st.val,
3076 Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
3077 VarEvalFlags_ToStringSpecs),
3078 Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
3079 VarFlags_ToStringSpecs));
3080 }
3081
3082 switch (*mod) {
3083 case ':':
3084 res = ApplyModifier_Assign(&p, &st);
3085 break;
3086 case '@':
3087 res = ApplyModifier_Loop(&p, &st);
3088 break;
3089 case '_':
3090 res = ApplyModifier_Remember(&p, &st);
3091 break;
3092 case 'D':
3093 case 'U':
3094 res = ApplyModifier_Defined(&p, &st);
3095 break;
3096 case 'L':
3097 if (st.v->flags & VAR_JUNK)
3098 st.v->flags |= VAR_KEEP;
3099 st.newVal = bmake_strdup(st.v->name);
3100 p++;
3101 res = AMR_OK;
3102 break;
3103 case 'P':
3104 res = ApplyModifier_Path(&p, &st);
3105 break;
3106 case '!':
3107 res = ApplyModifier_Exclam(&p, &st);
3108 break;
3109 case '[':
3110 res = ApplyModifier_Words(&p, &st);
3111 break;
3112 case 'g':
3113 res = ApplyModifier_Gmtime(&p, &st);
3114 break;
3115 case 'h':
3116 res = ApplyModifier_Hash(&p, &st);
3117 break;
3118 case 'l':
3119 res = ApplyModifier_Localtime(&p, &st);
3120 break;
3121 case 't':
3122 res = ApplyModifier_To(&p, &st);
3123 break;
3124 case 'N':
3125 case 'M':
3126 res = ApplyModifier_Match(&p, &st);
3127 break;
3128 case 'S':
3129 res = ApplyModifier_Subst(&p, &st);
3130 break;
3131 case '?':
3132 res = ApplyModifier_IfElse(&p, &st);
3133 break;
3134 #ifndef NO_REGEX
3135 case 'C':
3136 res = ApplyModifier_Regex(&p, &st);
3137 break;
3138 #endif
3139 case 'q':
3140 case 'Q':
3141 if (p[1] == st.endc || p[1] == ':') {
3142 st.newVal = VarQuote(st.val, *mod == 'q');
3143 p++;
3144 res = AMR_OK;
3145 } else
3146 res = AMR_UNKNOWN;
3147 break;
3148 case 'T':
3149 res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Tail);
3150 break;
3151 case 'H':
3152 res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Head);
3153 break;
3154 case 'E':
3155 res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Suffix);
3156 break;
3157 case 'R':
3158 res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Root);
3159 break;
3160 case 'r':
3161 res = ApplyModifier_Range(&p, &st);
3162 break;
3163 case 'O':
3164 res = ApplyModifier_Order(&p, &st);
3165 break;
3166 case 'u':
3167 if (p[1] == st.endc || p[1] == ':') {
3168 st.newVal = VarUniq(st.val);
3169 p++;
3170 res = AMR_OK;
3171 } else
3172 res = AMR_UNKNOWN;
3173 break;
3174 #ifdef SUNSHCMD
3175 case 's':
3176 if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
3177 if (st.eflags & VARE_WANTRES) {
3178 const char *errfmt;
3179 st.newVal = Cmd_Exec(st.val, &errfmt);
3180 if (errfmt)
3181 Error(errfmt, st.val);
3182 } else
3183 st.newVal = varNoError;
3184 p += 2;
3185 res = AMR_OK;
3186 } else
3187 res = AMR_UNKNOWN;
3188 break;
3189 #endif
3190 default:
3191 res = AMR_UNKNOWN;
3192 }
3193
3194 #ifdef SYSVVARSUB
3195 if (res == AMR_UNKNOWN) {
3196 assert(p == mod);
3197 res = ApplyModifier_SysV(&p, &st);
3198 }
3199 #endif
3200
3201 if (res == AMR_UNKNOWN) {
3202 Error("Unknown modifier '%c'", *mod);
3203 for (p++; *p != ':' && *p != st.endc && *p != '\0'; p++)
3204 continue;
3205 st.newVal = var_Error;
3206 }
3207 if (res == AMR_CLEANUP)
3208 goto cleanup;
3209 if (res == AMR_BAD)
3210 goto bad_modifier;
3211
3212 if (DEBUG(VAR)) {
3213 char eflags_str[VarEvalFlags_ToStringSize];
3214 char vflags_str[VarFlags_ToStringSize];
3215 const char *q = st.newVal == var_Error ? "" : "\"";
3216 const char *newVal = st.newVal == var_Error ? "error" : st.newVal;
3217
3218 VAR_DEBUG("Result of ${%s:%.*s} is %s%s%s "
3219 "(eflags = %s, vflags = %s)\n",
3220 st.v->name, (int)(p - mod), mod, q, newVal, q,
3221 Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
3222 VarEvalFlags_ToStringSpecs),
3223 Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
3224 VarFlags_ToStringSpecs));
3225 }
3226
3227 if (st.newVal != st.val) {
3228 if (*freePtr) {
3229 free(st.val);
3230 *freePtr = NULL;
3231 }
3232 st.val = st.newVal;
3233 if (st.val != var_Error && st.val != varNoError) {
3234 *freePtr = st.val;
3235 }
3236 }
3237 if (*p == '\0' && st.endc != '\0') {
3238 Error("Unclosed variable specification (expecting '%c') "
3239 "for \"%s\" (value \"%s\") modifier %c",
3240 st.endc, st.v->name, st.val, *mod);
3241 } else if (*p == ':') {
3242 p++;
3243 }
3244 mod = p;
3245 }
3246 out:
3247 *pp = p;
3248 return st.val;
3249
3250 bad_modifier:
3251 Error("Bad modifier `:%.*s' for %s",
3252 (int)strcspn(mod, ":)}"), mod, st.v->name);
3253
3254 cleanup:
3255 *pp = p;
3256 if (st.missing_delim != '\0')
3257 Error("Unfinished modifier for %s ('%c' missing)",
3258 st.v->name, st.missing_delim);
3259 free(*freePtr);
3260 *freePtr = NULL;
3261 return var_Error;
3262 }
3263
3264 static Boolean
3265 VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)
3266 {
3267 if ((namelen == 1 ||
3268 (namelen == 2 && (varname[1] == 'F' || varname[1] == 'D'))) &&
3269 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3270 {
3271 /*
3272 * If substituting a local variable in a non-local context,
3273 * assume it's for dynamic source stuff. We have to handle
3274 * this specially and return the longhand for the variable
3275 * with the dollar sign escaped so it makes it back to the
3276 * caller. Only four of the local variables are treated
3277 * specially as they are the only four that will be set
3278 * when dynamic sources are expanded.
3279 */
3280 switch (varname[0]) {
3281 case '@':
3282 case '%':
3283 case '*':
3284 case '!':
3285 return TRUE;
3286 }
3287 return FALSE;
3288 }
3289
3290 if ((namelen == 7 || namelen == 8) && varname[0] == '.' &&
3291 isupper((unsigned char)varname[1]) &&
3292 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3293 {
3294 return strcmp(varname, ".TARGET") == 0 ||
3295 strcmp(varname, ".ARCHIVE") == 0 ||
3296 strcmp(varname, ".PREFIX") == 0 ||
3297 strcmp(varname, ".MEMBER") == 0;
3298 }
3299
3300 return FALSE;
3301 }
3302
3303 /*-
3304 *-----------------------------------------------------------------------
3305 * Var_Parse --
3306 * Given the start of a variable invocation (such as $v, $(VAR),
3307 * ${VAR:Mpattern}), extract the variable name, possibly some
3308 * modifiers and find its value by applying the modifiers to the
3309 * original value.
3310 *
3311 * Input:
3312 * str The string to parse
3313 * ctxt The context for the variable
3314 * flags VARE_UNDEFERR if undefineds are an error
3315 * VARE_WANTRES if we actually want the result
3316 * VARE_ASSIGN if we are in a := assignment
3317 * lengthPtr OUT: The length of the specification
3318 * freePtr OUT: Non-NULL if caller should free *freePtr
3319 *
3320 * Results:
3321 * The value of the variable expression or var_Error if the
3322 * specification is invalid. The length of the specification is
3323 * placed in *lengthPtr (for invalid specifications, this is just
3324 * 2...?).
3325 * If *freePtr is non-NULL then it's a pointer that the caller
3326 * should pass to free() to free memory used by the result.
3327 *
3328 * Side Effects:
3329 * Any effects from the modifiers, such as :!cmd! or ::=value.
3330 *-----------------------------------------------------------------------
3331 */
3332 /* coverity[+alloc : arg-*4] */
3333 const char *
3334 Var_Parse(const char * const str, GNode *ctxt, VarEvalFlags eflags,
3335 int *lengthPtr, void **freePtr)
3336 {
3337 const char *tstr; /* Pointer into str */
3338 Boolean haveModifier; /* TRUE if have modifiers for the variable */
3339 char startc; /* Starting character if variable in parens
3340 * or braces */
3341 char endc; /* Ending character if variable in parens
3342 * or braces */
3343 Boolean dynamic; /* TRUE if the variable is local and we're
3344 * expanding it in a non-local context. This
3345 * is done to support dynamic sources. The
3346 * result is just the invocation, unaltered */
3347 const char *extramodifiers;
3348 Var *v;
3349 char *nstr;
3350 char eflags_str[VarEvalFlags_ToStringSize];
3351
3352 VAR_DEBUG("%s: %s with %s\n", __func__, str,
3353 Enum_ToString(eflags_str, sizeof eflags_str, eflags,
3354 VarEvalFlags_ToStringSpecs));
3355
3356 *freePtr = NULL;
3357 extramodifiers = NULL; /* extra modifiers to apply first */
3358 dynamic = FALSE;
3359
3360 startc = str[1];
3361 if (startc != PROPEN && startc != BROPEN) {
3362 char name[2];
3363
3364 /*
3365 * If it's not bounded by braces of some sort, life is much simpler.
3366 * We just need to check for the first character and return the
3367 * value if it exists.
3368 */
3369
3370 /* Error out some really stupid names */
3371 if (startc == '\0' || strchr(")}:$", startc)) {
3372 *lengthPtr = 1;
3373 return var_Error;
3374 }
3375
3376 name[0] = startc;
3377 name[1] = '\0';
3378 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3379 if (v == NULL) {
3380 *lengthPtr = 2;
3381
3382 if (ctxt == VAR_CMD || ctxt == VAR_GLOBAL) {
3383 /*
3384 * If substituting a local variable in a non-local context,
3385 * assume it's for dynamic source stuff. We have to handle
3386 * this specially and return the longhand for the variable
3387 * with the dollar sign escaped so it makes it back to the
3388 * caller. Only four of the local variables are treated
3389 * specially as they are the only four that will be set
3390 * when dynamic sources are expanded.
3391 */
3392 switch (str[1]) {
3393 case '@':
3394 return "$(.TARGET)";
3395 case '%':
3396 return "$(.MEMBER)";
3397 case '*':
3398 return "$(.PREFIX)";
3399 case '!':
3400 return "$(.ARCHIVE)";
3401 }
3402 }
3403 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3404 } else {
3405 haveModifier = FALSE;
3406 tstr = str + 1;
3407 }
3408 } else {
3409 Buffer namebuf; /* Holds the variable name */
3410 int depth;
3411 size_t namelen;
3412 char *varname;
3413
3414 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3415
3416 Buf_Init(&namebuf, 0);
3417
3418 /*
3419 * Skip to the end character or a colon, whichever comes first.
3420 */
3421 depth = 1;
3422 for (tstr = str + 2; *tstr != '\0'; tstr++) {
3423 /* Track depth so we can spot parse errors. */
3424 if (*tstr == startc)
3425 depth++;
3426 if (*tstr == endc) {
3427 if (--depth == 0)
3428 break;
3429 }
3430 if (*tstr == ':' && depth == 1)
3431 break;
3432 /* A variable inside a variable, expand. */
3433 if (*tstr == '$') {
3434 int rlen;
3435 void *freeIt;
3436 const char *rval = Var_Parse(tstr, ctxt, eflags, &rlen,
3437 &freeIt);
3438 if (rval != NULL)
3439 Buf_AddStr(&namebuf, rval);
3440 free(freeIt);
3441 tstr += rlen - 1;
3442 } else
3443 Buf_AddByte(&namebuf, *tstr);
3444 }
3445 if (*tstr == ':') {
3446 haveModifier = TRUE;
3447 } else if (*tstr == endc) {
3448 haveModifier = FALSE;
3449 } else {
3450 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"",
3451 Buf_GetAll(&namebuf, NULL));
3452 /*
3453 * If we never did find the end character, return NULL
3454 * right now, setting the length to be the distance to
3455 * the end of the string, since that's what make does.
3456 */
3457 *lengthPtr = tstr - str;
3458 Buf_Destroy(&namebuf, TRUE);
3459 return var_Error;
3460 }
3461
3462 varname = Buf_GetAll(&namebuf, &namelen);
3463
3464 /*
3465 * At this point, varname points into newly allocated memory from
3466 * namebuf, containing only the name of the variable.
3467 *
3468 * start and tstr point into the const string that was pointed
3469 * to by the original value of the str parameter. start points
3470 * to the '$' at the beginning of the string, while tstr points
3471 * to the char just after the end of the variable name -- this
3472 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3473 */
3474
3475 v = VarFind(varname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3476 /*
3477 * Check also for bogus D and F forms of local variables since we're
3478 * in a local context and the name is the right length.
3479 */
3480 if (v == NULL && ctxt != VAR_CMD && ctxt != VAR_GLOBAL &&
3481 namelen == 2 && (varname[1] == 'F' || varname[1] == 'D') &&
3482 strchr("@%?*!<>", varname[0]) != NULL)
3483 {
3484 /*
3485 * Well, it's local -- go look for it.
3486 */
3487 char name[] = { varname[0], '\0' };
3488 v = VarFind(name, ctxt, 0);
3489
3490 if (v != NULL) {
3491 if (varname[1] == 'D') {
3492 extramodifiers = "H:";
3493 } else { /* F */
3494 extramodifiers = "T:";
3495 }
3496 }
3497 }
3498
3499 if (v == NULL) {
3500 dynamic = VarIsDynamic(ctxt, varname, namelen);
3501
3502 if (!haveModifier) {
3503 /*
3504 * No modifiers -- have specification length so we can return
3505 * now.
3506 */
3507 *lengthPtr = tstr - str + 1;
3508 if (dynamic) {
3509 char *pstr = bmake_strndup(str, *lengthPtr);
3510 *freePtr = pstr;
3511 Buf_Destroy(&namebuf, TRUE);
3512 return pstr;
3513 } else {
3514 Buf_Destroy(&namebuf, TRUE);
3515 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3516 }
3517 } else {
3518 /*
3519 * Still need to get to the end of the variable specification,
3520 * so kludge up a Var structure for the modifications
3521 */
3522 v = bmake_malloc(sizeof(Var));
3523 v->name = varname;
3524 Buf_Init(&v->val, 1);
3525 v->flags = VAR_JUNK;
3526 Buf_Destroy(&namebuf, FALSE);
3527 }
3528 } else
3529 Buf_Destroy(&namebuf, TRUE);
3530 }
3531
3532 if (v->flags & VAR_IN_USE) {
3533 Fatal("Variable %s is recursive.", v->name);
3534 /*NOTREACHED*/
3535 } else {
3536 v->flags |= VAR_IN_USE;
3537 }
3538
3539 /*
3540 * Before doing any modification, we have to make sure the value
3541 * has been fully expanded. If it looks like recursion might be
3542 * necessary (there's a dollar sign somewhere in the variable's value)
3543 * we just call Var_Subst to do any other substitutions that are
3544 * necessary. Note that the value returned by Var_Subst will have
3545 * been dynamically-allocated, so it will need freeing when we
3546 * return.
3547 */
3548 nstr = Buf_GetAll(&v->val, NULL);
3549 if (strchr(nstr, '$') != NULL && (eflags & VARE_WANTRES) != 0) {
3550 nstr = Var_Subst(nstr, ctxt, eflags);
3551 *freePtr = nstr;
3552 }
3553
3554 v->flags &= ~VAR_IN_USE;
3555
3556 if (nstr != NULL && (haveModifier || extramodifiers != NULL)) {
3557 void *extraFree;
3558
3559 extraFree = NULL;
3560 if (extramodifiers != NULL) {
3561 const char *em = extramodifiers;
3562 nstr = ApplyModifiers(&em, nstr, '(', ')',
3563 v, ctxt, eflags, &extraFree);
3564 }
3565
3566 if (haveModifier) {
3567 /* Skip initial colon. */
3568 tstr++;
3569
3570 nstr = ApplyModifiers(&tstr, nstr, startc, endc,
3571 v, ctxt, eflags, freePtr);
3572 free(extraFree);
3573 } else {
3574 *freePtr = extraFree;
3575 }
3576 }
3577
3578 /* Skip past endc if possible. */
3579 *lengthPtr = tstr + (*tstr ? 1 : 0) - str;
3580
3581 if (v->flags & VAR_FROM_ENV) {
3582 Boolean destroy = nstr != Buf_GetAll(&v->val, NULL);
3583 if (!destroy) {
3584 /*
3585 * Returning the value unmodified, so tell the caller to free
3586 * the thing.
3587 */
3588 *freePtr = nstr;
3589 }
3590 (void)VarFreeEnv(v, destroy);
3591 } else if (v->flags & VAR_JUNK) {
3592 /*
3593 * Perform any freeing needed and set *freePtr to NULL so the caller
3594 * doesn't try to free a static pointer.
3595 * If VAR_KEEP is also set then we want to keep str(?) as is.
3596 */
3597 if (!(v->flags & VAR_KEEP)) {
3598 if (*freePtr != NULL) {
3599 free(*freePtr);
3600 *freePtr = NULL;
3601 }
3602 if (dynamic) {
3603 nstr = bmake_strndup(str, *lengthPtr);
3604 *freePtr = nstr;
3605 } else {
3606 nstr = (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3607 }
3608 }
3609 if (nstr != Buf_GetAll(&v->val, NULL))
3610 Buf_Destroy(&v->val, TRUE);
3611 free(v->name);
3612 free(v);
3613 }
3614 return nstr;
3615 }
3616
3617 /*-
3618 *-----------------------------------------------------------------------
3619 * Var_Subst --
3620 * Substitute for all variables in the given string in the given context.
3621 * If eflags & VARE_UNDEFERR, Parse_Error will be called when an undefined
3622 * variable is encountered.
3623 *
3624 * Input:
3625 * var Named variable || NULL for all
3626 * str the string which to substitute
3627 * ctxt the context wherein to find variables
3628 * eflags VARE_UNDEFERR if undefineds are an error
3629 * VARE_WANTRES if we actually want the result
3630 * VARE_ASSIGN if we are in a := assignment
3631 *
3632 * Results:
3633 * The resulting string.
3634 *
3635 * Side Effects:
3636 * Any effects from the modifiers, such as ::=, :sh or !cmd!,
3637 * if eflags contains VARE_WANTRES.
3638 *-----------------------------------------------------------------------
3639 */
3640 char *
3641 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags)
3642 {
3643 Buffer buf; /* Buffer for forming things */
3644 Boolean trailingBslash;
3645
3646 /* Set true if an error has already been reported,
3647 * to prevent a plethora of messages when recursing */
3648 static Boolean errorReported;
3649
3650 Buf_Init(&buf, 0);
3651 errorReported = FALSE;
3652 trailingBslash = FALSE; /* variable ends in \ */
3653
3654 while (*str) {
3655 if (*str == '\n' && trailingBslash)
3656 Buf_AddByte(&buf, ' ');
3657
3658 if (*str == '$' && str[1] == '$') {
3659 /*
3660 * A dollar sign may be escaped with another dollar sign.
3661 * In such a case, we skip over the escape character and store the
3662 * dollar sign into the buffer directly.
3663 */
3664 if (save_dollars && (eflags & VARE_ASSIGN))
3665 Buf_AddByte(&buf, '$');
3666 Buf_AddByte(&buf, '$');
3667 str += 2;
3668 } else if (*str != '$') {
3669 /*
3670 * Skip as many characters as possible -- either to the end of
3671 * the string or to the next dollar sign (variable invocation).
3672 */
3673 const char *cp;
3674
3675 for (cp = str++; *str != '$' && *str != '\0'; str++)
3676 continue;
3677 Buf_AddBytesBetween(&buf, cp, str);
3678 } else {
3679 int length;
3680 void *freeIt;
3681 const char *val = Var_Parse(str, ctxt, eflags, &length, &freeIt);
3682
3683 /*
3684 * When we come down here, val should either point to the
3685 * value of this variable, suitably modified, or be NULL.
3686 * Length should be the total length of the potential
3687 * variable invocation (from $ to end character...)
3688 */
3689 if (val == var_Error || val == varNoError) {
3690 /*
3691 * If performing old-time variable substitution, skip over
3692 * the variable and continue with the substitution. Otherwise,
3693 * store the dollar sign and advance str so we continue with
3694 * the string...
3695 */
3696 if (oldVars) {
3697 str += length;
3698 } else if ((eflags & VARE_UNDEFERR) || val == var_Error) {
3699 /*
3700 * If variable is undefined, complain and skip the
3701 * variable. The complaint will stop us from doing anything
3702 * when the file is parsed.
3703 */
3704 if (!errorReported) {
3705 Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
3706 length, str);
3707 }
3708 str += length;
3709 errorReported = TRUE;
3710 } else {
3711 Buf_AddByte(&buf, *str);
3712 str += 1;
3713 }
3714 } else {
3715 size_t val_len;
3716
3717 str += length;
3718
3719 val_len = strlen(val);
3720 Buf_AddBytes(&buf, val, val_len);
3721 trailingBslash = val_len > 0 && val[val_len - 1] == '\\';
3722 }
3723 free(freeIt);
3724 freeIt = NULL;
3725 }
3726 }
3727
3728 return Buf_DestroyCompact(&buf);
3729 }
3730
3731 /* Initialize the module. */
3732 void
3733 Var_Init(void)
3734 {
3735 VAR_INTERNAL = Targ_NewGN("Internal");
3736 VAR_GLOBAL = Targ_NewGN("Global");
3737 VAR_CMD = Targ_NewGN("Command");
3738 }
3739
3740
3741 void
3742 Var_End(void)
3743 {
3744 Var_Stats();
3745 }
3746
3747 void
3748 Var_Stats(void)
3749 {
3750 Hash_DebugStats(&VAR_GLOBAL->context, "VAR_GLOBAL");
3751 }
3752
3753
3754 /****************** PRINT DEBUGGING INFO *****************/
3755 static void
3756 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
3757 {
3758 Var *v = (Var *)vp;
3759 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
3760 }
3761
3762 /* Print all variables in a context, unordered. */
3763 void
3764 Var_Dump(GNode *ctxt)
3765 {
3766 Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
3767 }
3768