- Include <alloca.h> even on non-__GNUC__ systems.
[make.git] / variable.c
blob6a74dcd6c59876c15d689afaa2f65f6bd783da0f
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 the last struct in the pack of a specific size, from 1 to 255.*/
40 static struct pattern_var *last_pattern_vars[256];
42 /* Create a new pattern-specific variable struct. The new variable is
43 inserted into the PATTERN_VARS list in the shortest patterns first
44 order to support the shortest stem matching (the variables are
45 matched in the reverse order so the ones with the longest pattern
46 will be considered first). Variables with the same pattern length
47 are inserted in the definition order. */
49 struct pattern_var *
50 create_pattern_var (const char *target, const char *suffix)
52 register unsigned int len = strlen (target);
53 register struct pattern_var *p = xmalloc (sizeof (struct pattern_var));
55 if (pattern_vars != 0)
57 if (len < 256 && last_pattern_vars[len] != 0)
59 p->next = last_pattern_vars[len]->next;
60 last_pattern_vars[len]->next = p;
62 else
64 /* Find the position where we can insert this variable. */
65 register struct pattern_var **v;
67 for (v = &pattern_vars; ; v = &(*v)->next)
69 /* Insert at the end of the pack so that patterns with the
70 same length appear in the order they were defined .*/
72 if (*v == 0 || (*v)->len > len)
74 p->next = *v;
75 *v = p;
76 break;
81 else
83 pattern_vars = p;
84 p->next = 0;
87 p->target = target;
88 p->len = len;
89 p->suffix = suffix + 1;
91 if (len < 256)
92 last_pattern_vars[len] = p;
94 return p;
97 /* Look up a target in the pattern-specific variable list. */
99 static struct pattern_var *
100 lookup_pattern_var (struct pattern_var *start, const char *target)
102 struct pattern_var *p;
103 unsigned int targlen = strlen(target);
105 for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
107 const char *stem;
108 unsigned int stemlen;
110 if (p->len > targlen)
111 /* It can't possibly match. */
112 continue;
114 /* From the lengths of the filename and the pattern parts,
115 find the stem: the part of the filename that matches the %. */
116 stem = target + (p->suffix - p->target - 1);
117 stemlen = targlen - p->len + 1;
119 /* Compare the text in the pattern before the stem, if any. */
120 if (stem > target && !strneq (p->target, target, stem - target))
121 continue;
123 /* Compare the text in the pattern after the stem, if any.
124 We could test simply using streq, but this way we compare the
125 first two characters immediately. This saves time in the very
126 common case where the first character matches because it is a
127 period. */
128 if (*p->suffix == stem[stemlen]
129 && (*p->suffix == '\0' || streq (&p->suffix[1], &stem[stemlen+1])))
130 break;
133 return p;
136 /* Hash table of all global variable definitions. */
138 static unsigned long
139 variable_hash_1 (const void *keyv)
141 struct variable const *key = (struct variable const *) keyv;
142 return_STRING_N_HASH_1 (key->name, key->length);
145 static unsigned long
146 variable_hash_2 (const void *keyv)
148 struct variable const *key = (struct variable const *) keyv;
149 return_STRING_N_HASH_2 (key->name, key->length);
152 static int
153 variable_hash_cmp (const void *xv, const void *yv)
155 struct variable const *x = (struct variable const *) xv;
156 struct variable const *y = (struct variable const *) yv;
157 int result = x->length - y->length;
158 if (result)
159 return result;
160 return_STRING_N_COMPARE (x->name, y->name, x->length);
163 #ifndef VARIABLE_BUCKETS
164 #define VARIABLE_BUCKETS 523
165 #endif
166 #ifndef PERFILE_VARIABLE_BUCKETS
167 #define PERFILE_VARIABLE_BUCKETS 23
168 #endif
169 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
170 #define SMALL_SCOPE_VARIABLE_BUCKETS 13
171 #endif
173 static struct variable_set global_variable_set;
174 static struct variable_set_list global_setlist
175 = { 0, &global_variable_set, 0 };
176 struct variable_set_list *current_variable_set_list = &global_setlist;
178 /* Implement variables. */
180 void
181 init_hash_global_variable_set (void)
183 hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
184 variable_hash_1, variable_hash_2, variable_hash_cmp);
187 /* Define variable named NAME with value VALUE in SET. VALUE is copied.
188 LENGTH is the length of NAME, which does not need to be null-terminated.
189 ORIGIN specifies the origin of the variable (makefile, command line
190 or environment).
191 If RECURSIVE is nonzero a flag is set in the variable saying
192 that it should be recursively re-expanded. */
194 struct variable *
195 define_variable_in_set (const char *name, unsigned int length,
196 const char *value, enum variable_origin origin,
197 int recursive, struct variable_set *set,
198 const struct floc *flocp)
200 struct variable *v;
201 struct variable **var_slot;
202 struct variable var_key;
204 if (set == NULL)
205 set = &global_variable_set;
207 var_key.name = (char *) name;
208 var_key.length = length;
209 var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
211 if (env_overrides && origin == o_env)
212 origin = o_env_override;
214 v = *var_slot;
215 if (! HASH_VACANT (v))
217 if (env_overrides && v->origin == o_env)
218 /* V came from in the environment. Since it was defined
219 before the switches were parsed, it wasn't affected by -e. */
220 v->origin = o_env_override;
222 /* A variable of this name is already defined.
223 If the old definition is from a stronger source
224 than this one, don't redefine it. */
225 if ((int) origin >= (int) v->origin)
227 if (v->value != 0)
228 free (v->value);
229 v->value = xstrdup (value);
230 if (flocp != 0)
231 v->fileinfo = *flocp;
232 else
233 v->fileinfo.filenm = 0;
234 v->origin = origin;
235 v->recursive = recursive;
237 return v;
240 /* Create a new variable definition and add it to the hash table. */
242 v = xmalloc (sizeof (struct variable));
243 v->name = xstrndup (name, length);
244 v->length = length;
245 hash_insert_at (&set->table, v, var_slot);
246 v->value = xstrdup (value);
247 if (flocp != 0)
248 v->fileinfo = *flocp;
249 else
250 v->fileinfo.filenm = 0;
251 v->origin = origin;
252 v->recursive = recursive;
253 v->special = 0;
254 v->expanding = 0;
255 v->exp_count = 0;
256 v->per_target = 0;
257 v->append = 0;
258 v->private_var = 0;
259 v->export = v_default;
261 v->exportable = 1;
262 if (*name != '_' && (*name < 'A' || *name > 'Z')
263 && (*name < 'a' || *name > 'z'))
264 v->exportable = 0;
265 else
267 for (++name; *name != '\0'; ++name)
268 if (*name != '_' && (*name < 'a' || *name > 'z')
269 && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
270 break;
272 if (*name != '\0')
273 v->exportable = 0;
276 return v;
279 /* If the variable passed in is "special", handle its special nature.
280 Currently there are two such variables, both used for introspection:
281 .VARIABLES expands to a list of all the variables defined in this instance
282 of make.
283 .TARGETS expands to a list of all the targets defined in this
284 instance of make.
285 Returns the variable reference passed in. */
287 #define EXPANSION_INCREMENT(_l) ((((_l) / 500) + 1) * 500)
289 static struct variable *
290 lookup_special_var (struct variable *var)
292 static unsigned long last_var_count = 0;
295 /* This one actually turns out to be very hard, due to the way the parser
296 records targets. The way it works is that target information is collected
297 internally until make knows the target is completely specified. It unitl
298 it sees that some new construct (a new target or variable) is defined that
299 it knows the previous one is done. In short, this means that if you do
300 this:
302 all:
304 TARGS := $(.TARGETS)
306 then $(TARGS) won't contain "all", because it's not until after the
307 variable is created that the previous target is completed.
309 Changing this would be a major pain. I think a less complex way to do it
310 would be to pre-define the target files as soon as the first line is
311 parsed, then come back and do the rest of the definition as now. That
312 would allow $(.TARGETS) to be correct without a major change to the way
313 the parser works.
315 if (streq (var->name, ".TARGETS"))
316 var->value = build_target_list (var->value);
317 else
320 if (streq (var->name, ".VARIABLES")
321 && global_variable_set.table.ht_fill != last_var_count)
323 unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
324 unsigned long len;
325 char *p;
326 struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
327 struct variable **end = &vp[global_variable_set.table.ht_size];
329 /* Make sure we have at least MAX bytes in the allocated buffer. */
330 var->value = xrealloc (var->value, max);
332 /* Walk through the hash of variables, constructing a list of names. */
333 p = var->value;
334 len = 0;
335 for (; vp < end; ++vp)
336 if (!HASH_VACANT (*vp))
338 struct variable *v = *vp;
339 int l = v->length;
341 len += l + 1;
342 if (len > max)
344 unsigned long off = p - var->value;
346 max += EXPANSION_INCREMENT (l + 1);
347 var->value = xrealloc (var->value, max);
348 p = &var->value[off];
351 memcpy (p, v->name, l);
352 p += l;
353 *(p++) = ' ';
355 *(p-1) = '\0';
357 /* Remember how many variables are in our current count. Since we never
358 remove variables from the list, this is a reliable way to know whether
359 the list is up to date or needs to be recomputed. */
361 last_var_count = global_variable_set.table.ht_fill;
364 return var;
368 /* Lookup a variable whose name is a string starting at NAME
369 and with LENGTH chars. NAME need not be null-terminated.
370 Returns address of the `struct variable' containing all info
371 on the variable, or nil if no such variable is defined. */
373 struct variable *
374 lookup_variable (const char *name, unsigned int length)
376 const struct variable_set_list *setlist;
377 struct variable var_key;
378 int is_parent = 0;
380 var_key.name = (char *) name;
381 var_key.length = length;
383 for (setlist = current_variable_set_list;
384 setlist != 0; setlist = setlist->next)
386 const struct variable_set *set = setlist->set;
387 struct variable *v;
389 v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
390 if (v && (!is_parent || !v->private_var))
391 return v->special ? lookup_special_var (v) : v;
393 is_parent |= setlist->next_is_parent;
396 #ifdef VMS
397 /* since we don't read envp[] on startup, try to get the
398 variable via getenv() here. */
400 char *vname = alloca (length + 1);
401 char *value;
402 strncpy (vname, name, length);
403 vname[length] = 0;
404 value = getenv (vname);
405 if (value != 0)
407 char *sptr;
408 int scnt;
410 sptr = value;
411 scnt = 0;
413 while ((sptr = strchr (sptr, '$')))
415 scnt++;
416 sptr++;
419 if (scnt > 0)
421 char *nvalue;
422 char *nptr;
424 nvalue = alloca (strlen (value) + scnt + 1);
425 sptr = value;
426 nptr = nvalue;
428 while (*sptr)
430 if (*sptr == '$')
432 *nptr++ = '$';
433 *nptr++ = '$';
435 else
437 *nptr++ = *sptr;
439 sptr++;
442 *nptr = '\0';
443 return define_variable (vname, length, nvalue, o_env, 1);
447 return define_variable (vname, length, value, o_env, 1);
450 #endif /* VMS */
452 return 0;
455 /* Lookup a variable whose name is a string starting at NAME
456 and with LENGTH chars in set SET. NAME need not be null-terminated.
457 Returns address of the `struct variable' containing all info
458 on the variable, or nil if no such variable is defined. */
460 struct variable *
461 lookup_variable_in_set (const char *name, unsigned int length,
462 const struct variable_set *set)
464 struct variable var_key;
466 var_key.name = (char *) name;
467 var_key.length = length;
469 return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
472 /* Initialize FILE's variable set list. If FILE already has a variable set
473 list, the topmost variable set is left intact, but the the rest of the
474 chain is replaced with FILE->parent's setlist. If FILE is a double-colon
475 rule, then we will use the "root" double-colon target's variable set as the
476 parent of FILE's variable set.
478 If we're READING a makefile, don't do the pattern variable search now,
479 since the pattern variable might not have been defined yet. */
481 void
482 initialize_file_variables (struct file *file, int reading)
484 struct variable_set_list *l = file->variables;
486 if (l == 0)
488 l = (struct variable_set_list *)
489 xmalloc (sizeof (struct variable_set_list));
490 l->set = xmalloc (sizeof (struct variable_set));
491 hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
492 variable_hash_1, variable_hash_2, variable_hash_cmp);
493 file->variables = l;
496 /* If this is a double-colon, then our "parent" is the "root" target for
497 this double-colon rule. Since that rule has the same name, parent,
498 etc. we can just use its variables as the "next" for ours. */
500 if (file->double_colon && file->double_colon != file)
502 initialize_file_variables (file->double_colon, reading);
503 l->next = file->double_colon->variables;
504 l->next_is_parent = 0;
505 return;
508 if (file->parent == 0)
509 l->next = &global_setlist;
510 else
512 initialize_file_variables (file->parent, reading);
513 l->next = file->parent->variables;
515 l->next_is_parent = 1;
517 /* If we're not reading makefiles and we haven't looked yet, see if
518 we can find pattern variables for this target. */
520 if (!reading && !file->pat_searched)
522 struct pattern_var *p;
524 p = lookup_pattern_var (0, file->name);
525 if (p != 0)
527 struct variable_set_list *global = current_variable_set_list;
529 /* We found at least one. Set up a new variable set to accumulate
530 all the pattern variables that match this target. */
532 file->pat_variables = create_new_variable_set ();
533 current_variable_set_list = file->pat_variables;
537 /* We found one, so insert it into the set. */
539 struct variable *v;
541 if (p->variable.flavor == f_simple)
543 v = define_variable_loc (
544 p->variable.name, strlen (p->variable.name),
545 p->variable.value, p->variable.origin,
546 0, &p->variable.fileinfo);
548 v->flavor = f_simple;
550 else
552 v = do_variable_definition (
553 &p->variable.fileinfo, p->variable.name,
554 p->variable.value, p->variable.origin,
555 p->variable.flavor, 1);
558 /* Also mark it as a per-target and copy export status. */
559 v->per_target = p->variable.per_target;
560 v->export = p->variable.export;
561 v->private_var = p->variable.private_var;
563 while ((p = lookup_pattern_var (p, file->name)) != 0);
565 current_variable_set_list = global;
567 file->pat_searched = 1;
570 /* If we have a pattern variable match, set it up. */
572 if (file->pat_variables != 0)
574 file->pat_variables->next = l->next;
575 file->pat_variables->next_is_parent = l->next_is_parent;
576 l->next = file->pat_variables;
577 l->next_is_parent = 0;
581 /* Pop the top set off the current variable set list,
582 and free all its storage. */
584 struct variable_set_list *
585 create_new_variable_set (void)
587 register struct variable_set_list *setlist;
588 register struct variable_set *set;
590 set = xmalloc (sizeof (struct variable_set));
591 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
592 variable_hash_1, variable_hash_2, variable_hash_cmp);
594 setlist = (struct variable_set_list *)
595 xmalloc (sizeof (struct variable_set_list));
596 setlist->set = set;
597 setlist->next = current_variable_set_list;
598 setlist->next_is_parent = 0;
600 return setlist;
603 static void
604 free_variable_name_and_value (const void *item)
606 struct variable *v = (struct variable *) item;
607 free (v->name);
608 free (v->value);
611 void
612 free_variable_set (struct variable_set_list *list)
614 hash_map (&list->set->table, free_variable_name_and_value);
615 hash_free (&list->set->table, 1);
616 free (list->set);
617 free (list);
620 /* Create a new variable set and push it on the current setlist.
621 If we're pushing a global scope (that is, the current scope is the global
622 scope) then we need to "push" it the other way: file variable sets point
623 directly to the global_setlist so we need to replace that with the new one.
626 struct variable_set_list *
627 push_new_variable_scope (void)
629 current_variable_set_list = create_new_variable_set();
630 if (current_variable_set_list->next == &global_setlist)
632 /* It was the global, so instead of new -> &global we want to replace
633 &global with the new one and have &global -> new, with current still
634 pointing to &global */
635 struct variable_set *set = current_variable_set_list->set;
636 current_variable_set_list->set = global_setlist.set;
637 global_setlist.set = set;
638 current_variable_set_list->next = global_setlist.next;
639 global_setlist.next = current_variable_set_list;
640 current_variable_set_list = &global_setlist;
642 return (current_variable_set_list);
645 void
646 pop_variable_scope (void)
648 struct variable_set_list *setlist;
649 struct variable_set *set;
651 /* Can't call this if there's no scope to pop! */
652 assert(current_variable_set_list->next != NULL);
654 if (current_variable_set_list != &global_setlist)
656 /* We're not pointing to the global setlist, so pop this one. */
657 setlist = current_variable_set_list;
658 set = setlist->set;
659 current_variable_set_list = setlist->next;
661 else
663 /* This set is the one in the global_setlist, but there is another global
664 set beyond that. We want to copy that set to global_setlist, then
665 delete what used to be in global_setlist. */
666 setlist = global_setlist.next;
667 set = global_setlist.set;
668 global_setlist.set = setlist->set;
669 global_setlist.next = setlist->next;
670 global_setlist.next_is_parent = setlist->next_is_parent;
673 /* Free the one we no longer need. */
674 free (setlist);
675 hash_map (&set->table, free_variable_name_and_value);
676 hash_free (&set->table, 1);
677 free (set);
680 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
682 static void
683 merge_variable_sets (struct variable_set *to_set,
684 struct variable_set *from_set)
686 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
687 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
689 for ( ; from_var_slot < from_var_end; from_var_slot++)
690 if (! HASH_VACANT (*from_var_slot))
692 struct variable *from_var = *from_var_slot;
693 struct variable **to_var_slot
694 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
695 if (HASH_VACANT (*to_var_slot))
696 hash_insert_at (&to_set->table, from_var, to_var_slot);
697 else
699 /* GKM FIXME: delete in from_set->table */
700 free (from_var->value);
701 free (from_var);
706 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
708 void
709 merge_variable_set_lists (struct variable_set_list **setlist0,
710 struct variable_set_list *setlist1)
712 struct variable_set_list *to = *setlist0;
713 struct variable_set_list *last0 = 0;
715 /* If there's nothing to merge, stop now. */
716 if (!setlist1)
717 return;
719 /* This loop relies on the fact that all setlists terminate with the global
720 setlist (before NULL). If that's not true, arguably we SHOULD die. */
721 if (to)
722 while (setlist1 != &global_setlist && to != &global_setlist)
724 struct variable_set_list *from = setlist1;
725 setlist1 = setlist1->next;
727 merge_variable_sets (to->set, from->set);
729 last0 = to;
730 to = to->next;
733 if (setlist1 != &global_setlist)
735 if (last0 == 0)
736 *setlist0 = setlist1;
737 else
738 last0->next = setlist1;
742 /* Define the automatic variables, and record the addresses
743 of their structures so we can change their values quickly. */
745 void
746 define_automatic_variables (void)
748 #if defined(WINDOWS32) || defined(__EMX__)
749 extern char* default_shell;
750 #else
751 extern char default_shell[];
752 #endif
753 register struct variable *v;
754 char buf[200];
756 sprintf (buf, "%u", makelevel);
757 (void) define_variable (MAKELEVEL_NAME, MAKELEVEL_LENGTH, buf, o_env, 0);
759 sprintf (buf, "%s%s%s",
760 version_string,
761 (remote_description == 0 || remote_description[0] == '\0')
762 ? "" : "-",
763 (remote_description == 0 || remote_description[0] == '\0')
764 ? "" : remote_description);
765 (void) define_variable ("MAKE_VERSION", 12, buf, o_default, 0);
767 #ifdef __MSDOS__
768 /* Allow to specify a special shell just for Make,
769 and use $COMSPEC as the default $SHELL when appropriate. */
771 static char shell_str[] = "SHELL";
772 const int shlen = sizeof (shell_str) - 1;
773 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
774 struct variable *comp = lookup_variable ("COMSPEC", 7);
776 /* Make $MAKESHELL override $SHELL even if -e is in effect. */
777 if (mshp)
778 (void) define_variable (shell_str, shlen,
779 mshp->value, o_env_override, 0);
780 else if (comp)
782 /* $COMSPEC shouldn't override $SHELL. */
783 struct variable *shp = lookup_variable (shell_str, shlen);
785 if (!shp)
786 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
789 #elif defined(__EMX__)
791 static char shell_str[] = "SHELL";
792 const int shlen = sizeof (shell_str) - 1;
793 struct variable *shell = lookup_variable (shell_str, shlen);
794 struct variable *replace = lookup_variable ("MAKESHELL", 9);
796 /* if $MAKESHELL is defined in the environment assume o_env_override */
797 if (replace && *replace->value && replace->origin == o_env)
798 replace->origin = o_env_override;
800 /* if $MAKESHELL is not defined use $SHELL but only if the variable
801 did not come from the environment */
802 if (!replace || !*replace->value)
803 if (shell && *shell->value && (shell->origin == o_env
804 || shell->origin == o_env_override))
806 /* overwrite whatever we got from the environment */
807 free(shell->value);
808 shell->value = xstrdup (default_shell);
809 shell->origin = o_default;
812 /* Some people do not like cmd to be used as the default
813 if $SHELL is not defined in the Makefile.
814 With -DNO_CMD_DEFAULT you can turn off this behaviour */
815 # ifndef NO_CMD_DEFAULT
816 /* otherwise use $COMSPEC */
817 if (!replace || !*replace->value)
818 replace = lookup_variable ("COMSPEC", 7);
820 /* otherwise use $OS2_SHELL */
821 if (!replace || !*replace->value)
822 replace = lookup_variable ("OS2_SHELL", 9);
823 # else
824 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
825 # endif
827 if (replace && *replace->value)
828 /* overwrite $SHELL */
829 (void) define_variable (shell_str, shlen, replace->value,
830 replace->origin, 0);
831 else
832 /* provide a definition if there is none */
833 (void) define_variable (shell_str, shlen, default_shell,
834 o_default, 0);
837 #endif
839 /* This won't override any definition, but it will provide one if there
840 isn't one there. */
841 v = define_variable ("SHELL", 5, default_shell, o_default, 0);
842 #ifdef __MSDOS__
843 v->export = v_export; /* Export always SHELL. */
844 #endif
846 /* On MSDOS we do use SHELL from environment, since it isn't a standard
847 environment variable on MSDOS, so whoever sets it, does that on purpose.
848 On OS/2 we do not use SHELL from environment but we have already handled
849 that problem above. */
850 #if !defined(__MSDOS__) && !defined(__EMX__)
851 /* Don't let SHELL come from the environment. */
852 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
854 free (v->value);
855 v->origin = o_file;
856 v->value = xstrdup (default_shell);
858 #endif
860 /* Make sure MAKEFILES gets exported if it is set. */
861 v = define_variable ("MAKEFILES", 9, "", o_default, 0);
862 v->export = v_ifset;
864 /* Define the magic D and F variables in terms of
865 the automatic variables they are variations of. */
867 #ifdef VMS
868 define_variable ("@D", 2, "$(dir $@)", o_automatic, 1);
869 define_variable ("%D", 2, "$(dir $%)", o_automatic, 1);
870 define_variable ("*D", 2, "$(dir $*)", o_automatic, 1);
871 define_variable ("<D", 2, "$(dir $<)", o_automatic, 1);
872 define_variable ("?D", 2, "$(dir $?)", o_automatic, 1);
873 define_variable ("^D", 2, "$(dir $^)", o_automatic, 1);
874 define_variable ("+D", 2, "$(dir $+)", o_automatic, 1);
875 #else
876 define_variable ("@D", 2, "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
877 define_variable ("%D", 2, "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
878 define_variable ("*D", 2, "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
879 define_variable ("<D", 2, "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
880 define_variable ("?D", 2, "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
881 define_variable ("^D", 2, "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
882 define_variable ("+D", 2, "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
883 #endif
884 define_variable ("@F", 2, "$(notdir $@)", o_automatic, 1);
885 define_variable ("%F", 2, "$(notdir $%)", o_automatic, 1);
886 define_variable ("*F", 2, "$(notdir $*)", o_automatic, 1);
887 define_variable ("<F", 2, "$(notdir $<)", o_automatic, 1);
888 define_variable ("?F", 2, "$(notdir $?)", o_automatic, 1);
889 define_variable ("^F", 2, "$(notdir $^)", o_automatic, 1);
890 define_variable ("+F", 2, "$(notdir $+)", o_automatic, 1);
893 int export_all_variables;
895 /* Create a new environment for FILE's commands.
896 If FILE is nil, this is for the `shell' function.
897 The child's MAKELEVEL variable is incremented. */
899 char **
900 target_environment (struct file *file)
902 struct variable_set_list *set_list;
903 register struct variable_set_list *s;
904 struct hash_table table;
905 struct variable **v_slot;
906 struct variable **v_end;
907 struct variable makelevel_key;
908 char **result_0;
909 char **result;
911 if (file == 0)
912 set_list = current_variable_set_list;
913 else
914 set_list = file->variables;
916 hash_init (&table, VARIABLE_BUCKETS,
917 variable_hash_1, variable_hash_2, variable_hash_cmp);
919 /* Run through all the variable sets in the list,
920 accumulating variables in TABLE. */
921 for (s = set_list; s != 0; s = s->next)
923 struct variable_set *set = s->set;
924 v_slot = (struct variable **) set->table.ht_vec;
925 v_end = v_slot + set->table.ht_size;
926 for ( ; v_slot < v_end; v_slot++)
927 if (! HASH_VACANT (*v_slot))
929 struct variable **new_slot;
930 struct variable *v = *v_slot;
932 /* If this is a per-target variable and it hasn't been touched
933 already then look up the global version and take its export
934 value. */
935 if (v->per_target && v->export == v_default)
937 struct variable *gv;
939 gv = lookup_variable_in_set (v->name, strlen(v->name),
940 &global_variable_set);
941 if (gv)
942 v->export = gv->export;
945 switch (v->export)
947 case v_default:
948 if (v->origin == o_default || v->origin == o_automatic)
949 /* Only export default variables by explicit request. */
950 continue;
952 /* The variable doesn't have a name that can be exported. */
953 if (! v->exportable)
954 continue;
956 if (! export_all_variables
957 && v->origin != o_command
958 && v->origin != o_env && v->origin != o_env_override)
959 continue;
960 break;
962 case v_export:
963 break;
965 case v_noexport:
967 /* If this is the SHELL variable and it's not exported,
968 then add the value from our original environment, if
969 the original environment defined a value for SHELL. */
970 extern struct variable shell_var;
971 if (streq (v->name, "SHELL") && shell_var.value)
973 v = &shell_var;
974 break;
976 continue;
979 case v_ifset:
980 if (v->origin == o_default)
981 continue;
982 break;
985 new_slot = (struct variable **) hash_find_slot (&table, v);
986 if (HASH_VACANT (*new_slot))
987 hash_insert_at (&table, v, new_slot);
991 makelevel_key.name = MAKELEVEL_NAME;
992 makelevel_key.length = MAKELEVEL_LENGTH;
993 hash_delete (&table, &makelevel_key);
995 result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
997 v_slot = (struct variable **) table.ht_vec;
998 v_end = v_slot + table.ht_size;
999 for ( ; v_slot < v_end; v_slot++)
1000 if (! HASH_VACANT (*v_slot))
1002 struct variable *v = *v_slot;
1004 /* If V is recursively expanded and didn't come from the environment,
1005 expand its value. If it came from the environment, it should
1006 go back into the environment unchanged. */
1007 if (v->recursive
1008 && v->origin != o_env && v->origin != o_env_override)
1010 char *value = recursively_expand_for_file (v, file);
1011 #ifdef WINDOWS32
1012 if (strcmp(v->name, "Path") == 0 ||
1013 strcmp(v->name, "PATH") == 0)
1014 convert_Path_to_windows32(value, ';');
1015 #endif
1016 *result++ = xstrdup (concat (3, v->name, "=", value));
1017 free (value);
1019 else
1021 #ifdef WINDOWS32
1022 if (strcmp(v->name, "Path") == 0 ||
1023 strcmp(v->name, "PATH") == 0)
1024 convert_Path_to_windows32(v->value, ';');
1025 #endif
1026 *result++ = xstrdup (concat (3, v->name, "=", v->value));
1030 *result = xmalloc (100);
1031 sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
1032 *++result = 0;
1034 hash_free (&table, 0);
1036 return result_0;
1039 static struct variable *
1040 set_special_var (struct variable *var)
1042 if (streq (var->name, RECIPEPREFIX_NAME))
1044 /* The user is resetting the command introduction prefix. This has to
1045 happen immediately, so that subsequent rules are interpreted
1046 properly. */
1047 cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1050 return var;
1053 /* Given a variable, a value, and a flavor, define the variable.
1054 See the try_variable_definition() function for details on the parameters. */
1056 struct variable *
1057 do_variable_definition (const struct floc *flocp, const char *varname,
1058 const char *value, enum variable_origin origin,
1059 enum variable_flavor flavor, int target_var)
1061 const char *p;
1062 char *alloc_value = NULL;
1063 struct variable *v;
1064 int append = 0;
1065 int conditional = 0;
1067 /* Calculate the variable's new value in VALUE. */
1069 switch (flavor)
1071 default:
1072 case f_bogus:
1073 /* Should not be possible. */
1074 abort ();
1075 case f_simple:
1076 /* A simple variable definition "var := value". Expand the value.
1077 We have to allocate memory since otherwise it'll clobber the
1078 variable buffer, and we may still need that if we're looking at a
1079 target-specific variable. */
1080 p = alloc_value = allocated_variable_expand (value);
1081 break;
1082 case f_conditional:
1083 /* A conditional variable definition "var ?= value".
1084 The value is set IFF the variable is not defined yet. */
1085 v = lookup_variable (varname, strlen (varname));
1086 if (v)
1087 return v->special ? set_special_var (v) : v;
1089 conditional = 1;
1090 flavor = f_recursive;
1091 /* FALLTHROUGH */
1092 case f_recursive:
1093 /* A recursive variable definition "var = value".
1094 The value is used verbatim. */
1095 p = value;
1096 break;
1097 case f_append:
1099 /* If we have += but we're in a target variable context, we want to
1100 append only with other variables in the context of this target. */
1101 if (target_var)
1103 append = 1;
1104 v = lookup_variable_in_set (varname, strlen (varname),
1105 current_variable_set_list->set);
1107 /* Don't append from the global set if a previous non-appending
1108 target-specific variable definition exists. */
1109 if (v && !v->append)
1110 append = 0;
1112 else
1113 v = lookup_variable (varname, strlen (varname));
1115 if (v == 0)
1117 /* There was no old value.
1118 This becomes a normal recursive definition. */
1119 p = value;
1120 flavor = f_recursive;
1122 else
1124 /* Paste the old and new values together in VALUE. */
1126 unsigned int oldlen, vallen;
1127 const char *val;
1128 char *tp = NULL;
1130 val = value;
1131 if (v->recursive)
1132 /* The previous definition of the variable was recursive.
1133 The new value is the unexpanded old and new values. */
1134 flavor = f_recursive;
1135 else
1136 /* The previous definition of the variable was simple.
1137 The new value comes from the old value, which was expanded
1138 when it was set; and from the expanded new value. Allocate
1139 memory for the expansion as we may still need the rest of the
1140 buffer if we're looking at a target-specific variable. */
1141 val = tp = allocated_variable_expand (val);
1143 oldlen = strlen (v->value);
1144 vallen = strlen (val);
1145 p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1146 memcpy (alloc_value, v->value, oldlen);
1147 alloc_value[oldlen] = ' ';
1148 memcpy (&alloc_value[oldlen + 1], val, vallen + 1);
1150 if (tp)
1151 free (tp);
1156 #ifdef __MSDOS__
1157 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1158 non-Unix systems don't conform to this default configuration (in
1159 fact, most of them don't even have `/bin'). On the other hand,
1160 $SHELL in the environment, if set, points to the real pathname of
1161 the shell.
1162 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1163 the Makefile override $SHELL from the environment. But first, we
1164 look for the basename of the shell in the directory where SHELL=
1165 points, and along the $PATH; if it is found in any of these places,
1166 we define $SHELL to be the actual pathname of the shell. Thus, if
1167 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1168 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1169 defining SHELL to be "d:/unix/bash.exe". */
1170 if ((origin == o_file || origin == o_override)
1171 && strcmp (varname, "SHELL") == 0)
1173 PATH_VAR (shellpath);
1174 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1176 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1177 if (__dosexec_find_on_path (p, NULL, shellpath))
1179 char *tp;
1181 for (tp = shellpath; *tp; tp++)
1182 if (*tp == '\\')
1183 *tp = '/';
1185 v = define_variable_loc (varname, strlen (varname),
1186 shellpath, origin, flavor == f_recursive,
1187 flocp);
1189 else
1191 const char *shellbase, *bslash;
1192 struct variable *pathv = lookup_variable ("PATH", 4);
1193 char *path_string;
1194 char *fake_env[2];
1195 size_t pathlen = 0;
1197 shellbase = strrchr (p, '/');
1198 bslash = strrchr (p, '\\');
1199 if (!shellbase || bslash > shellbase)
1200 shellbase = bslash;
1201 if (!shellbase && p[1] == ':')
1202 shellbase = p + 1;
1203 if (shellbase)
1204 shellbase++;
1205 else
1206 shellbase = p;
1208 /* Search for the basename of the shell (with standard
1209 executable extensions) along the $PATH. */
1210 if (pathv)
1211 pathlen = strlen (pathv->value);
1212 path_string = xmalloc (5 + pathlen + 2 + 1);
1213 /* On MSDOS, current directory is considered as part of $PATH. */
1214 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1215 fake_env[0] = path_string;
1216 fake_env[1] = 0;
1217 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1219 char *tp;
1221 for (tp = shellpath; *tp; tp++)
1222 if (*tp == '\\')
1223 *tp = '/';
1225 v = define_variable_loc (varname, strlen (varname),
1226 shellpath, origin,
1227 flavor == f_recursive, flocp);
1229 else
1230 v = lookup_variable (varname, strlen (varname));
1232 free (path_string);
1235 else
1236 #endif /* __MSDOS__ */
1237 #ifdef WINDOWS32
1238 if ((origin == o_file || origin == o_override || origin == o_command)
1239 && streq (varname, "SHELL"))
1241 extern char *default_shell;
1243 /* Call shell locator function. If it returns TRUE, then
1244 set no_default_sh_exe to indicate sh was found and
1245 set new value for SHELL variable. */
1247 if (find_and_set_default_shell (p))
1249 v = define_variable_in_set (varname, strlen (varname), default_shell,
1250 origin, flavor == f_recursive,
1251 (target_var
1252 ? current_variable_set_list->set
1253 : NULL),
1254 flocp);
1255 no_default_sh_exe = 0;
1257 else
1259 char *tp = alloc_value;
1261 alloc_value = allocated_variable_expand (p);
1263 if (find_and_set_default_shell (alloc_value))
1265 v = define_variable_in_set (varname, strlen (varname), p,
1266 origin, flavor == f_recursive,
1267 (target_var
1268 ? current_variable_set_list->set
1269 : NULL),
1270 flocp);
1271 no_default_sh_exe = 0;
1273 else
1274 v = lookup_variable (varname, strlen (varname));
1276 if (tp)
1277 free (tp);
1280 else
1281 #endif
1283 /* If we are defining variables inside an $(eval ...), we might have a
1284 different variable context pushed, not the global context (maybe we're
1285 inside a $(call ...) or something. Since this function is only ever
1286 invoked in places where we want to define globally visible variables,
1287 make sure we define this variable in the global set. */
1289 v = define_variable_in_set (varname, strlen (varname), p,
1290 origin, flavor == f_recursive,
1291 (target_var
1292 ? current_variable_set_list->set : NULL),
1293 flocp);
1294 v->append = append;
1295 v->conditional = conditional;
1297 if (alloc_value)
1298 free (alloc_value);
1300 return v->special ? set_special_var (v) : v;
1303 /* Parse P (a null-terminated string) as a variable definition.
1305 If it is not a variable definition, return NULL.
1307 If it is a variable definition, return a pointer to the char after the
1308 assignment token and set *FLAVOR to the type of variable assignment. */
1310 char *
1311 parse_variable_definition (const char *p, enum variable_flavor *flavor)
1313 int wspace = 0;
1315 p = next_token (p);
1317 while (1)
1319 int c = *p++;
1321 /* If we find a comment or EOS, it's not a variable definition. */
1322 if (c == '\0' || c == '#')
1323 return NULL;
1325 if (c == '$')
1327 /* This begins a variable expansion reference. Make sure we don't
1328 treat chars inside the reference as assignment tokens. */
1329 char closeparen;
1330 int count;
1331 c = *p++;
1332 if (c == '(')
1333 closeparen = ')';
1334 else if (c == '{')
1335 closeparen = '}';
1336 else
1337 /* '$$' or '$X'. Either way, nothing special to do here. */
1338 continue;
1340 /* P now points past the opening paren or brace.
1341 Count parens or braces until it is matched. */
1342 count = 0;
1343 for (; *p != '\0'; ++p)
1345 if (*p == c)
1346 ++count;
1347 else if (*p == closeparen && --count < 0)
1349 ++p;
1350 break;
1353 continue;
1356 /* If we find whitespace skip it, and remember we found it. */
1357 if (isblank ((unsigned char)c))
1359 wspace = 1;
1360 p = next_token (p);
1361 c = *p;
1362 if (c == '\0')
1363 return NULL;
1364 ++p;
1368 if (c == '=')
1370 *flavor = f_recursive;
1371 return (char *)p;
1374 /* Match assignment variants (:=, +=, ?=) */
1375 if (*p == '=')
1377 switch (c)
1379 case ':':
1380 *flavor = f_simple;
1381 break;
1382 case '+':
1383 *flavor = f_append;
1384 break;
1385 case '?':
1386 *flavor = f_conditional;
1387 break;
1388 default:
1389 /* If we skipped whitespace, non-assignments means no var. */
1390 if (wspace)
1391 return NULL;
1393 /* Might be assignment, or might be $= or #=. Check. */
1394 continue;
1396 return (char *)++p;
1398 else if (c == ':')
1399 /* A colon other than := is a rule line, not a variable defn. */
1400 return NULL;
1402 /* If we skipped whitespace, non-assignments means no var. */
1403 if (wspace)
1404 return NULL;
1407 return (char *)p;
1410 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1412 If LINE was recognized as a variable definition, a pointer to its `struct
1413 variable' is returned. If LINE is not a variable definition, NULL is
1414 returned. */
1416 struct variable *
1417 assign_variable_definition (struct variable *v, char *line)
1419 char *beg;
1420 char *end;
1421 enum variable_flavor flavor;
1422 char *name;
1424 beg = next_token (line);
1425 line = parse_variable_definition (beg, &flavor);
1426 if (!line)
1427 return NULL;
1429 end = line - (flavor == f_recursive ? 1 : 2);
1430 while (end > beg && isblank ((unsigned char)end[-1]))
1431 --end;
1432 line = next_token (line);
1433 v->value = line;
1434 v->flavor = flavor;
1436 /* Expand the name, so "$(foo)bar = baz" works. */
1437 name = alloca (end - beg + 1);
1438 memcpy (name, beg, end - beg);
1439 name[end - beg] = '\0';
1440 v->name = allocated_variable_expand (name);
1442 if (v->name[0] == '\0')
1443 fatal (&v->fileinfo, _("empty variable name"));
1445 return v;
1448 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1450 ORIGIN may be o_file, o_override, o_env, o_env_override,
1451 or o_command specifying that the variable definition comes
1452 from a makefile, an override directive, the environment with
1453 or without the -e switch, or the command line.
1455 See the comments for assign_variable_definition().
1457 If LINE was recognized as a variable definition, a pointer to its `struct
1458 variable' is returned. If LINE is not a variable definition, NULL is
1459 returned. */
1461 struct variable *
1462 try_variable_definition (const struct floc *flocp, char *line,
1463 enum variable_origin origin, int target_var)
1465 struct variable v;
1466 struct variable *vp;
1468 if (flocp != 0)
1469 v.fileinfo = *flocp;
1470 else
1471 v.fileinfo.filenm = 0;
1473 if (!assign_variable_definition (&v, line))
1474 return 0;
1476 vp = do_variable_definition (flocp, v.name, v.value,
1477 origin, v.flavor, target_var);
1479 free (v.name);
1481 return vp;
1484 /* Print information for variable V, prefixing it with PREFIX. */
1486 static void
1487 print_variable (const void *item, void *arg)
1489 const struct variable *v = item;
1490 const char *prefix = arg;
1491 const char *origin;
1493 switch (v->origin)
1495 case o_default:
1496 origin = _("default");
1497 break;
1498 case o_env:
1499 origin = _("environment");
1500 break;
1501 case o_file:
1502 origin = _("makefile");
1503 break;
1504 case o_env_override:
1505 origin = _("environment under -e");
1506 break;
1507 case o_command:
1508 origin = _("command line");
1509 break;
1510 case o_override:
1511 origin = _("`override' directive");
1512 break;
1513 case o_automatic:
1514 origin = _("automatic");
1515 break;
1516 case o_invalid:
1517 default:
1518 abort ();
1520 fputs ("# ", stdout);
1521 fputs (origin, stdout);
1522 if (v->private_var)
1523 fputs (" private", stdout);
1524 if (v->fileinfo.filenm)
1525 printf (_(" (from `%s', line %lu)"),
1526 v->fileinfo.filenm, v->fileinfo.lineno);
1527 putchar ('\n');
1528 fputs (prefix, stdout);
1530 /* Is this a `define'? */
1531 if (v->recursive && strchr (v->value, '\n') != 0)
1532 printf ("define %s\n%s\nendef\n", v->name, v->value);
1533 else
1535 char *p;
1537 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1539 /* Check if the value is just whitespace. */
1540 p = next_token (v->value);
1541 if (p != v->value && *p == '\0')
1542 /* All whitespace. */
1543 printf ("$(subst ,,%s)", v->value);
1544 else if (v->recursive)
1545 fputs (v->value, stdout);
1546 else
1547 /* Double up dollar signs. */
1548 for (p = v->value; *p != '\0'; ++p)
1550 if (*p == '$')
1551 putchar ('$');
1552 putchar (*p);
1554 putchar ('\n');
1559 /* Print all the variables in SET. PREFIX is printed before
1560 the actual variable definitions (everything else is comments). */
1562 void
1563 print_variable_set (struct variable_set *set, char *prefix)
1565 hash_map_arg (&set->table, print_variable, prefix);
1567 fputs (_("# variable set hash-table stats:\n"), stdout);
1568 fputs ("# ", stdout);
1569 hash_print_stats (&set->table, stdout);
1570 putc ('\n', stdout);
1573 /* Print the data base of variables. */
1575 void
1576 print_variable_data_base (void)
1578 puts (_("\n# Variables\n"));
1580 print_variable_set (&global_variable_set, "");
1582 puts (_("\n# Pattern-specific Variable Values"));
1585 struct pattern_var *p;
1586 int rules = 0;
1588 for (p = pattern_vars; p != 0; p = p->next)
1590 ++rules;
1591 printf ("\n%s :\n", p->target);
1592 print_variable (&p->variable, "# ");
1595 if (rules == 0)
1596 puts (_("\n# No pattern-specific variable values."));
1597 else
1598 printf (_("\n# %u pattern-specific variable values"), rules);
1603 /* Print all the local variables of FILE. */
1605 void
1606 print_file_variables (const struct file *file)
1608 if (file->variables != 0)
1609 print_variable_set (file->variables->set, "# ");
1612 #ifdef WINDOWS32
1613 void
1614 sync_Path_environment (void)
1616 char *path = allocated_variable_expand ("$(PATH)");
1617 static char *environ_path = NULL;
1619 if (!path)
1620 return;
1623 * If done this before, don't leak memory unnecessarily.
1624 * Free the previous entry before allocating new one.
1626 if (environ_path)
1627 free (environ_path);
1630 * Create something WINDOWS32 world can grok
1632 convert_Path_to_windows32 (path, ';');
1633 environ_path = xstrdup (concat (3, "PATH", "=", path));
1634 putenv (environ_path);
1635 free (path);
1637 #endif