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