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