1 /* Internals of variables for GNU Make.
2 Copyright (C) 1988-2013 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 /* Chain of all pattern-specific variables. */
34 static struct pattern_var *pattern_vars;
36 /* Pointer to the last struct in the pack of a specific size, from 1 to 255.*/
38 static struct pattern_var *last_pattern_vars[256];
40 /* Create a new pattern-specific variable struct. The new variable is
41 inserted into the PATTERN_VARS list in the shortest patterns first
42 order to support the shortest stem matching (the variables are
43 matched in the reverse order so the ones with the longest pattern
44 will be considered first). Variables with the same pattern length
45 are inserted in the definition order. */
48 create_pattern_var (const char *target, const char *suffix)
50 register unsigned int len = strlen (target);
51 register struct pattern_var *p = xmalloc (sizeof (struct pattern_var));
53 if (pattern_vars != 0)
55 if (len < 256 && last_pattern_vars[len] != 0)
57 p->next = last_pattern_vars[len]->next;
58 last_pattern_vars[len]->next = p;
62 /* Find the position where we can insert this variable. */
63 register struct pattern_var **v;
65 for (v = &pattern_vars; ; v = &(*v)->next)
67 /* Insert at the end of the pack so that patterns with the
68 same length appear in the order they were defined .*/
70 if (*v == 0 || (*v)->len > len)
87 p->suffix = suffix + 1;
90 last_pattern_vars[len] = p;
95 /* Look up a target in the pattern-specific variable list. */
97 static struct pattern_var *
98 lookup_pattern_var (struct pattern_var *start, const char *target)
100 struct pattern_var *p;
101 unsigned int targlen = strlen (target);
103 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
106 unsigned int stemlen;
108 if (p->len > targlen)
109 /* It can't possibly match. */
112 /* From the lengths of the filename and the pattern parts,
113 find the stem: the part of the filename that matches the %. */
114 stem = target + (p->suffix - p->target - 1);
115 stemlen = targlen - p->len + 1;
117 /* Compare the text in the pattern before the stem, if any. */
118 if (stem > target && !strneq (p->target, target, stem - target))
121 /* Compare the text in the pattern after the stem, if any.
122 We could test simply using streq, but this way we compare the
123 first two characters immediately. This saves time in the very
124 common case where the first character matches because it is a
126 if (*p->suffix == stem[stemlen]
127 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
134 /* Hash table of all global variable definitions. */
137 variable_hash_1 (const void *keyv)
139 struct variable const *key = (struct variable const *) keyv;
140 return_STRING_N_HASH_1 (key->name, key->length);
144 variable_hash_2 (const void *keyv)
146 struct variable const *key = (struct variable const *) keyv;
147 return_STRING_N_HASH_2 (key->name, key->length);
151 variable_hash_cmp (const void *xv, const void *yv)
153 struct variable const *x = (struct variable const *) xv;
154 struct variable const *y = (struct variable const *) yv;
155 int result = x->length - y->length;
158 return_STRING_N_COMPARE (x->name, y->name, x->length);
161 #ifndef VARIABLE_BUCKETS
162 #define VARIABLE_BUCKETS 523
164 #ifndef PERFILE_VARIABLE_BUCKETS
165 #define PERFILE_VARIABLE_BUCKETS 23
167 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
168 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
171 static struct variable_set global_variable_set;
172 static struct variable_set_list global_setlist
173 = { 0, &global_variable_set, 0 };
174 struct variable_set_list *current_variable_set_list = &global_setlist;
176 /* Implement variables. */
179 init_hash_global_variable_set (void)
181 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
182 variable_hash_1, variable_hash_2, variable_hash_cmp);
185 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
186 LENGTH is the length of NAME, which does not need to be null-terminated.
187 ORIGIN specifies the origin of the variable (makefile, command line
189 If RECURSIVE is nonzero a flag is set in the variable saying
190 that it should be recursively re-expanded. */
193 define_variable_in_set (const char *name, unsigned int length,
194 const char *value, enum variable_origin origin,
195 int recursive, struct variable_set *set,
196 const gmk_floc *flocp)
199 struct variable **var_slot;
200 struct variable var_key;
203 set = &global_variable_set;
205 var_key.name = (char *) name;
206 var_key.length = length;
207 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
209 if (env_overrides && origin == o_env)
210 origin = o_env_override;
213 if (! HASH_VACANT (v))
215 if (env_overrides && v->origin == o_env)
216 /* V came from in the environment. Since it was defined
217 before the switches were parsed, it wasn't affected by -e. */
218 v->origin = o_env_override;
220 /* A variable of this name is already defined.
221 If the old definition is from a stronger source
222 than this one, don't redefine it. */
223 if ((int) origin >= (int) v->origin)
227 v->value = xstrdup (value);
229 v->fileinfo = *flocp;
231 v->fileinfo.filenm = 0;
233 v->recursive = recursive;
238 /* Create a new variable definition and add it to the hash table. */
240 v = xmalloc (sizeof (struct variable));
241 v->name = xstrndup (name, length);
243 hash_insert_at (&set->table, v, var_slot);
244 v->value = xstrdup (value);
246 v->fileinfo = *flocp;
248 v->fileinfo.filenm = 0;
250 v->recursive = recursive;
257 v->export = v_default;
260 if (*name != '_' && (*name < 'A' || *name > 'Z')
261 && (*name < 'a' || *name > 'z'))
265 for (++name; *name != '\0'; ++name)
266 if (*name != '_' && (*name < 'a' || *name > 'z')
267 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
278 /* Undefine variable named NAME in SET. LENGTH is the length of NAME, which
279 does not need to be null-terminated. ORIGIN specifies the origin of the
280 variable (makefile, command line or environment). */
283 free_variable_name_and_value (const void *item)
285 struct variable *v = (struct variable *) item;
291 free_variable_set (struct variable_set_list *list)
293 hash_map (&list->set->table, free_variable_name_and_value);
294 hash_free (&list->set->table, 1);
300 undefine_variable_in_set (const char *name, unsigned int length,
301 enum variable_origin origin,
302 struct variable_set *set)
305 struct variable **var_slot;
306 struct variable var_key;
309 set = &global_variable_set;
311 var_key.name = (char *) name;
312 var_key.length = length;
313 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
315 if (env_overrides && origin == o_env)
316 origin = o_env_override;
319 if (! HASH_VACANT (v))
321 if (env_overrides && v->origin == o_env)
322 /* V came from in the environment. Since it was defined
323 before the switches were parsed, it wasn't affected by -e. */
324 v->origin = o_env_override;
326 /* If the definition is from a stronger source than this one, don't
328 if ((int) origin >= (int) v->origin)
330 hash_delete_at (&set->table, var_slot);
331 free_variable_name_and_value (v);
336 /* If the variable passed in is "special", handle its special nature.
337 Currently there are two such variables, both used for introspection:
338 .VARIABLES expands to a list of all the variables defined in this instance
340 .TARGETS expands to a list of all the targets defined in this
342 Returns the variable reference passed in. */
344 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
346 static struct variable *
347 lookup_special_var (struct variable *var)
349 static unsigned long last_var_count = 0;
352 /* This one actually turns out to be very hard, due to the way the parser
353 records targets. The way it works is that target information is collected
354 internally until make knows the target is completely specified. It unitl
355 it sees that some new construct (a new target or variable) is defined that
356 it knows the previous one is done. In short, this means that if you do
363 then $(TARGS) won't contain "all", because it's not until after the
364 variable is created that the previous target is completed.
366 Changing this would be a major pain. I think a less complex way to do it
367 would be to pre-define the target files as soon as the first line is
368 parsed, then come back and do the rest of the definition as now. That
369 would allow $(.TARGETS) to be correct without a major change to the way
372 if (streq (var->name, ".TARGETS"))
373 var->value = build_target_list (var->value);
377 if (streq (var->name, ".VARIABLES")
378 && global_variable_set.table.ht_fill != last_var_count)
380 unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
383 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
384 struct variable **end = &vp[global_variable_set.table.ht_size];
386 /* Make sure we have at least MAX bytes in the allocated buffer. */
387 var->value = xrealloc (var->value, max);
389 /* Walk through the hash of variables, constructing a list of names. */
392 for (; vp < end; ++vp)
393 if (!HASH_VACANT (*vp))
395 struct variable *v = *vp;
401 unsigned long off = p - var->value;
403 max += EXPANSION_INCREMENT (l + 1);
404 var->value = xrealloc (var->value, max);
405 p = &var->value[off];
408 memcpy (p, v->name, l);
414 /* Remember how many variables are in our current count. Since we never
415 remove variables from the list, this is a reliable way to know whether
416 the list is up to date or needs to be recomputed. */
418 last_var_count = global_variable_set.table.ht_fill;
425 /* Lookup a variable whose name is a string starting at NAME
426 and with LENGTH chars. NAME need not be null-terminated.
427 Returns address of the 'struct variable' containing all info
428 on the variable, or nil if no such variable is defined. */
431 lookup_variable (const char *name, unsigned int length)
433 const struct variable_set_list *setlist;
434 struct variable var_key;
437 var_key.name = (char *) name;
438 var_key.length = length;
440 for (setlist = current_variable_set_list;
441 setlist != 0; setlist = setlist->next)
443 const struct variable_set *set = setlist->set;
446 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
447 if (v && (!is_parent || !v->private_var))
448 return v->special ? lookup_special_var (v) : v;
450 is_parent |= setlist->next_is_parent;
454 /* since we don't read envp[] on startup, try to get the
455 variable via getenv() here. */
457 char *vname = alloca (length + 1);
459 strncpy (vname, name, length);
461 value = getenv (vname);
470 while ((sptr = strchr (sptr, '$')))
481 nvalue = alloca (strlen (value) + scnt + 1);
500 return define_variable (vname, length, nvalue, o_env, 1);
504 return define_variable (vname, length, value, o_env, 1);
512 /* Lookup a variable whose name is a string starting at NAME
513 and with LENGTH chars in set SET. NAME need not be null-terminated.
514 Returns address of the 'struct variable' containing all info
515 on the variable, or nil if no such variable is defined. */
518 lookup_variable_in_set (const char *name, unsigned int length,
519 const struct variable_set *set)
521 struct variable var_key;
523 var_key.name = (char *) name;
524 var_key.length = length;
526 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
529 /* Initialize FILE's variable set list. If FILE already has a variable set
530 list, the topmost variable set is left intact, but the the rest of the
531 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
532 rule, then we will use the "root" double-colon target's variable set as the
533 parent of FILE's variable set.
535 If we're READING a makefile, don't do the pattern variable search now,
536 since the pattern variable might not have been defined yet. */
539 initialize_file_variables (struct file *file, int reading)
541 struct variable_set_list *l = file->variables;
545 l = (struct variable_set_list *)
546 xmalloc (sizeof (struct variable_set_list));
547 l->set = xmalloc (sizeof (struct variable_set));
548 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
549 variable_hash_1, variable_hash_2, variable_hash_cmp);
553 /* If this is a double-colon, then our "parent" is the "root" target for
554 this double-colon rule. Since that rule has the same name, parent,
555 etc. we can just use its variables as the "next" for ours. */
557 if (file->double_colon && file->double_colon != file)
559 initialize_file_variables (file->double_colon, reading);
560 l->next = file->double_colon->variables;
561 l->next_is_parent = 0;
565 if (file->parent == 0)
566 l->next = &global_setlist;
569 initialize_file_variables (file->parent, reading);
570 l->next = file->parent->variables;
572 l->next_is_parent = 1;
574 /* If we're not reading makefiles and we haven't looked yet, see if
575 we can find pattern variables for this target. */
577 if (!reading && !file->pat_searched)
579 struct pattern_var *p;
581 p = lookup_pattern_var (0, file->name);
584 struct variable_set_list *global = current_variable_set_list;
586 /* We found at least one. Set up a new variable set to accumulate
587 all the pattern variables that match this target. */
589 file->pat_variables = create_new_variable_set ();
590 current_variable_set_list = file->pat_variables;
594 /* We found one, so insert it into the set. */
598 if (p->variable.flavor == f_simple)
600 v = define_variable_loc (
601 p->variable.name, strlen (p->variable.name),
602 p->variable.value, p->variable.origin,
603 0, &p->variable.fileinfo);
605 v->flavor = f_simple;
609 v = do_variable_definition (
610 &p->variable.fileinfo, p->variable.name,
611 p->variable.value, p->variable.origin,
612 p->variable.flavor, 1);
615 /* Also mark it as a per-target and copy export status. */
616 v->per_target = p->variable.per_target;
617 v->export = p->variable.export;
618 v->private_var = p->variable.private_var;
620 while ((p = lookup_pattern_var (p, file->name)) != 0);
622 current_variable_set_list = global;
624 file->pat_searched = 1;
627 /* If we have a pattern variable match, set it up. */
629 if (file->pat_variables != 0)
631 file->pat_variables->next = l->next;
632 file->pat_variables->next_is_parent = l->next_is_parent;
633 l->next = file->pat_variables;
634 l->next_is_parent = 0;
638 /* Pop the top set off the current variable set list,
639 and free all its storage. */
641 struct variable_set_list *
642 create_new_variable_set (void)
644 register struct variable_set_list *setlist;
645 register struct variable_set *set;
647 set = xmalloc (sizeof (struct variable_set));
648 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
649 variable_hash_1, variable_hash_2, variable_hash_cmp);
651 setlist = (struct variable_set_list *)
652 xmalloc (sizeof (struct variable_set_list));
654 setlist->next = current_variable_set_list;
655 setlist->next_is_parent = 0;
660 /* Create a new variable set and push it on the current setlist.
661 If we're pushing a global scope (that is, the current scope is the global
662 scope) then we need to "push" it the other way: file variable sets point
663 directly to the global_setlist so we need to replace that with the new one.
666 struct variable_set_list *
667 push_new_variable_scope (void)
669 current_variable_set_list = create_new_variable_set ();
670 if (current_variable_set_list->next == &global_setlist)
672 /* It was the global, so instead of new -> &global we want to replace
673 &global with the new one and have &global -> new, with current still
674 pointing to &global */
675 struct variable_set *set = current_variable_set_list->set;
676 current_variable_set_list->set = global_setlist.set;
677 global_setlist.set = set;
678 current_variable_set_list->next = global_setlist.next;
679 global_setlist.next = current_variable_set_list;
680 current_variable_set_list = &global_setlist;
682 return (current_variable_set_list);
686 pop_variable_scope (void)
688 struct variable_set_list *setlist;
689 struct variable_set *set;
691 /* Can't call this if there's no scope to pop! */
692 assert (current_variable_set_list->next != NULL);
694 if (current_variable_set_list != &global_setlist)
696 /* We're not pointing to the global setlist, so pop this one. */
697 setlist = current_variable_set_list;
699 current_variable_set_list = setlist->next;
703 /* This set is the one in the global_setlist, but there is another global
704 set beyond that. We want to copy that set to global_setlist, then
705 delete what used to be in global_setlist. */
706 setlist = global_setlist.next;
707 set = global_setlist.set;
708 global_setlist.set = setlist->set;
709 global_setlist.next = setlist->next;
710 global_setlist.next_is_parent = setlist->next_is_parent;
713 /* Free the one we no longer need. */
715 hash_map (&set->table, free_variable_name_and_value);
716 hash_free (&set->table, 1);
720 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
723 merge_variable_sets (struct variable_set *to_set,
724 struct variable_set *from_set)
726 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
727 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
729 for ( ; from_var_slot < from_var_end; from_var_slot++)
730 if (! HASH_VACANT (*from_var_slot))
732 struct variable *from_var = *from_var_slot;
733 struct variable **to_var_slot
734 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
735 if (HASH_VACANT (*to_var_slot))
736 hash_insert_at (&to_set->table, from_var, to_var_slot);
739 /* GKM FIXME: delete in from_set->table */
740 free (from_var->value);
746 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
749 merge_variable_set_lists (struct variable_set_list **setlist0,
750 struct variable_set_list *setlist1)
752 struct variable_set_list *to = *setlist0;
753 struct variable_set_list *last0 = 0;
755 /* If there's nothing to merge, stop now. */
759 /* This loop relies on the fact that all setlists terminate with the global
760 setlist (before NULL). If that's not true, arguably we SHOULD die. */
762 while (setlist1 != &global_setlist && to != &global_setlist)
764 struct variable_set_list *from = setlist1;
765 setlist1 = setlist1->next;
767 merge_variable_sets (to->set, from->set);
773 if (setlist1 != &global_setlist)
776 *setlist0 = setlist1;
778 last0->next = setlist1;
782 /* Define the automatic variables, and record the addresses
783 of their structures so we can change their values quickly. */
786 define_automatic_variables (void)
788 #if defined(WINDOWS32) || defined(__EMX__)
789 extern char* default_shell;
791 extern char default_shell[];
793 register struct variable *v;
796 sprintf (buf, "%u", makelevel);
797 define_variable_cname (MAKELEVEL_NAME, buf, o_env, 0);
799 sprintf (buf, "%s%s%s",
801 (remote_description == 0 || remote_description[0] == '\0')
803 (remote_description == 0 || remote_description[0] == '\0')
804 ? "" : remote_description);
805 define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
806 define_variable_cname ("MAKE_HOST", make_host, o_default, 0);
809 /* Allow to specify a special shell just for Make,
810 and use $COMSPEC as the default $SHELL when appropriate. */
812 static char shell_str[] = "SHELL";
813 const int shlen = sizeof (shell_str) - 1;
814 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
815 struct variable *comp = lookup_variable ("COMSPEC", 7);
817 /* $(MAKESHELL) overrides $(SHELL) even if -e is in effect. */
819 (void) define_variable (shell_str, shlen,
820 mshp->value, o_env_override, 0);
823 /* $(COMSPEC) shouldn't override $(SHELL). */
824 struct variable *shp = lookup_variable (shell_str, shlen);
827 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
830 #elif defined(__EMX__)
832 static char shell_str[] = "SHELL";
833 const int shlen = sizeof (shell_str) - 1;
834 struct variable *shell = lookup_variable (shell_str, shlen);
835 struct variable *replace = lookup_variable ("MAKESHELL", 9);
837 /* if $MAKESHELL is defined in the environment assume o_env_override */
838 if (replace && *replace->value && replace->origin == o_env)
839 replace->origin = o_env_override;
841 /* if $MAKESHELL is not defined use $SHELL but only if the variable
842 did not come from the environment */
843 if (!replace || !*replace->value)
844 if (shell && *shell->value && (shell->origin == o_env
845 || shell->origin == o_env_override))
847 /* overwrite whatever we got from the environment */
849 shell->value = xstrdup (default_shell);
850 shell->origin = o_default;
853 /* Some people do not like cmd to be used as the default
854 if $SHELL is not defined in the Makefile.
855 With -DNO_CMD_DEFAULT you can turn off this behaviour */
856 # ifndef NO_CMD_DEFAULT
857 /* otherwise use $COMSPEC */
858 if (!replace || !*replace->value)
859 replace = lookup_variable ("COMSPEC", 7);
861 /* otherwise use $OS2_SHELL */
862 if (!replace || !*replace->value)
863 replace = lookup_variable ("OS2_SHELL", 9);
865 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
868 if (replace && *replace->value)
869 /* overwrite $SHELL */
870 (void) define_variable (shell_str, shlen, replace->value,
873 /* provide a definition if there is none */
874 (void) define_variable (shell_str, shlen, default_shell,
880 /* This won't override any definition, but it will provide one if there
882 v = define_variable_cname ("SHELL", default_shell, o_default, 0);
884 v->export = v_export; /* Export always SHELL. */
887 /* On MSDOS we do use SHELL from environment, since it isn't a standard
888 environment variable on MSDOS, so whoever sets it, does that on purpose.
889 On OS/2 we do not use SHELL from environment but we have already handled
890 that problem above. */
891 #if !defined(__MSDOS__) && !defined(__EMX__)
892 /* Don't let SHELL come from the environment. */
893 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
897 v->value = xstrdup (default_shell);
901 /* Make sure MAKEFILES gets exported if it is set. */
902 v = define_variable_cname ("MAKEFILES", "", o_default, 0);
905 /* Define the magic D and F variables in terms of
906 the automatic variables they are variations of. */
909 define_variable_cname ("@D", "$(dir $@)", o_automatic, 1);
910 define_variable_cname ("%D", "$(dir $%)", o_automatic, 1);
911 define_variable_cname ("*D", "$(dir $*)", o_automatic, 1);
912 define_variable_cname ("<D", "$(dir $<)", o_automatic, 1);
913 define_variable_cname ("?D", "$(dir $?)", o_automatic, 1);
914 define_variable_cname ("^D", "$(dir $^)", o_automatic, 1);
915 define_variable_cname ("+D", "$(dir $+)", o_automatic, 1);
916 #elif defined(__MSDOS__) || defined(WINDOWS32)
917 /* For consistency, remove the trailing backslash as well as slash. */
918 define_variable_cname ("@D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $@)))",
920 define_variable_cname ("%D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $%)))",
922 define_variable_cname ("*D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $*)))",
924 define_variable_cname ("<D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $<)))",
926 define_variable_cname ("?D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $?)))",
928 define_variable_cname ("^D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $^)))",
930 define_variable_cname ("+D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $+)))",
932 #else /* not __MSDOS__, not WINDOWS32 */
933 define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
934 define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
935 define_variable_cname ("*D", "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
936 define_variable_cname ("<D", "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
937 define_variable_cname ("?D", "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
938 define_variable_cname ("^D", "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
939 define_variable_cname ("+D", "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
941 define_variable_cname ("@F", "$(notdir $@)", o_automatic, 1);
942 define_variable_cname ("%F", "$(notdir $%)", o_automatic, 1);
943 define_variable_cname ("*F", "$(notdir $*)", o_automatic, 1);
944 define_variable_cname ("<F", "$(notdir $<)", o_automatic, 1);
945 define_variable_cname ("?F", "$(notdir $?)", o_automatic, 1);
946 define_variable_cname ("^F", "$(notdir $^)", o_automatic, 1);
947 define_variable_cname ("+F", "$(notdir $+)", o_automatic, 1);
950 int export_all_variables;
952 /* Create a new environment for FILE's commands.
953 If FILE is nil, this is for the 'shell' function.
954 The child's MAKELEVEL variable is incremented. */
957 target_environment (struct file *file)
959 struct variable_set_list *set_list;
960 register struct variable_set_list *s;
961 struct hash_table table;
962 struct variable **v_slot;
963 struct variable **v_end;
964 struct variable makelevel_key;
969 set_list = current_variable_set_list;
971 set_list = file->variables;
973 hash_init (&table, VARIABLE_BUCKETS,
974 variable_hash_1, variable_hash_2, variable_hash_cmp);
976 /* Run through all the variable sets in the list,
977 accumulating variables in TABLE. */
978 for (s = set_list; s != 0; s = s->next)
980 struct variable_set *set = s->set;
981 v_slot = (struct variable **) set->table.ht_vec;
982 v_end = v_slot + set->table.ht_size;
983 for ( ; v_slot < v_end; v_slot++)
984 if (! HASH_VACANT (*v_slot))
986 struct variable **new_slot;
987 struct variable *v = *v_slot;
989 /* If this is a per-target variable and it hasn't been touched
990 already then look up the global version and take its export
992 if (v->per_target && v->export == v_default)
996 gv = lookup_variable_in_set (v->name, strlen (v->name),
997 &global_variable_set);
999 v->export = gv->export;
1005 if (v->origin == o_default || v->origin == o_automatic)
1006 /* Only export default variables by explicit request. */
1009 /* The variable doesn't have a name that can be exported. */
1010 if (! v->exportable)
1013 if (! export_all_variables
1014 && v->origin != o_command
1015 && v->origin != o_env && v->origin != o_env_override)
1024 /* If this is the SHELL variable and it's not exported,
1025 then add the value from our original environment, if
1026 the original environment defined a value for SHELL. */
1027 extern struct variable shell_var;
1028 if (streq (v->name, "SHELL") && shell_var.value)
1037 if (v->origin == o_default)
1042 new_slot = (struct variable **) hash_find_slot (&table, v);
1043 if (HASH_VACANT (*new_slot))
1044 hash_insert_at (&table, v, new_slot);
1048 makelevel_key.name = MAKELEVEL_NAME;
1049 makelevel_key.length = MAKELEVEL_LENGTH;
1050 hash_delete (&table, &makelevel_key);
1052 result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
1054 v_slot = (struct variable **) table.ht_vec;
1055 v_end = v_slot + table.ht_size;
1056 for ( ; v_slot < v_end; v_slot++)
1057 if (! HASH_VACANT (*v_slot))
1059 struct variable *v = *v_slot;
1061 /* If V is recursively expanded and didn't come from the environment,
1062 expand its value. If it came from the environment, it should
1063 go back into the environment unchanged. */
1065 && v->origin != o_env && v->origin != o_env_override)
1067 char *value = recursively_expand_for_file (v, file);
1069 if (strcmp (v->name, "Path") == 0 ||
1070 strcmp (v->name, "PATH") == 0)
1071 convert_Path_to_windows32 (value, ';');
1073 *result++ = xstrdup (concat (3, v->name, "=", value));
1079 if (strcmp (v->name, "Path") == 0 ||
1080 strcmp (v->name, "PATH") == 0)
1081 convert_Path_to_windows32 (v->value, ';');
1083 *result++ = xstrdup (concat (3, v->name, "=", v->value));
1087 *result = xmalloc (100);
1088 sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
1091 hash_free (&table, 0);
1096 static struct variable *
1097 set_special_var (struct variable *var)
1099 if (streq (var->name, RECIPEPREFIX_NAME))
1101 /* The user is resetting the command introduction prefix. This has to
1102 happen immediately, so that subsequent rules are interpreted
1104 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1110 /* Given a string, shell-execute it and return a malloc'ed string of the
1111 * result. This removes only ONE newline (if any) at the end, for maximum
1112 * compatibility with the *BSD makes. If it fails, returns NULL. */
1115 shell_result (const char *p)
1122 install_variable_buffer (&buf, &len);
1124 args[0] = (char *) p;
1126 variable_buffer_output (func_shell_base (variable_buffer, args, 0), "\0", 1);
1127 result = strdup (variable_buffer);
1129 restore_variable_buffer (buf, len);
1133 /* Given a variable, a value, and a flavor, define the variable.
1134 See the try_variable_definition() function for details on the parameters. */
1137 do_variable_definition (const gmk_floc *flocp, const char *varname,
1138 const char *value, enum variable_origin origin,
1139 enum variable_flavor flavor, int target_var)
1142 char *alloc_value = NULL;
1145 int conditional = 0;
1147 /* Calculate the variable's new value in VALUE. */
1153 /* Should not be possible. */
1156 /* A simple variable definition "var := value". Expand the value.
1157 We have to allocate memory since otherwise it'll clobber the
1158 variable buffer, and we may still need that if we're looking at a
1159 target-specific variable. */
1160 p = alloc_value = allocated_variable_expand (value);
1164 /* A shell definition "var != value". Expand value, pass it to
1165 the shell, and store the result in recursively-expanded var. */
1166 char *q = allocated_variable_expand (value);
1167 p = alloc_value = shell_result (q);
1169 flavor = f_recursive;
1173 /* A conditional variable definition "var ?= value".
1174 The value is set IFF the variable is not defined yet. */
1175 v = lookup_variable (varname, strlen (varname));
1177 return v->special ? set_special_var (v) : v;
1180 flavor = f_recursive;
1183 /* A recursive variable definition "var = value".
1184 The value is used verbatim. */
1189 /* If we have += but we're in a target variable context, we want to
1190 append only with other variables in the context of this target. */
1194 v = lookup_variable_in_set (varname, strlen (varname),
1195 current_variable_set_list->set);
1197 /* Don't append from the global set if a previous non-appending
1198 target-specific variable definition exists. */
1199 if (v && !v->append)
1203 v = lookup_variable (varname, strlen (varname));
1207 /* There was no old value.
1208 This becomes a normal recursive definition. */
1210 flavor = f_recursive;
1214 /* Paste the old and new values together in VALUE. */
1216 unsigned int oldlen, vallen;
1222 /* The previous definition of the variable was recursive.
1223 The new value is the unexpanded old and new values. */
1224 flavor = f_recursive;
1226 /* The previous definition of the variable was simple.
1227 The new value comes from the old value, which was expanded
1228 when it was set; and from the expanded new value. Allocate
1229 memory for the expansion as we may still need the rest of the
1230 buffer if we're looking at a target-specific variable. */
1231 val = tp = allocated_variable_expand (val);
1233 oldlen = strlen (v->value);
1234 vallen = strlen (val);
1235 p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1236 memcpy (alloc_value, v->value, oldlen);
1237 alloc_value[oldlen] = ' ';
1238 memcpy (&alloc_value[oldlen + 1], val, vallen + 1);
1247 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1248 non-Unix systems don't conform to this default configuration (in
1249 fact, most of them don't even have '/bin'). On the other hand,
1250 $SHELL in the environment, if set, points to the real pathname of
1252 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1253 the Makefile override $SHELL from the environment. But first, we
1254 look for the basename of the shell in the directory where SHELL=
1255 points, and along the $PATH; if it is found in any of these places,
1256 we define $SHELL to be the actual pathname of the shell. Thus, if
1257 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1258 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1259 defining SHELL to be "d:/unix/bash.exe". */
1260 if ((origin == o_file || origin == o_override)
1261 && strcmp (varname, "SHELL") == 0)
1263 PATH_VAR (shellpath);
1264 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1266 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1267 if (__dosexec_find_on_path (p, NULL, shellpath))
1271 for (tp = shellpath; *tp; tp++)
1275 v = define_variable_loc (varname, strlen (varname),
1276 shellpath, origin, flavor == f_recursive,
1281 const char *shellbase, *bslash;
1282 struct variable *pathv = lookup_variable ("PATH", 4);
1287 shellbase = strrchr (p, '/');
1288 bslash = strrchr (p, '\\');
1289 if (!shellbase || bslash > shellbase)
1291 if (!shellbase && p[1] == ':')
1298 /* Search for the basename of the shell (with standard
1299 executable extensions) along the $PATH. */
1301 pathlen = strlen (pathv->value);
1302 path_string = xmalloc (5 + pathlen + 2 + 1);
1303 /* On MSDOS, current directory is considered as part of $PATH. */
1304 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1305 fake_env[0] = path_string;
1307 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1311 for (tp = shellpath; *tp; tp++)
1315 v = define_variable_loc (varname, strlen (varname),
1317 flavor == f_recursive, flocp);
1320 v = lookup_variable (varname, strlen (varname));
1326 #endif /* __MSDOS__ */
1328 if ((origin == o_file || origin == o_override || origin == o_command)
1329 && streq (varname, "SHELL"))
1331 extern char *default_shell;
1333 /* Call shell locator function. If it returns TRUE, then
1334 set no_default_sh_exe to indicate sh was found and
1335 set new value for SHELL variable. */
1337 if (find_and_set_default_shell (p))
1339 v = define_variable_in_set (varname, strlen (varname), default_shell,
1340 origin, flavor == f_recursive,
1342 ? current_variable_set_list->set
1345 no_default_sh_exe = 0;
1349 char *tp = alloc_value;
1351 alloc_value = allocated_variable_expand (p);
1353 if (find_and_set_default_shell (alloc_value))
1355 v = define_variable_in_set (varname, strlen (varname), p,
1356 origin, flavor == f_recursive,
1358 ? current_variable_set_list->set
1361 no_default_sh_exe = 0;
1364 v = lookup_variable (varname, strlen (varname));
1373 /* If we are defining variables inside an $(eval ...), we might have a
1374 different variable context pushed, not the global context (maybe we're
1375 inside a $(call ...) or something. Since this function is only ever
1376 invoked in places where we want to define globally visible variables,
1377 make sure we define this variable in the global set. */
1379 v = define_variable_in_set (varname, strlen (varname), p,
1380 origin, flavor == f_recursive,
1382 ? current_variable_set_list->set : NULL),
1385 v->conditional = conditional;
1390 return v->special ? set_special_var (v) : v;
1393 /* Parse P (a null-terminated string) as a variable definition.
1395 If it is not a variable definition, return NULL and the contents of *VAR
1396 are undefined, except NAME is set to the first non-space character or NIL.
1398 If it is a variable definition, return a pointer to the char after the
1399 assignment token and set the following fields (only) of *VAR:
1400 name : name of the variable (ALWAYS SET) (NOT NUL-TERMINATED!)
1401 length : length of the variable name
1402 value : value of the variable (nul-terminated)
1403 flavor : flavor of the variable
1404 Other values in *VAR are unchanged.
1408 parse_variable_definition (const char *p, struct variable *var)
1411 const char *e = NULL;
1414 var->name = (char *)p;
1421 /* If we find a comment or EOS, it's not a variable definition. */
1422 if (STOP_SET (c, MAP_COMMENT|MAP_NUL))
1427 /* This begins a variable expansion reference. Make sure we don't
1428 treat chars inside the reference as assignment tokens. */
1437 /* '$$' or '$X'. Either way, nothing special to do here. */
1440 /* P now points past the opening paren or brace.
1441 Count parens or braces until it is matched. */
1443 for (; *p != '\0'; ++p)
1447 else if (*p == closeparen && --count < 0)
1456 /* If we find whitespace skip it, and remember we found it. */
1457 if (isblank ((unsigned char)c))
1471 var->flavor = f_recursive;
1477 /* Match assignment variants (:=, +=, ?=, !=) */
1483 var->flavor = f_simple;
1486 var->flavor = f_append;
1489 var->flavor = f_conditional;
1492 var->flavor = f_shell;
1495 /* If we skipped whitespace, non-assignments means no var. */
1499 /* Might be assignment, or might be $= or #=. Check. */
1508 /* Check for POSIX ::= syntax */
1511 /* A colon other than :=/::= is not a variable defn. */
1512 if (*p != ':' || p[1] != '=')
1515 /* POSIX allows ::= to be the same as GNU make's := */
1516 var->flavor = f_simple;
1523 /* If we skipped whitespace, non-assignments means no var. */
1528 var->length = e - var->name;
1529 var->value = next_token (p);
1533 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1535 If LINE was recognized as a variable definition, a pointer to its 'struct
1536 variable' is returned. If LINE is not a variable definition, NULL is
1540 assign_variable_definition (struct variable *v, char *line)
1544 if (!parse_variable_definition (line, v))
1547 /* Expand the name, so "$(foo)bar = baz" works. */
1548 name = alloca (v->length + 1);
1549 memcpy (name, v->name, v->length);
1550 name[v->length] = '\0';
1551 v->name = allocated_variable_expand (name);
1553 if (v->name[0] == '\0')
1554 fatal (&v->fileinfo, _("empty variable name"));
1559 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1561 ORIGIN may be o_file, o_override, o_env, o_env_override,
1562 or o_command specifying that the variable definition comes
1563 from a makefile, an override directive, the environment with
1564 or without the -e switch, or the command line.
1566 See the comments for assign_variable_definition().
1568 If LINE was recognized as a variable definition, a pointer to its 'struct
1569 variable' is returned. If LINE is not a variable definition, NULL is
1573 try_variable_definition (const gmk_floc *flocp, char *line,
1574 enum variable_origin origin, int target_var)
1577 struct variable *vp;
1580 v.fileinfo = *flocp;
1582 v.fileinfo.filenm = 0;
1584 if (!assign_variable_definition (&v, line))
1587 vp = do_variable_definition (flocp, v.name, v.value,
1588 origin, v.flavor, target_var);
1595 /* Print information for variable V, prefixing it with PREFIX. */
1598 print_variable (const void *item, void *arg)
1600 const struct variable *v = item;
1601 const char *prefix = arg;
1607 origin = _("automatic");
1610 origin = _("default");
1613 origin = _("environment");
1616 origin = _("makefile");
1618 case o_env_override:
1619 origin = _("environment under -e");
1622 origin = _("command line");
1625 origin = _("'override' directive");
1631 fputs ("# ", stdout);
1632 fputs (origin, stdout);
1634 fputs (" private", stdout);
1635 if (v->fileinfo.filenm)
1636 printf (_(" (from '%s', line %lu)"),
1637 v->fileinfo.filenm, v->fileinfo.lineno);
1639 fputs (prefix, stdout);
1641 /* Is this a 'define'? */
1642 if (v->recursive && strchr (v->value, '\n') != 0)
1643 printf ("define %s\n%s\nendef\n", v->name, v->value);
1648 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1650 /* Check if the value is just whitespace. */
1651 p = next_token (v->value);
1652 if (p != v->value && *p == '\0')
1653 /* All whitespace. */
1654 printf ("$(subst ,,%s)", v->value);
1655 else if (v->recursive)
1656 fputs (v->value, stdout);
1658 /* Double up dollar signs. */
1659 for (p = v->value; *p != '\0'; ++p)
1671 print_auto_variable (const void *item, void *arg)
1673 const struct variable *v = item;
1675 if (v->origin == o_automatic)
1676 print_variable (item, arg);
1681 print_noauto_variable (const void *item, void *arg)
1683 const struct variable *v = item;
1685 if (v->origin != o_automatic)
1686 print_variable (item, arg);
1690 /* Print all the variables in SET. PREFIX is printed before
1691 the actual variable definitions (everything else is comments). */
1694 print_variable_set (struct variable_set *set, char *prefix, int pauto)
1696 hash_map_arg (&set->table, (pauto ? print_auto_variable : print_variable),
1699 fputs (_("# variable set hash-table stats:\n"), stdout);
1700 fputs ("# ", stdout);
1701 hash_print_stats (&set->table, stdout);
1702 putc ('\n', stdout);
1705 /* Print the data base of variables. */
1708 print_variable_data_base (void)
1710 puts (_("\n# Variables\n"));
1712 print_variable_set (&global_variable_set, "", 0);
1714 puts (_("\n# Pattern-specific Variable Values"));
1717 struct pattern_var *p;
1720 for (p = pattern_vars; p != 0; p = p->next)
1723 printf ("\n%s :\n", p->target);
1724 print_variable (&p->variable, "# ");
1728 puts (_("\n# No pattern-specific variable values."));
1730 printf (_("\n# %u pattern-specific variable values"), rules);
1735 /* Print all the local variables of FILE. */
1738 print_file_variables (const struct file *file)
1740 if (file->variables != 0)
1741 print_variable_set (file->variables->set, "# ", 1);
1745 print_target_variables (const struct file *file)
1747 if (file->variables != 0)
1749 int l = strlen (file->name);
1750 char *t = alloca (l + 3);
1752 strcpy (t, file->name);
1757 hash_map_arg (&file->variables->set->table, print_noauto_variable, t);
1763 sync_Path_environment (void)
1765 char *path = allocated_variable_expand ("$(PATH)");
1766 static char *environ_path = NULL;
1772 * If done this before, don't leak memory unnecessarily.
1773 * Free the previous entry before allocating new one.
1776 free (environ_path);
1779 * Create something WINDOWS32 world can grok
1781 convert_Path_to_windows32 (path, ';');
1782 environ_path = xstrdup (concat (3, "PATH", "=", path));
1783 putenv (environ_path);