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