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