1 /* Internals of variables for GNU Make.
2 Copyright (C) 1988-2020 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
28 #include "pathstuff.h"
32 /* Incremented every time we add or remove a global variable. */
33 static unsigned long variable_changenum;
35 /* Chain of all pattern-specific variables. */
37 static struct pattern_var *pattern_vars;
39 /* Pointer to the last struct in the pack of a specific size, from 1 to 255.*/
41 static struct pattern_var *last_pattern_vars[256];
43 /* Create a new pattern-specific variable struct. The new variable is
44 inserted into the PATTERN_VARS list in the shortest patterns first
45 order to support the shortest stem matching (the variables are
46 matched in the reverse order so the ones with the longest pattern
47 will be considered first). Variables with the same pattern length
48 are inserted in the definition order. */
51 create_pattern_var (const char *target, const char *suffix)
53 size_t len = strlen (target);
54 struct pattern_var *p = xcalloc (sizeof (struct pattern_var));
56 if (pattern_vars != 0)
58 if (len < 256 && last_pattern_vars[len] != 0)
60 p->next = last_pattern_vars[len]->next;
61 last_pattern_vars[len]->next = p;
65 /* Find the position where we can insert this variable. */
66 struct pattern_var **v;
68 for (v = &pattern_vars; ; v = &(*v)->next)
70 /* Insert at the end of the pack so that patterns with the
71 same length appear in the order they were defined .*/
73 if (*v == 0 || (*v)->len > len)
90 p->suffix = suffix + 1;
93 last_pattern_vars[len] = p;
98 /* Look up a target in the pattern-specific variable list. */
100 static struct pattern_var *
101 lookup_pattern_var (struct pattern_var *start, const char *target)
103 struct pattern_var *p;
104 size_t targlen = strlen (target);
106 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
111 if (p->len > targlen)
112 /* It can't possibly match. */
115 /* From the lengths of the filename and the pattern parts,
116 find the stem: the part of the filename that matches the %. */
117 stem = target + (p->suffix - p->target - 1);
118 stemlen = targlen - p->len + 1;
120 /* Compare the text in the pattern before the stem, if any. */
121 if (stem > target && !strneq (p->target, target, stem - target))
124 /* Compare the text in the pattern after the stem, if any.
125 We could test simply using streq, but this way we compare the
126 first two characters immediately. This saves time in the very
127 common case where the first character matches because it is a
129 if (*p->suffix == stem[stemlen]
130 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
137 /* Hash table of all global variable definitions. */
140 variable_hash_1 (const void *keyv)
142 struct variable const *key = (struct variable const *) keyv;
143 return_STRING_N_HASH_1 (key->name, key->length);
147 variable_hash_2 (const void *keyv)
149 struct variable const *key = (struct variable const *) keyv;
150 return_STRING_N_HASH_2 (key->name, key->length);
154 variable_hash_cmp (const void *xv, const void *yv)
156 struct variable const *x = (struct variable const *) xv;
157 struct variable const *y = (struct variable const *) yv;
158 int result = x->length - y->length;
161 return_STRING_N_COMPARE (x->name, y->name, x->length);
164 #ifndef VARIABLE_BUCKETS
165 #define VARIABLE_BUCKETS 523
167 #ifndef PERFILE_VARIABLE_BUCKETS
168 #define PERFILE_VARIABLE_BUCKETS 23
170 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
171 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
174 static struct variable_set global_variable_set;
175 static struct variable_set_list global_setlist
176 = { 0, &global_variable_set, 0 };
177 struct variable_set_list *current_variable_set_list = &global_setlist;
179 /* Implement variables. */
182 init_hash_global_variable_set (void)
184 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
185 variable_hash_1, variable_hash_2, variable_hash_cmp);
188 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
189 LENGTH is the length of NAME, which does not need to be null-terminated.
190 ORIGIN specifies the origin of the variable (makefile, command line
192 If RECURSIVE is nonzero a flag is set in the variable saying
193 that it should be recursively re-expanded. */
196 define_variable_in_set (const char *name, size_t length,
197 const char *value, enum variable_origin origin,
198 int recursive, struct variable_set *set,
202 struct variable **var_slot;
203 struct variable var_key;
206 set = &global_variable_set;
208 var_key.name = (char *) name;
209 var_key.length = (unsigned int) length;
210 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
214 /* VMS does not populate envp[] with DCL symbols and logical names which
215 historically are mapped to environent variables.
216 If the variable is not yet defined, then we need to check if getenv()
217 can find it. Do not do this for origin == o_env to avoid infinte
219 if (HASH_VACANT (v) && (origin != o_env))
221 struct variable * vms_variable;
222 char * vname = alloca (length + 1);
225 strncpy (vname, name, length);
226 vvalue = getenv(vname);
228 /* Values starting with '$' are probably foreign commands.
229 We want to treat them as Shell aliases and not look them up here */
230 if ((vvalue != NULL) && (vvalue[0] != '$'))
232 vms_variable = lookup_variable(name, length);
233 /* Refresh the slot */
234 var_slot = (struct variable **) hash_find_slot (&set->table,
241 if (env_overrides && origin == o_env)
242 origin = o_env_override;
244 if (! HASH_VACANT (v))
246 if (env_overrides && v->origin == o_env)
247 /* V came from in the environment. Since it was defined
248 before the switches were parsed, it wasn't affected by -e. */
249 v->origin = o_env_override;
251 /* A variable of this name is already defined.
252 If the old definition is from a stronger source
253 than this one, don't redefine it. */
254 if ((int) origin >= (int) v->origin)
257 v->value = xstrdup (value);
259 v->fileinfo = *flocp;
261 v->fileinfo.filenm = 0;
263 v->recursive = recursive;
268 /* Create a new variable definition and add it to the hash table. */
270 v = xcalloc (sizeof (struct variable));
271 v->name = xstrndup (name, length);
272 v->length = (unsigned int) length;
273 hash_insert_at (&set->table, v, var_slot);
274 if (set == &global_variable_set)
275 ++variable_changenum;
277 v->value = xstrdup (value);
279 v->fileinfo = *flocp;
281 v->recursive = recursive;
283 v->export = v_default;
285 if (*name != '_' && (*name < 'A' || *name > 'Z')
286 && (*name < 'a' || *name > 'z'))
290 for (++name; *name != '\0'; ++name)
291 if (*name != '_' && (*name < 'a' || *name > 'z')
292 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
303 /* Undefine variable named NAME in SET. LENGTH is the length of NAME, which
304 does not need to be null-terminated. ORIGIN specifies the origin of the
305 variable (makefile, command line or environment). */
308 free_variable_name_and_value (const void *item)
310 struct variable *v = (struct variable *) item;
316 free_variable_set (struct variable_set_list *list)
318 hash_map (&list->set->table, free_variable_name_and_value);
319 hash_free (&list->set->table, 1);
325 undefine_variable_in_set (const char *name, size_t length,
326 enum variable_origin origin,
327 struct variable_set *set)
330 struct variable **var_slot;
331 struct variable var_key;
334 set = &global_variable_set;
336 var_key.name = (char *) name;
337 var_key.length = (unsigned int) length;
338 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
340 if (env_overrides && origin == o_env)
341 origin = o_env_override;
344 if (! HASH_VACANT (v))
346 if (env_overrides && v->origin == o_env)
347 /* V came from in the environment. Since it was defined
348 before the switches were parsed, it wasn't affected by -e. */
349 v->origin = o_env_override;
351 /* Undefine only if this undefinition is from an equal or stronger
352 source than the variable definition. */
353 if ((int) origin >= (int) v->origin)
355 hash_delete_at (&set->table, var_slot);
356 free_variable_name_and_value (v);
358 if (set == &global_variable_set)
359 ++variable_changenum;
364 /* If the variable passed in is "special", handle its special nature.
365 Currently there are two such variables, both used for introspection:
366 .VARIABLES expands to a list of all the variables defined in this instance
368 .TARGETS expands to a list of all the targets defined in this
370 Returns the variable reference passed in. */
372 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
374 static struct variable *
375 lookup_special_var (struct variable *var)
377 static unsigned long last_changenum = 0;
380 /* This one actually turns out to be very hard, due to the way the parser
381 records targets. The way it works is that target information is collected
382 internally until make knows the target is completely specified. It unitl
383 it sees that some new construct (a new target or variable) is defined that
384 it knows the previous one is done. In short, this means that if you do
391 then $(TARGS) won't contain "all", because it's not until after the
392 variable is created that the previous target is completed.
394 Changing this would be a major pain. I think a less complex way to do it
395 would be to pre-define the target files as soon as the first line is
396 parsed, then come back and do the rest of the definition as now. That
397 would allow $(.TARGETS) to be correct without a major change to the way
400 if (streq (var->name, ".TARGETS"))
401 var->value = build_target_list (var->value);
405 if (variable_changenum != last_changenum && streq (var->name, ".VARIABLES"))
407 size_t max = EXPANSION_INCREMENT (strlen (var->value));
410 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
411 struct variable **end = &vp[global_variable_set.table.ht_size];
413 /* Make sure we have at least MAX bytes in the allocated buffer. */
414 var->value = xrealloc (var->value, max);
416 /* Walk through the hash of variables, constructing a list of names. */
419 for (; vp < end; ++vp)
420 if (!HASH_VACANT (*vp))
422 struct variable *v = *vp;
428 size_t off = p - var->value;
430 max += EXPANSION_INCREMENT (l + 1);
431 var->value = xrealloc (var->value, max);
432 p = &var->value[off];
435 memcpy (p, v->name, l);
441 /* Remember the current variable change number. */
442 last_changenum = variable_changenum;
449 /* Lookup a variable whose name is a string starting at NAME
450 and with LENGTH chars. NAME need not be null-terminated.
451 Returns address of the 'struct variable' containing all info
452 on the variable, or nil if no such variable is defined. */
455 lookup_variable (const char *name, size_t length)
457 const struct variable_set_list *setlist;
458 struct variable var_key;
461 var_key.name = (char *) name;
462 var_key.length = (unsigned int) length;
464 for (setlist = current_variable_set_list;
465 setlist != 0; setlist = setlist->next)
467 const struct variable_set *set = setlist->set;
470 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
471 if (v && (!is_parent || !v->private_var))
472 return v->special ? lookup_special_var (v) : v;
474 is_parent |= setlist->next_is_parent;
478 /* VMS does not populate envp[] with DCL symbols and logical names which
479 historically are mapped to enviroment varables and returned by getenv() */
481 char *vname = alloca (length + 1);
483 strncpy (vname, name, length);
485 value = getenv (vname);
494 while ((sptr = strchr (sptr, '$')))
505 nvalue = alloca (strlen (value) + scnt + 1);
524 return define_variable (vname, length, nvalue, o_env, 1);
528 return define_variable (vname, length, value, o_env, 1);
536 /* Lookup a variable whose name is a string starting at NAME
537 and with LENGTH chars in set SET. NAME need not be null-terminated.
538 Returns address of the 'struct variable' containing all info
539 on the variable, or nil if no such variable is defined. */
542 lookup_variable_in_set (const char *name, size_t length,
543 const struct variable_set *set)
545 struct variable var_key;
547 var_key.name = (char *) name;
548 var_key.length = (unsigned int) length;
550 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
553 /* Initialize FILE's variable set list. If FILE already has a variable set
554 list, the topmost variable set is left intact, but the the rest of the
555 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
556 rule, then we will use the "root" double-colon target's variable set as the
557 parent of FILE's variable set.
559 If we're READING a makefile, don't do the pattern variable search now,
560 since the pattern variable might not have been defined yet. */
563 initialize_file_variables (struct file *file, int reading)
565 struct variable_set_list *l = file->variables;
569 l = (struct variable_set_list *)
570 xmalloc (sizeof (struct variable_set_list));
571 l->set = xmalloc (sizeof (struct variable_set));
572 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
573 variable_hash_1, variable_hash_2, variable_hash_cmp);
577 /* If this is a double-colon, then our "parent" is the "root" target for
578 this double-colon rule. Since that rule has the same name, parent,
579 etc. we can just use its variables as the "next" for ours. */
581 if (file->double_colon && file->double_colon != file)
583 initialize_file_variables (file->double_colon, reading);
584 l->next = file->double_colon->variables;
585 l->next_is_parent = 0;
589 if (file->parent == 0)
590 l->next = &global_setlist;
593 initialize_file_variables (file->parent, reading);
594 l->next = file->parent->variables;
596 l->next_is_parent = 1;
598 /* If we're not reading makefiles and we haven't looked yet, see if
599 we can find pattern variables for this target. */
601 if (!reading && !file->pat_searched)
603 struct pattern_var *p;
605 p = lookup_pattern_var (0, file->name);
608 struct variable_set_list *global = current_variable_set_list;
610 /* We found at least one. Set up a new variable set to accumulate
611 all the pattern variables that match this target. */
613 file->pat_variables = create_new_variable_set ();
614 current_variable_set_list = file->pat_variables;
618 /* We found one, so insert it into the set. */
622 if (p->variable.flavor == f_simple)
624 v = define_variable_loc (
625 p->variable.name, strlen (p->variable.name),
626 p->variable.value, p->variable.origin,
627 0, &p->variable.fileinfo);
629 v->flavor = f_simple;
633 v = do_variable_definition (
634 &p->variable.fileinfo, p->variable.name,
635 p->variable.value, p->variable.origin,
636 p->variable.flavor, 1);
639 /* Also mark it as a per-target and copy export status. */
640 v->per_target = p->variable.per_target;
641 v->export = p->variable.export;
642 v->private_var = p->variable.private_var;
644 while ((p = lookup_pattern_var (p, file->name)) != 0);
646 current_variable_set_list = global;
648 file->pat_searched = 1;
651 /* If we have a pattern variable match, set it up. */
653 if (file->pat_variables != 0)
655 file->pat_variables->next = l->next;
656 file->pat_variables->next_is_parent = l->next_is_parent;
657 l->next = file->pat_variables;
658 l->next_is_parent = 0;
662 /* Pop the top set off the current variable set list,
663 and free all its storage. */
665 struct variable_set_list *
666 create_new_variable_set (void)
668 struct variable_set_list *setlist;
669 struct variable_set *set;
671 set = xmalloc (sizeof (struct variable_set));
672 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
673 variable_hash_1, variable_hash_2, variable_hash_cmp);
675 setlist = (struct variable_set_list *)
676 xmalloc (sizeof (struct variable_set_list));
678 setlist->next = current_variable_set_list;
679 setlist->next_is_parent = 0;
684 /* Create a new variable set and push it on the current setlist.
685 If we're pushing a global scope (that is, the current scope is the global
686 scope) then we need to "push" it the other way: file variable sets point
687 directly to the global_setlist so we need to replace that with the new one.
690 struct variable_set_list *
691 push_new_variable_scope (void)
693 current_variable_set_list = create_new_variable_set ();
694 if (current_variable_set_list->next == &global_setlist)
696 /* It was the global, so instead of new -> &global we want to replace
697 &global with the new one and have &global -> new, with current still
698 pointing to &global */
699 struct variable_set *set = current_variable_set_list->set;
700 current_variable_set_list->set = global_setlist.set;
701 global_setlist.set = set;
702 current_variable_set_list->next = global_setlist.next;
703 global_setlist.next = current_variable_set_list;
704 current_variable_set_list = &global_setlist;
706 return (current_variable_set_list);
710 pop_variable_scope (void)
712 struct variable_set_list *setlist;
713 struct variable_set *set;
715 /* Can't call this if there's no scope to pop! */
716 assert (current_variable_set_list->next != NULL);
718 if (current_variable_set_list != &global_setlist)
720 /* We're not pointing to the global setlist, so pop this one. */
721 setlist = current_variable_set_list;
723 current_variable_set_list = setlist->next;
727 /* This set is the one in the global_setlist, but there is another global
728 set beyond that. We want to copy that set to global_setlist, then
729 delete what used to be in global_setlist. */
730 setlist = global_setlist.next;
731 set = global_setlist.set;
732 global_setlist.set = setlist->set;
733 global_setlist.next = setlist->next;
734 global_setlist.next_is_parent = setlist->next_is_parent;
737 /* Free the one we no longer need. */
739 hash_map (&set->table, free_variable_name_and_value);
740 hash_free (&set->table, 1);
744 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
747 merge_variable_sets (struct variable_set *to_set,
748 struct variable_set *from_set)
750 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
751 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
753 int inc = to_set == &global_variable_set ? 1 : 0;
755 for ( ; from_var_slot < from_var_end; from_var_slot++)
756 if (! HASH_VACANT (*from_var_slot))
758 struct variable *from_var = *from_var_slot;
759 struct variable **to_var_slot
760 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
761 if (HASH_VACANT (*to_var_slot))
763 hash_insert_at (&to_set->table, from_var, to_var_slot);
764 variable_changenum += inc;
768 /* GKM FIXME: delete in from_set->table */
769 free (from_var->value);
775 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
778 merge_variable_set_lists (struct variable_set_list **setlist0,
779 struct variable_set_list *setlist1)
781 struct variable_set_list *to = *setlist0;
782 struct variable_set_list *last0 = 0;
784 /* If there's nothing to merge, stop now. */
785 if (!setlist1 || setlist1 == &global_setlist)
790 /* These loops rely on the fact that all setlists terminate with the
791 global setlist (before NULL). If not, arguably we SHOULD die. */
793 /* Make sure that setlist1 is not already a subset of setlist0. */
794 while (to != &global_setlist)
802 while (setlist1 != &global_setlist && to != &global_setlist)
804 struct variable_set_list *from = setlist1;
805 setlist1 = setlist1->next;
807 merge_variable_sets (to->set, from->set);
814 if (setlist1 != &global_setlist)
817 *setlist0 = setlist1;
819 last0->next = setlist1;
823 /* Define the automatic variables, and record the addresses
824 of their structures so we can change their values quickly. */
827 define_automatic_variables (void)
832 sprintf (buf, "%u", makelevel);
833 define_variable_cname (MAKELEVEL_NAME, buf, o_env, 0);
835 sprintf (buf, "%s%s%s",
837 (remote_description == 0 || remote_description[0] == '\0')
839 (remote_description == 0 || remote_description[0] == '\0')
840 ? "" : remote_description);
841 define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
842 define_variable_cname ("MAKE_HOST", make_host, o_default, 0);
845 /* Allow to specify a special shell just for Make,
846 and use $COMSPEC as the default $SHELL when appropriate. */
848 static char shell_str[] = "SHELL";
849 const int shlen = sizeof (shell_str) - 1;
850 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
851 struct variable *comp = lookup_variable ("COMSPEC", 7);
853 /* $(MAKESHELL) overrides $(SHELL) even if -e is in effect. */
855 (void) define_variable (shell_str, shlen,
856 mshp->value, o_env_override, 0);
859 /* $(COMSPEC) shouldn't override $(SHELL). */
860 struct variable *shp = lookup_variable (shell_str, shlen);
863 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
866 #elif defined(__EMX__)
868 static char shell_str[] = "SHELL";
869 const int shlen = sizeof (shell_str) - 1;
870 struct variable *shell = lookup_variable (shell_str, shlen);
871 struct variable *replace = lookup_variable ("MAKESHELL", 9);
873 /* if $MAKESHELL is defined in the environment assume o_env_override */
874 if (replace && *replace->value && replace->origin == o_env)
875 replace->origin = o_env_override;
877 /* if $MAKESHELL is not defined use $SHELL but only if the variable
878 did not come from the environment */
879 if (!replace || !*replace->value)
880 if (shell && *shell->value && (shell->origin == o_env
881 || shell->origin == o_env_override))
883 /* overwrite whatever we got from the environment */
885 shell->value = xstrdup (default_shell);
886 shell->origin = o_default;
889 /* Some people do not like cmd to be used as the default
890 if $SHELL is not defined in the Makefile.
891 With -DNO_CMD_DEFAULT you can turn off this behaviour */
892 # ifndef NO_CMD_DEFAULT
893 /* otherwise use $COMSPEC */
894 if (!replace || !*replace->value)
895 replace = lookup_variable ("COMSPEC", 7);
897 /* otherwise use $OS2_SHELL */
898 if (!replace || !*replace->value)
899 replace = lookup_variable ("OS2_SHELL", 9);
901 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
904 if (replace && *replace->value)
905 /* overwrite $SHELL */
906 (void) define_variable (shell_str, shlen, replace->value,
909 /* provide a definition if there is none */
910 (void) define_variable (shell_str, shlen, default_shell,
916 /* This won't override any definition, but it will provide one if there
918 v = define_variable_cname ("SHELL", default_shell, o_default, 0);
920 v->export = v_export; /* Export always SHELL. */
923 /* On MSDOS we do use SHELL from environment, since it isn't a standard
924 environment variable on MSDOS, so whoever sets it, does that on purpose.
925 On OS/2 we do not use SHELL from environment but we have already handled
926 that problem above. */
927 #if !defined(__MSDOS__) && !defined(__EMX__)
928 /* Don't let SHELL come from the environment. */
929 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
933 v->value = xstrdup (default_shell);
937 /* Make sure MAKEFILES gets exported if it is set. */
938 v = define_variable_cname ("MAKEFILES", "", o_default, 0);
941 /* Define the magic D and F variables in terms of
942 the automatic variables they are variations of. */
944 #if defined(__MSDOS__) || defined(WINDOWS32)
945 /* For consistency, remove the trailing backslash as well as slash. */
946 define_variable_cname ("@D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $@)))",
948 define_variable_cname ("%D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $%)))",
950 define_variable_cname ("*D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $*)))",
952 define_variable_cname ("<D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $<)))",
954 define_variable_cname ("?D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $?)))",
956 define_variable_cname ("^D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $^)))",
958 define_variable_cname ("+D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $+)))",
960 #else /* not __MSDOS__, not WINDOWS32 */
961 define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
962 define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
963 define_variable_cname ("*D", "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
964 define_variable_cname ("<D", "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
965 define_variable_cname ("?D", "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
966 define_variable_cname ("^D", "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
967 define_variable_cname ("+D", "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
969 define_variable_cname ("@F", "$(notdir $@)", o_automatic, 1);
970 define_variable_cname ("%F", "$(notdir $%)", o_automatic, 1);
971 define_variable_cname ("*F", "$(notdir $*)", o_automatic, 1);
972 define_variable_cname ("<F", "$(notdir $<)", o_automatic, 1);
973 define_variable_cname ("?F", "$(notdir $?)", o_automatic, 1);
974 define_variable_cname ("^F", "$(notdir $^)", o_automatic, 1);
975 define_variable_cname ("+F", "$(notdir $+)", o_automatic, 1);
978 int export_all_variables;
980 /* Create a new environment for FILE's commands.
981 If FILE is nil, this is for the 'shell' function.
982 The child's MAKELEVEL variable is incremented. */
985 target_environment (struct file *file)
987 struct variable_set_list *set_list;
988 struct variable_set_list *s;
989 struct hash_table table;
990 struct variable **v_slot;
991 struct variable **v_end;
992 struct variable makelevel_key;
997 set_list = current_variable_set_list;
999 set_list = file->variables;
1001 hash_init (&table, VARIABLE_BUCKETS,
1002 variable_hash_1, variable_hash_2, variable_hash_cmp);
1004 /* Run through all the variable sets in the list,
1005 accumulating variables in TABLE. */
1006 for (s = set_list; s != 0; s = s->next)
1008 struct variable_set *set = s->set;
1009 v_slot = (struct variable **) set->table.ht_vec;
1010 v_end = v_slot + set->table.ht_size;
1011 for ( ; v_slot < v_end; v_slot++)
1012 if (! HASH_VACANT (*v_slot))
1014 struct variable **new_slot;
1015 struct variable *v = *v_slot;
1017 /* If this is a per-target variable and it hasn't been touched
1018 already then look up the global version and take its export
1020 if (v->per_target && v->export == v_default)
1022 struct variable *gv;
1024 gv = lookup_variable_in_set (v->name, strlen (v->name),
1025 &global_variable_set);
1027 v->export = gv->export;
1033 if (v->origin == o_default || v->origin == o_automatic)
1034 /* Only export default variables by explicit request. */
1037 /* The variable doesn't have a name that can be exported. */
1038 if (! v->exportable)
1041 if (! export_all_variables
1042 && v->origin != o_command
1043 && v->origin != o_env && v->origin != o_env_override)
1052 /* If this is the SHELL variable and it's not exported,
1053 then add the value from our original environment, if
1054 the original environment defined a value for SHELL. */
1055 if (streq (v->name, "SHELL") && shell_var.value)
1064 if (v->origin == o_default)
1069 new_slot = (struct variable **) hash_find_slot (&table, v);
1070 if (HASH_VACANT (*new_slot))
1071 hash_insert_at (&table, v, new_slot);
1075 makelevel_key.name = (char *)MAKELEVEL_NAME;
1076 makelevel_key.length = MAKELEVEL_LENGTH;
1077 hash_delete (&table, &makelevel_key);
1079 result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
1081 v_slot = (struct variable **) table.ht_vec;
1082 v_end = v_slot + table.ht_size;
1083 for ( ; v_slot < v_end; v_slot++)
1084 if (! HASH_VACANT (*v_slot))
1086 struct variable *v = *v_slot;
1088 /* If V is recursively expanded and didn't come from the environment,
1089 expand its value. If it came from the environment, it should
1090 go back into the environment unchanged. */
1092 && v->origin != o_env && v->origin != o_env_override)
1094 char *value = recursively_expand_for_file (v, file);
1096 if (strcmp (v->name, "Path") == 0 ||
1097 strcmp (v->name, "PATH") == 0)
1098 convert_Path_to_windows32 (value, ';');
1100 *result++ = xstrdup (concat (3, v->name, "=", value));
1106 if (strcmp (v->name, "Path") == 0 ||
1107 strcmp (v->name, "PATH") == 0)
1108 convert_Path_to_windows32 (v->value, ';');
1110 *result++ = xstrdup (concat (3, v->name, "=", v->value));
1114 *result = xmalloc (100);
1115 sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
1118 hash_free (&table, 0);
1123 static struct variable *
1124 set_special_var (struct variable *var)
1126 if (streq (var->name, RECIPEPREFIX_NAME))
1128 /* The user is resetting the command introduction prefix. This has to
1129 happen immediately, so that subsequent rules are interpreted
1131 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1137 /* Given a string, shell-execute it and return a malloc'ed string of the
1138 * result. This removes only ONE newline (if any) at the end, for maximum
1139 * compatibility with the *BSD makes. If it fails, returns NULL. */
1142 shell_result (const char *p)
1149 install_variable_buffer (&buf, &len);
1151 args[0] = (char *) p;
1153 variable_buffer_output (func_shell_base (variable_buffer, args, 0), "\0", 1);
1154 result = strdup (variable_buffer);
1156 restore_variable_buffer (buf, len);
1160 /* Given a variable, a value, and a flavor, define the variable.
1161 See the try_variable_definition() function for details on the parameters. */
1164 do_variable_definition (const floc *flocp, const char *varname,
1165 const char *value, enum variable_origin origin,
1166 enum variable_flavor flavor, int target_var)
1169 char *alloc_value = NULL;
1172 int conditional = 0;
1174 /* Calculate the variable's new value in VALUE. */
1180 /* Should not be possible. */
1183 /* A simple variable definition "var := value". Expand the value.
1184 We have to allocate memory since otherwise it'll clobber the
1185 variable buffer, and we may still need that if we're looking at a
1186 target-specific variable. */
1187 p = alloc_value = allocated_variable_expand (value);
1191 /* A shell definition "var != value". Expand value, pass it to
1192 the shell, and store the result in recursively-expanded var. */
1193 char *q = allocated_variable_expand (value);
1194 p = alloc_value = shell_result (q);
1196 flavor = f_recursive;
1200 /* A conditional variable definition "var ?= value".
1201 The value is set IFF the variable is not defined yet. */
1202 v = lookup_variable (varname, strlen (varname));
1207 flavor = f_recursive;
1210 /* A recursive variable definition "var = value".
1211 The value is used verbatim. */
1215 case f_append_value:
1217 /* If we have += but we're in a target variable context, we want to
1218 append only with other variables in the context of this target. */
1222 v = lookup_variable_in_set (varname, strlen (varname),
1223 current_variable_set_list->set);
1225 /* Don't append from the global set if a previous non-appending
1226 target-specific variable definition exists. */
1227 if (v && !v->append)
1231 v = lookup_variable (varname, strlen (varname));
1235 /* There was no old value.
1236 This becomes a normal recursive definition. */
1238 flavor = f_recursive;
1242 /* Paste the old and new values together in VALUE. */
1244 size_t oldlen, vallen;
1250 /* The previous definition of the variable was recursive.
1251 The new value is the unexpanded old and new values. */
1252 flavor = f_recursive;
1253 else if (flavor != f_append_value)
1254 /* The previous definition of the variable was simple.
1255 The new value comes from the old value, which was expanded
1256 when it was set; and from the expanded new value. Allocate
1257 memory for the expansion as we may still need the rest of the
1258 buffer if we're looking at a target-specific variable. */
1259 val = tp = allocated_variable_expand (val);
1261 /* If the new value is empty, nothing to do. */
1262 vallen = strlen (val);
1269 oldlen = strlen (v->value);
1270 p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1274 memcpy (alloc_value, v->value, oldlen);
1275 alloc_value[oldlen] = ' ';
1279 memcpy (&alloc_value[oldlen], val, vallen + 1);
1288 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1289 non-Unix systems don't conform to this default configuration (in
1290 fact, most of them don't even have '/bin'). On the other hand,
1291 $SHELL in the environment, if set, points to the real pathname of
1293 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1294 the Makefile override $SHELL from the environment. But first, we
1295 look for the basename of the shell in the directory where SHELL=
1296 points, and along the $PATH; if it is found in any of these places,
1297 we define $SHELL to be the actual pathname of the shell. Thus, if
1298 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1299 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1300 defining SHELL to be "d:/unix/bash.exe". */
1301 if ((origin == o_file || origin == o_override)
1302 && strcmp (varname, "SHELL") == 0)
1304 PATH_VAR (shellpath);
1305 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1307 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1308 if (__dosexec_find_on_path (p, NULL, shellpath))
1312 for (tp = shellpath; *tp; tp++)
1316 v = define_variable_loc (varname, strlen (varname),
1317 shellpath, origin, flavor == f_recursive,
1322 const char *shellbase, *bslash;
1323 struct variable *pathv = lookup_variable ("PATH", 4);
1328 shellbase = strrchr (p, '/');
1329 bslash = strrchr (p, '\\');
1330 if (!shellbase || bslash > shellbase)
1332 if (!shellbase && p[1] == ':')
1339 /* Search for the basename of the shell (with standard
1340 executable extensions) along the $PATH. */
1342 pathlen = strlen (pathv->value);
1343 path_string = xmalloc (5 + pathlen + 2 + 1);
1344 /* On MSDOS, current directory is considered as part of $PATH. */
1345 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1346 fake_env[0] = path_string;
1348 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1352 for (tp = shellpath; *tp; tp++)
1356 v = define_variable_loc (varname, strlen (varname),
1358 flavor == f_recursive, flocp);
1361 v = lookup_variable (varname, strlen (varname));
1367 #endif /* __MSDOS__ */
1369 if ((origin == o_file || origin == o_override || origin == o_command)
1370 && streq (varname, "SHELL"))
1372 extern const char *default_shell;
1374 /* Call shell locator function. If it returns TRUE, then
1375 set no_default_sh_exe to indicate sh was found and
1376 set new value for SHELL variable. */
1378 if (find_and_set_default_shell (p))
1380 v = define_variable_in_set (varname, strlen (varname), default_shell,
1381 origin, flavor == f_recursive,
1383 ? current_variable_set_list->set
1386 no_default_sh_exe = 0;
1390 char *tp = alloc_value;
1392 alloc_value = allocated_variable_expand (p);
1394 if (find_and_set_default_shell (alloc_value))
1396 v = define_variable_in_set (varname, strlen (varname), p,
1397 origin, flavor == f_recursive,
1399 ? current_variable_set_list->set
1402 no_default_sh_exe = 0;
1405 v = lookup_variable (varname, strlen (varname));
1413 /* If not $SHELL, or if $SHELL points to a program we didn't find,
1414 just process this variable "as usual". */
1418 /* If we are defining variables inside an $(eval ...), we might have a
1419 different variable context pushed, not the global context (maybe we're
1420 inside a $(call ...) or something. Since this function is only ever
1421 invoked in places where we want to define globally visible variables,
1422 make sure we define this variable in the global set. */
1424 v = define_variable_in_set (varname, strlen (varname), p,
1425 origin, flavor == f_recursive,
1427 ? current_variable_set_list->set : NULL),
1430 v->conditional = conditional;
1434 return v->special ? set_special_var (v) : v;
1437 /* Parse P (a null-terminated string) as a variable definition.
1439 If it is not a variable definition, return NULL and the contents of *VAR
1440 are undefined, except NAME is set to the first non-space character or NIL.
1442 If it is a variable definition, return a pointer to the char after the
1443 assignment token and set the following fields (only) of *VAR:
1444 name : name of the variable (ALWAYS SET) (NOT NUL-TERMINATED!)
1445 length : length of the variable name
1446 value : value of the variable (nul-terminated)
1447 flavor : flavor of the variable
1448 Other values in *VAR are unchanged.
1452 parse_variable_definition (const char *p, struct variable *var)
1455 const char *e = NULL;
1458 var->name = (char *)p;
1465 /* If we find a comment or EOS, it's not a variable definition. */
1466 if (STOP_SET (c, MAP_COMMENT|MAP_NUL))
1471 /* This begins a variable expansion reference. Make sure we don't
1472 treat chars inside the reference as assignment tokens. */
1484 /* '$$' or '$X'. Either way, nothing special to do here. */
1487 /* P now points past the opening paren or brace.
1488 Count parens or braces until it is matched. */
1489 for (count = 1; *p != '\0'; ++p)
1491 if (*p == closeparen && --count == 0)
1502 /* If we find whitespace skip it, and remember we found it. */
1517 var->flavor = f_recursive;
1523 /* Match assignment variants (:=, +=, ?=, !=) */
1529 var->flavor = f_simple;
1532 var->flavor = f_append;
1535 var->flavor = f_conditional;
1538 var->flavor = f_shell;
1541 /* If we skipped whitespace, non-assignments means no var. */
1545 /* Might be assignment, or might be $= or #=. Check. */
1554 /* Check for POSIX ::= syntax */
1557 /* A colon other than :=/::= is not a variable defn. */
1558 if (*p != ':' || p[1] != '=')
1561 /* POSIX allows ::= to be the same as GNU make's := */
1562 var->flavor = f_simple;
1569 /* If we skipped whitespace, non-assignments means no var. */
1574 var->length = (unsigned int) (e - var->name);
1575 var->value = next_token (p);
1579 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1581 If LINE was recognized as a variable definition, a pointer to its 'struct
1582 variable' is returned. If LINE is not a variable definition, NULL is
1586 assign_variable_definition (struct variable *v, const char *line)
1590 if (!parse_variable_definition (line, v))
1593 /* Expand the name, so "$(foo)bar = baz" works. */
1594 name = alloca (v->length + 1);
1595 memcpy (name, v->name, v->length);
1596 name[v->length] = '\0';
1597 v->name = allocated_variable_expand (name);
1599 if (v->name[0] == '\0')
1600 O (fatal, &v->fileinfo, _("empty variable name"));
1605 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1607 ORIGIN may be o_file, o_override, o_env, o_env_override,
1608 or o_command specifying that the variable definition comes
1609 from a makefile, an override directive, the environment with
1610 or without the -e switch, or the command line.
1612 See the comments for assign_variable_definition().
1614 If LINE was recognized as a variable definition, a pointer to its 'struct
1615 variable' is returned. If LINE is not a variable definition, NULL is
1619 try_variable_definition (const floc *flocp, const char *line,
1620 enum variable_origin origin, int target_var)
1623 struct variable *vp;
1626 v.fileinfo = *flocp;
1628 v.fileinfo.filenm = 0;
1630 if (!assign_variable_definition (&v, line))
1633 vp = do_variable_definition (flocp, v.name, v.value,
1634 origin, v.flavor, target_var);
1641 /* Print information for variable V, prefixing it with PREFIX. */
1644 print_variable (const void *item, void *arg)
1646 const struct variable *v = item;
1647 const char *prefix = arg;
1653 origin = _("automatic");
1656 origin = _("default");
1659 origin = _("environment");
1662 origin = _("makefile");
1664 case o_env_override:
1665 origin = _("environment under -e");
1668 origin = _("command line");
1671 origin = _("'override' directive");
1677 fputs ("# ", stdout);
1678 fputs (origin, stdout);
1680 fputs (" private", stdout);
1681 if (v->fileinfo.filenm)
1682 printf (_(" (from '%s', line %lu)"),
1683 v->fileinfo.filenm, v->fileinfo.lineno + v->fileinfo.offset);
1685 fputs (prefix, stdout);
1687 /* Is this a 'define'? */
1688 if (v->recursive && strchr (v->value, '\n') != 0)
1689 printf ("define %s\n%s\nendef\n", v->name, v->value);
1694 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1696 /* Check if the value is just whitespace. */
1697 p = next_token (v->value);
1698 if (p != v->value && *p == '\0')
1699 /* All whitespace. */
1700 printf ("$(subst ,,%s)", v->value);
1701 else if (v->recursive)
1702 fputs (v->value, stdout);
1704 /* Double up dollar signs. */
1705 for (p = v->value; *p != '\0'; ++p)
1717 print_auto_variable (const void *item, void *arg)
1719 const struct variable *v = item;
1721 if (v->origin == o_automatic)
1722 print_variable (item, arg);
1727 print_noauto_variable (const void *item, void *arg)
1729 const struct variable *v = item;
1731 if (v->origin != o_automatic)
1732 print_variable (item, arg);
1736 /* Print all the variables in SET. PREFIX is printed before
1737 the actual variable definitions (everything else is comments). */
1740 print_variable_set (struct variable_set *set, const char *prefix, int pauto)
1742 hash_map_arg (&set->table, (pauto ? print_auto_variable : print_variable),
1745 fputs (_("# variable set hash-table stats:\n"), stdout);
1746 fputs ("# ", stdout);
1747 hash_print_stats (&set->table, stdout);
1748 putc ('\n', stdout);
1751 /* Print the data base of variables. */
1754 print_variable_data_base (void)
1756 puts (_("\n# Variables\n"));
1758 print_variable_set (&global_variable_set, "", 0);
1760 puts (_("\n# Pattern-specific Variable Values"));
1763 struct pattern_var *p;
1764 unsigned int rules = 0;
1766 for (p = pattern_vars; p != 0; p = p->next)
1769 printf ("\n%s :\n", p->target);
1770 print_variable (&p->variable, (void *)"# ");
1774 puts (_("\n# No pattern-specific variable values."));
1776 printf (_("\n# %u pattern-specific variable values"), rules);
1781 /* Print all the local variables of FILE. */
1784 print_file_variables (const struct file *file)
1786 if (file->variables != 0)
1787 print_variable_set (file->variables->set, "# ", 1);
1791 print_target_variables (const struct file *file)
1793 if (file->variables != 0)
1795 size_t l = strlen (file->name);
1796 char *t = alloca (l + 3);
1798 strcpy (t, file->name);
1803 hash_map_arg (&file->variables->set->table, print_noauto_variable, t);
1809 sync_Path_environment (void)
1811 char *path = allocated_variable_expand ("$(PATH)");
1812 static char *environ_path = NULL;
1817 /* If done this before, free the previous entry before allocating new one. */
1818 free (environ_path);
1820 /* Create something WINDOWS32 world can grok. */
1821 convert_Path_to_windows32 (path, ';');
1822 environ_path = xstrdup (concat (3, "PATH", "=", path));
1823 putenv (environ_path);