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