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