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