VarParseLong()
[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.139 2005/03/12 11:58:21 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  * This is a harmless return value for Var_Parse that can be used by Var_Subst
104  * to determine if there was an error in parsing -- easier than returning
105  * a flag, as things outside this module don't give a hoot.
106  */
107 char    var_Error[] = "";
108
109 /*
110  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
111  * set false. Why not just use a constant? Well, gcc likes to condense
112  * identical string instances...
113  */
114 static char     varNoError[] = "";
115
116 /*
117  * Internally, variables are contained in four different contexts.
118  *      1) the environment. They may not be changed. If an environment
119  *          variable is appended-to, the result is placed in the global
120  *          context.
121  *      2) the global context. Variables set in the Makefile are located in
122  *          the global context. It is the penultimate context searched when
123  *          substituting.
124  *      3) the command-line context. All variables set on the command line
125  *         are placed in this context. They are UNALTERABLE once placed here.
126  *      4) the local context. Each target has associated with it a context
127  *         list. On this list are located the structures describing such
128  *         local variables as $(@) and $(*)
129  * The four contexts are searched in the reverse order from which they are
130  * listed.
131  */
132 GNode          *VAR_GLOBAL;   /* variables from the makefile */
133 GNode          *VAR_CMD;      /* variables defined on the command-line */
134
135 #define FIND_CMD        0x1   /* look in VAR_CMD when searching */
136 #define FIND_GLOBAL     0x2   /* look in VAR_GLOBAL as well */
137 #define FIND_ENV        0x4   /* look in the environment also */
138
139 #define OPEN_PAREN              '('
140 #define CLOSE_PAREN             ')'
141 #define OPEN_BRACE              '{'
142 #define CLOSE_BRACE             '}'
143
144 /*
145  * Create a Var object.
146  *
147  * @param name          Name of variable.
148  * @param value         Value of variable.
149  * @param flags         Flags set on variable.
150  */
151 static Var *
152 VarCreate(const char name[], const char value[], int flags)
153 {
154         Var *v;
155
156         v = emalloc(sizeof(Var));
157         v->name = estrdup(name);
158         v->val  = Buf_Init(0);
159         v->flags        = flags;
160
161         if (value != NULL) {
162                 Buf_Append(v->val, value);
163         }
164         return (v);
165 }
166
167 /*
168  * Destroy a Var object.
169  *
170  * @param v     Object to destroy.
171  * @param f     true if internal buffer in Buffer object is to be
172  *              removed.
173  */
174 static void
175 VarDestroy(Var *v, Boolean f)
176 {
177
178         Buf_Destroy(v->val, f);
179         free(v->name);
180         free(v);
181 }
182
183 /*-
184  *-----------------------------------------------------------------------
185  * VarCmp  --
186  *      See if the given variable matches the named one. Called from
187  *      Lst_Find when searching for a variable of a given name.
188  *
189  * Results:
190  *      0 if they match. non-zero otherwise.
191  *
192  * Side Effects:
193  *      none
194  *-----------------------------------------------------------------------
195  */
196 static int
197 VarCmp(const void *v, const void *name)
198 {
199
200     return (strcmp(name, ((const Var *)v)->name));
201 }
202
203 /*-
204  *-----------------------------------------------------------------------
205  * VarPossiblyExpand --
206  *      Expand a variable name's embedded variables in the given context.
207  *
208  * Results:
209  *      The contents of name, possibly expanded.
210  *-----------------------------------------------------------------------
211  */
212 static char *
213 VarPossiblyExpand(const char *name, GNode *ctxt)
214 {
215         Buffer  *buf;
216         char    *str;
217         char    *tmp;
218
219         /*
220          * XXX make a temporary copy of the name because Var_Subst insists
221          * on writing into the string.
222          */
223         tmp = estrdup(name);
224         if (strchr(name, '$') != NULL) {
225                 buf = Var_Subst(NULL, tmp, ctxt, 0);
226                 str = Buf_GetAll(buf, NULL);
227                 Buf_Destroy(buf, FALSE);
228
229                 free(tmp);
230                 return (str);
231         } else {
232                 return (tmp);
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 set
434      * here will override anything in a lower context, so there's not much
435      * 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 != (Var *)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) {
468         if ((v->flags & VAR_TO_ENV) == 0) {
469             v->flags |= VAR_TO_ENV;
470             setenv(v->name, Buf_GetAll(v->val, NULL), 1);
471         }
472     } else {
473         Error("Cannot set environment flag on non-existant variable %s", name);
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
508     if (v == NULL) {
509         VarAdd(n, val, ctxt);
510     } else {
511         Buf_AddByte(v->val, (Byte)' ');
512         Buf_Append(v->val, val);
513
514         DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
515                (char *)Buf_GetAll(v->val, (size_t *)NULL)));
516
517         if (v->flags & VAR_FROM_ENV) {
518             /*
519              * If the original variable came from the environment, we
520              * have to install it in the global context (we could place
521              * it in the environment, but then we should provide a way to
522              * export other variables...)
523              */
524             v->flags &= ~VAR_FROM_ENV;
525             Lst_AtFront(&ctxt->context, v);
526         }
527     }
528     free(n);
529 }
530
531 /*-
532  *-----------------------------------------------------------------------
533  * Var_Exists --
534  *      See if the given variable exists.
535  *
536  * Results:
537  *      TRUE if it does, FALSE if it doesn't
538  *
539  * Side Effects:
540  *      None.
541  *
542  *-----------------------------------------------------------------------
543  */
544 Boolean
545 Var_Exists(const char *name, GNode *ctxt)
546 {
547     Var         *v;
548     char        *n;
549
550     n = VarPossiblyExpand(name, ctxt);
551     v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
552     free(n);
553
554     if (v == NULL) {
555         return (FALSE);
556     } else if (v->flags & VAR_FROM_ENV) {
557         VarDestroy(v, TRUE);
558     }
559     return (TRUE);
560 }
561
562 /*-
563  *-----------------------------------------------------------------------
564  * Var_Value --
565  *      Return the value of the named variable in the given context
566  *
567  * Results:
568  *      The value if the variable exists, NULL if it doesn't
569  *
570  * Side Effects:
571  *      None
572  *-----------------------------------------------------------------------
573  */
574 char *
575 Var_Value(const char *name, GNode *ctxt, char **frp)
576 {
577     Var         *v;
578     char        *n;
579
580     n = VarPossiblyExpand(name, ctxt);
581     v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
582     free(n);
583     *frp = NULL;
584     if (v != NULL) {
585         char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
586
587         if (v->flags & VAR_FROM_ENV) {
588             VarDestroy(v, FALSE);
589             *frp = p;
590         }
591         return (p);
592     } else {
593         return (NULL);
594     }
595 }
596
597 /*-
598  *-----------------------------------------------------------------------
599  * VarModify --
600  *      Modify each of the words of the passed string using the given
601  *      function. Used to implement all modifiers.
602  *
603  * Results:
604  *      A string of all the words modified appropriately.
605  *
606  * Side Effects:
607  *      Uses brk_string() so it invalidates any previous call to
608  *      brk_string().
609  *
610  *-----------------------------------------------------------------------
611  */
612 static char *
613 VarModify(const char *str, VarModifyProc *modProc, void *datum)
614 {
615         char    **av;           /* word list [first word does not count] */
616         int     ac;
617         Buffer  *buf;           /* Buffer for the new string */
618         Boolean addSpace;       /* TRUE if need to add a space to the buffer
619                                  * before adding the trimmed word */
620         int     i;
621         char    *result;
622
623         av = brk_string(str, &ac, FALSE);
624
625         buf = Buf_Init(0);
626
627         addSpace = FALSE;
628         for (i = 1; i < ac; i++)
629                 addSpace = (*modProc)(av[i], addSpace, buf, datum);
630
631         result = (char *)Buf_GetAll(buf, (size_t *)NULL);
632         Buf_Destroy(buf, FALSE);
633         return (result);
634 }
635
636 /*-
637  *-----------------------------------------------------------------------
638  * VarSortWords --
639  *      Sort the words in the string.
640  *
641  * Input:
642  *      str             String whose words should be sorted
643  *      cmp             A comparison function to control the ordering
644  *
645  * Results:
646  *      A string containing the words sorted
647  *
648  * Side Effects:
649  *      Uses brk_string() so it invalidates any previous call to
650  *      brk_string().
651  *
652  *-----------------------------------------------------------------------
653  */
654 static char *
655 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
656 {
657         char    **av;
658         int     ac;
659         Buffer  *buf;
660         int     i;
661         char    *result;
662
663         av = brk_string(str, &ac, FALSE);
664         qsort(av + 1, ac - 1, sizeof(char *), cmp);
665
666         buf = Buf_Init(0);
667         for (i = 1; i < ac; i++) {
668                 Buf_Append(buf, av[i]);
669                 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
670         }
671
672         result = (char *)Buf_GetAll(buf, (size_t *)NULL);
673         Buf_Destroy(buf, FALSE);
674         return (result);
675 }
676
677 static int
678 SortIncreasing(const void *l, const void *r)
679 {
680
681         return (strcmp(*(const char* const*)l, *(const char* const*)r));
682 }
683
684 /*-
685  *-----------------------------------------------------------------------
686  * VarGetPattern --
687  *      Pass through the tstr looking for 1) escaped delimiters,
688  *      '$'s and backslashes (place the escaped character in
689  *      uninterpreted) and 2) unescaped $'s that aren't before
690  *      the delimiter (expand the variable substitution unless flags
691  *      has VAR_NOSUBST set).
692  *      Return the expanded string or NULL if the delimiter was missing
693  *      If pattern is specified, handle escaped ampersands, and replace
694  *      unescaped ampersands with the lhs of the pattern.
695  *
696  * Results:
697  *      A string of all the words modified appropriately.
698  *      If length is specified, return the string length of the buffer
699  *      If flags is specified and the last character of the pattern is a
700  *      $ set the VAR_MATCH_END bit of flags.
701  *
702  * Side Effects:
703  *      None.
704  *-----------------------------------------------------------------------
705  */
706 static char *
707 VarGetPattern(GNode *ctxt, int err, const char **tstr, int delim, int *flags,
708     size_t *length, VarPattern *pattern)
709 {
710     const char *cp;
711     Buffer *buf = Buf_Init(0);
712     size_t junk;
713
714     if (length == NULL)
715         length = &junk;
716
717 #define IS_A_MATCH(cp, delim) \
718     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
719      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
720
721     /*
722      * Skim through until the matching delimiter is found;
723      * pick up variable substitutions on the way. Also allow
724      * backslashes to quote the delimiter, $, and \, but don't
725      * touch other backslashes.
726      */
727     for (cp = *tstr; *cp && (*cp != delim); cp++) {
728         if (IS_A_MATCH(cp, delim)) {
729             Buf_AddByte(buf, (Byte)cp[1]);
730             cp++;
731         } else if (*cp == '$') {
732             if (cp[1] == delim) {
733                 if (flags == NULL)
734                     Buf_AddByte(buf, (Byte)*cp);
735                 else
736                     /*
737                      * Unescaped $ at end of pattern => anchor
738                      * pattern at end.
739                      */
740                     *flags |= VAR_MATCH_END;
741             } else {
742                 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
743                     char   *cp2;
744                     size_t len;
745                     Boolean freeIt;
746
747                     /*
748                      * If unescaped dollar sign not before the
749                      * delimiter, assume it's a variable
750                      * substitution and recurse.
751                      */
752                     len = 0;
753                     cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
754                     Buf_Append(buf, cp2);
755                     if (freeIt)
756                         free(cp2);
757                     cp += len - 1;
758                 } else {
759                     const char *cp2 = &cp[1];
760
761                     if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACE) {
762                         /*
763                          * Find the end of this variable reference
764                          * and suck it in without further ado.
765                          * It will be interperated later.
766                          */
767                         int have = *cp2;
768                         int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
769                         int depth = 1;
770
771                         for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
772                             if (cp2[-1] != '\\') {
773                                 if (*cp2 == have)
774                                     ++depth;
775                                 if (*cp2 == want)
776                                     --depth;
777                             }
778                         }
779                         Buf_AppendRange(buf, cp, cp2);
780                         cp = --cp2;
781                     } else
782                         Buf_AddByte(buf, (Byte)*cp);
783                 }
784             }
785         }
786         else if (pattern && *cp == '&')
787             Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
788         else
789             Buf_AddByte(buf, (Byte)*cp);
790     }
791
792     Buf_AddByte(buf, (Byte)'\0');
793
794     if (*cp != delim) {
795         *tstr = cp;
796         *length = 0;
797         return (NULL);
798     } else {
799         char *result;
800         *tstr = ++cp;
801         result = (char *)Buf_GetAll(buf, length);
802         *length -= 1;   /* Don't count the NULL */
803         Buf_Destroy(buf, FALSE);
804         return (result);
805     }
806 }
807
808 /*-
809  *-----------------------------------------------------------------------
810  * Var_Quote --
811  *      Quote shell meta-characters in the string
812  *
813  * Results:
814  *      The quoted string
815  *
816  * Side Effects:
817  *      None.
818  *
819  *-----------------------------------------------------------------------
820  */
821 char *
822 Var_Quote(const char *str)
823 {
824     Buffer       *buf;
825     /* This should cover most shells :-( */
826     static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
827     char          *ret;
828
829     buf = Buf_Init(MAKE_BSIZE);
830     for (; *str; str++) {
831         if (strchr(meta, *str) != NULL)
832             Buf_AddByte(buf, (Byte)'\\');
833         Buf_AddByte(buf, (Byte)*str);
834     }
835     Buf_AddByte(buf, (Byte)'\0');
836     ret = Buf_GetAll(buf, NULL);
837     Buf_Destroy(buf, FALSE);
838     return (ret);
839 }
840
841 /*-
842  *-----------------------------------------------------------------------
843  * VarREError --
844  *      Print the error caused by a regcomp or regexec call.
845  *
846  * Results:
847  *      None.
848  *
849  * Side Effects:
850  *      An error gets printed.
851  *
852  *-----------------------------------------------------------------------
853  */
854 void
855 VarREError(int err, regex_t *pat, const char *str)
856 {
857     char *errbuf;
858     int errlen;
859
860     errlen = regerror(err, pat, 0, 0);
861     errbuf = emalloc(errlen);
862     regerror(err, pat, errbuf, errlen);
863     Error("%s: %s", str, errbuf);
864     free(errbuf);
865 }
866
867 /*
868  * Make sure this variable is fully expanded.
869  */
870 static char *
871 VarExpand(Var *v, GNode *ctxt, Boolean err)
872 {
873         char    *value;
874         char    *result;
875
876         if (v->flags & VAR_IN_USE) {
877                 Fatal("Variable %s is recursive.", v->name);
878                 /* NOTREACHED */
879         }
880
881         v->flags |= VAR_IN_USE;
882
883         /*
884          * Before doing any modification, we have to make sure the
885          * value has been fully expanded. If it looks like recursion
886          * might be necessary (there's a dollar sign somewhere in the
887          * variable's value) we just call Var_Subst to do any other
888          * substitutions that are necessary. Note that the value
889          * returned by Var_Subst will have been
890          * dynamically-allocated, so it will need freeing when we
891          * return.
892          */
893         value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
894         if (strchr(value, '$') == NULL) {
895                 result = strdup(value);
896         } else {
897                 Buffer  *buf;
898
899                 buf = Var_Subst(NULL, value, ctxt, err);
900                 result = Buf_GetAll(buf, NULL);
901                 Buf_Destroy(buf, FALSE);
902         }
903
904         v->flags &= ~VAR_IN_USE;
905
906         return (result);
907 }
908
909 /**
910  * Select only those words that match the modifier.
911  */
912 static char *
913 modifier_M(const char mod[], const char value[], char endc, size_t *consumed)
914 {
915         const char      *cur;
916         const char      *end;
917         char            *patt;
918         char            *ptr;
919         char            *newValue;
920
921         for (cur = mod + 1; *cur != '\0'; cur++) {
922                 if (cur[0] == endc) {
923                         break;
924                 } else if (cur[0] == ':') {
925                         break;
926                 } else if ((cur[0] == '\\') &&
927                            (cur[1] == ':' || cur[1] == endc)) {
928                         cur++;
929                 }
930         }
931         end = cur;
932
933         /*
934          * Compress the \:'s out of the pattern, so allocate enough
935          * room to hold the uncompressed pattern and compress the
936          * pattern into the space. (note that cur started at mod+1
937          * so cur-mod takes the null byte into account)
938          */
939         patt = emalloc(cur - mod);
940         ptr = patt;
941         for (cur = mod + 1; cur != end; cur++) {
942                 if ((cur[0] == '\\') &&
943                     (cur[1] == ':' || cur[1] == endc)) {
944                         cur++;
945                 }
946                 *ptr = *cur;
947                 ptr++;
948         }
949         *ptr = '\0';
950
951         if (*mod == 'M' || *mod == 'm') {
952                 newValue = VarModify(value, VarMatch, patt);
953         } else {
954                 newValue = VarModify(value, VarNoMatch, patt);
955         }
956         free(patt);
957
958         *consumed += (end - mod);
959
960         if (*end == ':') {
961                 *consumed += 1; /* include colon as part of modifier */
962         }
963
964         return (newValue);
965 }
966
967 static char *
968 modifier_S(const char mod[], const char value[], Var *v, GNode *ctxt, Boolean err, size_t *consumed)
969 {
970         VarPattern      pattern;
971         Buffer          *buf;           /* Buffer for patterns */
972         char            delim;
973         const char      *cur;
974         char            *newValue;
975
976         pattern.flags = 0;
977         buf = Buf_Init(0);
978
979         delim = mod[1]; /* used to find end of pattern */
980
981         /*
982          * If pattern begins with '^', it is anchored to the start of the
983          * word -- skip over it and flag pattern.
984          */
985         if (mod[2] == '^') {
986                 pattern.flags |= VAR_MATCH_START;
987                 cur = mod + 3;
988         } else {
989                 cur = mod + 2;
990         }
991
992         /*
993          * Pass through the lhs looking for 1) escaped delimiters, '$'s and
994          * backslashes (place the escaped character in uninterpreted) and 2)
995          * unescaped $'s that aren't before the delimiter (expand the
996          * variable substitution). The result is left in the Buffer buf.
997          */
998         while (cur[0] != delim) {
999                 if (cur[0] == '\0') {
1000                         /*
1001                          * LHS didn't end with the delim, complain and exit.
1002                          */
1003                         Fatal("Unclosed substitution for %s (%c missing)",
1004                               v->name, delim);
1005
1006                 } else if ((cur[0] == '\\') &&
1007                            ((cur[1] == delim) ||
1008                             (cur[1] == '$') ||
1009                             (cur[1] == '\\'))) {
1010                         cur++;  /* skip backslash */
1011                         Buf_AddByte(buf, (Byte) cur[0]);
1012                         cur++;
1013
1014                 } else if (cur[0] == '$') {
1015                         if (cur[1] == delim) {
1016                                 /*
1017                                  * Unescaped $ at end of pattern => anchor
1018                                  * pattern at end.
1019                                  */
1020                                 pattern.flags |= VAR_MATCH_END;
1021                                 cur++;
1022                         } else {
1023                                 /*
1024                                  * If unescaped dollar sign not before the
1025                                  * delimiter, assume it's a variable
1026                                  * substitution and recurse.
1027                                  */
1028                                 char   *cp2;
1029                                 size_t  len;
1030                                 Boolean freeIt;
1031
1032                                 len = 0;
1033                                 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1034                                 cur += len;
1035                                 Buf_Append(buf, cp2);
1036                                 if (freeIt) {
1037                                         free(cp2);
1038                                 }
1039                         }
1040                 } else {
1041                         Buf_AddByte(buf, (Byte)cur[0]);
1042                         cur++;
1043                 }
1044         }
1045         cur++;  /* skip over delim */
1046
1047         /*
1048          * Fetch pattern and destroy buffer, but preserve the data in it,
1049          * since that's our lhs.
1050          */
1051         pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1052         Buf_Destroy(buf, FALSE);
1053
1054         /*
1055          * Now comes the replacement string. Three things need to be done
1056          * here: 1) need to compress escaped delimiters and ampersands and 2)
1057          * need to replace unescaped ampersands with the l.h.s. (since this
1058          * isn't regexp, we can do it right here) and 3) expand any variable
1059          * substitutions.
1060          */
1061         buf = Buf_Init(0);
1062
1063         while (cur[0] != delim) {
1064                 if (cur[0] == '\0') {
1065                         /*
1066                          * Didn't end with delim character, complain
1067                          */
1068                         Fatal("Unclosed substitution for %s (%c missing)",
1069                               v->name, delim);
1070
1071                 } else if ((cur[0] == '\\') &&
1072                     ((cur[1] == delim) ||
1073                      (cur[1] == '&') ||
1074                      (cur[1] == '\\') ||
1075                      (cur[1] == '$'))) {
1076                         cur++;  /* skip backslash */
1077                         Buf_AddByte(buf, (Byte) cur[0]);
1078                         cur++;
1079
1080                 } else if (cur[0] == '$') {
1081                          if (cur[1] == delim) {
1082                                 Buf_AddByte(buf, (Byte) cur[0]);
1083                                 cur++;
1084                         } else {
1085                                 char   *cp2;
1086                                 size_t  len;
1087                                 Boolean freeIt;
1088
1089                                 len = 0;
1090                                 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1091                                 cur += len;
1092                                 Buf_Append(buf, cp2);
1093                                 if (freeIt) {
1094                                         free(cp2);
1095                                 }
1096                         }
1097                 } else if (cur[0] == '&') {
1098                         Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1099                         cur++;
1100                 } else {
1101                         Buf_AddByte(buf, (Byte) cur[0]);
1102                         cur++;
1103                 }
1104         }
1105         cur++;  /* skip over delim */
1106
1107         pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1108         Buf_Destroy(buf, FALSE);
1109
1110         /*
1111          * Check for global substitution. If 'g' after the final delimiter,
1112          * substitution is global and is marked that way.
1113          */
1114         if (cur[0] == 'g') {
1115                 pattern.flags |= VAR_SUB_GLOBAL;
1116                 cur++;
1117         }
1118
1119         /*
1120          * Global substitution of the empty string causes an infinite number
1121          * of matches, unless anchored by '^' (start of string) or '$' (end
1122          * of string). Catch the infinite substitution here. Note that flags
1123          * can only contain the 3 bits we're interested in so we don't have
1124          * to mask unrelated bits. We can test for equality.
1125          */
1126         if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1127                 Fatal("Global substitution of the empty string");
1128
1129         newValue = VarModify(value, VarSubstitute, &pattern);
1130
1131         /*
1132          * Free the two strings.
1133          */
1134         free(pattern.lhs);
1135         free(pattern.rhs);
1136
1137         *consumed += (cur - mod);
1138
1139         if (cur[0] == ':') {
1140                 *consumed += 1; /* include colin as part of modifier */
1141         }
1142
1143         return (newValue);
1144 }
1145
1146 /*
1147  * Now we need to apply any modifiers the user wants applied.
1148  * These are:
1149  *      :M<pattern>
1150  *              words which match the given <pattern>.
1151  *              <pattern> is of the standard file
1152  *              wildcarding form.
1153  *      :S<d><pat1><d><pat2><d>[g]
1154  *              Substitute <pat2> for <pat1> in the value
1155  *      :C<d><pat1><d><pat2><d>[g]
1156  *              Substitute <pat2> for regex <pat1> in the value
1157  *      :H      Substitute the head of each word
1158  *      :T      Substitute the tail of each word
1159  *      :E      Substitute the extension (minus '.') of
1160  *              each word
1161  *      :R      Substitute the root of each word
1162  *              (pathname minus the suffix).
1163  *      :lhs=rhs
1164  *              Like :S, but the rhs goes to the end of
1165  *              the invocation.
1166  *      :U      Converts variable to upper-case.
1167  *      :L      Converts variable to lower-case.
1168  *
1169  * XXXHB update this comment or remove it and point to the man page.
1170  */
1171 static char *
1172 ParseModifier(const char input[], const char tstr[],
1173         char startc, char endc, Boolean dynamic, Var *v,
1174         GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1175 {
1176         char            *rw_str;
1177         const char      *cp;
1178
1179         rw_str = VarExpand(v, ctxt, err);
1180         *freePtr = TRUE;
1181
1182         tstr++;
1183         while (*tstr != endc) {
1184             char        *newStr;    /* New value to return */
1185             char        termc;      /* Character which terminated scan */
1186             Boolean     readonly = FALSE;
1187             size_t      consumed = 0;
1188
1189             DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1190             switch (*tstr) {
1191                 case 'N':
1192                 case 'M':
1193                         readonly = TRUE; /* tstr isn't modified here */
1194
1195                         newStr = modifier_M(tstr, rw_str, endc, &consumed);
1196                         tstr += consumed;
1197                         break;
1198                 case 'S':
1199
1200                         readonly = TRUE; /* tstr isn't modified here */
1201
1202                         newStr = modifier_S(tstr, rw_str, v, ctxt, err, &consumed);
1203                         tstr += consumed;
1204                         break;
1205                 case 'C':
1206                 {
1207                     int         delim;
1208                     VarREPattern    pattern;
1209                     char           *re;
1210                     int             error;
1211
1212                     pattern.flags = 0;
1213                     delim = tstr[1];
1214                     tstr += 2;
1215
1216                     cp = tstr;
1217
1218                     if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1219                         NULL, NULL)) == NULL) {
1220                         /* was: goto cleanup */
1221                         *lengthPtr = cp - input + 1;
1222                         if (*freePtr)
1223                             free(rw_str);
1224                         if (delim != '\0')
1225                             Fatal("Unclosed substitution for %s (%c missing)",
1226                                   v->name, delim);
1227                         return (var_Error);
1228                     }
1229
1230                     if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1231                         delim, NULL, NULL, NULL)) == NULL){
1232                         free(re);
1233
1234                         /* was: goto cleanup */
1235                         *lengthPtr = cp - input + 1;
1236                         if (*freePtr)
1237                             free(rw_str);
1238                         if (delim != '\0')
1239                             Fatal("Unclosed substitution for %s (%c missing)",
1240                                   v->name, delim);
1241                         return (var_Error);
1242                     }
1243
1244                     for (;; cp++) {
1245                         switch (*cp) {
1246                         case 'g':
1247                             pattern.flags |= VAR_SUB_GLOBAL;
1248                             continue;
1249                         case '1':
1250                             pattern.flags |= VAR_SUB_ONE;
1251                             continue;
1252                         default:
1253                             break;
1254                         }
1255                         break;
1256                     }
1257
1258                     termc = *cp;
1259
1260                     error = regcomp(&pattern.re, re, REG_EXTENDED);
1261                     free(re);
1262                     if (error)  {
1263                         *lengthPtr = cp - input + 1;
1264                         VarREError(error, &pattern.re, "RE substitution error");
1265                         free(pattern.replace);
1266                         return (var_Error);
1267                     }
1268
1269                     pattern.nsub = pattern.re.re_nsub + 1;
1270                     if (pattern.nsub < 1)
1271                         pattern.nsub = 1;
1272                     if (pattern.nsub > 10)
1273                         pattern.nsub = 10;
1274                     pattern.matches = emalloc(pattern.nsub *
1275                                               sizeof(regmatch_t));
1276                     newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1277                     regfree(&pattern.re);
1278                     free(pattern.replace);
1279                     free(pattern.matches);
1280                     break;
1281                 }
1282                 case 'L':
1283                     if (tstr[1] == endc || tstr[1] == ':') {
1284                         Buffer *buf;
1285                         buf = Buf_Init(MAKE_BSIZE);
1286                         for (cp = rw_str; *cp ; cp++)
1287                             Buf_AddByte(buf, (Byte)tolower(*cp));
1288
1289                         Buf_AddByte(buf, (Byte)'\0');
1290                         newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1291                         Buf_Destroy(buf, FALSE);
1292
1293                         cp = tstr + 1;
1294                         termc = *cp;
1295                         break;
1296                     }
1297                     /* FALLTHROUGH */
1298                 case 'O':
1299                     if (tstr[1] == endc || tstr[1] == ':') {
1300                         newStr = VarSortWords(rw_str, SortIncreasing);
1301                         cp = tstr + 1;
1302                         termc = *cp;
1303                         break;
1304                     }
1305                     /* FALLTHROUGH */
1306                 case 'Q':
1307                     if (tstr[1] == endc || tstr[1] == ':') {
1308                         newStr = Var_Quote(rw_str);
1309                         cp = tstr + 1;
1310                         termc = *cp;
1311                         break;
1312                     }
1313                     /*FALLTHRU*/
1314                 case 'T':
1315                     if (tstr[1] == endc || tstr[1] == ':') {
1316                         newStr = VarModify(rw_str, VarTail, (void *)NULL);
1317                         cp = tstr + 1;
1318                         termc = *cp;
1319                         break;
1320                     }
1321                     /*FALLTHRU*/
1322                 case 'U':
1323                     if (tstr[1] == endc || tstr[1] == ':') {
1324                         Buffer *buf;
1325                         buf = Buf_Init(MAKE_BSIZE);
1326                         for (cp = rw_str; *cp ; cp++)
1327                             Buf_AddByte(buf, (Byte)toupper(*cp));
1328
1329                         Buf_AddByte(buf, (Byte)'\0');
1330                         newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1331                         Buf_Destroy(buf, FALSE);
1332
1333                         cp = tstr + 1;
1334                         termc = *cp;
1335                         break;
1336                     }
1337                     /* FALLTHROUGH */
1338                 case 'H':
1339                     if (tstr[1] == endc || tstr[1] == ':') {
1340                         newStr = VarModify(rw_str, VarHead, (void *)NULL);
1341                         cp = tstr + 1;
1342                         termc = *cp;
1343                         break;
1344                     }
1345                     /*FALLTHRU*/
1346                 case 'E':
1347                     if (tstr[1] == endc || tstr[1] == ':') {
1348                         newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1349                         cp = tstr + 1;
1350                         termc = *cp;
1351                         break;
1352                     }
1353                     /*FALLTHRU*/
1354                 case 'R':
1355                     if (tstr[1] == endc || tstr[1] == ':') {
1356                         newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1357                         cp = tstr + 1;
1358                         termc = *cp;
1359                         break;
1360                     }
1361                     /*FALLTHRU*/
1362 #ifdef SUNSHCMD
1363                 case 's':
1364                     if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1365                         const char *error;
1366                         Buffer *buf;
1367
1368                         buf = Cmd_Exec(rw_str, &error);
1369                         newStr = Buf_GetAll(buf, NULL);
1370                         Buf_Destroy(buf, FALSE);
1371
1372                         if (error)
1373                             Error(error, rw_str);
1374                         cp = tstr + 2;
1375                         termc = *cp;
1376                         break;
1377                     }
1378                     /*FALLTHRU*/
1379 #endif
1380                 default:
1381                 {
1382 #ifdef SYSVVARSUB
1383                     /*
1384                      * This can either be a bogus modifier or a System-V
1385                      * substitution command.
1386                      */
1387                     VarPattern  pattern;
1388                     Boolean     eqFound;
1389                     int         cnt;
1390
1391                     pattern.flags = 0;
1392                     eqFound = FALSE;
1393                     /*
1394                      * First we make a pass through the string trying
1395                      * to verify it is a SYSV-make-style translation:
1396                      * it must be: <string1>=<string2>)
1397                      */
1398                     cp = tstr;
1399                     cnt = 1;
1400                     while (*cp != '\0' && cnt) {
1401                         if (*cp == '=') {
1402                             eqFound = TRUE;
1403                             /* continue looking for endc */
1404                         }
1405                         else if (*cp == endc)
1406                             cnt--;
1407                         else if (*cp == startc)
1408                             cnt++;
1409                         if (cnt)
1410                             cp++;
1411                     }
1412                     if (*cp == endc && eqFound) {
1413                         int delim;
1414
1415                         /*
1416                          * Now we break this sucker into the lhs and
1417                          * rhs. We must null terminate them of course.
1418                          */
1419                         cp = tstr;
1420
1421                         delim = '=';
1422                         if ((pattern.lhs = VarGetPattern(ctxt,
1423                             err, &cp, delim, &pattern.flags, &pattern.leftLen,
1424                             NULL)) == NULL) {
1425                                 /* was: goto cleanup */
1426                                 *lengthPtr = cp - input + 1;
1427                                 if (*freePtr)
1428                                     free(rw_str);
1429                                 if (delim != '\0')
1430                                     Fatal("Unclosed substitution for %s (%c missing)",
1431                                           v->name, delim);
1432                                 return (var_Error);
1433                         }
1434
1435                         delim = endc;
1436                         if ((pattern.rhs = VarGetPattern(ctxt,
1437                             err, &cp, delim, NULL, &pattern.rightLen,
1438                             &pattern)) == NULL) {
1439                                 /* was: goto cleanup */
1440                                 *lengthPtr = cp - input + 1;
1441                                 if (*freePtr)
1442                                     free(rw_str);
1443                                 if (delim != '\0')
1444                                     Fatal("Unclosed substitution for %s (%c missing)",
1445                                           v->name, delim);
1446                                 return (var_Error);
1447                         }
1448
1449                         /*
1450                          * SYSV modifications happen through the whole
1451                          * string. Note the pattern is anchored at the end.
1452                          */
1453                         termc = *--cp;
1454                         delim = '\0';
1455                         newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1456
1457                         free(pattern.lhs);
1458                         free(pattern.rhs);
1459
1460                         termc = endc;
1461                     } else
1462 #endif
1463                     {
1464                         Error("Unknown modifier '%c'\n", *tstr);
1465                         for (cp = tstr+1;
1466                              *cp != ':' && *cp != endc && *cp != '\0';
1467                              cp++)
1468                                  continue;
1469                         termc = *cp;
1470                         newStr = var_Error;
1471                     }
1472                 }
1473             }
1474
1475             DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1476             if (*freePtr) {
1477                     free(rw_str);
1478             }
1479             rw_str = newStr;
1480             if (rw_str != var_Error) {
1481                     *freePtr = TRUE;
1482             } else {
1483                     *freePtr = FALSE;
1484             }
1485
1486             if (readonly == FALSE) {
1487                     if (termc == '\0') {
1488                             Error("Unclosed variable specification for %s",
1489                                   v->name);
1490                     } else if (termc == ':') {
1491                             cp++;
1492                     } else {
1493                     }
1494                     tstr = cp;
1495             }
1496         }
1497
1498         if (v->flags & VAR_FROM_ENV) {
1499             if (rw_str == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1500                 /*
1501                  * Returning the value unmodified, so tell the caller to free
1502                  * the thing.
1503                  */
1504                 *freePtr = TRUE;
1505                 *lengthPtr = tstr - input + 1;
1506                 VarDestroy(v, FALSE);
1507                 return (rw_str);
1508             } else {
1509                 *lengthPtr = tstr - input + 1;
1510                 VarDestroy(v, TRUE);
1511                 return (rw_str);
1512             }
1513         } else if (v->flags & VAR_JUNK) {
1514             /*
1515              * Perform any free'ing needed and set *freePtr to FALSE so the caller
1516              * doesn't try to free a static pointer.
1517              */
1518             if (*freePtr) {
1519                 free(rw_str);
1520             }
1521             if (dynamic) {
1522                 *freePtr = FALSE;
1523                 *lengthPtr = tstr - input + 1;
1524                 VarDestroy(v, TRUE);
1525                 rw_str = emalloc(*lengthPtr + 1);
1526                 strncpy(rw_str, input, *lengthPtr);
1527                 rw_str[*lengthPtr] = '\0';
1528                 *freePtr = TRUE;
1529                 return (rw_str);
1530             } else {
1531                 *freePtr = FALSE;
1532                 *lengthPtr = tstr - input + 1;
1533                 VarDestroy(v, TRUE);
1534                 return (err ? var_Error : varNoError);
1535             }
1536         } else {
1537             *lengthPtr = tstr - input + 1;
1538             return (rw_str);
1539         }
1540 }
1541
1542 static char *
1543 ParseRest(const char input[], const char ptr[], char startc, char endc, Buffer *buf, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1544 {
1545         const char      *const tstr = ptr;
1546         size_t          consumed = tstr - (input - 1) + 1;
1547         const char      *vname;
1548         size_t          vlen;
1549
1550         Var     *v;
1551         Boolean haveModifier;
1552         Boolean dynamic;        /* TRUE if the variable is local and we're
1553                                  * expanding it in a non-local context. This
1554                                  * is done to support dynamic sources. The
1555                                  * result is just the invocation, unaltered */
1556
1557         vname = Buf_GetAll(buf, &vlen);
1558
1559         input--;
1560         haveModifier = (*tstr == ':');
1561         dynamic = FALSE;
1562
1563         v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1564         if (v != NULL) {
1565                 if (haveModifier) {
1566                         return (ParseModifier(input, tstr,
1567                                         startc, endc, dynamic, v,
1568                                         ctxt, err, lengthPtr, freePtr));
1569                 } else {
1570                         char    *result;
1571
1572                         result = VarExpand(v, ctxt, err);
1573
1574                         if (v->flags & VAR_FROM_ENV) {
1575                                 VarDestroy(v, TRUE);
1576                         }
1577
1578                         *freePtr = TRUE;
1579                         *lengthPtr = consumed;
1580                         return (result);
1581                 }
1582         }
1583
1584         if ((ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL)) {
1585                 /*
1586                  * Check for D and F forms of local variables since we're in
1587                  * a local context and the name is the right length.
1588                  */
1589                 if ((vlen == 2) &&
1590                     (vname[1] == 'F' || vname[1] == 'D') &&
1591                     (strchr("!%*<>@", vname[0]) != NULL)) {
1592                         char    name[2];
1593                         char    *val;
1594
1595                         /*
1596                          * Well, it's local -- go look for it.
1597                          */
1598                         name[0] = vname[0];
1599                         name[1] = '\0';
1600
1601                         v = VarFind(name, ctxt, 0);
1602                         if (v != NULL) {
1603                                 if (haveModifier) {
1604                                         return (ParseModifier(input, tstr,
1605                                                         startc, endc, dynamic, v,
1606                                                         ctxt, err, lengthPtr, freePtr));
1607                                 } else {
1608                                         /*
1609                                          * No need for nested expansion or
1610                                          * anything, as we're the only one
1611                                          * who sets these things and we sure
1612                                          * don't put nested invocations in
1613                                          * them...
1614                                          */
1615                                         val = (char *)Buf_GetAll(v->val, (size_t *) NULL);
1616
1617                                         if (vname[1] == 'D') {
1618                                                 val = VarModify(val, VarHead, (void *)NULL);
1619                                         } else {
1620                                                 val = VarModify(val, VarTail, (void *)NULL);
1621                                         }
1622                                         /*
1623                                          * Resulting string is dynamically
1624                                          * allocated, so tell caller to free
1625                                          * it.
1626                                          */
1627                                         *freePtr = TRUE;
1628                                         *lengthPtr = consumed;
1629                                         return (val);
1630                                 }
1631                         }
1632                 }
1633         } else {
1634                 if (((vlen == 1)) ||
1635                     ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1636                         /*
1637                          * If substituting a local variable in a non-local
1638                          * context, assume it's for dynamic source stuff. We
1639                          * have to handle this specially and return the
1640                          * longhand for the variable with the dollar sign
1641                          * escaped so it makes it back to the caller. Only
1642                          * four of the local variables are treated specially
1643                          * as they are the only four that will be set when
1644                          * dynamic sources are expanded.
1645                          */
1646                         if (strchr("!%*@", vname[0]) != NULL) {
1647                                 dynamic = TRUE;
1648                         }
1649                 }
1650                 if ((vlen > 2) &&
1651                     (vname[0] == '.') &&
1652                     isupper((unsigned char)vname[1])) {
1653                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1654                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1655                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1656                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1657                                 dynamic = TRUE;
1658                         }
1659                 }
1660         }
1661
1662         if (haveModifier) {
1663                 /*
1664                  * Still need to get to the end of the variable
1665                  * specification, so kludge up a Var structure for
1666                  * the modifications
1667                  */
1668                 v = VarCreate(vname, NULL, VAR_JUNK);
1669
1670                 return (ParseModifier(input, tstr,
1671                                       startc, endc, dynamic, v,
1672                                     ctxt, err, lengthPtr, freePtr));
1673         } else {
1674                 /*
1675                  * No modifiers -- have specification length so we
1676                  * can return now.
1677                  */
1678                 if (dynamic) {
1679                         char   *result;
1680
1681                         result = emalloc(consumed + 1);
1682                         strncpy(result, input, consumed);
1683                         result[consumed] = '\0';
1684
1685                         *freePtr = TRUE;
1686                         *lengthPtr = consumed;
1687
1688                         return (result);
1689                 } else {
1690                         *freePtr = FALSE;
1691                         *lengthPtr = consumed;
1692
1693                         return (err ? var_Error : varNoError);
1694                 }
1695         }
1696 }
1697
1698 /**
1699  * Parse a multi letter variable name, and return it's value.
1700  */
1701 static char *
1702 VarParseLong(const char input[], GNode *ctxt, Boolean err,
1703         size_t *consumed, Boolean *freePtr)
1704 {
1705         Buffer          *buf;
1706         char            endc;   /* Ending character when variable in parens
1707                                  * or braces */
1708         char            startc; /* Starting character when variable in parens
1709                                  * or braces */
1710         const char      *ptr;
1711         char            *result;
1712
1713         buf = Buf_Init(MAKE_BSIZE);
1714
1715         /*
1716          * Process characters until we reach an end character or a
1717          * colon, replacing embedded variables as we go.
1718          */
1719         startc = input[0];
1720         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1721         ptr = input + 1;
1722
1723         while (*ptr != endc && *ptr != ':') {
1724                 if (*ptr == '\0') {
1725                         /*
1726                          * If we did not find the end character,
1727                          * return var_Error right now, setting the
1728                          * length to be the distance to the end of
1729                          * the string, since that's what make does.
1730                          */
1731                         *freePtr = FALSE;
1732                         *consumed += ptr - input;
1733                         Buf_Destroy(buf, TRUE);
1734                         return (var_Error);
1735
1736                 } else if (*ptr == '$') {
1737                         size_t  rlen;
1738                         Boolean rfree;
1739                         char    *rval;
1740
1741                         rlen = 0;
1742                         rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1743                         if (rval == var_Error) {
1744                                 Fatal("Error expanding embedded variable.");
1745                         }
1746                         Buf_Append(buf, rval);
1747                         if (rfree)
1748                                 free(rval);
1749                         ptr += rlen - 1;
1750                 } else {
1751                         Buf_AddByte(buf, (Byte)*ptr);
1752                 }
1753                 ptr++;
1754         }
1755
1756         result = ParseRest(input, ptr, startc, endc, buf, ctxt, err, consumed, freePtr);
1757
1758         Buf_Destroy(buf, TRUE);
1759         return (result);
1760 }
1761
1762 /**
1763  * Parse a single letter variable name, and return it's value.
1764  */
1765 static char *
1766 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1767         size_t *consumed, Boolean *freePtr)
1768 {
1769         char    name[2];
1770         Var     *v;
1771
1772         name[0] = input[0];
1773         name[1] = '\0';
1774
1775         /* consume character */
1776         *consumed += 1;
1777
1778         v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1779         if (v != NULL) {
1780                 char   *result;
1781
1782                 result = VarExpand(v, ctxt, err);
1783
1784                 if (v->flags & VAR_FROM_ENV) {
1785                         VarDestroy(v, TRUE);
1786                 }
1787
1788                 *freePtr = TRUE;
1789                 return (result);
1790         }
1791
1792         /*
1793          * If substituting a local variable in a non-local context, assume
1794          * it's for dynamic source stuff. We have to handle this specially
1795          * and return the longhand for the variable with the dollar sign
1796          * escaped so it makes it back to the caller. Only four of the local
1797          * variables are treated specially as they are the only four that
1798          * will be set when dynamic sources are expanded.
1799          */
1800         if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1801
1802                 /* XXX: It looks like $% and $! are reversed here */
1803                 switch (name[0]) {
1804                 case '@':
1805                         *freePtr = TRUE;
1806                         return (estrdup("$(.TARGET)"));
1807                 case '%':
1808                         *freePtr = TRUE;
1809                         return (estrdup("$(.ARCHIVE)"));
1810                 case '*':
1811                         *freePtr = TRUE;
1812                         return (estrdup("$(.PREFIX)"));
1813                 case '!':
1814                         *freePtr = TRUE;
1815                         return (estrdup("$(.MEMBER)"));
1816                 default:
1817                         *freePtr = FALSE;
1818                         return (err ? var_Error : varNoError);
1819                 }
1820         }
1821
1822         /*
1823          * Variable name was not found.
1824          */
1825         *freePtr = FALSE;
1826         return (err ? var_Error : varNoError);
1827 }
1828
1829 /*-
1830  *-----------------------------------------------------------------------
1831  * Var_Parse --
1832  *      Given the start of a variable invocation, extract the variable
1833  *      name and find its value, then modify it according to the
1834  *      specification.
1835  *
1836  * Results:
1837  *      The value of the variable or var_Error if the specification
1838  *      is invalid.  The number of characters in the specification
1839  *      is placed in the variable pointed to by consumed.  (for
1840  *      invalid specifications, this is just 2 to skip the '$' and
1841  *      the following letter, or 1 if '$' was the last character
1842  *      in the string).  A Boolean in *freePtr telling whether the
1843  *      returned string should be freed by the caller.
1844  *
1845  * Side Effects:
1846  *      None.
1847  *
1848  * Assumption:
1849  *      It is assumed that Var_Parse() is called with input[0] == '$'.
1850  *
1851  *-----------------------------------------------------------------------
1852  */
1853 char *
1854 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1855         size_t *consumed, Boolean *freePtr)
1856 {
1857         /* assert(input[0] == '$'); */
1858
1859         /* consume '$' */
1860         input += 1;
1861         *consumed += 1;
1862
1863         if (input[0] == '\0') {
1864                 /* Error, there is only a dollar sign in the input string. */
1865                 *freePtr = FALSE;
1866                 return (err ? var_Error : varNoError);
1867
1868         } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1869                 /* multi letter variable name */
1870                 return (VarParseLong(input, ctxt, err, consumed, freePtr));
1871
1872         } else {
1873                 /* single letter variable name */
1874                 return (VarParseShort(input, ctxt, err, consumed, freePtr));
1875         }
1876 }
1877
1878 /*-
1879  *-----------------------------------------------------------------------
1880  * Var_Subst  --
1881  *      Substitute for all variables in the given string in the given context
1882  *      If undefErr is TRUE, Parse_Error will be called when an undefined
1883  *      variable is encountered.
1884  *
1885  * Results:
1886  *      The resulting string.
1887  *
1888  * Side Effects:
1889  *      None. The old string must be freed by the caller
1890  *-----------------------------------------------------------------------
1891  */
1892 Buffer *
1893 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1894 {
1895     Boolean     errorReported;
1896     Buffer      *buf;           /* Buffer for forming things */
1897
1898     /*
1899      * Set TRUE if an error has already been reported to prevent a
1900      * plethora of messages when recursing.
1901      * XXXHB this comment sounds wrong.
1902      */
1903     errorReported = FALSE;
1904
1905     buf = Buf_Init(0);
1906     while (*str) {
1907         if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1908             /*
1909              * A dollar sign may be escaped either with another dollar sign.
1910              * In such a case, we skip over the escape character and store the
1911              * dollar sign into the buffer directly.
1912              */
1913             Buf_AddByte(buf, (Byte)str[0]);
1914             str += 2;
1915
1916         } else if (str[0] == '$') {
1917             char        *val;   /* Value to substitute for a variable */
1918             size_t      length; /* Length of the variable invocation */
1919             Boolean     doFree; /* Set true if val should be freed */
1920
1921             /*
1922              * Variable invocation.
1923              */
1924             if (var != NULL) {
1925                 int expand;
1926                 for (;;) {
1927                     if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1928                         size_t          ln;
1929                         const char      *p = str + 2;
1930
1931                         /*
1932                          * Scan up to the end of the variable name.
1933                          */
1934                         while (*p != '\0' &&
1935                                *p != ':' &&
1936                                *p != CLOSE_PAREN &&
1937                                *p != CLOSE_BRACE &&
1938                                *p != '$') {
1939                             ++p;
1940                         }
1941
1942                         /*
1943                          * A variable inside the variable. We cannot expand
1944                          * the external variable yet, so we try again with
1945                          * the nested one
1946                          */
1947                         if (*p == '$') {
1948                             Buf_AppendRange(buf, str, p);
1949                             str = p;
1950                             continue;
1951                         }
1952
1953                         ln = p - (str + 2);
1954                         if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1955                             expand = TRUE;
1956                         } else {
1957                             /*
1958                              * Not the variable we want to expand, scan
1959                              * until the next variable
1960                              */
1961                             while (*p != '$' && *p != '\0')
1962                                 p++;
1963
1964                             Buf_AppendRange(buf, str, p);
1965                             str = p;
1966                             expand = FALSE;
1967                         }
1968                     } else {
1969                         /*
1970                          * Single letter variable name
1971                          */
1972                         if (var[1] == '\0' && var[0] == str[1]) {
1973                             expand = TRUE;
1974                         } else {
1975                             Buf_AddBytes(buf, 2, (const Byte *)str);
1976                             str += 2;
1977                             expand = FALSE;
1978                         }
1979                     }
1980                     break;
1981                 }
1982                 if (!expand)
1983                     continue;
1984             }
1985
1986             length = 0;
1987             val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1988
1989             /*
1990              * When we come down here, val should either point to the
1991              * value of this variable, suitably modified, or be NULL.
1992              * Length should be the total length of the potential
1993              * variable invocation (from $ to end character...)
1994              */
1995             if (val == var_Error || val == varNoError) {
1996                 /*
1997                  * If performing old-time variable substitution, skip over
1998                  * the variable and continue with the substitution. Otherwise,
1999                  * store the dollar sign and advance str so we continue with
2000                  * the string...
2001                  */
2002                 if (oldVars) {
2003                     str += length;
2004                 } else if (undefErr) {
2005                     /*
2006                      * If variable is undefined, complain and skip the
2007                      * variable. The complaint will stop us from doing anything
2008                      * when the file is parsed.
2009                      */
2010                     if (!errorReported) {
2011                         Parse_Error(PARSE_FATAL,
2012                                      "Undefined variable \"%.*s\"",length,str);
2013                     }
2014                     str += length;
2015                     errorReported = TRUE;
2016                 } else {
2017                     Buf_AddByte(buf, (Byte)*str);
2018                     str += 1;
2019                 }
2020             } else {
2021                 /*
2022                  * We've now got a variable structure to store in. But first,
2023                  * advance the string pointer.
2024                  */
2025                 str += length;
2026
2027                 /*
2028                  * Copy all the characters from the variable value straight
2029                  * into the new string.
2030                  */
2031                 Buf_Append(buf, val);
2032                 if (doFree) {
2033                     free(val);
2034                 }
2035             }
2036         } else {
2037             /*
2038              * Skip as many characters as possible -- either to the end of
2039              * the string or to the next dollar sign (variable invocation).
2040              */
2041             const char *cp = str;
2042
2043             do {
2044                 str++;
2045             } while (str[0] != '$' && str[0] != '\0');
2046
2047             Buf_AppendRange(buf, cp, str);
2048         }
2049     }
2050
2051     return (buf);
2052 }
2053
2054 /*-
2055  *-----------------------------------------------------------------------
2056  * Var_GetTail --
2057  *      Return the tail from each of a list of words. Used to set the
2058  *      System V local variables.
2059  *
2060  * Results:
2061  *      The resulting string.
2062  *
2063  * Side Effects:
2064  *      None.
2065  *
2066  *-----------------------------------------------------------------------
2067  */
2068 char *
2069 Var_GetTail(char *file)
2070 {
2071
2072     return (VarModify(file, VarTail, (void *)NULL));
2073 }
2074
2075 /*-
2076  *-----------------------------------------------------------------------
2077  * Var_GetHead --
2078  *      Find the leading components of a (list of) filename(s).
2079  *      XXX: VarHead does not replace foo by ., as (sun) System V make
2080  *      does.
2081  *
2082  * Results:
2083  *      The leading components.
2084  *
2085  * Side Effects:
2086  *      None.
2087  *
2088  *-----------------------------------------------------------------------
2089  */
2090 char *
2091 Var_GetHead(char *file)
2092 {
2093
2094     return (VarModify(file, VarHead, (void *)NULL));
2095 }
2096
2097 /*-
2098  *-----------------------------------------------------------------------
2099  * Var_Init --
2100  *      Initialize the module
2101  *
2102  * Results:
2103  *      None
2104  *
2105  * Side Effects:
2106  *      The VAR_CMD and VAR_GLOBAL contexts are created
2107  *-----------------------------------------------------------------------
2108  */
2109 void
2110 Var_Init(void)
2111 {
2112
2113     VAR_GLOBAL = Targ_NewGN("Global");
2114     VAR_CMD = Targ_NewGN("Command");
2115 }
2116
2117 /*-
2118  *-----------------------------------------------------------------------
2119  * Var_Dump --
2120  *      print all variables in a context
2121  *-----------------------------------------------------------------------
2122  */
2123 void
2124 Var_Dump(const GNode *ctxt)
2125 {
2126         const LstNode   *ln;
2127         const Var       *v;
2128
2129         LST_FOREACH(ln, &ctxt->context) {
2130                 v = Lst_Datum(ln);
2131                 printf("%-16s = %s\n", v->name,
2132                     (const char *)Buf_GetAll(v->val, NULL));
2133         }
2134 }