var.c revision 1.50 1 /* $NetBSD: var.c,v 1.50 2000/06/06 09:00:49 mycroft 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.50 2000/06/06 09:00:49 mycroft 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.50 2000/06/06 09:00:49 mycroft 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[1];
1786 v->val = Buf_Init(1);
1787 v->flags = VAR_JUNK;
1788 }
1789 }
1790 Buf_Destroy (buf, TRUE);
1791 }
1792
1793
1794 if (v->flags & VAR_IN_USE) {
1795 Fatal("Variable %s is recursive.", v->name);
1796 /*NOTREACHED*/
1797 } else {
1798 v->flags |= VAR_IN_USE;
1799 }
1800 /*
1801 * Before doing any modification, we have to make sure the value
1802 * has been fully expanded. If it looks like recursion might be
1803 * necessary (there's a dollar sign somewhere in the variable's value)
1804 * we just call Var_Subst to do any other substitutions that are
1805 * necessary. Note that the value returned by Var_Subst will have
1806 * been dynamically-allocated, so it will need freeing when we
1807 * return.
1808 */
1809 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1810 if (strchr (str, '$') != (char *)NULL) {
1811 str = Var_Subst(NULL, str, ctxt, err);
1812 *freePtr = TRUE;
1813 }
1814
1815 v->flags &= ~VAR_IN_USE;
1816
1817 /*
1818 * Now we need to apply any modifiers the user wants applied.
1819 * These are:
1820 * :M<pattern> words which match the given <pattern>.
1821 * <pattern> is of the standard file
1822 * wildcarding form.
1823 * :N<pattern> words which do not match the given <pattern>.
1824 * :S<d><pat1><d><pat2><d>[g]
1825 * Substitute <pat2> for <pat1> in the value
1826 * :C<d><pat1><d><pat2><d>[g]
1827 * Substitute <pat2> for regex <pat1> in the value
1828 * :H Substitute the head of each word
1829 * :T Substitute the tail of each word
1830 * :E Substitute the extension (minus '.') of
1831 * each word
1832 * :R Substitute the root of each word
1833 * (pathname minus the suffix).
1834 * :O Sort words in variable.
1835 * :?<true-value>:<false-value>
1836 * If the variable evaluates to true, return
1837 * true value, else return the second value.
1838 * :lhs=rhs Like :S, but the rhs goes to the end of
1839 * the invocation.
1840 * :sh Treat the current value as a command
1841 * to be run, new value is its output.
1842 * The following added so we can handle ODE makefiles.
1843 * :@<tmpvar>@<newval>@
1844 * Assign a temporary local variable <tmpvar>
1845 * to the current value of each word in turn
1846 * and replace each word with the result of
1847 * evaluating <newval>
1848 * :D<newval> Use <newval> as value if variable defined
1849 * :U<newval> Use <newval> as value if variable undefined
1850 * :L Use the name of the variable as the value.
1851 * :P Use the path of the node that has the same
1852 * name as the variable as the value. This
1853 * basically includes an implied :L so that
1854 * the common method of refering to the path
1855 * of your dependent 'x' in a rule is to use
1856 * the form '${x:P}'.
1857 * :!<cmd>! Run cmd much the same as :sh run's the
1858 * current value of the variable.
1859 * The ::= modifiers, actually assign a value to the variable.
1860 * Their main purpose is in supporting modifiers of .for loop
1861 * iterators and other obscure uses. They always expand to
1862 * nothing. In a target rule that would otherwise expand to an
1863 * empty line they can be preceded with @: to keep make happy.
1864 * Eg.
1865 *
1866 * foo: .USE
1867 * .for i in ${.TARGET} ${.TARGET:R}.gz
1868 * @: ${t::=$i}
1869 * @echo blah ${t:T}
1870 * .endfor
1871 *
1872 * ::=<str> Assigns <str> as the new value of variable.
1873 * ::?=<str> Assigns <str> as value of variable if
1874 * it was not already set.
1875 * ::+=<str> Appends <str> to variable.
1876 * ::!=<cmd> Assigns output of <cmd> as the new value of
1877 * variable.
1878 */
1879 if ((str != (char *)NULL) && haveModifier) {
1880 /*
1881 * Skip initial colon while putting it back.
1882 */
1883 *tstr++ = ':';
1884 while (*tstr != endc) {
1885 char *newStr; /* New value to return */
1886 char termc; /* Character which terminated scan */
1887
1888 if (DEBUG(VAR)) {
1889 printf("Applying :%c to \"%s\"\n", *tstr, str);
1890 }
1891 switch (*tstr) {
1892 case ':':
1893
1894 if (tstr[1] == '=' ||
1895 (tstr[2] == '=' &&
1896 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
1897 GNode *v_ctxt; /* context where v belongs */
1898 char *emsg;
1899 VarPattern pattern;
1900 int how;
1901
1902 ++tstr;
1903 if (v->flags & VAR_JUNK) {
1904 /*
1905 * JUNK vars get name = &str[1]
1906 * we want the full name here.
1907 */
1908 v->name--;
1909 /*
1910 * We need to strdup() it incase
1911 * VarGetPattern() recurses.
1912 */
1913 v->name = strdup(v->name);
1914 v_ctxt = ctxt;
1915 } else if (ctxt != VAR_GLOBAL) {
1916 if (VarFind(v->name, ctxt, 0) == (Var *)NIL)
1917 v_ctxt = VAR_GLOBAL;
1918 else
1919 v_ctxt = ctxt;
1920 }
1921
1922 switch ((how = *tstr)) {
1923 case '+':
1924 case '?':
1925 case '!':
1926 cp = &tstr[2];
1927 break;
1928 default:
1929 cp = ++tstr;
1930 break;
1931 }
1932 delim = '}';
1933 pattern.flags = 0;
1934
1935 if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
1936 NULL, &pattern.rightLen, NULL)) == NULL) {
1937 if (v->flags & VAR_JUNK) {
1938 free(v->name);
1939 v->name = str;
1940 }
1941 goto cleanup;
1942 }
1943 termc = *--cp;
1944 delim = '\0';
1945
1946 switch (how) {
1947 case '+':
1948 Var_Append(v->name, pattern.rhs, v_ctxt);
1949 break;
1950 case '!':
1951 newStr = Cmd_Exec (pattern.rhs, &emsg);
1952 if (emsg)
1953 Error (emsg, str);
1954 else
1955 Var_Set(v->name, newStr, v_ctxt);
1956 if (newStr)
1957 free(newStr);
1958 break;
1959 case '?':
1960 if ((v->flags & VAR_JUNK) == 0)
1961 break;
1962 /* FALLTHROUGH */
1963 default:
1964 Var_Set(v->name, pattern.rhs, v_ctxt);
1965 break;
1966 }
1967 if (v->flags & VAR_JUNK) {
1968 free(v->name);
1969 v->name = str;
1970 }
1971 free(pattern.rhs);
1972 newStr = var_Error;
1973 break;
1974 }
1975 goto default_case;
1976 case '@':
1977 {
1978 VarLoop_t loop;
1979 int flags = VAR_NOSUBST;
1980
1981 cp = ++tstr;
1982 delim = '@';
1983 if ((loop.tvar = VarGetPattern(ctxt, err, &cp, delim,
1984 &flags, &loop.tvarLen,
1985 NULL)) == NULL)
1986 goto cleanup;
1987
1988 if ((loop.str = VarGetPattern(ctxt, err, &cp, delim,
1989 &flags, &loop.strLen,
1990 NULL)) == NULL)
1991 goto cleanup;
1992
1993 termc = *cp;
1994 delim = '\0';
1995
1996 loop.err = err;
1997 loop.ctxt = ctxt;
1998 newStr = VarModify(str, VarLoopExpand,
1999 (ClientData)&loop);
2000 free(loop.tvar);
2001 free(loop.str);
2002 break;
2003 }
2004 case 'D':
2005 case 'U':
2006 {
2007 Buffer buf; /* Buffer for patterns */
2008 int wantit; /* want data in buffer */
2009
2010 /*
2011 * Pass through tstr looking for 1) escaped delimiters,
2012 * '$'s and backslashes (place the escaped character in
2013 * uninterpreted) and 2) unescaped $'s that aren't before
2014 * the delimiter (expand the variable substitution).
2015 * The result is left in the Buffer buf.
2016 */
2017 buf = Buf_Init(0);
2018 for (cp = tstr + 1;
2019 *cp != endc && *cp != ':' && *cp != '\0';
2020 cp++) {
2021 if ((*cp == '\\') &&
2022 ((cp[1] == ':') ||
2023 (cp[1] == '$') ||
2024 (cp[1] == endc) ||
2025 (cp[1] == '\\')))
2026 {
2027 Buf_AddByte(buf, (Byte) cp[1]);
2028 cp++;
2029 } else if (*cp == '$') {
2030 /*
2031 * If unescaped dollar sign, assume it's a
2032 * variable substitution and recurse.
2033 */
2034 char *cp2;
2035 int len;
2036 Boolean freeIt;
2037
2038 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
2039 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
2040 if (freeIt)
2041 free(cp2);
2042 cp += len - 1;
2043 } else {
2044 Buf_AddByte(buf, (Byte) *cp);
2045 }
2046 }
2047 Buf_AddByte(buf, (Byte) '\0');
2048
2049 termc = *cp;
2050
2051 if (*tstr == 'U')
2052 wantit = ((v->flags & VAR_JUNK) != 0);
2053 else
2054 wantit = ((v->flags & VAR_JUNK) == 0);
2055 if ((v->flags & VAR_JUNK) != 0)
2056 v->flags |= VAR_KEEP;
2057 if (wantit) {
2058 newStr = (char *)Buf_GetAll(buf, (int *)NULL);
2059 Buf_Destroy(buf, FALSE);
2060 } else {
2061 newStr = str;
2062 Buf_Destroy(buf, TRUE);
2063 }
2064 break;
2065 }
2066 case 'L':
2067 {
2068 if (v->flags & VAR_JUNK) {
2069 v->flags |= VAR_KEEP;
2070 /*
2071 * JUNK vars get name = &str[1]
2072 * we want the full name here.
2073 */
2074 v->name--;
2075 }
2076 cp = ++tstr;
2077 termc = *tstr;
2078 newStr = strdup(v->name);
2079 break;
2080 }
2081 case 'P':
2082 {
2083 GNode *gn;
2084
2085 if (v->flags & VAR_JUNK) {
2086 v->flags |= VAR_KEEP;
2087 /*
2088 * JUNK vars get name = &str[1]
2089 * we want the full name here.
2090 */
2091 v->name--;
2092 }
2093 cp = ++tstr;
2094 termc = *tstr;
2095 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2096 newStr = strdup((gn == NILGNODE || gn->path == NULL) ?
2097 v->name :
2098 gn->path);
2099 break;
2100 }
2101 case '!':
2102 {
2103 char *emsg;
2104 VarPattern pattern;
2105 pattern.flags = 0;
2106
2107 delim = '!';
2108
2109 cp = ++tstr;
2110 if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2111 NULL, &pattern.rightLen, NULL)) == NULL)
2112 goto cleanup;
2113 newStr = Cmd_Exec (pattern.rhs, &emsg);
2114 free(pattern.rhs);
2115 if (emsg)
2116 Error (emsg, str);
2117 termc = *cp;
2118 delim = '\0';
2119 if (v->flags & VAR_JUNK) {
2120 v->flags |= VAR_KEEP;
2121 }
2122 break;
2123 }
2124 case 'N':
2125 case 'M':
2126 {
2127 char *pattern;
2128 char *cp2;
2129 Boolean copy;
2130 int nest;
2131
2132 copy = FALSE;
2133 nest = 1;
2134 for (cp = tstr + 1;
2135 *cp != '\0' && *cp != ':';
2136 cp++)
2137 {
2138 if (*cp == '\\' &&
2139 (cp[1] == ':' ||
2140 cp[1] == endc || cp[1] == startc)) {
2141 copy = TRUE;
2142 cp++;
2143 continue;
2144 }
2145 if (*cp == startc)
2146 ++nest;
2147 if (*cp == endc) {
2148 --nest;
2149 if (nest == 0)
2150 break;
2151 }
2152 }
2153 termc = *cp;
2154 *cp = '\0';
2155 if (copy) {
2156 /*
2157 * Need to compress the \:'s out of the pattern, so
2158 * allocate enough room to hold the uncompressed
2159 * pattern (note that cp started at tstr+1, so
2160 * cp - tstr takes the null byte into account) and
2161 * compress the pattern into the space.
2162 */
2163 pattern = emalloc(cp - tstr);
2164 for (cp2 = pattern, cp = tstr + 1;
2165 *cp != '\0';
2166 cp++, cp2++)
2167 {
2168 if ((*cp == '\\') &&
2169 (cp[1] == ':' || cp[1] == endc)) {
2170 cp++;
2171 }
2172 *cp2 = *cp;
2173 }
2174 *cp2 = '\0';
2175 } else {
2176 pattern = &tstr[1];
2177 }
2178 if ((cp2 = strchr(pattern, '$'))) {
2179 cp2 = pattern;
2180 pattern = Var_Subst(NULL, cp2, ctxt, err);
2181 if (copy)
2182 free(cp2);
2183 copy = TRUE;
2184 }
2185 if (*tstr == 'M' || *tstr == 'm') {
2186 newStr = VarModify(str, VarMatch, (ClientData)pattern);
2187 } else {
2188 newStr = VarModify(str, VarNoMatch,
2189 (ClientData)pattern);
2190 }
2191 if (copy) {
2192 free(pattern);
2193 }
2194 break;
2195 }
2196 case 'S':
2197 {
2198 VarPattern pattern;
2199
2200 pattern.flags = 0;
2201 delim = tstr[1];
2202 tstr += 2;
2203
2204 /*
2205 * If pattern begins with '^', it is anchored to the
2206 * start of the word -- skip over it and flag pattern.
2207 */
2208 if (*tstr == '^') {
2209 pattern.flags |= VAR_MATCH_START;
2210 tstr += 1;
2211 }
2212
2213 cp = tstr;
2214 if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
2215 &pattern.flags, &pattern.leftLen, NULL)) == NULL)
2216 goto cleanup;
2217
2218 if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2219 NULL, &pattern.rightLen, &pattern)) == NULL)
2220 goto cleanup;
2221
2222 /*
2223 * Check for global substitution. If 'g' after the final
2224 * delimiter, substitution is global and is marked that
2225 * way.
2226 */
2227 for (;; cp++) {
2228 switch (*cp) {
2229 case 'g':
2230 pattern.flags |= VAR_SUB_GLOBAL;
2231 continue;
2232 case '1':
2233 pattern.flags |= VAR_SUB_ONE;
2234 continue;
2235 }
2236 break;
2237 }
2238
2239 termc = *cp;
2240 newStr = VarModify(str, VarSubstitute,
2241 (ClientData)&pattern);
2242
2243 /*
2244 * Free the two strings.
2245 */
2246 free(pattern.lhs);
2247 free(pattern.rhs);
2248 break;
2249 }
2250 case '?':
2251 {
2252 VarPattern pattern;
2253 Boolean value;
2254
2255 /* find ':', and then substitute accordingly */
2256
2257 pattern.flags = 0;
2258
2259 cp = ++tstr;
2260 delim = ':';
2261 if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
2262 NULL, &pattern.leftLen, NULL)) == NULL)
2263 goto cleanup;
2264
2265 delim = '}';
2266 if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
2267 NULL, &pattern.rightLen, NULL)) == NULL)
2268 goto cleanup;
2269
2270 termc = *--cp;
2271 delim = '\0';
2272 if (Cond_EvalExpression(1, str, &value, 0) == COND_INVALID){
2273 Error("Bad conditional expression `%s' in %s?%s:%s",
2274 str, str, pattern.lhs, pattern.rhs);
2275 goto cleanup;
2276 }
2277
2278 if (value) {
2279 newStr = pattern.lhs;
2280 free(pattern.rhs);
2281 } else {
2282 newStr = pattern.rhs;
2283 free(pattern.lhs);
2284 }
2285 break;
2286 }
2287 #ifndef NO_REGEX
2288 case 'C':
2289 {
2290 VarREPattern pattern;
2291 char *re;
2292 int error;
2293
2294 pattern.flags = 0;
2295 delim = tstr[1];
2296 tstr += 2;
2297
2298 cp = tstr;
2299
2300 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
2301 NULL, NULL)) == NULL)
2302 goto cleanup;
2303
2304 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
2305 delim, NULL, NULL, NULL)) == NULL){
2306 free(re);
2307 goto cleanup;
2308 }
2309
2310 for (;; cp++) {
2311 switch (*cp) {
2312 case 'g':
2313 pattern.flags |= VAR_SUB_GLOBAL;
2314 continue;
2315 case '1':
2316 pattern.flags |= VAR_SUB_ONE;
2317 continue;
2318 }
2319 break;
2320 }
2321
2322 termc = *cp;
2323
2324 error = regcomp(&pattern.re, re, REG_EXTENDED);
2325 free(re);
2326 if (error) {
2327 *lengthPtr = cp - start + 1;
2328 VarREError(error, &pattern.re, "RE substitution error");
2329 free(pattern.replace);
2330 return (var_Error);
2331 }
2332
2333 pattern.nsub = pattern.re.re_nsub + 1;
2334 if (pattern.nsub < 1)
2335 pattern.nsub = 1;
2336 if (pattern.nsub > 10)
2337 pattern.nsub = 10;
2338 pattern.matches = emalloc(pattern.nsub *
2339 sizeof(regmatch_t));
2340 newStr = VarModify(str, VarRESubstitute,
2341 (ClientData) &pattern);
2342 regfree(&pattern.re);
2343 free(pattern.replace);
2344 free(pattern.matches);
2345 break;
2346 }
2347 #endif
2348 case 'Q':
2349 if (tstr[1] == endc || tstr[1] == ':') {
2350 newStr = VarQuote (str);
2351 cp = tstr + 1;
2352 termc = *cp;
2353 break;
2354 }
2355 /*FALLTHRU*/
2356 case 'T':
2357 if (tstr[1] == endc || tstr[1] == ':') {
2358 newStr = VarModify (str, VarTail, (ClientData)0);
2359 cp = tstr + 1;
2360 termc = *cp;
2361 break;
2362 }
2363 /*FALLTHRU*/
2364 case 'H':
2365 if (tstr[1] == endc || tstr[1] == ':') {
2366 newStr = VarModify (str, VarHead, (ClientData)0);
2367 cp = tstr + 1;
2368 termc = *cp;
2369 break;
2370 }
2371 /*FALLTHRU*/
2372 case 'E':
2373 if (tstr[1] == endc || tstr[1] == ':') {
2374 newStr = VarModify (str, VarSuffix, (ClientData)0);
2375 cp = tstr + 1;
2376 termc = *cp;
2377 break;
2378 }
2379 /*FALLTHRU*/
2380 case 'R':
2381 if (tstr[1] == endc || tstr[1] == ':') {
2382 newStr = VarModify (str, VarRoot, (ClientData)0);
2383 cp = tstr + 1;
2384 termc = *cp;
2385 break;
2386 }
2387 /*FALLTHRU*/
2388 case 'O':
2389 if (tstr[1] == endc || tstr[1] == ':') {
2390 newStr = VarSort (str);
2391 cp = tstr + 1;
2392 termc = *cp;
2393 break;
2394 }
2395 #ifdef SUNSHCMD
2396 case 's':
2397 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
2398 char *err;
2399 newStr = Cmd_Exec (str, &err);
2400 if (err)
2401 Error (err, str);
2402 cp = tstr + 2;
2403 termc = *cp;
2404 break;
2405 }
2406 /*FALLTHRU*/
2407 #endif
2408 default:
2409 default_case:
2410 {
2411 #ifdef SYSVVARSUB
2412 /*
2413 * This can either be a bogus modifier or a System-V
2414 * substitution command.
2415 */
2416 VarPattern pattern;
2417 Boolean eqFound;
2418
2419 pattern.flags = 0;
2420 eqFound = FALSE;
2421 /*
2422 * First we make a pass through the string trying
2423 * to verify it is a SYSV-make-style translation:
2424 * it must be: <string1>=<string2>)
2425 */
2426 cp = tstr;
2427 cnt = 1;
2428 while (*cp != '\0' && cnt) {
2429 if (*cp == '=') {
2430 eqFound = TRUE;
2431 /* continue looking for endc */
2432 }
2433 else if (*cp == endc)
2434 cnt--;
2435 else if (*cp == startc)
2436 cnt++;
2437 if (cnt)
2438 cp++;
2439 }
2440 if (*cp == endc && eqFound) {
2441
2442 /*
2443 * Now we break this sucker into the lhs and
2444 * rhs. We must null terminate them of course.
2445 */
2446 for (cp = tstr; *cp != '='; cp++)
2447 continue;
2448 pattern.lhs = tstr;
2449 pattern.leftLen = cp - tstr;
2450 *cp++ = '\0';
2451
2452 pattern.rhs = cp;
2453 cnt = 1;
2454 while (cnt) {
2455 if (*cp == endc)
2456 cnt--;
2457 else if (*cp == startc)
2458 cnt++;
2459 if (cnt)
2460 cp++;
2461 }
2462 pattern.rightLen = cp - pattern.rhs;
2463 *cp = '\0';
2464
2465 /*
2466 * SYSV modifications happen through the whole
2467 * string. Note the pattern is anchored at the end.
2468 */
2469 newStr = VarModify(str, VarSYSVMatch,
2470 (ClientData)&pattern);
2471
2472 /*
2473 * Restore the nulled characters
2474 */
2475 pattern.lhs[pattern.leftLen] = '=';
2476 pattern.rhs[pattern.rightLen] = endc;
2477 termc = endc;
2478 } else
2479 #endif
2480 {
2481 Error ("Unknown modifier '%c'\n", *tstr);
2482 for (cp = tstr+1;
2483 *cp != ':' && *cp != endc && *cp != '\0';
2484 cp++)
2485 continue;
2486 termc = *cp;
2487 newStr = var_Error;
2488 }
2489 }
2490 }
2491 if (DEBUG(VAR)) {
2492 printf("Result is \"%s\"\n", newStr);
2493 }
2494
2495 if (newStr != str) {
2496 if (*freePtr) {
2497 free (str);
2498 }
2499 str = newStr;
2500 if (str != var_Error) {
2501 *freePtr = TRUE;
2502 } else {
2503 *freePtr = FALSE;
2504 }
2505 }
2506 if (termc == '\0') {
2507 Error("Unclosed variable specification for %s", v->name);
2508 } else if (termc == ':') {
2509 *cp++ = termc;
2510 } else {
2511 *cp = termc;
2512 }
2513 tstr = cp;
2514 }
2515 *lengthPtr = tstr - start + 1;
2516 } else {
2517 *lengthPtr = tstr - start + 1;
2518 *tstr = endc;
2519 }
2520
2521 if (v->flags & VAR_FROM_ENV) {
2522 Boolean destroy = FALSE;
2523
2524 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
2525 destroy = TRUE;
2526 } else {
2527 /*
2528 * Returning the value unmodified, so tell the caller to free
2529 * the thing.
2530 */
2531 *freePtr = TRUE;
2532 }
2533 free(v->name);
2534 Buf_Destroy(v->val, destroy);
2535 free((Address)v);
2536 } else if (v->flags & VAR_JUNK) {
2537 /*
2538 * Perform any free'ing needed and set *freePtr to FALSE so the caller
2539 * doesn't try to free a static pointer.
2540 * If VAR_KEEP is also set then we want to keep str as is.
2541 */
2542 if (!(v->flags & VAR_KEEP)) {
2543 if (*freePtr) {
2544 free(str);
2545 }
2546 *freePtr = FALSE;
2547 }
2548 Buf_Destroy(v->val, TRUE);
2549 free((Address)v);
2550 if (!(v->flags & VAR_KEEP)) {
2551 if (dynamic) {
2552 str = emalloc(*lengthPtr + 1);
2553 strncpy(str, start, *lengthPtr);
2554 str[*lengthPtr] = '\0';
2555 *freePtr = TRUE;
2556 } else {
2557 str = var_Error;
2558 }
2559 }
2560 }
2561 return (str);
2562
2563 cleanup:
2564 *lengthPtr = cp - start + 1;
2565 if (*freePtr)
2566 free(str);
2567 if (delim != '\0')
2568 Error("Unclosed substitution for %s (%c missing)",
2569 v->name, delim);
2570 return (var_Error);
2571 }
2572
2573 /*-
2574 *-----------------------------------------------------------------------
2575 * Var_Subst --
2576 * Substitute for all variables in the given string in the given context
2577 * If undefErr is TRUE, Parse_Error will be called when an undefined
2578 * variable is encountered.
2579 *
2580 * Results:
2581 * The resulting string.
2582 *
2583 * Side Effects:
2584 * None. The old string must be freed by the caller
2585 *-----------------------------------------------------------------------
2586 */
2587 char *
2588 Var_Subst (var, str, ctxt, undefErr)
2589 char *var; /* Named variable || NULL for all */
2590 char *str; /* the string in which to substitute */
2591 GNode *ctxt; /* the context wherein to find variables */
2592 Boolean undefErr; /* TRUE if undefineds are an error */
2593 {
2594 Buffer buf; /* Buffer for forming things */
2595 char *val; /* Value to substitute for a variable */
2596 int length; /* Length of the variable invocation */
2597 Boolean doFree; /* Set true if val should be freed */
2598 static Boolean errorReported; /* Set true if an error has already
2599 * been reported to prevent a plethora
2600 * of messages when recursing */
2601
2602 buf = Buf_Init (MAKE_BSIZE);
2603 errorReported = FALSE;
2604
2605 while (*str) {
2606 if (var == NULL && (*str == '$') && (str[1] == '$')) {
2607 /*
2608 * A dollar sign may be escaped either with another dollar sign.
2609 * In such a case, we skip over the escape character and store the
2610 * dollar sign into the buffer directly.
2611 */
2612 str++;
2613 Buf_AddByte(buf, (Byte)*str);
2614 str++;
2615 } else if (*str != '$') {
2616 /*
2617 * Skip as many characters as possible -- either to the end of
2618 * the string or to the next dollar sign (variable invocation).
2619 */
2620 char *cp;
2621
2622 for (cp = str++; *str != '$' && *str != '\0'; str++)
2623 continue;
2624 Buf_AddBytes(buf, str - cp, (Byte *)cp);
2625 } else {
2626 if (var != NULL) {
2627 int expand;
2628 for (;;) {
2629 if (str[1] != '(' && str[1] != '{') {
2630 if (str[1] != *var || strlen(var) > 1) {
2631 Buf_AddBytes(buf, 2, (Byte *) str);
2632 str += 2;
2633 expand = FALSE;
2634 }
2635 else
2636 expand = TRUE;
2637 break;
2638 }
2639 else {
2640 char *p;
2641
2642 /*
2643 * Scan up to the end of the variable name.
2644 */
2645 for (p = &str[2]; *p &&
2646 *p != ':' && *p != ')' && *p != '}'; p++)
2647 if (*p == '$')
2648 break;
2649 /*
2650 * A variable inside the variable. We cannot expand
2651 * the external variable yet, so we try again with
2652 * the nested one
2653 */
2654 if (*p == '$') {
2655 Buf_AddBytes(buf, p - str, (Byte *) str);
2656 str = p;
2657 continue;
2658 }
2659
2660 if (strncmp(var, str + 2, p - str - 2) != 0 ||
2661 var[p - str - 2] != '\0') {
2662 /*
2663 * Not the variable we want to expand, scan
2664 * until the next variable
2665 */
2666 for (;*p != '$' && *p != '\0'; p++)
2667 continue;
2668 Buf_AddBytes(buf, p - str, (Byte *) str);
2669 str = p;
2670 expand = FALSE;
2671 }
2672 else
2673 expand = TRUE;
2674 break;
2675 }
2676 }
2677 if (!expand)
2678 continue;
2679 }
2680
2681 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
2682
2683 /*
2684 * When we come down here, val should either point to the
2685 * value of this variable, suitably modified, or be NULL.
2686 * Length should be the total length of the potential
2687 * variable invocation (from $ to end character...)
2688 */
2689 if (val == var_Error || val == varNoError) {
2690 /*
2691 * If performing old-time variable substitution, skip over
2692 * the variable and continue with the substitution. Otherwise,
2693 * store the dollar sign and advance str so we continue with
2694 * the string...
2695 */
2696 if (oldVars) {
2697 str += length;
2698 } else if (undefErr) {
2699 /*
2700 * If variable is undefined, complain and skip the
2701 * variable. The complaint will stop us from doing anything
2702 * when the file is parsed.
2703 */
2704 if (!errorReported) {
2705 Parse_Error (PARSE_FATAL,
2706 "Undefined variable \"%.*s\"",length,str);
2707 }
2708 str += length;
2709 errorReported = TRUE;
2710 } else {
2711 Buf_AddByte (buf, (Byte)*str);
2712 str += 1;
2713 }
2714 } else {
2715 /*
2716 * We've now got a variable structure to store in. But first,
2717 * advance the string pointer.
2718 */
2719 str += length;
2720
2721 /*
2722 * Copy all the characters from the variable value straight
2723 * into the new string.
2724 */
2725 Buf_AddBytes (buf, strlen (val), (Byte *)val);
2726 if (doFree) {
2727 free ((Address)val);
2728 }
2729 }
2730 }
2731 }
2732
2733 Buf_AddByte (buf, '\0');
2734 str = (char *)Buf_GetAll (buf, (int *)NULL);
2735 Buf_Destroy (buf, FALSE);
2736 return (str);
2737 }
2738
2739 /*-
2740 *-----------------------------------------------------------------------
2741 * Var_GetTail --
2742 * Return the tail from each of a list of words. Used to set the
2743 * System V local variables.
2744 *
2745 * Results:
2746 * The resulting string.
2747 *
2748 * Side Effects:
2749 * None.
2750 *
2751 *-----------------------------------------------------------------------
2752 */
2753 char *
2754 Var_GetTail(file)
2755 char *file; /* Filename to modify */
2756 {
2757 return(VarModify(file, VarTail, (ClientData)0));
2758 }
2759
2760 /*-
2761 *-----------------------------------------------------------------------
2762 * Var_GetHead --
2763 * Find the leading components of a (list of) filename(s).
2764 * XXX: VarHead does not replace foo by ., as (sun) System V make
2765 * does.
2766 *
2767 * Results:
2768 * The leading components.
2769 *
2770 * Side Effects:
2771 * None.
2772 *
2773 *-----------------------------------------------------------------------
2774 */
2775 char *
2776 Var_GetHead(file)
2777 char *file; /* Filename to manipulate */
2778 {
2779 return(VarModify(file, VarHead, (ClientData)0));
2780 }
2781
2782 /*-
2783 *-----------------------------------------------------------------------
2784 * Var_Init --
2785 * Initialize the module
2786 *
2787 * Results:
2788 * None
2789 *
2790 * Side Effects:
2791 * The VAR_CMD and VAR_GLOBAL contexts are created
2792 *-----------------------------------------------------------------------
2793 */
2794 void
2795 Var_Init ()
2796 {
2797 VAR_GLOBAL = Targ_NewGN ("Global");
2798 VAR_CMD = Targ_NewGN ("Command");
2799
2800 }
2801
2802
2803 void
2804 Var_End ()
2805 {
2806 }
2807
2808
2809 /****************** PRINT DEBUGGING INFO *****************/
2810 static void
2811 VarPrintVar (vp)
2812 ClientData vp;
2813 {
2814 Var *v = (Var *) vp;
2815 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
2816 }
2817
2818 /*-
2819 *-----------------------------------------------------------------------
2820 * Var_Dump --
2821 * print all variables in a context
2822 *-----------------------------------------------------------------------
2823 */
2824 void
2825 Var_Dump (ctxt)
2826 GNode *ctxt;
2827 {
2828 Hash_Search search;
2829 Hash_Entry *h;
2830
2831 for (h = Hash_EnumFirst(&ctxt->context, &search);
2832 h != NULL;
2833 h = Hash_EnumNext(&search)) {
2834 VarPrintVar(Hash_GetValue(h));
2835 }
2836 }
2837