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