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