- Add static pattern targets to the string cache.
[make.git] / variable.c
blob90c447c3de0d11e1b63f1e57f8a677ab47ab8597
1 /* Internals of variables for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4 Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
10 version.
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "make.h"
21 #include <assert.h>
23 #include "dep.h"
24 #include "filedef.h"
25 #include "job.h"
26 #include "commands.h"
27 #include "variable.h"
28 #include "rule.h"
29 #ifdef WINDOWS32
30 #include "pathstuff.h"
31 #endif
32 #include "hash.h"
34 /* Chain of all pattern-specific variables. */
36 static struct pattern_var *pattern_vars;
38 /* Pointer to last struct in the chain, so we can add onto the end. */
40 static struct pattern_var *last_pattern_var;
42 /* Create a new pattern-specific variable struct. */
44 struct pattern_var *
45 create_pattern_var (const char *target, const char *suffix)
47 register struct pattern_var *p = xmalloc (sizeof (struct pattern_var));
49 if (last_pattern_var != 0)
50 last_pattern_var->next = p;
51 else
52 pattern_vars = p;
53 last_pattern_var = p;
54 p->next = 0;
56 p->target = target;
57 p->len = strlen (target);
58 p->suffix = suffix + 1;
60 return p;
63 /* Look up a target in the pattern-specific variable list. */
65 static struct pattern_var *
66 lookup_pattern_var (struct pattern_var *start, const char *target)
68 struct pattern_var *p;
69 unsigned int targlen = strlen(target);
71 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
73 const char *stem;
74 unsigned int stemlen;
76 if (p->len > targlen)
77 /* It can't possibly match. */
78 continue;
80 /* From the lengths of the filename and the pattern parts,
81 find the stem: the part of the filename that matches the %. */
82 stem = target + (p->suffix - p->target - 1);
83 stemlen = targlen - p->len + 1;
85 /* Compare the text in the pattern before the stem, if any. */
86 if (stem > target && !strneq (p->target, target, stem - target))
87 continue;
89 /* Compare the text in the pattern after the stem, if any.
90 We could test simply using streq, but this way we compare the
91 first two characters immediately. This saves time in the very
92 common case where the first character matches because it is a
93 period. */
94 if (*p->suffix == stem[stemlen]
95 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
96 break;
99 return p;
102 /* Hash table of all global variable definitions. */
104 static unsigned long
105 variable_hash_1 (const void *keyv)
107 struct variable const *key = (struct variable const *) keyv;
108 return_STRING_N_HASH_1 (key->name, key->length);
111 static unsigned long
112 variable_hash_2 (const void *keyv)
114 struct variable const *key = (struct variable const *) keyv;
115 return_STRING_N_HASH_2 (key->name, key->length);
118 static int
119 variable_hash_cmp (const void *xv, const void *yv)
121 struct variable const *x = (struct variable const *) xv;
122 struct variable const *y = (struct variable const *) yv;
123 int result = x->length - y->length;
124 if (result)
125 return result;
126 return_STRING_N_COMPARE (x->name, y->name, x->length);
129 #ifndef VARIABLE_BUCKETS
130 #define VARIABLE_BUCKETS 523
131 #endif
132 #ifndef PERFILE_VARIABLE_BUCKETS
133 #define PERFILE_VARIABLE_BUCKETS 23
134 #endif
135 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
136 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
137 #endif
139 static struct variable_set global_variable_set;
140 static struct variable_set_list global_setlist
141 = { 0, &global_variable_set, 0 };
142 struct variable_set_list *current_variable_set_list = &global_setlist;
144 /* Implement variables. */
146 void
147 init_hash_global_variable_set (void)
149 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
150 variable_hash_1, variable_hash_2, variable_hash_cmp);
153 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
154 LENGTH is the length of NAME, which does not need to be null-terminated.
155 ORIGIN specifies the origin of the variable (makefile, command line
156 or environment).
157 If RECURSIVE is nonzero a flag is set in the variable saying
158 that it should be recursively re-expanded. */
160 struct variable *
161 define_variable_in_set (const char *name, unsigned int length,
162 const char *value, enum variable_origin origin,
163 int recursive, struct variable_set *set,
164 const struct floc *flocp)
166 struct variable *v;
167 struct variable **var_slot;
168 struct variable var_key;
170 if (set == NULL)
171 set = &global_variable_set;
173 var_key.name = (char *) name;
174 var_key.length = length;
175 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
177 if (env_overrides && origin == o_env)
178 origin = o_env_override;
180 v = *var_slot;
181 if (! HASH_VACANT (v))
183 if (env_overrides && v->origin == o_env)
184 /* V came from in the environment. Since it was defined
185 before the switches were parsed, it wasn't affected by -e. */
186 v->origin = o_env_override;
188 /* A variable of this name is already defined.
189 If the old definition is from a stronger source
190 than this one, don't redefine it. */
191 if ((int) origin >= (int) v->origin)
193 if (v->value != 0)
194 free (v->value);
195 v->value = xstrdup (value);
196 if (flocp != 0)
197 v->fileinfo = *flocp;
198 else
199 v->fileinfo.filenm = 0;
200 v->origin = origin;
201 v->recursive = recursive;
203 return v;
206 /* Create a new variable definition and add it to the hash table. */
208 v = xmalloc (sizeof (struct variable));
209 v->name = xstrndup (name, length);
210 v->length = length;
211 hash_insert_at (&set->table, v, var_slot);
212 v->value = xstrdup (value);
213 if (flocp != 0)
214 v->fileinfo = *flocp;
215 else
216 v->fileinfo.filenm = 0;
217 v->origin = origin;
218 v->recursive = recursive;
219 v->special = 0;
220 v->expanding = 0;
221 v->exp_count = 0;
222 v->per_target = 0;
223 v->append = 0;
224 v->private_var = 0;
225 v->export = v_default;
227 v->exportable = 1;
228 if (*name != '_' && (*name < 'A' || *name > 'Z')
229 && (*name < 'a' || *name > 'z'))
230 v->exportable = 0;
231 else
233 for (++name; *name != '\0'; ++name)
234 if (*name != '_' && (*name < 'a' || *name > 'z')
235 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
236 break;
238 if (*name != '\0')
239 v->exportable = 0;
242 return v;
245 /* If the variable passed in is "special", handle its special nature.
246 Currently there are two such variables, both used for introspection:
247 .VARIABLES expands to a list of all the variables defined in this instance
248 of make.
249 .TARGETS expands to a list of all the targets defined in this
250 instance of make.
251 Returns the variable reference passed in. */
253 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
255 static struct variable *
256 lookup_special_var (struct variable *var)
258 static unsigned long last_var_count = 0;
261 /* This one actually turns out to be very hard, due to the way the parser
262 records targets. The way it works is that target information is collected
263 internally until make knows the target is completely specified. It unitl
264 it sees that some new construct (a new target or variable) is defined that
265 it knows the previous one is done. In short, this means that if you do
266 this:
268 all:
270 TARGS := $(.TARGETS)
272 then $(TARGS) won't contain "all", because it's not until after the
273 variable is created that the previous target is completed.
275 Changing this would be a major pain. I think a less complex way to do it
276 would be to pre-define the target files as soon as the first line is
277 parsed, then come back and do the rest of the definition as now. That
278 would allow $(.TARGETS) to be correct without a major change to the way
279 the parser works.
281 if (streq (var->name, ".TARGETS"))
282 var->value = build_target_list (var->value);
283 else
286 if (streq (var->name, ".VARIABLES")
287 && global_variable_set.table.ht_fill != last_var_count)
289 unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
290 unsigned long len;
291 char *p;
292 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
293 struct variable **end = &vp[global_variable_set.table.ht_size];
295 /* Make sure we have at least MAX bytes in the allocated buffer. */
296 var->value = xrealloc (var->value, max);
298 /* Walk through the hash of variables, constructing a list of names. */
299 p = var->value;
300 len = 0;
301 for (; vp < end; ++vp)
302 if (!HASH_VACANT (*vp))
304 struct variable *v = *vp;
305 int l = v->length;
307 len += l + 1;
308 if (len > max)
310 unsigned long off = p - var->value;
312 max += EXPANSION_INCREMENT (l + 1);
313 var->value = xrealloc (var->value, max);
314 p = &var->value[off];
317 memcpy (p, v->name, l);
318 p += l;
319 *(p++) = ' ';
321 *(p-1) = '\0';
323 /* Remember how many variables are in our current count. Since we never
324 remove variables from the list, this is a reliable way to know whether
325 the list is up to date or needs to be recomputed. */
327 last_var_count = global_variable_set.table.ht_fill;
330 return var;
334 /* Lookup a variable whose name is a string starting at NAME
335 and with LENGTH chars. NAME need not be null-terminated.
336 Returns address of the `struct variable' containing all info
337 on the variable, or nil if no such variable is defined. */
339 struct variable *
340 lookup_variable (const char *name, unsigned int length)
342 const struct variable_set_list *setlist;
343 struct variable var_key;
344 int is_parent = 0;
346 var_key.name = (char *) name;
347 var_key.length = length;
349 for (setlist = current_variable_set_list;
350 setlist != 0; setlist = setlist->next)
352 const struct variable_set *set = setlist->set;
353 struct variable *v;
355 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
356 if (v && (!is_parent || !v->private_var))
357 return v->special ? lookup_special_var (v) : v;
359 is_parent |= setlist->next_is_parent;
362 #ifdef VMS
363 /* since we don't read envp[] on startup, try to get the
364 variable via getenv() here. */
366 char *vname = alloca (length + 1);
367 char *value;
368 strncpy (vname, name, length);
369 vname[length] = 0;
370 value = getenv (vname);
371 if (value != 0)
373 char *sptr;
374 int scnt;
376 sptr = value;
377 scnt = 0;
379 while ((sptr = strchr (sptr, '$')))
381 scnt++;
382 sptr++;
385 if (scnt > 0)
387 char *nvalue;
388 char *nptr;
390 nvalue = alloca (strlen (value) + scnt + 1);
391 sptr = value;
392 nptr = nvalue;
394 while (*sptr)
396 if (*sptr == '$')
398 *nptr++ = '$';
399 *nptr++ = '$';
401 else
403 *nptr++ = *sptr;
405 sptr++;
408 *nptr = '\0';
409 return define_variable (vname, length, nvalue, o_env, 1);
413 return define_variable (vname, length, value, o_env, 1);
416 #endif /* VMS */
418 return 0;
421 /* Lookup a variable whose name is a string starting at NAME
422 and with LENGTH chars in set SET. NAME need not be null-terminated.
423 Returns address of the `struct variable' containing all info
424 on the variable, or nil if no such variable is defined. */
426 struct variable *
427 lookup_variable_in_set (const char *name, unsigned int length,
428 const struct variable_set *set)
430 struct variable var_key;
432 var_key.name = (char *) name;
433 var_key.length = length;
435 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
438 /* Initialize FILE's variable set list. If FILE already has a variable set
439 list, the topmost variable set is left intact, but the the rest of the
440 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
441 rule, then we will use the "root" double-colon target's variable set as the
442 parent of FILE's variable set.
444 If we're READING a makefile, don't do the pattern variable search now,
445 since the pattern variable might not have been defined yet. */
447 void
448 initialize_file_variables (struct file *file, int reading)
450 struct variable_set_list *l = file->variables;
452 if (l == 0)
454 l = (struct variable_set_list *)
455 xmalloc (sizeof (struct variable_set_list));
456 l->set = xmalloc (sizeof (struct variable_set));
457 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
458 variable_hash_1, variable_hash_2, variable_hash_cmp);
459 file->variables = l;
462 /* If this is a double-colon, then our "parent" is the "root" target for
463 this double-colon rule. Since that rule has the same name, parent,
464 etc. we can just use its variables as the "next" for ours. */
466 if (file->double_colon && file->double_colon != file)
468 initialize_file_variables (file->double_colon, reading);
469 l->next = file->double_colon->variables;
470 l->next_is_parent = 0;
471 return;
474 if (file->parent == 0)
475 l->next = &global_setlist;
476 else
478 initialize_file_variables (file->parent, reading);
479 l->next = file->parent->variables;
481 l->next_is_parent = 1;
483 /* If we're not reading makefiles and we haven't looked yet, see if
484 we can find pattern variables for this target. */
486 if (!reading && !file->pat_searched)
488 struct pattern_var *p;
490 p = lookup_pattern_var (0, file->name);
491 if (p != 0)
493 struct variable_set_list *global = current_variable_set_list;
495 /* We found at least one. Set up a new variable set to accumulate
496 all the pattern variables that match this target. */
498 file->pat_variables = create_new_variable_set ();
499 current_variable_set_list = file->pat_variables;
503 /* We found one, so insert it into the set. */
505 struct variable *v;
507 if (p->variable.flavor == f_simple)
509 v = define_variable_loc (
510 p->variable.name, strlen (p->variable.name),
511 p->variable.value, p->variable.origin,
512 0, &p->variable.fileinfo);
514 v->flavor = f_simple;
516 else
518 v = do_variable_definition (
519 &p->variable.fileinfo, p->variable.name,
520 p->variable.value, p->variable.origin,
521 p->variable.flavor, 1);
524 /* Also mark it as a per-target and copy export status. */
525 v->per_target = p->variable.per_target;
526 v->export = p->variable.export;
527 v->private_var = p->variable.private_var;
529 while ((p = lookup_pattern_var (p, file->name)) != 0);
531 current_variable_set_list = global;
533 file->pat_searched = 1;
536 /* If we have a pattern variable match, set it up. */
538 if (file->pat_variables != 0)
540 file->pat_variables->next = l->next;
541 file->pat_variables->next_is_parent = l->next_is_parent;
542 l->next = file->pat_variables;
543 l->next_is_parent = 0;
547 /* Pop the top set off the current variable set list,
548 and free all its storage. */
550 struct variable_set_list *
551 create_new_variable_set (void)
553 register struct variable_set_list *setlist;
554 register struct variable_set *set;
556 set = xmalloc (sizeof (struct variable_set));
557 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
558 variable_hash_1, variable_hash_2, variable_hash_cmp);
560 setlist = (struct variable_set_list *)
561 xmalloc (sizeof (struct variable_set_list));
562 setlist->set = set;
563 setlist->next = current_variable_set_list;
564 setlist->next_is_parent = 0;
566 return setlist;
569 static void
570 free_variable_name_and_value (const void *item)
572 struct variable *v = (struct variable *) item;
573 free (v->name);
574 free (v->value);
577 void
578 free_variable_set (struct variable_set_list *list)
580 hash_map (&list->set->table, free_variable_name_and_value);
581 hash_free (&list->set->table, 1);
582 free (list->set);
583 free (list);
586 /* Create a new variable set and push it on the current setlist.
587 If we're pushing a global scope (that is, the current scope is the global
588 scope) then we need to "push" it the other way: file variable sets point
589 directly to the global_setlist so we need to replace that with the new one.
592 struct variable_set_list *
593 push_new_variable_scope (void)
595 current_variable_set_list = create_new_variable_set();
596 if (current_variable_set_list->next == &global_setlist)
598 /* It was the global, so instead of new -> &global we want to replace
599 &global with the new one and have &global -> new, with current still
600 pointing to &global */
601 struct variable_set *set = current_variable_set_list->set;
602 current_variable_set_list->set = global_setlist.set;
603 global_setlist.set = set;
604 current_variable_set_list->next = global_setlist.next;
605 global_setlist.next = current_variable_set_list;
606 current_variable_set_list = &global_setlist;
608 return (current_variable_set_list);
611 void
612 pop_variable_scope (void)
614 struct variable_set_list *setlist;
615 struct variable_set *set;
617 /* Can't call this if there's no scope to pop! */
618 assert(current_variable_set_list->next != NULL);
620 if (current_variable_set_list != &global_setlist)
622 /* We're not pointing to the global setlist, so pop this one. */
623 setlist = current_variable_set_list;
624 set = setlist->set;
625 current_variable_set_list = setlist->next;
627 else
629 /* This set is the one in the global_setlist, but there is another global
630 set beyond that. We want to copy that set to global_setlist, then
631 delete what used to be in global_setlist. */
632 setlist = global_setlist.next;
633 set = global_setlist.set;
634 global_setlist.set = setlist->set;
635 global_setlist.next = setlist->next;
636 global_setlist.next_is_parent = setlist->next_is_parent;
639 /* Free the one we no longer need. */
640 free (setlist);
641 hash_map (&set->table, free_variable_name_and_value);
642 hash_free (&set->table, 1);
643 free (set);
646 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
648 static void
649 merge_variable_sets (struct variable_set *to_set,
650 struct variable_set *from_set)
652 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
653 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
655 for ( ; from_var_slot < from_var_end; from_var_slot++)
656 if (! HASH_VACANT (*from_var_slot))
658 struct variable *from_var = *from_var_slot;
659 struct variable **to_var_slot
660 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
661 if (HASH_VACANT (*to_var_slot))
662 hash_insert_at (&to_set->table, from_var, to_var_slot);
663 else
665 /* GKM FIXME: delete in from_set->table */
666 free (from_var->value);
667 free (from_var);
672 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
674 void
675 merge_variable_set_lists (struct variable_set_list **setlist0,
676 struct variable_set_list *setlist1)
678 struct variable_set_list *to = *setlist0;
679 struct variable_set_list *last0 = 0;
681 /* If there's nothing to merge, stop now. */
682 if (!setlist1)
683 return;
685 /* This loop relies on the fact that all setlists terminate with the global
686 setlist (before NULL). If that's not true, arguably we SHOULD die. */
687 if (to)
688 while (setlist1 != &global_setlist && to != &global_setlist)
690 struct variable_set_list *from = setlist1;
691 setlist1 = setlist1->next;
693 merge_variable_sets (to->set, from->set);
695 last0 = to;
696 to = to->next;
699 if (setlist1 != &global_setlist)
701 if (last0 == 0)
702 *setlist0 = setlist1;
703 else
704 last0->next = setlist1;
708 /* Define the automatic variables, and record the addresses
709 of their structures so we can change their values quickly. */
711 void
712 define_automatic_variables (void)
714 #if defined(WINDOWS32) || defined(__EMX__)
715 extern char* default_shell;
716 #else
717 extern char default_shell[];
718 #endif
719 register struct variable *v;
720 char buf[200];
722 sprintf (buf, "%u", makelevel);
723 (void) define_variable (MAKELEVEL_NAME, MAKELEVEL_LENGTH, buf, o_env, 0);
725 sprintf (buf, "%s%s%s",
726 version_string,
727 (remote_description == 0 || remote_description[0] == '\0')
728 ? "" : "-",
729 (remote_description == 0 || remote_description[0] == '\0')
730 ? "" : remote_description);
731 (void) define_variable ("MAKE_VERSION", 12, buf, o_default, 0);
733 #ifdef __MSDOS__
734 /* Allow to specify a special shell just for Make,
735 and use $COMSPEC as the default $SHELL when appropriate. */
737 static char shell_str[] = "SHELL";
738 const int shlen = sizeof (shell_str) - 1;
739 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
740 struct variable *comp = lookup_variable ("COMSPEC", 7);
742 /* Make $MAKESHELL override $SHELL even if -e is in effect. */
743 if (mshp)
744 (void) define_variable (shell_str, shlen,
745 mshp->value, o_env_override, 0);
746 else if (comp)
748 /* $COMSPEC shouldn't override $SHELL. */
749 struct variable *shp = lookup_variable (shell_str, shlen);
751 if (!shp)
752 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
755 #elif defined(__EMX__)
757 static char shell_str[] = "SHELL";
758 const int shlen = sizeof (shell_str) - 1;
759 struct variable *shell = lookup_variable (shell_str, shlen);
760 struct variable *replace = lookup_variable ("MAKESHELL", 9);
762 /* if $MAKESHELL is defined in the environment assume o_env_override */
763 if (replace && *replace->value && replace->origin == o_env)
764 replace->origin = o_env_override;
766 /* if $MAKESHELL is not defined use $SHELL but only if the variable
767 did not come from the environment */
768 if (!replace || !*replace->value)
769 if (shell && *shell->value && (shell->origin == o_env
770 || shell->origin == o_env_override))
772 /* overwrite whatever we got from the environment */
773 free(shell->value);
774 shell->value = xstrdup (default_shell);
775 shell->origin = o_default;
778 /* Some people do not like cmd to be used as the default
779 if $SHELL is not defined in the Makefile.
780 With -DNO_CMD_DEFAULT you can turn off this behaviour */
781 # ifndef NO_CMD_DEFAULT
782 /* otherwise use $COMSPEC */
783 if (!replace || !*replace->value)
784 replace = lookup_variable ("COMSPEC", 7);
786 /* otherwise use $OS2_SHELL */
787 if (!replace || !*replace->value)
788 replace = lookup_variable ("OS2_SHELL", 9);
789 # else
790 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
791 # endif
793 if (replace && *replace->value)
794 /* overwrite $SHELL */
795 (void) define_variable (shell_str, shlen, replace->value,
796 replace->origin, 0);
797 else
798 /* provide a definition if there is none */
799 (void) define_variable (shell_str, shlen, default_shell,
800 o_default, 0);
803 #endif
805 /* This won't override any definition, but it will provide one if there
806 isn't one there. */
807 v = define_variable ("SHELL", 5, default_shell, o_default, 0);
808 #ifdef __MSDOS__
809 v->export = v_export; /* Export always SHELL. */
810 #endif
812 /* On MSDOS we do use SHELL from environment, since it isn't a standard
813 environment variable on MSDOS, so whoever sets it, does that on purpose.
814 On OS/2 we do not use SHELL from environment but we have already handled
815 that problem above. */
816 #if !defined(__MSDOS__) && !defined(__EMX__)
817 /* Don't let SHELL come from the environment. */
818 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
820 free (v->value);
821 v->origin = o_file;
822 v->value = xstrdup (default_shell);
824 #endif
826 /* Make sure MAKEFILES gets exported if it is set. */
827 v = define_variable ("MAKEFILES", 9, "", o_default, 0);
828 v->export = v_ifset;
830 /* Define the magic D and F variables in terms of
831 the automatic variables they are variations of. */
833 #ifdef VMS
834 define_variable ("@D", 2, "$(dir $@)", o_automatic, 1);
835 define_variable ("%D", 2, "$(dir $%)", o_automatic, 1);
836 define_variable ("*D", 2, "$(dir $*)", o_automatic, 1);
837 define_variable ("<D", 2, "$(dir $<)", o_automatic, 1);
838 define_variable ("?D", 2, "$(dir $?)", o_automatic, 1);
839 define_variable ("^D", 2, "$(dir $^)", o_automatic, 1);
840 define_variable ("+D", 2, "$(dir $+)", o_automatic, 1);
841 #else
842 define_variable ("@D", 2, "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
843 define_variable ("%D", 2, "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
844 define_variable ("*D", 2, "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
845 define_variable ("<D", 2, "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
846 define_variable ("?D", 2, "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
847 define_variable ("^D", 2, "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
848 define_variable ("+D", 2, "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
849 #endif
850 define_variable ("@F", 2, "$(notdir $@)", o_automatic, 1);
851 define_variable ("%F", 2, "$(notdir $%)", o_automatic, 1);
852 define_variable ("*F", 2, "$(notdir $*)", o_automatic, 1);
853 define_variable ("<F", 2, "$(notdir $<)", o_automatic, 1);
854 define_variable ("?F", 2, "$(notdir $?)", o_automatic, 1);
855 define_variable ("^F", 2, "$(notdir $^)", o_automatic, 1);
856 define_variable ("+F", 2, "$(notdir $+)", o_automatic, 1);
859 int export_all_variables;
861 /* Create a new environment for FILE's commands.
862 If FILE is nil, this is for the `shell' function.
863 The child's MAKELEVEL variable is incremented. */
865 char **
866 target_environment (struct file *file)
868 struct variable_set_list *set_list;
869 register struct variable_set_list *s;
870 struct hash_table table;
871 struct variable **v_slot;
872 struct variable **v_end;
873 struct variable makelevel_key;
874 char **result_0;
875 char **result;
877 if (file == 0)
878 set_list = current_variable_set_list;
879 else
880 set_list = file->variables;
882 hash_init (&table, VARIABLE_BUCKETS,
883 variable_hash_1, variable_hash_2, variable_hash_cmp);
885 /* Run through all the variable sets in the list,
886 accumulating variables in TABLE. */
887 for (s = set_list; s != 0; s = s->next)
889 struct variable_set *set = s->set;
890 v_slot = (struct variable **) set->table.ht_vec;
891 v_end = v_slot + set->table.ht_size;
892 for ( ; v_slot < v_end; v_slot++)
893 if (! HASH_VACANT (*v_slot))
895 struct variable **new_slot;
896 struct variable *v = *v_slot;
898 /* If this is a per-target variable and it hasn't been touched
899 already then look up the global version and take its export
900 value. */
901 if (v->per_target && v->export == v_default)
903 struct variable *gv;
905 gv = lookup_variable_in_set (v->name, strlen(v->name),
906 &global_variable_set);
907 if (gv)
908 v->export = gv->export;
911 switch (v->export)
913 case v_default:
914 if (v->origin == o_default || v->origin == o_automatic)
915 /* Only export default variables by explicit request. */
916 continue;
918 /* The variable doesn't have a name that can be exported. */
919 if (! v->exportable)
920 continue;
922 if (! export_all_variables
923 && v->origin != o_command
924 && v->origin != o_env && v->origin != o_env_override)
925 continue;
926 break;
928 case v_export:
929 break;
931 case v_noexport:
933 /* If this is the SHELL variable and it's not exported,
934 then add the value from our original environment, if
935 the original environment defined a value for SHELL. */
936 extern struct variable shell_var;
937 if (streq (v->name, "SHELL") && shell_var.value)
939 v = &shell_var;
940 break;
942 continue;
945 case v_ifset:
946 if (v->origin == o_default)
947 continue;
948 break;
951 new_slot = (struct variable **) hash_find_slot (&table, v);
952 if (HASH_VACANT (*new_slot))
953 hash_insert_at (&table, v, new_slot);
957 makelevel_key.name = MAKELEVEL_NAME;
958 makelevel_key.length = MAKELEVEL_LENGTH;
959 hash_delete (&table, &makelevel_key);
961 result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
963 v_slot = (struct variable **) table.ht_vec;
964 v_end = v_slot + table.ht_size;
965 for ( ; v_slot < v_end; v_slot++)
966 if (! HASH_VACANT (*v_slot))
968 struct variable *v = *v_slot;
970 /* If V is recursively expanded and didn't come from the environment,
971 expand its value. If it came from the environment, it should
972 go back into the environment unchanged. */
973 if (v->recursive
974 && v->origin != o_env && v->origin != o_env_override)
976 char *value = recursively_expand_for_file (v, file);
977 #ifdef WINDOWS32
978 if (strcmp(v->name, "Path") == 0 ||
979 strcmp(v->name, "PATH") == 0)
980 convert_Path_to_windows32(value, ';');
981 #endif
982 *result++ = xstrdup (concat (3, v->name, "=", value));
983 free (value);
985 else
987 #ifdef WINDOWS32
988 if (strcmp(v->name, "Path") == 0 ||
989 strcmp(v->name, "PATH") == 0)
990 convert_Path_to_windows32(v->value, ';');
991 #endif
992 *result++ = xstrdup (concat (3, v->name, "=", v->value));
996 *result = xmalloc (100);
997 sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
998 *++result = 0;
1000 hash_free (&table, 0);
1002 return result_0;
1005 static struct variable *
1006 set_special_var (struct variable *var)
1008 if (streq (var->name, RECIPEPREFIX_NAME))
1010 /* The user is resetting the command introduction prefix. This has to
1011 happen immediately, so that subsequent rules are interpreted
1012 properly. */
1013 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1016 return var;
1019 /* Given a variable, a value, and a flavor, define the variable.
1020 See the try_variable_definition() function for details on the parameters. */
1022 struct variable *
1023 do_variable_definition (const struct floc *flocp, const char *varname,
1024 const char *value, enum variable_origin origin,
1025 enum variable_flavor flavor, int target_var)
1027 const char *p;
1028 char *alloc_value = NULL;
1029 struct variable *v;
1030 int append = 0;
1031 int conditional = 0;
1033 /* Calculate the variable's new value in VALUE. */
1035 switch (flavor)
1037 default:
1038 case f_bogus:
1039 /* Should not be possible. */
1040 abort ();
1041 case f_simple:
1042 /* A simple variable definition "var := value". Expand the value.
1043 We have to allocate memory since otherwise it'll clobber the
1044 variable buffer, and we may still need that if we're looking at a
1045 target-specific variable. */
1046 p = alloc_value = allocated_variable_expand (value);
1047 break;
1048 case f_conditional:
1049 /* A conditional variable definition "var ?= value".
1050 The value is set IFF the variable is not defined yet. */
1051 v = lookup_variable (varname, strlen (varname));
1052 if (v)
1053 return v->special ? set_special_var (v) : v;
1055 conditional = 1;
1056 flavor = f_recursive;
1057 /* FALLTHROUGH */
1058 case f_recursive:
1059 /* A recursive variable definition "var = value".
1060 The value is used verbatim. */
1061 p = value;
1062 break;
1063 case f_append:
1065 /* If we have += but we're in a target variable context, we want to
1066 append only with other variables in the context of this target. */
1067 if (target_var)
1069 append = 1;
1070 v = lookup_variable_in_set (varname, strlen (varname),
1071 current_variable_set_list->set);
1073 /* Don't append from the global set if a previous non-appending
1074 target-specific variable definition exists. */
1075 if (v && !v->append)
1076 append = 0;
1078 else
1079 v = lookup_variable (varname, strlen (varname));
1081 if (v == 0)
1083 /* There was no old value.
1084 This becomes a normal recursive definition. */
1085 p = value;
1086 flavor = f_recursive;
1088 else
1090 /* Paste the old and new values together in VALUE. */
1092 unsigned int oldlen, vallen;
1093 const char *val;
1094 char *tp = NULL;
1096 val = value;
1097 if (v->recursive)
1098 /* The previous definition of the variable was recursive.
1099 The new value is the unexpanded old and new values. */
1100 flavor = f_recursive;
1101 else
1102 /* The previous definition of the variable was simple.
1103 The new value comes from the old value, which was expanded
1104 when it was set; and from the expanded new value. Allocate
1105 memory for the expansion as we may still need the rest of the
1106 buffer if we're looking at a target-specific variable. */
1107 val = tp = allocated_variable_expand (val);
1109 oldlen = strlen (v->value);
1110 vallen = strlen (val);
1111 p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1112 memcpy (alloc_value, v->value, oldlen);
1113 alloc_value[oldlen] = ' ';
1114 memcpy (&alloc_value[oldlen + 1], val, vallen + 1);
1116 if (tp)
1117 free (tp);
1122 #ifdef __MSDOS__
1123 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1124 non-Unix systems don't conform to this default configuration (in
1125 fact, most of them don't even have `/bin'). On the other hand,
1126 $SHELL in the environment, if set, points to the real pathname of
1127 the shell.
1128 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1129 the Makefile override $SHELL from the environment. But first, we
1130 look for the basename of the shell in the directory where SHELL=
1131 points, and along the $PATH; if it is found in any of these places,
1132 we define $SHELL to be the actual pathname of the shell. Thus, if
1133 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1134 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1135 defining SHELL to be "d:/unix/bash.exe". */
1136 if ((origin == o_file || origin == o_override)
1137 && strcmp (varname, "SHELL") == 0)
1139 PATH_VAR (shellpath);
1140 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1142 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1143 if (__dosexec_find_on_path (p, NULL, shellpath))
1145 char *tp;
1147 for (tp = shellpath; *tp; tp++)
1148 if (*tp == '\\')
1149 *tp = '/';
1151 v = define_variable_loc (varname, strlen (varname),
1152 shellpath, origin, flavor == f_recursive,
1153 flocp);
1155 else
1157 const char *shellbase, *bslash;
1158 struct variable *pathv = lookup_variable ("PATH", 4);
1159 char *path_string;
1160 char *fake_env[2];
1161 size_t pathlen = 0;
1163 shellbase = strrchr (p, '/');
1164 bslash = strrchr (p, '\\');
1165 if (!shellbase || bslash > shellbase)
1166 shellbase = bslash;
1167 if (!shellbase && p[1] == ':')
1168 shellbase = p + 1;
1169 if (shellbase)
1170 shellbase++;
1171 else
1172 shellbase = p;
1174 /* Search for the basename of the shell (with standard
1175 executable extensions) along the $PATH. */
1176 if (pathv)
1177 pathlen = strlen (pathv->value);
1178 path_string = xmalloc (5 + pathlen + 2 + 1);
1179 /* On MSDOS, current directory is considered as part of $PATH. */
1180 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1181 fake_env[0] = path_string;
1182 fake_env[1] = 0;
1183 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1185 char *tp;
1187 for (tp = shellpath; *tp; tp++)
1188 if (*tp == '\\')
1189 *tp = '/';
1191 v = define_variable_loc (varname, strlen (varname),
1192 shellpath, origin,
1193 flavor == f_recursive, flocp);
1195 else
1196 v = lookup_variable (varname, strlen (varname));
1198 free (path_string);
1201 else
1202 #endif /* __MSDOS__ */
1203 #ifdef WINDOWS32
1204 if ((origin == o_file || origin == o_override || origin == o_command)
1205 && streq (varname, "SHELL"))
1207 extern char *default_shell;
1209 /* Call shell locator function. If it returns TRUE, then
1210 set no_default_sh_exe to indicate sh was found and
1211 set new value for SHELL variable. */
1213 if (find_and_set_default_shell (p))
1215 v = define_variable_in_set (varname, strlen (varname), default_shell,
1216 origin, flavor == f_recursive,
1217 (target_var
1218 ? current_variable_set_list->set
1219 : NULL),
1220 flocp);
1221 no_default_sh_exe = 0;
1223 else
1225 char *tp = alloc_value;
1227 alloc_value = allocated_variable_expand (p);
1229 if (find_and_set_default_shell (alloc_value))
1231 v = define_variable_in_set (varname, strlen (varname), p,
1232 origin, flavor == f_recursive,
1233 (target_var
1234 ? current_variable_set_list->set
1235 : NULL),
1236 flocp);
1237 no_default_sh_exe = 0;
1239 else
1240 v = lookup_variable (varname, strlen (varname));
1242 if (tp)
1243 free (tp);
1246 else
1247 #endif
1249 /* If we are defining variables inside an $(eval ...), we might have a
1250 different variable context pushed, not the global context (maybe we're
1251 inside a $(call ...) or something. Since this function is only ever
1252 invoked in places where we want to define globally visible variables,
1253 make sure we define this variable in the global set. */
1255 v = define_variable_in_set (varname, strlen (varname), p,
1256 origin, flavor == f_recursive,
1257 (target_var
1258 ? current_variable_set_list->set : NULL),
1259 flocp);
1260 v->append = append;
1261 v->conditional = conditional;
1263 if (alloc_value)
1264 free (alloc_value);
1266 return v->special ? set_special_var (v) : v;
1269 /* Parse P (a null-terminated string) as a variable definition.
1271 If it is not a variable definition, return NULL.
1273 If it is a variable definition, return a pointer to the char after the
1274 assignment token and set *FLAVOR to the type of variable assignment. */
1276 char *
1277 parse_variable_definition (const char *p, enum variable_flavor *flavor)
1279 int wspace = 0;
1281 p = next_token (p);
1283 while (1)
1285 int c = *p++;
1287 /* If we find a comment or EOS, it's not a variable definition. */
1288 if (c == '\0' || c == '#')
1289 return NULL;
1291 if (c == '$')
1293 /* This begins a variable expansion reference. Make sure we don't
1294 treat chars inside the reference as assignment tokens. */
1295 char closeparen;
1296 int count;
1297 c = *p++;
1298 if (c == '(')
1299 closeparen = ')';
1300 else if (c == '{')
1301 closeparen = '}';
1302 else
1303 /* '$$' or '$X'. Either way, nothing special to do here. */
1304 continue;
1306 /* P now points past the opening paren or brace.
1307 Count parens or braces until it is matched. */
1308 count = 0;
1309 for (; *p != '\0'; ++p)
1311 if (*p == c)
1312 ++count;
1313 else if (*p == closeparen && --count < 0)
1315 ++p;
1316 break;
1319 continue;
1322 /* If we find whitespace skip it, and remember we found it. */
1323 if (isblank ((unsigned char)c))
1325 wspace = 1;
1326 p = next_token (p);
1327 c = *p;
1328 if (c == '\0')
1329 return NULL;
1330 ++p;
1334 if (c == '=')
1336 *flavor = f_recursive;
1337 return (char *)p;
1340 /* Match assignment variants (:=, +=, ?=) */
1341 if (*p == '=')
1343 switch (c)
1345 case ':':
1346 *flavor = f_simple;
1347 break;
1348 case '+':
1349 *flavor = f_append;
1350 break;
1351 case '?':
1352 *flavor = f_conditional;
1353 break;
1354 default:
1355 /* If we skipped whitespace, non-assignments means no var. */
1356 if (wspace)
1357 return NULL;
1359 /* Might be assignment, or might be $= or #=. Check. */
1360 continue;
1362 return (char *)++p;
1364 else if (c == ':')
1365 /* A colon other than := is a rule line, not a variable defn. */
1366 return NULL;
1368 /* If we skipped whitespace, non-assignments means no var. */
1369 if (wspace)
1370 return NULL;
1373 return (char *)p;
1376 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1378 If LINE was recognized as a variable definition, a pointer to its `struct
1379 variable' is returned. If LINE is not a variable definition, NULL is
1380 returned. */
1382 struct variable *
1383 assign_variable_definition (struct variable *v, char *line)
1385 char *beg;
1386 char *end;
1387 enum variable_flavor flavor;
1388 char *name;
1390 beg = next_token (line);
1391 line = parse_variable_definition (beg, &flavor);
1392 if (!line)
1393 return NULL;
1395 end = line - (flavor == f_recursive ? 1 : 2);
1396 while (end > beg && isblank ((unsigned char)end[-1]))
1397 --end;
1398 line = next_token (line);
1399 v->value = line;
1400 v->flavor = flavor;
1402 /* Expand the name, so "$(foo)bar = baz" works. */
1403 name = alloca (end - beg + 1);
1404 memcpy (name, beg, end - beg);
1405 name[end - beg] = '\0';
1406 v->name = allocated_variable_expand (name);
1408 if (v->name[0] == '\0')
1409 fatal (&v->fileinfo, _("empty variable name"));
1411 return v;
1414 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1416 ORIGIN may be o_file, o_override, o_env, o_env_override,
1417 or o_command specifying that the variable definition comes
1418 from a makefile, an override directive, the environment with
1419 or without the -e switch, or the command line.
1421 See the comments for assign_variable_definition().
1423 If LINE was recognized as a variable definition, a pointer to its `struct
1424 variable' is returned. If LINE is not a variable definition, NULL is
1425 returned. */
1427 struct variable *
1428 try_variable_definition (const struct floc *flocp, char *line,
1429 enum variable_origin origin, int target_var)
1431 struct variable v;
1432 struct variable *vp;
1434 if (flocp != 0)
1435 v.fileinfo = *flocp;
1436 else
1437 v.fileinfo.filenm = 0;
1439 if (!assign_variable_definition (&v, line))
1440 return 0;
1442 vp = do_variable_definition (flocp, v.name, v.value,
1443 origin, v.flavor, target_var);
1445 free (v.name);
1447 return vp;
1450 /* Print information for variable V, prefixing it with PREFIX. */
1452 static void
1453 print_variable (const void *item, void *arg)
1455 const struct variable *v = item;
1456 const char *prefix = arg;
1457 const char *origin;
1459 switch (v->origin)
1461 case o_default:
1462 origin = _("default");
1463 break;
1464 case o_env:
1465 origin = _("environment");
1466 break;
1467 case o_file:
1468 origin = _("makefile");
1469 break;
1470 case o_env_override:
1471 origin = _("environment under -e");
1472 break;
1473 case o_command:
1474 origin = _("command line");
1475 break;
1476 case o_override:
1477 origin = _("`override' directive");
1478 break;
1479 case o_automatic:
1480 origin = _("automatic");
1481 break;
1482 case o_invalid:
1483 default:
1484 abort ();
1486 fputs ("# ", stdout);
1487 fputs (origin, stdout);
1488 if (v->private_var)
1489 fputs (" private", stdout);
1490 if (v->fileinfo.filenm)
1491 printf (_(" (from `%s', line %lu)"),
1492 v->fileinfo.filenm, v->fileinfo.lineno);
1493 putchar ('\n');
1494 fputs (prefix, stdout);
1496 /* Is this a `define'? */
1497 if (v->recursive && strchr (v->value, '\n') != 0)
1498 printf ("define %s\n%s\nendef\n", v->name, v->value);
1499 else
1501 char *p;
1503 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1505 /* Check if the value is just whitespace. */
1506 p = next_token (v->value);
1507 if (p != v->value && *p == '\0')
1508 /* All whitespace. */
1509 printf ("$(subst ,,%s)", v->value);
1510 else if (v->recursive)
1511 fputs (v->value, stdout);
1512 else
1513 /* Double up dollar signs. */
1514 for (p = v->value; *p != '\0'; ++p)
1516 if (*p == '$')
1517 putchar ('$');
1518 putchar (*p);
1520 putchar ('\n');
1525 /* Print all the variables in SET. PREFIX is printed before
1526 the actual variable definitions (everything else is comments). */
1528 void
1529 print_variable_set (struct variable_set *set, char *prefix)
1531 hash_map_arg (&set->table, print_variable, prefix);
1533 fputs (_("# variable set hash-table stats:\n"), stdout);
1534 fputs ("# ", stdout);
1535 hash_print_stats (&set->table, stdout);
1536 putc ('\n', stdout);
1539 /* Print the data base of variables. */
1541 void
1542 print_variable_data_base (void)
1544 puts (_("\n# Variables\n"));
1546 print_variable_set (&global_variable_set, "");
1548 puts (_("\n# Pattern-specific Variable Values"));
1551 struct pattern_var *p;
1552 int rules = 0;
1554 for (p = pattern_vars; p != 0; p = p->next)
1556 ++rules;
1557 printf ("\n%s :\n", p->target);
1558 print_variable (&p->variable, "# ");
1561 if (rules == 0)
1562 puts (_("\n# No pattern-specific variable values."));
1563 else
1564 printf (_("\n# %u pattern-specific variable values"), rules);
1569 /* Print all the local variables of FILE. */
1571 void
1572 print_file_variables (const struct file *file)
1574 if (file->variables != 0)
1575 print_variable_set (file->variables->set, "# ");
1578 #ifdef WINDOWS32
1579 void
1580 sync_Path_environment (void)
1582 char *path = allocated_variable_expand ("$(PATH)");
1583 static char *environ_path = NULL;
1585 if (!path)
1586 return;
1589 * If done this before, don't leak memory unnecessarily.
1590 * Free the previous entry before allocating new one.
1592 if (environ_path)
1593 free (environ_path);
1596 * Create something WINDOWS32 world can grok
1598 convert_Path_to_windows32 (path, ';');
1599 environ_path = xstrdup (concat (3, "PATH", "=", path));
1600 putenv (environ_path);
1601 free (path);
1603 #endif