xref: /openbsd/usr.bin/make/var.c (revision fe82cac0)
1 /*	$OpenBSD: var.c,v 1.104 2022/06/09 13:13:14 espie Exp $	*/
2 /*	$NetBSD: var.c,v 1.18 1997/03/18 19:24:46 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1999,2000,2007 Marc Espie.
6  *
7  * Extensive code modifications for the OpenBSD project.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OPENBSD
22  * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 /*
31  * Copyright (c) 1988, 1989, 1990, 1993
32  *	The Regents of the University of California.  All rights reserved.
33  * Copyright (c) 1989 by Berkeley Softworks
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to Berkeley by
37  * Adam de Boor.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. Neither the name of the University nor the names of its contributors
48  *    may be used to endorse or promote products derived from this software
49  *    without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61  * SUCH DAMAGE.
62  */
63 
64 #include <assert.h>
65 #include <stddef.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <ohash.h>
71 
72 #include "config.h"
73 #include "defines.h"
74 #include "buf.h"
75 #include "cmd_exec.h"
76 #include "stats.h"
77 #include "pathnames.h"
78 #include "varmodifiers.h"
79 #include "var.h"
80 #include "varname.h"
81 #include "error.h"
82 #include "str.h"
83 #include "var_int.h"
84 #include "memory.h"
85 #include "symtable.h"
86 #include "gnode.h"
87 #include "dump.h"
88 #include "lowparse.h"
89 
90 /*
91  * This is a harmless return value for Var_Parse that can be used by Var_Subst
92  * to determine if there was an error in parsing -- easier than returning
93  * a flag, as things outside this module don't give a hoot.
94  */
95 char	var_Error[] = "";
96 
97 GNode *current_node = NULL;
98 /*
99  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
100  * set false. Why not just use a constant? Well, gcc likes to condense
101  * identical string instances...
102  */
103 static char	varNoError[] = "";
104 bool		errorIsOkay;
105 static bool	checkEnvFirst;	/* true if environment should be searched for
106 				 * variables before the global context */
107 
108 void
109 Var_setCheckEnvFirst(bool yes)
110 {
111 	checkEnvFirst = yes;
112 }
113 
114 /*
115  * The rules for variable look-up are complicated.
116  *
117  * - Dynamic variables like $@ and $* are special. They always pertain to
118  * a given variable.  In this implementation of make, it is an error to
119  * try to affect them manually. They are stored in a local symtable directly
120  * inside the gnode.
121  *
122  * Global variables can be obtained:
123  * - from the command line
124  * - from the environment
125  * - from the Makefile proper.
126  * All of these are stored in a hash global_variables.
127  *
128  * Variables set on the command line override Makefile contents, are
129  * passed to submakes (see Var_AddCmdLine), and are also exported to the
130  * environment.
131  *
132  * Without -e (!checkEnvFirst), make will see variables set in the
133  * Makefile, and default to the environment otherwise.
134  *
135  * With -e (checkEnvFirst), make will see the environment first, and that
136  * will override anything that's set in the Makefile (but not set on
137  * the command line).
138  *
139  * The SHELL variable is very special: it is never obtained from the
140  * environment, and never passed to the environment.
141  */
142 
143 /* definitions pertaining to dynamic variables */
144 
145 /* full names of dynamic variables */
146 static char *varnames[] = {
147 	TARGET,
148 	PREFIX,
149 	ARCHIVE,
150 	MEMBER,
151 	IMPSRC,
152 	OODATE,
153 	ALLSRC,
154 	FTARGET,
155 	DTARGET,
156 	FPREFIX,
157 	DPREFIX,
158 	FARCHIVE,
159 	DARCHIVE,
160 	FMEMBER,
161 	DMEMBER,
162 	FIMPSRC,
163 	DIMPSRC
164 };
165 
166 static bool xtlist[] = {
167 	false,	/* GLOBAL_INDEX */
168 	true,	/* $@ */
169 	false,	/* $* */
170 	false,	/* $! */
171 	true,	/* $% */
172 	true,	/* $< */
173 	false,	/* $? */
174 	false,	/* $> */
175 	true,	/* ${@F} */
176 	true,	/* ${@D} */
177 	false,	/* ${*F} */
178 	false,	/* ${*D} */
179 	false,	/* ${!F} */
180 	false,	/* ${!D} */
181 	true,	/* ${%F} */
182 	true,	/* ${%D} */
183 	true,	/* ${<F} */
184 	true,	/* ${<D} */
185 };
186 
187 /* so that we can access tlist[-1] */
188 static bool *tlist = xtlist+1;
189 
190 /* hashed names of dynamic variables */
191 #include    "varhashconsts.h"
192 
193 /* extended indices for System V stuff */
194 #define FTARGET_INDEX	7
195 #define DTARGET_INDEX	8
196 #define FPREFIX_INDEX	9
197 #define DPREFIX_INDEX	10
198 #define FARCHIVE_INDEX	11
199 #define DARCHIVE_INDEX	12
200 #define FMEMBER_INDEX	13
201 #define DMEMBER_INDEX	14
202 #define FIMPSRC_INDEX	15
203 #define DIMPSRC_INDEX	16
204 
205 #define GLOBAL_INDEX	-1
206 
207 #define EXTENDED2SIMPLE(i)	(((i)-LOCAL_SIZE)/2)
208 #define IS_EXTENDED_F(i)	((i)%2 == 1)
209 
210 
211 static struct ohash global_variables;
212 
213 
214 typedef struct Var_ {
215 	BUFFER val;		/* the variable value */
216 	unsigned int flags;	/* miscellaneous status flags */
217 #define VAR_IN_USE	1	/* Variable's value currently being used. */
218 				/* (Used to avoid recursion) */
219 #define VAR_DUMMY	2	/* Variable is currently just a name */
220 				/* In particular: BUFFER is invalid */
221 #define VAR_FROM_CMD	4	/* Special source: command line */
222 #define VAR_FROM_ENV	8	/* Special source: environment */
223 #define VAR_SEEN_ENV	16	/* No need to go look up environment again */
224 #define VAR_IS_SHELL	32	/* Magic behavior */
225 /* XXX there are also some flag values which are part of the visible API
226  * and thus defined inside var.h, don't forget to look there if you want
227  * to define some new flags !
228  */
229 #define POISONS (POISON_NORMAL | POISON_EMPTY | POISON_NOT_DEFINED)
230 				/* Defined in var.h */
231 	char name[1];		/* the variable's name */
232 }  Var;
233 
234 
235 static struct ohash_info var_info = {
236 	offsetof(Var, name),
237 	NULL,
238 	hash_calloc, hash_free, element_alloc
239 };
240 
241 static int classify_var(const char *, const char **, uint32_t *);
242 static Var *find_global_var(const char *, const char *, uint32_t);
243 static Var *find_global_var_without_env(const char *, const char *, uint32_t);
244 static void fill_from_env(Var *);
245 static Var *create_var(const char *, const char *);
246 static void var_set_initial_value(Var *, const char *);
247 static void var_set_value(Var *, const char *);
248 #define var_get_value(v)	((v)->flags & VAR_EXEC_LATER ? \
249 	var_exec_cmd(v) : \
250 	Buf_Retrieve(&((v)->val)))
251 static char *var_exec_cmd(Var *);
252 static void var_append_value(Var *, const char *);
253 static void poison_check(Var *);
254 static void var_set_append(const char *, const char *, const char *, int, bool);
255 static void set_magic_shell_variable(void);
256 
257 static void delete_var(Var *);
258 static void print_var(Var *);
259 
260 
261 static const char *find_rparen(const char *);
262 static const char *find_ket(const char *);
263 typedef const char * (*find_t)(const char *);
264 static find_t find_pos(int);
265 static void push_used(Var *);
266 static void pop_used(Var *);
267 static char *get_expanded_value(const char *, const char *, int, uint32_t,
268     SymTable *, bool, bool *);
269 static bool parse_base_variable_name(const char **, struct Name *, SymTable *);
270 
271 
272 
273 /* Variable lookup function: return idx for dynamic variable, or
274  * GLOBAL_INDEX if name is not dynamic. Set up *pk for further use.
275  */
276 static int
277 classify_var(const char *name, const char **enamePtr, uint32_t *pk)
278 {
279 	size_t len;
280 
281 	*pk = ohash_interval(name, enamePtr);
282 	len = *enamePtr - name;
283 	    /* substitute short version for long local name */
284 	switch (*pk % MAGICSLOTS1) {	/* MAGICSLOTS should be the    */
285 	case K_LONGALLSRC % MAGICSLOTS1:/* smallest constant yielding  */
286 					/* distinct case values	   */
287 		if (*pk == K_LONGALLSRC && len == strlen(LONGALLSRC) &&
288 		    strncmp(name, LONGALLSRC, len) == 0)
289 			return ALLSRC_INDEX;
290 		break;
291 	case K_LONGARCHIVE % MAGICSLOTS1:
292 		if (*pk == K_LONGARCHIVE && len == strlen(LONGARCHIVE) &&
293 		    strncmp(name, LONGARCHIVE, len) == 0)
294 			return ARCHIVE_INDEX;
295 		break;
296 	case K_LONGIMPSRC % MAGICSLOTS1:
297 		if (*pk == K_LONGIMPSRC && len == strlen(LONGIMPSRC) &&
298 		    strncmp(name, LONGIMPSRC, len) == 0)
299 			return IMPSRC_INDEX;
300 		break;
301 	case K_LONGMEMBER % MAGICSLOTS1:
302 		if (*pk == K_LONGMEMBER && len == strlen(LONGMEMBER) &&
303 		    strncmp(name, LONGMEMBER, len) == 0)
304 			return MEMBER_INDEX;
305 		break;
306 	case K_LONGOODATE % MAGICSLOTS1:
307 		if (*pk == K_LONGOODATE && len == strlen(LONGOODATE) &&
308 		    strncmp(name, LONGOODATE, len) == 0)
309 			return OODATE_INDEX;
310 		break;
311 	case K_LONGPREFIX % MAGICSLOTS1:
312 		if (*pk == K_LONGPREFIX && len == strlen(LONGPREFIX) &&
313 		    strncmp(name, LONGPREFIX, len) == 0)
314 			return PREFIX_INDEX;
315 		break;
316 	case K_LONGTARGET % MAGICSLOTS1:
317 		if (*pk == K_LONGTARGET && len == strlen(LONGTARGET) &&
318 		    strncmp(name, LONGTARGET, len) == 0)
319 			return TARGET_INDEX;
320 		break;
321 	case K_TARGET % MAGICSLOTS1:
322 		if (name[0] == TARGET[0] && len == 1)
323 			return TARGET_INDEX;
324 		break;
325 	case K_OODATE % MAGICSLOTS1:
326 		if (name[0] == OODATE[0] && len == 1)
327 			return OODATE_INDEX;
328 		break;
329 	case K_ALLSRC % MAGICSLOTS1:
330 		if (name[0] == ALLSRC[0] && len == 1)
331 			return ALLSRC_INDEX;
332 		break;
333 	case K_IMPSRC % MAGICSLOTS1:
334 		if (name[0] == IMPSRC[0] && len == 1)
335 			return IMPSRC_INDEX;
336 		break;
337 	case K_PREFIX % MAGICSLOTS1:
338 		if (name[0] == PREFIX[0] && len == 1)
339 			return PREFIX_INDEX;
340 		break;
341 	case K_ARCHIVE % MAGICSLOTS1:
342 		if (name[0] == ARCHIVE[0] && len == 1)
343 			return ARCHIVE_INDEX;
344 		break;
345 	case K_MEMBER % MAGICSLOTS1:
346 		if (name[0] == MEMBER[0] && len == 1)
347 			return MEMBER_INDEX;
348 		break;
349 	case K_FTARGET % MAGICSLOTS1:
350 		if (name[0] == FTARGET[0] && name[1] == FTARGET[1] && len == 2)
351 			return FTARGET_INDEX;
352 		break;
353 	case K_DTARGET % MAGICSLOTS1:
354 		if (name[0] == DTARGET[0] && name[1] == DTARGET[1] && len == 2)
355 			return DTARGET_INDEX;
356 		break;
357 	case K_FPREFIX % MAGICSLOTS1:
358 		if (name[0] == FPREFIX[0] && name[1] == FPREFIX[1] && len == 2)
359 			return FPREFIX_INDEX;
360 		break;
361 	case K_DPREFIX % MAGICSLOTS1:
362 		if (name[0] == DPREFIX[0] && name[1] == DPREFIX[1] && len == 2)
363 			return DPREFIX_INDEX;
364 		break;
365 	case K_FARCHIVE % MAGICSLOTS1:
366 		if (name[0] == FARCHIVE[0] && name[1] == FARCHIVE[1] &&
367 		    len == 2)
368 			return FARCHIVE_INDEX;
369 		break;
370 	case K_DARCHIVE % MAGICSLOTS1:
371 		if (name[0] == DARCHIVE[0] && name[1] == DARCHIVE[1] &&
372 		    len == 2)
373 			return DARCHIVE_INDEX;
374 		break;
375 	case K_FMEMBER % MAGICSLOTS1:
376 		if (name[0] == FMEMBER[0] && name[1] == FMEMBER[1] && len == 2)
377 			return FMEMBER_INDEX;
378 		break;
379 	case K_DMEMBER % MAGICSLOTS1:
380 		if (name[0] == DMEMBER[0] && name[1] == DMEMBER[1] && len == 2)
381 			return DMEMBER_INDEX;
382 		break;
383 	case K_FIMPSRC % MAGICSLOTS1:
384 		if (name[0] == FIMPSRC[0] && name[1] == FIMPSRC[1] && len == 2)
385 			return FIMPSRC_INDEX;
386 		break;
387 	case K_DIMPSRC % MAGICSLOTS1:
388 		if (name[0] == DIMPSRC[0] && name[1] == DIMPSRC[1] && len == 2)
389 			return DIMPSRC_INDEX;
390 		break;
391 	default:
392 		break;
393 	}
394 	return GLOBAL_INDEX;
395 }
396 
397 
398 /***
399  ***	Internal handling of variables.
400  ***/
401 
402 
403 /* Create a new variable, does not initialize anything except the name.
404  * in particular, buffer is invalid, and flag value is invalid. Accordingly,
405  * must either:
406  * - set flags to VAR_DUMMY
407  * - set flags to !VAR_DUMMY, and initialize buffer, for instance with
408  * var_set_initial_value().
409  */
410 static Var *
411 create_var(const char *name, const char *ename)
412 {
413 	return ohash_create_entry(&var_info, name, &ename);
414 }
415 
416 /* Initial version of var_set_value(), to be called after create_var().
417  */
418 static void
419 var_set_initial_value(Var *v, const char *val)
420 {
421 	size_t len;
422 
423 	len = strlen(val);
424 	Buf_Init(&(v->val), len+1);
425 	Buf_AddChars(&(v->val), len, val);
426 }
427 
428 /* Normal version of var_set_value(), to be called after variable is fully
429  * initialized.
430  */
431 static void
432 var_set_value(Var *v, const char *val)
433 {
434 	if ((v->flags & VAR_DUMMY) == 0) {
435 		Buf_Reset(&(v->val));
436 		Buf_AddString(&(v->val), val);
437 	} else {
438 		var_set_initial_value(v, val);
439 		v->flags &= ~VAR_DUMMY;
440 	}
441 }
442 
443 /* Add to a variable, insert a separating space if the variable was already
444  * defined.
445  */
446 static void
447 var_append_value(Var *v, const char *val)
448 {
449 	if ((v->flags & VAR_DUMMY) == 0) {
450 		Buf_AddSpace(&(v->val));
451 		Buf_AddString(&(v->val), val);
452 	} else {
453 		var_set_initial_value(v, val);
454 		v->flags &= ~VAR_DUMMY;
455 	}
456 }
457 
458 
459 /* Delete a variable and all the space associated with it.
460  */
461 static void
462 delete_var(Var *v)
463 {
464 	if ((v->flags & VAR_DUMMY) == 0)
465 		Buf_Destroy(&(v->val));
466 	free(v);
467 }
468 
469 
470 
471 
472 /***
473  ***	Dynamic variable handling.
474  ***/
475 
476 
477 
478 /* create empty symtable.
479  * XXX: to save space, dynamic variables may be NULL pointers.
480  */
481 void
482 SymTable_Init(SymTable *ctxt)
483 {
484 	static SymTable sym_template;
485 	memcpy(ctxt, &sym_template, sizeof(*ctxt));
486 }
487 
488 /***
489  ***	Global variable handling.
490  ***/
491 
492 /* Create a new global var if necessary, and set it up correctly.
493  * Do not take environment into account.
494  */
495 static Var *
496 find_global_var_without_env(const char *name, const char *ename, uint32_t k)
497 {
498 	unsigned int slot;
499 	Var *v;
500 
501 	slot = ohash_lookup_interval(&global_variables, name, ename, k);
502 	v = ohash_find(&global_variables, slot);
503 	if (v == NULL) {
504 		v = create_var(name, ename);
505 		v->flags = VAR_DUMMY;
506 		ohash_insert(&global_variables, slot, v);
507 	}
508 	return v;
509 }
510 
511 /* Helper for find_global_var(): grab environment value if needed.
512  */
513 static void
514 fill_from_env(Var *v)
515 {
516 	char	*env;
517 
518 	env = getenv(v->name);
519 	if (env == NULL)
520 		v->flags |= VAR_SEEN_ENV;
521 	else {
522 		var_set_value(v, env);
523 		v->flags |= VAR_FROM_ENV | VAR_SEEN_ENV;
524 	}
525 
526 #ifdef STATS_VAR_LOOKUP
527 	STAT_VAR_FROM_ENV++;
528 #endif
529 }
530 
531 /* Find global var, and obtain its value from the environment if needed.
532  */
533 static Var *
534 find_global_var(const char *name, const char *ename, uint32_t k)
535 {
536 	Var *v;
537 
538 	v = find_global_var_without_env(name, ename, k);
539 
540 	if ((v->flags & VAR_SEEN_ENV) == 0)
541 		if ((checkEnvFirst && (v->flags & VAR_FROM_CMD) == 0) ||
542 		    (v->flags & VAR_DUMMY) != 0)
543 			fill_from_env(v);
544 
545 	return v;
546 }
547 
548 /* mark variable with special flags, in a given setup.
549  */
550 void
551 Var_Mark(const char *name, const char *ename, unsigned int type)
552 {
553 	Var   *v;
554 	uint32_t	k;
555 	int		idx;
556 	idx = classify_var(name, &ename, &k);
557 
558 	if (idx != GLOBAL_INDEX) {
559 		Parse_Error(PARSE_FATAL,
560 		    "Trying to poison dynamic variable $%s",
561 		    varnames[idx]);
562 		return;
563 	}
564 
565 	v = find_global_var(name, ename, k);
566 	v->flags |= type;
567 	/* POISON_NORMAL is not lazy: if the variable already exists in
568 	 * the Makefile, then it's a mistake.
569 	 */
570 	if (v->flags & POISON_NORMAL) {
571 		if (v->flags & VAR_DUMMY)
572 			return;
573 		if (v->flags & VAR_FROM_ENV)
574 			return;
575 		Parse_Error(PARSE_FATAL,
576 		    "Poisoned variable %s is already set\n", v->name);
577 	}
578 }
579 
580 /* Check if there's any reason not to use this variable.
581  */
582 static void
583 poison_check(Var *v)
584 {
585 	if (v->flags & POISON_NORMAL) {
586 		Parse_Error(PARSE_FATAL,
587 		    "Poisoned variable %s has been referenced\n", v->name);
588 		return;
589 	}
590 	if (v->flags & VAR_DUMMY) {
591 		Parse_Error(PARSE_FATAL,
592 		    "Poisoned variable %s is not defined\n", v->name);
593 		return;
594 	}
595 	if (v->flags & POISON_EMPTY)
596 		if (strcmp(var_get_value(v), "") == 0)
597 			Parse_Error(PARSE_FATAL,
598 			    "Poisoned variable %s is empty\n", v->name);
599 }
600 
601 /* Delete global variable.
602  */
603 void
604 Var_Deletei(const char *name, const char *ename)
605 {
606 	Var *v;
607 	uint32_t k;
608 	unsigned int slot;
609 	int idx;
610 
611 	idx = classify_var(name, &ename, &k);
612 	if (idx != GLOBAL_INDEX) {
613 		Parse_Error(PARSE_FATAL,
614 		    "Trying to delete dynamic variable $%s", varnames[idx]);
615 		return;
616 	}
617 	slot = ohash_lookup_interval(&global_variables, name, ename, k);
618 	v = ohash_find(&global_variables, slot);
619 
620 	if (v == NULL)
621 		return;
622 
623 	if (checkEnvFirst && (v->flags & VAR_FROM_ENV))
624 		return;
625 
626 	if (v->flags & VAR_FROM_CMD)
627 		return;
628 
629 	ohash_remove(&global_variables, slot);
630 	delete_var(v);
631 }
632 
633 /* Set or add a global variable, either to VAR_CMD or VAR_GLOBAL.
634  */
635 static void
636 var_set_append(const char *name, const char *ename, const char *val, int ctxt,
637     bool append)
638 {
639 	Var *v;
640 	uint32_t k;
641 	int idx;
642 
643 	idx = classify_var(name, &ename, &k);
644 	if (idx != GLOBAL_INDEX) {
645 		Parse_Error(PARSE_FATAL, "Trying to %s dynamic variable $%s",
646 		    append ? "append to" : "set", varnames[idx]);
647 		return;
648 	}
649 
650 	v = find_global_var(name, ename, k);
651 	if (v->flags & POISON_NORMAL)
652 		Parse_Error(PARSE_FATAL, "Trying to %s poisoned variable %s\n",
653 		    append ? "append to" : "set", v->name);
654 	/* so can we write to it ? */
655 	if (ctxt == VAR_CMD) {	/* always for command line */
656 		(append ? var_append_value : var_set_value)(v, val);
657 		v->flags |= VAR_FROM_CMD;
658 		if ((v->flags & VAR_IS_SHELL) == 0) {
659 			/* Any variables given on the command line are
660 			 * automatically exported to the environment,
661 			 * except for SHELL (as per POSIX standard).
662 			 */
663 			esetenv(v->name, val);
664 		}
665 		if (DEBUG(VAR))
666 			printf("command:%s = %s\n", v->name, var_get_value(v));
667 	} else if ((v->flags & VAR_FROM_CMD) == 0 &&
668 	     (!checkEnvFirst || (v->flags & VAR_FROM_ENV) == 0)) {
669 		(append ? var_append_value : var_set_value)(v, val);
670 		if (DEBUG(VAR))
671 			printf("global:%s = %s\n", v->name, var_get_value(v));
672 	} else if (DEBUG(VAR))
673 		printf("overridden:%s = %s\n", v->name, var_get_value(v));
674 }
675 
676 void
677 Var_Seti_with_ctxt(const char *name, const char *ename, const char *val,
678     int ctxt)
679 {
680 	var_set_append(name, ename, val, ctxt, false);
681 }
682 
683 void
684 Var_Appendi_with_ctxt(const char *name, const char *ename, const char *val,
685     int ctxt)
686 {
687 	var_set_append(name, ename, val, ctxt, true);
688 }
689 
690 static char *
691 var_exec_cmd(Var *v)
692 {
693 	char *arg = Buf_Retrieve(&(v->val));
694 	char *err;
695 	char *res1;
696 	res1 = Cmd_Exec(arg, &err);
697 	if (err)
698 		Parse_Error(PARSE_WARNING, err, arg);
699 	var_set_value(v, res1);
700 	free(res1);
701 	v->flags &= ~VAR_EXEC_LATER;
702 	return Buf_Retrieve(&(v->val));
703 }
704 
705 /* XXX different semantics for Var_Valuei() and Var_Definedi():
706  * references to poisoned value variables will error out in Var_Valuei(),
707  * but not in Var_Definedi(), so the following construct works:
708  *	.poison BINDIR
709  *	BINDIR ?= /usr/bin
710  */
711 char *
712 Var_Valuei(const char *name, const char *ename)
713 {
714 	Var *v;
715 	uint32_t k;
716 	int idx;
717 
718 	idx = classify_var(name, &ename, &k);
719 	if (idx != GLOBAL_INDEX) {
720 		Parse_Error(PARSE_FATAL,
721 		    "Trying to get value of dynamic variable $%s",
722 			varnames[idx]);
723 		return NULL;
724 	}
725 	v = find_global_var(name, ename, k);
726 	if (v->flags & POISONS)
727 		poison_check(v);
728 	if ((v->flags & VAR_DUMMY) == 0)
729 		return var_get_value(v);
730 	else
731 		return NULL;
732 }
733 
734 bool
735 Var_Definedi(const char *name, const char *ename)
736 {
737 	Var *v;
738 	uint32_t k;
739 	int idx;
740 
741 	idx = classify_var(name, &ename, &k);
742 	/* We don't bother writing an error message for dynamic variables,
743 	 * these will be caught when getting set later, usually.
744 	 */
745 	if (idx == GLOBAL_INDEX) {
746 		v = find_global_var(name, ename, k);
747 		if (v->flags & POISON_NORMAL)
748 			poison_check(v);
749 		if ((v->flags & VAR_DUMMY) == 0)
750 			return true;
751 	}
752 	return false;
753 }
754 
755 
756 /***
757  ***	Substitution functions, handling both global and dynamic variables.
758  ***/
759 
760 
761 /* All the scanning functions needed to account for all the forms of
762  * variable names that exist:
763  *	$A, ${AB}, $(ABC), ${A:mod}, $(A:mod)
764  */
765 
766 static const char *
767 find_rparen(const char *p)
768 {
769 	while (*p != '$' && *p != '\0' && *p != ')' && *p != ':')
770 		p++;
771 	return p;
772 }
773 
774 static const char *
775 find_ket(const char *p)
776 {
777 	while (*p != '$' && *p != '\0' && *p != '}' && *p != ':')
778 		p++;
779 	return p;
780 }
781 
782 /* Figure out what kind of name we're looking for from a start character.
783  */
784 static find_t
785 find_pos(int c)
786 {
787 	switch(c) {
788 	case '(':
789 		return find_rparen;
790 	case '{':
791 		return find_ket;
792 	default:
793 		Parse_Error(PARSE_FATAL,
794 		    "Wrong character in variable spec %c (can't happen)", c);
795 		return find_rparen;
796 	}
797 }
798 
799 static bool
800 parse_base_variable_name(const char **pstr, struct Name *name, SymTable *ctxt)
801 {
802 	const char *str = *pstr;
803 	const char *tstr;
804 	bool has_modifier = false;
805 
806 	switch(str[1]) {
807 	case '(':
808 	case '{':
809 		/* Find eventual modifiers in the variable */
810 		tstr = VarName_Get(str+2, name, ctxt, false, find_pos(str[1]));
811 		if (*tstr == '\0')
812 			 Parse_Error(PARSE_FATAL, "Unterminated variable spec in %s", *pstr);
813 		else if (*tstr == ':')
814 			has_modifier = true;
815 		else
816 			tstr++;
817 		break;
818 	default:
819 		name->s = str+1;
820 		name->e = str+2;
821 		name->tofree = false;
822 		tstr = str + 2;
823 		break;
824 	}
825 	*pstr = tstr;
826 	return has_modifier;
827 }
828 
829 bool
830 Var_ParseSkip(const char **pstr, SymTable *ctxt)
831 {
832 	const char *str = *pstr;
833 	struct Name name;
834 	bool result;
835 	bool has_modifier;
836 	const char *tstr = str;
837 
838 	if (str[1] == 0) {
839 		*pstr = str+1;
840 		return false;
841 	}
842 	has_modifier = parse_base_variable_name(&tstr, &name, ctxt);
843 	VarName_Free(&name);
844 	result = true;
845 	if (has_modifier) {
846 		bool freePtr = false;
847 		char *s = VarModifiers_Apply(NULL, NULL, ctxt, true, &freePtr,
848 		    &tstr, str[1]);
849 		if (s == var_Error)
850 			result = false;
851 		if (freePtr)
852 			free(s);
853 	}
854 	*pstr = tstr;
855 	return result;
856 }
857 
858 /* As of now, Var_ParseBuffer is just a wrapper around Var_Parse. For
859  * speed, it may be better to revisit the implementation to do things
860  * directly. */
861 bool
862 Var_ParseBuffer(Buffer buf, const char *str, SymTable *ctxt, bool err,
863     size_t *lengthPtr)
864 {
865 	char *result;
866 	bool freeIt;
867 
868 	result = Var_Parse(str, ctxt, err, lengthPtr, &freeIt);
869 	if (result == var_Error)
870 		return false;
871 
872 	Buf_AddString(buf, result);
873 	if (freeIt)
874 		free(result);
875 	return true;
876 }
877 
878 /* Helper function for Var_Parse: still recursive, but we tag what variables
879  * we expand for better error messages.
880  */
881 #define MAX_DEPTH 350
882 static Var *call_trace[MAX_DEPTH];
883 static int current_depth = 0;
884 
885 static void
886 push_used(Var *v)
887 {
888 	if (v->flags & VAR_IN_USE) {
889 		int i;
890 		fprintf(stderr, "Problem with variable expansion chain: ");
891 		for (i = 0;
892 		    i < (current_depth > MAX_DEPTH ? MAX_DEPTH : current_depth);
893 		    i++)
894 			fprintf(stderr, "%s -> ", call_trace[i]->name);
895 		fprintf(stderr, "%s\n", v->name);
896 		Fatal("\tVariable %s is recursive.", v->name);
897 		/*NOTREACHED*/
898 	}
899 
900 	v->flags |= VAR_IN_USE;
901 	if (current_depth < MAX_DEPTH)
902 		call_trace[current_depth] = v;
903 	current_depth++;
904 }
905 
906 static void
907 pop_used(Var *v)
908 {
909 	v->flags &= ~VAR_IN_USE;
910 	current_depth--;
911 }
912 
913 static char *
914 get_expanded_value(const char *name, const char *ename, int idx, uint32_t k,
915     SymTable *ctxt, bool err, bool *freePtr)
916 {
917 	char *val;
918 
919 	/* Before doing any modification, we have to make sure the
920 	 * value has been fully expanded. If it looks like recursion
921 	 * might be necessary (there's a dollar sign somewhere in
922 	 * the variable's value) we just call Var_Subst to do any
923 	 * other substitutions that are necessary. Note that the
924 	 * value returned by Var_Subst will have been dynamically
925 	 * allocated, so it will need freeing when we return.
926 	 */
927 	if (idx == GLOBAL_INDEX) {
928 		Var *v = find_global_var(name, ename, k);
929 
930 		if (v == NULL)
931 			return NULL;
932 
933 		if ((v->flags & POISONS) != 0)
934 			poison_check(v);
935 		if ((v->flags & VAR_DUMMY) != 0)
936 			return NULL;
937 
938 		val = var_get_value(v);
939 		if (strchr(val, '$') != NULL) {
940 			push_used(v);
941 			val = Var_Subst(val, ctxt, err);
942 			pop_used(v);
943 			*freePtr = true;
944 		}
945 	} else {
946 		if (ctxt != NULL) {
947 			if (idx < LOCAL_SIZE)
948 				val = ctxt->locals[idx];
949 			else
950 				val = ctxt->locals[EXTENDED2SIMPLE(idx)];
951 		} else
952 			val = NULL;
953 		if (val == NULL)
954 			return NULL;
955 
956 		if (idx >= LOCAL_SIZE) {
957 			if (IS_EXTENDED_F(idx))
958 				val = Var_GetTail(val);
959 			else
960 				val = Var_GetHead(val);
961 			*freePtr = true;
962 		}
963 	}
964 	return val;
965 }
966 
967 #define ERRMSG1 "Using $< in a non-suffix rule context is a GNUmake idiom "
968 #define ERRMSG2  "Using undefined dynamic variable $%s "
969 static void
970 bad_dynamic_variable(int idx)
971 {
972 	Location origin;
973 
974 	Parse_FillLocation(&origin);
975 	if (idx >= LOCAL_SIZE)
976 		idx = EXTENDED2SIMPLE(idx);
977 	switch(idx) {
978 	case IMPSRC_INDEX:
979 		if (origin.fname)
980 			Fatal(ERRMSG1  "(%s:%lu)",
981 			    origin.fname, origin.lineno);
982 		else if (current_node)
983 			Fatal(ERRMSG1 "(prereq of %s)", current_node->name);
984 		else
985 			Fatal(ERRMSG1 "(?)");
986 		break;
987 	default:
988 		if (origin.fname)
989 			Error(ERRMSG2 "(%s:%lu)", varnames[idx],
990 			    origin.fname, origin.lineno);
991 		else if (current_node)
992 			Error(ERRMSG2 "(prereq of %s)", varnames[idx],
993 			    current_node->name);
994 		else
995 			Error(ERRMSG2 "(?)", varnames[idx]);
996 		break;
997     	}
998 }
999 
1000 char *
1001 Var_Parse(const char *str,	/* The string to parse */
1002     SymTable *ctxt,		/* The context for the variable */
1003     bool err,			/* true if undefined variables are an error */
1004     size_t *lengthPtr,		/* OUT: The length of the specification */
1005     bool *freePtr)		/* OUT: true if caller should free result */
1006 {
1007 	const char *tstr;
1008 	struct Name name;
1009 	char *val;
1010 	uint32_t k;
1011 	int idx;
1012 	bool has_modifier;
1013 
1014 	*freePtr = false;
1015 
1016 	tstr = str;
1017 
1018 	if (str[1] == 0) {
1019 		*lengthPtr = 1;
1020 		*freePtr = false;
1021 		return err ? var_Error : varNoError;
1022 	}
1023 
1024 	has_modifier = parse_base_variable_name(&tstr, &name, ctxt);
1025 
1026 	idx = classify_var(name.s, &name.e, &k);
1027 	val = get_expanded_value(name.s, name.e, idx, k, ctxt, err, freePtr);
1028 	if (has_modifier) {
1029 		val = VarModifiers_Apply(val, &name, ctxt, err, freePtr,
1030 		    &tstr, str[1]);
1031 	}
1032 	if (val == NULL) {
1033 		val = err ? var_Error : varNoError;
1034 		/* If it comes from a dynamic source, and it doesn't have
1035 		 * a local context, copy the spec instead.
1036 		 * Specifically, this make allows constructs like:
1037 		 * 	target.o: $*.c
1038 		 * Absence of a context means "parsing". But these can't
1039 		 * be expanded during parsing, to be consistent with the
1040 		 * way .SUFFIXES work.
1041 		 * .SUFFIXES may be added/reset/removed during parsing,
1042 		 * but in the end, the final list is what's considered for
1043 		 * handling targets.  So those dynamic variables must be
1044 		 * handled lazily too.
1045 		 */
1046 		if (idx != GLOBAL_INDEX) {
1047 			if (ctxt == NULL) {
1048 				*freePtr = true;
1049 				val = Str_dupi(str, tstr);
1050 			} else {
1051 				bad_dynamic_variable(idx);
1052 			}
1053 		}
1054 	}
1055 	VarName_Free(&name);
1056 	*lengthPtr = tstr - str;
1057 	return val;
1058 }
1059 
1060 
1061 char *
1062 Var_Subst(const char *str,	/* the string in which to substitute */
1063     SymTable *ctxt,		/* the context wherein to find variables */
1064     bool undefErr)		/* true if undefineds are an error */
1065 {
1066 	BUFFER buf;		/* Buffer for forming things */
1067 	static bool errorReported;
1068 
1069 	Buf_Init(&buf, MAKE_BSIZE);
1070 	errorReported = false;
1071 
1072 	for (;;) {
1073 		char *val;	/* Value to substitute for a variable */
1074 		size_t length;	/* Length of the variable invocation */
1075 		bool doFree;	/* Set true if val should be freed */
1076 		const char *cp;
1077 
1078 		/* copy uninteresting stuff */
1079 		for (cp = str; *str != '\0' && *str != '$'; str++)
1080 			;
1081 		Buf_Addi(&buf, cp, str);
1082 		if (*str == '\0')
1083 			break;
1084 		if (str[1] == '$') {
1085 			/* A $ may be escaped with another $. */
1086 			Buf_AddChar(&buf, '$');
1087 			str += 2;
1088 			continue;
1089 		}
1090 		val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1091 		/* When we come down here, val should either point to the
1092 		 * value of this variable, suitably modified, or be NULL.
1093 		 * Length should be the total length of the potential
1094 		 * variable invocation (from $ to end character...) */
1095 		if (val == var_Error || val == varNoError) {
1096 			/* If errors are not an issue, skip over the variable
1097 			 * and continue with the substitution. Otherwise, store
1098 			 * the dollar sign and advance str so we continue with
1099 			 * the string...  */
1100 			if (errorIsOkay)
1101 				str += length;
1102 			else if (undefErr) {
1103 				/* If variable is undefined, complain and
1104 				 * skip the variable name. The complaint
1105 				 * will stop us from doing anything when
1106 				 * the file is parsed.  */
1107 				if (!errorReported)
1108 					Parse_Error(PARSE_FATAL,
1109 					     "Undefined variable \"%.*s\"",
1110 					     (int)length, str);
1111 				str += length;
1112 				errorReported = true;
1113 			} else {
1114 				Buf_AddChar(&buf, *str);
1115 				str++;
1116 			}
1117 		} else {
1118 			/* We've now got a variable structure to store in.
1119 			 * But first, advance the string pointer.  */
1120 			str += length;
1121 
1122 			/* Copy all the characters from the variable value
1123 			 * straight into the new string.  */
1124 			Buf_AddString(&buf, val);
1125 			if (doFree)
1126 				free(val);
1127 		}
1128 	}
1129 	return  Buf_Retrieve(&buf);
1130 }
1131 
1132 /* Very quick version of the variable scanner that just looks for target
1133  * variables, and never ever errors out
1134  */
1135 bool
1136 Var_Check_for_target(const char *str)
1137 {
1138 	bool seen_target = false;
1139 
1140 	for (;;) {
1141 		const char *tstr;
1142 		uint32_t k;
1143 		int idx;
1144 		bool has_modifier;
1145 		struct Name name;
1146 
1147 		/* skip over uninteresting stuff */
1148 		for (; *str != '\0' && *str != '$'; str++)
1149 			;
1150 		if (*str == '\0')
1151 			break;
1152 		if (str[1] == '$') {
1153 			/* A $ may be escaped with another $. */
1154 			str += 2;
1155 			continue;
1156 		}
1157 
1158 		tstr = str;
1159 
1160 		has_modifier = parse_base_variable_name(&tstr, &name, NULL);
1161 		idx = classify_var(name.s, &name.e, &k);
1162 		if (has_modifier) {
1163 			bool doFree = false;
1164 			char *val = VarModifiers_Apply(NULL, NULL, NULL, false,
1165 			    &doFree, &tstr, str[1]);
1166 			if (doFree)
1167 				free(val);
1168 		}
1169 		if (tlist[idx])
1170 			seen_target = true;
1171 		VarName_Free(&name);
1172 		str = tstr;
1173 	}
1174 	return seen_target;
1175 }
1176 
1177 static BUFFER subst_buffer;
1178 
1179 /* we would like to subst on intervals, but it's complicated, so we cheat
1180  * by storing the interval in a static buffer.
1181  */
1182 char *
1183 Var_Substi(const char *str, const char *estr, SymTable *ctxt, bool undefErr)
1184 {
1185 	/* delimited string: no need to copy */
1186 	if (estr == NULL || *estr == '\0')
1187 		return Var_Subst(str, ctxt, undefErr);
1188 
1189 	Buf_Reset(&subst_buffer);
1190 	Buf_Addi(&subst_buffer, str, estr);
1191 	return Var_Subst(Buf_Retrieve(&subst_buffer), ctxt, undefErr);
1192 }
1193 
1194 /***
1195  ***	Supplementary support for .for loops.
1196  ***/
1197 
1198 
1199 
1200 struct LoopVar
1201 {
1202 	Var old;	/* keep old variable value (before the loop) */
1203 	Var *me;	/* the variable we're dealing with */
1204 };
1205 
1206 
1207 struct LoopVar *
1208 Var_NewLoopVar(const char *name, const char *ename)
1209 {
1210 	struct LoopVar *l;
1211 	uint32_t k;
1212 
1213 	l = emalloc(sizeof(struct LoopVar));
1214 
1215 	/* we obtain a new variable quickly, make a snapshot of its old
1216 	 * value, and make sure the environment cannot touch us.
1217 	 */
1218 	/* XXX: should we avoid dynamic variables ? */
1219 	k = ohash_interval(name, &ename);
1220 
1221 	l->me = find_global_var_without_env(name, ename, k);
1222 	l->old = *(l->me);
1223 	l->me->flags = VAR_SEEN_ENV | VAR_DUMMY;
1224 	return l;
1225 }
1226 
1227 char *
1228 Var_LoopVarName(struct LoopVar *v)
1229 {
1230 	return v->me->name;
1231 }
1232 
1233 void
1234 Var_DeleteLoopVar(struct LoopVar *l)
1235 {
1236 	if ((l->me->flags & VAR_DUMMY) == 0)
1237 		Buf_Destroy(&(l->me->val));
1238 	*(l->me) = l->old;
1239 	free(l);
1240 }
1241 
1242 void
1243 Var_SubstVar(Buffer buf,	/* To store result */
1244     const char *str,		/* The string in which to substitute */
1245     struct LoopVar *l,		/* Handle */
1246     const char *val)		/* Its value */
1247 {
1248 	const char *var = l->me->name;
1249 
1250 	var_set_value(l->me, val);
1251 
1252 	for (;;) {
1253 		const char *start;
1254 		/* Copy uninteresting stuff */
1255 		for (start = str; *str != '\0' && *str != '$'; str++)
1256 			;
1257 		Buf_Addi(buf, start, str);
1258 
1259 		start = str;
1260 		if (*str++ == '\0')
1261 			break;
1262 		str++;
1263 		/* and escaped dollars */
1264 		if (start[1] == '$') {
1265 			Buf_Addi(buf, start, start+2);
1266 			continue;
1267 		}
1268 		/* Simple variable, if it's not us, copy.  */
1269 		if (start[1] != '(' && start[1] != '{') {
1270 			if (start[1] != *var || var[1] != '\0') {
1271 				Buf_AddChars(buf, 2, start);
1272 				continue;
1273 		    }
1274 		} else {
1275 			const char *p;
1276 			char paren = start[1];
1277 
1278 
1279 			/* Find the end of the variable specification.  */
1280 			p = find_pos(paren)(str);
1281 			/* A variable inside the variable. We don't know how to
1282 			 * expand the external variable at this point, so we
1283 			 * try  again with the nested variable.	*/
1284 			if (*p == '$') {
1285 				Buf_Addi(buf, start, p);
1286 				str = p;
1287 				continue;
1288 			}
1289 
1290 			if (strncmp(var, str, p - str) != 0 ||
1291 				var[p - str] != '\0') {
1292 				/* Not the variable we want to expand.	*/
1293 				Buf_Addi(buf, start, p);
1294 				str = p;
1295 				continue;
1296 			}
1297 			if (*p == ':') {
1298 				bool doFree;	/* should val be freed ? */
1299 				char *newval;
1300 				struct Name name;
1301 
1302 				doFree = false;
1303 				name.s = var;
1304 				name.e = var + (p-str);
1305 
1306 				/* val won't be freed since !doFree, but
1307 				 * VarModifiers_Apply doesn't know that,
1308 				 * hence the cast. */
1309 				newval = VarModifiers_Apply((char *)val,
1310 				    &name, NULL, false, &doFree, &p, paren);
1311 				Buf_AddString(buf, newval);
1312 				if (doFree)
1313 					free(newval);
1314 				str = p;
1315 				continue;
1316 			} else
1317 				str = p+1;
1318 		}
1319 		Buf_AddString(buf, val);
1320 	}
1321 }
1322 
1323 /***
1324  ***	Odds and ends
1325  ***/
1326 
1327 static void
1328 set_magic_shell_variable()
1329 {
1330 	const char *name = "SHELL";
1331 	const char *ename = NULL;
1332 	uint32_t k;
1333 	Var *v;
1334 
1335 	k = ohash_interval(name, &ename);
1336 	v = find_global_var_without_env(name, ename, k);
1337 	var_set_value(v, _PATH_BSHELL);
1338 	/* XXX the environment shall never affect it */
1339 	v->flags = VAR_IS_SHELL | VAR_SEEN_ENV;
1340 }
1341 
1342 /*
1343  * Var_Init
1344  *	Initialize the module
1345  */
1346 void
1347 Var_Init(void)
1348 {
1349 	ohash_init(&global_variables, 10, &var_info);
1350 	set_magic_shell_variable();
1351 
1352 
1353 	errorIsOkay = true;
1354 	Var_setCheckEnvFirst(false);
1355 
1356 	VarModifiers_Init();
1357 	Buf_Init(&subst_buffer, MAKE_BSIZE);
1358 }
1359 
1360 
1361 static const char *interpret(int);
1362 
1363 static const char *
1364 interpret(int f)
1365 {
1366 	if (f & VAR_DUMMY)
1367 		return "(D)";
1368 	return "";
1369 }
1370 
1371 
1372 static void
1373 print_var(Var *v)
1374 {
1375 	printf("%-16s%s = %s\n", v->name, interpret(v->flags),
1376 	    (v->flags & VAR_DUMMY) == 0 ? var_get_value(v) : "(none)");
1377 }
1378 
1379 
1380 void
1381 Var_Dump(void)
1382 {
1383 	Var **t;
1384 
1385 	unsigned int i;
1386 	const char *banner;
1387 	bool first = true;
1388 
1389 	t = sort_ohash_by_name(&global_variables);
1390 /* somewhat dirty, but does the trick */
1391 
1392 #define LOOP(mask, value, do_stuff) \
1393 	for (i = 0; t[i] != NULL; i++) \
1394 		if ((t[i]->flags & (mask)) == (value)) { \
1395 			if (banner) { \
1396 				if (first) \
1397 					first = false; \
1398 				else \
1399 					putchar('\n'); \
1400 				fputs(banner, stdout); \
1401 				banner = NULL; \
1402 			} \
1403 		    do_stuff; \
1404 		}
1405 
1406 	banner = "#variables from command line:\n";
1407 	LOOP(VAR_FROM_CMD | VAR_DUMMY, VAR_FROM_CMD, print_var(t[i]));
1408 
1409 	banner = "#global variables:\n";
1410 	LOOP(VAR_FROM_ENV| VAR_FROM_CMD | VAR_DUMMY, 0, print_var(t[i]));
1411 
1412 	banner = "#variables from env:\n";
1413 	LOOP(VAR_FROM_ENV|VAR_DUMMY, VAR_FROM_ENV, print_var(t[i]));
1414 
1415 	banner = "#variable name seen, but not defined:";
1416 	LOOP(VAR_DUMMY|POISONS, VAR_DUMMY, printf(" %s", t[i]->name));
1417 
1418 #undef LOOP
1419 
1420 	printf("\n\n");
1421 
1422 	for (i = 0; t[i] != NULL; i++)
1423 		switch(t[i]->flags & POISONS) {
1424 		case POISON_NORMAL:
1425 			printf(".poison %s\n", t[i]->name);
1426 			break;
1427 		case POISON_EMPTY:
1428 			printf(".poison empty(%s)\n", t[i]->name);
1429 			break;
1430 		case POISON_NOT_DEFINED:
1431 			printf(".poison !defined(%s)\n", t[i]->name);
1432 			break;
1433 		default:
1434 			break;
1435 		}
1436 	free(t);
1437 	printf("\n");
1438 }
1439 
1440 static const char *quotable = " \t\n\\'\"";
1441 
1442 /* POSIX says that variable assignments passed on the command line should be
1443  * propagated to sub makes through MAKEFLAGS.
1444  */
1445 void
1446 Var_AddCmdline(const char *name)
1447 {
1448 	Var *v;
1449 	unsigned int i;
1450 	BUFFER buf;
1451 	char *s;
1452 
1453 	Buf_Init(&buf, MAKE_BSIZE);
1454 
1455 	for (v = ohash_first(&global_variables, &i); v != NULL;
1456 	    v = ohash_next(&global_variables, &i)) {
1457 		/* This is not as expensive as it looks: this function is
1458 		 * called before parsing Makefiles, so there are just a
1459 		 * few non cmdling variables in there.
1460 		 */
1461 		if (!(v->flags & VAR_FROM_CMD)) {
1462 			continue;
1463 		}
1464 		/* We assume variable names don't need quoting */
1465 		Buf_AddString(&buf, v->name);
1466 		Buf_AddChar(&buf, '=');
1467 		for (s = var_get_value(v); *s != '\0'; s++) {
1468 			if (strchr(quotable, *s))
1469 				Buf_AddChar(&buf, '\\');
1470 			Buf_AddChar(&buf, *s);
1471 		}
1472 		Buf_AddSpace(&buf);
1473 	}
1474 	Var_Append(name, Buf_Retrieve(&buf));
1475 	Buf_Destroy(&buf);
1476 }
1477