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