Manual typo.
[make.git] / variable.c
blob3dc8a2281a0bde787722bc37eb42fa7733f706a7
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 };
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 = savestring (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->export = v_default;
226 v->exportable = 1;
227 if (*name != '_' && (*name < 'A' || *name > 'Z')
228 && (*name < 'a' || *name > 'z'))
229 v->exportable = 0;
230 else
232 for (++name; *name != '\0'; ++name)
233 if (*name != '_' && (*name < 'a' || *name > 'z')
234 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
235 break;
237 if (*name != '\0')
238 v->exportable = 0;
241 return v;
244 /* If the variable passed in is "special", handle its special nature.
245 Currently there are two such variables, both used for introspection:
246 .VARIABLES expands to a list of all the variables defined in this instance
247 of make.
248 .TARGETS expands to a list of all the targets defined in this
249 instance of make.
250 Returns the variable reference passed in. */
252 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
254 static struct variable *
255 lookup_special_var (struct variable *var)
257 static unsigned long last_var_count = 0;
260 /* This one actually turns out to be very hard, due to the way the parser
261 records targets. The way it works is that target information is collected
262 internally until make knows the target is completely specified. It unitl
263 it sees that some new construct (a new target or variable) is defined that
264 it knows the previous one is done. In short, this means that if you do
265 this:
267 all:
269 TARGS := $(.TARGETS)
271 then $(TARGS) won't contain "all", because it's not until after the
272 variable is created that the previous target is completed.
274 Changing this would be a major pain. I think a less complex way to do it
275 would be to pre-define the target files as soon as the first line is
276 parsed, then come back and do the rest of the definition as now. That
277 would allow $(.TARGETS) to be correct without a major change to the way
278 the parser works.
280 if (streq (var->name, ".TARGETS"))
281 var->value = build_target_list (var->value);
282 else
285 if (streq (var->name, ".VARIABLES")
286 && global_variable_set.table.ht_fill != last_var_count)
288 unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
289 unsigned long len;
290 char *p;
291 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
292 struct variable **end = &vp[global_variable_set.table.ht_size];
294 /* Make sure we have at least MAX bytes in the allocated buffer. */
295 var->value = xrealloc (var->value, max);
297 /* Walk through the hash of variables, constructing a list of names. */
298 p = var->value;
299 len = 0;
300 for (; vp < end; ++vp)
301 if (!HASH_VACANT (*vp))
303 struct variable *v = *vp;
304 int l = v->length;
306 len += l + 1;
307 if (len > max)
309 unsigned long off = p - var->value;
311 max += EXPANSION_INCREMENT (l + 1);
312 var->value = xrealloc (var->value, max);
313 p = &var->value[off];
316 memcpy (p, v->name, l);
317 p += l;
318 *(p++) = ' ';
320 *(p-1) = '\0';
322 /* Remember how many variables are in our current count. Since we never
323 remove variables from the list, this is a reliable way to know whether
324 the list is up to date or needs to be recomputed. */
326 last_var_count = global_variable_set.table.ht_fill;
329 return var;
333 /* Lookup a variable whose name is a string starting at NAME
334 and with LENGTH chars. NAME need not be null-terminated.
335 Returns address of the `struct variable' containing all info
336 on the variable, or nil if no such variable is defined. */
338 struct variable *
339 lookup_variable (const char *name, unsigned int length)
341 const struct variable_set_list *setlist;
342 struct variable var_key;
344 var_key.name = (char *) name;
345 var_key.length = length;
347 for (setlist = current_variable_set_list;
348 setlist != 0; setlist = setlist->next)
350 const struct variable_set *set = setlist->set;
351 struct variable *v;
353 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
354 if (v)
355 return v->special ? lookup_special_var (v) : v;
358 #ifdef VMS
359 /* since we don't read envp[] on startup, try to get the
360 variable via getenv() here. */
362 char *vname = alloca (length + 1);
363 char *value;
364 strncpy (vname, name, length);
365 vname[length] = 0;
366 value = getenv (vname);
367 if (value != 0)
369 char *sptr;
370 int scnt;
372 sptr = value;
373 scnt = 0;
375 while ((sptr = strchr (sptr, '$')))
377 scnt++;
378 sptr++;
381 if (scnt > 0)
383 char *nvalue;
384 char *nptr;
386 nvalue = alloca (strlen (value) + scnt + 1);
387 sptr = value;
388 nptr = nvalue;
390 while (*sptr)
392 if (*sptr == '$')
394 *nptr++ = '$';
395 *nptr++ = '$';
397 else
399 *nptr++ = *sptr;
401 sptr++;
404 *nptr = '\0';
405 return define_variable (vname, length, nvalue, o_env, 1);
409 return define_variable (vname, length, value, o_env, 1);
412 #endif /* VMS */
414 return 0;
417 /* Lookup a variable whose name is a string starting at NAME
418 and with LENGTH chars in set SET. NAME need not be null-terminated.
419 Returns address of the `struct variable' containing all info
420 on the variable, or nil if no such variable is defined. */
422 struct variable *
423 lookup_variable_in_set (const char *name, unsigned int length,
424 const struct variable_set *set)
426 struct variable var_key;
428 var_key.name = (char *) name;
429 var_key.length = length;
431 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
434 /* Initialize FILE's variable set list. If FILE already has a variable set
435 list, the topmost variable set is left intact, but the the rest of the
436 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
437 rule, then we will use the "root" double-colon target's variable set as the
438 parent of FILE's variable set.
440 If we're READING a makefile, don't do the pattern variable search now,
441 since the pattern variable might not have been defined yet. */
443 void
444 initialize_file_variables (struct file *file, int reading)
446 struct variable_set_list *l = file->variables;
448 if (l == 0)
450 l = (struct variable_set_list *)
451 xmalloc (sizeof (struct variable_set_list));
452 l->set = xmalloc (sizeof (struct variable_set));
453 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
454 variable_hash_1, variable_hash_2, variable_hash_cmp);
455 file->variables = l;
458 /* If this is a double-colon, then our "parent" is the "root" target for
459 this double-colon rule. Since that rule has the same name, parent,
460 etc. we can just use its variables as the "next" for ours. */
462 if (file->double_colon && file->double_colon != file)
464 initialize_file_variables (file->double_colon, reading);
465 l->next = file->double_colon->variables;
466 return;
469 if (file->parent == 0)
470 l->next = &global_setlist;
471 else
473 initialize_file_variables (file->parent, reading);
474 l->next = file->parent->variables;
477 /* If we're not reading makefiles and we haven't looked yet, see if
478 we can find pattern variables for this target. */
480 if (!reading && !file->pat_searched)
482 struct pattern_var *p;
484 p = lookup_pattern_var (0, file->name);
485 if (p != 0)
487 struct variable_set_list *global = current_variable_set_list;
489 /* We found at least one. Set up a new variable set to accumulate
490 all the pattern variables that match this target. */
492 file->pat_variables = create_new_variable_set ();
493 current_variable_set_list = file->pat_variables;
497 /* We found one, so insert it into the set. */
499 struct variable *v;
501 if (p->variable.flavor == f_simple)
503 v = define_variable_loc (
504 p->variable.name, strlen (p->variable.name),
505 p->variable.value, p->variable.origin,
506 0, &p->variable.fileinfo);
508 v->flavor = f_simple;
510 else
512 v = do_variable_definition (
513 &p->variable.fileinfo, p->variable.name,
514 p->variable.value, p->variable.origin,
515 p->variable.flavor, 1);
518 /* Also mark it as a per-target and copy export status. */
519 v->per_target = p->variable.per_target;
520 v->export = p->variable.export;
522 while ((p = lookup_pattern_var (p, file->name)) != 0);
524 current_variable_set_list = global;
526 file->pat_searched = 1;
529 /* If we have a pattern variable match, set it up. */
531 if (file->pat_variables != 0)
533 file->pat_variables->next = l->next;
534 l->next = file->pat_variables;
538 /* Pop the top set off the current variable set list,
539 and free all its storage. */
541 struct variable_set_list *
542 create_new_variable_set (void)
544 register struct variable_set_list *setlist;
545 register struct variable_set *set;
547 set = xmalloc (sizeof (struct variable_set));
548 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
549 variable_hash_1, variable_hash_2, variable_hash_cmp);
551 setlist = (struct variable_set_list *)
552 xmalloc (sizeof (struct variable_set_list));
553 setlist->set = set;
554 setlist->next = current_variable_set_list;
556 return setlist;
559 static void
560 free_variable_name_and_value (const void *item)
562 struct variable *v = (struct variable *) item;
563 free (v->name);
564 free (v->value);
567 void
568 free_variable_set (struct variable_set_list *list)
570 hash_map (&list->set->table, free_variable_name_and_value);
571 hash_free (&list->set->table, 1);
572 free (list->set);
573 free (list);
576 /* Create a new variable set and push it on the current setlist.
577 If we're pushing a global scope (that is, the current scope is the global
578 scope) then we need to "push" it the other way: file variable sets point
579 directly to the global_setlist so we need to replace that with the new one.
582 struct variable_set_list *
583 push_new_variable_scope (void)
585 current_variable_set_list = create_new_variable_set();
586 if (current_variable_set_list->next == &global_setlist)
588 /* It was the global, so instead of new -> &global we want to replace
589 &global with the new one and have &global -> new, with current still
590 pointing to &global */
591 struct variable_set *set = current_variable_set_list->set;
592 current_variable_set_list->set = global_setlist.set;
593 global_setlist.set = set;
594 current_variable_set_list->next = global_setlist.next;
595 global_setlist.next = current_variable_set_list;
596 current_variable_set_list = &global_setlist;
598 return (current_variable_set_list);
601 void
602 pop_variable_scope (void)
604 struct variable_set_list *setlist;
605 struct variable_set *set;
607 /* Can't call this if there's no scope to pop! */
608 assert(current_variable_set_list->next != NULL);
610 if (current_variable_set_list != &global_setlist)
612 /* We're not pointing to the global setlist, so pop this one. */
613 setlist = current_variable_set_list;
614 set = setlist->set;
615 current_variable_set_list = setlist->next;
617 else
619 /* This set is the one in the global_setlist, but there is another global
620 set beyond that. We want to copy that set to global_setlist, then
621 delete what used to be in global_setlist. */
622 setlist = global_setlist.next;
623 set = global_setlist.set;
624 global_setlist.set = setlist->set;
625 global_setlist.next = setlist->next;
628 /* Free the one we no longer need. */
629 free (setlist);
630 hash_map (&set->table, free_variable_name_and_value);
631 hash_free (&set->table, 1);
632 free (set);
635 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
637 static void
638 merge_variable_sets (struct variable_set *to_set,
639 struct variable_set *from_set)
641 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
642 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
644 for ( ; from_var_slot < from_var_end; from_var_slot++)
645 if (! HASH_VACANT (*from_var_slot))
647 struct variable *from_var = *from_var_slot;
648 struct variable **to_var_slot
649 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
650 if (HASH_VACANT (*to_var_slot))
651 hash_insert_at (&to_set->table, from_var, to_var_slot);
652 else
654 /* GKM FIXME: delete in from_set->table */
655 free (from_var->value);
656 free (from_var);
661 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
663 void
664 merge_variable_set_lists (struct variable_set_list **setlist0,
665 struct variable_set_list *setlist1)
667 struct variable_set_list *to = *setlist0;
668 struct variable_set_list *last0 = 0;
670 /* If there's nothing to merge, stop now. */
671 if (!setlist1)
672 return;
674 /* This loop relies on the fact that all setlists terminate with the global
675 setlist (before NULL). If that's not true, arguably we SHOULD die. */
676 if (to)
677 while (setlist1 != &global_setlist && to != &global_setlist)
679 struct variable_set_list *from = setlist1;
680 setlist1 = setlist1->next;
682 merge_variable_sets (to->set, from->set);
684 last0 = to;
685 to = to->next;
688 if (setlist1 != &global_setlist)
690 if (last0 == 0)
691 *setlist0 = setlist1;
692 else
693 last0->next = setlist1;
697 /* Define the automatic variables, and record the addresses
698 of their structures so we can change their values quickly. */
700 void
701 define_automatic_variables (void)
703 #if defined(WINDOWS32) || defined(__EMX__)
704 extern char* default_shell;
705 #else
706 extern char default_shell[];
707 #endif
708 register struct variable *v;
709 char buf[200];
711 sprintf (buf, "%u", makelevel);
712 (void) define_variable (MAKELEVEL_NAME, MAKELEVEL_LENGTH, buf, o_env, 0);
714 sprintf (buf, "%s%s%s",
715 version_string,
716 (remote_description == 0 || remote_description[0] == '\0')
717 ? "" : "-",
718 (remote_description == 0 || remote_description[0] == '\0')
719 ? "" : remote_description);
720 (void) define_variable ("MAKE_VERSION", 12, buf, o_default, 0);
722 #ifdef __MSDOS__
723 /* Allow to specify a special shell just for Make,
724 and use $COMSPEC as the default $SHELL when appropriate. */
726 static char shell_str[] = "SHELL";
727 const int shlen = sizeof (shell_str) - 1;
728 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
729 struct variable *comp = lookup_variable ("COMSPEC", 7);
731 /* Make $MAKESHELL override $SHELL even if -e is in effect. */
732 if (mshp)
733 (void) define_variable (shell_str, shlen,
734 mshp->value, o_env_override, 0);
735 else if (comp)
737 /* $COMSPEC shouldn't override $SHELL. */
738 struct variable *shp = lookup_variable (shell_str, shlen);
740 if (!shp)
741 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
744 #elif defined(__EMX__)
746 static char shell_str[] = "SHELL";
747 const int shlen = sizeof (shell_str) - 1;
748 struct variable *shell = lookup_variable (shell_str, shlen);
749 struct variable *replace = lookup_variable ("MAKESHELL", 9);
751 /* if $MAKESHELL is defined in the environment assume o_env_override */
752 if (replace && *replace->value && replace->origin == o_env)
753 replace->origin = o_env_override;
755 /* if $MAKESHELL is not defined use $SHELL but only if the variable
756 did not come from the environment */
757 if (!replace || !*replace->value)
758 if (shell && *shell->value && (shell->origin == o_env
759 || shell->origin == o_env_override))
761 /* overwrite whatever we got from the environment */
762 free(shell->value);
763 shell->value = xstrdup (default_shell);
764 shell->origin = o_default;
767 /* Some people do not like cmd to be used as the default
768 if $SHELL is not defined in the Makefile.
769 With -DNO_CMD_DEFAULT you can turn off this behaviour */
770 # ifndef NO_CMD_DEFAULT
771 /* otherwise use $COMSPEC */
772 if (!replace || !*replace->value)
773 replace = lookup_variable ("COMSPEC", 7);
775 /* otherwise use $OS2_SHELL */
776 if (!replace || !*replace->value)
777 replace = lookup_variable ("OS2_SHELL", 9);
778 # else
779 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
780 # endif
782 if (replace && *replace->value)
783 /* overwrite $SHELL */
784 (void) define_variable (shell_str, shlen, replace->value,
785 replace->origin, 0);
786 else
787 /* provide a definition if there is none */
788 (void) define_variable (shell_str, shlen, default_shell,
789 o_default, 0);
792 #endif
794 /* This won't override any definition, but it will provide one if there
795 isn't one there. */
796 v = define_variable ("SHELL", 5, default_shell, o_default, 0);
797 #ifdef __MSDOS__
798 v->export = v_export; /* Export always SHELL. */
799 #endif
801 /* On MSDOS we do use SHELL from environment, since it isn't a standard
802 environment variable on MSDOS, so whoever sets it, does that on purpose.
803 On OS/2 we do not use SHELL from environment but we have already handled
804 that problem above. */
805 #if !defined(__MSDOS__) && !defined(__EMX__)
806 /* Don't let SHELL come from the environment. */
807 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
809 free (v->value);
810 v->origin = o_file;
811 v->value = xstrdup (default_shell);
813 #endif
815 /* Make sure MAKEFILES gets exported if it is set. */
816 v = define_variable ("MAKEFILES", 9, "", o_default, 0);
817 v->export = v_ifset;
819 /* Define the magic D and F variables in terms of
820 the automatic variables they are variations of. */
822 #ifdef VMS
823 define_variable ("@D", 2, "$(dir $@)", o_automatic, 1);
824 define_variable ("%D", 2, "$(dir $%)", o_automatic, 1);
825 define_variable ("*D", 2, "$(dir $*)", o_automatic, 1);
826 define_variable ("<D", 2, "$(dir $<)", o_automatic, 1);
827 define_variable ("?D", 2, "$(dir $?)", o_automatic, 1);
828 define_variable ("^D", 2, "$(dir $^)", o_automatic, 1);
829 define_variable ("+D", 2, "$(dir $+)", o_automatic, 1);
830 #else
831 define_variable ("@D", 2, "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
832 define_variable ("%D", 2, "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
833 define_variable ("*D", 2, "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
834 define_variable ("<D", 2, "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
835 define_variable ("?D", 2, "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
836 define_variable ("^D", 2, "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
837 define_variable ("+D", 2, "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
838 #endif
839 define_variable ("@F", 2, "$(notdir $@)", o_automatic, 1);
840 define_variable ("%F", 2, "$(notdir $%)", o_automatic, 1);
841 define_variable ("*F", 2, "$(notdir $*)", o_automatic, 1);
842 define_variable ("<F", 2, "$(notdir $<)", o_automatic, 1);
843 define_variable ("?F", 2, "$(notdir $?)", o_automatic, 1);
844 define_variable ("^F", 2, "$(notdir $^)", o_automatic, 1);
845 define_variable ("+F", 2, "$(notdir $+)", o_automatic, 1);
848 int export_all_variables;
850 /* Create a new environment for FILE's commands.
851 If FILE is nil, this is for the `shell' function.
852 The child's MAKELEVEL variable is incremented. */
854 char **
855 target_environment (struct file *file)
857 struct variable_set_list *set_list;
858 register struct variable_set_list *s;
859 struct hash_table table;
860 struct variable **v_slot;
861 struct variable **v_end;
862 struct variable makelevel_key;
863 char **result_0;
864 char **result;
866 if (file == 0)
867 set_list = current_variable_set_list;
868 else
869 set_list = file->variables;
871 hash_init (&table, VARIABLE_BUCKETS,
872 variable_hash_1, variable_hash_2, variable_hash_cmp);
874 /* Run through all the variable sets in the list,
875 accumulating variables in TABLE. */
876 for (s = set_list; s != 0; s = s->next)
878 struct variable_set *set = s->set;
879 v_slot = (struct variable **) set->table.ht_vec;
880 v_end = v_slot + set->table.ht_size;
881 for ( ; v_slot < v_end; v_slot++)
882 if (! HASH_VACANT (*v_slot))
884 struct variable **new_slot;
885 struct variable *v = *v_slot;
887 /* If this is a per-target variable and it hasn't been touched
888 already then look up the global version and take its export
889 value. */
890 if (v->per_target && v->export == v_default)
892 struct variable *gv;
894 gv = lookup_variable_in_set (v->name, strlen(v->name),
895 &global_variable_set);
896 if (gv)
897 v->export = gv->export;
900 switch (v->export)
902 case v_default:
903 if (v->origin == o_default || v->origin == o_automatic)
904 /* Only export default variables by explicit request. */
905 continue;
907 /* The variable doesn't have a name that can be exported. */
908 if (! v->exportable)
909 continue;
911 if (! export_all_variables
912 && v->origin != o_command
913 && v->origin != o_env && v->origin != o_env_override)
914 continue;
915 break;
917 case v_export:
918 break;
920 case v_noexport:
922 /* If this is the SHELL variable and it's not exported,
923 then add the value from our original environment, if
924 the original environment defined a value for SHELL. */
925 extern struct variable shell_var;
926 if (streq (v->name, "SHELL") && shell_var.value)
928 v = &shell_var;
929 break;
931 continue;
934 case v_ifset:
935 if (v->origin == o_default)
936 continue;
937 break;
940 new_slot = (struct variable **) hash_find_slot (&table, v);
941 if (HASH_VACANT (*new_slot))
942 hash_insert_at (&table, v, new_slot);
946 makelevel_key.name = MAKELEVEL_NAME;
947 makelevel_key.length = MAKELEVEL_LENGTH;
948 hash_delete (&table, &makelevel_key);
950 result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
952 v_slot = (struct variable **) table.ht_vec;
953 v_end = v_slot + table.ht_size;
954 for ( ; v_slot < v_end; v_slot++)
955 if (! HASH_VACANT (*v_slot))
957 struct variable *v = *v_slot;
959 /* If V is recursively expanded and didn't come from the environment,
960 expand its value. If it came from the environment, it should
961 go back into the environment unchanged. */
962 if (v->recursive
963 && v->origin != o_env && v->origin != o_env_override)
965 char *value = recursively_expand_for_file (v, file);
966 #ifdef WINDOWS32
967 if (strcmp(v->name, "Path") == 0 ||
968 strcmp(v->name, "PATH") == 0)
969 convert_Path_to_windows32(value, ';');
970 #endif
971 *result++ = xstrdup (concat (v->name, "=", value));
972 free (value);
974 else
976 #ifdef WINDOWS32
977 if (strcmp(v->name, "Path") == 0 ||
978 strcmp(v->name, "PATH") == 0)
979 convert_Path_to_windows32(v->value, ';');
980 #endif
981 *result++ = xstrdup (concat (v->name, "=", v->value));
985 *result = xmalloc (100);
986 sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
987 *++result = 0;
989 hash_free (&table, 0);
991 return result_0;
994 static struct variable *
995 set_special_var (struct variable *var)
997 if (streq (var->name, RECIPEPREFIX_NAME))
999 /* The user is resetting the command introduction prefix. This has to
1000 happen immediately, so that subsequent rules are interpreted
1001 properly. */
1002 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1005 return var;
1008 /* Given a variable, a value, and a flavor, define the variable.
1009 See the try_variable_definition() function for details on the parameters. */
1011 struct variable *
1012 do_variable_definition (const struct floc *flocp, const char *varname,
1013 const char *value, enum variable_origin origin,
1014 enum variable_flavor flavor, int target_var)
1016 const char *p;
1017 char *alloc_value = NULL;
1018 struct variable *v;
1019 int append = 0;
1020 int conditional = 0;
1022 /* Calculate the variable's new value in VALUE. */
1024 switch (flavor)
1026 default:
1027 case f_bogus:
1028 /* Should not be possible. */
1029 abort ();
1030 case f_simple:
1031 /* A simple variable definition "var := value". Expand the value.
1032 We have to allocate memory since otherwise it'll clobber the
1033 variable buffer, and we may still need that if we're looking at a
1034 target-specific variable. */
1035 p = alloc_value = allocated_variable_expand (value);
1036 break;
1037 case f_conditional:
1038 /* A conditional variable definition "var ?= value".
1039 The value is set IFF the variable is not defined yet. */
1040 v = lookup_variable (varname, strlen (varname));
1041 if (v)
1042 return v->special ? set_special_var (v) : v;
1044 conditional = 1;
1045 flavor = f_recursive;
1046 /* FALLTHROUGH */
1047 case f_recursive:
1048 /* A recursive variable definition "var = value".
1049 The value is used verbatim. */
1050 p = value;
1051 break;
1052 case f_append:
1054 /* If we have += but we're in a target variable context, we want to
1055 append only with other variables in the context of this target. */
1056 if (target_var)
1058 append = 1;
1059 v = lookup_variable_in_set (varname, strlen (varname),
1060 current_variable_set_list->set);
1062 /* Don't append from the global set if a previous non-appending
1063 target-specific variable definition exists. */
1064 if (v && !v->append)
1065 append = 0;
1067 else
1068 v = lookup_variable (varname, strlen (varname));
1070 if (v == 0)
1072 /* There was no old value.
1073 This becomes a normal recursive definition. */
1074 p = value;
1075 flavor = f_recursive;
1077 else
1079 /* Paste the old and new values together in VALUE. */
1081 unsigned int oldlen, vallen;
1082 const char *val;
1083 char *tp;
1085 val = value;
1086 if (v->recursive)
1087 /* The previous definition of the variable was recursive.
1088 The new value is the unexpanded old and new values. */
1089 flavor = f_recursive;
1090 else
1091 /* The previous definition of the variable was simple.
1092 The new value comes from the old value, which was expanded
1093 when it was set; and from the expanded new value. Allocate
1094 memory for the expansion as we may still need the rest of the
1095 buffer if we're looking at a target-specific variable. */
1096 val = alloc_value = allocated_variable_expand (val);
1098 oldlen = strlen (v->value);
1099 vallen = strlen (val);
1100 tp = alloca (oldlen + 1 + vallen + 1);
1101 memcpy (tp, v->value, oldlen);
1102 tp[oldlen] = ' ';
1103 memcpy (&tp[oldlen + 1], val, vallen + 1);
1104 p = tp;
1109 #ifdef __MSDOS__
1110 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1111 non-Unix systems don't conform to this default configuration (in
1112 fact, most of them don't even have `/bin'). On the other hand,
1113 $SHELL in the environment, if set, points to the real pathname of
1114 the shell.
1115 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1116 the Makefile override $SHELL from the environment. But first, we
1117 look for the basename of the shell in the directory where SHELL=
1118 points, and along the $PATH; if it is found in any of these places,
1119 we define $SHELL to be the actual pathname of the shell. Thus, if
1120 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1121 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1122 defining SHELL to be "d:/unix/bash.exe". */
1123 if ((origin == o_file || origin == o_override)
1124 && strcmp (varname, "SHELL") == 0)
1126 PATH_VAR (shellpath);
1127 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1129 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1130 if (__dosexec_find_on_path (p, NULL, shellpath))
1132 char *tp;
1134 for (tp = shellpath; *tp; tp++)
1135 if (*tp == '\\')
1136 *tp = '/';
1138 v = define_variable_loc (varname, strlen (varname),
1139 shellpath, origin, flavor == f_recursive,
1140 flocp);
1142 else
1144 const char *shellbase, *bslash;
1145 struct variable *pathv = lookup_variable ("PATH", 4);
1146 char *path_string;
1147 char *fake_env[2];
1148 size_t pathlen = 0;
1150 shellbase = strrchr (p, '/');
1151 bslash = strrchr (p, '\\');
1152 if (!shellbase || bslash > shellbase)
1153 shellbase = bslash;
1154 if (!shellbase && p[1] == ':')
1155 shellbase = p + 1;
1156 if (shellbase)
1157 shellbase++;
1158 else
1159 shellbase = p;
1161 /* Search for the basename of the shell (with standard
1162 executable extensions) along the $PATH. */
1163 if (pathv)
1164 pathlen = strlen (pathv->value);
1165 path_string = xmalloc (5 + pathlen + 2 + 1);
1166 /* On MSDOS, current directory is considered as part of $PATH. */
1167 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1168 fake_env[0] = path_string;
1169 fake_env[1] = 0;
1170 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1172 char *tp;
1174 for (tp = shellpath; *tp; tp++)
1175 if (*tp == '\\')
1176 *tp = '/';
1178 v = define_variable_loc (varname, strlen (varname),
1179 shellpath, origin,
1180 flavor == f_recursive, flocp);
1182 else
1183 v = lookup_variable (varname, strlen (varname));
1185 free (path_string);
1188 else
1189 #endif /* __MSDOS__ */
1190 #ifdef WINDOWS32
1191 if ((origin == o_file || origin == o_override || origin == o_command)
1192 && streq (varname, "SHELL"))
1194 extern char *default_shell;
1196 /* Call shell locator function. If it returns TRUE, then
1197 set no_default_sh_exe to indicate sh was found and
1198 set new value for SHELL variable. */
1200 if (find_and_set_default_shell (p))
1202 v = define_variable_in_set (varname, strlen (varname), default_shell,
1203 origin, flavor == f_recursive,
1204 (target_var
1205 ? current_variable_set_list->set
1206 : NULL),
1207 flocp);
1208 no_default_sh_exe = 0;
1210 else
1212 if (alloc_value)
1213 free (alloc_value);
1215 alloc_value = allocated_variable_expand (p);
1216 if (find_and_set_default_shell (alloc_value))
1218 v = define_variable_in_set (varname, strlen (varname), p,
1219 origin, flavor == f_recursive,
1220 (target_var
1221 ? current_variable_set_list->set
1222 : NULL),
1223 flocp);
1224 no_default_sh_exe = 0;
1226 else
1227 v = lookup_variable (varname, strlen (varname));
1230 else
1231 #endif
1233 /* If we are defining variables inside an $(eval ...), we might have a
1234 different variable context pushed, not the global context (maybe we're
1235 inside a $(call ...) or something. Since this function is only ever
1236 invoked in places where we want to define globally visible variables,
1237 make sure we define this variable in the global set. */
1239 v = define_variable_in_set (varname, strlen (varname), p,
1240 origin, flavor == f_recursive,
1241 (target_var
1242 ? current_variable_set_list->set : NULL),
1243 flocp);
1244 v->append = append;
1245 v->conditional = conditional;
1247 if (alloc_value)
1248 free (alloc_value);
1250 return v->special ? set_special_var (v) : v;
1253 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1255 ORIGIN may be o_file, o_override, o_env, o_env_override,
1256 or o_command specifying that the variable definition comes
1257 from a makefile, an override directive, the environment with
1258 or without the -e switch, or the command line.
1260 See the comments for parse_variable_definition().
1262 If LINE was recognized as a variable definition, a pointer to its `struct
1263 variable' is returned. If LINE is not a variable definition, NULL is
1264 returned. */
1266 struct variable *
1267 parse_variable_definition (struct variable *v, char *line)
1269 register int c;
1270 register char *p = line;
1271 register char *beg;
1272 register char *end;
1273 enum variable_flavor flavor = f_bogus;
1274 char *name;
1276 while (1)
1278 c = *p++;
1279 if (c == '\0' || c == '#')
1280 return 0;
1281 if (c == '=')
1283 end = p - 1;
1284 flavor = f_recursive;
1285 break;
1287 else if (c == ':')
1288 if (*p == '=')
1290 end = p++ - 1;
1291 flavor = f_simple;
1292 break;
1294 else
1295 /* A colon other than := is a rule line, not a variable defn. */
1296 return 0;
1297 else if (c == '+' && *p == '=')
1299 end = p++ - 1;
1300 flavor = f_append;
1301 break;
1303 else if (c == '?' && *p == '=')
1305 end = p++ - 1;
1306 flavor = f_conditional;
1307 break;
1309 else if (c == '$')
1311 /* This might begin a variable expansion reference. Make sure we
1312 don't misrecognize chars inside the reference as =, := or +=. */
1313 char closeparen;
1314 int count;
1315 c = *p++;
1316 if (c == '(')
1317 closeparen = ')';
1318 else if (c == '{')
1319 closeparen = '}';
1320 else
1321 continue; /* Nope. */
1323 /* P now points past the opening paren or brace.
1324 Count parens or braces until it is matched. */
1325 count = 0;
1326 for (; *p != '\0'; ++p)
1328 if (*p == c)
1329 ++count;
1330 else if (*p == closeparen && --count < 0)
1332 ++p;
1333 break;
1338 v->flavor = flavor;
1340 beg = next_token (line);
1341 while (end > beg && isblank ((unsigned char)end[-1]))
1342 --end;
1343 p = next_token (p);
1344 v->value = p;
1346 /* Expand the name, so "$(foo)bar = baz" works. */
1347 name = alloca (end - beg + 1);
1348 memcpy (name, beg, end - beg);
1349 name[end - beg] = '\0';
1350 v->name = allocated_variable_expand (name);
1352 if (v->name[0] == '\0')
1353 fatal (&v->fileinfo, _("empty variable name"));
1355 return v;
1358 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1360 ORIGIN may be o_file, o_override, o_env, o_env_override,
1361 or o_command specifying that the variable definition comes
1362 from a makefile, an override directive, the environment with
1363 or without the -e switch, or the command line.
1365 See the comments for parse_variable_definition().
1367 If LINE was recognized as a variable definition, a pointer to its `struct
1368 variable' is returned. If LINE is not a variable definition, NULL is
1369 returned. */
1371 struct variable *
1372 try_variable_definition (const struct floc *flocp, char *line,
1373 enum variable_origin origin, int target_var)
1375 struct variable v;
1376 struct variable *vp;
1378 if (flocp != 0)
1379 v.fileinfo = *flocp;
1380 else
1381 v.fileinfo.filenm = 0;
1383 if (!parse_variable_definition (&v, line))
1384 return 0;
1386 vp = do_variable_definition (flocp, v.name, v.value,
1387 origin, v.flavor, target_var);
1389 free (v.name);
1391 return vp;
1394 /* Print information for variable V, prefixing it with PREFIX. */
1396 static void
1397 print_variable (const void *item, void *arg)
1399 const struct variable *v = item;
1400 const char *prefix = arg;
1401 const char *origin;
1403 switch (v->origin)
1405 case o_default:
1406 origin = _("default");
1407 break;
1408 case o_env:
1409 origin = _("environment");
1410 break;
1411 case o_file:
1412 origin = _("makefile");
1413 break;
1414 case o_env_override:
1415 origin = _("environment under -e");
1416 break;
1417 case o_command:
1418 origin = _("command line");
1419 break;
1420 case o_override:
1421 origin = _("`override' directive");
1422 break;
1423 case o_automatic:
1424 origin = _("automatic");
1425 break;
1426 case o_invalid:
1427 default:
1428 abort ();
1430 fputs ("# ", stdout);
1431 fputs (origin, stdout);
1432 if (v->fileinfo.filenm)
1433 printf (_(" (from `%s', line %lu)"),
1434 v->fileinfo.filenm, v->fileinfo.lineno);
1435 putchar ('\n');
1436 fputs (prefix, stdout);
1438 /* Is this a `define'? */
1439 if (v->recursive && strchr (v->value, '\n') != 0)
1440 printf ("define %s\n%s\nendef\n", v->name, v->value);
1441 else
1443 register char *p;
1445 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1447 /* Check if the value is just whitespace. */
1448 p = next_token (v->value);
1449 if (p != v->value && *p == '\0')
1450 /* All whitespace. */
1451 printf ("$(subst ,,%s)", v->value);
1452 else if (v->recursive)
1453 fputs (v->value, stdout);
1454 else
1455 /* Double up dollar signs. */
1456 for (p = v->value; *p != '\0'; ++p)
1458 if (*p == '$')
1459 putchar ('$');
1460 putchar (*p);
1462 putchar ('\n');
1467 /* Print all the variables in SET. PREFIX is printed before
1468 the actual variable definitions (everything else is comments). */
1470 void
1471 print_variable_set (struct variable_set *set, char *prefix)
1473 hash_map_arg (&set->table, print_variable, prefix);
1475 fputs (_("# variable set hash-table stats:\n"), stdout);
1476 fputs ("# ", stdout);
1477 hash_print_stats (&set->table, stdout);
1478 putc ('\n', stdout);
1481 /* Print the data base of variables. */
1483 void
1484 print_variable_data_base (void)
1486 puts (_("\n# Variables\n"));
1488 print_variable_set (&global_variable_set, "");
1490 puts (_("\n# Pattern-specific Variable Values"));
1493 struct pattern_var *p;
1494 int rules = 0;
1496 for (p = pattern_vars; p != 0; p = p->next)
1498 ++rules;
1499 printf ("\n%s :\n", p->target);
1500 print_variable (&p->variable, "# ");
1503 if (rules == 0)
1504 puts (_("\n# No pattern-specific variable values."));
1505 else
1506 printf (_("\n# %u pattern-specific variable values"), rules);
1511 /* Print all the local variables of FILE. */
1513 void
1514 print_file_variables (const struct file *file)
1516 if (file->variables != 0)
1517 print_variable_set (file->variables->set, "# ");
1520 #ifdef WINDOWS32
1521 void
1522 sync_Path_environment (void)
1524 char *path = allocated_variable_expand ("$(PATH)");
1525 static char *environ_path = NULL;
1527 if (!path)
1528 return;
1531 * If done this before, don't leak memory unnecessarily.
1532 * Free the previous entry before allocating new one.
1534 if (environ_path)
1535 free (environ_path);
1538 * Create something WINDOWS32 world can grok
1540 convert_Path_to_windows32 (path, ';');
1541 environ_path = xstrdup (concat ("PATH", "=", path));
1542 putenv (environ_path);
1543 free (path);
1545 #endif