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