Fix comment indention.
[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 $
95e5cd47 40 * $DragonFly: src/usr.bin/make/var.c,v 1.78 2005/02/10 10:45:59 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 900
12fcaf94
MO
901 /*
902 * It is assumed that Var_Parse() is called with str[0] == '$'
903 */
904
4e473958
MO
905 if (str[1] == '\0') {
906 /*
907 * Error, there is only a dollar sign in the input string.
908 */
962507cc 909 *freePtr = FALSE;
4e473958
MO
910 *lengthPtr = 1;
911 return (err ? var_Error : varNoError);
912
9df78e4a 913 } else if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
4e473958
MO
914 /*
915 * Check if brackets contain a variable name.
916 */
95e5cd47
MO
917 int vlen; /* length of variable name, after embedded variable
918 * expansion */
4e473958 919
984263bc 920 /* build up expanded variable name in this buffer */
6a3d9147 921 Buffer *buf = Buf_Init(MAKE_BSIZE);
984263bc 922
984263bc
MD
923 /*
924 * Skip to the end character or a colon, whichever comes first,
925 * replacing embedded variables as we go.
926 */
12fcaf94 927 startc = str[1];
9df78e4a 928 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
4e473958 929 tstr = str + 2;
12fcaf94 930
12fcaf94
MO
931 while (*tstr != '\0' && *tstr != endc && *tstr != ':') {
932 if (*tstr == '$') {
933 size_t rlen;
934 Boolean rfree;
935 char *rval;
936
937 rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
938 if (rval == var_Error) {
939 Fatal("Error expanding embedded variable.");
940 } else if (rval != NULL) {
941 Buf_Append(buf, rval);
942 if (rfree)
943 free(rval);
944 }
945 tstr += rlen - 1;
946 } else {
947 Buf_AddByte(buf, (Byte)*tstr);
948 }
949 tstr++;
950 }
fbfaa208 951
984263bc
MD
952 if (*tstr == '\0') {
953 /*
954 * If we never did find the end character, return NULL
955 * right now, setting the length to be the distance to
956 * the end of the string, since that's what make does.
957 */
962507cc 958 *freePtr = FALSE;
984263bc
MD
959 *lengthPtr = tstr - str;
960 return (var_Error);
961 }
fbfaa208 962
984263bc 963 haveModifier = (*tstr == ':');
12fcaf94 964 *tstr = '\0'; /* modify input string */
962507cc 965 start = str;
984263bc 966
8294fbb3 967 Buf_AddByte(buf, (Byte)'\0');
4e473958 968 str = Buf_GetAll(buf, (size_t *)NULL); /* REPLACE str */
984263bc
MD
969 vlen = strlen(str);
970
fbfaa208 971 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
962507cc 972
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';
984263bc 996
962507cc 997 v = VarFind(vname, ctxt, 0);
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;
962507cc 1016 *lengthPtr = tstr - start + 1;
984263bc
MD
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 1049 default:
962507cc 1050 dynamic = FALSE;
454224cf 1051 break;
984263bc
MD
1052 }
1053 } else if ((vlen > 2) && (str[0] == '.') &&
fbfaa208 1054 isupper((unsigned char)str[1]) &&
984263bc
MD
1055 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1056 {
1057 int len;
1058
1059 len = vlen - 1;
1060 if ((strncmp(str, ".TARGET", len) == 0) ||
1061 (strncmp(str, ".ARCHIVE", len) == 0) ||
1062 (strncmp(str, ".PREFIX", len) == 0) ||
1063 (strncmp(str, ".MEMBER", len) == 0))
1064 {
1065 dynamic = TRUE;
962507cc
MO
1066 } else {
1067 dynamic = FALSE;
984263bc 1068 }
962507cc
MO
1069 } else {
1070 dynamic = FALSE;
984263bc
MD
1071 }
1072
002d4cd8
MO
1073 if (haveModifier) {
1074 /*
1075 * Still need to get to the end of the variable specification,
1076 * so kludge up a Var structure for the modifications
1077 */
1078 v = VarCreate(str, NULL, VAR_JUNK);
1079
1080 } else {
984263bc
MD
1081 /*
1082 * No modifiers -- have specification length so we can return
1083 * now.
1084 */
1085 *lengthPtr = tstr - start + 1;
1086 *tstr = endc;
1087 if (dynamic) {
1088 str = emalloc(*lengthPtr + 1);
1089 strncpy(str, start, *lengthPtr);
1090 str[*lengthPtr] = '\0';
1091 *freePtr = TRUE;
1092 Buf_Destroy(buf, TRUE);
fbfaa208 1093 return (str);
984263bc 1094 } else {
962507cc 1095 *freePtr = FALSE;
984263bc
MD
1096 Buf_Destroy(buf, TRUE);
1097 return (err ? var_Error : varNoError);
1098 }
002d4cd8 1099 }
962507cc
MO
1100 } else {
1101 dynamic = FALSE;
002d4cd8 1102 }
962507cc 1103 *freePtr = FALSE;
002d4cd8
MO
1104 Buf_Destroy(buf, TRUE);
1105
1106 } else {
1107 /*
1108 * If it's not bounded by braces of some sort, life is much simpler.
1109 * We just need to check for the first character and return the
1110 * value if it exists.
1111 */
1112 char name[2];
1113
1114 name[0] = str[1];
1115 name[1] = '\0';
962507cc
MO
1116 *lengthPtr = 2;
1117
002d4cd8 1118 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
d8aee9f2 1119 if (v == NULL) {
002d4cd8 1120 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
984263bc 1121 /*
002d4cd8
MO
1122 * If substituting a local variable in a non-local context,
1123 * assume it's for dynamic source stuff. We have to handle
1124 * this specially and return the longhand for the variable
1125 * with the dollar sign escaped so it makes it back to the
1126 * caller. Only four of the local variables are treated
1127 * specially as they are the only four that will be set
1128 * when dynamic sources are expanded.
984263bc 1129 */
002d4cd8 1130 /* XXX: It looks like $% and $! are reversed here */
962507cc 1131 *freePtr = FALSE;
002d4cd8
MO
1132 switch (str[1]) {
1133 case '@':
1134 return ("$(.TARGET)");
1135 case '%':
1136 return ("$(.ARCHIVE)");
1137 case '*':
1138 return ("$(.PREFIX)");
1139 case '!':
1140 return ("$(.MEMBER)");
1141 default:
d8aee9f2 1142 return (err ? var_Error : varNoError);
002d4cd8 1143 }
d8aee9f2 1144 } else {
962507cc 1145 *freePtr = FALSE;
d8aee9f2 1146 return (err ? var_Error : varNoError);
984263bc 1147 }
002d4cd8 1148 } else {
962507cc
MO
1149 dynamic = FALSE;
1150 start = str;
1151 *freePtr = FALSE;
002d4cd8 1152 haveModifier = FALSE;
4e473958 1153 startc = 0;
002d4cd8 1154 endc = str[1];
4e473958 1155 tstr = &str[1];
984263bc 1156 }
984263bc
MD
1157 }
1158
1159 if (v->flags & VAR_IN_USE) {
1160 Fatal("Variable %s is recursive.", v->name);
1161 /*NOTREACHED*/
1162 } else {
1163 v->flags |= VAR_IN_USE;
1164 }
12fcaf94 1165
984263bc
MD
1166 /*
1167 * Before doing any modification, we have to make sure the value
1168 * has been fully expanded. If it looks like recursion might be
1169 * necessary (there's a dollar sign somewhere in the variable's value)
1170 * we just call Var_Subst to do any other substitutions that are
1171 * necessary. Note that the value returned by Var_Subst will have
1172 * been dynamically-allocated, so it will need freeing when we
1173 * return.
1174 */
9cf296a4 1175 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
b0ef9278
MO
1176 if (strchr(str, '$') != NULL) {
1177 Buffer *buf;
1178
1179 buf = Var_Subst(NULL, str, ctxt, err);
1180 str = Buf_GetAll(buf, NULL);
1181 Buf_Destroy(buf, FALSE);
1182
984263bc
MD
1183 *freePtr = TRUE;
1184 }
1185
1186 v->flags &= ~VAR_IN_USE;
1187
1188 /*
1189 * Now we need to apply any modifiers the user wants applied.
1190 * These are:
1191 * :M<pattern> words which match the given <pattern>.
1192 * <pattern> is of the standard file
1193 * wildcarding form.
1194 * :S<d><pat1><d><pat2><d>[g]
1195 * Substitute <pat2> for <pat1> in the value
1196 * :C<d><pat1><d><pat2><d>[g]
1197 * Substitute <pat2> for regex <pat1> in the value
1198 * :H Substitute the head of each word
1199 * :T Substitute the tail of each word
1200 * :E Substitute the extension (minus '.') of
1201 * each word
1202 * :R Substitute the root of each word
1203 * (pathname minus the suffix).
1204 * :lhs=rhs Like :S, but the rhs goes to the end of
1205 * the invocation.
1206 * :U Converts variable to upper-case.
1207 * :L Converts variable to lower-case.
1208 */
9a4c88c2 1209 if ((str != NULL) && haveModifier) {
fb150f02 1210 char *cp;
984263bc
MD
1211 /*
1212 * Skip initial colon while putting it back.
1213 */
1214 *tstr++ = ':';
1215 while (*tstr != endc) {
1216 char *newStr; /* New value to return */
1217 char termc; /* Character which terminated scan */
1218
913800f5 1219 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
984263bc 1220 switch (*tstr) {
984263bc
MD
1221 case 'N':
1222 case 'M':
1223 {
1224 char *pattern;
1225 char *cp2;
1226 Boolean copy;
1227
1228 copy = FALSE;
1229 for (cp = tstr + 1;
1230 *cp != '\0' && *cp != ':' && *cp != endc;
1231 cp++)
1232 {
fbfaa208 1233 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
984263bc
MD
1234 copy = TRUE;
1235 cp++;
1236 }
1237 }
1238 termc = *cp;
1239 *cp = '\0';
1240 if (copy) {
1241 /*
1242 * Need to compress the \:'s out of the pattern, so
1243 * allocate enough room to hold the uncompressed
1244 * pattern (note that cp started at tstr+1, so
1245 * cp - tstr takes the null byte into account) and
1246 * compress the pattern into the space.
1247 */
1248 pattern = emalloc(cp - tstr);
1249 for (cp2 = pattern, cp = tstr + 1;
1250 *cp != '\0';
1251 cp++, cp2++)
1252 {
1253 if ((*cp == '\\') &&
1254 (cp[1] == ':' || cp[1] == endc)) {
1255 cp++;
1256 }
1257 *cp2 = *cp;
1258 }
1259 *cp2 = '\0';
1260 } else {
1261 pattern = &tstr[1];
1262 }
1263 if (*tstr == 'M' || *tstr == 'm') {
9a4c88c2 1264 newStr = VarModify(str, VarMatch, pattern);
984263bc 1265 } else {
9a4c88c2 1266 newStr = VarModify(str, VarNoMatch, pattern);
984263bc
MD
1267 }
1268 if (copy) {
1269 free(pattern);
1270 }
1271 break;
1272 }
1273 case 'S':
1274 {
1275 VarPattern pattern;
454224cf 1276 char del;
6a3d9147 1277 Buffer *buf; /* Buffer for patterns */
984263bc
MD
1278
1279 pattern.flags = 0;
454224cf 1280 del = tstr[1];
984263bc
MD
1281 tstr += 2;
1282
1283 /*
1284 * If pattern begins with '^', it is anchored to the
1285 * start of the word -- skip over it and flag pattern.
1286 */
1287 if (*tstr == '^') {
1288 pattern.flags |= VAR_MATCH_START;
1289 tstr += 1;
1290 }
1291
1292 buf = Buf_Init(0);
1293
1294 /*
1295 * Pass through the lhs looking for 1) escaped delimiters,
1296 * '$'s and backslashes (place the escaped character in
1297 * uninterpreted) and 2) unescaped $'s that aren't before
1298 * the delimiter (expand the variable substitution).
1299 * The result is left in the Buffer buf.
1300 */
454224cf 1301 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
984263bc 1302 if ((*cp == '\\') &&
454224cf 1303 ((cp[1] == del) ||
984263bc
MD
1304 (cp[1] == '$') ||
1305 (cp[1] == '\\')))
1306 {
1307 Buf_AddByte(buf, (Byte)cp[1]);
1308 cp++;
1309 } else if (*cp == '$') {
454224cf 1310 if (cp[1] != del) {
984263bc
MD
1311 /*
1312 * If unescaped dollar sign not before the
1313 * delimiter, assume it's a variable
1314 * substitution and recurse.
1315 */
1316 char *cp2;
9cf296a4 1317 size_t len;
984263bc
MD
1318 Boolean freeIt;
1319
1320 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
fcf95e9c 1321 Buf_Append(buf, cp2);
984263bc
MD
1322 if (freeIt) {
1323 free(cp2);
1324 }
1325 cp += len - 1;
1326 } else {
1327 /*
1328 * Unescaped $ at end of pattern => anchor
1329 * pattern at end.
1330 */
1331 pattern.flags |= VAR_MATCH_END;
1332 }
1333 } else {
1334 Buf_AddByte(buf, (Byte)*cp);
1335 }
1336 }
1337
8294fbb3
MO
1338 Buf_AddByte(buf, (Byte)'\0');
1339
984263bc
MD
1340 /*
1341 * If lhs didn't end with the delimiter, complain and
d2ffb6f1 1342 * exit.
984263bc 1343 */
454224cf 1344 if (*cp != del) {
d2ffb6f1 1345 Fatal("Unclosed substitution for %s (%c missing)",
454224cf 1346 v->name, del);
984263bc
MD
1347 }
1348
1349 /*
1350 * Fetch pattern and destroy buffer, but preserve the data
1351 * in it, since that's our lhs. Note that Buf_GetAll
1352 * will return the actual number of bytes, which includes
1353 * the null byte, so we have to decrement the length by
1354 * one.
1355 */
1356 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1357 pattern.leftLen--;
1358 Buf_Destroy(buf, FALSE);
1359
1360 /*
1361 * Now comes the replacement string. Three things need to
1362 * be done here: 1) need to compress escaped delimiters and
1363 * ampersands and 2) need to replace unescaped ampersands
1364 * with the l.h.s. (since this isn't regexp, we can do
1365 * it right here) and 3) expand any variable substitutions.
1366 */
1367 buf = Buf_Init(0);
1368
1369 tstr = cp + 1;
454224cf 1370 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
984263bc 1371 if ((*cp == '\\') &&
454224cf 1372 ((cp[1] == del) ||
984263bc
MD
1373 (cp[1] == '&') ||
1374 (cp[1] == '\\') ||
1375 (cp[1] == '$')))
1376 {
1377 Buf_AddByte(buf, (Byte)cp[1]);
1378 cp++;
454224cf 1379 } else if ((*cp == '$') && (cp[1] != del)) {
984263bc 1380 char *cp2;
9cf296a4 1381 size_t len;
984263bc
MD
1382 Boolean freeIt;
1383
1384 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
fcf95e9c 1385 Buf_Append(buf, cp2);
984263bc
MD
1386 cp += len - 1;
1387 if (freeIt) {
1388 free(cp2);
1389 }
1390 } else if (*cp == '&') {
1391 Buf_AddBytes(buf, pattern.leftLen,
1392 (Byte *)pattern.lhs);
1393 } else {
1394 Buf_AddByte(buf, (Byte)*cp);
1395 }
1396 }
1397
8294fbb3
MO
1398 Buf_AddByte(buf, (Byte)'\0');
1399
984263bc
MD
1400 /*
1401 * If didn't end in delimiter character, complain
1402 */
454224cf 1403 if (*cp != del) {
d2ffb6f1 1404 Fatal("Unclosed substitution for %s (%c missing)",
454224cf 1405 v->name, del);
984263bc
MD
1406 }
1407
1408 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1409 pattern.rightLen--;
1410 Buf_Destroy(buf, FALSE);
1411
1412 /*
1413 * Check for global substitution. If 'g' after the final
1414 * delimiter, substitution is global and is marked that
1415 * way.
1416 */
1417 cp++;
1418 if (*cp == 'g') {
1419 pattern.flags |= VAR_SUB_GLOBAL;
1420 cp++;
1421 }
1422
6065a492
MD
1423 /*
1424 * Global substitution of the empty string causes an
1425 * infinite number of matches, unless anchored by '^'
1426 * (start of string) or '$' (end of string). Catch the
1427 * infinite substitution here.
1428 * Note that flags can only contain the 3 bits we're
1429 * interested in so we don't have to mask unrelated
1430 * bits. We can test for equality.
1431 */
1432 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1433 Fatal("Global substitution of the empty string");
1434
984263bc 1435 termc = *cp;
9a4c88c2 1436 newStr = VarModify(str, VarSubstitute, &pattern);
984263bc
MD
1437 /*
1438 * Free the two strings.
1439 */
1440 free(pattern.lhs);
1441 free(pattern.rhs);
1442 break;
1443 }
1444 case 'C':
1445 {
fb150f02 1446 int delim;
984263bc
MD
1447 VarREPattern pattern;
1448 char *re;
1449 int error;
1450
1451 pattern.flags = 0;
1452 delim = tstr[1];
1453 tstr += 2;
1454
1455 cp = tstr;
1456
1457 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1458 NULL, NULL)) == NULL) {
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 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1470 delim, NULL, NULL, NULL)) == NULL){
1471 free(re);
1472
1473 /* was: goto cleanup */
1474 *lengthPtr = cp - start + 1;
1475 if (*freePtr)
1476 free(str);
1477 if (delim != '\0')
d2ffb6f1 1478 Fatal("Unclosed substitution for %s (%c missing)",
984263bc
MD
1479 v->name, delim);
1480 return (var_Error);
1481 }
1482
1483 for (;; cp++) {
1484 switch (*cp) {
1485 case 'g':
1486 pattern.flags |= VAR_SUB_GLOBAL;
1487 continue;
1488 case '1':
1489 pattern.flags |= VAR_SUB_ONE;
1490 continue;
454224cf
MD
1491 default:
1492 break;
984263bc
MD
1493 }
1494 break;
1495 }
1496
1497 termc = *cp;
1498
1499 error = regcomp(&pattern.re, re, REG_EXTENDED);
1500 free(re);
1501 if (error) {
1502 *lengthPtr = cp - start + 1;
1503 VarREError(error, &pattern.re, "RE substitution error");
1504 free(pattern.replace);
1505 return (var_Error);
1506 }
1507
1508 pattern.nsub = pattern.re.re_nsub + 1;
1509 if (pattern.nsub < 1)
1510 pattern.nsub = 1;
1511 if (pattern.nsub > 10)
1512 pattern.nsub = 10;
1513 pattern.matches = emalloc(pattern.nsub *
1514 sizeof(regmatch_t));
9a4c88c2 1515 newStr = VarModify(str, VarRESubstitute, &pattern);
984263bc
MD
1516 regfree(&pattern.re);
1517 free(pattern.replace);
1518 free(pattern.matches);
1519 break;
1520 }
754c8e77
JS
1521 case 'L':
1522 if (tstr[1] == endc || tstr[1] == ':') {
6a3d9147 1523 Buffer *buf;
754c8e77
JS
1524 buf = Buf_Init(MAKE_BSIZE);
1525 for (cp = str; *cp ; cp++)
fbfaa208 1526 Buf_AddByte(buf, (Byte)tolower(*cp));
754c8e77 1527
8294fbb3 1528 Buf_AddByte(buf, (Byte)'\0');
9cf296a4 1529 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
754c8e77
JS
1530 Buf_Destroy(buf, FALSE);
1531
1532 cp = tstr + 1;
1533 termc = *cp;
1534 break;
1535 }
1536 /* FALLTHROUGH */
372b1ac6
JS
1537 case 'O':
1538 if (tstr[1] == endc || tstr[1] == ':') {
1539 newStr = VarSortWords(str, SortIncreasing);
1540 cp = tstr + 1;
1541 termc = *cp;
1542 break;
1543 }
1544 /* FALLTHROUGH */
984263bc
MD
1545 case 'Q':
1546 if (tstr[1] == endc || tstr[1] == ':') {
fbfaa208 1547 newStr = Var_Quote(str);
984263bc
MD
1548 cp = tstr + 1;
1549 termc = *cp;
1550 break;
1551 }
1552 /*FALLTHRU*/
1553 case 'T':
1554 if (tstr[1] == endc || tstr[1] == ':') {
9a4c88c2 1555 newStr = VarModify(str, VarTail, (void *)NULL);
984263bc
MD
1556 cp = tstr + 1;
1557 termc = *cp;
1558 break;
1559 }
1560 /*FALLTHRU*/
754c8e77
JS
1561 case 'U':
1562 if (tstr[1] == endc || tstr[1] == ':') {
6a3d9147 1563 Buffer *buf;
754c8e77
JS
1564 buf = Buf_Init(MAKE_BSIZE);
1565 for (cp = str; *cp ; cp++)
fbfaa208 1566 Buf_AddByte(buf, (Byte)toupper(*cp));
754c8e77 1567
8294fbb3 1568 Buf_AddByte(buf, (Byte)'\0');
9cf296a4 1569 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
754c8e77
JS
1570 Buf_Destroy(buf, FALSE);
1571
1572 cp = tstr + 1;
1573 termc = *cp;
1574 break;
1575 }
1576 /* FALLTHROUGH */
984263bc
MD
1577 case 'H':
1578 if (tstr[1] == endc || tstr[1] == ':') {
9a4c88c2 1579 newStr = VarModify(str, VarHead, (void *)NULL);
984263bc
MD
1580 cp = tstr + 1;
1581 termc = *cp;
1582 break;
1583 }
1584 /*FALLTHRU*/
1585 case 'E':
1586 if (tstr[1] == endc || tstr[1] == ':') {
9a4c88c2 1587 newStr = VarModify(str, VarSuffix, (void *)NULL);
984263bc
MD
1588 cp = tstr + 1;
1589 termc = *cp;
1590 break;
1591 }
1592 /*FALLTHRU*/
1593 case 'R':
1594 if (tstr[1] == endc || tstr[1] == ':') {
9a4c88c2 1595 newStr = VarModify(str, VarRoot, (void *)NULL);
984263bc
MD
1596 cp = tstr + 1;
1597 termc = *cp;
1598 break;
1599 }
1600 /*FALLTHRU*/
1601#ifdef SUNSHCMD
1602 case 's':
1603 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
230209a1 1604 const char *error;
fa8e78c0
MO
1605 Buffer *buf;
1606
1607 buf = Cmd_Exec(str, &error);
1608 newStr = Buf_GetAll(buf, NULL);
1609 Buf_Destroy(buf, FALSE);
1610
454224cf 1611 if (error)
fbfaa208 1612 Error(error, str);
984263bc
MD
1613 cp = tstr + 2;
1614 termc = *cp;
1615 break;
1616 }
1617 /*FALLTHRU*/
1618#endif
1619 default:
1620 {
1621#ifdef SYSVVARSUB
1622 /*
1623 * This can either be a bogus modifier or a System-V
1624 * substitution command.
1625 */
b632f142
MO
1626 VarPattern pattern;
1627 Boolean eqFound;
1628 int cnt;
984263bc
MD
1629
1630 pattern.flags = 0;
1631 eqFound = FALSE;
1632 /*
1633 * First we make a pass through the string trying
1634 * to verify it is a SYSV-make-style translation:
1635 * it must be: <string1>=<string2>)
1636 */
1637 cp = tstr;
1638 cnt = 1;
1639 while (*cp != '\0' && cnt) {
1640 if (*cp == '=') {
1641 eqFound = TRUE;
1642 /* continue looking for endc */
1643 }
1644 else if (*cp == endc)
1645 cnt--;
1646 else if (*cp == startc)
1647 cnt++;
1648 if (cnt)
1649 cp++;
1650 }
1651 if (*cp == endc && eqFound) {
fb150f02 1652 int delim;
984263bc
MD
1653
1654 /*
1655 * Now we break this sucker into the lhs and
1656 * rhs. We must null terminate them of course.
1657 */
754c8e77
JS
1658 cp = tstr;
1659
1660 delim = '=';
1661 if ((pattern.lhs = VarGetPattern(ctxt,
1662 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1663 NULL)) == 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);
1672 }
1673
1674 delim = endc;
1675 if ((pattern.rhs = VarGetPattern(ctxt,
1676 err, &cp, delim, NULL, &pattern.rightLen,
1677 &pattern)) == NULL) {
1678 /* was: goto cleanup */
1679 *lengthPtr = cp - start + 1;
1680 if (*freePtr)
1681 free(str);
1682 if (delim != '\0')
1683 Fatal("Unclosed substitution for %s (%c missing)",
1684 v->name, delim);
1685 return (var_Error);
984263bc 1686 }
984263bc
MD
1687
1688 /*
1689 * SYSV modifications happen through the whole
1690 * string. Note the pattern is anchored at the end.
1691 */
754c8e77
JS
1692 termc = *--cp;
1693 delim = '\0';
9a4c88c2 1694 newStr = VarModify(str, VarSYSVMatch, &pattern);
984263bc 1695
754c8e77
JS
1696 free(pattern.lhs);
1697 free(pattern.rhs);
1698
984263bc
MD
1699 termc = endc;
1700 } else
1701#endif
1702 {
fbfaa208 1703 Error("Unknown modifier '%c'\n", *tstr);
984263bc
MD
1704 for (cp = tstr+1;
1705 *cp != ':' && *cp != endc && *cp != '\0';
1706 cp++)
1707 continue;
1708 termc = *cp;
1709 newStr = var_Error;
1710 }
1711 }
1712 }
913800f5 1713 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
984263bc
MD
1714
1715 if (*freePtr) {
fbfaa208 1716 free(str);
984263bc
MD
1717 }
1718 str = newStr;
1719 if (str != var_Error) {
1720 *freePtr = TRUE;
1721 } else {
1722 *freePtr = FALSE;
1723 }
1724 if (termc == '\0') {
1725 Error("Unclosed variable specification for %s", v->name);
1726 } else if (termc == ':') {
1727 *cp++ = termc;
1728 } else {
1729 *cp = termc;
1730 }
1731 tstr = cp;
1732 }
1733 *lengthPtr = tstr - start + 1;
1734 } else {
1735 *lengthPtr = tstr - start + 1;
1736 *tstr = endc;
1737 }
1738
1739 if (v->flags & VAR_FROM_ENV) {
1740 Boolean destroy = FALSE;
1741
9cf296a4 1742 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
984263bc
MD
1743 destroy = TRUE;
1744 } else {
1745 /*
1746 * Returning the value unmodified, so tell the caller to free
1747 * the thing.
1748 */
1749 *freePtr = TRUE;
1750 }
5cfd56df 1751 VarDestroy(v, destroy);
984263bc
MD
1752 } else if (v->flags & VAR_JUNK) {
1753 /*
1754 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1755 * doesn't try to free a static pointer.
1756 */
1757 if (*freePtr) {
1758 free(str);
1759 }
1760 *freePtr = FALSE;
5cfd56df 1761 VarDestroy(v, TRUE);
984263bc
MD
1762 if (dynamic) {
1763 str = emalloc(*lengthPtr + 1);
1764 strncpy(str, start, *lengthPtr);
1765 str[*lengthPtr] = '\0';
1766 *freePtr = TRUE;
1767 } else {
1768 str = err ? var_Error : varNoError;
1769 }
1770 }
1771 return (str);
1772}
1773
1774/*-
1775 *-----------------------------------------------------------------------
1776 * Var_Subst --
1777 * Substitute for all variables in the given string in the given context
1778 * If undefErr is TRUE, Parse_Error will be called when an undefined
1779 * variable is encountered.
1780 *
1781 * Results:
1782 * The resulting string.
1783 *
1784 * Side Effects:
1785 * None. The old string must be freed by the caller
1786 *-----------------------------------------------------------------------
1787 */
b0ef9278 1788Buffer *
ea6d42d8 1789Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
984263bc 1790{
b0ef9278
MO
1791 Boolean errorReported;
1792 Buffer *buf; /* Buffer for forming things */
984263bc 1793
b0ef9278
MO
1794 /*
1795 * Set TRUE if an error has already been reported to prevent a
1796 * plethora of messages when recursing.
1797 */
984263bc
MD
1798 errorReported = FALSE;
1799
b0ef9278 1800 buf = Buf_Init(0);
984263bc 1801 while (*str) {
f9402228 1802 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
984263bc
MD
1803 /*
1804 * A dollar sign may be escaped either with another dollar sign.
1805 * In such a case, we skip over the escape character and store the
1806 * dollar sign into the buffer directly.
1807 */
f9402228
MO
1808 Buf_AddByte(buf, (Byte)str[0]);
1809 str += 2;
1810
b0ef9278
MO
1811 } else if (str[0] == '$') {
1812 char *val; /* Value to substitute for a variable */
1813 size_t length; /* Length of the variable invocation */
1814 Boolean doFree; /* Set true if val should be freed */
de3fa3f4
MO
1815 /*
1816 * Variable invocation.
1817 */
984263bc
MD
1818 if (var != NULL) {
1819 int expand;
1820 for (;;) {
9df78e4a 1821 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
eb3f0099
MO
1822 size_t l;
1823 const char *p = str + 2;
984263bc
MD
1824
1825 /*
1826 * Scan up to the end of the variable name.
1827 */
de3fa3f4
MO
1828 while (*p != '\0' &&
1829 *p != ':' &&
1830 *p != CLOSE_PAREN &&
9df78e4a 1831 *p != CLOSE_BRACE &&
de3fa3f4
MO
1832 *p != '$') {
1833 ++p;
1834 }
b0ef9278 1835
984263bc
MD
1836 /*
1837 * A variable inside the variable. We cannot expand
1838 * the external variable yet, so we try again with
1839 * the nested one
1840 */
1841 if (*p == '$') {
76b1c519 1842 Buf_AppendRange(buf, str, p);
984263bc
MD
1843 str = p;
1844 continue;
1845 }
1846
eb3f0099
MO
1847 l = p - (str + 2);
1848 if (var[l] == '\0' && strncmp(var, str + 2, l) == 0) {
b0ef9278
MO
1849 expand = TRUE;
1850 } else {
984263bc
MD
1851 /*
1852 * Not the variable we want to expand, scan
1853 * until the next variable
1854 */
b0ef9278
MO
1855 while (*p != '$' && *p != '\0')
1856 ++p;
1857
76b1c519 1858 Buf_AppendRange(buf, str, p);
984263bc
MD
1859 str = p;
1860 expand = FALSE;
b0ef9278 1861 }
b0ef9278
MO
1862 } else {
1863 /*
1864 * Single letter variable name.
1865 */
eb3f0099 1866 if (var[1] == '\0' && var[0] == str[1]) {
984263bc 1867 expand = TRUE;
b0ef9278
MO
1868 } else {
1869 Buf_AddBytes(buf, 2, (const Byte *)str);
1870 str += 2;
1871 expand = FALSE;
f9402228 1872 }
984263bc 1873 }
b0ef9278 1874 break;
984263bc
MD
1875 }
1876 if (!expand)
1877 continue;
1878 }
1879
fbfaa208 1880 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
984263bc
MD
1881
1882 /*
1883 * When we come down here, val should either point to the
1884 * value of this variable, suitably modified, or be NULL.
1885 * Length should be the total length of the potential
1886 * variable invocation (from $ to end character...)
1887 */
1888 if (val == var_Error || val == varNoError) {
1889 /*
1890 * If performing old-time variable substitution, skip over
1891 * the variable and continue with the substitution. Otherwise,
1892 * store the dollar sign and advance str so we continue with
1893 * the string...
1894 */
1895 if (oldVars) {
1896 str += length;
1897 } else if (undefErr) {
1898 /*
1899 * If variable is undefined, complain and skip the
1900 * variable. The complaint will stop us from doing anything
1901 * when the file is parsed.
1902 */
1903 if (!errorReported) {
fbfaa208 1904 Parse_Error(PARSE_FATAL,
984263bc
MD
1905 "Undefined variable \"%.*s\"",length,str);
1906 }
1907 str += length;
1908 errorReported = TRUE;
1909 } else {
bf2bcf34 1910 Buf_AddByte(buf, (Byte)*str);
984263bc
MD
1911 str += 1;
1912 }
1913 } else {
1914 /*
1915 * We've now got a variable structure to store in. But first,
1916 * advance the string pointer.
1917 */
1918 str += length;
1919
1920 /*
1921 * Copy all the characters from the variable value straight
1922 * into the new string.
1923 */
fcf95e9c 1924 Buf_Append(buf, val);
984263bc 1925 if (doFree) {
fbfaa208 1926 free(val);
984263bc
MD
1927 }
1928 }
b0ef9278
MO
1929 } else {
1930 /*
1931 * Skip as many characters as possible -- either to the end of
1932 * the string or to the next dollar sign (variable invocation).
1933 */
1934 const char *cp = str;
1935
1936 do {
1937 str++;
1938 } while (str[0] != '$' && str[0] != '\0');
1939
1940 Buf_AppendRange(buf, cp, str);
984263bc
MD
1941 }
1942 }
1943
b0ef9278 1944 return (buf);
984263bc
MD
1945}
1946
1947/*-
1948 *-----------------------------------------------------------------------
1949 * Var_GetTail --
1950 * Return the tail from each of a list of words. Used to set the
1951 * System V local variables.
1952 *
1953 * Results:
1954 * The resulting string.
1955 *
1956 * Side Effects:
1957 * None.
1958 *
1959 *-----------------------------------------------------------------------
1960 */
1961char *
84de9e23 1962Var_GetTail(char *file)
984263bc 1963{
8e4eb27a 1964
9a4c88c2 1965 return (VarModify(file, VarTail, (void *)NULL));
984263bc
MD
1966}
1967
1968/*-
1969 *-----------------------------------------------------------------------
1970 * Var_GetHead --
1971 * Find the leading components of a (list of) filename(s).
1972 * XXX: VarHead does not replace foo by ., as (sun) System V make
1973 * does.
1974 *
1975 * Results:
1976 * The leading components.
1977 *
1978 * Side Effects:
1979 * None.
1980 *
1981 *-----------------------------------------------------------------------
1982 */
1983char *
84de9e23 1984Var_GetHead(char *file)
984263bc 1985{
fbfaa208 1986
9a4c88c2 1987 return (VarModify(file, VarHead, (void *)NULL));
984263bc
MD
1988}
1989
1990/*-
1991 *-----------------------------------------------------------------------
1992 * Var_Init --
1993 * Initialize the module
1994 *
1995 * Results:
1996 * None
1997 *
1998 * Side Effects:
1999 * The VAR_CMD and VAR_GLOBAL contexts are created
2000 *-----------------------------------------------------------------------
2001 */
2002void
fbfaa208 2003Var_Init(void)
984263bc 2004{
8e4eb27a 2005
fbfaa208
MO
2006 VAR_GLOBAL = Targ_NewGN("Global");
2007 VAR_CMD = Targ_NewGN("Command");
984263bc
MD
2008}
2009
984263bc
MD
2010/****************** PRINT DEBUGGING INFO *****************/
2011static int
fbfaa208 2012VarPrintVar(void *vp, void *dummy __unused)
984263bc
MD
2013{
2014 Var *v = (Var *) vp;
fbfaa208 2015
9cf296a4 2016 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
84de9e23 2017 return (0);
984263bc
MD
2018}
2019
2020/*-
2021 *-----------------------------------------------------------------------
2022 * Var_Dump --
2023 * print all variables in a context
2024 *-----------------------------------------------------------------------
2025 */
2026void
fbfaa208 2027Var_Dump(GNode *ctxt)
984263bc 2028{
09040c89 2029
0a7e0b85 2030 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);
984263bc 2031}