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