Add rdate(8). This supports both SNTP(RFC 2030) and RFC 868.
[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 $
c382ef3f 40 * $DragonFly: src/usr.bin/make/var.c,v 1.17 2004/12/01 01:29:31 joerg 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
984263bc
MD
774/*-
775 *-----------------------------------------------------------------------
c382ef3f 776 * Var_Quote --
984263bc
MD
777 * Quote shell meta-characters in the string
778 *
779 * Results:
780 * The quoted string
781 *
782 * Side Effects:
783 * None.
784 *
785 *-----------------------------------------------------------------------
786 */
c382ef3f
JS
787char *
788Var_Quote(const char *str)
984263bc 789{
984263bc 790 Buffer buf;
c382ef3f 791 char *retstr;
984263bc
MD
792 /* This should cover most shells :-( */
793 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
794
795 buf = Buf_Init (MAKE_BSIZE);
796 for (; *str; str++) {
797 if (strchr(meta, *str) != NULL)
798 Buf_AddByte(buf, (Byte)'\\');
799 Buf_AddByte(buf, (Byte)*str);
800 }
801 Buf_AddByte(buf, (Byte) '\0');
c382ef3f 802 retstr = Buf_GetAll (buf, (int *)NULL);
984263bc 803 Buf_Destroy (buf, FALSE);
c382ef3f 804 return retstr;
984263bc
MD
805}
806
807/*-
808 *-----------------------------------------------------------------------
809 * Var_Parse --
810 * Given the start of a variable invocation, extract the variable
811 * name and find its value, then modify it according to the
812 * specification.
813 *
814 * Results:
815 * The (possibly-modified) value of the variable or var_Error if the
816 * specification is invalid. The length of the specification is
817 * placed in *lengthPtr (for invalid specifications, this is just
3b340ba1
JS
818 * 2 to skip the '$' and the following letter, or 1 if '$' was the
819 * last character in the string).
984263bc
MD
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) {
3b340ba1
JS
868 if (str[1] != '\0')
869 *lengthPtr = 2;
870 else
871 *lengthPtr = 1;
984263bc
MD
872
873 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
874 /*
875 * If substituting a local variable in a non-local context,
876 * assume it's for dynamic source stuff. We have to handle
877 * this specially and return the longhand for the variable
878 * with the dollar sign escaped so it makes it back to the
879 * caller. Only four of the local variables are treated
880 * specially as they are the only four that will be set
881 * when dynamic sources are expanded.
882 */
883 /* XXX: It looks like $% and $! are reversed here */
884 switch (str[1]) {
885 case '@':
886 return("$(.TARGET)");
887 case '%':
888 return("$(.ARCHIVE)");
889 case '*':
890 return("$(.PREFIX)");
891 case '!':
892 return("$(.MEMBER)");
454224cf
MD
893 default:
894 break;
984263bc
MD
895 }
896 }
897 /*
898 * Error
899 */
900 return (err ? var_Error : varNoError);
901 } else {
902 haveModifier = FALSE;
903 tstr = &str[1];
904 endc = str[1];
905 }
906 } else {
907 /* build up expanded variable name in this buffer */
908 Buffer buf = Buf_Init(MAKE_BSIZE);
909
910 startc = str[1];
911 endc = startc == '(' ? ')' : '}';
912
913 /*
914 * Skip to the end character or a colon, whichever comes first,
915 * replacing embedded variables as we go.
916 */
917 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
918 if (*tstr == '$') {
919 int rlen;
920 Boolean rfree;
921 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
922
923 if (rval == var_Error) {
924 Fatal("Error expanding embedded variable.");
925 } else if (rval != NULL) {
926 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
927 if (rfree)
928 free(rval);
929 }
930 tstr += rlen - 1;
931 } else
932 Buf_AddByte(buf, (Byte) *tstr);
933
934 if (*tstr == '\0') {
935 /*
936 * If we never did find the end character, return NULL
937 * right now, setting the length to be the distance to
938 * the end of the string, since that's what make does.
939 */
940 *lengthPtr = tstr - str;
941 return (var_Error);
942 }
943
944 haveModifier = (*tstr == ':');
945 *tstr = '\0';
946
947 Buf_AddByte(buf, (Byte) '\0');
948 str = Buf_GetAll(buf, NULL);
949 vlen = strlen(str);
950
951 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
9edd457e 952 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
984263bc
MD
953 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
954 {
955 /*
956 * Check for bogus D and F forms of local variables since we're
957 * in a local context and the name is the right length.
958 */
959 switch(str[0]) {
960 case '@':
961 case '%':
962 case '*':
963 case '!':
964 case '>':
965 case '<':
966 {
967 char vname[2];
968 char *val;
969
970 /*
971 * Well, it's local -- go look for it.
972 */
973 vname[0] = str[0];
974 vname[1] = '\0';
975 v = VarFind(vname, ctxt, 0);
976
9edd457e 977 if (v != (Var *)NULL && !haveModifier) {
984263bc
MD
978 /*
979 * No need for nested expansion or anything, as we're
980 * the only one who sets these things and we sure don't
981 * put nested invocations in them...
982 */
983 val = (char *)Buf_GetAll(v->val, (int *)NULL);
984
985 if (str[1] == 'D') {
9edd457e 986 val = VarModify(val, VarHead, (void *)0);
984263bc 987 } else {
9edd457e 988 val = VarModify(val, VarTail, (void *)0);
984263bc
MD
989 }
990 /*
991 * Resulting string is dynamically allocated, so
992 * tell caller to free it.
993 */
994 *freePtr = TRUE;
995 *lengthPtr = tstr-start+1;
996 *tstr = endc;
997 Buf_Destroy(buf, TRUE);
998 return(val);
999 }
1000 break;
454224cf
MD
1001 default:
1002 break;
984263bc
MD
1003 }
1004 }
1005 }
1006
9edd457e 1007 if (v == (Var *)NULL) {
984263bc
MD
1008 if (((vlen == 1) ||
1009 (((vlen == 2) && (str[1] == 'F' ||
1010 str[1] == 'D')))) &&
1011 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1012 {
1013 /*
1014 * If substituting a local variable in a non-local context,
1015 * assume it's for dynamic source stuff. We have to handle
1016 * this specially and return the longhand for the variable
1017 * with the dollar sign escaped so it makes it back to the
1018 * caller. Only four of the local variables are treated
1019 * specially as they are the only four that will be set
1020 * when dynamic sources are expanded.
1021 */
1022 switch (str[0]) {
1023 case '@':
1024 case '%':
1025 case '*':
1026 case '!':
1027 dynamic = TRUE;
1028 break;
454224cf
MD
1029 default:
1030 break;
984263bc
MD
1031 }
1032 } else if ((vlen > 2) && (str[0] == '.') &&
1033 isupper((unsigned char) str[1]) &&
1034 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1035 {
1036 int len;
1037
1038 len = vlen - 1;
1039 if ((strncmp(str, ".TARGET", len) == 0) ||
1040 (strncmp(str, ".ARCHIVE", len) == 0) ||
1041 (strncmp(str, ".PREFIX", len) == 0) ||
1042 (strncmp(str, ".MEMBER", len) == 0))
1043 {
1044 dynamic = TRUE;
1045 }
1046 }
1047
1048 if (!haveModifier) {
1049 /*
1050 * No modifiers -- have specification length so we can return
1051 * now.
1052 */
1053 *lengthPtr = tstr - start + 1;
1054 *tstr = endc;
1055 if (dynamic) {
1056 str = emalloc(*lengthPtr + 1);
1057 strncpy(str, start, *lengthPtr);
1058 str[*lengthPtr] = '\0';
1059 *freePtr = TRUE;
1060 Buf_Destroy(buf, TRUE);
1061 return(str);
1062 } else {
1063 Buf_Destroy(buf, TRUE);
1064 return (err ? var_Error : varNoError);
1065 }
1066 } else {
1067 /*
1068 * Still need to get to the end of the variable specification,
1069 * so kludge up a Var structure for the modifications
1070 */
1071 v = (Var *) emalloc(sizeof(Var));
6065a492 1072 v->name = estrdup(str);
984263bc
MD
1073 v->val = Buf_Init(1);
1074 v->flags = VAR_JUNK;
1075 }
1076 }
1077 Buf_Destroy(buf, TRUE);
1078 }
1079
1080 if (v->flags & VAR_IN_USE) {
1081 Fatal("Variable %s is recursive.", v->name);
1082 /*NOTREACHED*/
1083 } else {
1084 v->flags |= VAR_IN_USE;
1085 }
1086 /*
1087 * Before doing any modification, we have to make sure the value
1088 * has been fully expanded. If it looks like recursion might be
1089 * necessary (there's a dollar sign somewhere in the variable's value)
1090 * we just call Var_Subst to do any other substitutions that are
1091 * necessary. Note that the value returned by Var_Subst will have
1092 * been dynamically-allocated, so it will need freeing when we
1093 * return.
1094 */
1095 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1096 if (strchr (str, '$') != (char *)NULL) {
1097 str = Var_Subst(NULL, str, ctxt, err);
1098 *freePtr = TRUE;
1099 }
1100
1101 v->flags &= ~VAR_IN_USE;
1102
1103 /*
1104 * Now we need to apply any modifiers the user wants applied.
1105 * These are:
1106 * :M<pattern> words which match the given <pattern>.
1107 * <pattern> is of the standard file
1108 * wildcarding form.
1109 * :S<d><pat1><d><pat2><d>[g]
1110 * Substitute <pat2> for <pat1> in the value
1111 * :C<d><pat1><d><pat2><d>[g]
1112 * Substitute <pat2> for regex <pat1> in the value
1113 * :H Substitute the head of each word
1114 * :T Substitute the tail of each word
1115 * :E Substitute the extension (minus '.') of
1116 * each word
1117 * :R Substitute the root of each word
1118 * (pathname minus the suffix).
1119 * :lhs=rhs Like :S, but the rhs goes to the end of
1120 * the invocation.
1121 * :U Converts variable to upper-case.
1122 * :L Converts variable to lower-case.
1123 */
1124 if ((str != (char *)NULL) && haveModifier) {
1125 /*
1126 * Skip initial colon while putting it back.
1127 */
1128 *tstr++ = ':';
1129 while (*tstr != endc) {
1130 char *newStr; /* New value to return */
1131 char termc; /* Character which terminated scan */
1132
913800f5 1133 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
984263bc
MD
1134 switch (*tstr) {
1135 case 'U':
1136 if (tstr[1] == endc || tstr[1] == ':') {
1137 Buffer buf;
1138 buf = Buf_Init(MAKE_BSIZE);
1139 for (cp = str; *cp ; cp++)
1140 Buf_AddByte(buf, (Byte) toupper(*cp));
1141
1142 Buf_AddByte(buf, (Byte) '\0');
1143 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1144 Buf_Destroy(buf, FALSE);
1145
1146 cp = tstr + 1;
1147 termc = *cp;
1148 break;
1149 }
1150 /* FALLTHROUGH */
1151 case 'L':
1152 if (tstr[1] == endc || tstr[1] == ':') {
1153 Buffer buf;
1154 buf = Buf_Init(MAKE_BSIZE);
1155 for (cp = str; *cp ; cp++)
1156 Buf_AddByte(buf, (Byte) tolower(*cp));
1157
1158 Buf_AddByte(buf, (Byte) '\0');
1159 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1160 Buf_Destroy(buf, FALSE);
1161
1162 cp = tstr + 1;
1163 termc = *cp;
1164 break;
1165 }
1166 /* FALLTHROUGH */
1167 case 'N':
1168 case 'M':
1169 {
1170 char *pattern;
1171 char *cp2;
1172 Boolean copy;
1173
1174 copy = FALSE;
1175 for (cp = tstr + 1;
1176 *cp != '\0' && *cp != ':' && *cp != endc;
1177 cp++)
1178 {
1179 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1180 copy = TRUE;
1181 cp++;
1182 }
1183 }
1184 termc = *cp;
1185 *cp = '\0';
1186 if (copy) {
1187 /*
1188 * Need to compress the \:'s out of the pattern, so
1189 * allocate enough room to hold the uncompressed
1190 * pattern (note that cp started at tstr+1, so
1191 * cp - tstr takes the null byte into account) and
1192 * compress the pattern into the space.
1193 */
1194 pattern = emalloc(cp - tstr);
1195 for (cp2 = pattern, cp = tstr + 1;
1196 *cp != '\0';
1197 cp++, cp2++)
1198 {
1199 if ((*cp == '\\') &&
1200 (cp[1] == ':' || cp[1] == endc)) {
1201 cp++;
1202 }
1203 *cp2 = *cp;
1204 }
1205 *cp2 = '\0';
1206 } else {
1207 pattern = &tstr[1];
1208 }
1209 if (*tstr == 'M' || *tstr == 'm') {
9edd457e 1210 newStr = VarModify(str, VarMatch, (void *)pattern);
984263bc
MD
1211 } else {
1212 newStr = VarModify(str, VarNoMatch,
9edd457e 1213 (void *)pattern);
984263bc
MD
1214 }
1215 if (copy) {
1216 free(pattern);
1217 }
1218 break;
1219 }
1220 case 'S':
1221 {
1222 VarPattern pattern;
454224cf 1223 char del;
984263bc
MD
1224 Buffer buf; /* Buffer for patterns */
1225
1226 pattern.flags = 0;
454224cf 1227 del = tstr[1];
984263bc
MD
1228 tstr += 2;
1229
1230 /*
1231 * If pattern begins with '^', it is anchored to the
1232 * start of the word -- skip over it and flag pattern.
1233 */
1234 if (*tstr == '^') {
1235 pattern.flags |= VAR_MATCH_START;
1236 tstr += 1;
1237 }
1238
1239 buf = Buf_Init(0);
1240
1241 /*
1242 * Pass through the lhs looking for 1) escaped delimiters,
1243 * '$'s and backslashes (place the escaped character in
1244 * uninterpreted) and 2) unescaped $'s that aren't before
1245 * the delimiter (expand the variable substitution).
1246 * The result is left in the Buffer buf.
1247 */
454224cf 1248 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
984263bc 1249 if ((*cp == '\\') &&
454224cf 1250 ((cp[1] == del) ||
984263bc
MD
1251 (cp[1] == '$') ||
1252 (cp[1] == '\\')))
1253 {
1254 Buf_AddByte(buf, (Byte)cp[1]);
1255 cp++;
1256 } else if (*cp == '$') {
454224cf 1257 if (cp[1] != del) {
984263bc
MD
1258 /*
1259 * If unescaped dollar sign not before the
1260 * delimiter, assume it's a variable
1261 * substitution and recurse.
1262 */
1263 char *cp2;
1264 int len;
1265 Boolean freeIt;
1266
1267 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1268 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1269 if (freeIt) {
1270 free(cp2);
1271 }
1272 cp += len - 1;
1273 } else {
1274 /*
1275 * Unescaped $ at end of pattern => anchor
1276 * pattern at end.
1277 */
1278 pattern.flags |= VAR_MATCH_END;
1279 }
1280 } else {
1281 Buf_AddByte(buf, (Byte)*cp);
1282 }
1283 }
1284
1285 Buf_AddByte(buf, (Byte)'\0');
1286
1287 /*
1288 * If lhs didn't end with the delimiter, complain and
d2ffb6f1 1289 * exit.
984263bc 1290 */
454224cf 1291 if (*cp != del) {
d2ffb6f1 1292 Fatal("Unclosed substitution for %s (%c missing)",
454224cf 1293 v->name, del);
984263bc
MD
1294 }
1295
1296 /*
1297 * Fetch pattern and destroy buffer, but preserve the data
1298 * in it, since that's our lhs. Note that Buf_GetAll
1299 * will return the actual number of bytes, which includes
1300 * the null byte, so we have to decrement the length by
1301 * one.
1302 */
1303 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1304 pattern.leftLen--;
1305 Buf_Destroy(buf, FALSE);
1306
1307 /*
1308 * Now comes the replacement string. Three things need to
1309 * be done here: 1) need to compress escaped delimiters and
1310 * ampersands and 2) need to replace unescaped ampersands
1311 * with the l.h.s. (since this isn't regexp, we can do
1312 * it right here) and 3) expand any variable substitutions.
1313 */
1314 buf = Buf_Init(0);
1315
1316 tstr = cp + 1;
454224cf 1317 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
984263bc 1318 if ((*cp == '\\') &&
454224cf 1319 ((cp[1] == del) ||
984263bc
MD
1320 (cp[1] == '&') ||
1321 (cp[1] == '\\') ||
1322 (cp[1] == '$')))
1323 {
1324 Buf_AddByte(buf, (Byte)cp[1]);
1325 cp++;
454224cf 1326 } else if ((*cp == '$') && (cp[1] != del)) {
984263bc
MD
1327 char *cp2;
1328 int len;
1329 Boolean freeIt;
1330
1331 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1332 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1333 cp += len - 1;
1334 if (freeIt) {
1335 free(cp2);
1336 }
1337 } else if (*cp == '&') {
1338 Buf_AddBytes(buf, pattern.leftLen,
1339 (Byte *)pattern.lhs);
1340 } else {
1341 Buf_AddByte(buf, (Byte)*cp);
1342 }
1343 }
1344
1345 Buf_AddByte(buf, (Byte)'\0');
1346
1347 /*
1348 * If didn't end in delimiter character, complain
1349 */
454224cf 1350 if (*cp != del) {
d2ffb6f1 1351 Fatal("Unclosed substitution for %s (%c missing)",
454224cf 1352 v->name, del);
984263bc
MD
1353 }
1354
1355 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1356 pattern.rightLen--;
1357 Buf_Destroy(buf, FALSE);
1358
1359 /*
1360 * Check for global substitution. If 'g' after the final
1361 * delimiter, substitution is global and is marked that
1362 * way.
1363 */
1364 cp++;
1365 if (*cp == 'g') {
1366 pattern.flags |= VAR_SUB_GLOBAL;
1367 cp++;
1368 }
1369
6065a492
MD
1370 /*
1371 * Global substitution of the empty string causes an
1372 * infinite number of matches, unless anchored by '^'
1373 * (start of string) or '$' (end of string). Catch the
1374 * infinite substitution here.
1375 * Note that flags can only contain the 3 bits we're
1376 * interested in so we don't have to mask unrelated
1377 * bits. We can test for equality.
1378 */
1379 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1380 Fatal("Global substitution of the empty string");
1381
984263bc
MD
1382 termc = *cp;
1383 newStr = VarModify(str, VarSubstitute,
9edd457e 1384 (void *)&pattern);
984263bc
MD
1385 /*
1386 * Free the two strings.
1387 */
1388 free(pattern.lhs);
1389 free(pattern.rhs);
1390 break;
1391 }
1392 case 'C':
1393 {
1394 VarREPattern pattern;
1395 char *re;
1396 int error;
1397
1398 pattern.flags = 0;
1399 delim = tstr[1];
1400 tstr += 2;
1401
1402 cp = tstr;
1403
1404 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1405 NULL, NULL)) == NULL) {
1406 /* was: goto cleanup */
1407 *lengthPtr = cp - start + 1;
1408 if (*freePtr)
1409 free(str);
1410 if (delim != '\0')
d2ffb6f1 1411 Fatal("Unclosed substitution for %s (%c missing)",
984263bc
MD
1412 v->name, delim);
1413 return (var_Error);
1414 }
1415
1416 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1417 delim, NULL, NULL, NULL)) == NULL){
1418 free(re);
1419
1420 /* was: goto cleanup */
1421 *lengthPtr = cp - start + 1;
1422 if (*freePtr)
1423 free(str);
1424 if (delim != '\0')
d2ffb6f1 1425 Fatal("Unclosed substitution for %s (%c missing)",
984263bc
MD
1426 v->name, delim);
1427 return (var_Error);
1428 }
1429
1430 for (;; cp++) {
1431 switch (*cp) {
1432 case 'g':
1433 pattern.flags |= VAR_SUB_GLOBAL;
1434 continue;
1435 case '1':
1436 pattern.flags |= VAR_SUB_ONE;
1437 continue;
454224cf
MD
1438 default:
1439 break;
984263bc
MD
1440 }
1441 break;
1442 }
1443
1444 termc = *cp;
1445
1446 error = regcomp(&pattern.re, re, REG_EXTENDED);
1447 free(re);
1448 if (error) {
1449 *lengthPtr = cp - start + 1;
1450 VarREError(error, &pattern.re, "RE substitution error");
1451 free(pattern.replace);
1452 return (var_Error);
1453 }
1454
1455 pattern.nsub = pattern.re.re_nsub + 1;
1456 if (pattern.nsub < 1)
1457 pattern.nsub = 1;
1458 if (pattern.nsub > 10)
1459 pattern.nsub = 10;
1460 pattern.matches = emalloc(pattern.nsub *
1461 sizeof(regmatch_t));
1462 newStr = VarModify(str, VarRESubstitute,
9edd457e 1463 (void *) &pattern);
984263bc
MD
1464 regfree(&pattern.re);
1465 free(pattern.replace);
1466 free(pattern.matches);
1467 break;
1468 }
1469 case 'Q':
1470 if (tstr[1] == endc || tstr[1] == ':') {
c382ef3f 1471 newStr = Var_Quote (str);
984263bc
MD
1472 cp = tstr + 1;
1473 termc = *cp;
1474 break;
1475 }
1476 /*FALLTHRU*/
1477 case 'T':
1478 if (tstr[1] == endc || tstr[1] == ':') {
9edd457e 1479 newStr = VarModify (str, VarTail, (void *)0);
984263bc
MD
1480 cp = tstr + 1;
1481 termc = *cp;
1482 break;
1483 }
1484 /*FALLTHRU*/
1485 case 'H':
1486 if (tstr[1] == endc || tstr[1] == ':') {
9edd457e 1487 newStr = VarModify (str, VarHead, (void *)0);
984263bc
MD
1488 cp = tstr + 1;
1489 termc = *cp;
1490 break;
1491 }
1492 /*FALLTHRU*/
1493 case 'E':
1494 if (tstr[1] == endc || tstr[1] == ':') {
9edd457e 1495 newStr = VarModify (str, VarSuffix, (void *)0);
984263bc
MD
1496 cp = tstr + 1;
1497 termc = *cp;
1498 break;
1499 }
1500 /*FALLTHRU*/
1501 case 'R':
1502 if (tstr[1] == endc || tstr[1] == ':') {
9edd457e 1503 newStr = VarModify (str, VarRoot, (void *)0);
984263bc
MD
1504 cp = tstr + 1;
1505 termc = *cp;
1506 break;
1507 }
1508 /*FALLTHRU*/
1509#ifdef SUNSHCMD
1510 case 's':
1511 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
454224cf
MD
1512 char *error;
1513 newStr = Cmd_Exec (str, &error);
1514 if (error)
1515 Error (error, str);
984263bc
MD
1516 cp = tstr + 2;
1517 termc = *cp;
1518 break;
1519 }
1520 /*FALLTHRU*/
1521#endif
1522 default:
1523 {
1524#ifdef SYSVVARSUB
1525 /*
1526 * This can either be a bogus modifier or a System-V
1527 * substitution command.
1528 */
1529 VarPattern pattern;
1530 Boolean eqFound;
1531
1532 pattern.flags = 0;
1533 eqFound = FALSE;
1534 /*
1535 * First we make a pass through the string trying
1536 * to verify it is a SYSV-make-style translation:
1537 * it must be: <string1>=<string2>)
1538 */
1539 cp = tstr;
1540 cnt = 1;
1541 while (*cp != '\0' && cnt) {
1542 if (*cp == '=') {
1543 eqFound = TRUE;
1544 /* continue looking for endc */
1545 }
1546 else if (*cp == endc)
1547 cnt--;
1548 else if (*cp == startc)
1549 cnt++;
1550 if (cnt)
1551 cp++;
1552 }
1553 if (*cp == endc && eqFound) {
1554
1555 /*
1556 * Now we break this sucker into the lhs and
1557 * rhs. We must null terminate them of course.
1558 */
1559 for (cp = tstr; *cp != '='; cp++)
1560 continue;
1561 pattern.lhs = tstr;
1562 pattern.leftLen = cp - tstr;
1563 *cp++ = '\0';
1564
1565 pattern.rhs = cp;
1566 cnt = 1;
1567 while (cnt) {
1568 if (*cp == endc)
1569 cnt--;
1570 else if (*cp == startc)
1571 cnt++;
1572 if (cnt)
1573 cp++;
1574 }
1575 pattern.rightLen = cp - pattern.rhs;
1576 *cp = '\0';
1577
1578 /*
1579 * SYSV modifications happen through the whole
1580 * string. Note the pattern is anchored at the end.
1581 */
1582 newStr = VarModify(str, VarSYSVMatch,
9edd457e 1583 (void *)&pattern);
984263bc
MD
1584
1585 /*
1586 * Restore the nulled characters
1587 */
1588 pattern.lhs[pattern.leftLen] = '=';
1589 pattern.rhs[pattern.rightLen] = endc;
1590 termc = endc;
1591 } else
1592#endif
1593 {
1594 Error ("Unknown modifier '%c'\n", *tstr);
1595 for (cp = tstr+1;
1596 *cp != ':' && *cp != endc && *cp != '\0';
1597 cp++)
1598 continue;
1599 termc = *cp;
1600 newStr = var_Error;
1601 }
1602 }
1603 }
913800f5 1604 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
984263bc
MD
1605
1606 if (*freePtr) {
1607 free (str);
1608 }
1609 str = newStr;
1610 if (str != var_Error) {
1611 *freePtr = TRUE;
1612 } else {
1613 *freePtr = FALSE;
1614 }
1615 if (termc == '\0') {
1616 Error("Unclosed variable specification for %s", v->name);
1617 } else if (termc == ':') {
1618 *cp++ = termc;
1619 } else {
1620 *cp = termc;
1621 }
1622 tstr = cp;
1623 }
1624 *lengthPtr = tstr - start + 1;
1625 } else {
1626 *lengthPtr = tstr - start + 1;
1627 *tstr = endc;
1628 }
1629
1630 if (v->flags & VAR_FROM_ENV) {
1631 Boolean destroy = FALSE;
1632
1633 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
1634 destroy = TRUE;
1635 } else {
1636 /*
1637 * Returning the value unmodified, so tell the caller to free
1638 * the thing.
1639 */
1640 *freePtr = TRUE;
1641 }
6065a492 1642 free(v->name);
984263bc 1643 Buf_Destroy(v->val, destroy);
9edd457e 1644 free(v);
984263bc
MD
1645 } else if (v->flags & VAR_JUNK) {
1646 /*
1647 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1648 * doesn't try to free a static pointer.
1649 */
1650 if (*freePtr) {
1651 free(str);
1652 }
1653 *freePtr = FALSE;
6065a492 1654 free(v->name);
984263bc 1655 Buf_Destroy(v->val, TRUE);
9edd457e 1656 free(v);
984263bc
MD
1657 if (dynamic) {
1658 str = emalloc(*lengthPtr + 1);
1659 strncpy(str, start, *lengthPtr);
1660 str[*lengthPtr] = '\0';
1661 *freePtr = TRUE;
1662 } else {
1663 str = err ? var_Error : varNoError;
1664 }
1665 }
1666 return (str);
1667}
1668
1669/*-
1670 *-----------------------------------------------------------------------
1671 * Var_Subst --
1672 * Substitute for all variables in the given string in the given context
1673 * If undefErr is TRUE, Parse_Error will be called when an undefined
1674 * variable is encountered.
1675 *
1676 * Results:
1677 * The resulting string.
1678 *
1679 * Side Effects:
1680 * None. The old string must be freed by the caller
1681 *-----------------------------------------------------------------------
1682 */
1683char *
84de9e23 1684Var_Subst (char *var, char *str, GNode *ctxt, Boolean undefErr)
984263bc
MD
1685{
1686 Buffer buf; /* Buffer for forming things */
1687 char *val; /* Value to substitute for a variable */
1688 int length; /* Length of the variable invocation */
1689 Boolean doFree; /* Set true if val should be freed */
1690 static Boolean errorReported; /* Set true if an error has already
1691 * been reported to prevent a plethora
1692 * of messages when recursing */
1693
1694 buf = Buf_Init (MAKE_BSIZE);
1695 errorReported = FALSE;
1696
1697 while (*str) {
1698 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1699 /*
1700 * A dollar sign may be escaped either with another dollar sign.
1701 * In such a case, we skip over the escape character and store the
1702 * dollar sign into the buffer directly.
1703 */
1704 str++;
1705 Buf_AddByte(buf, (Byte)*str);
1706 str++;
1707 } else if (*str != '$') {
1708 /*
1709 * Skip as many characters as possible -- either to the end of
1710 * the string or to the next dollar sign (variable invocation).
1711 */
1712 char *cp;
1713
1714 for (cp = str++; *str != '$' && *str != '\0'; str++)
1715 continue;
1716 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1717 } else {
1718 if (var != NULL) {
1719 int expand;
1720 for (;;) {
1721 if (str[1] != '(' && str[1] != '{') {
6065a492 1722 if (str[1] != *var || var[1] != '\0') {
984263bc
MD
1723 Buf_AddBytes(buf, 2, (Byte *) str);
1724 str += 2;
1725 expand = FALSE;
1726 }
1727 else
1728 expand = TRUE;
1729 break;
1730 }
1731 else {
1732 char *p;
1733
1734 /*
1735 * Scan up to the end of the variable name.
1736 */
1737 for (p = &str[2]; *p &&
1738 *p != ':' && *p != ')' && *p != '}'; p++)
1739 if (*p == '$')
1740 break;
1741 /*
1742 * A variable inside the variable. We cannot expand
1743 * the external variable yet, so we try again with
1744 * the nested one
1745 */
1746 if (*p == '$') {
1747 Buf_AddBytes(buf, p - str, (Byte *) str);
1748 str = p;
1749 continue;
1750 }
1751
1752 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1753 var[p - str - 2] != '\0') {
1754 /*
1755 * Not the variable we want to expand, scan
1756 * until the next variable
1757 */
1758 for (;*p != '$' && *p != '\0'; p++)
1759 continue;
1760 Buf_AddBytes(buf, p - str, (Byte *) str);
1761 str = p;
1762 expand = FALSE;
1763 }
1764 else
1765 expand = TRUE;
1766 break;
1767 }
1768 }
1769 if (!expand)
1770 continue;
1771 }
1772
1773 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
1774
1775 /*
1776 * When we come down here, val should either point to the
1777 * value of this variable, suitably modified, or be NULL.
1778 * Length should be the total length of the potential
1779 * variable invocation (from $ to end character...)
1780 */
1781 if (val == var_Error || val == varNoError) {
1782 /*
1783 * If performing old-time variable substitution, skip over
1784 * the variable and continue with the substitution. Otherwise,
1785 * store the dollar sign and advance str so we continue with
1786 * the string...
1787 */
1788 if (oldVars) {
1789 str += length;
1790 } else if (undefErr) {
1791 /*
1792 * If variable is undefined, complain and skip the
1793 * variable. The complaint will stop us from doing anything
1794 * when the file is parsed.
1795 */
1796 if (!errorReported) {
1797 Parse_Error (PARSE_FATAL,
1798 "Undefined variable \"%.*s\"",length,str);
1799 }
1800 str += length;
1801 errorReported = TRUE;
1802 } else {
1803 Buf_AddByte (buf, (Byte)*str);
1804 str += 1;
1805 }
1806 } else {
1807 /*
1808 * We've now got a variable structure to store in. But first,
1809 * advance the string pointer.
1810 */
1811 str += length;
1812
1813 /*
1814 * Copy all the characters from the variable value straight
1815 * into the new string.
1816 */
1817 Buf_AddBytes (buf, strlen (val), (Byte *)val);
1818 if (doFree) {
9edd457e 1819 free (val);
984263bc
MD
1820 }
1821 }
1822 }
1823 }
1824
1825 Buf_AddByte (buf, '\0');
1826 str = (char *)Buf_GetAll (buf, (int *)NULL);
1827 Buf_Destroy (buf, FALSE);
1828 return (str);
1829}
1830
1831/*-
1832 *-----------------------------------------------------------------------
1833 * Var_GetTail --
1834 * Return the tail from each of a list of words. Used to set the
1835 * System V local variables.
1836 *
1837 * Results:
1838 * The resulting string.
1839 *
1840 * Side Effects:
1841 * None.
1842 *
1843 *-----------------------------------------------------------------------
1844 */
1845char *
84de9e23 1846Var_GetTail(char *file)
984263bc 1847{
9edd457e 1848 return(VarModify(file, VarTail, (void *)0));
984263bc
MD
1849}
1850
1851/*-
1852 *-----------------------------------------------------------------------
1853 * Var_GetHead --
1854 * Find the leading components of a (list of) filename(s).
1855 * XXX: VarHead does not replace foo by ., as (sun) System V make
1856 * does.
1857 *
1858 * Results:
1859 * The leading components.
1860 *
1861 * Side Effects:
1862 * None.
1863 *
1864 *-----------------------------------------------------------------------
1865 */
1866char *
84de9e23 1867Var_GetHead(char *file)
984263bc 1868{
9edd457e 1869 return(VarModify(file, VarHead, (void *)0));
984263bc
MD
1870}
1871
1872/*-
1873 *-----------------------------------------------------------------------
1874 * Var_Init --
1875 * Initialize the module
1876 *
1877 * Results:
1878 * None
1879 *
1880 * Side Effects:
1881 * The VAR_CMD and VAR_GLOBAL contexts are created
1882 *-----------------------------------------------------------------------
1883 */
1884void
84de9e23 1885Var_Init (void)
984263bc
MD
1886{
1887 VAR_GLOBAL = Targ_NewGN ("Global");
1888 VAR_CMD = Targ_NewGN ("Command");
1889 allVars = Lst_Init(FALSE);
1890
1891}
1892
1893
1894void
84de9e23 1895Var_End (void)
984263bc
MD
1896{
1897 Lst_Destroy(allVars, VarDelete);
1898}
1899
1900
1901/****************** PRINT DEBUGGING INFO *****************/
1902static int
84de9e23 1903VarPrintVar (void *vp, void *dummy __unused)
984263bc
MD
1904{
1905 Var *v = (Var *) vp;
1906 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
84de9e23 1907 return (0);
984263bc
MD
1908}
1909
1910/*-
1911 *-----------------------------------------------------------------------
1912 * Var_Dump --
1913 * print all variables in a context
1914 *-----------------------------------------------------------------------
1915 */
1916void
84de9e23 1917Var_Dump (GNode *ctxt)
984263bc 1918{
9edd457e 1919 Lst_ForEach (ctxt->context, VarPrintVar, (void *) 0);
984263bc 1920}