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