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