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