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