Make sure to assign a boolean value to a 1-bit bitfield. Reported on
[make.git] / variable.c
blob43964a59fa721551629ed9ac43ba89fde4da9581
1 /* Internals of variables for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1996, 1997,
3 2002 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Make is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Make; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include "make.h"
23 #include <assert.h>
25 #include "dep.h"
26 #include "filedef.h"
27 #include "job.h"
28 #include "commands.h"
29 #include "variable.h"
30 #include "rule.h"
31 #ifdef WINDOWS32
32 #include "pathstuff.h"
33 #endif
34 #include "hash.h"
36 /* Chain of all pattern-specific variables. */
38 static struct pattern_var *pattern_vars;
40 /* Pointer to last struct in the chain, so we can add onto the end. */
42 static struct pattern_var *last_pattern_var;
44 /* Create a new pattern-specific variable struct. */
46 struct pattern_var *
47 create_pattern_var (char *target, char *suffix)
49 register struct pattern_var *p
50 = (struct pattern_var *) xmalloc (sizeof (struct pattern_var));
52 if (last_pattern_var != 0)
53 last_pattern_var->next = p;
54 else
55 pattern_vars = p;
56 last_pattern_var = p;
57 p->next = 0;
59 p->target = target;
60 p->len = strlen (target);
61 p->suffix = suffix + 1;
63 return p;
66 /* Look up a target in the pattern-specific variable list. */
68 static struct pattern_var *
69 lookup_pattern_var (struct pattern_var *start, char *target)
71 struct pattern_var *p;
72 unsigned int targlen = strlen(target);
74 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
76 char *stem;
77 unsigned int stemlen;
79 if (p->len > targlen)
80 /* It can't possibly match. */
81 continue;
83 /* From the lengths of the filename and the pattern parts,
84 find the stem: the part of the filename that matches the %. */
85 stem = target + (p->suffix - p->target - 1);
86 stemlen = targlen - p->len + 1;
88 /* Compare the text in the pattern before the stem, if any. */
89 if (stem > target && !strneq (p->target, target, stem - target))
90 continue;
92 /* Compare the text in the pattern after the stem, if any.
93 We could test simply using streq, but this way we compare the
94 first two characters immediately. This saves time in the very
95 common case where the first character matches because it is a
96 period. */
97 if (*p->suffix == stem[stemlen]
98 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
99 break;
102 return p;
105 /* Hash table of all global variable definitions. */
107 static unsigned long
108 variable_hash_1 (const void *keyv)
110 struct variable const *key = (struct variable const *) keyv;
111 return_STRING_N_HASH_1 (key->name, key->length);
114 static unsigned long
115 variable_hash_2 (const void *keyv)
117 struct variable const *key = (struct variable const *) keyv;
118 return_STRING_N_HASH_2 (key->name, key->length);
121 static int
122 variable_hash_cmp (const void *xv, const void *yv)
124 struct variable const *x = (struct variable const *) xv;
125 struct variable const *y = (struct variable const *) yv;
126 int result = x->length - y->length;
127 if (result)
128 return result;
129 return_STRING_N_COMPARE (x->name, y->name, x->length);
132 #ifndef VARIABLE_BUCKETS
133 #define VARIABLE_BUCKETS 523
134 #endif
135 #ifndef PERFILE_VARIABLE_BUCKETS
136 #define PERFILE_VARIABLE_BUCKETS 23
137 #endif
138 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
139 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
140 #endif
142 static struct variable_set global_variable_set;
143 static struct variable_set_list global_setlist
144 = { 0, &global_variable_set };
145 struct variable_set_list *current_variable_set_list = &global_setlist;
147 /* Implement variables. */
149 void
150 init_hash_global_variable_set (void)
152 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
153 variable_hash_1, variable_hash_2, variable_hash_cmp);
156 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
157 LENGTH is the length of NAME, which does not need to be null-terminated.
158 ORIGIN specifies the origin of the variable (makefile, command line
159 or environment).
160 If RECURSIVE is nonzero a flag is set in the variable saying
161 that it should be recursively re-expanded. */
163 struct variable *
164 define_variable_in_set (const char *name, unsigned int length,
165 char *value, enum variable_origin origin,
166 int recursive, struct variable_set *set,
167 const struct floc *flocp)
169 struct variable *v;
170 struct variable **var_slot;
171 struct variable var_key;
173 if (set == NULL)
174 set = &global_variable_set;
176 var_key.name = (char *) name;
177 var_key.length = length;
178 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
180 if (env_overrides && origin == o_env)
181 origin = o_env_override;
183 v = *var_slot;
184 if (! HASH_VACANT (v))
186 if (env_overrides && v->origin == o_env)
187 /* V came from in the environment. Since it was defined
188 before the switches were parsed, it wasn't affected by -e. */
189 v->origin = o_env_override;
191 /* A variable of this name is already defined.
192 If the old definition is from a stronger source
193 than this one, don't redefine it. */
194 if ((int) origin >= (int) v->origin)
196 if (v->value != 0)
197 free (v->value);
198 v->value = xstrdup (value);
199 if (flocp != 0)
200 v->fileinfo = *flocp;
201 else
202 v->fileinfo.filenm = 0;
203 v->origin = origin;
204 v->recursive = recursive;
206 return v;
209 /* Create a new variable definition and add it to the hash table. */
211 v = (struct variable *) xmalloc (sizeof (struct variable));
212 v->name = savestring (name, length);
213 v->length = length;
214 hash_insert_at (&set->table, v, var_slot);
215 v->value = xstrdup (value);
216 if (flocp != 0)
217 v->fileinfo = *flocp;
218 else
219 v->fileinfo.filenm = 0;
220 v->origin = origin;
221 v->recursive = recursive;
222 v->special = 0;
223 v->expanding = 0;
224 v->exp_count = 0;
225 v->per_target = 0;
226 v->append = 0;
227 v->export = v_default;
229 v->exportable = 1;
230 if (*name != '_' && (*name < 'A' || *name > 'Z')
231 && (*name < 'a' || *name > 'z'))
232 v->exportable = 0;
233 else
235 for (++name; *name != '\0'; ++name)
236 if (*name != '_' && (*name < 'a' || *name > 'z')
237 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
238 break;
240 if (*name != '\0')
241 v->exportable = 0;
244 return v;
247 /* If the variable passed in is "special", handle its special nature.
248 Currently there are two such variables, both used for introspection:
249 .VARIABLES expands to a list of all the variables defined in this instance
250 of make.
251 .TARGETS expands to a list of all the targets defined in this
252 instance of make.
253 Returns the variable reference passed in. */
255 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
257 static struct variable *
258 handle_special_var (struct variable *var)
260 static unsigned long last_var_count = 0;
263 /* This one actually turns out to be very hard, due to the way the parser
264 records targets. The way it works is that target information is collected
265 internally until make knows the target is completely specified. It unitl
266 it sees that some new construct (a new target or variable) is defined that
267 it knows the previous one is done. In short, this means that if you do
268 this:
270 all:
272 TARGS := $(.TARGETS)
274 then $(TARGS) won't contain "all", because it's not until after the
275 variable is created that the previous target is completed.
277 Changing this would be a major pain. I think a less complex way to do it
278 would be to pre-define the target files as soon as the first line is
279 parsed, then come back and do the rest of the definition as now. That
280 would allow $(.TARGETS) to be correct without a major change to the way
281 the parser works.
283 if (streq (var->name, ".TARGETS"))
284 var->value = build_target_list (var->value);
285 else
288 if (streq (var->name, ".VARIABLES")
289 && global_variable_set.table.ht_fill != last_var_count)
291 unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
292 unsigned long len;
293 char *p;
294 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
295 struct variable **end = &vp[global_variable_set.table.ht_size];
297 /* Make sure we have at least MAX bytes in the allocated buffer. */
298 var->value = xrealloc (var->value, max);
300 /* Walk through the hash of variables, constructing a list of names. */
301 p = var->value;
302 len = 0;
303 for (; vp < end; ++vp)
304 if (!HASH_VACANT (*vp))
306 struct variable *v = *vp;
307 int l = v->length;
309 len += l + 1;
310 if (len > max)
312 unsigned long off = p - var->value;
314 max += EXPANSION_INCREMENT (l + 1);
315 var->value = xrealloc (var->value, max);
316 p = &var->value[off];
319 bcopy (v->name, p, l);
320 p += l;
321 *(p++) = ' ';
323 *(p-1) = '\0';
325 /* Remember how many variables are in our current count. Since we never
326 remove variables from the list, this is a reliable way to know whether
327 the list is up to date or needs to be recomputed. */
329 last_var_count = global_variable_set.table.ht_fill;
332 return var;
336 /* Lookup a variable whose name is a string starting at NAME
337 and with LENGTH chars. NAME need not be null-terminated.
338 Returns address of the `struct variable' containing all info
339 on the variable, or nil if no such variable is defined. */
341 struct variable *
342 lookup_variable (const char *name, unsigned int length)
344 const struct variable_set_list *setlist;
345 struct variable var_key;
347 var_key.name = (char *) name;
348 var_key.length = length;
350 for (setlist = current_variable_set_list;
351 setlist != 0; setlist = setlist->next)
353 const struct variable_set *set = setlist->set;
354 struct variable *v;
356 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
357 if (v)
358 return v->special ? handle_special_var (v) : v;
361 #ifdef VMS
362 /* since we don't read envp[] on startup, try to get the
363 variable via getenv() here. */
365 char *vname = alloca (length + 1);
366 char *value;
367 strncpy (vname, name, length);
368 vname[length] = 0;
369 value = getenv (vname);
370 if (value != 0)
372 char *sptr;
373 int scnt;
375 sptr = value;
376 scnt = 0;
378 while ((sptr = strchr (sptr, '$')))
380 scnt++;
381 sptr++;
384 if (scnt > 0)
386 char *nvalue;
387 char *nptr;
389 nvalue = alloca (strlen (value) + scnt + 1);
390 sptr = value;
391 nptr = nvalue;
393 while (*sptr)
395 if (*sptr == '$')
397 *nptr++ = '$';
398 *nptr++ = '$';
400 else
402 *nptr++ = *sptr;
404 sptr++;
407 *nptr = '\0';
408 return define_variable (vname, length, nvalue, o_env, 1);
412 return define_variable (vname, length, value, o_env, 1);
415 #endif /* VMS */
417 return 0;
420 /* Lookup a variable whose name is a string starting at NAME
421 and with LENGTH chars in set SET. NAME need not be null-terminated.
422 Returns address of the `struct variable' containing all info
423 on the variable, or nil if no such variable is defined. */
425 struct variable *
426 lookup_variable_in_set (const char *name, unsigned int length,
427 const struct variable_set *set)
429 struct variable var_key;
431 var_key.name = (char *) name;
432 var_key.length = length;
434 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
437 /* Initialize FILE's variable set list. If FILE already has a variable set
438 list, the topmost variable set is left intact, but the the rest of the
439 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
440 rule, then we will use the "root" double-colon target's variable set as the
441 parent of FILE's variable set.
443 If we're READing a makefile, don't do the pattern variable search now,
444 since the pattern variable might not have been defined yet. */
446 void
447 initialize_file_variables (struct file *file, int reading)
449 struct variable_set_list *l = file->variables;
451 if (l == 0)
453 l = (struct variable_set_list *)
454 xmalloc (sizeof (struct variable_set_list));
455 l->set = (struct variable_set *) xmalloc (sizeof (struct variable_set));
456 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
457 variable_hash_1, variable_hash_2, variable_hash_cmp);
458 file->variables = l;
461 /* If this is a double-colon, then our "parent" is the "root" target for
462 this double-colon rule. Since that rule has the same name, parent,
463 etc. we can just use its variables as the "next" for ours. */
465 if (file->double_colon && file->double_colon != file)
467 initialize_file_variables (file->double_colon, reading);
468 l->next = file->double_colon->variables;
469 return;
472 if (file->parent == 0)
473 l->next = &global_setlist;
474 else
476 initialize_file_variables (file->parent, reading);
477 l->next = file->parent->variables;
480 /* If we're not reading makefiles and we haven't looked yet, see if
481 we can find pattern variables for this target. */
483 if (!reading && !file->pat_searched)
485 struct pattern_var *p;
487 p = lookup_pattern_var (0, file->name);
488 if (p != 0)
490 struct variable_set_list *global = current_variable_set_list;
492 /* We found at least one. Set up a new variable set to accumulate
493 all the pattern variables that match this target. */
495 file->pat_variables = create_new_variable_set ();
496 current_variable_set_list = file->pat_variables;
500 /* We found one, so insert it into the set. */
502 struct variable *v;
504 if (p->variable.flavor == f_simple)
506 v = define_variable_loc (
507 p->variable.name, strlen (p->variable.name),
508 p->variable.value, p->variable.origin,
509 0, &p->variable.fileinfo);
511 v->flavor = f_simple;
513 else
515 v = do_variable_definition (
516 &p->variable.fileinfo, p->variable.name,
517 p->variable.value, p->variable.origin,
518 p->variable.flavor, 1);
521 /* Also mark it as a per-target and copy export status. */
522 v->per_target = p->variable.per_target;
523 v->export = p->variable.export;
525 while ((p = lookup_pattern_var (p, file->name)) != 0);
527 current_variable_set_list = global;
529 file->pat_searched = 1;
532 /* If we have a pattern variable match, set it up. */
534 if (file->pat_variables != 0)
536 file->pat_variables->next = l->next;
537 l->next = file->pat_variables;
541 /* Pop the top set off the current variable set list,
542 and free all its storage. */
544 static void
545 free_variable_name_and_value (const void *item)
547 struct variable *v = (struct variable *) item;
548 free (v->name);
549 free (v->value);
552 struct variable_set_list *
553 create_new_variable_set (void)
555 register struct variable_set_list *setlist;
556 register struct variable_set *set;
558 set = (struct variable_set *) xmalloc (sizeof (struct variable_set));
559 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
560 variable_hash_1, variable_hash_2, variable_hash_cmp);
562 setlist = (struct variable_set_list *)
563 xmalloc (sizeof (struct variable_set_list));
564 setlist->set = set;
565 setlist->next = current_variable_set_list;
567 return setlist;
570 /* Create a new variable set and push it on the current setlist.
571 If we're pushing a global scope (that is, the current scope is the global
572 scope) then we need to "push" it the other way: file variable sets point
573 directly to the global_setlist so we need to replace that with the new one.
576 struct variable_set_list *
577 push_new_variable_scope (void)
579 current_variable_set_list = create_new_variable_set();
580 if (current_variable_set_list->next == &global_setlist)
582 /* It was the global, so instead of new -> &global we want to replace
583 &global with the new one and have &global -> new, with current still
584 pointing to &global */
585 struct variable_set *set = current_variable_set_list->set;
586 current_variable_set_list->set = global_setlist.set;
587 global_setlist.set = set;
588 current_variable_set_list->next = global_setlist.next;
589 global_setlist.next = current_variable_set_list;
590 current_variable_set_list = &global_setlist;
592 return (current_variable_set_list);
595 void
596 pop_variable_scope (void)
598 struct variable_set_list *setlist;
599 struct variable_set *set;
601 /* Can't call this if there's no scope to pop! */
602 assert(current_variable_set_list->next != NULL);
604 if (current_variable_set_list != &global_setlist)
606 /* We're not pointing to the global setlist, so pop this one. */
607 setlist = current_variable_set_list;
608 set = setlist->set;
609 current_variable_set_list = setlist->next;
611 else
613 /* This set is the one in the global_setlist, but there is another global
614 set beyond that. We want to copy that set to global_setlist, then
615 delete what used to be in global_setlist. */
616 setlist = global_setlist.next;
617 set = global_setlist.set;
618 global_setlist.set = setlist->set;
619 global_setlist.next = setlist->next;
622 /* Free the one we no longer need. */
623 free ((char *) setlist);
624 hash_map (&set->table, free_variable_name_and_value);
625 hash_free (&set->table, 1);
626 free ((char *) set);
629 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
631 static void
632 merge_variable_sets (struct variable_set *to_set,
633 struct variable_set *from_set)
635 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
636 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
638 for ( ; from_var_slot < from_var_end; from_var_slot++)
639 if (! HASH_VACANT (*from_var_slot))
641 struct variable *from_var = *from_var_slot;
642 struct variable **to_var_slot
643 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
644 if (HASH_VACANT (*to_var_slot))
645 hash_insert_at (&to_set->table, from_var, to_var_slot);
646 else
648 /* GKM FIXME: delete in from_set->table */
649 free (from_var->value);
650 free (from_var);
655 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
657 void
658 merge_variable_set_lists (struct variable_set_list **setlist0,
659 struct variable_set_list *setlist1)
661 register struct variable_set_list *list0 = *setlist0;
662 struct variable_set_list *last0 = 0;
664 while (setlist1 != 0 && list0 != 0)
666 struct variable_set_list *next = setlist1;
667 setlist1 = setlist1->next;
669 merge_variable_sets (list0->set, next->set);
671 last0 = list0;
672 list0 = list0->next;
675 if (setlist1 != 0)
677 if (last0 == 0)
678 *setlist0 = setlist1;
679 else
680 last0->next = setlist1;
684 /* Define the automatic variables, and record the addresses
685 of their structures so we can change their values quickly. */
687 void
688 define_automatic_variables (void)
690 #if defined(WINDOWS32) || defined(__EMX__)
691 extern char* default_shell;
692 #else
693 extern char default_shell[];
694 #endif
695 register struct variable *v;
696 char buf[200];
698 sprintf (buf, "%u", makelevel);
699 (void) define_variable (MAKELEVEL_NAME, MAKELEVEL_LENGTH, buf, o_env, 0);
701 sprintf (buf, "%s%s%s",
702 version_string,
703 (remote_description == 0 || remote_description[0] == '\0')
704 ? "" : "-",
705 (remote_description == 0 || remote_description[0] == '\0')
706 ? "" : remote_description);
707 (void) define_variable ("MAKE_VERSION", 12, buf, o_default, 0);
709 #ifdef __MSDOS__
710 /* Allow to specify a special shell just for Make,
711 and use $COMSPEC as the default $SHELL when appropriate. */
713 static char shell_str[] = "SHELL";
714 const int shlen = sizeof (shell_str) - 1;
715 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
716 struct variable *comp = lookup_variable ("COMSPEC", 7);
718 /* Make $MAKESHELL override $SHELL even if -e is in effect. */
719 if (mshp)
720 (void) define_variable (shell_str, shlen,
721 mshp->value, o_env_override, 0);
722 else if (comp)
724 /* $COMSPEC shouldn't override $SHELL. */
725 struct variable *shp = lookup_variable (shell_str, shlen);
727 if (!shp)
728 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
731 #elif defined(__EMX__)
733 static char shell_str[] = "SHELL";
734 const int shlen = sizeof (shell_str) - 1;
735 struct variable *shell = lookup_variable (shell_str, shlen);
736 struct variable *replace = lookup_variable ("MAKESHELL", 9);
738 /* if $MAKESHELL is defined in the environment assume o_env_override */
739 if (replace && *replace->value && replace->origin == o_env)
740 replace->origin = o_env_override;
742 /* if $MAKESHELL is not defined use $SHELL but only if the variable
743 did not come from the environment */
744 if (!replace || !*replace->value)
745 if (shell && *shell->value && (shell->origin == o_env
746 || shell->origin == o_env_override))
748 /* overwrite whatever we got from the environment */
749 free(shell->value);
750 shell->value = xstrdup (default_shell);
751 shell->origin = o_default;
754 /* Some people do not like cmd to be used as the default
755 if $SHELL is not defined in the Makefile.
756 With -DNO_CMD_DEFAULT you can turn off this behaviour */
757 # ifndef NO_CMD_DEFAULT
758 /* otherwise use $COMSPEC */
759 if (!replace || !*replace->value)
760 replace = lookup_variable ("COMSPEC", 7);
762 /* otherwise use $OS2_SHELL */
763 if (!replace || !*replace->value)
764 replace = lookup_variable ("OS2_SHELL", 9);
765 # else
766 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
767 # endif
769 if (replace && *replace->value)
770 /* overwrite $SHELL */
771 (void) define_variable (shell_str, shlen, replace->value,
772 replace->origin, 0);
773 else
774 /* provide a definition if there is none */
775 (void) define_variable (shell_str, shlen, default_shell,
776 o_default, 0);
779 #endif
781 /* This won't override any definition, but it will provide one if there
782 isn't one there. */
783 v = define_variable ("SHELL", 5, default_shell, o_default, 0);
785 /* On MSDOS we do use SHELL from environment, since it isn't a standard
786 environment variable on MSDOS, so whoever sets it, does that on purpose.
787 On OS/2 we do not use SHELL from environment but we have already handled
788 that problem above. */
789 #if !defined(__MSDOS__) && !defined(__EMX__)
790 /* Don't let SHELL come from the environment. */
791 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
793 free (v->value);
794 v->origin = o_file;
795 v->value = xstrdup (default_shell);
797 #endif
799 /* Make sure MAKEFILES gets exported if it is set. */
800 v = define_variable ("MAKEFILES", 9, "", o_default, 0);
801 v->export = v_ifset;
803 /* Define the magic D and F variables in terms of
804 the automatic variables they are variations of. */
806 #ifdef VMS
807 define_variable ("@D", 2, "$(dir $@)", o_automatic, 1);
808 define_variable ("%D", 2, "$(dir $%)", o_automatic, 1);
809 define_variable ("*D", 2, "$(dir $*)", o_automatic, 1);
810 define_variable ("<D", 2, "$(dir $<)", o_automatic, 1);
811 define_variable ("?D", 2, "$(dir $?)", o_automatic, 1);
812 define_variable ("^D", 2, "$(dir $^)", o_automatic, 1);
813 define_variable ("+D", 2, "$(dir $+)", o_automatic, 1);
814 #else
815 define_variable ("@D", 2, "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
816 define_variable ("%D", 2, "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
817 define_variable ("*D", 2, "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
818 define_variable ("<D", 2, "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
819 define_variable ("?D", 2, "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
820 define_variable ("^D", 2, "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
821 define_variable ("+D", 2, "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
822 #endif
823 define_variable ("@F", 2, "$(notdir $@)", o_automatic, 1);
824 define_variable ("%F", 2, "$(notdir $%)", o_automatic, 1);
825 define_variable ("*F", 2, "$(notdir $*)", o_automatic, 1);
826 define_variable ("<F", 2, "$(notdir $<)", o_automatic, 1);
827 define_variable ("?F", 2, "$(notdir $?)", o_automatic, 1);
828 define_variable ("^F", 2, "$(notdir $^)", o_automatic, 1);
829 define_variable ("+F", 2, "$(notdir $+)", o_automatic, 1);
832 int export_all_variables;
834 /* Create a new environment for FILE's commands.
835 If FILE is nil, this is for the `shell' function.
836 The child's MAKELEVEL variable is incremented. */
838 char **
839 target_environment (struct file *file)
841 struct variable_set_list *set_list;
842 register struct variable_set_list *s;
843 struct hash_table table;
844 struct variable **v_slot;
845 struct variable **v_end;
846 struct variable makelevel_key;
847 char **result_0;
848 char **result;
850 if (file == 0)
851 set_list = current_variable_set_list;
852 else
853 set_list = file->variables;
855 hash_init (&table, VARIABLE_BUCKETS,
856 variable_hash_1, variable_hash_2, variable_hash_cmp);
858 /* Run through all the variable sets in the list,
859 accumulating variables in TABLE. */
860 for (s = set_list; s != 0; s = s->next)
862 struct variable_set *set = s->set;
863 v_slot = (struct variable **) set->table.ht_vec;
864 v_end = v_slot + set->table.ht_size;
865 for ( ; v_slot < v_end; v_slot++)
866 if (! HASH_VACANT (*v_slot))
868 struct variable **new_slot;
869 struct variable *v = *v_slot;
871 /* If this is a per-target variable and it hasn't been touched
872 already then look up the global version and take its export
873 value. */
874 if (v->per_target && v->export == v_default)
876 struct variable *gv;
878 gv = lookup_variable_in_set (v->name, strlen(v->name),
879 &global_variable_set);
880 if (gv)
881 v->export = gv->export;
884 switch (v->export)
886 case v_default:
887 if (v->origin == o_default || v->origin == o_automatic)
888 /* Only export default variables by explicit request. */
889 continue;
891 /* The variable doesn't have a name that can be exported. */
892 if (! v->exportable)
893 continue;
895 if (! export_all_variables
896 && v->origin != o_command
897 && v->origin != o_env && v->origin != o_env_override)
898 continue;
899 break;
901 case v_export:
902 break;
904 case v_noexport:
905 /* If this is the SHELL variable and it's not exported, then
906 add the value from our original environment. */
907 if (streq (v->name, "SHELL"))
909 extern struct variable shell_var;
910 v = &shell_var;
911 break;
913 continue;
915 case v_ifset:
916 if (v->origin == o_default)
917 continue;
918 break;
921 new_slot = (struct variable **) hash_find_slot (&table, v);
922 if (HASH_VACANT (*new_slot))
923 hash_insert_at (&table, v, new_slot);
927 makelevel_key.name = MAKELEVEL_NAME;
928 makelevel_key.length = MAKELEVEL_LENGTH;
929 hash_delete (&table, &makelevel_key);
931 result = result_0 = (char **) xmalloc ((table.ht_fill + 2) * sizeof (char *));
933 v_slot = (struct variable **) table.ht_vec;
934 v_end = v_slot + table.ht_size;
935 for ( ; v_slot < v_end; v_slot++)
936 if (! HASH_VACANT (*v_slot))
938 struct variable *v = *v_slot;
940 /* If V is recursively expanded and didn't come from the environment,
941 expand its value. If it came from the environment, it should
942 go back into the environment unchanged. */
943 if (v->recursive
944 && v->origin != o_env && v->origin != o_env_override)
946 char *value = recursively_expand_for_file (v, file);
947 #ifdef WINDOWS32
948 if (strcmp(v->name, "Path") == 0 ||
949 strcmp(v->name, "PATH") == 0)
950 convert_Path_to_windows32(value, ';');
951 #endif
952 *result++ = concat (v->name, "=", value);
953 free (value);
955 else
957 #ifdef WINDOWS32
958 if (strcmp(v->name, "Path") == 0 ||
959 strcmp(v->name, "PATH") == 0)
960 convert_Path_to_windows32(v->value, ';');
961 #endif
962 *result++ = concat (v->name, "=", v->value);
966 *result = (char *) xmalloc (100);
967 (void) sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
968 *++result = 0;
970 hash_free (&table, 0);
972 return result_0;
975 /* Given a variable, a value, and a flavor, define the variable.
976 See the try_variable_definition() function for details on the parameters. */
978 struct variable *
979 do_variable_definition (const struct floc *flocp, const char *varname,
980 char *value, enum variable_origin origin,
981 enum variable_flavor flavor, int target_var)
983 char *p, *alloc_value = NULL;
984 struct variable *v;
985 int append = 0;
986 int conditional = 0;
988 /* Calculate the variable's new value in VALUE. */
990 switch (flavor)
992 default:
993 case f_bogus:
994 /* Should not be possible. */
995 abort ();
996 case f_simple:
997 /* A simple variable definition "var := value". Expand the value.
998 We have to allocate memory since otherwise it'll clobber the
999 variable buffer, and we may still need that if we're looking at a
1000 target-specific variable. */
1001 p = alloc_value = allocated_variable_expand (value);
1002 break;
1003 case f_conditional:
1004 /* A conditional variable definition "var ?= value".
1005 The value is set IFF the variable is not defined yet. */
1006 v = lookup_variable (varname, strlen (varname));
1007 if (v)
1008 return v;
1010 conditional = 1;
1011 flavor = f_recursive;
1012 /* FALLTHROUGH */
1013 case f_recursive:
1014 /* A recursive variable definition "var = value".
1015 The value is used verbatim. */
1016 p = value;
1017 break;
1018 case f_append:
1020 /* If we have += but we're in a target variable context, we want to
1021 append only with other variables in the context of this target. */
1022 if (target_var)
1024 append = 1;
1025 v = lookup_variable_in_set (varname, strlen (varname),
1026 current_variable_set_list->set);
1028 /* Don't append from the global set if a previous non-appending
1029 target-specific variable definition exists. */
1030 if (v && !v->append)
1031 append = 0;
1033 else
1034 v = lookup_variable (varname, strlen (varname));
1036 if (v == 0)
1038 /* There was no old value.
1039 This becomes a normal recursive definition. */
1040 p = value;
1041 flavor = f_recursive;
1043 else
1045 /* Paste the old and new values together in VALUE. */
1047 unsigned int oldlen, vallen;
1048 char *val;
1050 val = value;
1051 if (v->recursive)
1052 /* The previous definition of the variable was recursive.
1053 The new value is the unexpanded old and new values. */
1054 flavor = f_recursive;
1055 else
1056 /* The previous definition of the variable was simple.
1057 The new value comes from the old value, which was expanded
1058 when it was set; and from the expanded new value. Allocate
1059 memory for the expansion as we may still need the rest of the
1060 buffer if we're looking at a target-specific variable. */
1061 val = alloc_value = allocated_variable_expand (val);
1063 oldlen = strlen (v->value);
1064 vallen = strlen (val);
1065 p = (char *) alloca (oldlen + 1 + vallen + 1);
1066 bcopy (v->value, p, oldlen);
1067 p[oldlen] = ' ';
1068 bcopy (val, &p[oldlen + 1], vallen + 1);
1073 #ifdef __MSDOS__
1074 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1075 non-Unix systems don't conform to this default configuration (in
1076 fact, most of them don't even have `/bin'). On the other hand,
1077 $SHELL in the environment, if set, points to the real pathname of
1078 the shell.
1079 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1080 the Makefile override $SHELL from the environment. But first, we
1081 look for the basename of the shell in the directory where SHELL=
1082 points, and along the $PATH; if it is found in any of these places,
1083 we define $SHELL to be the actual pathname of the shell. Thus, if
1084 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1085 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1086 defining SHELL to be "d:/unix/bash.exe". */
1087 if ((origin == o_file || origin == o_override)
1088 && strcmp (varname, "SHELL") == 0)
1090 PATH_VAR (shellpath);
1091 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1093 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1094 if (__dosexec_find_on_path (p, (char **)0, shellpath))
1096 char *p;
1098 for (p = shellpath; *p; p++)
1100 if (*p == '\\')
1101 *p = '/';
1103 v = define_variable_loc (varname, strlen (varname),
1104 shellpath, origin, flavor == f_recursive,
1105 flocp);
1107 else
1109 char *shellbase, *bslash;
1110 struct variable *pathv = lookup_variable ("PATH", 4);
1111 char *path_string;
1112 char *fake_env[2];
1113 size_t pathlen = 0;
1115 shellbase = strrchr (p, '/');
1116 bslash = strrchr (p, '\\');
1117 if (!shellbase || bslash > shellbase)
1118 shellbase = bslash;
1119 if (!shellbase && p[1] == ':')
1120 shellbase = p + 1;
1121 if (shellbase)
1122 shellbase++;
1123 else
1124 shellbase = p;
1126 /* Search for the basename of the shell (with standard
1127 executable extensions) along the $PATH. */
1128 if (pathv)
1129 pathlen = strlen (pathv->value);
1130 path_string = (char *)xmalloc (5 + pathlen + 2 + 1);
1131 /* On MSDOS, current directory is considered as part of $PATH. */
1132 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1133 fake_env[0] = path_string;
1134 fake_env[1] = (char *)0;
1135 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1137 char *p;
1139 for (p = shellpath; *p; p++)
1141 if (*p == '\\')
1142 *p = '/';
1144 v = define_variable_loc (varname, strlen (varname),
1145 shellpath, origin,
1146 flavor == f_recursive, flocp);
1148 else
1149 v = lookup_variable (varname, strlen (varname));
1151 free (path_string);
1154 else
1155 #endif /* __MSDOS__ */
1156 #ifdef WINDOWS32
1157 if ((origin == o_file || origin == o_override) && streq (varname, "SHELL"))
1159 extern char *default_shell;
1161 /* Call shell locator function. If it returns TRUE, then
1162 set no_default_sh_exe to indicate sh was found and
1163 set new value for SHELL variable. */
1165 if (find_and_set_default_shell (p))
1167 v = define_variable_in_set (varname, strlen (varname), default_shell,
1168 origin, flavor == f_recursive,
1169 (target_var
1170 ? current_variable_set_list->set
1171 : NULL),
1172 flocp);
1173 no_default_sh_exe = 0;
1175 else
1176 v = lookup_variable (varname, strlen (varname));
1178 else
1179 #endif
1181 /* If we are defining variables inside an $(eval ...), we might have a
1182 different variable context pushed, not the global context (maybe we're
1183 inside a $(call ...) or something. Since this function is only ever
1184 invoked in places where we want to define globally visible variables,
1185 make sure we define this variable in the global set. */
1187 v = define_variable_in_set (varname, strlen (varname), p,
1188 origin, flavor == f_recursive,
1189 (target_var
1190 ? current_variable_set_list->set : NULL),
1191 flocp);
1192 v->append = append;
1193 v->conditional = conditional;
1195 if (alloc_value)
1196 free (alloc_value);
1198 return v;
1201 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1203 ORIGIN may be o_file, o_override, o_env, o_env_override,
1204 or o_command specifying that the variable definition comes
1205 from a makefile, an override directive, the environment with
1206 or without the -e switch, or the command line.
1208 See the comments for parse_variable_definition().
1210 If LINE was recognized as a variable definition, a pointer to its `struct
1211 variable' is returned. If LINE is not a variable definition, NULL is
1212 returned. */
1214 struct variable *
1215 parse_variable_definition (struct variable *v, char *line)
1217 register int c;
1218 register char *p = line;
1219 register char *beg;
1220 register char *end;
1221 enum variable_flavor flavor = f_bogus;
1222 char *name;
1224 while (1)
1226 c = *p++;
1227 if (c == '\0' || c == '#')
1228 return 0;
1229 if (c == '=')
1231 end = p - 1;
1232 flavor = f_recursive;
1233 break;
1235 else if (c == ':')
1236 if (*p == '=')
1238 end = p++ - 1;
1239 flavor = f_simple;
1240 break;
1242 else
1243 /* A colon other than := is a rule line, not a variable defn. */
1244 return 0;
1245 else if (c == '+' && *p == '=')
1247 end = p++ - 1;
1248 flavor = f_append;
1249 break;
1251 else if (c == '?' && *p == '=')
1253 end = p++ - 1;
1254 flavor = f_conditional;
1255 break;
1257 else if (c == '$')
1259 /* This might begin a variable expansion reference. Make sure we
1260 don't misrecognize chars inside the reference as =, := or +=. */
1261 char closeparen;
1262 int count;
1263 c = *p++;
1264 if (c == '(')
1265 closeparen = ')';
1266 else if (c == '{')
1267 closeparen = '}';
1268 else
1269 continue; /* Nope. */
1271 /* P now points past the opening paren or brace.
1272 Count parens or braces until it is matched. */
1273 count = 0;
1274 for (; *p != '\0'; ++p)
1276 if (*p == c)
1277 ++count;
1278 else if (*p == closeparen && --count < 0)
1280 ++p;
1281 break;
1286 v->flavor = flavor;
1288 beg = next_token (line);
1289 while (end > beg && isblank ((unsigned char)end[-1]))
1290 --end;
1291 p = next_token (p);
1292 v->value = p;
1294 /* Expand the name, so "$(foo)bar = baz" works. */
1295 name = (char *) alloca (end - beg + 1);
1296 bcopy (beg, name, end - beg);
1297 name[end - beg] = '\0';
1298 v->name = allocated_variable_expand (name);
1300 if (v->name[0] == '\0')
1301 fatal (&v->fileinfo, _("empty variable name"));
1303 return v;
1306 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1308 ORIGIN may be o_file, o_override, o_env, o_env_override,
1309 or o_command specifying that the variable definition comes
1310 from a makefile, an override directive, the environment with
1311 or without the -e switch, or the command line.
1313 See the comments for parse_variable_definition().
1315 If LINE was recognized as a variable definition, a pointer to its `struct
1316 variable' is returned. If LINE is not a variable definition, NULL is
1317 returned. */
1319 struct variable *
1320 try_variable_definition (const struct floc *flocp, char *line,
1321 enum variable_origin origin, int target_var)
1323 struct variable v;
1324 struct variable *vp;
1326 if (flocp != 0)
1327 v.fileinfo = *flocp;
1328 else
1329 v.fileinfo.filenm = 0;
1331 if (!parse_variable_definition (&v, line))
1332 return 0;
1334 vp = do_variable_definition (flocp, v.name, v.value,
1335 origin, v.flavor, target_var);
1337 free (v.name);
1339 return vp;
1342 /* Print information for variable V, prefixing it with PREFIX. */
1344 static void
1345 print_variable (const void *item, void *arg)
1347 const struct variable *v = (struct variable *) item;
1348 const char *prefix = (char *) arg;
1349 const char *origin;
1351 switch (v->origin)
1353 case o_default:
1354 origin = _("default");
1355 break;
1356 case o_env:
1357 origin = _("environment");
1358 break;
1359 case o_file:
1360 origin = _("makefile");
1361 break;
1362 case o_env_override:
1363 origin = _("environment under -e");
1364 break;
1365 case o_command:
1366 origin = _("command line");
1367 break;
1368 case o_override:
1369 origin = _("`override' directive");
1370 break;
1371 case o_automatic:
1372 origin = _("automatic");
1373 break;
1374 case o_invalid:
1375 default:
1376 abort ();
1378 fputs ("# ", stdout);
1379 fputs (origin, stdout);
1380 if (v->fileinfo.filenm)
1381 printf (_(" (from `%s', line %lu)"),
1382 v->fileinfo.filenm, v->fileinfo.lineno);
1383 putchar ('\n');
1384 fputs (prefix, stdout);
1386 /* Is this a `define'? */
1387 if (v->recursive && strchr (v->value, '\n') != 0)
1388 printf ("define %s\n%s\nendef\n", v->name, v->value);
1389 else
1391 register char *p;
1393 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1395 /* Check if the value is just whitespace. */
1396 p = next_token (v->value);
1397 if (p != v->value && *p == '\0')
1398 /* All whitespace. */
1399 printf ("$(subst ,,%s)", v->value);
1400 else if (v->recursive)
1401 fputs (v->value, stdout);
1402 else
1403 /* Double up dollar signs. */
1404 for (p = v->value; *p != '\0'; ++p)
1406 if (*p == '$')
1407 putchar ('$');
1408 putchar (*p);
1410 putchar ('\n');
1415 /* Print all the variables in SET. PREFIX is printed before
1416 the actual variable definitions (everything else is comments). */
1418 void
1419 print_variable_set (struct variable_set *set, char *prefix)
1421 hash_map_arg (&set->table, print_variable, prefix);
1423 fputs (_("# variable set hash-table stats:\n"), stdout);
1424 fputs ("# ", stdout);
1425 hash_print_stats (&set->table, stdout);
1426 putc ('\n', stdout);
1429 /* Print the data base of variables. */
1431 void
1432 print_variable_data_base (void)
1434 puts (_("\n# Variables\n"));
1436 print_variable_set (&global_variable_set, "");
1438 puts (_("\n# Pattern-specific Variable Values"));
1441 struct pattern_var *p;
1442 int rules = 0;
1444 for (p = pattern_vars; p != 0; p = p->next)
1446 ++rules;
1447 printf ("\n%s :\n", p->target);
1448 print_variable (&p->variable, "# ");
1451 if (rules == 0)
1452 puts (_("\n# No pattern-specific variable values."));
1453 else
1454 printf (_("\n# %u pattern-specific variable values"), rules);
1459 /* Print all the local variables of FILE. */
1461 void
1462 print_file_variables (struct file *file)
1464 if (file->variables != 0)
1465 print_variable_set (file->variables->set, "# ");
1468 #ifdef WINDOWS32
1469 void
1470 sync_Path_environment (void)
1472 char *path = allocated_variable_expand ("$(PATH)");
1473 static char *environ_path = NULL;
1475 if (!path)
1476 return;
1479 * If done this before, don't leak memory unnecessarily.
1480 * Free the previous entry before allocating new one.
1482 if (environ_path)
1483 free (environ_path);
1486 * Create something WINDOWS32 world can grok
1488 convert_Path_to_windows32 (path, ';');
1489 environ_path = concat ("PATH", "=", path);
1490 putenv (environ_path);
1491 free (path);
1493 #endif