VirtualBox

source: kBuild/trunk/src/kmk/var.c@ 51

Last change on this file since 51 was 51, checked in by bird, 22 years ago

kMk and porting to kLib.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette