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