source: trunk/src/kmk/var.c@ 27

Last change on this file since 27 was 27, checked in by bird, 23 years ago

OS2 / VAC308

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