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