var.c revision 1.101 1 /* $NetBSD: var.c,v 1.101 2006/02/18 01:29:27 sjg 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.101 2006/02/18 01:29:27 sjg 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.101 2006/02/18 01:29:27 sjg 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 char *tstr2; /* Secondary tstr if we need
1894 * to expand modifiers */
1895 Var *v; /* Variable in invocation */
1896 const char *cp; /* Secondary pointer into str (place marker
1897 * for tstr) */
1898 Boolean haveModifier;/* TRUE if have modifiers for the variable */
1899 char endc; /* Ending character when variable in parens
1900 * or braces */
1901 char startc=0; /* Starting character when variable in parens
1902 * or braces */
1903 int cnt; /* Used to count brace pairs when variable in
1904 * in parens or braces */
1905 int vlen; /* Length of variable name */
1906 const char *start;
1907 char delim;
1908 char *nstr;
1909 Boolean dynamic; /* TRUE if the variable is local and we're
1910 * expanding it in a non-local context. This
1911 * is done to support dynamic sources. The
1912 * result is just the invocation, unaltered */
1913 Var_Parse_State parsestate; /* Flags passed to helper functions */
1914
1915 *freePtr = FALSE;
1916 dynamic = FALSE;
1917 start = str;
1918 parsestate.oneBigWord = FALSE;
1919 parsestate.varSpace = ' '; /* word separator */
1920 tstr2 = NULL;
1921
1922 if (str[1] != PROPEN && str[1] != BROPEN) {
1923 /*
1924 * If it's not bounded by braces of some sort, life is much simpler.
1925 * We just need to check for the first character and return the
1926 * value if it exists.
1927 */
1928 char name[2];
1929
1930 name[0] = str[1];
1931 name[1] = '\0';
1932
1933 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1934 if (v == (Var *)NIL) {
1935 *lengthPtr = 2;
1936
1937 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1938 /*
1939 * If substituting a local variable in a non-local context,
1940 * assume it's for dynamic source stuff. We have to handle
1941 * this specially and return the longhand for the variable
1942 * with the dollar sign escaped so it makes it back to the
1943 * caller. Only four of the local variables are treated
1944 * specially as they are the only four that will be set
1945 * when dynamic sources are expanded.
1946 */
1947 switch (str[1]) {
1948 case '@':
1949 return UNCONST("$(.TARGET)");
1950 case '%':
1951 return UNCONST("$(.ARCHIVE)");
1952 case '*':
1953 return UNCONST("$(.PREFIX)");
1954 case '!':
1955 return UNCONST("$(.MEMBER)");
1956 }
1957 }
1958 /*
1959 * Error
1960 */
1961 return (err ? var_Error : varNoError);
1962 } else {
1963 haveModifier = FALSE;
1964 tstr = &str[1];
1965 endc = str[1];
1966 }
1967 } else if (str[1] == '\0') {
1968 *lengthPtr = 1;
1969 return (err ? var_Error : varNoError);
1970 } else {
1971 Buffer buf; /* Holds the variable name */
1972
1973 startc = str[1];
1974 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
1975 buf = Buf_Init(MAKE_BSIZE);
1976
1977 /*
1978 * Skip to the end character or a colon, whichever comes first.
1979 */
1980 for (tstr = str + 2;
1981 *tstr != '\0' && *tstr != endc && *tstr != ':';
1982 tstr++)
1983 {
1984 /*
1985 * A variable inside a variable, expand
1986 */
1987 if (*tstr == '$') {
1988 int rlen;
1989 Boolean rfree;
1990 char *rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
1991 if (rval != NULL) {
1992 Buf_AddBytes(buf, strlen(rval), (Byte *)rval);
1993 if (rfree)
1994 free(rval);
1995 }
1996 tstr += rlen - 1;
1997 }
1998 else
1999 Buf_AddByte(buf, (Byte)*tstr);
2000 }
2001 if (*tstr == ':') {
2002 haveModifier = TRUE;
2003 } else if (*tstr != '\0') {
2004 haveModifier = FALSE;
2005 } else {
2006 /*
2007 * If we never did find the end character, return NULL
2008 * right now, setting the length to be the distance to
2009 * the end of the string, since that's what make does.
2010 */
2011 *lengthPtr = tstr - str;
2012 return (var_Error);
2013 }
2014 *WR(tstr) = '\0';
2015 Buf_AddByte(buf, (Byte)'\0');
2016 str = Buf_GetAll(buf, NULL);
2017 vlen = strlen(str);
2018
2019 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
2020 if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
2021 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
2022 {
2023 /*
2024 * Check for bogus D and F forms of local variables since we're
2025 * in a local context and the name is the right length.
2026 */
2027 switch(*str) {
2028 case '@':
2029 case '%':
2030 case '*':
2031 case '!':
2032 case '>':
2033 case '<':
2034 {
2035 char vname[2];
2036 char *val;
2037
2038 /*
2039 * Well, it's local -- go look for it.
2040 */
2041 vname[0] = *str;
2042 vname[1] = '\0';
2043 v = VarFind(vname, ctxt, 0);
2044
2045 if (v != (Var *)NIL) {
2046 /*
2047 * No need for nested expansion or anything, as we're
2048 * the only one who sets these things and we sure don't
2049 * but nested invocations in them...
2050 */
2051 val = (char *)Buf_GetAll(v->val, NULL);
2052
2053 if (str[1] == 'D') {
2054 val = VarModify(ctxt, &parsestate, val, VarHead,
2055 (ClientData)0);
2056 } else {
2057 val = VarModify(ctxt, &parsestate, val, VarTail,
2058 (ClientData)0);
2059 }
2060 /*
2061 * Resulting string is dynamically allocated, so
2062 * tell caller to free it.
2063 */
2064 *freePtr = TRUE;
2065 *lengthPtr = tstr-start+1;
2066 *WR(tstr) = endc;
2067 Buf_Destroy(buf, TRUE);
2068 return(val);
2069 }
2070 break;
2071 }
2072 }
2073 }
2074
2075 if (v == (Var *)NIL) {
2076 if (((vlen == 1) ||
2077 (((vlen == 2) && (str[1] == 'F' ||
2078 str[1] == 'D')))) &&
2079 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
2080 {
2081 /*
2082 * If substituting a local variable in a non-local context,
2083 * assume it's for dynamic source stuff. We have to handle
2084 * this specially and return the longhand for the variable
2085 * with the dollar sign escaped so it makes it back to the
2086 * caller. Only four of the local variables are treated
2087 * specially as they are the only four that will be set
2088 * when dynamic sources are expanded.
2089 */
2090 switch (*str) {
2091 case '@':
2092 case '%':
2093 case '*':
2094 case '!':
2095 dynamic = TRUE;
2096 break;
2097 }
2098 } else if ((vlen > 2) && (*str == '.') &&
2099 isupper((unsigned char) str[1]) &&
2100 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
2101 {
2102 int len;
2103
2104 len = vlen - 1;
2105 if ((strncmp(str, ".TARGET", len) == 0) ||
2106 (strncmp(str, ".ARCHIVE", len) == 0) ||
2107 (strncmp(str, ".PREFIX", len) == 0) ||
2108 (strncmp(str, ".MEMBER", len) == 0))
2109 {
2110 dynamic = TRUE;
2111 }
2112 }
2113
2114 if (!haveModifier) {
2115 /*
2116 * No modifiers -- have specification length so we can return
2117 * now.
2118 */
2119 *lengthPtr = tstr - start + 1;
2120 *WR(tstr) = endc;
2121 if (dynamic) {
2122 char *pstr = emalloc(*lengthPtr + 1);
2123 strncpy(pstr, start, *lengthPtr);
2124 pstr[*lengthPtr] = '\0';
2125 *freePtr = TRUE;
2126 Buf_Destroy(buf, TRUE);
2127 return(pstr);
2128 } else {
2129 Buf_Destroy(buf, TRUE);
2130 return (err ? var_Error : varNoError);
2131 }
2132 } else {
2133 /*
2134 * Still need to get to the end of the variable specification,
2135 * so kludge up a Var structure for the modifications
2136 */
2137 v = emalloc(sizeof(Var));
2138 v->name = UNCONST(str);
2139 v->val = Buf_Init(1);
2140 v->flags = VAR_JUNK;
2141 Buf_Destroy(buf, FALSE);
2142 }
2143 } else
2144 Buf_Destroy(buf, TRUE);
2145 }
2146
2147
2148 if (v->flags & VAR_IN_USE) {
2149 Fatal("Variable %s is recursive.", v->name);
2150 /*NOTREACHED*/
2151 } else {
2152 v->flags |= VAR_IN_USE;
2153 }
2154 /*
2155 * Before doing any modification, we have to make sure the value
2156 * has been fully expanded. If it looks like recursion might be
2157 * necessary (there's a dollar sign somewhere in the variable's value)
2158 * we just call Var_Subst to do any other substitutions that are
2159 * necessary. Note that the value returned by Var_Subst will have
2160 * been dynamically-allocated, so it will need freeing when we
2161 * return.
2162 */
2163 nstr = (char *)Buf_GetAll(v->val, NULL);
2164 if (strchr(nstr, '$') != NULL) {
2165 nstr = Var_Subst(NULL, nstr, ctxt, err);
2166 *freePtr = TRUE;
2167 }
2168
2169 v->flags &= ~VAR_IN_USE;
2170
2171 /*
2172 * Now we need to apply any modifiers the user wants applied.
2173 * These are:
2174 * :M<pattern> words which match the given <pattern>.
2175 * <pattern> is of the standard file
2176 * wildcarding form.
2177 * :N<pattern> words which do not match the given <pattern>.
2178 * :S<d><pat1><d><pat2><d>[1gW]
2179 * Substitute <pat2> for <pat1> in the value
2180 * :C<d><pat1><d><pat2><d>[1gW]
2181 * Substitute <pat2> for regex <pat1> in the value
2182 * :H Substitute the head of each word
2183 * :T Substitute the tail of each word
2184 * :E Substitute the extension (minus '.') of
2185 * each word
2186 * :R Substitute the root of each word
2187 * (pathname minus the suffix).
2188 * :O ("Order") Alphabeticaly sort words in variable.
2189 * :Ox ("intermiX") Randomize words in variable.
2190 * :u ("uniq") Remove adjacent duplicate words.
2191 * :tu Converts the variable contents to uppercase.
2192 * :tl Converts the variable contents to lowercase.
2193 * :ts[c] Sets varSpace - the char used to
2194 * separate words to 'c'. If 'c' is
2195 * omitted then no separation is used.
2196 * :tW Treat the variable contents as a single
2197 * word, even if it contains spaces.
2198 * (Mnemonic: one big 'W'ord.)
2199 * :tw Treat the variable contents as multiple
2200 * space-separated words.
2201 * (Mnemonic: many small 'w'ords.)
2202 * :[index] Select a single word from the value.
2203 * :[start..end] Select multiple words from the value.
2204 * :[*] or :[0] Select the entire value, as a single
2205 * word. Equivalent to :tW.
2206 * :[@] Select the entire value, as multiple
2207 * words. Undoes the effect of :[*].
2208 * Equivalent to :tw.
2209 * :[#] Returns the number of words in the value.
2210 *
2211 * :?<true-value>:<false-value>
2212 * If the variable evaluates to true, return
2213 * true value, else return the second value.
2214 * :lhs=rhs Like :S, but the rhs goes to the end of
2215 * the invocation.
2216 * :sh Treat the current value as a command
2217 * to be run, new value is its output.
2218 * The following added so we can handle ODE makefiles.
2219 * :@<tmpvar>@<newval>@
2220 * Assign a temporary local variable <tmpvar>
2221 * to the current value of each word in turn
2222 * and replace each word with the result of
2223 * evaluating <newval>
2224 * :D<newval> Use <newval> as value if variable defined
2225 * :U<newval> Use <newval> as value if variable undefined
2226 * :L Use the name of the variable as the value.
2227 * :P Use the path of the node that has the same
2228 * name as the variable as the value. This
2229 * basically includes an implied :L so that
2230 * the common method of refering to the path
2231 * of your dependent 'x' in a rule is to use
2232 * the form '${x:P}'.
2233 * :!<cmd>! Run cmd much the same as :sh run's the
2234 * current value of the variable.
2235 * The ::= modifiers, actually assign a value to the variable.
2236 * Their main purpose is in supporting modifiers of .for loop
2237 * iterators and other obscure uses. They always expand to
2238 * nothing. In a target rule that would otherwise expand to an
2239 * empty line they can be preceded with @: to keep make happy.
2240 * Eg.
2241 *
2242 * foo: .USE
2243 * .for i in ${.TARGET} ${.TARGET:R}.gz
2244 * @: ${t::=$i}
2245 * @echo blah ${t:T}
2246 * .endfor
2247 *
2248 * ::=<str> Assigns <str> as the new value of variable.
2249 * ::?=<str> Assigns <str> as value of variable if
2250 * it was not already set.
2251 * ::+=<str> Appends <str> to variable.
2252 * ::!=<cmd> Assigns output of <cmd> as the new value of
2253 * variable.
2254 */
2255 if ((nstr != NULL) && haveModifier) {
2256 /*
2257 * Skip initial colon while putting it back.
2258 */
2259 *WR(tstr) = ':';
2260 tstr++;
2261 delim = '\0';
2262
2263 if (*tstr == '$') {
2264 tstr = tstr2 = Var_Subst(NULL, tstr, ctxt, err);
2265 }
2266 while (*tstr && *tstr != endc) {
2267 char *newStr; /* New value to return */
2268 char termc; /* Character which terminated scan */
2269
2270 if (DEBUG(VAR)) {
2271 printf("Applying :%c to \"%s\"\n", *tstr, nstr);
2272 }
2273 newStr = var_Error;
2274 switch (*tstr) {
2275 case ':':
2276 {
2277 if (tstr[1] == '=' ||
2278 (tstr[2] == '=' &&
2279 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2280 /*
2281 * "::=", "::!=", "::+=", or "::?="
2282 */
2283 GNode *v_ctxt; /* context where v belongs */
2284 const char *emsg;
2285 char *sv_name;
2286 VarPattern pattern;
2287 int how;
2288
2289 v_ctxt = ctxt;
2290 sv_name = NULL;
2291 ++tstr;
2292 if (v->flags & VAR_JUNK) {
2293 /*
2294 * We need to strdup() it incase
2295 * VarGetPattern() recurses.
2296 */
2297 sv_name = v->name;
2298 v->name = strdup(v->name);
2299 } else if (ctxt != VAR_GLOBAL) {
2300 if (VarFind(v->name, ctxt, 0) == (Var *)NIL)
2301 v_ctxt = VAR_GLOBAL;
2302 }
2303
2304 switch ((how = *tstr)) {
2305 case '+':
2306 case '?':
2307 case '!':
2308 cp = &tstr[2];
2309 break;
2310 default:
2311 cp = ++tstr;
2312 break;
2313 }
2314 delim = BRCLOSE;
2315 pattern.flags = 0;
2316
2317 pattern.rhs = VarGetPattern(ctxt, &parsestate, err,
2318 &cp, delim, NULL,
2319 &pattern.rightLen,
2320 NULL);
2321 if (v->flags & VAR_JUNK) {
2322 /* restore original name */
2323 free(v->name);
2324 v->name = sv_name;
2325 }
2326 if (pattern.rhs == NULL)
2327 goto cleanup;
2328
2329 termc = *--cp;
2330 delim = '\0';
2331
2332 switch (how) {
2333 case '+':
2334 Var_Append(v->name, pattern.rhs, v_ctxt);
2335 break;
2336 case '!':
2337 newStr = Cmd_Exec(pattern.rhs, &emsg);
2338 if (emsg)
2339 Error(emsg, nstr);
2340 else
2341 Var_Set(v->name, newStr, v_ctxt, 0);
2342 if (newStr)
2343 free(newStr);
2344 break;
2345 case '?':
2346 if ((v->flags & VAR_JUNK) == 0)
2347 break;
2348 /* FALLTHROUGH */
2349 default:
2350 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2351 break;
2352 }
2353 free(UNCONST(pattern.rhs));
2354 newStr = var_Error;
2355 break;
2356 }
2357 goto default_case; /* "::<unrecognised>" */
2358 }
2359 case '@':
2360 {
2361 VarLoop_t loop;
2362 int flags = VAR_NOSUBST;
2363
2364 cp = ++tstr;
2365 delim = '@';
2366 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, err,
2367 &cp, delim,
2368 &flags, &loop.tvarLen,
2369 NULL)) == NULL)
2370 goto cleanup;
2371
2372 if ((loop.str = VarGetPattern(ctxt, &parsestate, err,
2373 &cp, delim,
2374 &flags, &loop.strLen,
2375 NULL)) == NULL)
2376 goto cleanup;
2377
2378 termc = *cp;
2379 delim = '\0';
2380
2381 loop.err = err;
2382 loop.ctxt = ctxt;
2383 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2384 (ClientData)&loop);
2385 free(loop.tvar);
2386 free(loop.str);
2387 break;
2388 }
2389 case 'D':
2390 case 'U':
2391 {
2392 Buffer buf; /* Buffer for patterns */
2393 int wantit; /* want data in buffer */
2394
2395 /*
2396 * Pass through tstr looking for 1) escaped delimiters,
2397 * '$'s and backslashes (place the escaped character in
2398 * uninterpreted) and 2) unescaped $'s that aren't before
2399 * the delimiter (expand the variable substitution).
2400 * The result is left in the Buffer buf.
2401 */
2402 buf = Buf_Init(0);
2403 for (cp = tstr + 1;
2404 *cp != endc && *cp != ':' && *cp != '\0';
2405 cp++) {
2406 if ((*cp == '\\') &&
2407 ((cp[1] == ':') ||
2408 (cp[1] == '$') ||
2409 (cp[1] == endc) ||
2410 (cp[1] == '\\')))
2411 {
2412 Buf_AddByte(buf, (Byte)cp[1]);
2413 cp++;
2414 } else if (*cp == '$') {
2415 /*
2416 * If unescaped dollar sign, assume it's a
2417 * variable substitution and recurse.
2418 */
2419 char *cp2;
2420 int len;
2421 Boolean freeIt;
2422
2423 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
2424 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
2425 if (freeIt)
2426 free(cp2);
2427 cp += len - 1;
2428 } else {
2429 Buf_AddByte(buf, (Byte)*cp);
2430 }
2431 }
2432 Buf_AddByte(buf, (Byte)'\0');
2433
2434 termc = *cp;
2435
2436 if (*tstr == 'U')
2437 wantit = ((v->flags & VAR_JUNK) != 0);
2438 else
2439 wantit = ((v->flags & VAR_JUNK) == 0);
2440 if ((v->flags & VAR_JUNK) != 0)
2441 v->flags |= VAR_KEEP;
2442 if (wantit) {
2443 newStr = (char *)Buf_GetAll(buf, NULL);
2444 Buf_Destroy(buf, FALSE);
2445 } else {
2446 newStr = nstr;
2447 Buf_Destroy(buf, TRUE);
2448 }
2449 break;
2450 }
2451 case 'L':
2452 {
2453 if ((v->flags & VAR_JUNK) != 0)
2454 v->flags |= VAR_KEEP;
2455 newStr = strdup(v->name);
2456 cp = ++tstr;
2457 termc = *tstr;
2458 break;
2459 }
2460 case 'P':
2461 {
2462 GNode *gn;
2463
2464 if ((v->flags & VAR_JUNK) != 0)
2465 v->flags |= VAR_KEEP;
2466 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2467 if (gn == NILGNODE || gn->path == NULL)
2468 newStr = strdup(v->name);
2469 else
2470 newStr = strdup(gn->path);
2471 cp = ++tstr;
2472 termc = *tstr;
2473 break;
2474 }
2475 case '!':
2476 {
2477 const char *emsg;
2478 VarPattern pattern;
2479 pattern.flags = 0;
2480
2481 delim = '!';
2482
2483 cp = ++tstr;
2484 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, err,
2485 &cp, delim,
2486 NULL, &pattern.rightLen,
2487 NULL)) == NULL)
2488 goto cleanup;
2489 newStr = Cmd_Exec(pattern.rhs, &emsg);
2490 free(UNCONST(pattern.rhs));
2491 if (emsg)
2492 Error(emsg, nstr);
2493 termc = *cp;
2494 delim = '\0';
2495 if (v->flags & VAR_JUNK) {
2496 v->flags |= VAR_KEEP;
2497 }
2498 break;
2499 }
2500 case '[':
2501 {
2502 /*
2503 * Look for the closing ']', recursively
2504 * expanding any embedded variables.
2505 *
2506 * estr is a pointer to the expanded result,
2507 * which we must free().
2508 */
2509 char *estr;
2510
2511 cp = tstr+1; /* point to char after '[' */
2512 delim = ']'; /* look for closing ']' */
2513 estr = VarGetPattern(ctxt, &parsestate,
2514 err, &cp, delim,
2515 NULL, NULL, NULL);
2516 if (estr == NULL)
2517 goto cleanup; /* report missing ']' */
2518 /* now cp points just after the closing ']' */
2519 delim = '\0';
2520 if (cp[0] != ':' && cp[0] != endc) {
2521 /* Found junk after ']' */
2522 free(estr);
2523 goto bad_modifier;
2524 }
2525 if (estr[0] == '\0') {
2526 /* Found empty square brackets in ":[]". */
2527 free(estr);
2528 goto bad_modifier;
2529 } else if (estr[0] == '#' && estr[1] == '\0') {
2530 /* Found ":[#]" */
2531
2532 /*
2533 * We will need enough space for the decimal
2534 * representation of an int. We calculate the
2535 * space needed for the octal representation,
2536 * and add enough slop to cope with a '-' sign
2537 * (which should never be needed) and a '\0'
2538 * string terminator.
2539 */
2540 int newStrSize =
2541 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2542
2543 newStr = emalloc(newStrSize);
2544 if (parsestate.oneBigWord) {
2545 strncpy(newStr, "1", newStrSize);
2546 } else {
2547 /* XXX: brk_string() is a rather expensive
2548 * way of counting words. */
2549 char **av;
2550 char *as;
2551 int ac;
2552
2553 av = brk_string(nstr, &ac, FALSE, &as);
2554 snprintf(newStr, newStrSize, "%d", ac);
2555 free(as);
2556 free(av);
2557 }
2558 termc = *cp;
2559 free(estr);
2560 break;
2561 } else if (estr[0] == '*' && estr[1] == '\0') {
2562 /* Found ":[*]" */
2563 parsestate.oneBigWord = TRUE;
2564 newStr = nstr;
2565 termc = *cp;
2566 free(estr);
2567 break;
2568 } else if (estr[0] == '@' && estr[1] == '\0') {
2569 /* Found ":[@]" */
2570 parsestate.oneBigWord = FALSE;
2571 newStr = nstr;
2572 termc = *cp;
2573 free(estr);
2574 break;
2575 } else {
2576 /*
2577 * We expect estr to contain a single
2578 * integer for :[N], or two integers
2579 * separated by ".." for :[start..end].
2580 */
2581 char *ep;
2582
2583 VarSelectWords_t seldata = { 0, 0 };
2584
2585 seldata.start = strtol(estr, &ep, 0);
2586 if (ep == estr) {
2587 /* Found junk instead of a number */
2588 free(estr);
2589 goto bad_modifier;
2590 } else if (ep[0] == '\0') {
2591 /* Found only one integer in :[N] */
2592 seldata.end = seldata.start;
2593 } else if (ep[0] == '.' && ep[1] == '.' &&
2594 ep[2] != '\0') {
2595 /* Expecting another integer after ".." */
2596 ep += 2;
2597 seldata.end = strtol(ep, &ep, 0);
2598 if (ep[0] != '\0') {
2599 /* Found junk after ".." */
2600 free(estr);
2601 goto bad_modifier;
2602 }
2603 } else {
2604 /* Found junk instead of ".." */
2605 free(estr);
2606 goto bad_modifier;
2607 }
2608 /*
2609 * Now seldata is properly filled in,
2610 * but we still have to check for 0 as
2611 * a special case.
2612 */
2613 if (seldata.start == 0 && seldata.end == 0) {
2614 /* ":[0]" or perhaps ":[0..0]" */
2615 parsestate.oneBigWord = TRUE;
2616 newStr = nstr;
2617 termc = *cp;
2618 free(estr);
2619 break;
2620 } else if (seldata.start == 0 ||
2621 seldata.end == 0) {
2622 /* ":[0..N]" or ":[N..0]" */
2623 free(estr);
2624 goto bad_modifier;
2625 }
2626 /*
2627 * Normal case: select the words
2628 * described by seldata.
2629 */
2630 newStr = VarSelectWords(ctxt, &parsestate,
2631 nstr, &seldata);
2632
2633 termc = *cp;
2634 free(estr);
2635 break;
2636 }
2637
2638 }
2639 case 't':
2640 {
2641 cp = tstr + 1; /* make sure it is set */
2642 if (tstr[1] != endc && tstr[1] != ':') {
2643 if (tstr[1] == 's') {
2644 /*
2645 * Use the char (if any) at tstr[2]
2646 * as the word separator.
2647 */
2648 VarPattern pattern;
2649
2650 if (tstr[2] != endc &&
2651 (tstr[3] == endc || tstr[3] == ':')) {
2652 /* ":ts<unrecognised><endc>" or
2653 * ":ts<unrecognised>:" */
2654 parsestate.varSpace = tstr[2];
2655 cp = tstr + 3;
2656 } else if (tstr[2] == endc || tstr[2] == ':') {
2657 /* ":ts<endc>" or ":ts:" */
2658 parsestate.varSpace = 0; /* no separator */
2659 cp = tstr + 2;
2660 } else if (tstr[2] == '\\') {
2661 switch (tstr[3]) {
2662 case 'n':
2663 parsestate.varSpace = '\n';
2664 cp = tstr + 4;
2665 break;
2666 case 't':
2667 parsestate.varSpace = '\t';
2668 cp = tstr + 4;
2669 break;
2670 default:
2671 if (isdigit((unsigned char)tstr[3])) {
2672 char *ep;
2673
2674 parsestate.varSpace =
2675 strtoul(&tstr[3], &ep, 0);
2676 if (*ep != ':' && *ep != endc)
2677 goto bad_modifier;
2678 cp = ep;
2679 } else {
2680 /*
2681 * ":ts<backslash><unrecognised>".
2682 */
2683 goto bad_modifier;
2684 }
2685 break;
2686 }
2687 } else {
2688 /*
2689 * Found ":ts<unrecognised><unrecognised>".
2690 */
2691 goto bad_modifier;
2692 }
2693
2694 termc = *cp;
2695
2696 /*
2697 * We cannot be certain that VarModify
2698 * will be used - even if there is a
2699 * subsequent modifier, so do a no-op
2700 * VarSubstitute now to for str to be
2701 * re-expanded without the spaces.
2702 */
2703 pattern.flags = VAR_SUB_ONE;
2704 pattern.lhs = pattern.rhs = "\032";
2705 pattern.leftLen = pattern.rightLen = 1;
2706
2707 newStr = VarModify(ctxt, &parsestate, nstr,
2708 VarSubstitute,
2709 (ClientData)&pattern);
2710 } else if (tstr[2] == endc || tstr[2] == ':') {
2711 /*
2712 * Check for two-character options:
2713 * ":tu", ":tl"
2714 */
2715 if (tstr[1] == 'u' || tstr[1] == 'l') {
2716 newStr = VarChangeCase(nstr, (tstr[1] == 'u'));
2717 cp = tstr + 2;
2718 termc = *cp;
2719 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
2720 parsestate.oneBigWord = (tstr[1] == 'W');
2721 newStr = nstr;
2722 cp = tstr + 2;
2723 termc = *cp;
2724 } else {
2725 /* Found ":t<unrecognised>:" or
2726 * ":t<unrecognised><endc>". */
2727 goto bad_modifier;
2728 }
2729 } else {
2730 /*
2731 * Found ":t<unrecognised><unrecognised>".
2732 */
2733 goto bad_modifier;
2734 }
2735 } else {
2736 /*
2737 * Found ":t<endc>" or ":t:".
2738 */
2739 goto bad_modifier;
2740 }
2741 break;
2742 }
2743 case 'N':
2744 case 'M':
2745 {
2746 char *pattern;
2747 char *cp2;
2748 Boolean copy;
2749 int nest;
2750
2751 copy = FALSE;
2752 nest = 1;
2753 /*
2754 * In the loop below, ignore ':' unless we are at
2755 * (or back to) the original brace level.
2756 * XXX This will likely not work right if $() and ${}
2757 * are intermixed.
2758 */
2759 for (cp = tstr + 1;
2760 *cp != '\0' && !(*cp == ':' && nest == 1);
2761 cp++)
2762 {
2763 if (*cp == '\\' &&
2764 (cp[1] == ':' ||
2765 cp[1] == endc || cp[1] == startc)) {
2766 copy = TRUE;
2767 cp++;
2768 continue;
2769 }
2770 if (*cp == startc)
2771 ++nest;
2772 if (*cp == endc) {
2773 --nest;
2774 if (nest == 0)
2775 break;
2776 }
2777 }
2778 termc = *cp;
2779 *WR(cp) = '\0';
2780 if (copy) {
2781 /*
2782 * Need to compress the \:'s out of the pattern, so
2783 * allocate enough room to hold the uncompressed
2784 * pattern (note that cp started at tstr+1, so
2785 * cp - tstr takes the null byte into account) and
2786 * compress the pattern into the space.
2787 */
2788 pattern = emalloc(cp - tstr);
2789 for (cp2 = pattern, cp = tstr + 1;
2790 *cp != '\0';
2791 cp++, cp2++)
2792 {
2793 if ((*cp == '\\') &&
2794 (cp[1] == ':' || cp[1] == endc)) {
2795 cp++;
2796 }
2797 *cp2 = *cp;
2798 }
2799 *cp2 = '\0';
2800 } else {
2801 pattern = UNCONST(&tstr[1]);
2802 }
2803 if ((cp2 = strchr(pattern, '$'))) {
2804 cp2 = pattern;
2805 pattern = Var_Subst(NULL, cp2, ctxt, err);
2806 if (copy)
2807 free(cp2);
2808 copy = TRUE;
2809 }
2810 if (*tstr == 'M' || *tstr == 'm') {
2811 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
2812 (ClientData)pattern);
2813 } else {
2814 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
2815 (ClientData)pattern);
2816 }
2817 if (copy) {
2818 free(pattern);
2819 }
2820 break;
2821 }
2822 case 'S':
2823 {
2824 VarPattern pattern;
2825 Var_Parse_State tmpparsestate;
2826
2827 pattern.flags = 0;
2828 tmpparsestate = parsestate;
2829 delim = tstr[1];
2830 tstr += 2;
2831
2832 /*
2833 * If pattern begins with '^', it is anchored to the
2834 * start of the word -- skip over it and flag pattern.
2835 */
2836 if (*tstr == '^') {
2837 pattern.flags |= VAR_MATCH_START;
2838 tstr += 1;
2839 }
2840
2841 cp = tstr;
2842 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, err,
2843 &cp, delim,
2844 &pattern.flags,
2845 &pattern.leftLen,
2846 NULL)) == NULL)
2847 goto cleanup;
2848
2849 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, err,
2850 &cp, delim, NULL,
2851 &pattern.rightLen,
2852 &pattern)) == NULL)
2853 goto cleanup;
2854
2855 /*
2856 * Check for global substitution. If 'g' after the final
2857 * delimiter, substitution is global and is marked that
2858 * way.
2859 */
2860 for (;; cp++) {
2861 switch (*cp) {
2862 case 'g':
2863 pattern.flags |= VAR_SUB_GLOBAL;
2864 continue;
2865 case '1':
2866 pattern.flags |= VAR_SUB_ONE;
2867 continue;
2868 case 'W':
2869 tmpparsestate.oneBigWord = TRUE;
2870 continue;
2871 }
2872 break;
2873 }
2874
2875 termc = *cp;
2876 newStr = VarModify(ctxt, &tmpparsestate, nstr,
2877 VarSubstitute,
2878 (ClientData)&pattern);
2879
2880 /*
2881 * Free the two strings.
2882 */
2883 free(UNCONST(pattern.lhs));
2884 free(UNCONST(pattern.rhs));
2885 delim = '\0';
2886 break;
2887 }
2888 case '?':
2889 {
2890 VarPattern pattern;
2891 Boolean value;
2892
2893 /* find ':', and then substitute accordingly */
2894
2895 pattern.flags = 0;
2896
2897 cp = ++tstr;
2898 delim = ':';
2899 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, err,
2900 &cp, delim, NULL,
2901 &pattern.leftLen,
2902 NULL)) == NULL)
2903 goto cleanup;
2904
2905 /* BROPEN or PROPEN */
2906 delim = endc;
2907 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, err,
2908 &cp, delim, NULL,
2909 &pattern.rightLen,
2910 NULL)) == NULL)
2911 goto cleanup;
2912
2913 termc = *--cp;
2914 delim = '\0';
2915 if (Cond_EvalExpression(1, v->name, &value, 0)
2916 == COND_INVALID) {
2917 Error("Bad conditional expression `%s' in %s?%s:%s",
2918 v->name, v->name, pattern.lhs, pattern.rhs);
2919 goto cleanup;
2920 }
2921
2922 if (value) {
2923 newStr = UNCONST(pattern.lhs);
2924 free(UNCONST(pattern.rhs));
2925 } else {
2926 newStr = UNCONST(pattern.rhs);
2927 free(UNCONST(pattern.lhs));
2928 }
2929 if (v->flags & VAR_JUNK) {
2930 v->flags |= VAR_KEEP;
2931 }
2932 break;
2933 }
2934 #ifndef NO_REGEX
2935 case 'C':
2936 {
2937 VarREPattern pattern;
2938 char *re;
2939 int error;
2940 Var_Parse_State tmpparsestate;
2941
2942 pattern.flags = 0;
2943 tmpparsestate = parsestate;
2944 delim = tstr[1];
2945 tstr += 2;
2946
2947 cp = tstr;
2948
2949 if ((re = VarGetPattern(ctxt, &parsestate, err, &cp, delim,
2950 NULL, NULL, NULL)) == NULL)
2951 goto cleanup;
2952
2953 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
2954 err, &cp, delim, NULL,
2955 NULL, NULL)) == NULL){
2956 free(re);
2957 goto cleanup;
2958 }
2959
2960 for (;; cp++) {
2961 switch (*cp) {
2962 case 'g':
2963 pattern.flags |= VAR_SUB_GLOBAL;
2964 continue;
2965 case '1':
2966 pattern.flags |= VAR_SUB_ONE;
2967 continue;
2968 case 'W':
2969 tmpparsestate.oneBigWord = TRUE;
2970 continue;
2971 }
2972 break;
2973 }
2974
2975 termc = *cp;
2976
2977 error = regcomp(&pattern.re, re, REG_EXTENDED);
2978 free(re);
2979 if (error) {
2980 *lengthPtr = cp - start + 1;
2981 VarREError(error, &pattern.re, "RE substitution error");
2982 free(pattern.replace);
2983 goto cleanup;
2984 }
2985
2986 pattern.nsub = pattern.re.re_nsub + 1;
2987 if (pattern.nsub < 1)
2988 pattern.nsub = 1;
2989 if (pattern.nsub > 10)
2990 pattern.nsub = 10;
2991 pattern.matches = emalloc(pattern.nsub *
2992 sizeof(regmatch_t));
2993 newStr = VarModify(ctxt, &tmpparsestate, nstr,
2994 VarRESubstitute,
2995 (ClientData) &pattern);
2996 regfree(&pattern.re);
2997 free(pattern.replace);
2998 free(pattern.matches);
2999 delim = '\0';
3000 break;
3001 }
3002 #endif
3003 case 'Q':
3004 if (tstr[1] == endc || tstr[1] == ':') {
3005 newStr = VarQuote(nstr);
3006 cp = tstr + 1;
3007 termc = *cp;
3008 break;
3009 }
3010 goto default_case;
3011 case 'T':
3012 if (tstr[1] == endc || tstr[1] == ':') {
3013 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3014 (ClientData)0);
3015 cp = tstr + 1;
3016 termc = *cp;
3017 break;
3018 }
3019 goto default_case;
3020 case 'H':
3021 if (tstr[1] == endc || tstr[1] == ':') {
3022 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3023 (ClientData)0);
3024 cp = tstr + 1;
3025 termc = *cp;
3026 break;
3027 }
3028 goto default_case;
3029 case 'E':
3030 if (tstr[1] == endc || tstr[1] == ':') {
3031 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3032 (ClientData)0);
3033 cp = tstr + 1;
3034 termc = *cp;
3035 break;
3036 }
3037 goto default_case;
3038 case 'R':
3039 if (tstr[1] == endc || tstr[1] == ':') {
3040 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3041 (ClientData)0);
3042 cp = tstr + 1;
3043 termc = *cp;
3044 break;
3045 }
3046 goto default_case;
3047 case 'O':
3048 {
3049 char otype;
3050
3051 cp = tstr + 1; /* skip to the rest in any case */
3052 if (tstr[1] == endc || tstr[1] == ':') {
3053 otype = 's';
3054 termc = *cp;
3055 } else if ( (tstr[1] == 'x') &&
3056 (tstr[2] == endc || tstr[2] == ':') ) {
3057 otype = tstr[1];
3058 cp = tstr + 2;
3059 termc = *cp;
3060 } else {
3061 goto bad_modifier;
3062 }
3063 newStr = VarOrder(nstr, otype);
3064 break;
3065 }
3066 case 'u':
3067 if (tstr[1] == endc || tstr[1] == ':') {
3068 newStr = VarUniq(nstr);
3069 cp = tstr + 1;
3070 termc = *cp;
3071 break;
3072 }
3073 goto default_case;
3074 #ifdef SUNSHCMD
3075 case 's':
3076 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3077 const char *emsg;
3078 newStr = Cmd_Exec(nstr, &emsg);
3079 if (emsg)
3080 Error(emsg, nstr);
3081 cp = tstr + 2;
3082 termc = *cp;
3083 break;
3084 }
3085 goto default_case;
3086 #endif
3087 default:
3088 default_case:
3089 {
3090 #ifdef SYSVVARSUB
3091 /*
3092 * This can either be a bogus modifier or a System-V
3093 * substitution command.
3094 */
3095 VarPattern pattern;
3096 Boolean eqFound;
3097
3098 pattern.flags = 0;
3099 eqFound = FALSE;
3100 /*
3101 * First we make a pass through the string trying
3102 * to verify it is a SYSV-make-style translation:
3103 * it must be: <string1>=<string2>)
3104 */
3105 cp = tstr;
3106 cnt = 1;
3107 while (*cp != '\0' && cnt) {
3108 if (*cp == '=') {
3109 eqFound = TRUE;
3110 /* continue looking for endc */
3111 }
3112 else if (*cp == endc)
3113 cnt--;
3114 else if (*cp == startc)
3115 cnt++;
3116 if (cnt)
3117 cp++;
3118 }
3119 if (*cp == endc && eqFound) {
3120
3121 /*
3122 * Now we break this sucker into the lhs and
3123 * rhs. We must null terminate them of course.
3124 */
3125 delim='=';
3126 cp = tstr;
3127 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3128 err, &cp, delim, &pattern.flags,
3129 &pattern.leftLen, NULL)) == NULL)
3130 goto cleanup;
3131 delim = endc;
3132 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3133 err, &cp, delim, NULL, &pattern.rightLen,
3134 &pattern)) == NULL)
3135 goto cleanup;
3136
3137 /*
3138 * SYSV modifications happen through the whole
3139 * string. Note the pattern is anchored at the end.
3140 */
3141 termc = *--cp;
3142 delim = '\0';
3143 newStr = VarModify(ctxt, &parsestate, nstr,
3144 VarSYSVMatch,
3145 (ClientData)&pattern);
3146 free(UNCONST(pattern.lhs));
3147 free(UNCONST(pattern.rhs));
3148 } else
3149 #endif
3150 {
3151 Error("Unknown modifier '%c'", *tstr);
3152 for (cp = tstr+1;
3153 *cp != ':' && *cp != endc && *cp != '\0';
3154 cp++)
3155 continue;
3156 termc = *cp;
3157 newStr = var_Error;
3158 }
3159 }
3160 }
3161 if (DEBUG(VAR)) {
3162 printf("Result is \"%s\"\n", newStr);
3163 }
3164
3165 if (newStr != nstr) {
3166 if (*freePtr) {
3167 free(nstr);
3168 }
3169 nstr = newStr;
3170 if (nstr != var_Error && nstr != varNoError) {
3171 *freePtr = TRUE;
3172 } else {
3173 *freePtr = FALSE;
3174 }
3175 }
3176 if (termc == '\0') {
3177 Error("Unclosed variable specification for %s", v->name);
3178 } else if (termc == ':') {
3179 *WR(cp) = termc;
3180 cp++;
3181 } else {
3182 *WR(cp) = termc;
3183 }
3184 tstr = cp;
3185 }
3186 *lengthPtr = tstr - start + 1;
3187 } else {
3188 *lengthPtr = tstr - start + 1;
3189 *WR(tstr) = endc;
3190 }
3191
3192 if (v->flags & VAR_FROM_ENV) {
3193 Boolean destroy = FALSE;
3194
3195 if (nstr != (char *)Buf_GetAll(v->val, NULL)) {
3196 destroy = TRUE;
3197 } else {
3198 /*
3199 * Returning the value unmodified, so tell the caller to free
3200 * the thing.
3201 */
3202 *freePtr = TRUE;
3203 }
3204 if (nstr != (char *)Buf_GetAll(v->val, NULL))
3205 Buf_Destroy(v->val, destroy);
3206 free(v->name);
3207 free(v);
3208 } else if (v->flags & VAR_JUNK) {
3209 /*
3210 * Perform any free'ing needed and set *freePtr to FALSE so the caller
3211 * doesn't try to free a static pointer.
3212 * If VAR_KEEP is also set then we want to keep str as is.
3213 */
3214 if (!(v->flags & VAR_KEEP)) {
3215 if (*freePtr) {
3216 free(nstr);
3217 }
3218 *freePtr = FALSE;
3219 if (dynamic) {
3220 nstr = emalloc(*lengthPtr + 1);
3221 strncpy(nstr, start, *lengthPtr);
3222 nstr[*lengthPtr] = '\0';
3223 *freePtr = TRUE;
3224 } else {
3225 nstr = var_Error;
3226 }
3227 }
3228 if (nstr != (char *)Buf_GetAll(v->val, NULL))
3229 Buf_Destroy(v->val, TRUE);
3230 free(v->name);
3231 free(v);
3232 }
3233 /*
3234 * XXX: If we need to free tstr2 - tstr is no longer valid either.
3235 */
3236 if (tstr2)
3237 free(tstr2);
3238 return (nstr);
3239
3240 bad_modifier:
3241 /* "{(" */
3242 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3243 v->name);
3244
3245 cleanup:
3246 *lengthPtr = cp - start + 1;
3247 if (*freePtr)
3248 free(nstr);
3249 if (tstr2)
3250 free(tstr2);
3251 if (delim != '\0')
3252 Error("Unclosed substitution for %s (%c missing)",
3253 v->name, delim);
3254 return (var_Error);
3255 }
3256
3257 /*-
3258 *-----------------------------------------------------------------------
3259 * Var_Subst --
3260 * Substitute for all variables in the given string in the given context
3261 * If undefErr is TRUE, Parse_Error will be called when an undefined
3262 * variable is encountered.
3263 *
3264 * Input:
3265 * var Named variable || NULL for all
3266 * str the string which to substitute
3267 * ctxt the context wherein to find variables
3268 * undefErr TRUE if undefineds are an error
3269 *
3270 * Results:
3271 * The resulting string.
3272 *
3273 * Side Effects:
3274 * None. The old string must be freed by the caller
3275 *-----------------------------------------------------------------------
3276 */
3277 char *
3278 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3279 {
3280 Buffer buf; /* Buffer for forming things */
3281 char *val; /* Value to substitute for a variable */
3282 int length; /* Length of the variable invocation */
3283 Boolean trailingBslash; /* variable ends in \ */
3284 Boolean doFree; /* Set true if val should be freed */
3285 static Boolean errorReported; /* Set true if an error has already
3286 * been reported to prevent a plethora
3287 * of messages when recursing */
3288
3289 buf = Buf_Init(MAKE_BSIZE);
3290 errorReported = FALSE;
3291 trailingBslash = FALSE;
3292
3293 while (*str) {
3294 if (*str == '\n' && trailingBslash)
3295 Buf_AddByte(buf, ' ');
3296 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3297 /*
3298 * A dollar sign may be escaped either with another dollar sign.
3299 * In such a case, we skip over the escape character and store the
3300 * dollar sign into the buffer directly.
3301 */
3302 str++;
3303 Buf_AddByte(buf, (Byte)*str);
3304 str++;
3305 } else if (*str != '$') {
3306 /*
3307 * Skip as many characters as possible -- either to the end of
3308 * the string or to the next dollar sign (variable invocation).
3309 */
3310 const char *cp;
3311
3312 for (cp = str++; *str != '$' && *str != '\0'; str++)
3313 continue;
3314 Buf_AddBytes(buf, str - cp, (const Byte *)cp);
3315 } else {
3316 if (var != NULL) {
3317 int expand;
3318 for (;;) {
3319 if (str[1] == '\0') {
3320 /* A trailing $ is kind of a special case */
3321 Buf_AddByte(buf, str[0]);
3322 str++;
3323 expand = FALSE;
3324 } else if (str[1] != PROPEN && str[1] != BROPEN) {
3325 if (str[1] != *var || strlen(var) > 1) {
3326 Buf_AddBytes(buf, 2, (const Byte *)str);
3327 str += 2;
3328 expand = FALSE;
3329 }
3330 else
3331 expand = TRUE;
3332 break;
3333 }
3334 else {
3335 const char *p;
3336
3337 /*
3338 * Scan up to the end of the variable name.
3339 */
3340 for (p = &str[2]; *p &&
3341 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
3342 if (*p == '$')
3343 break;
3344 /*
3345 * A variable inside the variable. We cannot expand
3346 * the external variable yet, so we try again with
3347 * the nested one
3348 */
3349 if (*p == '$') {
3350 Buf_AddBytes(buf, p - str, (const Byte *)str);
3351 str = p;
3352 continue;
3353 }
3354
3355 if (strncmp(var, str + 2, p - str - 2) != 0 ||
3356 var[p - str - 2] != '\0') {
3357 /*
3358 * Not the variable we want to expand, scan
3359 * until the next variable
3360 */
3361 for (;*p != '$' && *p != '\0'; p++)
3362 continue;
3363 Buf_AddBytes(buf, p - str, (const Byte *)str);
3364 str = p;
3365 expand = FALSE;
3366 }
3367 else
3368 expand = TRUE;
3369 break;
3370 }
3371 }
3372 if (!expand)
3373 continue;
3374 }
3375
3376 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
3377
3378 /*
3379 * When we come down here, val should either point to the
3380 * value of this variable, suitably modified, or be NULL.
3381 * Length should be the total length of the potential
3382 * variable invocation (from $ to end character...)
3383 */
3384 if (val == var_Error || val == varNoError) {
3385 /*
3386 * If performing old-time variable substitution, skip over
3387 * the variable and continue with the substitution. Otherwise,
3388 * store the dollar sign and advance str so we continue with
3389 * the string...
3390 */
3391 if (oldVars) {
3392 str += length;
3393 } else if (undefErr) {
3394 /*
3395 * If variable is undefined, complain and skip the
3396 * variable. The complaint will stop us from doing anything
3397 * when the file is parsed.
3398 */
3399 if (!errorReported) {
3400 Parse_Error(PARSE_FATAL,
3401 "Undefined variable \"%.*s\"",length,str);
3402 }
3403 str += length;
3404 errorReported = TRUE;
3405 } else {
3406 Buf_AddByte(buf, (Byte)*str);
3407 str += 1;
3408 }
3409 } else {
3410 /*
3411 * We've now got a variable structure to store in. But first,
3412 * advance the string pointer.
3413 */
3414 str += length;
3415
3416 /*
3417 * Copy all the characters from the variable value straight
3418 * into the new string.
3419 */
3420 length = strlen(val);
3421 Buf_AddBytes(buf, length, (Byte *)val);
3422 trailingBslash = length > 0 && val[length - 1] == '\\';
3423 if (doFree) {
3424 free(val);
3425 }
3426 }
3427 }
3428 }
3429
3430 Buf_AddByte(buf, '\0');
3431 val = (char *)Buf_GetAll(buf, NULL);
3432 Buf_Destroy(buf, FALSE);
3433 return (val);
3434 }
3435
3436 /*-
3437 *-----------------------------------------------------------------------
3438 * Var_GetTail --
3439 * Return the tail from each of a list of words. Used to set the
3440 * System V local variables.
3441 *
3442 * Input:
3443 * file Filename to modify
3444 *
3445 * Results:
3446 * The resulting string.
3447 *
3448 * Side Effects:
3449 * None.
3450 *
3451 *-----------------------------------------------------------------------
3452 */
3453 #if 0
3454 char *
3455 Var_GetTail(char *file)
3456 {
3457 return(VarModify(file, VarTail, (ClientData)0));
3458 }
3459
3460 /*-
3461 *-----------------------------------------------------------------------
3462 * Var_GetHead --
3463 * Find the leading components of a (list of) filename(s).
3464 * XXX: VarHead does not replace foo by ., as (sun) System V make
3465 * does.
3466 *
3467 * Input:
3468 * file Filename to manipulate
3469 *
3470 * Results:
3471 * The leading components.
3472 *
3473 * Side Effects:
3474 * None.
3475 *
3476 *-----------------------------------------------------------------------
3477 */
3478 char *
3479 Var_GetHead(char *file)
3480 {
3481 return(VarModify(file, VarHead, (ClientData)0));
3482 }
3483 #endif
3484
3485 /*-
3486 *-----------------------------------------------------------------------
3487 * Var_Init --
3488 * Initialize the module
3489 *
3490 * Results:
3491 * None
3492 *
3493 * Side Effects:
3494 * The VAR_CMD and VAR_GLOBAL contexts are created
3495 *-----------------------------------------------------------------------
3496 */
3497 void
3498 Var_Init(void)
3499 {
3500 VAR_GLOBAL = Targ_NewGN("Global");
3501 VAR_CMD = Targ_NewGN("Command");
3502
3503 }
3504
3505
3506 void
3507 Var_End(void)
3508 {
3509 }
3510
3511
3512 /****************** PRINT DEBUGGING INFO *****************/
3513 static void
3514 VarPrintVar(ClientData vp)
3515 {
3516 Var *v = (Var *)vp;
3517 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, NULL));
3518 }
3519
3520 /*-
3521 *-----------------------------------------------------------------------
3522 * Var_Dump --
3523 * print all variables in a context
3524 *-----------------------------------------------------------------------
3525 */
3526 void
3527 Var_Dump(GNode *ctxt)
3528 {
3529 Hash_Search search;
3530 Hash_Entry *h;
3531
3532 for (h = Hash_EnumFirst(&ctxt->context, &search);
3533 h != NULL;
3534 h = Hash_EnumNext(&search)) {
3535 VarPrintVar(Hash_GetValue(h));
3536 }
3537 }
3538