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