Add a sysctl to control 8254 bios overwrite warnings. Default is on.
[dragonfly.git] / usr.bin / make / var.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1989 by Berkeley Softworks
5 * 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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 * @(#)var.c 8.3 (Berkeley) 3/19/94
39 * $FreeBSD: src/usr.bin/make/var.c,v 1.16.2.3 2002/02/27 14:18:57 cjc Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.52 2005/01/30 07:20:59 okumoto Exp $
41 */
42
43/*-
44 * var.c --
45 * Variable-handling functions
46 *
47 * Interface:
48 * Var_Set Set the value of a variable in the given
49 * context. The variable is created if it doesn't
50 * yet exist. The value and variable name need not
51 * be preserved.
52 *
53 * Var_Append Append more characters to an existing variable
54 * in the given context. The variable needn't
55 * exist already -- it will be created if it doesn't.
56 * A space is placed between the old value and the
57 * new one.
58 *
59 * Var_Exists See if a variable exists.
60 *
61 * Var_Value Return the value of a variable in a context or
62 * NULL if the variable is undefined.
63 *
64 * Var_Subst Substitute named variable, or all variables if
65 * NULL in a string using
66 * the given context as the top-most one. If the
67 * third argument is non-zero, Parse_Error is
68 * called if any variables are undefined.
69 *
70 * Var_Parse Parse a variable expansion from a string and
71 * return the result and the number of characters
72 * consumed.
73 *
74 * Var_Delete Delete a variable in a context.
75 *
76 * Var_Init Initialize this module.
77 *
78 * Debugging:
79 * Var_Dump Print out all variables defined in the given
80 * context.
81 *
82 * XXX: There's a lot of duplication in these functions.
83 */
84
85#include <ctype.h>
86#include <stdlib.h>
87#include <string.h>
88
89#include "buf.h"
90#include "config.h"
91#include "globals.h"
92#include "GNode.h"
93#include "make.h"
94#include "nonints.h"
95#include "parse.h"
96#include "str.h"
97#include "targ.h"
98#include "util.h"
99#include "var.h"
100
101/*
102 * This is a harmless return value for Var_Parse that can be used by Var_Subst
103 * to determine if there was an error in parsing -- easier than returning
104 * a flag, as things outside this module don't give a hoot.
105 */
106char var_Error[] = "";
107
108/*
109 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
110 * set false. Why not just use a constant? Well, gcc likes to condense
111 * identical string instances...
112 */
113static char varNoError[] = "";
114
115/*
116 * Internally, variables are contained in four different contexts.
117 * 1) the environment. They may not be changed. If an environment
118 * variable is appended-to, the result is placed in the global
119 * context.
120 * 2) the global context. Variables set in the Makefile are located in
121 * the global context. It is the penultimate context searched when
122 * substituting.
123 * 3) the command-line context. All variables set on the command line
124 * are placed in this context. They are UNALTERABLE once placed here.
125 * 4) the local context. Each target has associated with it a context
126 * list. On this list are located the structures describing such
127 * local variables as $(@) and $(*)
128 * The four contexts are searched in the reverse order from which they are
129 * listed.
130 */
131GNode *VAR_GLOBAL; /* variables from the makefile */
132GNode *VAR_CMD; /* variables defined on the command-line */
133
134#define FIND_CMD 0x1 /* look in VAR_CMD when searching */
135#define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
136#define FIND_ENV 0x4 /* look in the environment also */
137
138#define OPEN_PAREN '('
139#define CLOSE_PAREN ')'
140#define OPEN_BRACKET '{'
141#define CLOSE_BRACKET '}'
142
143static char *VarPossiblyExpand(const char *, GNode *);
144static Var *VarFind(const char *, GNode *, int);
145static void VarAdd(const char *, const char *, GNode *);
146static Var *VarCreate(const char [], const char [], int);
147static void VarDestroy(Var *, Boolean);
148static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
149 VarPattern *);
150static char *VarModify(char *,
151 Boolean (*)(const char *, Boolean, Buffer *, void *),
152 void *);
153static int VarPrintVar(void *, void *);
154
155/*-
156 *-----------------------------------------------------------------------
157 * VarCmp --
158 * See if the given variable matches the named one. Called from
159 * Lst_Find when searching for a variable of a given name.
160 *
161 * Results:
162 * 0 if they match. non-zero otherwise.
163 *
164 * Side Effects:
165 * none
166 *-----------------------------------------------------------------------
167 */
168static int
169VarCmp(const void *v, const void *name)
170{
171 return (strcmp(name, ((const Var *)v)->name));
172}
173
174/*-
175 *-----------------------------------------------------------------------
176 * VarPossiblyExpand --
177 * Expand a variable name's embedded variables in the given context.
178 *
179 * Results:
180 * The contents of name, possibly expanded.
181 *-----------------------------------------------------------------------
182 */
183static char *
184VarPossiblyExpand(const char *name, GNode *ctxt)
185{
186 if (strchr(name, '$') != NULL)
187 return Var_Subst(NULL, name, ctxt, 0);
188 else
189 return estrdup(name);
190}
191
192/*-
193 *-----------------------------------------------------------------------
194 * VarFind --
195 * Find the given variable in the given context and any other contexts
196 * indicated.
197 *
198 * Flags:
199 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
200 * FIND_CMD set means to look in the VAR_CMD context too
201 * FIND_ENV set means to look in the environment
202 *
203 * Results:
204 * A pointer to the structure describing the desired variable or
205 * NULL if the variable does not exist.
206 *
207 * Side Effects:
208 * None
209 *-----------------------------------------------------------------------
210 */
211static Var *
212VarFind(const char *name, GNode *ctxt, int flags)
213{
214 Boolean localCheckEnvFirst;
215 LstNode *var;
216 Var *v;
217
218 /*
219 * If the variable name begins with a '.', it could very well be one of
220 * the local ones. We check the name against all the local variables
221 * and substitute the short version in for 'name' if it matches one of
222 * them.
223 */
224 if (name[0] == '.' && isupper((unsigned char)name[1]))
225 switch (name[1]) {
226 case 'A':
227 if (!strcmp(name, ".ALLSRC"))
228 name = ALLSRC;
229 if (!strcmp(name, ".ARCHIVE"))
230 name = ARCHIVE;
231 break;
232 case 'I':
233 if (!strcmp(name, ".IMPSRC"))
234 name = IMPSRC;
235 break;
236 case 'M':
237 if (!strcmp(name, ".MEMBER"))
238 name = MEMBER;
239 break;
240 case 'O':
241 if (!strcmp(name, ".OODATE"))
242 name = OODATE;
243 break;
244 case 'P':
245 if (!strcmp(name, ".PREFIX"))
246 name = PREFIX;
247 break;
248 case 'T':
249 if (!strcmp(name, ".TARGET"))
250 name = TARGET;
251 break;
252 }
253
254 /*
255 * Note whether this is one of the specific variables we were told through
256 * the -E flag to use environment-variable-override for.
257 */
258 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
259 localCheckEnvFirst = TRUE;
260 } else {
261 localCheckEnvFirst = FALSE;
262 }
263
264 /*
265 * First look for the variable in the given context. If it's not there,
266 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
267 * depending on the FIND_* flags in 'flags'
268 */
269 var = Lst_Find(&ctxt->context, name, VarCmp);
270
271 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
272 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
273 }
274 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
275 !checkEnvFirst && !localCheckEnvFirst)
276 {
277 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
278 }
279 if ((var == NULL) && (flags & FIND_ENV)) {
280 char *env;
281
282 if ((env = getenv(name)) != NULL) {
283 v = VarCreate(name, env, VAR_FROM_ENV);
284
285 return (v);
286 } else if ((checkEnvFirst || localCheckEnvFirst) &&
287 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
288 {
289 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
290 if (var == NULL) {
291 return (NULL);
292 } else {
293 return (Lst_Datum(var));
294 }
295 } else {
296 return (NULL);
297 }
298 } else if (var == NULL) {
299 return (NULL);
300 } else {
301 return (Lst_Datum(var));
302 }
303}
304
305/*-
306 *-----------------------------------------------------------------------
307 * VarAdd --
308 * Add a new variable of name name and value val to the given context.
309 *
310 * Results:
311 * None
312 *
313 * Side Effects:
314 * The new variable is placed at the front of the given context
315 * The name and val arguments are duplicated so they may
316 * safely be freed.
317 *-----------------------------------------------------------------------
318 */
319static void
320VarAdd(const char *name, const char *val, GNode *ctxt)
321{
322 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
323
324 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
325}
326
327/*
328 * Create a Var object.
329 *
330 * @param name Name of variable.
331 * @param value Value of variable.
332 * @param flags Flags set on variable.
333 */
334static Var *
335VarCreate(const char name[], const char value[], int flags)
336{
337 Var *v;
338
339 v = emalloc(sizeof(Var));
340 v->name = estrdup(name);
341 v->val = Buf_Init(0);
342 v->flags = flags;
343
344 if (value != NULL) {
345 Buf_Append(v->val, value);
346 }
347 return (v);
348}
349
350/*
351 * Destroy a Var object.
352 *
353 * @param v Object to destroy.
354 * @param f true if internal buffer in Buffer object is to be
355 * removed.
356 */
357static void
358VarDestroy(Var *v, Boolean f)
359{
360 Buf_Destroy(v->val, f);
361 free(v->name);
362 free(v);
363}
364
365/*-
366 *-----------------------------------------------------------------------
367 * Var_Delete --
368 * Remove a variable from a context.
369 *
370 * Results:
371 * None.
372 *
373 * Side Effects:
374 * The Var structure is removed and freed.
375 *
376 *-----------------------------------------------------------------------
377 */
378void
379Var_Delete(char *name, GNode *ctxt)
380{
381 LstNode *ln;
382
383 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
384 ln = Lst_Find(&ctxt->context, name, VarCmp);
385 if (ln != NULL) {
386 VarDestroy(Lst_Datum(ln), TRUE);
387 Lst_Remove(&ctxt->context, ln);
388 }
389}
390
391/*-
392 *-----------------------------------------------------------------------
393 * Var_Set --
394 * Set the variable name to the value val in the given context.
395 *
396 * Results:
397 * None.
398 *
399 * Side Effects:
400 * If the variable doesn't yet exist, a new record is created for it.
401 * Else the old value is freed and the new one stuck in its place
402 *
403 * Notes:
404 * The variable is searched for only in its context before being
405 * created in that context. I.e. if the context is VAR_GLOBAL,
406 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
407 * VAR_CMD->context is searched. This is done to avoid the literally
408 * thousands of unnecessary strcmp's that used to be done to
409 * set, say, $(@) or $(<).
410 *-----------------------------------------------------------------------
411 */
412void
413Var_Set(const char *name, const char *val, GNode *ctxt)
414{
415 Var *v;
416 char *n;
417
418 /*
419 * We only look for a variable in the given context since anything set
420 * here will override anything in a lower context, so there's not much
421 * point in searching them all just to save a bit of memory...
422 */
423 n = VarPossiblyExpand(name, ctxt);
424 v = VarFind(n, ctxt, 0);
425 if (v == NULL) {
426 VarAdd(n, val, ctxt);
427 } else {
428 Buf_Clear(v->val);
429 Buf_Append(v->val, val);
430
431 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
432 }
433 /*
434 * Any variables given on the command line are automatically exported
435 * to the environment (as per POSIX standard)
436 */
437 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
438 setenv(n, val, 1);
439 }
440 free(n);
441}
442
443/*
444 * Var_SetEnv --
445 * Set the VAR_TO_ENV flag on a variable
446 */
447void
448Var_SetEnv(const char *name, GNode *ctxt)
449{
450 Var *v;
451
452 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
453 if (v) {
454 if ((v->flags & VAR_TO_ENV) == 0) {
455 v->flags |= VAR_TO_ENV;
456 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
457 }
458 } else {
459 Error("Cannot set environment flag on non-existant variable %s", name);
460 }
461}
462
463/*-
464 *-----------------------------------------------------------------------
465 * Var_Append --
466 * The variable of the given name has the given value appended to it in
467 * the given context.
468 *
469 * Results:
470 * None
471 *
472 * Side Effects:
473 * If the variable doesn't exist, it is created. Else the strings
474 * are concatenated (with a space in between).
475 *
476 * Notes:
477 * Only if the variable is being sought in the global context is the
478 * environment searched.
479 * XXX: Knows its calling circumstances in that if called with ctxt
480 * an actual target, it will only search that context since only
481 * a local variable could be being appended to. This is actually
482 * a big win and must be tolerated.
483 *-----------------------------------------------------------------------
484 */
485void
486Var_Append(const char *name, const char *val, GNode *ctxt)
487{
488 Var *v;
489 char *n;
490
491 n = VarPossiblyExpand(name, ctxt);
492 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
493 if (v == NULL) {
494 VarAdd(n, val, ctxt);
495 } else {
496 Buf_AddByte(v->val, (Byte)' ');
497 Buf_Append(v->val, val);
498
499 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
500 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
501
502 if (v->flags & VAR_FROM_ENV) {
503 /*
504 * If the original variable came from the environment, we
505 * have to install it in the global context (we could place
506 * it in the environment, but then we should provide a way to
507 * export other variables...)
508 */
509 v->flags &= ~VAR_FROM_ENV;
510 Lst_AtFront(&ctxt->context, v);
511 }
512 }
513 free(n);
514}
515
516/*-
517 *-----------------------------------------------------------------------
518 * Var_Exists --
519 * See if the given variable exists.
520 *
521 * Results:
522 * TRUE if it does, FALSE if it doesn't
523 *
524 * Side Effects:
525 * None.
526 *
527 *-----------------------------------------------------------------------
528 */
529Boolean
530Var_Exists(const char *name, GNode *ctxt)
531{
532 Var *v;
533 char *n;
534
535 n = VarPossiblyExpand(name, ctxt);
536 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
537 free(n);
538
539 if (v == NULL) {
540 return (FALSE);
541 } else if (v->flags & VAR_FROM_ENV) {
542 VarDestroy(v, TRUE);
543 }
544 return (TRUE);
545}
546
547/*-
548 *-----------------------------------------------------------------------
549 * Var_Value --
550 * Return the value of the named variable in the given context
551 *
552 * Results:
553 * The value if the variable exists, NULL if it doesn't
554 *
555 * Side Effects:
556 * None
557 *-----------------------------------------------------------------------
558 */
559char *
560Var_Value(const char *name, GNode *ctxt, char **frp)
561{
562 Var *v;
563 char *n;
564
565 n = VarPossiblyExpand(name, ctxt);
566 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
567 free(n);
568 *frp = NULL;
569 if (v != NULL) {
570 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
571
572 if (v->flags & VAR_FROM_ENV) {
573 VarDestroy(v, FALSE);
574 *frp = p;
575 }
576 return (p);
577 } else {
578 return (NULL);
579 }
580}
581
582/*-
583 *-----------------------------------------------------------------------
584 * VarModify --
585 * Modify each of the words of the passed string using the given
586 * function. Used to implement all modifiers.
587 *
588 * Results:
589 * A string of all the words modified appropriately.
590 *
591 * Side Effects:
592 * None.
593 *
594 *-----------------------------------------------------------------------
595 */
596static char *
597VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer *, void *), void *datum)
598{
599 Buffer *buf; /* Buffer for the new string */
600 Boolean addSpace; /* TRUE if need to add a space to the
601 * buffer before adding the trimmed
602 * word */
603 char **av; /* word list [first word does not count] */
604 int ac, i;
605
606 buf = Buf_Init(0);
607 addSpace = FALSE;
608
609 av = brk_string(str, &ac, FALSE);
610
611 for (i = 1; i < ac; i++)
612 addSpace = (*modProc)(av[i], addSpace, buf, datum);
613
614 Buf_AddByte(buf, '\0');
615 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
616 Buf_Destroy(buf, FALSE);
617 return (str);
618}
619
620/*-
621 *-----------------------------------------------------------------------
622 * VarSortWords --
623 * Sort the words in the string.
624 *
625 * Input:
626 * str String whose words should be sorted
627 * cmp A comparison function to control the ordering
628 *
629 * Results:
630 * A string containing the words sorted
631 *
632 * Side Effects:
633 * None.
634 *
635 *-----------------------------------------------------------------------
636 */
637static char *
638VarSortWords(char *str, int (*cmp)(const void *, const void *))
639{
640 Buffer *buf;
641 char **av;
642 int ac, i;
643
644 buf = Buf_Init(0);
645 av = brk_string(str, &ac, FALSE);
646 qsort(av + 1, ac - 1, sizeof(char *), cmp);
647 for (i = 1; i < ac; i++) {
648 Buf_Append(buf, av[i]);
649 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
650 }
651 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
652 Buf_Destroy(buf, FALSE);
653 return (str);
654}
655
656static int
657SortIncreasing(const void *l, const void *r)
658{
659 return (strcmp(*(const char* const*)l, *(const char* const*)r));
660}
661
662/*-
663 *-----------------------------------------------------------------------
664 * VarGetPattern --
665 * Pass through the tstr looking for 1) escaped delimiters,
666 * '$'s and backslashes (place the escaped character in
667 * uninterpreted) and 2) unescaped $'s that aren't before
668 * the delimiter (expand the variable substitution unless flags
669 * has VAR_NOSUBST set).
670 * Return the expanded string or NULL if the delimiter was missing
671 * If pattern is specified, handle escaped ampersands, and replace
672 * unescaped ampersands with the lhs of the pattern.
673 *
674 * Results:
675 * A string of all the words modified appropriately.
676 * If length is specified, return the string length of the buffer
677 * If flags is specified and the last character of the pattern is a
678 * $ set the VAR_MATCH_END bit of flags.
679 *
680 * Side Effects:
681 * None.
682 *-----------------------------------------------------------------------
683 */
684static char *
685VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
686 size_t *length, VarPattern *pattern)
687{
688 char *cp;
689 Buffer *buf = Buf_Init(0);
690 size_t junk;
691
692 if (length == NULL)
693 length = &junk;
694
695#define IS_A_MATCH(cp, delim) \
696 ((cp[0] == '\\') && ((cp[1] == delim) || \
697 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
698
699 /*
700 * Skim through until the matching delimiter is found;
701 * pick up variable substitutions on the way. Also allow
702 * backslashes to quote the delimiter, $, and \, but don't
703 * touch other backslashes.
704 */
705 for (cp = *tstr; *cp && (*cp != delim); cp++) {
706 if (IS_A_MATCH(cp, delim)) {
707 Buf_AddByte(buf, (Byte)cp[1]);
708 cp++;
709 } else if (*cp == '$') {
710 if (cp[1] == delim) {
711 if (flags == NULL)
712 Buf_AddByte(buf, (Byte)*cp);
713 else
714 /*
715 * Unescaped $ at end of pattern => anchor
716 * pattern at end.
717 */
718 *flags |= VAR_MATCH_END;
719 } else {
720 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
721 char *cp2;
722 size_t len;
723 Boolean freeIt;
724
725 /*
726 * If unescaped dollar sign not before the
727 * delimiter, assume it's a variable
728 * substitution and recurse.
729 */
730 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
731 Buf_Append(buf, cp2);
732 if (freeIt)
733 free(cp2);
734 cp += len - 1;
735 } else {
736 char *cp2 = &cp[1];
737
738 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACKET) {
739 /*
740 * Find the end of this variable reference
741 * and suck it in without further ado.
742 * It will be interperated later.
743 */
744 int have = *cp2;
745 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
746 int depth = 1;
747
748 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
749 if (cp2[-1] != '\\') {
750 if (*cp2 == have)
751 ++depth;
752 if (*cp2 == want)
753 --depth;
754 }
755 }
756 Buf_AppendRange(buf, cp, cp2);
757 cp = --cp2;
758 } else
759 Buf_AddByte(buf, (Byte)*cp);
760 }
761 }
762 }
763 else if (pattern && *cp == '&')
764 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
765 else
766 Buf_AddByte(buf, (Byte)*cp);
767 }
768
769 Buf_AddByte(buf, (Byte)'\0');
770
771 if (*cp != delim) {
772 *tstr = cp;
773 *length = 0;
774 return (NULL);
775 } else {
776 *tstr = ++cp;
777 cp = (char *)Buf_GetAll(buf, length);
778 *length -= 1; /* Don't count the NULL */
779 Buf_Destroy(buf, FALSE);
780 return (cp);
781 }
782}
783
784/*-
785 *-----------------------------------------------------------------------
786 * Var_Quote --
787 * Quote shell meta-characters in the string
788 *
789 * Results:
790 * The quoted string
791 *
792 * Side Effects:
793 * None.
794 *
795 *-----------------------------------------------------------------------
796 */
797char *
798Var_Quote(const char *str)
799{
800 Buffer *buf;
801 /* This should cover most shells :-( */
802 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
803 char *ret;
804
805 buf = Buf_Init(MAKE_BSIZE);
806 for (; *str; str++) {
807 if (strchr(meta, *str) != NULL)
808 Buf_AddByte(buf, (Byte)'\\');
809 Buf_AddByte(buf, (Byte)*str);
810 }
811 Buf_AddByte(buf, (Byte)'\0');
812 ret = Buf_GetAll(buf, NULL);
813 Buf_Destroy(buf, FALSE);
814 return (ret);
815}
816
817/*-
818 *-----------------------------------------------------------------------
819 * VarREError --
820 * Print the error caused by a regcomp or regexec call.
821 *
822 * Results:
823 * None.
824 *
825 * Side Effects:
826 * An error gets printed.
827 *
828 *-----------------------------------------------------------------------
829 */
830void
831VarREError(int err, regex_t *pat, const char *str)
832{
833 char *errbuf;
834 int errlen;
835
836 errlen = regerror(err, pat, 0, 0);
837 errbuf = emalloc(errlen);
838 regerror(err, pat, errbuf, errlen);
839 Error("%s: %s", str, errbuf);
840 free(errbuf);
841}
842
843/*-
844 *-----------------------------------------------------------------------
845 * Var_Parse --
846 * Given the start of a variable invocation, extract the variable
847 * name and find its value, then modify it according to the
848 * specification.
849 *
850 * Results:
851 * The (possibly-modified) value of the variable or var_Error if the
852 * specification is invalid. The length of the specification is
853 * placed in *lengthPtr (for invalid specifications, this is just
854 * 2 to skip the '$' and the following letter, or 1 if '$' was the
855 * last character in the string).
856 * A Boolean in *freePtr telling whether the returned string should
857 * be freed by the caller.
858 *
859 * Side Effects:
860 * None.
861 *
862 *-----------------------------------------------------------------------
863 */
864char *
865Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
866{
867 char *tstr; /* Pointer into str */
868 Var *v; /* Variable in invocation */
869 char *cp; /* Secondary pointer into str (place marker
870 * for tstr) */
871 Boolean haveModifier;/* TRUE if have modifiers for the variable */
872 char endc; /* Ending character when variable in parens
873 * or braces */
874 char startc=0; /* Starting character when variable in parens
875 * or braces */
876 int cnt; /* Used to count brace pairs when variable in
877 * in parens or braces */
878 char *start;
879 char delim;
880 Boolean dynamic; /* TRUE if the variable is local and we're
881 * expanding it in a non-local context. This
882 * is done to support dynamic sources. The
883 * result is just the invocation, unaltered */
884 int vlen; /* length of variable name, after embedded variable
885 * expansion */
886
887 *freePtr = FALSE;
888 dynamic = FALSE;
889 start = str;
890
891 if (str[1] != OPEN_PAREN && str[1] != OPEN_BRACKET) {
892 /*
893 * If it's not bounded by braces of some sort, life is much simpler.
894 * We just need to check for the first character and return the
895 * value if it exists.
896 */
897 char name[2];
898
899 name[0] = str[1];
900 name[1] = '\0';
901
902 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
903 if (v == (Var *)NULL) {
904 if (str[1] != '\0')
905 *lengthPtr = 2;
906 else
907 *lengthPtr = 1;
908
909 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
910 /*
911 * If substituting a local variable in a non-local context,
912 * assume it's for dynamic source stuff. We have to handle
913 * this specially and return the longhand for the variable
914 * with the dollar sign escaped so it makes it back to the
915 * caller. Only four of the local variables are treated
916 * specially as they are the only four that will be set
917 * when dynamic sources are expanded.
918 */
919 /* XXX: It looks like $% and $! are reversed here */
920 switch (str[1]) {
921 case '@':
922 return ("$(.TARGET)");
923 case '%':
924 return ("$(.ARCHIVE)");
925 case '*':
926 return ("$(.PREFIX)");
927 case '!':
928 return ("$(.MEMBER)");
929 default:
930 break;
931 }
932 }
933 /*
934 * Error
935 */
936 return (err ? var_Error : varNoError);
937 } else {
938 haveModifier = FALSE;
939 tstr = &str[1];
940 endc = str[1];
941 }
942 } else {
943 /* build up expanded variable name in this buffer */
944 Buffer *buf = Buf_Init(MAKE_BSIZE);
945
946 startc = str[1];
947 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
948
949 /*
950 * Skip to the end character or a colon, whichever comes first,
951 * replacing embedded variables as we go.
952 */
953 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
954 if (*tstr == '$') {
955 size_t rlen;
956 Boolean rfree;
957 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
958
959 if (rval == var_Error) {
960 Fatal("Error expanding embedded variable.");
961 } else if (rval != NULL) {
962 Buf_Append(buf, rval);
963 if (rfree)
964 free(rval);
965 }
966 tstr += rlen - 1;
967 } else
968 Buf_AddByte(buf, (Byte)*tstr);
969
970 if (*tstr == '\0') {
971 /*
972 * If we never did find the end character, return NULL
973 * right now, setting the length to be the distance to
974 * the end of the string, since that's what make does.
975 */
976 *lengthPtr = tstr - str;
977 return (var_Error);
978 }
979
980 haveModifier = (*tstr == ':');
981 *tstr = '\0';
982
983 Buf_AddByte(buf, (Byte)'\0');
984 str = Buf_GetAll(buf, (size_t *)NULL);
985 vlen = strlen(str);
986
987 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
988 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
989 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
990 {
991 /*
992 * Check for bogus D and F forms of local variables since we're
993 * in a local context and the name is the right length.
994 */
995 switch (str[0]) {
996 case '@':
997 case '%':
998 case '*':
999 case '!':
1000 case '>':
1001 case '<':
1002 {
1003 char vname[2];
1004 char *val;
1005
1006 /*
1007 * Well, it's local -- go look for it.
1008 */
1009 vname[0] = str[0];
1010 vname[1] = '\0';
1011 v = VarFind(vname, ctxt, 0);
1012
1013 if (v != NULL && !haveModifier) {
1014 /*
1015 * No need for nested expansion or anything, as we're
1016 * the only one who sets these things and we sure don't
1017 * put nested invocations in them...
1018 */
1019 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1020
1021 if (str[1] == 'D') {
1022 val = VarModify(val, VarHead, (void *)NULL);
1023 } else {
1024 val = VarModify(val, VarTail, (void *)NULL);
1025 }
1026 /*
1027 * Resulting string is dynamically allocated, so
1028 * tell caller to free it.
1029 */
1030 *freePtr = TRUE;
1031 *lengthPtr = tstr-start+1;
1032 *tstr = endc;
1033 Buf_Destroy(buf, TRUE);
1034 return (val);
1035 }
1036 break;
1037 default:
1038 break;
1039 }
1040 }
1041 }
1042
1043 if (v == (Var *)NULL) {
1044 if (((vlen == 1) ||
1045 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1046 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1047 {
1048 /*
1049 * If substituting a local variable in a non-local context,
1050 * assume it's for dynamic source stuff. We have to handle
1051 * this specially and return the longhand for the variable
1052 * with the dollar sign escaped so it makes it back to the
1053 * caller. Only four of the local variables are treated
1054 * specially as they are the only four that will be set
1055 * when dynamic sources are expanded.
1056 */
1057 switch (str[0]) {
1058 case '@':
1059 case '%':
1060 case '*':
1061 case '!':
1062 dynamic = TRUE;
1063 break;
1064 default:
1065 break;
1066 }
1067 } else if ((vlen > 2) && (str[0] == '.') &&
1068 isupper((unsigned char)str[1]) &&
1069 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1070 {
1071 int len;
1072
1073 len = vlen - 1;
1074 if ((strncmp(str, ".TARGET", len) == 0) ||
1075 (strncmp(str, ".ARCHIVE", len) == 0) ||
1076 (strncmp(str, ".PREFIX", len) == 0) ||
1077 (strncmp(str, ".MEMBER", len) == 0))
1078 {
1079 dynamic = TRUE;
1080 }
1081 }
1082
1083 if (!haveModifier) {
1084 /*
1085 * No modifiers -- have specification length so we can return
1086 * now.
1087 */
1088 *lengthPtr = tstr - start + 1;
1089 *tstr = endc;
1090 if (dynamic) {
1091 str = emalloc(*lengthPtr + 1);
1092 strncpy(str, start, *lengthPtr);
1093 str[*lengthPtr] = '\0';
1094 *freePtr = TRUE;
1095 Buf_Destroy(buf, TRUE);
1096 return (str);
1097 } else {
1098 Buf_Destroy(buf, TRUE);
1099 return (err ? var_Error : varNoError);
1100 }
1101 } else {
1102 /*
1103 * Still need to get to the end of the variable specification,
1104 * so kludge up a Var structure for the modifications
1105 */
1106 v = VarCreate(str, NULL, VAR_JUNK);
1107 }
1108 }
1109 Buf_Destroy(buf, TRUE);
1110 }
1111
1112 if (v->flags & VAR_IN_USE) {
1113 Fatal("Variable %s is recursive.", v->name);
1114 /*NOTREACHED*/
1115 } else {
1116 v->flags |= VAR_IN_USE;
1117 }
1118 /*
1119 * Before doing any modification, we have to make sure the value
1120 * has been fully expanded. If it looks like recursion might be
1121 * necessary (there's a dollar sign somewhere in the variable's value)
1122 * we just call Var_Subst to do any other substitutions that are
1123 * necessary. Note that the value returned by Var_Subst will have
1124 * been dynamically-allocated, so it will need freeing when we
1125 * return.
1126 */
1127 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1128 if (strchr(str, '$') != (char *)NULL) {
1129 str = Var_Subst(NULL, str, ctxt, err);
1130 *freePtr = TRUE;
1131 }
1132
1133 v->flags &= ~VAR_IN_USE;
1134
1135 /*
1136 * Now we need to apply any modifiers the user wants applied.
1137 * These are:
1138 * :M<pattern> words which match the given <pattern>.
1139 * <pattern> is of the standard file
1140 * wildcarding form.
1141 * :S<d><pat1><d><pat2><d>[g]
1142 * Substitute <pat2> for <pat1> in the value
1143 * :C<d><pat1><d><pat2><d>[g]
1144 * Substitute <pat2> for regex <pat1> in the value
1145 * :H Substitute the head of each word
1146 * :T Substitute the tail of each word
1147 * :E Substitute the extension (minus '.') of
1148 * each word
1149 * :R Substitute the root of each word
1150 * (pathname minus the suffix).
1151 * :lhs=rhs Like :S, but the rhs goes to the end of
1152 * the invocation.
1153 * :U Converts variable to upper-case.
1154 * :L Converts variable to lower-case.
1155 */
1156 if ((str != NULL) && haveModifier) {
1157 /*
1158 * Skip initial colon while putting it back.
1159 */
1160 *tstr++ = ':';
1161 while (*tstr != endc) {
1162 char *newStr; /* New value to return */
1163 char termc; /* Character which terminated scan */
1164
1165 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1166 switch (*tstr) {
1167 case 'N':
1168 case 'M':
1169 {
1170 char *pattern;
1171 char *cp2;
1172 Boolean copy;
1173
1174 copy = FALSE;
1175 for (cp = tstr + 1;
1176 *cp != '\0' && *cp != ':' && *cp != endc;
1177 cp++)
1178 {
1179 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1180 copy = TRUE;
1181 cp++;
1182 }
1183 }
1184 termc = *cp;
1185 *cp = '\0';
1186 if (copy) {
1187 /*
1188 * Need to compress the \:'s out of the pattern, so
1189 * allocate enough room to hold the uncompressed
1190 * pattern (note that cp started at tstr+1, so
1191 * cp - tstr takes the null byte into account) and
1192 * compress the pattern into the space.
1193 */
1194 pattern = emalloc(cp - tstr);
1195 for (cp2 = pattern, cp = tstr + 1;
1196 *cp != '\0';
1197 cp++, cp2++)
1198 {
1199 if ((*cp == '\\') &&
1200 (cp[1] == ':' || cp[1] == endc)) {
1201 cp++;
1202 }
1203 *cp2 = *cp;
1204 }
1205 *cp2 = '\0';
1206 } else {
1207 pattern = &tstr[1];
1208 }
1209 if (*tstr == 'M' || *tstr == 'm') {
1210 newStr = VarModify(str, VarMatch, pattern);
1211 } else {
1212 newStr = VarModify(str, VarNoMatch, pattern);
1213 }
1214 if (copy) {
1215 free(pattern);
1216 }
1217 break;
1218 }
1219 case 'S':
1220 {
1221 VarPattern pattern;
1222 char del;
1223 Buffer *buf; /* Buffer for patterns */
1224
1225 pattern.flags = 0;
1226 del = tstr[1];
1227 tstr += 2;
1228
1229 /*
1230 * If pattern begins with '^', it is anchored to the
1231 * start of the word -- skip over it and flag pattern.
1232 */
1233 if (*tstr == '^') {
1234 pattern.flags |= VAR_MATCH_START;
1235 tstr += 1;
1236 }
1237
1238 buf = Buf_Init(0);
1239
1240 /*
1241 * Pass through the lhs looking for 1) escaped delimiters,
1242 * '$'s and backslashes (place the escaped character in
1243 * uninterpreted) and 2) unescaped $'s that aren't before
1244 * the delimiter (expand the variable substitution).
1245 * The result is left in the Buffer buf.
1246 */
1247 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1248 if ((*cp == '\\') &&
1249 ((cp[1] == del) ||
1250 (cp[1] == '$') ||
1251 (cp[1] == '\\')))
1252 {
1253 Buf_AddByte(buf, (Byte)cp[1]);
1254 cp++;
1255 } else if (*cp == '$') {
1256 if (cp[1] != del) {
1257 /*
1258 * If unescaped dollar sign not before the
1259 * delimiter, assume it's a variable
1260 * substitution and recurse.
1261 */
1262 char *cp2;
1263 size_t len;
1264 Boolean freeIt;
1265
1266 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1267 Buf_Append(buf, cp2);
1268 if (freeIt) {
1269 free(cp2);
1270 }
1271 cp += len - 1;
1272 } else {
1273 /*
1274 * Unescaped $ at end of pattern => anchor
1275 * pattern at end.
1276 */
1277 pattern.flags |= VAR_MATCH_END;
1278 }
1279 } else {
1280 Buf_AddByte(buf, (Byte)*cp);
1281 }
1282 }
1283
1284 Buf_AddByte(buf, (Byte)'\0');
1285
1286 /*
1287 * If lhs didn't end with the delimiter, complain and
1288 * exit.
1289 */
1290 if (*cp != del) {
1291 Fatal("Unclosed substitution for %s (%c missing)",
1292 v->name, del);
1293 }
1294
1295 /*
1296 * Fetch pattern and destroy buffer, but preserve the data
1297 * in it, since that's our lhs. Note that Buf_GetAll
1298 * will return the actual number of bytes, which includes
1299 * the null byte, so we have to decrement the length by
1300 * one.
1301 */
1302 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1303 pattern.leftLen--;
1304 Buf_Destroy(buf, FALSE);
1305
1306 /*
1307 * Now comes the replacement string. Three things need to
1308 * be done here: 1) need to compress escaped delimiters and
1309 * ampersands and 2) need to replace unescaped ampersands
1310 * with the l.h.s. (since this isn't regexp, we can do
1311 * it right here) and 3) expand any variable substitutions.
1312 */
1313 buf = Buf_Init(0);
1314
1315 tstr = cp + 1;
1316 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1317 if ((*cp == '\\') &&
1318 ((cp[1] == del) ||
1319 (cp[1] == '&') ||
1320 (cp[1] == '\\') ||
1321 (cp[1] == '$')))
1322 {
1323 Buf_AddByte(buf, (Byte)cp[1]);
1324 cp++;
1325 } else if ((*cp == '$') && (cp[1] != del)) {
1326 char *cp2;
1327 size_t len;
1328 Boolean freeIt;
1329
1330 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1331 Buf_Append(buf, cp2);
1332 cp += len - 1;
1333 if (freeIt) {
1334 free(cp2);
1335 }
1336 } else if (*cp == '&') {
1337 Buf_AddBytes(buf, pattern.leftLen,
1338 (Byte *)pattern.lhs);
1339 } else {
1340 Buf_AddByte(buf, (Byte)*cp);
1341 }
1342 }
1343
1344 Buf_AddByte(buf, (Byte)'\0');
1345
1346 /*
1347 * If didn't end in delimiter character, complain
1348 */
1349 if (*cp != del) {
1350 Fatal("Unclosed substitution for %s (%c missing)",
1351 v->name, del);
1352 }
1353
1354 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1355 pattern.rightLen--;
1356 Buf_Destroy(buf, FALSE);
1357
1358 /*
1359 * Check for global substitution. If 'g' after the final
1360 * delimiter, substitution is global and is marked that
1361 * way.
1362 */
1363 cp++;
1364 if (*cp == 'g') {
1365 pattern.flags |= VAR_SUB_GLOBAL;
1366 cp++;
1367 }
1368
1369 /*
1370 * Global substitution of the empty string causes an
1371 * infinite number of matches, unless anchored by '^'
1372 * (start of string) or '$' (end of string). Catch the
1373 * infinite substitution here.
1374 * Note that flags can only contain the 3 bits we're
1375 * interested in so we don't have to mask unrelated
1376 * bits. We can test for equality.
1377 */
1378 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1379 Fatal("Global substitution of the empty string");
1380
1381 termc = *cp;
1382 newStr = VarModify(str, VarSubstitute, &pattern);
1383 /*
1384 * Free the two strings.
1385 */
1386 free(pattern.lhs);
1387 free(pattern.rhs);
1388 break;
1389 }
1390 case 'C':
1391 {
1392 VarREPattern pattern;
1393 char *re;
1394 int error;
1395
1396 pattern.flags = 0;
1397 delim = tstr[1];
1398 tstr += 2;
1399
1400 cp = tstr;
1401
1402 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1403 NULL, NULL)) == NULL) {
1404 /* was: goto cleanup */
1405 *lengthPtr = cp - start + 1;
1406 if (*freePtr)
1407 free(str);
1408 if (delim != '\0')
1409 Fatal("Unclosed substitution for %s (%c missing)",
1410 v->name, delim);
1411 return (var_Error);
1412 }
1413
1414 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1415 delim, NULL, NULL, NULL)) == NULL){
1416 free(re);
1417
1418 /* was: goto cleanup */
1419 *lengthPtr = cp - start + 1;
1420 if (*freePtr)
1421 free(str);
1422 if (delim != '\0')
1423 Fatal("Unclosed substitution for %s (%c missing)",
1424 v->name, delim);
1425 return (var_Error);
1426 }
1427
1428 for (;; cp++) {
1429 switch (*cp) {
1430 case 'g':
1431 pattern.flags |= VAR_SUB_GLOBAL;
1432 continue;
1433 case '1':
1434 pattern.flags |= VAR_SUB_ONE;
1435 continue;
1436 default:
1437 break;
1438 }
1439 break;
1440 }
1441
1442 termc = *cp;
1443
1444 error = regcomp(&pattern.re, re, REG_EXTENDED);
1445 free(re);
1446 if (error) {
1447 *lengthPtr = cp - start + 1;
1448 VarREError(error, &pattern.re, "RE substitution error");
1449 free(pattern.replace);
1450 return (var_Error);
1451 }
1452
1453 pattern.nsub = pattern.re.re_nsub + 1;
1454 if (pattern.nsub < 1)
1455 pattern.nsub = 1;
1456 if (pattern.nsub > 10)
1457 pattern.nsub = 10;
1458 pattern.matches = emalloc(pattern.nsub *
1459 sizeof(regmatch_t));
1460 newStr = VarModify(str, VarRESubstitute, &pattern);
1461 regfree(&pattern.re);
1462 free(pattern.replace);
1463 free(pattern.matches);
1464 break;
1465 }
1466 case 'L':
1467 if (tstr[1] == endc || tstr[1] == ':') {
1468 Buffer *buf;
1469 buf = Buf_Init(MAKE_BSIZE);
1470 for (cp = str; *cp ; cp++)
1471 Buf_AddByte(buf, (Byte)tolower(*cp));
1472
1473 Buf_AddByte(buf, (Byte)'\0');
1474 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1475 Buf_Destroy(buf, FALSE);
1476
1477 cp = tstr + 1;
1478 termc = *cp;
1479 break;
1480 }
1481 /* FALLTHROUGH */
1482 case 'O':
1483 if (tstr[1] == endc || tstr[1] == ':') {
1484 newStr = VarSortWords(str, SortIncreasing);
1485 cp = tstr + 1;
1486 termc = *cp;
1487 break;
1488 }
1489 /* FALLTHROUGH */
1490 case 'Q':
1491 if (tstr[1] == endc || tstr[1] == ':') {
1492 newStr = Var_Quote(str);
1493 cp = tstr + 1;
1494 termc = *cp;
1495 break;
1496 }
1497 /*FALLTHRU*/
1498 case 'T':
1499 if (tstr[1] == endc || tstr[1] == ':') {
1500 newStr = VarModify(str, VarTail, (void *)NULL);
1501 cp = tstr + 1;
1502 termc = *cp;
1503 break;
1504 }
1505 /*FALLTHRU*/
1506 case 'U':
1507 if (tstr[1] == endc || tstr[1] == ':') {
1508 Buffer *buf;
1509 buf = Buf_Init(MAKE_BSIZE);
1510 for (cp = str; *cp ; cp++)
1511 Buf_AddByte(buf, (Byte)toupper(*cp));
1512
1513 Buf_AddByte(buf, (Byte)'\0');
1514 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1515 Buf_Destroy(buf, FALSE);
1516
1517 cp = tstr + 1;
1518 termc = *cp;
1519 break;
1520 }
1521 /* FALLTHROUGH */
1522 case 'H':
1523 if (tstr[1] == endc || tstr[1] == ':') {
1524 newStr = VarModify(str, VarHead, (void *)NULL);
1525 cp = tstr + 1;
1526 termc = *cp;
1527 break;
1528 }
1529 /*FALLTHRU*/
1530 case 'E':
1531 if (tstr[1] == endc || tstr[1] == ':') {
1532 newStr = VarModify(str, VarSuffix, (void *)NULL);
1533 cp = tstr + 1;
1534 termc = *cp;
1535 break;
1536 }
1537 /*FALLTHRU*/
1538 case 'R':
1539 if (tstr[1] == endc || tstr[1] == ':') {
1540 newStr = VarModify(str, VarRoot, (void *)NULL);
1541 cp = tstr + 1;
1542 termc = *cp;
1543 break;
1544 }
1545 /*FALLTHRU*/
1546#ifdef SUNSHCMD
1547 case 's':
1548 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1549 const char *error;
1550 {
1551 Buffer *buf = Cmd_Exec(str, &error);
1552 newStr = Buf_GetAll(buf, NULL);
1553 Buf_Destroy(buf, FALSE);
1554 }
1555 if (error)
1556 Error(error, str);
1557 cp = tstr + 2;
1558 termc = *cp;
1559 break;
1560 }
1561 /*FALLTHRU*/
1562#endif
1563 default:
1564 {
1565#ifdef SYSVVARSUB
1566 /*
1567 * This can either be a bogus modifier or a System-V
1568 * substitution command.
1569 */
1570 VarPattern pattern;
1571 Boolean eqFound;
1572
1573 pattern.flags = 0;
1574 eqFound = FALSE;
1575 /*
1576 * First we make a pass through the string trying
1577 * to verify it is a SYSV-make-style translation:
1578 * it must be: <string1>=<string2>)
1579 */
1580 cp = tstr;
1581 cnt = 1;
1582 while (*cp != '\0' && cnt) {
1583 if (*cp == '=') {
1584 eqFound = TRUE;
1585 /* continue looking for endc */
1586 }
1587 else if (*cp == endc)
1588 cnt--;
1589 else if (*cp == startc)
1590 cnt++;
1591 if (cnt)
1592 cp++;
1593 }
1594 if (*cp == endc && eqFound) {
1595
1596 /*
1597 * Now we break this sucker into the lhs and
1598 * rhs. We must null terminate them of course.
1599 */
1600 cp = tstr;
1601
1602 delim = '=';
1603 if ((pattern.lhs = VarGetPattern(ctxt,
1604 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1605 NULL)) == NULL) {
1606 /* was: goto cleanup */
1607 *lengthPtr = cp - start + 1;
1608 if (*freePtr)
1609 free(str);
1610 if (delim != '\0')
1611 Fatal("Unclosed substitution for %s (%c missing)",
1612 v->name, delim);
1613 return (var_Error);
1614 }
1615
1616 delim = endc;
1617 if ((pattern.rhs = VarGetPattern(ctxt,
1618 err, &cp, delim, NULL, &pattern.rightLen,
1619 &pattern)) == NULL) {
1620 /* was: goto cleanup */
1621 *lengthPtr = cp - start + 1;
1622 if (*freePtr)
1623 free(str);
1624 if (delim != '\0')
1625 Fatal("Unclosed substitution for %s (%c missing)",
1626 v->name, delim);
1627 return (var_Error);
1628 }
1629
1630 /*
1631 * SYSV modifications happen through the whole
1632 * string. Note the pattern is anchored at the end.
1633 */
1634 termc = *--cp;
1635 delim = '\0';
1636 newStr = VarModify(str, VarSYSVMatch, &pattern);
1637
1638 free(pattern.lhs);
1639 free(pattern.rhs);
1640
1641 termc = endc;
1642 } else
1643#endif
1644 {
1645 Error("Unknown modifier '%c'\n", *tstr);
1646 for (cp = tstr+1;
1647 *cp != ':' && *cp != endc && *cp != '\0';
1648 cp++)
1649 continue;
1650 termc = *cp;
1651 newStr = var_Error;
1652 }
1653 }
1654 }
1655 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1656
1657 if (*freePtr) {
1658 free(str);
1659 }
1660 str = newStr;
1661 if (str != var_Error) {
1662 *freePtr = TRUE;
1663 } else {
1664 *freePtr = FALSE;
1665 }
1666 if (termc == '\0') {
1667 Error("Unclosed variable specification for %s", v->name);
1668 } else if (termc == ':') {
1669 *cp++ = termc;
1670 } else {
1671 *cp = termc;
1672 }
1673 tstr = cp;
1674 }
1675 *lengthPtr = tstr - start + 1;
1676 } else {
1677 *lengthPtr = tstr - start + 1;
1678 *tstr = endc;
1679 }
1680
1681 if (v->flags & VAR_FROM_ENV) {
1682 Boolean destroy = FALSE;
1683
1684 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1685 destroy = TRUE;
1686 } else {
1687 /*
1688 * Returning the value unmodified, so tell the caller to free
1689 * the thing.
1690 */
1691 *freePtr = TRUE;
1692 }
1693 VarDestroy(v, destroy);
1694 } else if (v->flags & VAR_JUNK) {
1695 /*
1696 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1697 * doesn't try to free a static pointer.
1698 */
1699 if (*freePtr) {
1700 free(str);
1701 }
1702 *freePtr = FALSE;
1703 VarDestroy(v, TRUE);
1704 if (dynamic) {
1705 str = emalloc(*lengthPtr + 1);
1706 strncpy(str, start, *lengthPtr);
1707 str[*lengthPtr] = '\0';
1708 *freePtr = TRUE;
1709 } else {
1710 str = err ? var_Error : varNoError;
1711 }
1712 }
1713 return (str);
1714}
1715
1716/*-
1717 *-----------------------------------------------------------------------
1718 * Var_Subst --
1719 * Substitute for all variables in the given string in the given context
1720 * If undefErr is TRUE, Parse_Error will be called when an undefined
1721 * variable is encountered.
1722 *
1723 * Results:
1724 * The resulting string.
1725 *
1726 * Side Effects:
1727 * None. The old string must be freed by the caller
1728 *-----------------------------------------------------------------------
1729 */
1730char *
1731Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1732{
1733 Buffer *buf; /* Buffer for forming things */
1734 char *val; /* Value to substitute for a variable */
1735 size_t length; /* Length of the variable invocation */
1736 Boolean doFree; /* Set true if val should be freed */
1737 char *result;
1738
1739 static Boolean errorReported; /* Set true if an error has already
1740 * been reported to prevent a plethora
1741 * of messages when recursing */
1742
1743 buf = Buf_Init(0);
1744 errorReported = FALSE;
1745
1746 while (*str) {
1747 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1748 /*
1749 * A dollar sign may be escaped either with another dollar sign.
1750 * In such a case, we skip over the escape character and store the
1751 * dollar sign into the buffer directly.
1752 */
1753 Buf_AddByte(buf, (Byte)str[0]);
1754 str += 2;
1755
1756 } else if (str[0] != '$') {
1757 /*
1758 * Skip as many characters as possible -- either to the end of
1759 * the string or to the next dollar sign (variable invocation).
1760 */
1761 const char *cp = str;
1762
1763 do {
1764 str++;
1765 } while (str[0] != '$' && str[0] != '\0');
1766
1767 Buf_AppendRange(buf, cp, str);
1768
1769 } else {
1770 /*
1771 * Variable invocation.
1772 */
1773 if (var != NULL) {
1774 int expand;
1775 for (;;) {
1776 if (str[1] != OPEN_PAREN && str[1] != OPEN_BRACKET) {
1777 if (str[1] != var[0] || var[1] != '\0') {
1778 Buf_AddBytes(buf, 2, (const Byte *)str);
1779 str += 2;
1780 expand = FALSE;
1781 } else {
1782 expand = TRUE;
1783 }
1784 break;
1785 } else {
1786 const char *p = str + 2;
1787
1788 /*
1789 * Scan up to the end of the variable name.
1790 */
1791 while (*p != '\0' &&
1792 *p != ':' &&
1793 *p != CLOSE_PAREN &&
1794 *p != CLOSE_BRACKET &&
1795 *p != '$') {
1796 ++p;
1797 }
1798 /*
1799 * A variable inside the variable. We cannot expand
1800 * the external variable yet, so we try again with
1801 * the nested one
1802 */
1803 if (*p == '$') {
1804 Buf_AppendRange(buf, str, p);
1805 str = p;
1806 continue;
1807 }
1808
1809 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1810 var[p - str - 2] != '\0') {
1811 /*
1812 * Not the variable we want to expand, scan
1813 * until the next variable
1814 */
1815 for (;*p != '$' && *p != '\0'; p++)
1816 continue;
1817 Buf_AppendRange(buf, str, p);
1818 str = p;
1819 expand = FALSE;
1820 } else {
1821 expand = TRUE;
1822 }
1823 break;
1824 }
1825 }
1826 if (!expand)
1827 continue;
1828 }
1829
1830 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1831
1832 /*
1833 * When we come down here, val should either point to the
1834 * value of this variable, suitably modified, or be NULL.
1835 * Length should be the total length of the potential
1836 * variable invocation (from $ to end character...)
1837 */
1838 if (val == var_Error || val == varNoError) {
1839 /*
1840 * If performing old-time variable substitution, skip over
1841 * the variable and continue with the substitution. Otherwise,
1842 * store the dollar sign and advance str so we continue with
1843 * the string...
1844 */
1845 if (oldVars) {
1846 str += length;
1847 } else if (undefErr) {
1848 /*
1849 * If variable is undefined, complain and skip the
1850 * variable. The complaint will stop us from doing anything
1851 * when the file is parsed.
1852 */
1853 if (!errorReported) {
1854 Parse_Error(PARSE_FATAL,
1855 "Undefined variable \"%.*s\"",length,str);
1856 }
1857 str += length;
1858 errorReported = TRUE;
1859 } else {
1860 Buf_AddByte(buf, (Byte)*str);
1861 str += 1;
1862 }
1863 } else {
1864 /*
1865 * We've now got a variable structure to store in. But first,
1866 * advance the string pointer.
1867 */
1868 str += length;
1869
1870 /*
1871 * Copy all the characters from the variable value straight
1872 * into the new string.
1873 */
1874 Buf_Append(buf, val);
1875 if (doFree) {
1876 free(val);
1877 }
1878 }
1879 }
1880 }
1881
1882 //Buf_AddByte(buf, '\0');
1883 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
1884 Buf_Destroy(buf, FALSE);
1885 return (result);
1886}
1887
1888/*-
1889 *-----------------------------------------------------------------------
1890 * Var_GetTail --
1891 * Return the tail from each of a list of words. Used to set the
1892 * System V local variables.
1893 *
1894 * Results:
1895 * The resulting string.
1896 *
1897 * Side Effects:
1898 * None.
1899 *
1900 *-----------------------------------------------------------------------
1901 */
1902char *
1903Var_GetTail(char *file)
1904{
1905 return (VarModify(file, VarTail, (void *)NULL));
1906}
1907
1908/*-
1909 *-----------------------------------------------------------------------
1910 * Var_GetHead --
1911 * Find the leading components of a (list of) filename(s).
1912 * XXX: VarHead does not replace foo by ., as (sun) System V make
1913 * does.
1914 *
1915 * Results:
1916 * The leading components.
1917 *
1918 * Side Effects:
1919 * None.
1920 *
1921 *-----------------------------------------------------------------------
1922 */
1923char *
1924Var_GetHead(char *file)
1925{
1926
1927 return (VarModify(file, VarHead, (void *)NULL));
1928}
1929
1930/*-
1931 *-----------------------------------------------------------------------
1932 * Var_Init --
1933 * Initialize the module
1934 *
1935 * Results:
1936 * None
1937 *
1938 * Side Effects:
1939 * The VAR_CMD and VAR_GLOBAL contexts are created
1940 *-----------------------------------------------------------------------
1941 */
1942void
1943Var_Init(void)
1944{
1945 VAR_GLOBAL = Targ_NewGN("Global");
1946 VAR_CMD = Targ_NewGN("Command");
1947}
1948
1949/****************** PRINT DEBUGGING INFO *****************/
1950static int
1951VarPrintVar(void *vp, void *dummy __unused)
1952{
1953 Var *v = (Var *) vp;
1954
1955 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1956 return (0);
1957}
1958
1959/*-
1960 *-----------------------------------------------------------------------
1961 * Var_Dump --
1962 * print all variables in a context
1963 *-----------------------------------------------------------------------
1964 */
1965void
1966Var_Dump(GNode *ctxt)
1967{
1968 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);
1969}