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