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