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