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