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