Update copyright and license notices on all files.
[make/kirr.git] / variable.c
blob978bfe12eea9bfcd87cfb50304bc1667efc5bfe5
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, 2005, 2006 Free Software Foundation, Inc.
4 This file is part of GNU Make.
6 GNU Make is free software; you can redistribute it and/or modify it under the
7 terms of the GNU General Public License as published by the Free Software
8 Foundation; either version 2, or (at your option) any later version.
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 GNU Make; see the file COPYING. If not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
18 #include "make.h"
20 #include <assert.h>
22 #include "dep.h"
23 #include "filedef.h"
24 #include "job.h"
25 #include "commands.h"
26 #include "variable.h"
27 #include "rule.h"
28 #ifdef WINDOWS32
29 #include "pathstuff.h"
30 #endif
31 #include "hash.h"
33 /* Chain of all pattern-specific variables. */
35 static struct pattern_var *pattern_vars;
37 /* Pointer to last struct in the chain, so we can add onto the end. */
39 static struct pattern_var *last_pattern_var;
41 /* Create a new pattern-specific variable struct. */
43 struct pattern_var *
44 create_pattern_var (char *target, char *suffix)
46 register struct pattern_var *p
47 = (struct pattern_var *) 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, 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 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 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 = (struct variable *) 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 handle_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 bcopy (v->name, p, 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 ? handle_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 = (struct variable_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 static void
542 free_variable_name_and_value (const void *item)
544 struct variable *v = (struct variable *) item;
545 free (v->name);
546 free (v->value);
549 struct variable_set_list *
550 create_new_variable_set (void)
552 register struct variable_set_list *setlist;
553 register struct variable_set *set;
555 set = (struct variable_set *) xmalloc (sizeof (struct variable_set));
556 hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
557 variable_hash_1, variable_hash_2, variable_hash_cmp);
559 setlist = (struct variable_set_list *)
560 xmalloc (sizeof (struct variable_set_list));
561 setlist->set = set;
562 setlist->next = current_variable_set_list;
564 return setlist;
567 /* Create a new variable set and push it on the current setlist.
568 If we're pushing a global scope (that is, the current scope is the global
569 scope) then we need to "push" it the other way: file variable sets point
570 directly to the global_setlist so we need to replace that with the new one.
573 struct variable_set_list *
574 push_new_variable_scope (void)
576 current_variable_set_list = create_new_variable_set();
577 if (current_variable_set_list->next == &global_setlist)
579 /* It was the global, so instead of new -> &global we want to replace
580 &global with the new one and have &global -> new, with current still
581 pointing to &global */
582 struct variable_set *set = current_variable_set_list->set;
583 current_variable_set_list->set = global_setlist.set;
584 global_setlist.set = set;
585 current_variable_set_list->next = global_setlist.next;
586 global_setlist.next = current_variable_set_list;
587 current_variable_set_list = &global_setlist;
589 return (current_variable_set_list);
592 void
593 pop_variable_scope (void)
595 struct variable_set_list *setlist;
596 struct variable_set *set;
598 /* Can't call this if there's no scope to pop! */
599 assert(current_variable_set_list->next != NULL);
601 if (current_variable_set_list != &global_setlist)
603 /* We're not pointing to the global setlist, so pop this one. */
604 setlist = current_variable_set_list;
605 set = setlist->set;
606 current_variable_set_list = setlist->next;
608 else
610 /* This set is the one in the global_setlist, but there is another global
611 set beyond that. We want to copy that set to global_setlist, then
612 delete what used to be in global_setlist. */
613 setlist = global_setlist.next;
614 set = global_setlist.set;
615 global_setlist.set = setlist->set;
616 global_setlist.next = setlist->next;
619 /* Free the one we no longer need. */
620 free ((char *) setlist);
621 hash_map (&set->table, free_variable_name_and_value);
622 hash_free (&set->table, 1);
623 free ((char *) set);
626 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET. */
628 static void
629 merge_variable_sets (struct variable_set *to_set,
630 struct variable_set *from_set)
632 struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
633 struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
635 for ( ; from_var_slot < from_var_end; from_var_slot++)
636 if (! HASH_VACANT (*from_var_slot))
638 struct variable *from_var = *from_var_slot;
639 struct variable **to_var_slot
640 = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
641 if (HASH_VACANT (*to_var_slot))
642 hash_insert_at (&to_set->table, from_var, to_var_slot);
643 else
645 /* GKM FIXME: delete in from_set->table */
646 free (from_var->value);
647 free (from_var);
652 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1. */
654 void
655 merge_variable_set_lists (struct variable_set_list **setlist0,
656 struct variable_set_list *setlist1)
658 register struct variable_set_list *list0 = *setlist0;
659 struct variable_set_list *last0 = 0;
661 while (setlist1 != 0 && list0 != 0)
663 struct variable_set_list *next = setlist1;
664 setlist1 = setlist1->next;
666 merge_variable_sets (list0->set, next->set);
668 last0 = list0;
669 list0 = list0->next;
672 if (setlist1 != 0)
674 if (last0 == 0)
675 *setlist0 = setlist1;
676 else
677 last0->next = setlist1;
681 /* Define the automatic variables, and record the addresses
682 of their structures so we can change their values quickly. */
684 void
685 define_automatic_variables (void)
687 #if defined(WINDOWS32) || defined(__EMX__)
688 extern char* default_shell;
689 #else
690 extern char default_shell[];
691 #endif
692 register struct variable *v;
693 char buf[200];
695 sprintf (buf, "%u", makelevel);
696 (void) define_variable (MAKELEVEL_NAME, MAKELEVEL_LENGTH, buf, o_env, 0);
698 sprintf (buf, "%s%s%s",
699 version_string,
700 (remote_description == 0 || remote_description[0] == '\0')
701 ? "" : "-",
702 (remote_description == 0 || remote_description[0] == '\0')
703 ? "" : remote_description);
704 (void) define_variable ("MAKE_VERSION", 12, buf, o_default, 0);
706 #ifdef __MSDOS__
707 /* Allow to specify a special shell just for Make,
708 and use $COMSPEC as the default $SHELL when appropriate. */
710 static char shell_str[] = "SHELL";
711 const int shlen = sizeof (shell_str) - 1;
712 struct variable *mshp = lookup_variable ("MAKESHELL", 9);
713 struct variable *comp = lookup_variable ("COMSPEC", 7);
715 /* Make $MAKESHELL override $SHELL even if -e is in effect. */
716 if (mshp)
717 (void) define_variable (shell_str, shlen,
718 mshp->value, o_env_override, 0);
719 else if (comp)
721 /* $COMSPEC shouldn't override $SHELL. */
722 struct variable *shp = lookup_variable (shell_str, shlen);
724 if (!shp)
725 (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
728 #elif defined(__EMX__)
730 static char shell_str[] = "SHELL";
731 const int shlen = sizeof (shell_str) - 1;
732 struct variable *shell = lookup_variable (shell_str, shlen);
733 struct variable *replace = lookup_variable ("MAKESHELL", 9);
735 /* if $MAKESHELL is defined in the environment assume o_env_override */
736 if (replace && *replace->value && replace->origin == o_env)
737 replace->origin = o_env_override;
739 /* if $MAKESHELL is not defined use $SHELL but only if the variable
740 did not come from the environment */
741 if (!replace || !*replace->value)
742 if (shell && *shell->value && (shell->origin == o_env
743 || shell->origin == o_env_override))
745 /* overwrite whatever we got from the environment */
746 free(shell->value);
747 shell->value = xstrdup (default_shell);
748 shell->origin = o_default;
751 /* Some people do not like cmd to be used as the default
752 if $SHELL is not defined in the Makefile.
753 With -DNO_CMD_DEFAULT you can turn off this behaviour */
754 # ifndef NO_CMD_DEFAULT
755 /* otherwise use $COMSPEC */
756 if (!replace || !*replace->value)
757 replace = lookup_variable ("COMSPEC", 7);
759 /* otherwise use $OS2_SHELL */
760 if (!replace || !*replace->value)
761 replace = lookup_variable ("OS2_SHELL", 9);
762 # else
763 # warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
764 # endif
766 if (replace && *replace->value)
767 /* overwrite $SHELL */
768 (void) define_variable (shell_str, shlen, replace->value,
769 replace->origin, 0);
770 else
771 /* provide a definition if there is none */
772 (void) define_variable (shell_str, shlen, default_shell,
773 o_default, 0);
776 #endif
778 /* This won't override any definition, but it will provide one if there
779 isn't one there. */
780 v = define_variable ("SHELL", 5, default_shell, o_default, 0);
782 /* On MSDOS we do use SHELL from environment, since it isn't a standard
783 environment variable on MSDOS, so whoever sets it, does that on purpose.
784 On OS/2 we do not use SHELL from environment but we have already handled
785 that problem above. */
786 #if !defined(__MSDOS__) && !defined(__EMX__)
787 /* Don't let SHELL come from the environment. */
788 if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
790 free (v->value);
791 v->origin = o_file;
792 v->value = xstrdup (default_shell);
794 #endif
796 /* Make sure MAKEFILES gets exported if it is set. */
797 v = define_variable ("MAKEFILES", 9, "", o_default, 0);
798 v->export = v_ifset;
800 /* Define the magic D and F variables in terms of
801 the automatic variables they are variations of. */
803 #ifdef VMS
804 define_variable ("@D", 2, "$(dir $@)", o_automatic, 1);
805 define_variable ("%D", 2, "$(dir $%)", o_automatic, 1);
806 define_variable ("*D", 2, "$(dir $*)", o_automatic, 1);
807 define_variable ("<D", 2, "$(dir $<)", o_automatic, 1);
808 define_variable ("?D", 2, "$(dir $?)", o_automatic, 1);
809 define_variable ("^D", 2, "$(dir $^)", o_automatic, 1);
810 define_variable ("+D", 2, "$(dir $+)", o_automatic, 1);
811 #else
812 define_variable ("@D", 2, "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
813 define_variable ("%D", 2, "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
814 define_variable ("*D", 2, "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
815 define_variable ("<D", 2, "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
816 define_variable ("?D", 2, "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
817 define_variable ("^D", 2, "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
818 define_variable ("+D", 2, "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
819 #endif
820 define_variable ("@F", 2, "$(notdir $@)", o_automatic, 1);
821 define_variable ("%F", 2, "$(notdir $%)", o_automatic, 1);
822 define_variable ("*F", 2, "$(notdir $*)", o_automatic, 1);
823 define_variable ("<F", 2, "$(notdir $<)", o_automatic, 1);
824 define_variable ("?F", 2, "$(notdir $?)", o_automatic, 1);
825 define_variable ("^F", 2, "$(notdir $^)", o_automatic, 1);
826 define_variable ("+F", 2, "$(notdir $+)", o_automatic, 1);
829 int export_all_variables;
831 /* Create a new environment for FILE's commands.
832 If FILE is nil, this is for the `shell' function.
833 The child's MAKELEVEL variable is incremented. */
835 char **
836 target_environment (struct file *file)
838 struct variable_set_list *set_list;
839 register struct variable_set_list *s;
840 struct hash_table table;
841 struct variable **v_slot;
842 struct variable **v_end;
843 struct variable makelevel_key;
844 char **result_0;
845 char **result;
847 if (file == 0)
848 set_list = current_variable_set_list;
849 else
850 set_list = file->variables;
852 hash_init (&table, VARIABLE_BUCKETS,
853 variable_hash_1, variable_hash_2, variable_hash_cmp);
855 /* Run through all the variable sets in the list,
856 accumulating variables in TABLE. */
857 for (s = set_list; s != 0; s = s->next)
859 struct variable_set *set = s->set;
860 v_slot = (struct variable **) set->table.ht_vec;
861 v_end = v_slot + set->table.ht_size;
862 for ( ; v_slot < v_end; v_slot++)
863 if (! HASH_VACANT (*v_slot))
865 struct variable **new_slot;
866 struct variable *v = *v_slot;
868 /* If this is a per-target variable and it hasn't been touched
869 already then look up the global version and take its export
870 value. */
871 if (v->per_target && v->export == v_default)
873 struct variable *gv;
875 gv = lookup_variable_in_set (v->name, strlen(v->name),
876 &global_variable_set);
877 if (gv)
878 v->export = gv->export;
881 switch (v->export)
883 case v_default:
884 if (v->origin == o_default || v->origin == o_automatic)
885 /* Only export default variables by explicit request. */
886 continue;
888 /* The variable doesn't have a name that can be exported. */
889 if (! v->exportable)
890 continue;
892 if (! export_all_variables
893 && v->origin != o_command
894 && v->origin != o_env && v->origin != o_env_override)
895 continue;
896 break;
898 case v_export:
899 break;
901 case v_noexport:
902 /* If this is the SHELL variable and it's not exported, then
903 add the value from our original environment. */
904 if (streq (v->name, "SHELL"))
906 extern struct variable shell_var;
907 v = &shell_var;
908 break;
910 continue;
912 case v_ifset:
913 if (v->origin == o_default)
914 continue;
915 break;
918 new_slot = (struct variable **) hash_find_slot (&table, v);
919 if (HASH_VACANT (*new_slot))
920 hash_insert_at (&table, v, new_slot);
924 makelevel_key.name = MAKELEVEL_NAME;
925 makelevel_key.length = MAKELEVEL_LENGTH;
926 hash_delete (&table, &makelevel_key);
928 result = result_0 = (char **) xmalloc ((table.ht_fill + 2) * sizeof (char *));
930 v_slot = (struct variable **) table.ht_vec;
931 v_end = v_slot + table.ht_size;
932 for ( ; v_slot < v_end; v_slot++)
933 if (! HASH_VACANT (*v_slot))
935 struct variable *v = *v_slot;
937 /* If V is recursively expanded and didn't come from the environment,
938 expand its value. If it came from the environment, it should
939 go back into the environment unchanged. */
940 if (v->recursive
941 && v->origin != o_env && v->origin != o_env_override)
943 char *value = recursively_expand_for_file (v, file);
944 #ifdef WINDOWS32
945 if (strcmp(v->name, "Path") == 0 ||
946 strcmp(v->name, "PATH") == 0)
947 convert_Path_to_windows32(value, ';');
948 #endif
949 *result++ = concat (v->name, "=", value);
950 free (value);
952 else
954 #ifdef WINDOWS32
955 if (strcmp(v->name, "Path") == 0 ||
956 strcmp(v->name, "PATH") == 0)
957 convert_Path_to_windows32(v->value, ';');
958 #endif
959 *result++ = concat (v->name, "=", v->value);
963 *result = (char *) xmalloc (100);
964 (void) sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
965 *++result = 0;
967 hash_free (&table, 0);
969 return result_0;
972 /* Given a variable, a value, and a flavor, define the variable.
973 See the try_variable_definition() function for details on the parameters. */
975 struct variable *
976 do_variable_definition (const struct floc *flocp, const char *varname,
977 char *value, enum variable_origin origin,
978 enum variable_flavor flavor, int target_var)
980 char *p, *alloc_value = NULL;
981 struct variable *v;
982 int append = 0;
983 int conditional = 0;
985 /* Calculate the variable's new value in VALUE. */
987 switch (flavor)
989 default:
990 case f_bogus:
991 /* Should not be possible. */
992 abort ();
993 case f_simple:
994 /* A simple variable definition "var := value". Expand the value.
995 We have to allocate memory since otherwise it'll clobber the
996 variable buffer, and we may still need that if we're looking at a
997 target-specific variable. */
998 p = alloc_value = allocated_variable_expand (value);
999 break;
1000 case f_conditional:
1001 /* A conditional variable definition "var ?= value".
1002 The value is set IFF the variable is not defined yet. */
1003 v = lookup_variable (varname, strlen (varname));
1004 if (v)
1005 return v;
1007 conditional = 1;
1008 flavor = f_recursive;
1009 /* FALLTHROUGH */
1010 case f_recursive:
1011 /* A recursive variable definition "var = value".
1012 The value is used verbatim. */
1013 p = value;
1014 break;
1015 case f_append:
1017 /* If we have += but we're in a target variable context, we want to
1018 append only with other variables in the context of this target. */
1019 if (target_var)
1021 append = 1;
1022 v = lookup_variable_in_set (varname, strlen (varname),
1023 current_variable_set_list->set);
1025 /* Don't append from the global set if a previous non-appending
1026 target-specific variable definition exists. */
1027 if (v && !v->append)
1028 append = 0;
1030 else
1031 v = lookup_variable (varname, strlen (varname));
1033 if (v == 0)
1035 /* There was no old value.
1036 This becomes a normal recursive definition. */
1037 p = value;
1038 flavor = f_recursive;
1040 else
1042 /* Paste the old and new values together in VALUE. */
1044 unsigned int oldlen, vallen;
1045 char *val;
1047 val = value;
1048 if (v->recursive)
1049 /* The previous definition of the variable was recursive.
1050 The new value is the unexpanded old and new values. */
1051 flavor = f_recursive;
1052 else
1053 /* The previous definition of the variable was simple.
1054 The new value comes from the old value, which was expanded
1055 when it was set; and from the expanded new value. Allocate
1056 memory for the expansion as we may still need the rest of the
1057 buffer if we're looking at a target-specific variable. */
1058 val = alloc_value = allocated_variable_expand (val);
1060 oldlen = strlen (v->value);
1061 vallen = strlen (val);
1062 p = (char *) alloca (oldlen + 1 + vallen + 1);
1063 bcopy (v->value, p, oldlen);
1064 p[oldlen] = ' ';
1065 bcopy (val, &p[oldlen + 1], vallen + 1);
1070 #ifdef __MSDOS__
1071 /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1072 non-Unix systems don't conform to this default configuration (in
1073 fact, most of them don't even have `/bin'). On the other hand,
1074 $SHELL in the environment, if set, points to the real pathname of
1075 the shell.
1076 Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1077 the Makefile override $SHELL from the environment. But first, we
1078 look for the basename of the shell in the directory where SHELL=
1079 points, and along the $PATH; if it is found in any of these places,
1080 we define $SHELL to be the actual pathname of the shell. Thus, if
1081 you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1082 your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1083 defining SHELL to be "d:/unix/bash.exe". */
1084 if ((origin == o_file || origin == o_override)
1085 && strcmp (varname, "SHELL") == 0)
1087 PATH_VAR (shellpath);
1088 extern char * __dosexec_find_on_path (const char *, char *[], char *);
1090 /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc. */
1091 if (__dosexec_find_on_path (p, (char **)0, shellpath))
1093 char *p;
1095 for (p = shellpath; *p; p++)
1097 if (*p == '\\')
1098 *p = '/';
1100 v = define_variable_loc (varname, strlen (varname),
1101 shellpath, origin, flavor == f_recursive,
1102 flocp);
1104 else
1106 char *shellbase, *bslash;
1107 struct variable *pathv = lookup_variable ("PATH", 4);
1108 char *path_string;
1109 char *fake_env[2];
1110 size_t pathlen = 0;
1112 shellbase = strrchr (p, '/');
1113 bslash = strrchr (p, '\\');
1114 if (!shellbase || bslash > shellbase)
1115 shellbase = bslash;
1116 if (!shellbase && p[1] == ':')
1117 shellbase = p + 1;
1118 if (shellbase)
1119 shellbase++;
1120 else
1121 shellbase = p;
1123 /* Search for the basename of the shell (with standard
1124 executable extensions) along the $PATH. */
1125 if (pathv)
1126 pathlen = strlen (pathv->value);
1127 path_string = (char *)xmalloc (5 + pathlen + 2 + 1);
1128 /* On MSDOS, current directory is considered as part of $PATH. */
1129 sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1130 fake_env[0] = path_string;
1131 fake_env[1] = (char *)0;
1132 if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1134 char *p;
1136 for (p = shellpath; *p; p++)
1138 if (*p == '\\')
1139 *p = '/';
1141 v = define_variable_loc (varname, strlen (varname),
1142 shellpath, origin,
1143 flavor == f_recursive, flocp);
1145 else
1146 v = lookup_variable (varname, strlen (varname));
1148 free (path_string);
1151 else
1152 #endif /* __MSDOS__ */
1153 #ifdef WINDOWS32
1154 if ((origin == o_file || origin == o_override) && streq (varname, "SHELL"))
1156 extern char *default_shell;
1158 /* Call shell locator function. If it returns TRUE, then
1159 set no_default_sh_exe to indicate sh was found and
1160 set new value for SHELL variable. */
1162 if (find_and_set_default_shell (p))
1164 v = define_variable_in_set (varname, strlen (varname), default_shell,
1165 origin, flavor == f_recursive,
1166 (target_var
1167 ? current_variable_set_list->set
1168 : NULL),
1169 flocp);
1170 no_default_sh_exe = 0;
1172 else
1173 v = lookup_variable (varname, strlen (varname));
1175 else
1176 #endif
1178 /* If we are defining variables inside an $(eval ...), we might have a
1179 different variable context pushed, not the global context (maybe we're
1180 inside a $(call ...) or something. Since this function is only ever
1181 invoked in places where we want to define globally visible variables,
1182 make sure we define this variable in the global set. */
1184 v = define_variable_in_set (varname, strlen (varname), p,
1185 origin, flavor == f_recursive,
1186 (target_var
1187 ? current_variable_set_list->set : NULL),
1188 flocp);
1189 v->append = append;
1190 v->conditional = conditional;
1192 if (alloc_value)
1193 free (alloc_value);
1195 return v;
1198 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1200 ORIGIN may be o_file, o_override, o_env, o_env_override,
1201 or o_command specifying that the variable definition comes
1202 from a makefile, an override directive, the environment with
1203 or without the -e switch, or the command line.
1205 See the comments for parse_variable_definition().
1207 If LINE was recognized as a variable definition, a pointer to its `struct
1208 variable' is returned. If LINE is not a variable definition, NULL is
1209 returned. */
1211 struct variable *
1212 parse_variable_definition (struct variable *v, char *line)
1214 register int c;
1215 register char *p = line;
1216 register char *beg;
1217 register char *end;
1218 enum variable_flavor flavor = f_bogus;
1219 char *name;
1221 while (1)
1223 c = *p++;
1224 if (c == '\0' || c == '#')
1225 return 0;
1226 if (c == '=')
1228 end = p - 1;
1229 flavor = f_recursive;
1230 break;
1232 else if (c == ':')
1233 if (*p == '=')
1235 end = p++ - 1;
1236 flavor = f_simple;
1237 break;
1239 else
1240 /* A colon other than := is a rule line, not a variable defn. */
1241 return 0;
1242 else if (c == '+' && *p == '=')
1244 end = p++ - 1;
1245 flavor = f_append;
1246 break;
1248 else if (c == '?' && *p == '=')
1250 end = p++ - 1;
1251 flavor = f_conditional;
1252 break;
1254 else if (c == '$')
1256 /* This might begin a variable expansion reference. Make sure we
1257 don't misrecognize chars inside the reference as =, := or +=. */
1258 char closeparen;
1259 int count;
1260 c = *p++;
1261 if (c == '(')
1262 closeparen = ')';
1263 else if (c == '{')
1264 closeparen = '}';
1265 else
1266 continue; /* Nope. */
1268 /* P now points past the opening paren or brace.
1269 Count parens or braces until it is matched. */
1270 count = 0;
1271 for (; *p != '\0'; ++p)
1273 if (*p == c)
1274 ++count;
1275 else if (*p == closeparen && --count < 0)
1277 ++p;
1278 break;
1283 v->flavor = flavor;
1285 beg = next_token (line);
1286 while (end > beg && isblank ((unsigned char)end[-1]))
1287 --end;
1288 p = next_token (p);
1289 v->value = p;
1291 /* Expand the name, so "$(foo)bar = baz" works. */
1292 name = (char *) alloca (end - beg + 1);
1293 bcopy (beg, name, end - beg);
1294 name[end - beg] = '\0';
1295 v->name = allocated_variable_expand (name);
1297 if (v->name[0] == '\0')
1298 fatal (&v->fileinfo, _("empty variable name"));
1300 return v;
1303 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1305 ORIGIN may be o_file, o_override, o_env, o_env_override,
1306 or o_command specifying that the variable definition comes
1307 from a makefile, an override directive, the environment with
1308 or without the -e switch, or the command line.
1310 See the comments for parse_variable_definition().
1312 If LINE was recognized as a variable definition, a pointer to its `struct
1313 variable' is returned. If LINE is not a variable definition, NULL is
1314 returned. */
1316 struct variable *
1317 try_variable_definition (const struct floc *flocp, char *line,
1318 enum variable_origin origin, int target_var)
1320 struct variable v;
1321 struct variable *vp;
1323 if (flocp != 0)
1324 v.fileinfo = *flocp;
1325 else
1326 v.fileinfo.filenm = 0;
1328 if (!parse_variable_definition (&v, line))
1329 return 0;
1331 vp = do_variable_definition (flocp, v.name, v.value,
1332 origin, v.flavor, target_var);
1334 free (v.name);
1336 return vp;
1339 /* Print information for variable V, prefixing it with PREFIX. */
1341 static void
1342 print_variable (const void *item, void *arg)
1344 const struct variable *v = (struct variable *) item;
1345 const char *prefix = (char *) arg;
1346 const char *origin;
1348 switch (v->origin)
1350 case o_default:
1351 origin = _("default");
1352 break;
1353 case o_env:
1354 origin = _("environment");
1355 break;
1356 case o_file:
1357 origin = _("makefile");
1358 break;
1359 case o_env_override:
1360 origin = _("environment under -e");
1361 break;
1362 case o_command:
1363 origin = _("command line");
1364 break;
1365 case o_override:
1366 origin = _("`override' directive");
1367 break;
1368 case o_automatic:
1369 origin = _("automatic");
1370 break;
1371 case o_invalid:
1372 default:
1373 abort ();
1375 fputs ("# ", stdout);
1376 fputs (origin, stdout);
1377 if (v->fileinfo.filenm)
1378 printf (_(" (from `%s', line %lu)"),
1379 v->fileinfo.filenm, v->fileinfo.lineno);
1380 putchar ('\n');
1381 fputs (prefix, stdout);
1383 /* Is this a `define'? */
1384 if (v->recursive && strchr (v->value, '\n') != 0)
1385 printf ("define %s\n%s\nendef\n", v->name, v->value);
1386 else
1388 register char *p;
1390 printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1392 /* Check if the value is just whitespace. */
1393 p = next_token (v->value);
1394 if (p != v->value && *p == '\0')
1395 /* All whitespace. */
1396 printf ("$(subst ,,%s)", v->value);
1397 else if (v->recursive)
1398 fputs (v->value, stdout);
1399 else
1400 /* Double up dollar signs. */
1401 for (p = v->value; *p != '\0'; ++p)
1403 if (*p == '$')
1404 putchar ('$');
1405 putchar (*p);
1407 putchar ('\n');
1412 /* Print all the variables in SET. PREFIX is printed before
1413 the actual variable definitions (everything else is comments). */
1415 void
1416 print_variable_set (struct variable_set *set, char *prefix)
1418 hash_map_arg (&set->table, print_variable, prefix);
1420 fputs (_("# variable set hash-table stats:\n"), stdout);
1421 fputs ("# ", stdout);
1422 hash_print_stats (&set->table, stdout);
1423 putc ('\n', stdout);
1426 /* Print the data base of variables. */
1428 void
1429 print_variable_data_base (void)
1431 puts (_("\n# Variables\n"));
1433 print_variable_set (&global_variable_set, "");
1435 puts (_("\n# Pattern-specific Variable Values"));
1438 struct pattern_var *p;
1439 int rules = 0;
1441 for (p = pattern_vars; p != 0; p = p->next)
1443 ++rules;
1444 printf ("\n%s :\n", p->target);
1445 print_variable (&p->variable, "# ");
1448 if (rules == 0)
1449 puts (_("\n# No pattern-specific variable values."));
1450 else
1451 printf (_("\n# %u pattern-specific variable values"), rules);
1456 /* Print all the local variables of FILE. */
1458 void
1459 print_file_variables (struct file *file)
1461 if (file->variables != 0)
1462 print_variable_set (file->variables->set, "# ");
1465 #ifdef WINDOWS32
1466 void
1467 sync_Path_environment (void)
1469 char *path = allocated_variable_expand ("$(PATH)");
1470 static char *environ_path = NULL;
1472 if (!path)
1473 return;
1476 * If done this before, don't leak memory unnecessarily.
1477 * Free the previous entry before allocating new one.
1479 if (environ_path)
1480 free (environ_path);
1483 * Create something WINDOWS32 world can grok
1485 convert_Path_to_windows32 (path, ';');
1486 environ_path = concat ("PATH", "=", path);
1487 putenv (environ_path);
1488 free (path);
1490 #endif