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