patch-7.156
[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.173 2005/03/20 12:22:46 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
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, Buf_Data(v->val)));
515
516                 if (v->flags & VAR_FROM_ENV) {
517                         /*
518                          * If the original variable came from the
519                          * environment, we have to install it in the global
520                          * context (we could place it in the environment, but
521                          * then we should provide a way to export other
522                          * 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 = Buf_Data(v->val);
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
622         av = brk_string(str, &ac, FALSE);
623
624         buf = Buf_Init(0);
625
626         addSpace = FALSE;
627         for (i = 1; i < ac; i++)
628                 addSpace = (*modProc)(av[i], addSpace, buf, datum);
629
630         return (Buf_Peel(buf));
631 }
632
633 /*-
634  *-----------------------------------------------------------------------
635  * VarSortWords --
636  *      Sort the words in the string.
637  *
638  * Input:
639  *      str             String whose words should be sorted
640  *      cmp             A comparison function to control the ordering
641  *
642  * Results:
643  *      A string containing the words sorted
644  *
645  * Side Effects:
646  *      Uses brk_string() so it invalidates any previous call to
647  *      brk_string().
648  *
649  *-----------------------------------------------------------------------
650  */
651 static char *
652 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
653 {
654         char    **av;
655         int     ac;
656         Buffer  *buf;
657         int     i;
658
659         av = brk_string(str, &ac, FALSE);
660         qsort(av + 1, ac - 1, sizeof(char *), cmp);
661
662         buf = Buf_Init(0);
663         for (i = 1; i < ac; i++) {
664                 Buf_Append(buf, av[i]);
665                 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
666         }
667
668         return (Buf_Peel(buf));
669 }
670
671 static int
672 SortIncreasing(const void *l, const void *r)
673 {
674
675         return (strcmp(*(const char* const*)l, *(const char* const*)r));
676 }
677
678 /*-
679  *-----------------------------------------------------------------------
680  * VarGetPattern --
681  *      Pass through the tstr looking for 1) escaped delimiters,
682  *      '$'s and backslashes (place the escaped character in
683  *      uninterpreted) and 2) unescaped $'s that aren't before
684  *      the delimiter (expand the variable substitution).
685  *      Return the expanded string or NULL if the delimiter was missing
686  *      If pattern is specified, handle escaped ampersands, and replace
687  *      unescaped ampersands with the lhs of the pattern.
688  *
689  * Results:
690  *      A string of all the words modified appropriately.
691  *      If length is specified, return the string length of the buffer
692  *      If flags is specified and the last character of the pattern is a
693  *      $ set the VAR_MATCH_END bit of flags.
694  *
695  * Side Effects:
696  *      None.
697  *-----------------------------------------------------------------------
698  */
699 static char *
700 VarGetPattern(VarParser *vp, int delim, int *flags,
701     size_t *length, VarPattern *patt)
702 {
703         Buffer          *buf;
704
705         buf = Buf_Init(0);
706
707         /*
708          * Skim through until the matching delimiter is found; pick up
709          * variable substitutions on the way. Also allow backslashes to quote
710          * the delimiter, $, and \, but don't touch other backslashes.
711          */
712         while (*vp->ptr != '\0') {
713                 if (*vp->ptr == delim) {
714                         char   *result;
715
716                         result = (char *)Buf_GetAll(buf, length);
717                         Buf_Destroy(buf, FALSE);
718                         return (result);
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_AddBytes(buf, patt->leftLen, (Byte *)patt->lhs);
762                         vp->ptr++;
763                 } else {
764                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
765                         vp->ptr++;
766                 }
767         }
768
769         if (length != NULL) {
770                 *length = 0;
771         }
772         Buf_Destroy(buf, TRUE);
773         return (NULL);
774 }
775
776 /*-
777  *-----------------------------------------------------------------------
778  * Var_Quote --
779  *      Quote shell meta-characters in the string
780  *
781  * Results:
782  *      The quoted string
783  *
784  * Side Effects:
785  *      None.
786  *
787  *-----------------------------------------------------------------------
788  */
789 char *
790 Var_Quote(const char *str)
791 {
792         Buffer *buf;
793         /* This should cover most shells :-( */
794         static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
795
796         buf = Buf_Init(MAKE_BSIZE);
797         for (; *str; str++) {
798                 if (strchr(meta, *str) != NULL)
799                         Buf_AddByte(buf, (Byte)'\\');
800                 Buf_AddByte(buf, (Byte)*str);
801         }
802
803         return (Buf_Peel(buf));
804 }
805
806 /*-
807  *-----------------------------------------------------------------------
808  * VarREError --
809  *      Print the error caused by a regcomp or regexec call.
810  *
811  * Results:
812  *      None.
813  *
814  * Side Effects:
815  *      An error gets printed.
816  *
817  *-----------------------------------------------------------------------
818  */
819 void
820 VarREError(int err, regex_t *pat, const char *str)
821 {
822         char   *errbuf;
823         int     errlen;
824
825         errlen = regerror(err, pat, 0, 0);
826         errbuf = emalloc(errlen);
827         regerror(err, pat, errbuf, errlen);
828         Error("%s: %s", str, errbuf);
829         free(errbuf);
830 }
831
832 /**
833  * Make sure this variable is fully expanded.
834  */
835 static char *
836 VarExpand(Var *v, VarParser *vp)
837 {
838         char    *value;
839         char    *result;
840
841         if (v->flags & VAR_IN_USE) {
842                 Fatal("Variable %s is recursive.", v->name);
843                 /* NOTREACHED */
844         }
845
846         v->flags |= VAR_IN_USE;
847
848         /*
849          * Before doing any modification, we have to make sure the
850          * value has been fully expanded. If it looks like recursion
851          * might be necessary (there's a dollar sign somewhere in the
852          * variable's value) we just call Var_Subst to do any other
853          * substitutions that are necessary. Note that the value
854          * returned by Var_Subst will have been
855          * dynamically-allocated, so it will need freeing when we
856          * return.
857          */
858         value = Buf_Data(v->val);
859         if (strchr(value, '$') == NULL) {
860                 result = strdup(value);
861         } else {
862                 Buffer  *buf;
863
864                 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
865                 result = Buf_Peel(buf);
866         }
867
868         v->flags &= ~VAR_IN_USE;
869
870         return (result);
871 }
872
873 /**
874  * Select only those words in value that match the modifier.
875  */
876 static char *
877 modifier_M(VarParser *vp, const char value[], char endc)
878 {
879         char    *patt;
880         char    *ptr;
881         char    *newValue;
882         char    modifier;
883
884         modifier = vp->ptr[0];
885         vp->ptr++;      /* consume 'M' or 'N' */
886
887         /*
888          * Compress the \:'s out of the pattern, so allocate enough
889          * room to hold the uncompressed pattern and compress the
890          * pattern into that space.
891          */
892         patt = estrdup(vp->ptr);
893         ptr = patt;
894         while (vp->ptr[0] != '\0') {
895                 if ((vp->ptr[0] == endc) || (vp->ptr[0] == ':')) {
896                         break;
897                 }
898                 if ((vp->ptr[0] == '\\') &&
899                     ((vp->ptr[1] == endc) || (vp->ptr[1] == ':'))) {
900                         vp->ptr++;      /* consume backslash */
901                 }
902                 *ptr = vp->ptr[0];
903                 ptr++;
904                 vp->ptr++;
905         }
906         *ptr = '\0';
907
908         if (modifier == 'M') {
909                 newValue = VarModify(value, VarMatch, patt);
910         } else {
911                 newValue = VarModify(value, VarNoMatch, patt);
912         }
913         free(patt);
914
915         return (newValue);
916 }
917
918 /**
919  * Substitute the replacement string for the pattern.  The substitution
920  * is applied to each word in value.
921  */
922 static char *
923 modifier_S(VarParser *vp, const char value[], Var *v)
924 {
925         VarPattern      patt;
926         char            delim;
927         char            *newValue;
928
929         patt.flags = 0;
930
931         vp->ptr++;              /* consume 'S' */
932
933         delim = *vp->ptr;       /* used to find end of pattern */
934         vp->ptr++;              /* consume 1st delim */
935
936         /*
937          * If pattern begins with '^', it is anchored to the start of the
938          * word -- skip over it and flag pattern.
939          */
940         if (*vp->ptr == '^') {
941                 patt.flags |= VAR_MATCH_START;
942                 vp->ptr++;
943         }
944
945         patt.lhs = VarGetPattern(vp, delim, &patt.flags, &patt.leftLen, NULL);
946         if (patt.lhs == NULL) {
947                 /*
948                  * LHS didn't end with the delim, complain and exit.
949                  */
950                 Fatal("Unclosed substitution for %s (%c missing)",
951                     v->name, delim);
952         }
953
954         vp->ptr++;      /* consume 2nd delim */
955
956         patt.rhs = VarGetPattern(vp, delim, NULL, &patt.rightLen, &patt);
957         if (patt.rhs == NULL) {
958                 /*
959                  * RHS didn't end with the delim, complain and exit.
960                  */
961                 Fatal("Unclosed substitution for %s (%c missing)",
962                     v->name, delim);
963         }
964
965         vp->ptr++;      /* consume last delim */
966
967         /*
968          * Check for global substitution. If 'g' after the final delimiter,
969          * substitution is global and is marked that way.
970          */
971         if (vp->ptr[0] == 'g') {
972                 patt.flags |= VAR_SUB_GLOBAL;
973                 vp->ptr++;
974         }
975
976         /*
977          * Global substitution of the empty string causes an infinite number
978          * of matches, unless anchored by '^' (start of string) or '$' (end
979          * of string). Catch the infinite substitution here. Note that flags
980          * can only contain the 3 bits we're interested in so we don't have
981          * to mask unrelated bits. We can test for equality.
982          */
983         if (patt.leftLen == 0 && patt.flags == VAR_SUB_GLOBAL)
984                 Fatal("Global substitution of the empty string");
985
986         newValue = VarModify(value, VarSubstitute, &patt);
987
988         /*
989          * Free the two strings.
990          */
991         free(patt.lhs);
992         free(patt.rhs);
993
994         return (newValue);
995 }
996
997 static char *
998 modifier_C(VarParser *vp, char value[], Var *v)
999 {
1000         VarPattern      patt;
1001         char            delim;
1002         char            *re;
1003         int             error;
1004         char            *newValue;
1005
1006         patt.flags = 0;
1007
1008         vp->ptr++;              /* consume 'C' */
1009
1010         delim = *vp->ptr;       /* delimiter between sections */
1011
1012         vp->ptr++;              /* consume 1st delim */
1013
1014         re = VarGetPattern(vp, delim, NULL, NULL, NULL);
1015         if (re == NULL) {
1016                 Fatal("Unclosed substitution for %s (%c missing)",
1017                      v->name, delim);
1018         }
1019
1020         vp->ptr++;              /* consume 2st delim */
1021
1022         patt.rhs = VarGetPattern(vp, delim, NULL, NULL, NULL);
1023         if (patt.rhs == NULL) {
1024                 Fatal("Unclosed substitution for %s (%c missing)",
1025                      v->name, delim);
1026         }
1027
1028         vp->ptr++;              /* consume last delim */
1029
1030         switch (*vp->ptr) {
1031         case 'g':
1032                 patt.flags |= VAR_SUB_GLOBAL;
1033                 vp->ptr++;              /* consume 'g' */
1034                 break;
1035         case '1':
1036                 patt.flags |= VAR_SUB_ONE;
1037                 vp->ptr++;              /* consume '1' */
1038                 break;
1039         default:
1040                 break;
1041         }
1042
1043         error = regcomp(&patt.re, re, REG_EXTENDED);
1044         if (error) {
1045                 VarREError(error, &patt.re, "RE substitution error");
1046                 free(patt.rhs);
1047                 free(re);
1048                 return (var_Error);
1049         }
1050
1051         patt.nsub = patt.re.re_nsub + 1;
1052         if (patt.nsub < 1)
1053                 patt.nsub = 1;
1054         if (patt.nsub > 10)
1055                 patt.nsub = 10;
1056         patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1057
1058         newValue = VarModify(value, VarRESubstitute, &patt);
1059
1060         regfree(&patt.re);
1061         free(patt.matches);
1062         free(patt.rhs);
1063         free(re);
1064
1065         return (newValue);
1066 }
1067
1068 static char *
1069 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1070 {
1071 #ifdef SYSVVARSUB
1072         /*
1073          * This can either be a bogus modifier or a System-V substitution
1074          * command.
1075          */
1076         char            endc;
1077         VarPattern      patt;
1078         Boolean         eqFound;
1079         int             cnt;
1080         char            *newStr;
1081         const char      *cp;
1082
1083         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1084
1085         patt.flags = 0;
1086
1087         /*
1088          * First we make a pass through the string trying to verify it is a
1089          * SYSV-make-style translation: it must be: <string1>=<string2>)
1090          */
1091         eqFound = FALSE;
1092         cp = vp->ptr;
1093         cnt = 1;
1094         while (*cp != '\0' && cnt) {
1095                 if (*cp == '=') {
1096                         eqFound = TRUE;
1097                         /* continue looking for endc */
1098                 } else if (*cp == endc)
1099                         cnt--;
1100                 else if (*cp == startc)
1101                         cnt++;
1102                 if (cnt)
1103                         cp++;
1104         }
1105
1106         if (*cp == endc && eqFound) {
1107                 /*
1108                  * Now we break this sucker into the lhs and rhs.
1109                  */
1110                 patt.lhs = VarGetPattern(vp, '=', &patt.flags, &patt.leftLen, NULL);
1111                 if (patt.lhs == NULL) {
1112                         Fatal("Unclosed substitution for %s (%c missing)",
1113                               v->name, '=');
1114                 }
1115                 vp->ptr++;      /* consume '=' */
1116
1117                 patt.rhs = VarGetPattern(vp, endc, NULL, &patt.rightLen, &patt);
1118                 if (patt.rhs == NULL) {
1119                         Fatal("Unclosed substitution for %s (%c missing)",
1120                               v->name, endc);
1121                 }
1122
1123                 /*
1124                  * SYSV modifications happen through the whole string. Note
1125                  * the pattern is anchored at the end.
1126                  */
1127                 newStr = VarModify(value, VarSYSVMatch, &patt);
1128
1129                 free(patt.lhs);
1130                 free(patt.rhs);
1131         } else
1132 #endif
1133         {
1134                 Error("Unknown modifier '%c'\n", *vp->ptr);
1135                 vp->ptr++;
1136                 while (*vp->ptr != '\0') {
1137                         if (*vp->ptr == endc && *vp->ptr == ':') {
1138                                 break;
1139                         }
1140                         vp->ptr++;
1141                 }
1142                 newStr = var_Error;
1143         }
1144
1145         return (newStr);
1146 }
1147
1148 /*
1149  * Now we need to apply any modifiers the user wants applied.
1150  * These are:
1151  *      :M<pattern>
1152  *              words which match the given <pattern>.
1153  *              <pattern> is of the standard file
1154  *              wildcarding form.
1155  *      :S<d><pat1><d><pat2><d>[g]
1156  *              Substitute <pat2> for <pat1> in the value
1157  *      :C<d><pat1><d><pat2><d>[g]
1158  *              Substitute <pat2> for regex <pat1> in the value
1159  *      :H      Substitute the head of each word
1160  *      :T      Substitute the tail of each word
1161  *      :E      Substitute the extension (minus '.') of
1162  *              each word
1163  *      :R      Substitute the root of each word
1164  *              (pathname minus the suffix).
1165  *      :lhs=rhs
1166  *              Like :S, but the rhs goes to the end of
1167  *              the invocation.
1168  *      :U      Converts variable to upper-case.
1169  *      :L      Converts variable to lower-case.
1170  *
1171  * XXXHB update this comment or remove it and point to the man page.
1172  */
1173 static char *
1174 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1175 {
1176         char    *value;
1177         char    endc;
1178
1179         value = VarExpand(v, vp);
1180         *freeResult = TRUE;
1181
1182         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1183
1184         vp->ptr++;      /* consume first colon */
1185
1186         while (*vp->ptr != '\0') {
1187                 char    *newStr;        /* New value to return */
1188
1189                 if (*vp->ptr == endc) {
1190                         return (value);
1191                 }
1192
1193                 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1194                 switch (*vp->ptr) {
1195                 case 'N':
1196                 case 'M':
1197                         newStr = modifier_M(vp, value, endc);
1198                         break;
1199                 case 'S':
1200                         newStr = modifier_S(vp, value, v);
1201                         break;
1202                 case 'C':
1203                         newStr = modifier_C(vp, value, v);
1204                         break;
1205                 default:
1206                         if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1207 #ifdef SUNSHCMD
1208                                 if ((vp->ptr[0] == 's') &&
1209                                     (vp->ptr[1] == 'h') &&
1210                                     (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1211                                         const char      *error;
1212                                         Buffer          *buf;
1213
1214                                         buf = Cmd_Exec(value, &error);
1215                                         newStr = Buf_Peel(buf);
1216
1217                                         if (error)
1218                                                 Error(error, value);
1219                                         vp->ptr += 2;
1220                                 } else
1221 #endif
1222                                 {
1223                                         newStr = sysVvarsub(vp, startc, v, value);
1224                                 }
1225                                 break;
1226                         }
1227
1228                         switch (vp->ptr[0]) {
1229                         case 'L':
1230                                 {
1231                                 const char      *cp;
1232                                 Buffer          *buf;
1233                                 buf = Buf_Init(MAKE_BSIZE);
1234                                 for (cp = value; *cp; cp++)
1235                                         Buf_AddByte(buf, (Byte)tolower(*cp));
1236
1237                                 newStr = Buf_Peel(buf);
1238
1239                                 vp->ptr++;
1240                                 break;
1241                                 }
1242                         case 'O':
1243                                 newStr = VarSortWords(value, SortIncreasing);
1244                                 vp->ptr++;
1245                                 break;
1246                         case 'Q':
1247                                 newStr = Var_Quote(value);
1248                                 vp->ptr++;
1249                                 break;
1250                         case 'T':
1251                                 newStr = VarModify(value, VarTail, NULL);
1252                                 vp->ptr++;
1253                                 break;
1254                         case 'U':
1255                                 {
1256                                 const char      *cp;
1257                                 Buffer          *buf;
1258                                 buf = Buf_Init(MAKE_BSIZE);
1259                                 for (cp = value; *cp; cp++)
1260                                         Buf_AddByte(buf, (Byte)toupper(*cp));
1261
1262                                 newStr = Buf_Peel(buf);
1263
1264                                 vp->ptr++;
1265                                 break;
1266                                 }
1267                         case 'H':
1268                                 newStr = VarModify(value, VarHead, NULL);
1269                                 vp->ptr++;
1270                                 break;
1271                         case 'E':
1272                                 newStr = VarModify(value, VarSuffix, NULL);
1273                                 vp->ptr++;
1274                                 break;
1275                         case 'R':
1276                                 newStr = VarModify(value, VarRoot, NULL);
1277                                 vp->ptr++;
1278                                 break;
1279                         default:
1280                                 newStr = sysVvarsub(vp, startc, v, value);
1281                                 break;
1282                         }
1283                         break;
1284                 }
1285
1286                 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1287                 if (*freeResult) {
1288                         free(value);
1289                 }
1290
1291                 value = newStr;
1292                 *freeResult = (value == var_Error) ? FALSE : TRUE;
1293
1294                 if (vp->ptr[0] == ':') {
1295                         vp->ptr++;      /* consume colon */
1296                 }
1297         }
1298
1299         return (value);
1300 }
1301
1302 static char *
1303 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1304 {
1305         const char      *vname;
1306         size_t          vlen;
1307         Var             *v;
1308         char            *value;
1309
1310         vname = Buf_GetAll(buf, &vlen);
1311
1312         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1313         if (v != NULL) {
1314                 value = ParseModifier(vp, startc, v, freeResult);
1315
1316                 if (v->flags & VAR_FROM_ENV) {
1317                         VarDestroy(v, TRUE);
1318                 }
1319                 return (value);
1320         }
1321
1322         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1323                 size_t  consumed = vp->ptr - vp->input + 1;
1324
1325                 /*
1326                  * If substituting a local variable in a non-local context,
1327                  * assume it's for dynamic source stuff. We have to handle
1328                  * this specially and return the longhand for the variable
1329                  * with the dollar sign escaped so it makes it back to the
1330                  * caller. Only four of the local variables are treated
1331                  * specially as they are the only four that will be set when
1332                  * dynamic sources are expanded.
1333                  */
1334                 if ((vlen == 1) ||
1335                     ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1336                         if (strchr("!%*@", vname[0]) != NULL) {
1337                                 value = emalloc(consumed + 1);
1338                                 strncpy(value, vp->input, consumed);
1339                                 value[consumed] = '\0';
1340
1341                                 *freeResult = TRUE;
1342                                 return (value);
1343                         }
1344                 }
1345                 if ((vlen > 2) &&
1346                     (vname[0] == '.') &&
1347                     isupper((unsigned char)vname[1])) {
1348                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1349                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1350                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1351                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1352                                 value = emalloc(consumed + 1);
1353                                 strncpy(value, vp->input, consumed);
1354                                 value[consumed] = '\0';
1355
1356                                 *freeResult = TRUE;
1357                                 return (value);
1358                         }
1359                 }
1360         } else {
1361                 /*
1362                  * Check for D and F forms of local variables since we're in
1363                  * a local context and the name is the right length.
1364                  */
1365                 if ((vlen == 2) &&
1366                     (vname[1] == 'F' || vname[1] == 'D') &&
1367                     (strchr("!%*<>@", vname[0]) != NULL)) {
1368                         char    name[2];
1369
1370                         name[0] = vname[0];
1371                         name[1] = '\0';
1372
1373                         v = VarFind(name, vp->ctxt, 0);
1374                         if (v != NULL) {
1375                                 value = ParseModifier(vp, startc, v, freeResult);
1376                                 return (value);
1377                         }
1378                 }
1379         }
1380
1381         /*
1382          * Still need to get to the end of the variable
1383          * specification, so kludge up a Var structure for the
1384          * modifications
1385          */
1386         v = VarCreate(vname, NULL, VAR_JUNK);
1387         value = ParseModifier(vp, startc, v, freeResult);
1388         if (*freeResult) {
1389                 free(value);
1390         }
1391         VarDestroy(v, TRUE);
1392
1393         *freeResult = FALSE;
1394         return (vp->err ? var_Error : varNoError);
1395 }
1396
1397 static char *
1398 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1399 {
1400         const char      *vname;
1401         size_t          vlen;
1402         Var             *v;
1403         char            *value;
1404
1405         vname = Buf_GetAll(buf, &vlen);
1406
1407         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1408         if (v != NULL) {
1409                 value = VarExpand(v, vp);
1410
1411                 if (v->flags & VAR_FROM_ENV) {
1412                         VarDestroy(v, TRUE);
1413                 }
1414
1415                 *freeResult = TRUE;
1416                 return (value);
1417         }
1418
1419         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1420                 size_t consumed = vp->ptr - vp->input + 1;
1421
1422                 /*
1423                  * If substituting a local variable in a non-local context,
1424                  * assume it's for dynamic source stuff. We have to handle
1425                  * this specially and return the longhand for the variable
1426                  * with the dollar sign escaped so it makes it back to the
1427                  * caller. Only four of the local variables are treated
1428                  * specially as they are the only four that will be set when
1429                  * dynamic sources are expanded.
1430                  */
1431                 if (((vlen == 1)) ||
1432                     ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1433                         if (strchr("!%*@", vname[0]) != NULL) {
1434                                 value = emalloc(consumed + 1);
1435                                 strncpy(value, vp->input, consumed);
1436                                 value[consumed] = '\0';
1437
1438                                 *freeResult = TRUE;
1439                                 return (value);
1440                         }
1441                 }
1442                 if ((vlen > 2) &&
1443                     (vname[0] == '.') &&
1444                     isupper((unsigned char)vname[1])) {
1445                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1446                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1447                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1448                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1449                                 value = emalloc(consumed + 1);
1450                                 strncpy(value, vp->input, consumed);
1451                                 value[consumed] = '\0';
1452
1453                                 *freeResult = TRUE;
1454                                 return (value);
1455                         }
1456                 }
1457         } else {
1458                 /*
1459                  * Check for D and F forms of local variables since we're in
1460                  * a local context and the name is the right length.
1461                  */
1462                 if ((vlen == 2) &&
1463                     (vname[1] == 'F' || vname[1] == 'D') &&
1464                     (strchr("!%*<>@", vname[0]) != NULL)) {
1465                         char    name[2];
1466
1467                         name[0] = vname[0];
1468                         name[1] = '\0';
1469
1470                         v = VarFind(name, vp->ctxt, 0);
1471                         if (v != NULL) {
1472                                 char    *val;
1473                                 /*
1474                                  * No need for nested expansion or anything,
1475                                  * as we're the only one who sets these
1476                                  * things and we sure don't put nested
1477                                  * invocations in them...
1478                                  */
1479                                 val = Buf_Data(v->val);
1480
1481                                 if (vname[1] == 'D') {
1482                                         val = VarModify(val, VarHead, NULL);
1483                                 } else {
1484                                         val = VarModify(val, VarTail, NULL);
1485                                 }
1486
1487                                 *freeResult = TRUE;
1488                                 return (val);
1489                         }
1490                 }
1491         }
1492
1493         *freeResult = FALSE;
1494         return (vp->err ? var_Error : varNoError);
1495 }
1496
1497 /**
1498  * Parse a multi letter variable name, and return it's value.
1499  */
1500 static char *
1501 VarParseLong(VarParser *vp, Boolean *freeResult)
1502 {
1503         Buffer          *buf;
1504         char            startc;
1505         char            endc;
1506         char            *value;
1507
1508         buf = Buf_Init(MAKE_BSIZE);
1509
1510         startc = vp->ptr[0];
1511         vp->ptr++;              /* consume opening paren or brace */
1512
1513         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1514
1515         /*
1516          * Process characters until we reach an end character or a colon,
1517          * replacing embedded variables as we go.
1518          */
1519         while (*vp->ptr != '\0') {
1520                 if (*vp->ptr == endc) {
1521                         value = ParseRestEnd(vp, buf, freeResult);
1522                         vp->ptr++;      /* consume closing paren or brace */
1523                         Buf_Destroy(buf, TRUE);
1524                         return (value);
1525
1526                 } else if (*vp->ptr == ':') {
1527                         value = ParseRestModifier(vp, startc, buf, freeResult);
1528                         vp->ptr++;      /* consume closing paren or brace */
1529                         Buf_Destroy(buf, TRUE);
1530                         return (value);
1531
1532                 } else if (*vp->ptr == '$') {
1533                         size_t  rlen;
1534                         Boolean rfree;
1535                         char    *rval;
1536
1537                         rlen = 0;
1538                         rval = Var_Parse(vp->ptr, vp->ctxt, vp->err,
1539                             &rlen, &rfree);
1540                         if (rval == var_Error) {
1541                                 Fatal("Error expanding embedded variable.");
1542                         }
1543                         Buf_Append(buf, rval);
1544                         if (rfree)
1545                                 free(rval);
1546                         vp->ptr += rlen;
1547
1548                 } else {
1549                         Buf_AddByte(buf, (Byte)*vp->ptr);
1550                         vp->ptr++;
1551                 }
1552         }
1553
1554         /* If we did not find the end character, return var_Error */
1555         Buf_Destroy(buf, TRUE);
1556         *freeResult = FALSE;
1557         return (var_Error);
1558 }
1559
1560 /**
1561  * Parse a single letter variable name, and return it's value.
1562  */
1563 static char *
1564 VarParseShort(VarParser *vp, Boolean *freeResult)
1565 {
1566         char    vname[2];
1567         Var     *v;
1568         char    *value;
1569
1570         vname[0] = vp->ptr[0];
1571         vname[1] = '\0';
1572
1573         vp->ptr++;      /* consume single letter */
1574
1575         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1576         if (v != NULL) {
1577                 value = VarExpand(v, vp);
1578
1579                 if (v->flags & VAR_FROM_ENV) {
1580                         VarDestroy(v, TRUE);
1581                 }
1582
1583                 *freeResult = TRUE;
1584                 return (value);
1585         }
1586
1587         /*
1588          * If substituting a local variable in a non-local context, assume
1589          * it's for dynamic source stuff. We have to handle this specially
1590          * and return the longhand for the variable with the dollar sign
1591          * escaped so it makes it back to the caller. Only four of the local
1592          * variables are treated specially as they are the only four that
1593          * will be set when dynamic sources are expanded.
1594          */
1595         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1596
1597                 /* XXX: It looks like $% and $! are reversed here */
1598                 switch (vname[0]) {
1599                 case '@':
1600                         *freeResult = TRUE;
1601                         return (estrdup("$(.TARGET)"));
1602                 case '%':
1603                         *freeResult = TRUE;
1604                         return (estrdup("$(.ARCHIVE)"));
1605                 case '*':
1606                         *freeResult = TRUE;
1607                         return (estrdup("$(.PREFIX)"));
1608                 case '!':
1609                         *freeResult = TRUE;
1610                         return (estrdup("$(.MEMBER)"));
1611                 default:
1612                         *freeResult = FALSE;
1613                         return (vp->err ? var_Error : varNoError);
1614                 }
1615         }
1616
1617         /* Variable name was not found. */
1618         *freeResult = FALSE;
1619         return (vp->err ? var_Error : varNoError);
1620 }
1621
1622 static char *
1623 VarParse(VarParser *vp, Boolean *freeResult)
1624 {
1625
1626         vp->ptr++;      /* consume '$' or last letter of conditional */
1627
1628         if (vp->ptr[0] == '\0') {
1629                 /* Error, there is only a dollar sign in the input string. */
1630                 *freeResult = FALSE;
1631                 return (vp->err ? var_Error : varNoError);
1632
1633         } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1634                 /* multi letter variable name */
1635                 return (VarParseLong(vp, freeResult));
1636
1637         } else {
1638                 /* single letter variable name */
1639                 return (VarParseShort(vp, freeResult));
1640         }
1641 }
1642
1643 /*-
1644  *-----------------------------------------------------------------------
1645  * Var_Parse --
1646  *      Given the start of a variable invocation, extract the variable
1647  *      name and find its value, then modify it according to the
1648  *      specification.
1649  *
1650  * Results:
1651  *      The value of the variable or var_Error if the specification
1652  *      is invalid.  The number of characters in the specification
1653  *      is placed in the variable pointed to by consumed.  (for
1654  *      invalid specifications, this is just 2 to skip the '$' and
1655  *      the following letter, or 1 if '$' was the last character
1656  *      in the string).  A Boolean in *freeResult telling whether the
1657  *      returned string should be freed by the caller.
1658  *
1659  * Side Effects:
1660  *      None.
1661  *-----------------------------------------------------------------------
1662  */
1663 char *
1664 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1665         size_t *consumed, Boolean *freeResult)
1666 {
1667         VarParser       vp = {
1668                 input,
1669                 input,
1670                 ctxt,
1671                 err
1672         };
1673         char            *value;
1674
1675         value = VarParse(&vp, freeResult);
1676         *consumed += vp.ptr - vp.input;
1677         return (value);
1678 }
1679
1680 /*-
1681  *-----------------------------------------------------------------------
1682  * Var_Subst  --
1683  *      Substitute for all variables in the given string in the given context
1684  *      If undefErr is TRUE, Parse_Error will be called when an undefined
1685  *      variable is encountered.
1686  *
1687  * Results:
1688  *      The resulting string.
1689  *
1690  * Side Effects:
1691  *      None. The old string must be freed by the caller
1692  *-----------------------------------------------------------------------
1693  */
1694 Buffer *
1695 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1696 {
1697         Boolean errorReported;
1698         Buffer *buf;            /* Buffer for forming things */
1699
1700         /*
1701          * Set TRUE if an error has already been reported to prevent a
1702          * plethora of messages when recursing. XXXHB this comment sounds
1703          * wrong.
1704          */
1705         errorReported = FALSE;
1706
1707         buf = Buf_Init(0);
1708         while (*str) {
1709                 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1710                         /*
1711                          * A dollar sign may be escaped either with another
1712                          * dollar sign. In such a case, we skip over the
1713                          * escape character and store the dollar sign into
1714                          * the buffer directly.
1715                          */
1716                         Buf_AddByte(buf, (Byte)str[0]);
1717                         str += 2;
1718
1719                 } else if (str[0] == '$') {
1720                         char   *val;    /* Value to substitute for a variable */
1721                         size_t  length; /* Length of the variable invocation */
1722                         Boolean doFree; /* Set true if val should be freed */
1723
1724                         /*
1725                          * Variable invocation.
1726                          */
1727                         if (var != NULL) {
1728                                 int     expand;
1729                                 for (;;) {
1730                                         if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1731                                                 size_t  ln;
1732                                                 const char *p = str + 2;
1733
1734                                                 /*
1735                                                  * Scan up to the end of the
1736                                                  * variable name.
1737                                                  */
1738                                                 while (*p != '\0' &&
1739                                                        *p != ':' &&
1740                                                        *p != CLOSE_PAREN &&
1741                                                        *p != CLOSE_BRACE &&
1742                                                        *p != '$') {
1743                                                         ++p;
1744                                                 }
1745
1746                                                 /*
1747                                                  * A variable inside the
1748                                                  * variable. We cannot expand
1749                                                  * the external variable yet,
1750                                                  * so we try again with the
1751                                                  * nested one
1752                                                  */
1753                                                 if (*p == '$') {
1754                                                         Buf_AppendRange(buf, str, p);
1755                                                         str = p;
1756                                                         continue;
1757                                                 }
1758                                                 ln = p - (str + 2);
1759                                                 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1760                                                         expand = TRUE;
1761                                                 } else {
1762                                                         /*
1763                                                          * Not the variable
1764                                                          * we want to expand,
1765                                                          * scan until the
1766                                                          * next variable
1767                                                          */
1768                                                         while (*p != '$' && *p != '\0')
1769                                                                 p++;
1770
1771                                                         Buf_AppendRange(buf, str, p);
1772                                                         str = p;
1773                                                         expand = FALSE;
1774                                                 }
1775                                         } else {
1776                                                 /*
1777                                                  * Single letter variable
1778                                                  * name
1779                                                  */
1780                                                 if (var[1] == '\0' && var[0] == str[1]) {
1781                                                         expand = TRUE;
1782                                                 } else {
1783                                                         Buf_AddBytes(buf, 2, (const Byte *) str);
1784                                                         str += 2;
1785                                                         expand = FALSE;
1786                                                 }
1787                                         }
1788                                         break;
1789                                 }
1790                                 if (!expand)
1791                                         continue;
1792                         }
1793                         length = 0;
1794                         val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1795
1796                         /*
1797                          * When we come down here, val should either point to
1798                          * the value of this variable, suitably modified, or
1799                          * be NULL. Length should be the total length of the
1800                          * potential variable invocation (from $ to end
1801                          * character...)
1802                          */
1803                         if (val == var_Error || val == varNoError) {
1804                                 /*
1805                                  * If performing old-time variable
1806                                  * substitution, skip over the variable and
1807                                  * continue with the substitution. Otherwise,
1808                                  * store the dollar sign and advance str so
1809                                  * we continue with the string...
1810                                  */
1811                                 if (oldVars) {
1812                                         str += length;
1813                                 } else if (undefErr) {
1814                                         /*
1815                                          * If variable is undefined, complain
1816                                          * and skip the variable. The
1817                                          * complaint will stop us from doing
1818                                          * anything when the file is parsed.
1819                                          */
1820                                         if (!errorReported) {
1821                                                 Parse_Error(PARSE_FATAL,
1822                                                             "Undefined variable \"%.*s\"", length, str);
1823                                         }
1824                                         str += length;
1825                                         errorReported = TRUE;
1826                                 } else {
1827                                         Buf_AddByte(buf, (Byte)*str);
1828                                         str += 1;
1829                                 }
1830                         } else {
1831                                 /*
1832                                  * We've now got a variable structure to
1833                                  * store in. But first, advance the string
1834                                  * pointer.
1835                                  */
1836                                 str += length;
1837
1838                                 /*
1839                                  * Copy all the characters from the variable
1840                                  * value straight into the new string.
1841                                  */
1842                                 Buf_Append(buf, val);
1843                                 if (doFree) {
1844                                         free(val);
1845                                 }
1846                         }
1847                 } else {
1848                         /*
1849                          * Skip as many characters as possible -- either to
1850                          * the end of the string or to the next dollar sign
1851                          * (variable invocation).
1852                          */
1853                         const char *cp = str;
1854
1855                         do {
1856                                 str++;
1857                         } while (str[0] != '$' && str[0] != '\0');
1858
1859                         Buf_AppendRange(buf, cp, str);
1860                 }
1861         }
1862
1863         return (buf);
1864 }
1865
1866 /*-
1867  *-----------------------------------------------------------------------
1868  * Var_GetTail --
1869  *      Return the tail from each of a list of words. Used to set the
1870  *      System V local variables.
1871  *
1872  * Results:
1873  *      The resulting string.
1874  *
1875  * Side Effects:
1876  *      None.
1877  *
1878  *-----------------------------------------------------------------------
1879  */
1880 char *
1881 Var_GetTail(char *file)
1882 {
1883
1884         return (VarModify(file, VarTail, (void *)NULL));
1885 }
1886
1887 /*-
1888  *-----------------------------------------------------------------------
1889  * Var_GetHead --
1890  *      Find the leading components of a (list of) filename(s).
1891  *      XXX: VarHead does not replace foo by ., as (sun) System V make
1892  *      does.
1893  *
1894  * Results:
1895  *      The leading components.
1896  *
1897  * Side Effects:
1898  *      None.
1899  *
1900  *-----------------------------------------------------------------------
1901  */
1902 char *
1903 Var_GetHead(char *file)
1904 {
1905
1906         return (VarModify(file, VarHead, (void *)NULL));
1907 }
1908
1909 /*-
1910  *-----------------------------------------------------------------------
1911  * Var_Init --
1912  *      Initialize the module
1913  *
1914  * Results:
1915  *      None
1916  *
1917  * Side Effects:
1918  *      The VAR_CMD and VAR_GLOBAL contexts are created
1919  *-----------------------------------------------------------------------
1920  */
1921 void
1922 Var_Init(void)
1923 {
1924
1925         VAR_GLOBAL = Targ_NewGN("Global");
1926         VAR_CMD = Targ_NewGN("Command");
1927 }
1928
1929 /*-
1930  *-----------------------------------------------------------------------
1931  * Var_Dump --
1932  *      print all variables in a context
1933  *-----------------------------------------------------------------------
1934  */
1935 void
1936 Var_Dump(const GNode *ctxt)
1937 {
1938         const LstNode   *ln;
1939         const Var       *v;
1940
1941         LST_FOREACH(ln, &ctxt->context) {
1942                 v = Lst_Datum(ln);
1943                 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
1944         }
1945 }