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