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