Annotation of src/usr.bin/make/var.c, Revision 1.12
1.12 ! espie 1: /* $OpenBSD: var.c,v 1.11 1999/09/25 14:44:00 espie Exp $ */
1.6 millert 2: /* $NetBSD: var.c,v 1.18 1997/03/18 19:24:46 christos Exp $ */
1.1 deraadt 3:
4: /*
1.5 millert 5: * Copyright (c) 1988, 1989, 1990, 1993
6: * The Regents of the University of California. All rights reserved.
1.1 deraadt 7: * Copyright (c) 1989 by Berkeley Softworks
8: * All rights reserved.
9: *
10: * This code is derived from software contributed to Berkeley by
11: * Adam de Boor.
12: *
13: * Redistribution and use in source and binary forms, with or without
14: * modification, are permitted provided that the following conditions
15: * are met:
16: * 1. Redistributions of source code must retain the above copyright
17: * notice, this list of conditions and the following disclaimer.
18: * 2. Redistributions in binary form must reproduce the above copyright
19: * notice, this list of conditions and the following disclaimer in the
20: * documentation and/or other materials provided with the distribution.
21: * 3. All advertising materials mentioning features or use of this software
22: * must display the following acknowledgement:
23: * This product includes software developed by the University of
24: * California, Berkeley and its contributors.
25: * 4. Neither the name of the University nor the names of its contributors
26: * may be used to endorse or promote products derived from this software
27: * without specific prior written permission.
28: *
29: * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39: * SUCH DAMAGE.
40: */
41:
42: #ifndef lint
43: #if 0
1.5 millert 44: static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
1.1 deraadt 45: #else
1.12 ! espie 46: static char rcsid[] = "$OpenBSD: var.c,v 1.11 1999/09/25 14:44:00 espie Exp $";
1.1 deraadt 47: #endif
48: #endif /* not lint */
49:
50: /*-
51: * var.c --
52: * Variable-handling functions
53: *
54: * Interface:
55: * Var_Set Set the value of a variable in the given
56: * context. The variable is created if it doesn't
57: * yet exist. The value and variable name need not
58: * be preserved.
59: *
60: * Var_Append Append more characters to an existing variable
61: * in the given context. The variable needn't
62: * exist already -- it will be created if it doesn't.
63: * A space is placed between the old value and the
64: * new one.
65: *
66: * Var_Exists See if a variable exists.
67: *
68: * Var_Value Return the value of a variable in a context or
69: * NULL if the variable is undefined.
70: *
71: * Var_Subst Substitute named variable, or all variables if
72: * NULL in a string using
73: * the given context as the top-most one. If the
74: * third argument is non-zero, Parse_Error is
75: * called if any variables are undefined.
76: *
77: * Var_Parse Parse a variable expansion from a string and
78: * return the result and the number of characters
79: * consumed.
80: *
81: * Var_Delete Delete a variable in a context.
82: *
83: * Var_Init Initialize this module.
84: *
85: * Debugging:
86: * Var_Dump Print out all variables defined in the given
87: * context.
88: *
89: * XXX: There's a lot of duplication in these functions.
90: */
91:
92: #include <ctype.h>
1.6 millert 93: #ifndef MAKE_BOOTSTRAP
1.9 deraadt 94: #include <sys/types.h>
1.6 millert 95: #include <regex.h>
96: #endif
97: #include <stdlib.h>
1.1 deraadt 98: #include "make.h"
99: #include "buf.h"
100:
101: /*
102: * This is a harmless return value for Var_Parse that can be used by Var_Subst
103: * to determine if there was an error in parsing -- easier than returning
104: * a flag, as things outside this module don't give a hoot.
105: */
106: char var_Error[] = "";
107:
108: /*
109: * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
110: * set false. Why not just use a constant? Well, gcc likes to condense
111: * identical string instances...
112: */
113: static char varNoError[] = "";
114:
115: /*
116: * Internally, variables are contained in four different contexts.
117: * 1) the environment. They may not be changed. If an environment
118: * variable is appended-to, the result is placed in the global
119: * context.
120: * 2) the global context. Variables set in the Makefile are located in
121: * the global context. It is the penultimate context searched when
122: * substituting.
123: * 3) the command-line context. All variables set on the command line
124: * are placed in this context. They are UNALTERABLE once placed here.
125: * 4) the local context. Each target has associated with it a context
126: * list. On this list are located the structures describing such
127: * local variables as $(@) and $(*)
128: * The four contexts are searched in the reverse order from which they are
129: * listed.
130: */
131: GNode *VAR_GLOBAL; /* variables from the makefile */
132: GNode *VAR_CMD; /* variables defined on the command-line */
133:
134: static Lst allVars; /* List of all variables */
135:
136: #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
137: #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
138: #define FIND_ENV 0x4 /* look in the environment also */
139:
140: typedef struct Var {
141: char *name; /* the variable's name */
142: Buffer val; /* its value */
143: int flags; /* miscellaneous status flags */
144: #define VAR_IN_USE 1 /* Variable's value currently being used.
145: * Used to avoid recursion */
146: #define VAR_FROM_ENV 2 /* Variable comes from the environment */
147: #define VAR_JUNK 4 /* Variable is a junk variable that
148: * should be destroyed when done with
149: * it. Used by Var_Parse for undefined,
150: * modified variables */
151: } Var;
152:
1.6 millert 153: /* Var*Pattern flags */
154: #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
155: #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
156: #define VAR_SUB_MATCHED 0x04 /* There was a match */
157: #define VAR_MATCH_START 0x08 /* Match at start of word */
158: #define VAR_MATCH_END 0x10 /* Match at end of word */
159:
1.1 deraadt 160: typedef struct {
161: char *lhs; /* String to match */
162: int leftLen; /* Length of string */
163: char *rhs; /* Replacement string (w/ &'s removed) */
164: int rightLen; /* Length of replacement */
165: int flags;
166: } VarPattern;
167:
1.6 millert 168: #ifndef MAKE_BOOTSTRAP
169: typedef struct {
170: regex_t re;
171: int nsub;
172: regmatch_t *matches;
173: char *replace;
174: int flags;
175: } VarREPattern;
176: #endif
177:
1.1 deraadt 178: static int VarCmp __P((ClientData, ClientData));
179: static Var *VarFind __P((char *, GNode *, int));
180: static void VarAdd __P((char *, char *, GNode *));
181: static void VarDelete __P((ClientData));
182: static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
183: static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
184: static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
185: static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
186: static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
1.4 briggs 187: #ifdef SYSVVARSUB
1.1 deraadt 188: static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
1.4 briggs 189: #endif
1.1 deraadt 190: static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
1.6 millert 191: #ifndef MAKE_BOOTSTRAP
192: static void VarREError __P((int, regex_t *, const char *));
193: static Boolean VarRESubstitute __P((char *, Boolean, Buffer, ClientData));
194: #endif
1.1 deraadt 195: static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
1.6 millert 196: static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
197: VarPattern *));
198: static char *VarQuote __P((char *));
1.1 deraadt 199: static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
200: ClientData),
201: ClientData));
202: static int VarPrintVar __P((ClientData, ClientData));
203:
204: /*-
205: *-----------------------------------------------------------------------
206: * VarCmp --
207: * See if the given variable matches the named one. Called from
208: * Lst_Find when searching for a variable of a given name.
209: *
210: * Results:
211: * 0 if they match. non-zero otherwise.
212: *
213: * Side Effects:
214: * none
215: *-----------------------------------------------------------------------
216: */
217: static int
218: VarCmp (v, name)
219: ClientData v; /* VAR structure to compare */
220: ClientData name; /* name to look for */
221: {
222: return (strcmp ((char *) name, ((Var *) v)->name));
223: }
224:
225: /*-
226: *-----------------------------------------------------------------------
227: * VarFind --
228: * Find the given variable in the given context and any other contexts
229: * indicated.
230: *
231: * Results:
232: * A pointer to the structure describing the desired variable or
233: * NIL if the variable does not exist.
234: *
235: * Side Effects:
236: * None
237: *-----------------------------------------------------------------------
238: */
239: static Var *
240: VarFind (name, ctxt, flags)
241: char *name; /* name to find */
242: GNode *ctxt; /* context in which to find it */
243: int flags; /* FIND_GLOBAL set means to look in the
244: * VAR_GLOBAL context as well.
245: * FIND_CMD set means to look in the VAR_CMD
246: * context also.
247: * FIND_ENV set means to look in the
248: * environment */
249: {
250: LstNode var;
251: Var *v;
252:
253: /*
254: * If the variable name begins with a '.', it could very well be one of
255: * the local ones. We check the name against all the local variables
256: * and substitute the short version in for 'name' if it matches one of
257: * them.
258: */
259: if (*name == '.' && isupper((unsigned char) name[1]))
260: switch (name[1]) {
261: case 'A':
262: if (!strcmp(name, ".ALLSRC"))
263: name = ALLSRC;
264: if (!strcmp(name, ".ARCHIVE"))
265: name = ARCHIVE;
266: break;
267: case 'I':
268: if (!strcmp(name, ".IMPSRC"))
269: name = IMPSRC;
270: break;
271: case 'M':
272: if (!strcmp(name, ".MEMBER"))
273: name = MEMBER;
274: break;
275: case 'O':
276: if (!strcmp(name, ".OODATE"))
277: name = OODATE;
278: break;
279: case 'P':
280: if (!strcmp(name, ".PREFIX"))
281: name = PREFIX;
282: break;
283: case 'T':
284: if (!strcmp(name, ".TARGET"))
285: name = TARGET;
286: break;
287: }
288: /*
289: * First look for the variable in the given context. If it's not there,
290: * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
291: * depending on the FIND_* flags in 'flags'
292: */
293: var = Lst_Find (ctxt->context, (ClientData)name, VarCmp);
294:
295: if ((var == NILLNODE) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
296: var = Lst_Find (VAR_CMD->context, (ClientData)name, VarCmp);
297: }
298: if (!checkEnvFirst && (var == NILLNODE) && (flags & FIND_GLOBAL) &&
299: (ctxt != VAR_GLOBAL))
300: {
301: var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
302: }
303: if ((var == NILLNODE) && (flags & FIND_ENV)) {
304: char *env;
305:
306: if ((env = getenv (name)) != NULL) {
307: int len;
1.5 millert 308:
1.1 deraadt 309: v = (Var *) emalloc(sizeof(Var));
1.4 briggs 310: v->name = estrdup(name);
1.1 deraadt 311:
312: len = strlen(env);
1.5 millert 313:
1.1 deraadt 314: v->val = Buf_Init(len);
315: Buf_AddBytes(v->val, len, (Byte *)env);
1.5 millert 316:
1.1 deraadt 317: v->flags = VAR_FROM_ENV;
318: return (v);
319: } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
320: (ctxt != VAR_GLOBAL))
321: {
322: var = Lst_Find (VAR_GLOBAL->context, (ClientData)name, VarCmp);
323: if (var == NILLNODE) {
324: return ((Var *) NIL);
325: } else {
326: return ((Var *)Lst_Datum(var));
327: }
328: } else {
329: return((Var *)NIL);
330: }
331: } else if (var == NILLNODE) {
332: return ((Var *) NIL);
333: } else {
334: return ((Var *) Lst_Datum (var));
335: }
336: }
337:
338: /*-
339: *-----------------------------------------------------------------------
340: * VarAdd --
341: * Add a new variable of name name and value val to the given context
342: *
343: * Results:
344: * None
345: *
346: * Side Effects:
347: * The new variable is placed at the front of the given context
348: * The name and val arguments are duplicated so they may
349: * safely be freed.
350: *-----------------------------------------------------------------------
351: */
352: static void
353: VarAdd (name, val, ctxt)
354: char *name; /* name of variable to add */
355: char *val; /* value to set it to */
356: GNode *ctxt; /* context in which to set it */
357: {
358: register Var *v;
359: int len;
360:
361: v = (Var *) emalloc (sizeof (Var));
362:
1.4 briggs 363: v->name = estrdup (name);
1.1 deraadt 364:
365: len = val ? strlen(val) : 0;
366: v->val = Buf_Init(len+1);
367: Buf_AddBytes(v->val, len, (Byte *)val);
368:
369: v->flags = 0;
370:
371: (void) Lst_AtFront (ctxt->context, (ClientData)v);
372: (void) Lst_AtEnd (allVars, (ClientData) v);
373: if (DEBUG(VAR)) {
374: printf("%s:%s = %s\n", ctxt->name, name, val);
375: }
376: }
377:
378:
379: /*-
380: *-----------------------------------------------------------------------
381: * VarDelete --
382: * Delete a variable and all the space associated with it.
383: *
384: * Results:
385: * None
386: *
387: * Side Effects:
388: * None
389: *-----------------------------------------------------------------------
390: */
391: static void
392: VarDelete(vp)
393: ClientData vp;
394: {
395: Var *v = (Var *) vp;
396: free(v->name);
397: Buf_Destroy(v->val, TRUE);
398: free((Address) v);
399: }
400:
401:
402:
403: /*-
404: *-----------------------------------------------------------------------
405: * Var_Delete --
406: * Remove a variable from a context.
407: *
408: * Results:
409: * None.
410: *
411: * Side Effects:
412: * The Var structure is removed and freed.
413: *
414: *-----------------------------------------------------------------------
415: */
416: void
417: Var_Delete(name, ctxt)
418: char *name;
419: GNode *ctxt;
420: {
421: LstNode ln;
422:
423: if (DEBUG(VAR)) {
424: printf("%s:delete %s\n", ctxt->name, name);
425: }
426: ln = Lst_Find(ctxt->context, (ClientData)name, VarCmp);
427: if (ln != NILLNODE) {
428: register Var *v;
429:
430: v = (Var *)Lst_Datum(ln);
431: Lst_Remove(ctxt->context, ln);
432: ln = Lst_Member(allVars, v);
433: Lst_Remove(allVars, ln);
434: VarDelete((ClientData) v);
435: }
436: }
437:
438: /*-
439: *-----------------------------------------------------------------------
440: * Var_Set --
441: * Set the variable name to the value val in the given context.
442: *
443: * Results:
444: * None.
445: *
446: * Side Effects:
447: * If the variable doesn't yet exist, a new record is created for it.
448: * Else the old value is freed and the new one stuck in its place
449: *
450: * Notes:
451: * The variable is searched for only in its context before being
452: * created in that context. I.e. if the context is VAR_GLOBAL,
453: * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
454: * VAR_CMD->context is searched. This is done to avoid the literally
455: * thousands of unnecessary strcmp's that used to be done to
456: * set, say, $(@) or $(<).
457: *-----------------------------------------------------------------------
458: */
459: void
460: Var_Set (name, val, ctxt)
461: char *name; /* name of variable to set */
462: char *val; /* value to give to the variable */
463: GNode *ctxt; /* context in which to set it */
464: {
465: register Var *v;
466:
467: /*
468: * We only look for a variable in the given context since anything set
469: * here will override anything in a lower context, so there's not much
470: * point in searching them all just to save a bit of memory...
471: */
472: v = VarFind (name, ctxt, 0);
473: if (v == (Var *) NIL) {
474: VarAdd (name, val, ctxt);
475: } else {
476: Buf_Discard(v->val, Buf_Size(v->val));
477: Buf_AddBytes(v->val, strlen(val), (Byte *)val);
478:
479: if (DEBUG(VAR)) {
480: printf("%s:%s = %s\n", ctxt->name, name, val);
481: }
482: }
483: /*
484: * Any variables given on the command line are automatically exported
485: * to the environment (as per POSIX standard)
486: */
487: if (ctxt == VAR_CMD) {
488: setenv(name, val, 1);
489: }
490: }
491:
492: /*-
493: *-----------------------------------------------------------------------
494: * Var_Append --
495: * The variable of the given name has the given value appended to it in
496: * the given context.
497: *
498: * Results:
499: * None
500: *
501: * Side Effects:
502: * If the variable doesn't exist, it is created. Else the strings
503: * are concatenated (with a space in between).
504: *
505: * Notes:
506: * Only if the variable is being sought in the global context is the
507: * environment searched.
508: * XXX: Knows its calling circumstances in that if called with ctxt
509: * an actual target, it will only search that context since only
510: * a local variable could be being appended to. This is actually
511: * a big win and must be tolerated.
512: *-----------------------------------------------------------------------
513: */
514: void
515: Var_Append (name, val, ctxt)
516: char *name; /* Name of variable to modify */
517: char *val; /* String to append to it */
518: GNode *ctxt; /* Context in which this should occur */
519: {
520: register Var *v;
521:
522: v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
523:
524: if (v == (Var *) NIL) {
525: VarAdd (name, val, ctxt);
526: } else {
527: Buf_AddByte(v->val, (Byte)' ');
528: Buf_AddBytes(v->val, strlen(val), (Byte *)val);
529:
530: if (DEBUG(VAR)) {
531: printf("%s:%s = %s\n", ctxt->name, name,
532: (char *) Buf_GetAll(v->val, (int *)NULL));
533: }
534:
535: if (v->flags & VAR_FROM_ENV) {
536: /*
537: * If the original variable came from the environment, we
538: * have to install it in the global context (we could place
539: * it in the environment, but then we should provide a way to
540: * export other variables...)
541: */
542: v->flags &= ~VAR_FROM_ENV;
543: Lst_AtFront(ctxt->context, (ClientData)v);
544: }
545: }
546: }
547:
548: /*-
549: *-----------------------------------------------------------------------
550: * Var_Exists --
551: * See if the given variable exists.
552: *
553: * Results:
554: * TRUE if it does, FALSE if it doesn't
555: *
556: * Side Effects:
557: * None.
558: *
559: *-----------------------------------------------------------------------
560: */
561: Boolean
562: Var_Exists(name, ctxt)
563: char *name; /* Variable to find */
564: GNode *ctxt; /* Context in which to start search */
565: {
566: Var *v;
567:
568: v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
569:
570: if (v == (Var *)NIL) {
571: return(FALSE);
572: } else if (v->flags & VAR_FROM_ENV) {
573: free(v->name);
574: Buf_Destroy(v->val, TRUE);
575: free((char *)v);
576: }
577: return(TRUE);
578: }
579:
580: /*-
581: *-----------------------------------------------------------------------
582: * Var_Value --
583: * Return the value of the named variable in the given context
584: *
585: * Results:
586: * The value if the variable exists, NULL if it doesn't
587: *
588: * Side Effects:
589: * None
590: *-----------------------------------------------------------------------
591: */
592: char *
593: Var_Value (name, ctxt, frp)
594: char *name; /* name to find */
595: GNode *ctxt; /* context in which to search for it */
596: char **frp;
597: {
598: Var *v;
599:
600: v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
601: *frp = NULL;
602: if (v != (Var *) NIL) {
603: char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
604: if (v->flags & VAR_FROM_ENV) {
605: Buf_Destroy(v->val, FALSE);
606: free((Address) v);
607: *frp = p;
608: }
609: return p;
610: } else {
611: return ((char *) NULL);
612: }
613: }
614:
615: /*-
616: *-----------------------------------------------------------------------
1.11 espie 617: * VarUppercase --
618: * Place the Upper cased word in the given buffer.
619: *
620: * Results:
621: * TRUE if characters were added to the buffer (a space needs to be
622: * added to the buffer before the next word).
623: *
624: * Side Effects:
625: * The word is added to the buffer.
626: *
627: *-----------------------------------------------------------------------
628: */
629: static Boolean
630: VarUppercase (word, addSpace, buf, dummy)
631: char *word; /* Word to Upper Case */
632: Boolean addSpace; /* True if need to add a space to the buffer
633: * before sticking in the head */
634: Buffer buf; /* Buffer in which to store it */
635: ClientData dummy;
636: {
637: size_t len = strlen(word);
638:
639: if (addSpace) {
640: Buf_AddByte (buf, (Byte)' ');
641: }
642:
643: while (len--) {
644: Buf_AddByte (buf, toupper(*word++));
645: }
646: return (TRUE);
647: }
648:
649: /*-
650: *-----------------------------------------------------------------------
651: * VarLowercase --
652: * Place the Lower cased word in the given buffer.
653: *
654: * Results:
655: * TRUE if characters were added to the buffer (a space needs to be
656: * added to the buffer before the next word).
657: *
658: * Side Effects:
659: * The word is added to the buffer.
660: *
661: *-----------------------------------------------------------------------
662: */
663: static Boolean
664: VarLowercase (word, addSpace, buf, dummy)
665: char *word; /* Word to Lower Case */
666: Boolean addSpace; /* True if need to add a space to the buffer
667: * before sticking in the head */
668: Buffer buf; /* Buffer in which to store it */
669: ClientData dummy;
670: {
671: size_t len = strlen(word);
672:
673: if (addSpace) {
674: Buf_AddByte (buf, (Byte)' ');
675: }
676:
677: while (len--) {
678: Buf_AddByte (buf, tolower(*word++));
679: }
680: return (TRUE);
681: }
682:
683: /*-
684: *-----------------------------------------------------------------------
1.1 deraadt 685: * VarHead --
686: * Remove the tail of the given word and place the result in the given
687: * buffer.
688: *
689: * Results:
690: * TRUE if characters were added to the buffer (a space needs to be
691: * added to the buffer before the next word).
692: *
693: * Side Effects:
694: * The trimmed word is added to the buffer.
695: *
696: *-----------------------------------------------------------------------
697: */
698: static Boolean
699: VarHead (word, addSpace, buf, dummy)
700: char *word; /* Word to trim */
701: Boolean addSpace; /* True if need to add a space to the buffer
702: * before sticking in the head */
703: Buffer buf; /* Buffer in which to store it */
704: ClientData dummy;
705: {
706: register char *slash;
707:
708: slash = strrchr (word, '/');
709: if (slash != (char *)NULL) {
710: if (addSpace) {
711: Buf_AddByte (buf, (Byte)' ');
712: }
713: *slash = '\0';
714: Buf_AddBytes (buf, strlen (word), (Byte *)word);
715: *slash = '/';
716: return (TRUE);
717: } else {
718: /*
719: * If no directory part, give . (q.v. the POSIX standard)
720: */
721: if (addSpace) {
722: Buf_AddBytes(buf, 2, (Byte *)" .");
723: } else {
724: Buf_AddByte(buf, (Byte)'.');
725: }
726: }
727: return(dummy ? TRUE : TRUE);
728: }
729:
730: /*-
731: *-----------------------------------------------------------------------
732: * VarTail --
733: * Remove the head of the given word and place the result in the given
734: * buffer.
735: *
736: * Results:
737: * TRUE if characters were added to the buffer (a space needs to be
738: * added to the buffer before the next word).
739: *
740: * Side Effects:
741: * The trimmed word is added to the buffer.
742: *
743: *-----------------------------------------------------------------------
744: */
745: static Boolean
746: VarTail (word, addSpace, buf, dummy)
747: char *word; /* Word to trim */
748: Boolean addSpace; /* TRUE if need to stick a space in the
749: * buffer before adding the tail */
750: Buffer buf; /* Buffer in which to store it */
751: ClientData dummy;
752: {
753: register char *slash;
754:
755: if (addSpace) {
756: Buf_AddByte (buf, (Byte)' ');
757: }
758:
759: slash = strrchr (word, '/');
760: if (slash != (char *)NULL) {
761: *slash++ = '\0';
762: Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
763: slash[-1] = '/';
764: } else {
765: Buf_AddBytes (buf, strlen(word), (Byte *)word);
766: }
767: return (dummy ? TRUE : TRUE);
768: }
769:
770: /*-
771: *-----------------------------------------------------------------------
772: * VarSuffix --
773: * Place the suffix of the given word in the given buffer.
774: *
775: * Results:
776: * TRUE if characters were added to the buffer (a space needs to be
777: * added to the buffer before the next word).
778: *
779: * Side Effects:
780: * The suffix from the word is placed in the buffer.
781: *
782: *-----------------------------------------------------------------------
783: */
784: static Boolean
785: VarSuffix (word, addSpace, buf, dummy)
786: char *word; /* Word to trim */
787: Boolean addSpace; /* TRUE if need to add a space before placing
788: * the suffix in the buffer */
789: Buffer buf; /* Buffer in which to store it */
790: ClientData dummy;
791: {
792: register char *dot;
793:
794: dot = strrchr (word, '.');
795: if (dot != (char *)NULL) {
796: if (addSpace) {
797: Buf_AddByte (buf, (Byte)' ');
798: }
799: *dot++ = '\0';
800: Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
801: dot[-1] = '.';
802: addSpace = TRUE;
803: }
804: return (dummy ? addSpace : addSpace);
805: }
806:
807: /*-
808: *-----------------------------------------------------------------------
809: * VarRoot --
810: * Remove the suffix of the given word and place the result in the
811: * buffer.
812: *
813: * Results:
814: * TRUE if characters were added to the buffer (a space needs to be
815: * added to the buffer before the next word).
816: *
817: * Side Effects:
818: * The trimmed word is added to the buffer.
819: *
820: *-----------------------------------------------------------------------
821: */
822: static Boolean
823: VarRoot (word, addSpace, buf, dummy)
824: char *word; /* Word to trim */
825: Boolean addSpace; /* TRUE if need to add a space to the buffer
826: * before placing the root in it */
827: Buffer buf; /* Buffer in which to store it */
828: ClientData dummy;
829: {
830: register char *dot;
831:
832: if (addSpace) {
833: Buf_AddByte (buf, (Byte)' ');
834: }
835:
836: dot = strrchr (word, '.');
837: if (dot != (char *)NULL) {
838: *dot = '\0';
839: Buf_AddBytes (buf, strlen (word), (Byte *)word);
840: *dot = '.';
841: } else {
842: Buf_AddBytes (buf, strlen(word), (Byte *)word);
843: }
844: return (dummy ? TRUE : TRUE);
845: }
846:
847: /*-
848: *-----------------------------------------------------------------------
849: * VarMatch --
850: * Place the word in the buffer if it matches the given pattern.
851: * Callback function for VarModify to implement the :M modifier.
1.5 millert 852: *
1.1 deraadt 853: * Results:
854: * TRUE if a space should be placed in the buffer before the next
855: * word.
856: *
857: * Side Effects:
858: * The word may be copied to the buffer.
859: *
860: *-----------------------------------------------------------------------
861: */
862: static Boolean
863: VarMatch (word, addSpace, buf, pattern)
864: char *word; /* Word to examine */
865: Boolean addSpace; /* TRUE if need to add a space to the
866: * buffer before adding the word, if it
867: * matches */
868: Buffer buf; /* Buffer in which to store it */
869: ClientData pattern; /* Pattern the word must match */
870: {
871: if (Str_Match(word, (char *) pattern)) {
872: if (addSpace) {
873: Buf_AddByte(buf, (Byte)' ');
874: }
875: addSpace = TRUE;
876: Buf_AddBytes(buf, strlen(word), (Byte *)word);
877: }
878: return(addSpace);
879: }
880:
1.4 briggs 881: #ifdef SYSVVARSUB
1.1 deraadt 882: /*-
883: *-----------------------------------------------------------------------
884: * VarSYSVMatch --
885: * Place the word in the buffer if it matches the given pattern.
886: * Callback function for VarModify to implement the System V %
887: * modifiers.
1.5 millert 888: *
1.1 deraadt 889: * Results:
890: * TRUE if a space should be placed in the buffer before the next
891: * word.
892: *
893: * Side Effects:
894: * The word may be copied to the buffer.
895: *
896: *-----------------------------------------------------------------------
897: */
898: static Boolean
899: VarSYSVMatch (word, addSpace, buf, patp)
900: char *word; /* Word to examine */
901: Boolean addSpace; /* TRUE if need to add a space to the
902: * buffer before adding the word, if it
903: * matches */
904: Buffer buf; /* Buffer in which to store it */
905: ClientData patp; /* Pattern the word must match */
906: {
907: int len;
908: char *ptr;
909: VarPattern *pat = (VarPattern *) patp;
910:
1.7 deraadt 911: if (*word) {
912: if (addSpace)
913: Buf_AddByte(buf, (Byte)' ');
914:
915: addSpace = TRUE;
916:
917: if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
918: Str_SYSVSubst(buf, pat->rhs, ptr, len);
919: else
920: Buf_AddBytes(buf, strlen(word), (Byte *) word);
921: }
1.1 deraadt 922: return(addSpace);
923: }
1.4 briggs 924: #endif
1.1 deraadt 925:
926:
927: /*-
928: *-----------------------------------------------------------------------
929: * VarNoMatch --
930: * Place the word in the buffer if it doesn't match the given pattern.
931: * Callback function for VarModify to implement the :N modifier.
1.5 millert 932: *
1.1 deraadt 933: * Results:
934: * TRUE if a space should be placed in the buffer before the next
935: * word.
936: *
937: * Side Effects:
938: * The word may be copied to the buffer.
939: *
940: *-----------------------------------------------------------------------
941: */
942: static Boolean
943: VarNoMatch (word, addSpace, buf, pattern)
944: char *word; /* Word to examine */
945: Boolean addSpace; /* TRUE if need to add a space to the
946: * buffer before adding the word, if it
947: * matches */
948: Buffer buf; /* Buffer in which to store it */
949: ClientData pattern; /* Pattern the word must match */
950: {
951: if (!Str_Match(word, (char *) pattern)) {
952: if (addSpace) {
953: Buf_AddByte(buf, (Byte)' ');
954: }
955: addSpace = TRUE;
956: Buf_AddBytes(buf, strlen(word), (Byte *)word);
957: }
958: return(addSpace);
959: }
960:
961:
962: /*-
963: *-----------------------------------------------------------------------
964: * VarSubstitute --
965: * Perform a string-substitution on the given word, placing the
966: * result in the passed buffer.
967: *
968: * Results:
969: * TRUE if a space is needed before more characters are added.
970: *
971: * Side Effects:
972: * None.
973: *
974: *-----------------------------------------------------------------------
975: */
976: static Boolean
977: VarSubstitute (word, addSpace, buf, patternp)
978: char *word; /* Word to modify */
979: Boolean addSpace; /* True if space should be added before
980: * other characters */
981: Buffer buf; /* Buffer for result */
982: ClientData patternp; /* Pattern for substitution */
983: {
984: register int wordLen; /* Length of word */
985: register char *cp; /* General pointer */
986: VarPattern *pattern = (VarPattern *) patternp;
987:
988: wordLen = strlen(word);
1.6 millert 989: if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
990: (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1.1 deraadt 991: /*
1.6 millert 992: * Still substituting -- break it down into simple anchored cases
1.1 deraadt 993: * and if none of them fits, perform the general substitution case.
994: */
995: if ((pattern->flags & VAR_MATCH_START) &&
996: (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
997: /*
998: * Anchored at start and beginning of word matches pattern
999: */
1000: if ((pattern->flags & VAR_MATCH_END) &&
1001: (wordLen == pattern->leftLen)) {
1002: /*
1003: * Also anchored at end and matches to the end (word
1004: * is same length as pattern) add space and rhs only
1005: * if rhs is non-null.
1006: */
1007: if (pattern->rightLen != 0) {
1008: if (addSpace) {
1009: Buf_AddByte(buf, (Byte)' ');
1010: }
1011: addSpace = TRUE;
1012: Buf_AddBytes(buf, pattern->rightLen,
1013: (Byte *)pattern->rhs);
1014: }
1.6 millert 1015: pattern->flags |= VAR_SUB_MATCHED;
1.1 deraadt 1016: } else if (pattern->flags & VAR_MATCH_END) {
1017: /*
1018: * Doesn't match to end -- copy word wholesale
1019: */
1020: goto nosub;
1021: } else {
1022: /*
1023: * Matches at start but need to copy in trailing characters
1024: */
1025: if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1026: if (addSpace) {
1027: Buf_AddByte(buf, (Byte)' ');
1028: }
1029: addSpace = TRUE;
1030: }
1031: Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1032: Buf_AddBytes(buf, wordLen - pattern->leftLen,
1033: (Byte *)(word + pattern->leftLen));
1.6 millert 1034: pattern->flags |= VAR_SUB_MATCHED;
1.1 deraadt 1035: }
1036: } else if (pattern->flags & VAR_MATCH_START) {
1037: /*
1038: * Had to match at start of word and didn't -- copy whole word.
1039: */
1040: goto nosub;
1041: } else if (pattern->flags & VAR_MATCH_END) {
1042: /*
1043: * Anchored at end, Find only place match could occur (leftLen
1044: * characters from the end of the word) and see if it does. Note
1045: * that because the $ will be left at the end of the lhs, we have
1046: * to use strncmp.
1047: */
1048: cp = word + (wordLen - pattern->leftLen);
1049: if ((cp >= word) &&
1050: (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1051: /*
1052: * Match found. If we will place characters in the buffer,
1053: * add a space before hand as indicated by addSpace, then
1054: * stuff in the initial, unmatched part of the word followed
1055: * by the right-hand-side.
1056: */
1057: if (((cp - word) + pattern->rightLen) != 0) {
1058: if (addSpace) {
1059: Buf_AddByte(buf, (Byte)' ');
1060: }
1061: addSpace = TRUE;
1062: }
1063: Buf_AddBytes(buf, cp - word, (Byte *)word);
1064: Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1.6 millert 1065: pattern->flags |= VAR_SUB_MATCHED;
1.1 deraadt 1066: } else {
1067: /*
1068: * Had to match at end and didn't. Copy entire word.
1069: */
1070: goto nosub;
1071: }
1072: } else {
1073: /*
1074: * Pattern is unanchored: search for the pattern in the word using
1075: * String_FindSubstring, copying unmatched portions and the
1076: * right-hand-side for each match found, handling non-global
1.5 millert 1077: * substitutions correctly, etc. When the loop is done, any
1.1 deraadt 1078: * remaining part of the word (word and wordLen are adjusted
1079: * accordingly through the loop) is copied straight into the
1080: * buffer.
1081: * addSpace is set FALSE as soon as a space is added to the
1082: * buffer.
1083: */
1084: register Boolean done;
1085: int origSize;
1086:
1087: done = FALSE;
1088: origSize = Buf_Size(buf);
1089: while (!done) {
1090: cp = Str_FindSubstring(word, pattern->lhs);
1091: if (cp != (char *)NULL) {
1092: if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1093: Buf_AddByte(buf, (Byte)' ');
1094: addSpace = FALSE;
1095: }
1096: Buf_AddBytes(buf, cp-word, (Byte *)word);
1097: Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
1098: wordLen -= (cp - word) + pattern->leftLen;
1099: word = cp + pattern->leftLen;
1.5 millert 1100: if (wordLen == 0 || (pattern->flags & VAR_SUB_GLOBAL) == 0){
1.1 deraadt 1101: done = TRUE;
1102: }
1.6 millert 1103: pattern->flags |= VAR_SUB_MATCHED;
1.1 deraadt 1104: } else {
1105: done = TRUE;
1106: }
1107: }
1108: if (wordLen != 0) {
1109: if (addSpace) {
1110: Buf_AddByte(buf, (Byte)' ');
1111: }
1112: Buf_AddBytes(buf, wordLen, (Byte *)word);
1113: }
1114: /*
1115: * If added characters to the buffer, need to add a space
1116: * before we add any more. If we didn't add any, just return
1117: * the previous value of addSpace.
1118: */
1119: return ((Buf_Size(buf) != origSize) || addSpace);
1120: }
1121: return (addSpace);
1122: }
1123: nosub:
1124: if (addSpace) {
1125: Buf_AddByte(buf, (Byte)' ');
1126: }
1127: Buf_AddBytes(buf, wordLen, (Byte *)word);
1128: return(TRUE);
1129: }
1130:
1.6 millert 1131: #ifndef MAKE_BOOTSTRAP
1132: /*-
1133: *-----------------------------------------------------------------------
1134: * VarREError --
1135: * Print the error caused by a regcomp or regexec call.
1136: *
1137: * Results:
1138: * None.
1139: *
1140: * Side Effects:
1141: * An error gets printed.
1142: *
1143: *-----------------------------------------------------------------------
1144: */
1145: static void
1146: VarREError(err, pat, str)
1147: int err;
1148: regex_t *pat;
1149: const char *str;
1150: {
1151: char *errbuf;
1152: int errlen;
1153:
1154: errlen = regerror(err, pat, 0, 0);
1155: errbuf = emalloc(errlen);
1156: regerror(err, pat, errbuf, errlen);
1157: Error("%s: %s", str, errbuf);
1158: free(errbuf);
1159: }
1160:
1161: /*-
1162: *-----------------------------------------------------------------------
1163: * VarRESubstitute --
1164: * Perform a regex substitution on the given word, placing the
1165: * result in the passed buffer.
1166: *
1167: * Results:
1168: * TRUE if a space is needed before more characters are added.
1169: *
1170: * Side Effects:
1171: * None.
1172: *
1173: *-----------------------------------------------------------------------
1174: */
1175: static Boolean
1176: VarRESubstitute(word, addSpace, buf, patternp)
1177: char *word;
1178: Boolean addSpace;
1179: Buffer buf;
1180: ClientData patternp;
1181: {
1182: VarREPattern *pat;
1183: int xrv;
1184: char *wp;
1185: char *rp;
1186: int added;
1187:
1188: #define MAYBE_ADD_SPACE() \
1189: if (addSpace && !added) \
1190: Buf_AddByte(buf, ' '); \
1191: added = 1
1192:
1193: added = 0;
1194: wp = word;
1195: pat = patternp;
1196:
1197: if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1198: (VAR_SUB_ONE|VAR_SUB_MATCHED))
1199: xrv = REG_NOMATCH;
1200: else {
1201: tryagain:
1202: xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, 0);
1203: }
1204:
1205: switch (xrv) {
1206: case 0:
1207: pat->flags |= VAR_SUB_MATCHED;
1208: if (pat->matches[0].rm_so > 0) {
1209: MAYBE_ADD_SPACE();
1210: Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1211: }
1212:
1213: for (rp = pat->replace; *rp; rp++) {
1214: if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1215: MAYBE_ADD_SPACE();
1216: Buf_AddByte(buf,rp[1]);
1217: rp++;
1218: }
1219: else if ((*rp == '&') || ((*rp == '\\') && isdigit(rp[1]))) {
1220: int n;
1221: char *subbuf;
1222: int sublen;
1223: char errstr[3];
1224:
1225: if (*rp == '&') {
1226: n = 0;
1227: errstr[0] = '&';
1228: errstr[1] = '\0';
1229: } else {
1230: n = rp[1] - '0';
1231: errstr[0] = '\\';
1232: errstr[1] = rp[1];
1233: errstr[2] = '\0';
1234: rp++;
1235: }
1236:
1237: if (n > pat->nsub) {
1238: Error("No subexpression %s", &errstr[0]);
1239: subbuf = "";
1240: sublen = 0;
1241: } else if ((pat->matches[n].rm_so == -1) &&
1242: (pat->matches[n].rm_eo == -1)) {
1243: Error("No match for subexpression %s", &errstr[0]);
1244: subbuf = "";
1245: sublen = 0;
1246: } else {
1247: subbuf = wp + pat->matches[n].rm_so;
1248: sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1249: }
1250:
1251: if (sublen > 0) {
1252: MAYBE_ADD_SPACE();
1253: Buf_AddBytes(buf, sublen, subbuf);
1254: }
1255: } else {
1256: MAYBE_ADD_SPACE();
1257: Buf_AddByte(buf, *rp);
1258: }
1259: }
1260: wp += pat->matches[0].rm_eo;
1261: if (pat->flags & VAR_SUB_GLOBAL)
1262: goto tryagain;
1263: if (*wp) {
1264: MAYBE_ADD_SPACE();
1265: Buf_AddBytes(buf, strlen(wp), wp);
1266: }
1267: break;
1268: default:
1269: VarREError(xrv, &pat->re, "Unexpected regex error");
1270: /* fall through */
1271: case REG_NOMATCH:
1272: if (*wp) {
1273: MAYBE_ADD_SPACE();
1274: Buf_AddBytes(buf,strlen(wp),wp);
1275: }
1276: break;
1277: }
1278: return(addSpace||added);
1279: }
1280: #endif
1281:
1.1 deraadt 1282: /*-
1283: *-----------------------------------------------------------------------
1284: * VarModify --
1285: * Modify each of the words of the passed string using the given
1286: * function. Used to implement all modifiers.
1287: *
1288: * Results:
1289: * A string of all the words modified appropriately.
1290: *
1291: * Side Effects:
1292: * None.
1293: *
1294: *-----------------------------------------------------------------------
1295: */
1296: static char *
1297: VarModify (str, modProc, datum)
1298: char *str; /* String whose words should be trimmed */
1299: /* Function to use to modify them */
1300: Boolean (*modProc) __P((char *, Boolean, Buffer, ClientData));
1301: ClientData datum; /* Datum to pass it */
1302: {
1303: Buffer buf; /* Buffer for the new string */
1304: Boolean addSpace; /* TRUE if need to add a space to the
1305: * buffer before adding the trimmed
1306: * word */
1.10 espie 1307: char **av; /* word list */
1308: char *as; /* word list memory */
1.1 deraadt 1309: int ac, i;
1310:
1311: buf = Buf_Init (0);
1312: addSpace = FALSE;
1313:
1.10 espie 1314: av = brk_string(str, &ac, FALSE, &as);
1.1 deraadt 1315:
1.10 espie 1316: for (i = 0; i < ac; i++)
1.1 deraadt 1317: addSpace = (*modProc)(av[i], addSpace, buf, datum);
1.5 millert 1318:
1.10 espie 1319: free(as);
1320: free(av);
1.1 deraadt 1321: Buf_AddByte (buf, '\0');
1322: str = (char *)Buf_GetAll (buf, (int *)NULL);
1323: Buf_Destroy (buf, FALSE);
1324: return (str);
1325: }
1326:
1327: /*-
1328: *-----------------------------------------------------------------------
1.6 millert 1329: * VarGetPattern --
1330: * Pass through the tstr looking for 1) escaped delimiters,
1331: * '$'s and backslashes (place the escaped character in
1332: * uninterpreted) and 2) unescaped $'s that aren't before
1333: * the delimiter (expand the variable substitution).
1334: * Return the expanded string or NULL if the delimiter was missing
1.10 espie 1335: * If pattern is specified, handle escaped ampersands, and replace
1.6 millert 1336: * unescaped ampersands with the lhs of the pattern.
1337: *
1338: * Results:
1339: * A string of all the words modified appropriately.
1340: * If length is specified, return the string length of the buffer
1341: * If flags is specified and the last character of the pattern is a
1342: * $ set the VAR_MATCH_END bit of flags.
1343: *
1344: * Side Effects:
1345: * None.
1346: *-----------------------------------------------------------------------
1347: */
1348: static char *
1349: VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
1350: GNode *ctxt;
1351: int err;
1352: char **tstr;
1353: int delim;
1354: int *flags;
1355: int *length;
1356: VarPattern *pattern;
1357: {
1358: char *cp;
1359: Buffer buf = Buf_Init(0);
1360: int junk;
1361: if (length == NULL)
1362: length = &junk;
1363:
1364: #define IS_A_MATCH(cp, delim) \
1365: ((cp[0] == '\\') && ((cp[1] == delim) || \
1366: (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
1367:
1368: /*
1369: * Skim through until the matching delimiter is found;
1370: * pick up variable substitutions on the way. Also allow
1371: * backslashes to quote the delimiter, $, and \, but don't
1372: * touch other backslashes.
1373: */
1374: for (cp = *tstr; *cp && (*cp != delim); cp++) {
1375: if (IS_A_MATCH(cp, delim)) {
1376: Buf_AddByte(buf, (Byte) cp[1]);
1377: cp++;
1378: } else if (*cp == '$') {
1379: if (cp[1] == delim) {
1380: if (flags == NULL)
1381: Buf_AddByte(buf, (Byte) *cp);
1382: else
1383: /*
1384: * Unescaped $ at end of pattern => anchor
1385: * pattern at end.
1386: */
1387: *flags |= VAR_MATCH_END;
1388: }
1389: else {
1390: char *cp2;
1391: int len;
1392: Boolean freeIt;
1393:
1394: /*
1395: * If unescaped dollar sign not before the
1396: * delimiter, assume it's a variable
1397: * substitution and recurse.
1398: */
1399: cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1400: Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
1401: if (freeIt)
1402: free(cp2);
1403: cp += len - 1;
1404: }
1405: }
1406: else if (pattern && *cp == '&')
1407: Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
1408: else
1409: Buf_AddByte(buf, (Byte) *cp);
1410: }
1411:
1412: Buf_AddByte(buf, (Byte) '\0');
1413:
1414: if (*cp != delim) {
1415: *tstr = cp;
1416: *length = 0;
1417: return NULL;
1418: }
1419: else {
1420: *tstr = ++cp;
1421: cp = (char *) Buf_GetAll(buf, length);
1422: *length -= 1; /* Don't count the NULL */
1423: Buf_Destroy(buf, FALSE);
1424: return cp;
1425: }
1426: }
1427:
1428: /*-
1429: *-----------------------------------------------------------------------
1430: * VarQuote --
1431: * Quote shell meta-characters in the string
1432: *
1433: * Results:
1434: * The quoted string
1435: *
1436: * Side Effects:
1437: * None.
1438: *
1439: *-----------------------------------------------------------------------
1440: */
1441: static char *
1442: VarQuote(str)
1443: char *str;
1444: {
1445:
1446: Buffer buf;
1447: /* This should cover most shells :-( */
1448: static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1449:
1450: buf = Buf_Init (MAKE_BSIZE);
1451: for (; *str; str++) {
1452: if (strchr(meta, *str) != NULL)
1453: Buf_AddByte(buf, (Byte)'\\');
1454: Buf_AddByte(buf, (Byte)*str);
1455: }
1456: Buf_AddByte(buf, (Byte) '\0');
1457: str = (char *)Buf_GetAll (buf, (int *)NULL);
1458: Buf_Destroy (buf, FALSE);
1459: return str;
1460: }
1461:
1462: /*-
1463: *-----------------------------------------------------------------------
1.1 deraadt 1464: * Var_Parse --
1465: * Given the start of a variable invocation, extract the variable
1466: * name and find its value, then modify it according to the
1467: * specification.
1468: *
1469: * Results:
1470: * The (possibly-modified) value of the variable or var_Error if the
1471: * specification is invalid. The length of the specification is
1472: * placed in *lengthPtr (for invalid specifications, this is just
1473: * 2...?).
1474: * A Boolean in *freePtr telling whether the returned string should
1475: * be freed by the caller.
1476: *
1477: * Side Effects:
1478: * None.
1479: *
1480: *-----------------------------------------------------------------------
1481: */
1482: char *
1483: Var_Parse (str, ctxt, err, lengthPtr, freePtr)
1484: char *str; /* The string to parse */
1485: GNode *ctxt; /* The context for the variable */
1486: Boolean err; /* TRUE if undefined variables are an error */
1487: int *lengthPtr; /* OUT: The length of the specification */
1488: Boolean *freePtr; /* OUT: TRUE if caller should free result */
1489: {
1490: register char *tstr; /* Pointer into str */
1491: Var *v; /* Variable in invocation */
1.6 millert 1492: char *cp; /* Secondary pointer into str (place marker
1.1 deraadt 1493: * for tstr) */
1494: Boolean haveModifier;/* TRUE if have modifiers for the variable */
1495: register char endc; /* Ending character when variable in parens
1496: * or braces */
1.2 deraadt 1497: register char startc=0; /* Starting character when variable in parens
1.1 deraadt 1498: * or braces */
1499: int cnt; /* Used to count brace pairs when variable in
1500: * in parens or braces */
1501: char *start;
1.6 millert 1502: char delim;
1.1 deraadt 1503: Boolean dynamic; /* TRUE if the variable is local and we're
1504: * expanding it in a non-local context. This
1505: * is done to support dynamic sources. The
1506: * result is just the invocation, unaltered */
1.5 millert 1507:
1.1 deraadt 1508: *freePtr = FALSE;
1509: dynamic = FALSE;
1510: start = str;
1.5 millert 1511:
1.1 deraadt 1512: if (str[1] != '(' && str[1] != '{') {
1513: /*
1514: * If it's not bounded by braces of some sort, life is much simpler.
1515: * We just need to check for the first character and return the
1516: * value if it exists.
1517: */
1518: char name[2];
1519:
1520: name[0] = str[1];
1521: name[1] = '\0';
1522:
1523: v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1524: if (v == (Var *)NIL) {
1525: *lengthPtr = 2;
1.5 millert 1526:
1.1 deraadt 1527: if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1528: /*
1529: * If substituting a local variable in a non-local context,
1530: * assume it's for dynamic source stuff. We have to handle
1531: * this specially and return the longhand for the variable
1532: * with the dollar sign escaped so it makes it back to the
1533: * caller. Only four of the local variables are treated
1534: * specially as they are the only four that will be set
1535: * when dynamic sources are expanded.
1536: */
1537: switch (str[1]) {
1538: case '@':
1539: return("$(.TARGET)");
1540: case '%':
1541: return("$(.ARCHIVE)");
1542: case '*':
1543: return("$(.PREFIX)");
1544: case '!':
1545: return("$(.MEMBER)");
1546: }
1547: }
1548: /*
1549: * Error
1550: */
1551: return (err ? var_Error : varNoError);
1552: } else {
1553: haveModifier = FALSE;
1554: tstr = &str[1];
1555: endc = str[1];
1556: }
1557: } else {
1558: startc = str[1];
1559: endc = startc == '(' ? ')' : '}';
1560:
1561: /*
1562: * Skip to the end character or a colon, whichever comes first.
1563: */
1564: for (tstr = str + 2;
1565: *tstr != '\0' && *tstr != endc && *tstr != ':';
1566: tstr++)
1567: {
1568: continue;
1569: }
1570: if (*tstr == ':') {
1571: haveModifier = TRUE;
1572: } else if (*tstr != '\0') {
1573: haveModifier = FALSE;
1574: } else {
1575: /*
1576: * If we never did find the end character, return NULL
1577: * right now, setting the length to be the distance to
1578: * the end of the string, since that's what make does.
1579: */
1580: *lengthPtr = tstr - str;
1581: return (var_Error);
1582: }
1583: *tstr = '\0';
1.5 millert 1584:
1.1 deraadt 1585: v = VarFind (str + 2, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1586: if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1587: ((tstr-str) == 4) && (str[3] == 'F' || str[3] == 'D'))
1588: {
1589: /*
1590: * Check for bogus D and F forms of local variables since we're
1591: * in a local context and the name is the right length.
1592: */
1593: switch(str[2]) {
1594: case '@':
1595: case '%':
1596: case '*':
1597: case '!':
1598: case '>':
1599: case '<':
1600: {
1601: char vname[2];
1602: char *val;
1603:
1604: /*
1605: * Well, it's local -- go look for it.
1606: */
1607: vname[0] = str[2];
1608: vname[1] = '\0';
1609: v = VarFind(vname, ctxt, 0);
1.5 millert 1610:
1.1 deraadt 1611: if (v != (Var *)NIL) {
1612: /*
1613: * No need for nested expansion or anything, as we're
1614: * the only one who sets these things and we sure don't
1615: * but nested invocations in them...
1616: */
1617: val = (char *)Buf_GetAll(v->val, (int *)NULL);
1.5 millert 1618:
1.1 deraadt 1619: if (str[3] == 'D') {
1620: val = VarModify(val, VarHead, (ClientData)0);
1621: } else {
1622: val = VarModify(val, VarTail, (ClientData)0);
1623: }
1624: /*
1625: * Resulting string is dynamically allocated, so
1626: * tell caller to free it.
1627: */
1628: *freePtr = TRUE;
1629: *lengthPtr = tstr-start+1;
1630: *tstr = endc;
1631: return(val);
1632: }
1633: break;
1634: }
1635: }
1636: }
1.5 millert 1637:
1.1 deraadt 1638: if (v == (Var *)NIL) {
1639: if ((((tstr-str) == 3) ||
1640: ((((tstr-str) == 4) && (str[3] == 'F' ||
1641: str[3] == 'D')))) &&
1642: ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1643: {
1644: /*
1645: * If substituting a local variable in a non-local context,
1646: * assume it's for dynamic source stuff. We have to handle
1647: * this specially and return the longhand for the variable
1648: * with the dollar sign escaped so it makes it back to the
1649: * caller. Only four of the local variables are treated
1650: * specially as they are the only four that will be set
1651: * when dynamic sources are expanded.
1652: */
1653: switch (str[2]) {
1654: case '@':
1655: case '%':
1656: case '*':
1657: case '!':
1658: dynamic = TRUE;
1659: break;
1660: }
1661: } else if (((tstr-str) > 4) && (str[2] == '.') &&
1662: isupper((unsigned char) str[3]) &&
1663: ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1664: {
1665: int len;
1.5 millert 1666:
1.1 deraadt 1667: len = (tstr-str) - 3;
1668: if ((strncmp(str+2, ".TARGET", len) == 0) ||
1669: (strncmp(str+2, ".ARCHIVE", len) == 0) ||
1670: (strncmp(str+2, ".PREFIX", len) == 0) ||
1671: (strncmp(str+2, ".MEMBER", len) == 0))
1672: {
1673: dynamic = TRUE;
1674: }
1675: }
1.5 millert 1676:
1.1 deraadt 1677: if (!haveModifier) {
1678: /*
1679: * No modifiers -- have specification length so we can return
1680: * now.
1681: */
1682: *lengthPtr = tstr - start + 1;
1683: *tstr = endc;
1684: if (dynamic) {
1685: str = emalloc(*lengthPtr + 1);
1686: strncpy(str, start, *lengthPtr);
1687: str[*lengthPtr] = '\0';
1688: *freePtr = TRUE;
1689: return(str);
1690: } else {
1691: return (err ? var_Error : varNoError);
1692: }
1693: } else {
1694: /*
1695: * Still need to get to the end of the variable specification,
1696: * so kludge up a Var structure for the modifications
1697: */
1698: v = (Var *) emalloc(sizeof(Var));
1699: v->name = &str[1];
1700: v->val = Buf_Init(1);
1701: v->flags = VAR_JUNK;
1702: }
1703: }
1704: }
1705:
1706: if (v->flags & VAR_IN_USE) {
1707: Fatal("Variable %s is recursive.", v->name);
1708: /*NOTREACHED*/
1709: } else {
1710: v->flags |= VAR_IN_USE;
1711: }
1712: /*
1713: * Before doing any modification, we have to make sure the value
1714: * has been fully expanded. If it looks like recursion might be
1715: * necessary (there's a dollar sign somewhere in the variable's value)
1716: * we just call Var_Subst to do any other substitutions that are
1717: * necessary. Note that the value returned by Var_Subst will have
1718: * been dynamically-allocated, so it will need freeing when we
1719: * return.
1720: */
1721: str = (char *)Buf_GetAll(v->val, (int *)NULL);
1722: if (strchr (str, '$') != (char *)NULL) {
1723: str = Var_Subst(NULL, str, ctxt, err);
1724: *freePtr = TRUE;
1725: }
1.5 millert 1726:
1.1 deraadt 1727: v->flags &= ~VAR_IN_USE;
1.5 millert 1728:
1.1 deraadt 1729: /*
1730: * Now we need to apply any modifiers the user wants applied.
1731: * These are:
1732: * :M<pattern> words which match the given <pattern>.
1733: * <pattern> is of the standard file
1734: * wildcarding form.
1735: * :S<d><pat1><d><pat2><d>[g]
1736: * Substitute <pat2> for <pat1> in the value
1.6 millert 1737: * :C<d><pat1><d><pat2><d>[g]
1738: * Substitute <pat2> for regex <pat1> in the value
1.1 deraadt 1739: * :H Substitute the head of each word
1740: * :T Substitute the tail of each word
1741: * :E Substitute the extension (minus '.') of
1742: * each word
1743: * :R Substitute the root of each word
1744: * (pathname minus the suffix).
1745: * :lhs=rhs Like :S, but the rhs goes to the end of
1746: * the invocation.
1747: */
1748: if ((str != (char *)NULL) && haveModifier) {
1749: /*
1750: * Skip initial colon while putting it back.
1751: */
1752: *tstr++ = ':';
1753: while (*tstr != endc) {
1754: char *newStr; /* New value to return */
1755: char termc; /* Character which terminated scan */
1.5 millert 1756:
1.1 deraadt 1757: if (DEBUG(VAR)) {
1758: printf("Applying :%c to \"%s\"\n", *tstr, str);
1759: }
1760: switch (*tstr) {
1761: case 'N':
1762: case 'M':
1763: {
1764: char *pattern;
1765: char *cp2;
1766: Boolean copy;
1767:
1768: copy = FALSE;
1769: for (cp = tstr + 1;
1770: *cp != '\0' && *cp != ':' && *cp != endc;
1771: cp++)
1772: {
1773: if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1774: copy = TRUE;
1775: cp++;
1776: }
1777: }
1778: termc = *cp;
1779: *cp = '\0';
1780: if (copy) {
1781: /*
1782: * Need to compress the \:'s out of the pattern, so
1783: * allocate enough room to hold the uncompressed
1784: * pattern (note that cp started at tstr+1, so
1785: * cp - tstr takes the null byte into account) and
1786: * compress the pattern into the space.
1787: */
1788: pattern = emalloc(cp - tstr);
1789: for (cp2 = pattern, cp = tstr + 1;
1790: *cp != '\0';
1791: cp++, cp2++)
1792: {
1793: if ((*cp == '\\') &&
1794: (cp[1] == ':' || cp[1] == endc)) {
1795: cp++;
1796: }
1797: *cp2 = *cp;
1798: }
1799: *cp2 = '\0';
1800: } else {
1801: pattern = &tstr[1];
1802: }
1803: if (*tstr == 'M' || *tstr == 'm') {
1804: newStr = VarModify(str, VarMatch, (ClientData)pattern);
1805: } else {
1806: newStr = VarModify(str, VarNoMatch,
1807: (ClientData)pattern);
1808: }
1809: if (copy) {
1810: free(pattern);
1811: }
1812: break;
1813: }
1814: case 'S':
1815: {
1816: VarPattern pattern;
1817:
1818: pattern.flags = 0;
1819: delim = tstr[1];
1820: tstr += 2;
1.6 millert 1821:
1.1 deraadt 1822: /*
1823: * If pattern begins with '^', it is anchored to the
1824: * start of the word -- skip over it and flag pattern.
1825: */
1826: if (*tstr == '^') {
1827: pattern.flags |= VAR_MATCH_START;
1828: tstr += 1;
1829: }
1830:
1.6 millert 1831: cp = tstr;
1832: if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
1833: &pattern.flags, &pattern.leftLen, NULL)) == NULL)
1834: goto cleanup;
1835:
1836: if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
1837: NULL, &pattern.rightLen, &pattern)) == NULL)
1838: goto cleanup;
1.5 millert 1839:
1.1 deraadt 1840: /*
1.6 millert 1841: * Check for global substitution. If 'g' after the final
1842: * delimiter, substitution is global and is marked that
1843: * way.
1.1 deraadt 1844: */
1.6 millert 1845: for (;; cp++) {
1846: switch (*cp) {
1847: case 'g':
1848: pattern.flags |= VAR_SUB_GLOBAL;
1849: continue;
1850: case '1':
1851: pattern.flags |= VAR_SUB_ONE;
1852: continue;
1.1 deraadt 1853: }
1.6 millert 1854: break;
1.1 deraadt 1855: }
1856:
1.6 millert 1857: termc = *cp;
1858: newStr = VarModify(str, VarSubstitute,
1859: (ClientData)&pattern);
1.5 millert 1860:
1.1 deraadt 1861: /*
1.6 millert 1862: * Free the two strings.
1.1 deraadt 1863: */
1.6 millert 1864: free(pattern.lhs);
1865: free(pattern.rhs);
1866: break;
1867: }
1868: #ifndef MAKE_BOOTSTRAP
1869: case 'C':
1870: {
1871: VarREPattern pattern;
1872: char *re;
1873: int error;
1874:
1875: pattern.flags = 0;
1876: delim = tstr[1];
1877: tstr += 2;
1.1 deraadt 1878:
1.6 millert 1879: cp = tstr;
1.1 deraadt 1880:
1.6 millert 1881: if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1882: NULL, NULL)) == NULL)
1883: goto cleanup;
1884:
1885: if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1886: delim, NULL, NULL, NULL)) == NULL) {
1887: free(re);
1888: goto cleanup;
1889: }
1.5 millert 1890:
1.6 millert 1891: for (;; cp++) {
1892: switch (*cp) {
1893: case 'g':
1894: pattern.flags |= VAR_SUB_GLOBAL;
1895: continue;
1896: case '1':
1897: pattern.flags |= VAR_SUB_ONE;
1898: continue;
1.1 deraadt 1899: }
1.6 millert 1900: break;
1.1 deraadt 1901: }
1902:
1.6 millert 1903: termc = *cp;
1.5 millert 1904:
1.6 millert 1905: error = regcomp(&pattern.re, re, REG_EXTENDED);
1906: free(re);
1907: if (error) {
1.1 deraadt 1908: *lengthPtr = cp - start + 1;
1.6 millert 1909: VarREError(error, &pattern.re, "RE substitution error");
1910: free(pattern.replace);
1.1 deraadt 1911: return (var_Error);
1912: }
1913:
1.6 millert 1914: pattern.nsub = pattern.re.re_nsub + 1;
1915: if (pattern.nsub < 1)
1916: pattern.nsub = 1;
1917: if (pattern.nsub > 10)
1918: pattern.nsub = 10;
1919: pattern.matches = emalloc(pattern.nsub *
1920: sizeof(regmatch_t));
1921: newStr = VarModify(str, VarRESubstitute,
1922: (ClientData) &pattern);
1923: regfree(&pattern.re);
1924: free(pattern.replace);
1925: free(pattern.matches);
1.1 deraadt 1926: break;
1927: }
1.6 millert 1928: #endif
1929: case 'Q':
1930: if (tstr[1] == endc || tstr[1] == ':') {
1931: newStr = VarQuote (str);
1932: cp = tstr + 1;
1933: termc = *cp;
1934: break;
1935: }
1936: /*FALLTHRU*/
1.1 deraadt 1937: case 'T':
1938: if (tstr[1] == endc || tstr[1] == ':') {
1939: newStr = VarModify (str, VarTail, (ClientData)0);
1940: cp = tstr + 1;
1941: termc = *cp;
1942: break;
1943: }
1944: /*FALLTHRU*/
1945: case 'H':
1946: if (tstr[1] == endc || tstr[1] == ':') {
1947: newStr = VarModify (str, VarHead, (ClientData)0);
1948: cp = tstr + 1;
1949: termc = *cp;
1950: break;
1951: }
1952: /*FALLTHRU*/
1953: case 'E':
1954: if (tstr[1] == endc || tstr[1] == ':') {
1955: newStr = VarModify (str, VarSuffix, (ClientData)0);
1956: cp = tstr + 1;
1957: termc = *cp;
1958: break;
1959: }
1960: /*FALLTHRU*/
1961: case 'R':
1962: if (tstr[1] == endc || tstr[1] == ':') {
1963: newStr = VarModify (str, VarRoot, (ClientData)0);
1.11 espie 1964: cp = tstr + 1;
1965: termc = *cp;
1966: break;
1967: }
1968: /*FALLTHRU*/
1969: case 'U':
1970: if (tstr[1] == endc || tstr[1] == ':') {
1971: newStr = VarModify (str, VarUppercase, (ClientData)0);
1972: cp = tstr + 1;
1973: termc = *cp;
1974: break;
1975: }
1976: /*FALLTHRU*/
1977: case 'L':
1978: if (tstr[1] == endc || tstr[1] == ':') {
1979: newStr = VarModify (str, VarLowercase, (ClientData)0);
1.1 deraadt 1980: cp = tstr + 1;
1981: termc = *cp;
1982: break;
1983: }
1984: /*FALLTHRU*/
1.4 briggs 1985: #ifdef SUNSHCMD
1986: case 's':
1987: if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1988: char *err;
1989: newStr = Cmd_Exec (str, &err);
1990: if (err)
1991: Error (err, str);
1992: cp = tstr + 2;
1993: termc = *cp;
1994: break;
1995: }
1996: /*FALLTHRU*/
1997: #endif
1998: default:
1999: {
2000: #ifdef SYSVVARSUB
1.1 deraadt 2001: /*
2002: * This can either be a bogus modifier or a System-V
2003: * substitution command.
2004: */
2005: VarPattern pattern;
2006: Boolean eqFound;
1.5 millert 2007:
1.1 deraadt 2008: pattern.flags = 0;
2009: eqFound = FALSE;
2010: /*
2011: * First we make a pass through the string trying
2012: * to verify it is a SYSV-make-style translation:
2013: * it must be: <string1>=<string2>)
2014: */
2015: cp = tstr;
2016: cnt = 1;
2017: while (*cp != '\0' && cnt) {
2018: if (*cp == '=') {
2019: eqFound = TRUE;
2020: /* continue looking for endc */
2021: }
2022: else if (*cp == endc)
2023: cnt--;
2024: else if (*cp == startc)
2025: cnt++;
2026: if (cnt)
2027: cp++;
2028: }
2029: if (*cp == endc && eqFound) {
1.5 millert 2030:
1.1 deraadt 2031: /*
2032: * Now we break this sucker into the lhs and
2033: * rhs. We must null terminate them of course.
2034: */
2035: for (cp = tstr; *cp != '='; cp++)
2036: continue;
2037: pattern.lhs = tstr;
2038: pattern.leftLen = cp - tstr;
2039: *cp++ = '\0';
1.5 millert 2040:
1.1 deraadt 2041: pattern.rhs = cp;
2042: cnt = 1;
2043: while (cnt) {
2044: if (*cp == endc)
2045: cnt--;
2046: else if (*cp == startc)
2047: cnt++;
2048: if (cnt)
2049: cp++;
2050: }
2051: pattern.rightLen = cp - pattern.rhs;
2052: *cp = '\0';
1.5 millert 2053:
1.1 deraadt 2054: /*
2055: * SYSV modifications happen through the whole
2056: * string. Note the pattern is anchored at the end.
2057: */
2058: newStr = VarModify(str, VarSYSVMatch,
2059: (ClientData)&pattern);
2060:
2061: /*
2062: * Restore the nulled characters
2063: */
2064: pattern.lhs[pattern.leftLen] = '=';
2065: pattern.rhs[pattern.rightLen] = endc;
2066: termc = endc;
1.4 briggs 2067: } else
2068: #endif
2069: {
1.1 deraadt 2070: Error ("Unknown modifier '%c'\n", *tstr);
2071: for (cp = tstr+1;
2072: *cp != ':' && *cp != endc && *cp != '\0';
1.5 millert 2073: cp++)
1.1 deraadt 2074: continue;
2075: termc = *cp;
2076: newStr = var_Error;
2077: }
2078: }
2079: }
2080: if (DEBUG(VAR)) {
2081: printf("Result is \"%s\"\n", newStr);
2082: }
1.5 millert 2083:
1.1 deraadt 2084: if (*freePtr) {
2085: free (str);
2086: }
2087: str = newStr;
2088: if (str != var_Error) {
2089: *freePtr = TRUE;
2090: } else {
2091: *freePtr = FALSE;
2092: }
2093: if (termc == '\0') {
2094: Error("Unclosed variable specification for %s", v->name);
2095: } else if (termc == ':') {
2096: *cp++ = termc;
2097: } else {
2098: *cp = termc;
2099: }
2100: tstr = cp;
2101: }
2102: *lengthPtr = tstr - start + 1;
2103: } else {
2104: *lengthPtr = tstr - start + 1;
2105: *tstr = endc;
2106: }
1.5 millert 2107:
1.1 deraadt 2108: if (v->flags & VAR_FROM_ENV) {
2109: Boolean destroy = FALSE;
1.5 millert 2110:
1.1 deraadt 2111: if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
2112: destroy = TRUE;
2113: } else {
2114: /*
2115: * Returning the value unmodified, so tell the caller to free
2116: * the thing.
2117: */
2118: *freePtr = TRUE;
2119: }
2120: Buf_Destroy(v->val, destroy);
2121: free((Address)v);
2122: } else if (v->flags & VAR_JUNK) {
2123: /*
2124: * Perform any free'ing needed and set *freePtr to FALSE so the caller
2125: * doesn't try to free a static pointer.
2126: */
2127: if (*freePtr) {
2128: free(str);
2129: }
2130: *freePtr = FALSE;
2131: Buf_Destroy(v->val, TRUE);
2132: free((Address)v);
2133: if (dynamic) {
2134: str = emalloc(*lengthPtr + 1);
2135: strncpy(str, start, *lengthPtr);
2136: str[*lengthPtr] = '\0';
2137: *freePtr = TRUE;
2138: } else {
1.12 ! espie 2139: str = err ? var_Error : varNoError;
1.1 deraadt 2140: }
2141: }
2142: return (str);
1.6 millert 2143:
2144: cleanup:
2145: *lengthPtr = cp - start + 1;
2146: if (*freePtr)
2147: free(str);
2148: Error("Unclosed substitution for %s (%c missing)",
2149: v->name, delim);
2150: return (var_Error);
1.1 deraadt 2151: }
2152:
2153: /*-
2154: *-----------------------------------------------------------------------
2155: * Var_Subst --
2156: * Substitute for all variables in the given string in the given context
2157: * If undefErr is TRUE, Parse_Error will be called when an undefined
2158: * variable is encountered.
2159: *
2160: * Results:
2161: * The resulting string.
2162: *
2163: * Side Effects:
2164: * None. The old string must be freed by the caller
2165: *-----------------------------------------------------------------------
2166: */
2167: char *
2168: Var_Subst (var, str, ctxt, undefErr)
2169: char *var; /* Named variable || NULL for all */
2170: char *str; /* the string in which to substitute */
2171: GNode *ctxt; /* the context wherein to find variables */
2172: Boolean undefErr; /* TRUE if undefineds are an error */
2173: {
2174: Buffer buf; /* Buffer for forming things */
2175: char *val; /* Value to substitute for a variable */
2176: int length; /* Length of the variable invocation */
2177: Boolean doFree; /* Set true if val should be freed */
2178: static Boolean errorReported; /* Set true if an error has already
2179: * been reported to prevent a plethora
2180: * of messages when recursing */
2181:
2182: buf = Buf_Init (MAKE_BSIZE);
2183: errorReported = FALSE;
2184:
2185: while (*str) {
2186: if (var == NULL && (*str == '$') && (str[1] == '$')) {
2187: /*
2188: * A dollar sign may be escaped either with another dollar sign.
2189: * In such a case, we skip over the escape character and store the
2190: * dollar sign into the buffer directly.
2191: */
2192: str++;
2193: Buf_AddByte(buf, (Byte)*str);
2194: str++;
2195: } else if (*str != '$') {
2196: /*
2197: * Skip as many characters as possible -- either to the end of
2198: * the string or to the next dollar sign (variable invocation).
2199: */
2200: char *cp;
2201:
2202: for (cp = str++; *str != '$' && *str != '\0'; str++)
2203: continue;
2204: Buf_AddBytes(buf, str - cp, (Byte *)cp);
2205: } else {
2206: if (var != NULL) {
2207: int expand;
2208: for (;;) {
2209: if (str[1] != '(' && str[1] != '{') {
2210: if (str[1] != *var) {
2211: Buf_AddBytes(buf, 2, (Byte *) str);
2212: str += 2;
2213: expand = FALSE;
2214: }
2215: else
2216: expand = TRUE;
2217: break;
2218: }
2219: else {
2220: char *p;
2221:
2222: /*
2223: * Scan up to the end of the variable name.
2224: */
1.5 millert 2225: for (p = &str[2]; *p &&
1.1 deraadt 2226: *p != ':' && *p != ')' && *p != '}'; p++)
1.5 millert 2227: if (*p == '$')
1.1 deraadt 2228: break;
2229: /*
2230: * A variable inside the variable. We cannot expand
2231: * the external variable yet, so we try again with
2232: * the nested one
2233: */
2234: if (*p == '$') {
2235: Buf_AddBytes(buf, p - str, (Byte *) str);
2236: str = p;
2237: continue;
2238: }
1.5 millert 2239:
2240: if (strncmp(var, str + 2, p - str - 2) != 0 ||
1.1 deraadt 2241: var[p - str - 2] != '\0') {
2242: /*
2243: * Not the variable we want to expand, scan
2244: * until the next variable
2245: */
1.5 millert 2246: for (;*p != '$' && *p != '\0'; p++)
1.1 deraadt 2247: continue;
2248: Buf_AddBytes(buf, p - str, (Byte *) str);
2249: str = p;
2250: expand = FALSE;
2251: }
2252: else
2253: expand = TRUE;
2254: break;
2255: }
2256: }
2257: if (!expand)
2258: continue;
2259: }
1.5 millert 2260:
1.1 deraadt 2261: val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
2262:
2263: /*
2264: * When we come down here, val should either point to the
2265: * value of this variable, suitably modified, or be NULL.
2266: * Length should be the total length of the potential
2267: * variable invocation (from $ to end character...)
2268: */
2269: if (val == var_Error || val == varNoError) {
2270: /*
2271: * If performing old-time variable substitution, skip over
2272: * the variable and continue with the substitution. Otherwise,
2273: * store the dollar sign and advance str so we continue with
2274: * the string...
2275: */
2276: if (oldVars) {
2277: str += length;
2278: } else if (undefErr) {
2279: /*
2280: * If variable is undefined, complain and skip the
2281: * variable. The complaint will stop us from doing anything
2282: * when the file is parsed.
2283: */
2284: if (!errorReported) {
2285: Parse_Error (PARSE_FATAL,
2286: "Undefined variable \"%.*s\"",length,str);
2287: }
2288: str += length;
2289: errorReported = TRUE;
2290: } else {
2291: Buf_AddByte (buf, (Byte)*str);
2292: str += 1;
2293: }
2294: } else {
2295: /*
2296: * We've now got a variable structure to store in. But first,
2297: * advance the string pointer.
2298: */
2299: str += length;
1.5 millert 2300:
1.1 deraadt 2301: /*
2302: * Copy all the characters from the variable value straight
2303: * into the new string.
2304: */
2305: Buf_AddBytes (buf, strlen (val), (Byte *)val);
2306: if (doFree) {
2307: free ((Address)val);
2308: }
2309: }
2310: }
2311: }
1.5 millert 2312:
1.1 deraadt 2313: Buf_AddByte (buf, '\0');
2314: str = (char *)Buf_GetAll (buf, (int *)NULL);
2315: Buf_Destroy (buf, FALSE);
2316: return (str);
2317: }
2318:
2319: /*-
2320: *-----------------------------------------------------------------------
2321: * Var_GetTail --
2322: * Return the tail from each of a list of words. Used to set the
2323: * System V local variables.
2324: *
2325: * Results:
2326: * The resulting string.
2327: *
2328: * Side Effects:
2329: * None.
2330: *
2331: *-----------------------------------------------------------------------
2332: */
2333: char *
2334: Var_GetTail(file)
2335: char *file; /* Filename to modify */
2336: {
2337: return(VarModify(file, VarTail, (ClientData)0));
2338: }
2339:
2340: /*-
2341: *-----------------------------------------------------------------------
2342: * Var_GetHead --
2343: * Find the leading components of a (list of) filename(s).
2344: * XXX: VarHead does not replace foo by ., as (sun) System V make
2345: * does.
2346: *
2347: * Results:
2348: * The leading components.
2349: *
2350: * Side Effects:
2351: * None.
2352: *
2353: *-----------------------------------------------------------------------
2354: */
2355: char *
2356: Var_GetHead(file)
2357: char *file; /* Filename to manipulate */
2358: {
2359: return(VarModify(file, VarHead, (ClientData)0));
2360: }
2361:
2362: /*-
2363: *-----------------------------------------------------------------------
2364: * Var_Init --
2365: * Initialize the module
2366: *
2367: * Results:
2368: * None
2369: *
2370: * Side Effects:
1.5 millert 2371: * The VAR_CMD and VAR_GLOBAL contexts are created
1.1 deraadt 2372: *-----------------------------------------------------------------------
2373: */
2374: void
2375: Var_Init ()
2376: {
2377: VAR_GLOBAL = Targ_NewGN ("Global");
2378: VAR_CMD = Targ_NewGN ("Command");
2379: allVars = Lst_Init(FALSE);
2380:
2381: }
2382:
2383:
2384: void
2385: Var_End ()
2386: {
2387: Lst_Destroy(allVars, VarDelete);
2388: }
1.5 millert 2389:
1.1 deraadt 2390:
2391: /****************** PRINT DEBUGGING INFO *****************/
2392: static int
2393: VarPrintVar (vp, dummy)
2394: ClientData vp;
2395: ClientData dummy;
2396: {
2397: Var *v = (Var *) vp;
2398: printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
2399: return (dummy ? 0 : 0);
2400: }
2401:
2402: /*-
2403: *-----------------------------------------------------------------------
2404: * Var_Dump --
2405: * print all variables in a context
2406: *-----------------------------------------------------------------------
2407: */
2408: void
2409: Var_Dump (ctxt)
2410: GNode *ctxt;
2411: {
2412: Lst_ForEach (ctxt->context, VarPrintVar, (ClientData) 0);
2413: }