1 /* Internals of variables for GNU Make.
2 Copyright (C) 1988-2022 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 <https://www.gnu.org/licenses/>. */
30 #include "pathstuff.h"
34 /* Incremented every time we enter target_environment(). */
35 unsigned long long env_recursion = 0;
37 /* Incremented every time we add or remove a global variable. */
38 static unsigned long variable_changenum = 0;
40 /* Chain of all pattern-specific variables. */
42 static struct pattern_var *pattern_vars = NULL;
44 /* Pointer to the last struct in the pack of a specific size, from 1 to 255.*/
46 static struct pattern_var *last_pattern_vars[256];
48 /* Create a new pattern-specific variable struct. The new variable is
49 inserted into the PATTERN_VARS list in the shortest patterns first
50 order to support the shortest stem matching (the variables are
51 matched in the reverse order so the ones with the longest pattern
52 will be considered first). Variables with the same pattern length
53 are inserted in the definition order. */
56 create_pattern_var (const char *target, const char *suffix)
58 size_t len = strlen (target);
59 struct pattern_var *p = xcalloc (sizeof (struct pattern_var));
61 if (pattern_vars != 0)
63 if (len < 256 && last_pattern_vars[len] != 0)
65 p->next = last_pattern_vars[len]->next;
66 last_pattern_vars[len]->next = p;
70 /* Find the position where we can insert this variable. */
71 struct pattern_var **v;
73 for (v = &pattern_vars; ; v = &(*v)->next)
75 /* Insert at the end of the pack so that patterns with the
76 same length appear in the order they were defined .*/
78 if (*v == 0 || (*v)->len > len)
95 p->suffix = suffix + 1;
98 last_pattern_vars[len] = p;
103 /* Look up a target in the pattern-specific variable list. */
105 static struct pattern_var *
106 lookup_pattern_var (struct pattern_var *start, const char *target,
109 struct pattern_var *p;
111 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
116 if (p->len > targlen)
117 /* It can't possibly match. */
120 /* From the lengths of the filename and the pattern parts,
121 find the stem: the part of the filename that matches the %. */
122 stem = target + (p->suffix - p->target - 1);
123 stemlen = targlen - p->len + 1;
125 /* Compare the text in the pattern before the stem, if any. */
126 if (stem > target && !strneq (p->target, target, stem - target))
129 /* Compare the text in the pattern after the stem, if any.
130 We could test simply using streq, but this way we compare the
131 first two characters immediately. This saves time in the very
132 common case where the first character matches because it is a
134 if (*p->suffix == stem[stemlen]
135 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
142 /* Hash table of all global variable definitions. */
145 variable_hash_1 (const void *keyv)
147 struct variable const *key = (struct variable const *) keyv;
148 return_STRING_N_HASH_1 (key->name, key->length);
152 variable_hash_2 (const void *keyv)
154 struct variable const *key = (struct variable const *) keyv;
155 return_STRING_N_HASH_2 (key->name, key->length);
159 variable_hash_cmp (const void *xv, const void *yv)
161 struct variable const *x = (struct variable const *) xv;
162 struct variable const *y = (struct variable const *) yv;
163 int result = x->length - y->length;
166 return_STRING_N_COMPARE (x->name, y->name, x->length);
169 #ifndef VARIABLE_BUCKETS
170 #define VARIABLE_BUCKETS 523
172 #ifndef PERFILE_VARIABLE_BUCKETS
173 #define PERFILE_VARIABLE_BUCKETS 23
175 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
176 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
179 static struct variable_set global_variable_set;
180 static struct variable_set_list global_setlist
181 = { 0, &global_variable_set, 0 };
182 struct variable_set_list *current_variable_set_list = &global_setlist;
184 /* Implement variables. */
187 init_hash_global_variable_set (void)
189 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
190 variable_hash_1, variable_hash_2, variable_hash_cmp);
193 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
194 LENGTH is the length of NAME, which does not need to be null-terminated.
195 ORIGIN specifies the origin of the variable (makefile, command line
197 If RECURSIVE is nonzero a flag is set in the variable saying
198 that it should be recursively re-expanded. */
201 define_variable_in_set (const char *name, size_t length,
202 const char *value, enum variable_origin origin,
203 int recursive, struct variable_set *set,
207 struct variable **var_slot;
208 struct variable var_key;
211 set = &global_variable_set;
213 var_key.name = (char *) name;
214 var_key.length = (unsigned int) length;
215 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
219 /* VMS does not populate envp[] with DCL symbols and logical names which
220 historically are mapped to environment variables.
221 If the variable is not yet defined, then we need to check if getenv()
222 can find it. Do not do this for origin == o_env to avoid infinite
224 if (HASH_VACANT (v) && (origin != o_env))
226 struct variable * vms_variable;
227 char * vname = alloca (length + 1);
230 strncpy (vname, name, length);
231 vvalue = getenv(vname);
233 /* Values starting with '$' are probably foreign commands.
234 We want to treat them as Shell aliases and not look them up here */
235 if ((vvalue != NULL) && (vvalue[0] != '$'))
237 vms_variable = lookup_variable(name, length);
238 /* Refresh the slot */
239 var_slot = (struct variable **) hash_find_slot (&set->table,
246 if (env_overrides && origin == o_env)
247 origin = o_env_override;
249 if (! HASH_VACANT (v))
251 if (env_overrides && v->origin == o_env)
252 /* V came from in the environment. Since it was defined
253 before the switches were parsed, it wasn't affected by -e. */
254 v->origin = o_env_override;
256 /* A variable of this name is already defined.
257 If the old definition is from a stronger source
258 than this one, don't redefine it. */
259 if ((int) origin >= (int) v->origin)
262 v->value = xstrdup (value);
264 v->fileinfo = *flocp;
266 v->fileinfo.filenm = 0;
268 v->recursive = recursive;
273 /* Create a new variable definition and add it to the hash table. */
275 v = xcalloc (sizeof (struct variable));
276 v->name = xstrndup (name, length);
277 v->length = (unsigned int) length;
278 hash_insert_at (&set->table, v, var_slot);
279 if (set == &global_variable_set)
280 ++variable_changenum;
282 v->value = xstrdup (value);
284 v->fileinfo = *flocp;
286 v->recursive = recursive;
288 v->export = v_default;
290 /* Check the nul-terminated variable name. */
292 if (*name != '_' && (*name < 'A' || *name > 'Z')
293 && (*name < 'a' || *name > 'z'))
297 for (++name; *name != '\0'; ++name)
298 if (*name != '_' && (*name < 'a' || *name > 'z')
299 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
310 /* Undefine variable named NAME in SET. LENGTH is the length of NAME, which
311 does not need to be null-terminated. ORIGIN specifies the origin of the
312 variable (makefile, command line or environment). */
315 free_variable_name_and_value (const void *item)
317 struct variable *v = (struct variable *) item;
323 free_variable_set (struct variable_set_list *list)
325 hash_map (&list->set->table, free_variable_name_and_value);
326 hash_free (&list->set->table, 1);
332 undefine_variable_in_set (const char *name, size_t length,
333 enum variable_origin origin,
334 struct variable_set *set)
337 struct variable **var_slot;
338 struct variable var_key;
341 set = &global_variable_set;
343 var_key.name = (char *) name;
344 var_key.length = (unsigned int) length;
345 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
347 if (env_overrides && origin == o_env)
348 origin = o_env_override;
351 if (! HASH_VACANT (v))
353 if (env_overrides && v->origin == o_env)
354 /* V came from in the environment. Since it was defined
355 before the switches were parsed, it wasn't affected by -e. */
356 v->origin = o_env_override;
358 /* Undefine only if this undefinition is from an equal or stronger
359 source than the variable definition. */
360 if ((int) origin >= (int) v->origin)
362 hash_delete_at (&set->table, var_slot);
363 free_variable_name_and_value (v);
365 if (set == &global_variable_set)
366 ++variable_changenum;
371 /* If the variable passed in is "special", handle its special nature.
372 Currently there are two such variables, both used for introspection:
373 .VARIABLES expands to a list of all the variables defined in this instance
375 .TARGETS expands to a list of all the targets defined in this
377 Returns the variable reference passed in. */
379 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
381 static struct variable *
382 lookup_special_var (struct variable *var)
384 static unsigned long last_changenum = 0;
386 /* This one actually turns out to be very hard, due to the way the parser
387 records targets. The way it works is that target information is collected
388 internally until make knows the target is completely specified. Only when
389 it sees that some new construct (a new target or variable) is defined does
390 make know that the previous one is done. In short, this means that if
397 then $(TARGS) won't contain "all", because it's not until after the
398 variable is created that the previous target is completed.
400 Changing this would be a major pain. I think a less complex way to do it
401 would be to pre-define the target files as soon as the first line is
402 parsed, then come back and do the rest of the definition as now. That
403 would allow $(.TARGETS) to be correct without a major change to the way
406 if (streq (var->name, ".TARGETS"))
407 var->value = build_target_list (var->value);
411 if (variable_changenum != last_changenum && streq (var->name, ".VARIABLES"))
413 size_t max = EXPANSION_INCREMENT (strlen (var->value));
416 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
417 struct variable **end = &vp[global_variable_set.table.ht_size];
419 /* Make sure we have at least MAX bytes in the allocated buffer. */
420 var->value = xrealloc (var->value, max);
422 /* Walk through the hash of variables, constructing a list of names. */
425 for (; vp < end; ++vp)
426 if (!HASH_VACANT (*vp))
428 struct variable *v = *vp;
434 size_t off = p - var->value;
436 max += EXPANSION_INCREMENT (l + 1);
437 var->value = xrealloc (var->value, max);
438 p = &var->value[off];
441 p = mempcpy (p, v->name, l);
446 /* Remember the current variable change number. */
447 last_changenum = variable_changenum;
454 /* Lookup a variable whose name is a string starting at NAME
455 and with LENGTH chars. NAME need not be null-terminated.
456 Returns address of the 'struct variable' containing all info
457 on the variable, or nil if no such variable is defined. */
460 lookup_variable (const char *name, size_t length)
462 const struct variable_set_list *setlist;
463 struct variable var_key;
466 var_key.name = (char *) name;
467 var_key.length = (unsigned int) length;
469 for (setlist = current_variable_set_list;
470 setlist != 0; setlist = setlist->next)
472 const struct variable_set *set = setlist->set;
475 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
476 if (v && (!is_parent || !v->private_var))
477 return v->special ? lookup_special_var (v) : v;
479 is_parent |= setlist->next_is_parent;
483 /* VMS doesn't populate envp[] with DCL symbols and logical names, which
484 historically are mapped to environment variables and returned by
487 char *vname = alloca (length + 1);
489 strncpy (vname, name, length);
491 value = getenv (vname);
500 while ((sptr = strchr (sptr, '$')))
511 nvalue = alloca (strlen (value) + scnt + 1);
530 return define_variable (vname, length, nvalue, o_env, 1);
534 return define_variable (vname, length, value, o_env, 1);
542 /* Lookup a variable whose name is a string starting at NAME
543 and with LENGTH chars in set SET. NAME need not be null-terminated.
544 Returns address of the 'struct variable' containing all info
545 on the variable, or nil if no such variable is defined. */
548 lookup_variable_in_set (const char *name, size_t length,
549 const struct variable_set *set)
551 struct variable var_key;
553 var_key.name = (char *) name;
554 var_key.length = (unsigned int) length;
556 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
559 /* Initialize FILE's variable set list. If FILE already has a variable set
560 list, the topmost variable set is left intact, but the the rest of the
561 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
562 rule, then we will use the "root" double-colon target's variable set as the
563 parent of FILE's variable set.
565 If we're READING a makefile, don't do the pattern variable search now,
566 since the pattern variable might not have been defined yet. */
569 initialize_file_variables (struct file *file, int reading)
571 struct variable_set_list *l = file->variables;
575 l = (struct variable_set_list *)
576 xmalloc (sizeof (struct variable_set_list));
577 l->set = xmalloc (sizeof (struct variable_set));
578 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
579 variable_hash_1, variable_hash_2, variable_hash_cmp);
583 /* If this is a double-colon, then our "parent" is the "root" target for
584 this double-colon rule. Since that rule has the same name, parent,
585 etc. we can just use its variables as the "next" for ours. */
587 if (file->double_colon && file->double_colon != file)
589 initialize_file_variables (file->double_colon, reading);
590 l->next = file->double_colon->variables;
591 l->next_is_parent = 0;
595 if (file->parent == 0)
596 l->next = &global_setlist;
599 initialize_file_variables (file->parent, reading);
600 l->next = file->parent->variables;
602 l->next_is_parent = 1;
604 /* If we're not reading makefiles and we haven't looked yet, see if
605 we can find pattern variables for this target. */
607 if (!reading && !file->pat_searched)
609 struct pattern_var *p;
610 const size_t targlen = strlen (file->name);
612 p = lookup_pattern_var (0, file->name, targlen);
615 struct variable_set_list *global = current_variable_set_list;
617 /* We found at least one. Set up a new variable set to accumulate
618 all the pattern variables that match this target. */
620 file->pat_variables = create_new_variable_set ();
621 current_variable_set_list = file->pat_variables;
625 /* We found one, so insert it into the set. */
629 if (p->variable.flavor == f_simple)
631 v = define_variable_loc (
632 p->variable.name, strlen (p->variable.name),
633 p->variable.value, p->variable.origin,
634 0, &p->variable.fileinfo);
636 v->flavor = f_simple;
640 v = do_variable_definition (
641 &p->variable.fileinfo, p->variable.name,
642 p->variable.value, p->variable.origin,
643 p->variable.flavor, 1);
646 /* Also mark it as a per-target and copy export status. */
647 v->per_target = p->variable.per_target;
648 v->export = p->variable.export;
649 v->private_var = p->variable.private_var;
651 while ((p = lookup_pattern_var (p, file->name, targlen)) != 0);
653 current_variable_set_list = global;
655 file->pat_searched = 1;
658 /* If we have a pattern variable match, set it up. */
660 if (file->pat_variables != 0)
662 file->pat_variables->next = l->next;
663 file->pat_variables->next_is_parent = l->next_is_parent;
664 l->next = file->pat_variables;
665 l->next_is_parent = 0;
669 /* Pop the top set off the current variable set list,
670 and free all its storage. */
672 struct variable_set_list *
673 create_new_variable_set (void)
675 struct variable_set_list *setlist;
676 struct variable_set *set;
678 set = xmalloc (sizeof (struct variable_set));
679 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
680 variable_hash_1, variable_hash_2, variable_hash_cmp);
682 setlist = (struct variable_set_list *)
683 xmalloc (sizeof (struct variable_set_list));
685 setlist->next = current_variable_set_list;
686 setlist->next_is_parent = 0;
691 /* Create a new variable set and push it on the current setlist.
692 If we're pushing a global scope (that is, the current scope is the global
693 scope) then we need to "push" it the other way: file variable sets point
694 directly to the global_setlist so we need to replace that with the new one.
697 struct variable_set_list *
698 push_new_variable_scope (void)
700 current_variable_set_list = create_new_variable_set ();
701 if (current_variable_set_list->next == &global_setlist)
703 /* It was the global, so instead of new -> &global we want to replace
704 &global with the new one and have &global -> new, with current still
705 pointing to &global */
706 struct variable_set *set = current_variable_set_list->set;
707 current_variable_set_list->set = global_setlist.set;
708 global_setlist.set = set;
709 current_variable_set_list->next = global_setlist.next;
710 global_setlist.next = current_variable_set_list;
711 current_variable_set_list = &global_setlist;
713 return (current_variable_set_list);
717 pop_variable_scope (void)
719 struct variable_set_list *setlist;
720 struct variable_set *set;
722 /* Can't call this if there's no scope to pop! */
723 assert (current_variable_set_list->next != NULL);
725 if (current_variable_set_list != &global_setlist)
727 /* We're not pointing to the global setlist, so pop this one. */
728 setlist = current_variable_set_list;
730 current_variable_set_list = setlist->next;
734 /* This set is the one in the global_setlist, but there is another global
735 set beyond that. We want to copy that set to global_setlist, then
736 delete what used to be in global_setlist. */
737 setlist = global_setlist.next;
738 set = global_setlist.set;
739 global_setlist.set = setlist->set;
740 global_setlist.next = setlist->next;
741 global_setlist.next_is_parent = setlist->next_is_parent;
744 /* Free the one we no longer need. */
746 hash_map (&set->table, free_variable_name_and_value);
747 hash_free (&set->table, 1);
751 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
754 merge_variable_sets (struct variable_set *to_set,
755 struct variable_set *from_set)
757 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
758 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
760 int inc = to_set == &global_variable_set ? 1 : 0;
762 for ( ; from_var_slot < from_var_end; from_var_slot++)
763 if (! HASH_VACANT (*from_var_slot))
765 struct variable *from_var = *from_var_slot;
766 struct variable **to_var_slot
767 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
768 if (HASH_VACANT (*to_var_slot))
770 hash_insert_at (&to_set->table, from_var, to_var_slot);
771 variable_changenum += inc;
775 /* GKM FIXME: delete in from_set->table */
776 free (from_var->value);
782 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
785 merge_variable_set_lists (struct variable_set_list **setlist0,
786 struct variable_set_list *setlist1)
788 struct variable_set_list *to = *setlist0;
789 struct variable_set_list *last0 = 0;
791 /* If there's nothing to merge, stop now. */
792 if (!setlist1 || setlist1 == &global_setlist)
797 /* These loops rely on the fact that all setlists terminate with the
798 global setlist (before NULL). If not, arguably we SHOULD die. */
800 /* Make sure that setlist1 is not already a subset of setlist0. */
801 while (to != &global_setlist)
809 while (setlist1 != &global_setlist && to != &global_setlist)
811 struct variable_set_list *from = setlist1;
812 setlist1 = setlist1->next;
814 merge_variable_sets (to->set, from->set);
821 if (setlist1 != &global_setlist)
824 *setlist0 = setlist1;
826 last0->next = setlist1;
830 /* Define the automatic variables, and record the addresses
831 of their structures so we can change their values quickly. */
834 define_automatic_variables (void)
839 sprintf (buf, "%u", makelevel);
840 define_variable_cname (MAKELEVEL_NAME, buf, o_env, 0);
842 sprintf (buf, "%s%s%s",
844 (remote_description == 0 || remote_description[0] == '\0')
846 (remote_description == 0 || remote_description[0] == '\0')
847 ? "" : remote_description);
848 define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
849 define_variable_cname ("MAKE_HOST", make_host, o_default, 0);
852 /* Allow to specify a special shell just for Make,
853 and use $COMSPEC as the default $SHELL when appropriate. */
855 static char shell_str[] = "SHELL";
856 const int shlen = sizeof (shell_str) - 1;
857 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
858 struct variable *comp = lookup_variable ("COMSPEC", 7);
860 /* $(MAKESHELL) overrides $(SHELL) even if -e is in effect. */
862 (void) define_variable (shell_str, shlen,
863 mshp->value, o_env_override, 0);
866 /* $(COMSPEC) shouldn't override $(SHELL). */
867 struct variable *shp = lookup_variable (shell_str, shlen);
870 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
873 #elif defined(__EMX__)
875 static char shell_str[] = "SHELL";
876 const int shlen = sizeof (shell_str) - 1;
877 struct variable *shell = lookup_variable (shell_str, shlen);
878 struct variable *replace = lookup_variable ("MAKESHELL", 9);
880 /* if $MAKESHELL is defined in the environment assume o_env_override */
881 if (replace && *replace->value && replace->origin == o_env)
882 replace->origin = o_env_override;
884 /* if $MAKESHELL is not defined use $SHELL but only if the variable
885 did not come from the environment */
886 if (!replace || !*replace->value)
887 if (shell && *shell->value && (shell->origin == o_env
888 || shell->origin == o_env_override))
890 /* overwrite whatever we got from the environment */
892 shell->value = xstrdup (default_shell);
893 shell->origin = o_default;
896 /* Some people do not like cmd to be used as the default
897 if $SHELL is not defined in the Makefile.
898 With -DNO_CMD_DEFAULT you can turn off this behaviour */
899 # ifndef NO_CMD_DEFAULT
900 /* otherwise use $COMSPEC */
901 if (!replace || !*replace->value)
902 replace = lookup_variable ("COMSPEC", 7);
904 /* otherwise use $OS2_SHELL */
905 if (!replace || !*replace->value)
906 replace = lookup_variable ("OS2_SHELL", 9);
908 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
911 if (replace && *replace->value)
912 /* overwrite $SHELL */
913 (void) define_variable (shell_str, shlen, replace->value,
916 /* provide a definition if there is none */
917 (void) define_variable (shell_str, shlen, default_shell,
923 /* This won't override any definition, but it will provide one if there
925 v = define_variable_cname ("SHELL", default_shell, o_default, 0);
927 v->export = v_export; /* Export always SHELL. */
930 /* On MSDOS we do use SHELL from environment, since it isn't a standard
931 environment variable on MSDOS, so whoever sets it, does that on purpose.
932 On OS/2 we do not use SHELL from environment but we have already handled
933 that problem above. */
934 #if !defined(__MSDOS__) && !defined(__EMX__)
935 /* Don't let SHELL come from the environment. */
936 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
940 v->value = xstrdup (default_shell);
944 /* Make sure MAKEFILES gets exported if it is set. */
945 v = define_variable_cname ("MAKEFILES", "", o_default, 0);
948 /* Define the magic D and F variables in terms of
949 the automatic variables they are variations of. */
951 #if defined(__MSDOS__) || defined(WINDOWS32)
952 /* For consistency, remove the trailing backslash as well as slash. */
953 define_variable_cname ("@D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $@)))",
955 define_variable_cname ("%D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $%)))",
957 define_variable_cname ("*D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $*)))",
959 define_variable_cname ("<D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $<)))",
961 define_variable_cname ("?D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $?)))",
963 define_variable_cname ("^D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $^)))",
965 define_variable_cname ("+D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $+)))",
967 #else /* not __MSDOS__, not WINDOWS32 */
968 define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
969 define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
970 define_variable_cname ("*D", "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
971 define_variable_cname ("<D", "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
972 define_variable_cname ("?D", "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
973 define_variable_cname ("^D", "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
974 define_variable_cname ("+D", "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
976 define_variable_cname ("@F", "$(notdir $@)", o_automatic, 1);
977 define_variable_cname ("%F", "$(notdir $%)", o_automatic, 1);
978 define_variable_cname ("*F", "$(notdir $*)", o_automatic, 1);
979 define_variable_cname ("<F", "$(notdir $<)", o_automatic, 1);
980 define_variable_cname ("?F", "$(notdir $?)", o_automatic, 1);
981 define_variable_cname ("^F", "$(notdir $^)", o_automatic, 1);
982 define_variable_cname ("+F", "$(notdir $+)", o_automatic, 1);
985 int export_all_variables;
988 should_export (const struct variable *v)
999 if (v->origin == o_default)
1004 if (v->origin == o_default || v->origin == o_automatic)
1005 /* Only export default variables by explicit request. */
1008 /* The variable doesn't have a name that can be exported. */
1009 if (! v->exportable)
1012 if (! export_all_variables
1013 && v->origin != o_command
1014 && v->origin != o_env && v->origin != o_env_override)
1022 /* Create a new environment for FILE's commands.
1023 If FILE is nil, this is for the 'shell' function.
1024 The child's MAKELEVEL variable is incremented.
1025 If recursive is true then we're running a recursive make, else not. */
1028 target_environment (struct file *file, int recursive)
1030 struct variable_set_list *set_list;
1031 struct variable_set_list *s;
1032 struct hash_table table;
1033 struct variable **v_slot;
1034 struct variable **v_end;
1037 const char *invalid = NULL;
1038 /* If we got no value from the environment then never add the default. */
1039 int added_SHELL = shell_var.value == 0;
1040 int found_makelevel = 0;
1041 int found_mflags = 0;
1042 int found_makeflags = 0;
1044 /* If file is NULL we're creating the target environment for $(shell ...)
1045 Remember this so we can just ignore recursion. */
1049 /* We need to update makeflags if (a) we're not recurive, (b) jobserver_auth
1050 is enabled, and (c) we need to add invalidation. */
1051 if (!recursive && jobserver_auth)
1052 invalid = jobserver_get_invalid_auth ();
1055 set_list = file->variables;
1057 set_list = current_variable_set_list;
1059 hash_init (&table, VARIABLE_BUCKETS,
1060 variable_hash_1, variable_hash_2, variable_hash_cmp);
1062 /* Run through all the variable sets in the list, accumulating variables
1063 in TABLE. We go from most specific to least, so the first variable we
1064 encounter is the keeper. */
1065 for (s = set_list; s != 0; s = s->next)
1067 struct variable_set *set = s->set;
1068 int isglobal = set == &global_variable_set;
1070 v_slot = (struct variable **) set->table.ht_vec;
1071 v_end = v_slot + set->table.ht_size;
1072 for ( ; v_slot < v_end; v_slot++)
1073 if (! HASH_VACANT (*v_slot))
1075 struct variable **evslot;
1076 struct variable *v = *v_slot;
1078 evslot = (struct variable **) hash_find_slot (&table, v);
1080 if (HASH_VACANT (*evslot))
1082 /* If we're not global, or we are and should export, add it. */
1083 if (!isglobal || should_export (v))
1084 hash_insert_at (&table, v, evslot);
1086 else if ((*evslot)->export == v_default)
1087 /* We already have a variable but we don't know its status. */
1088 (*evslot)->export = v->export;
1092 result = result_0 = xmalloc ((table.ht_fill + 3) * sizeof (char *));
1094 v_slot = (struct variable **) table.ht_vec;
1095 v_end = v_slot + table.ht_size;
1096 for ( ; v_slot < v_end; v_slot++)
1097 if (! HASH_VACANT (*v_slot))
1099 struct variable *v = *v_slot;
1100 char *value = v->value;
1103 /* This might be here because it was a target-specific variable that
1104 we didn't know the status of when we added it. */
1105 if (! should_export (v))
1108 /* If V is recursively expanded and didn't come from the environment,
1109 expand its value. If it came from the environment, it should
1110 go back into the environment unchanged. */
1111 if (v->recursive && v->origin != o_env && v->origin != o_env_override)
1112 value = cp = recursively_expand_for_file (v, file);
1114 /* If this is the SHELL variable remember we already added it. */
1115 if (!added_SHELL && streq (v->name, "SHELL"))
1121 /* If this is MAKELEVEL, update it. */
1122 if (!found_makelevel && streq (v->name, MAKELEVEL_NAME))
1124 char val[INTSTR_LENGTH + 1];
1125 sprintf (val, "%u", makelevel + 1);
1127 value = cp = xstrdup (val);
1128 found_makelevel = 1;
1132 /* If we need to reset jobserver, check for MAKEFLAGS / MFLAGS. */
1135 if (!found_makeflags && streq (v->name, MAKEFLAGS_NAME))
1139 found_makeflags = 1;
1141 if (!strstr (value, " --" JOBSERVER_AUTH_OPT "="))
1144 /* The invalid option must come before variable overrides. */
1145 vars = strstr (value, " -- ");
1147 mf = xstrdup (concat (2, value, invalid));
1150 size_t lf = vars - value;
1151 size_t li = strlen (invalid);
1152 mf = xmalloc (strlen (value) + li + 1);
1153 strcpy (mempcpy (mempcpy (mf, value, lf), invalid, li),
1163 if (!found_mflags && streq (v->name, "MFLAGS"))
1168 if (!strstr (value, " --" JOBSERVER_AUTH_OPT "="))
1171 if (v->origin != o_env)
1173 mf = concat (2, value, invalid);
1175 value = cp = xstrdup (mf);
1176 if (found_makeflags)
1183 if (streq (v->name, "Path") || streq (v->name, "PATH"))
1186 cp = xstrdup (value);
1187 value = convert_Path_to_windows32 (cp, ';');
1193 *result++ = xstrdup (concat (3, v->name, "=", value));
1198 *result++ = xstrdup (concat (3, shell_var.name, "=", shell_var.value));
1200 if (!found_makelevel)
1202 char val[MAKELEVEL_LENGTH + 1 + INTSTR_LENGTH + 1];
1203 sprintf (val, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
1204 *result++ = xstrdup (val);
1209 hash_free (&table, 0);
1217 static struct variable *
1218 set_special_var (struct variable *var)
1220 if (streq (var->name, RECIPEPREFIX_NAME))
1222 /* The user is resetting the command introduction prefix. This has to
1223 happen immediately, so that subsequent rules are interpreted
1225 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1227 else if (streq (var->name, MAKEFLAGS_NAME))
1228 decode_env_switches (STRING_SIZE_TUPLE(MAKEFLAGS_NAME));
1233 /* Given a string, shell-execute it and return a malloc'ed string of the
1234 * result. This removes only ONE newline (if any) at the end, for maximum
1235 * compatibility with the *BSD makes. If it fails, returns NULL. */
1238 shell_result (const char *p)
1245 install_variable_buffer (&buf, &len);
1247 args[0] = (char *) p;
1249 variable_buffer_output (func_shell_base (variable_buffer, args, 0), "\0", 1);
1250 result = strdup (variable_buffer);
1252 restore_variable_buffer (buf, len);
1256 /* Given a variable, a value, and a flavor, define the variable.
1257 See the try_variable_definition() function for details on the parameters. */
1260 do_variable_definition (const floc *flocp, const char *varname,
1261 const char *value, enum variable_origin origin,
1262 enum variable_flavor flavor, int target_var)
1265 char *alloc_value = NULL;
1268 int conditional = 0;
1270 /* Calculate the variable's new value in VALUE. */
1275 /* A simple variable definition "var := value". Expand the value.
1276 We have to allocate memory since otherwise it'll clobber the
1277 variable buffer, and we may still need that if we're looking at a
1278 target-specific variable. */
1279 p = alloc_value = allocated_variable_expand (value);
1283 /* A POSIX "var :::= value" assignment. Expand the value, then it
1284 becomes a recursive variable. After expansion convert all '$'
1285 tokens to '$$' to resolve to '$' when recursively expanded. */
1286 char *t = allocated_variable_expand (value);
1287 char *np = alloc_value = xmalloc (strlen (t) * 2 + 1);
1289 while (p[0] != '\0')
1302 /* A shell definition "var != value". Expand value, pass it to
1303 the shell, and store the result in recursively-expanded var. */
1304 char *q = allocated_variable_expand (value);
1305 p = alloc_value = shell_result (q);
1307 flavor = f_recursive;
1311 /* A conditional variable definition "var ?= value".
1312 The value is set IFF the variable is not defined yet. */
1313 v = lookup_variable (varname, strlen (varname));
1318 flavor = f_recursive;
1321 /* A recursive variable definition "var = value".
1322 The value is used verbatim. */
1326 case f_append_value:
1328 /* If we have += but we're in a target variable context, we want to
1329 append only with other variables in the context of this target. */
1333 v = lookup_variable_in_set (varname, strlen (varname),
1334 current_variable_set_list->set);
1336 /* Don't append from the global set if a previous non-appending
1337 target-specific variable definition exists. */
1338 if (v && !v->append)
1342 v = lookup_variable (varname, strlen (varname));
1346 /* There was no old value.
1347 This becomes a normal recursive definition. */
1349 flavor = f_recursive;
1353 /* Paste the old and new values together in VALUE. */
1355 size_t oldlen, vallen;
1361 /* The previous definition of the variable was recursive.
1362 The new value is the unexpanded old and new values. */
1363 flavor = f_recursive;
1364 else if (flavor != f_append_value)
1365 /* The previous definition of the variable was simple.
1366 The new value comes from the old value, which was expanded
1367 when it was set; and from the expanded new value. Allocate
1368 memory for the expansion as we may still need the rest of the
1369 buffer if we're looking at a target-specific variable. */
1370 val = tp = allocated_variable_expand (val);
1372 /* If the new value is empty, nothing to do. */
1373 vallen = strlen (val);
1380 oldlen = strlen (v->value);
1381 p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1385 memcpy (alloc_value, v->value, oldlen);
1386 alloc_value[oldlen] = ' ';
1390 memcpy (&alloc_value[oldlen], val, vallen + 1);
1398 /* Should not be possible. */
1403 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1404 non-Unix systems don't conform to this default configuration (in
1405 fact, most of them don't even have '/bin'). On the other hand,
1406 $SHELL in the environment, if set, points to the real pathname of
1408 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1409 the Makefile override $SHELL from the environment. But first, we
1410 look for the basename of the shell in the directory where SHELL=
1411 points, and along the $PATH; if it is found in any of these places,
1412 we define $SHELL to be the actual pathname of the shell. Thus, if
1413 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1414 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1415 defining SHELL to be "d:/unix/bash.exe". */
1416 if ((origin == o_file || origin == o_override)
1417 && strcmp (varname, "SHELL") == 0)
1419 PATH_VAR (shellpath);
1420 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1422 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1423 if (__dosexec_find_on_path (p, NULL, shellpath))
1427 for (tp = shellpath; *tp; tp++)
1431 v = define_variable_loc (varname, strlen (varname),
1432 shellpath, origin, flavor == f_recursive,
1437 const char *shellbase, *bslash;
1438 struct variable *pathv = lookup_variable ("PATH", 4);
1443 shellbase = strrchr (p, '/');
1444 bslash = strrchr (p, '\\');
1445 if (!shellbase || bslash > shellbase)
1447 if (!shellbase && p[1] == ':')
1454 /* Search for the basename of the shell (with standard
1455 executable extensions) along the $PATH. */
1457 pathlen = strlen (pathv->value);
1458 path_string = xmalloc (5 + pathlen + 2 + 1);
1459 /* On MSDOS, current directory is considered as part of $PATH. */
1460 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1461 fake_env[0] = path_string;
1463 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1467 for (tp = shellpath; *tp; tp++)
1471 v = define_variable_loc (varname, strlen (varname),
1473 flavor == f_recursive, flocp);
1476 v = lookup_variable (varname, strlen (varname));
1482 #endif /* __MSDOS__ */
1484 if ((origin == o_file || origin == o_override || origin == o_command)
1485 && streq (varname, "SHELL"))
1487 extern const char *default_shell;
1489 /* Call shell locator function. If it returns TRUE, then
1490 set no_default_sh_exe to indicate sh was found and
1491 set new value for SHELL variable. */
1493 if (find_and_set_default_shell (p))
1495 v = define_variable_in_set (varname, strlen (varname), default_shell,
1496 origin, flavor == f_recursive,
1498 ? current_variable_set_list->set
1501 no_default_sh_exe = 0;
1505 char *tp = alloc_value;
1507 alloc_value = allocated_variable_expand (p);
1509 if (find_and_set_default_shell (alloc_value))
1511 v = define_variable_in_set (varname, strlen (varname), p,
1512 origin, flavor == f_recursive,
1514 ? current_variable_set_list->set
1517 no_default_sh_exe = 0;
1520 v = lookup_variable (varname, strlen (varname));
1528 /* If not $SHELL, or if $SHELL points to a program we didn't find,
1529 just process this variable "as usual". */
1533 /* If we are defining variables inside an $(eval ...), we might have a
1534 different variable context pushed, not the global context (maybe we're
1535 inside a $(call ...) or something. Since this function is only ever
1536 invoked in places where we want to define globally visible variables,
1537 make sure we define this variable in the global set. */
1539 v = define_variable_in_set (varname, strlen (varname), p, origin,
1540 flavor == f_recursive || flavor == f_expand,
1542 ? current_variable_set_list->set : NULL),
1545 v->conditional = conditional;
1549 return v->special ? set_special_var (v) : v;
1552 /* Parse P (a null-terminated string) as a variable definition.
1554 If it is not a variable definition, return NULL and the contents of *VAR
1555 are undefined, except NAME points to the first non-space character or EOS.
1557 If it is a variable definition, return a pointer to the char after the
1558 assignment token and set the following fields (only) of *VAR:
1559 name : name of the variable (ALWAYS SET) (NOT NUL-TERMINATED!)
1560 length : length of the variable name
1561 value : value of the variable (nul-terminated)
1562 flavor : flavor of the variable
1563 Other values in *VAR are unchanged.
1567 parse_variable_definition (const char *str, struct variable *var)
1569 const char *p = str;
1570 const char *end = NULL;
1573 var->name = (char *)p;
1576 /* Walk through STR until we find a valid assignment operator. Each time
1577 through this loop P points to the next character to consider. */
1582 /* If we find a comment or EOS, it's not a variable definition. */
1583 if (STOP_SET (c, MAP_COMMENT|MAP_NUL))
1588 /* Variable names can't contain spaces so if this is the second set
1589 of spaces we know it's not a variable assignment. */
1597 /* If we found = we're done! */
1602 var->flavor = f_recursive;
1611 /* We need to distinguish :=, ::=, and :::=, and : outside of an
1612 assignment (which means this is not a variable definition). */
1616 var->flavor = f_simple;
1624 var->flavor = f_simple;
1627 if (c == ':' && *p++ == '=')
1629 var->flavor = f_expand;
1636 /* See if it's one of the other two-byte operators. */
1642 var->flavor = f_append;
1645 var->flavor = f_conditional;
1648 var->flavor = f_shell;
1661 /* We found a char which is not part of an assignment operator.
1662 If we've seen whitespace, then we know this is not a variable
1663 assignment since variable names cannot contain whitespace. */
1669 /* Skip any variable reference, to ensure we don't treat chars
1670 inside the reference as assignment operators. */
1686 /* '$$' or '$X': skip it. */
1690 /* P now points past the opening paren or brace. Count parens or
1691 braces until we find the closing paren/brace. */
1692 for (count = 1; *p != '\0'; ++p)
1694 if (*p == closeparen && --count == 0)
1705 /* We found a valid variable assignment: END points to the char after the
1706 end of the variable name and P points to the char after the =. */
1707 var->length = (unsigned int) (end - var->name);
1708 var->value = next_token (p);
1712 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1714 If LINE was recognized as a variable definition, a pointer to its 'struct
1715 variable' is returned. If LINE is not a variable definition, NULL is
1719 assign_variable_definition (struct variable *v, const char *line)
1723 if (!parse_variable_definition (line, v))
1726 /* Expand the name, so "$(foo)bar = baz" works. */
1727 name = alloca (v->length + 1);
1728 memcpy (name, v->name, v->length);
1729 name[v->length] = '\0';
1730 v->name = allocated_variable_expand (name);
1732 if (v->name[0] == '\0')
1733 O (fatal, &v->fileinfo, _("empty variable name"));
1738 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1740 ORIGIN may be o_file, o_override, o_env, o_env_override,
1741 or o_command specifying that the variable definition comes
1742 from a makefile, an override directive, the environment with
1743 or without the -e switch, or the command line.
1745 See the comments for assign_variable_definition().
1747 If LINE was recognized as a variable definition, a pointer to its 'struct
1748 variable' is returned. If LINE is not a variable definition, NULL is
1752 try_variable_definition (const floc *flocp, const char *line,
1753 enum variable_origin origin, int target_var)
1756 struct variable *vp;
1759 v.fileinfo = *flocp;
1761 v.fileinfo.filenm = 0;
1763 if (!assign_variable_definition (&v, line))
1766 vp = do_variable_definition (flocp, v.name, v.value,
1767 origin, v.flavor, target_var);
1774 /* Print information for variable V, prefixing it with PREFIX. */
1777 print_variable (const void *item, void *arg)
1779 const struct variable *v = item;
1780 const char *prefix = arg;
1786 origin = _("automatic");
1789 origin = _("default");
1792 origin = _("environment");
1795 origin = _("makefile");
1797 case o_env_override:
1798 origin = _("environment under -e");
1801 origin = _("command line");
1804 origin = _("'override' directive");
1809 fputs ("# ", stdout);
1810 fputs (origin, stdout);
1812 fputs (" private", stdout);
1813 if (v->fileinfo.filenm)
1814 printf (_(" (from '%s', line %lu)"),
1815 v->fileinfo.filenm, v->fileinfo.lineno + v->fileinfo.offset);
1817 fputs (prefix, stdout);
1819 /* Is this a 'define'? */
1820 if (v->recursive && strchr (v->value, '\n') != 0)
1821 printf ("define %s\n%s\nendef\n", v->name, v->value);
1826 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1828 /* Check if the value is just whitespace. */
1829 p = next_token (v->value);
1830 if (p != v->value && *p == '\0')
1831 /* All whitespace. */
1832 printf ("$(subst ,,%s)", v->value);
1833 else if (v->recursive)
1834 fputs (v->value, stdout);
1836 /* Double up dollar signs. */
1837 for (p = v->value; *p != '\0'; ++p)
1849 print_auto_variable (const void *item, void *arg)
1851 const struct variable *v = item;
1853 if (v->origin == o_automatic)
1854 print_variable (item, arg);
1859 print_noauto_variable (const void *item, void *arg)
1861 const struct variable *v = item;
1863 if (v->origin != o_automatic)
1864 print_variable (item, arg);
1868 /* Print all the variables in SET. PREFIX is printed before
1869 the actual variable definitions (everything else is comments). */
1872 print_variable_set (struct variable_set *set, const char *prefix, int pauto)
1874 hash_map_arg (&set->table, (pauto ? print_auto_variable : print_variable),
1877 fputs (_("# variable set hash-table stats:\n"), stdout);
1878 fputs ("# ", stdout);
1879 hash_print_stats (&set->table, stdout);
1880 putc ('\n', stdout);
1883 /* Print the data base of variables. */
1886 print_variable_data_base (void)
1888 puts (_("\n# Variables\n"));
1890 print_variable_set (&global_variable_set, "", 0);
1892 puts (_("\n# Pattern-specific Variable Values"));
1895 struct pattern_var *p;
1896 unsigned int rules = 0;
1898 for (p = pattern_vars; p != 0; p = p->next)
1901 printf ("\n%s :\n", p->target);
1902 print_variable (&p->variable, (void *)"# ");
1906 puts (_("\n# No pattern-specific variable values."));
1908 printf (_("\n# %u pattern-specific variable values"), rules);
1913 /* Print all the local variables of FILE. */
1916 print_file_variables (const struct file *file)
1918 if (file->variables != 0)
1919 print_variable_set (file->variables->set, "# ", 1);
1923 print_target_variables (const struct file *file)
1925 if (file->variables != 0)
1927 size_t l = strlen (file->name);
1928 char *t = alloca (l + 3);
1930 memcpy (t, file->name, l);
1935 hash_map_arg (&file->variables->set->table, print_noauto_variable, t);
1941 sync_Path_environment ()
1943 static char *environ_path = NULL;
1944 char *oldpath = environ_path;
1945 char *path = allocated_variable_expand ("PATH=$(PATH)");
1950 /* Convert PATH into something WINDOWS32 world can grok. */
1951 convert_Path_to_windows32 (path, ';');
1953 environ_path = path;
1954 putenv (environ_path);