Imported Upstream version 3.82
[platform/upstream/make.git] / variable.c
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, 2008, 2009,
4 2010 Free Software Foundation, Inc.
5 This file is part of GNU Make.
6
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.
11
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.
15
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/>.  */
18
19 #include "make.h"
20
21 #include <assert.h>
22
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"
33
34 /* Chain of all pattern-specific variables.  */
35
36 static struct pattern_var *pattern_vars;
37
38 /* Pointer to the last struct in the pack of a specific size, from 1 to 255.*/
39
40 static struct pattern_var *last_pattern_vars[256];
41
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. */
48
49 struct pattern_var *
50 create_pattern_var (const char *target, const char *suffix)
51 {
52   register unsigned int len = strlen (target);
53   register struct pattern_var *p = xmalloc (sizeof (struct pattern_var));
54
55   if (pattern_vars != 0)
56     {
57       if (len < 256 && last_pattern_vars[len] != 0)
58         {
59           p->next = last_pattern_vars[len]->next;
60           last_pattern_vars[len]->next = p;
61         }
62       else
63         {
64           /* Find the position where we can insert this variable. */
65           register struct pattern_var **v;
66
67           for (v = &pattern_vars; ; v = &(*v)->next)
68             {
69               /* Insert at the end of the pack so that patterns with the
70                  same length appear in the order they were defined .*/
71
72               if (*v == 0 || (*v)->len > len)
73                 {
74                   p->next = *v;
75                   *v = p;
76                   break;
77                 }
78             }
79         }
80     }
81   else
82     {
83       pattern_vars = p;
84       p->next = 0;
85     }
86
87   p->target = target;
88   p->len = len;
89   p->suffix = suffix + 1;
90
91   if (len < 256)
92     last_pattern_vars[len] = p;
93
94   return p;
95 }
96
97 /* Look up a target in the pattern-specific variable list.  */
98
99 static struct pattern_var *
100 lookup_pattern_var (struct pattern_var *start, const char *target)
101 {
102   struct pattern_var *p;
103   unsigned int targlen = strlen(target);
104
105   for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
106     {
107       const char *stem;
108       unsigned int stemlen;
109
110       if (p->len > targlen)
111         /* It can't possibly match.  */
112         continue;
113
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;
118
119       /* Compare the text in the pattern before the stem, if any.  */
120       if (stem > target && !strneq (p->target, target, stem - target))
121         continue;
122
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;
131     }
132
133   return p;
134 }
135 \f
136 /* Hash table of all global variable definitions.  */
137
138 static unsigned long
139 variable_hash_1 (const void *keyv)
140 {
141   struct variable const *key = (struct variable const *) keyv;
142   return_STRING_N_HASH_1 (key->name, key->length);
143 }
144
145 static unsigned long
146 variable_hash_2 (const void *keyv)
147 {
148   struct variable const *key = (struct variable const *) keyv;
149   return_STRING_N_HASH_2 (key->name, key->length);
150 }
151
152 static int
153 variable_hash_cmp (const void *xv, const void *yv)
154 {
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);
161 }
162
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
172
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;
177 \f
178 /* Implement variables.  */
179
180 void
181 init_hash_global_variable_set (void)
182 {
183   hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
184              variable_hash_1, variable_hash_2, variable_hash_cmp);
185 }
186
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.  */
193
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)
199 {
200   struct variable *v;
201   struct variable **var_slot;
202   struct variable var_key;
203
204   if (set == NULL)
205     set = &global_variable_set;
206
207   var_key.name = (char *) name;
208   var_key.length = length;
209   var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
210
211   if (env_overrides && origin == o_env)
212     origin = o_env_override;
213
214   v = *var_slot;
215   if (! HASH_VACANT (v))
216     {
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;
221
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)
226         {
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;
236         }
237       return v;
238     }
239
240   /* Create a new variable definition and add it to the hash table.  */
241
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;
260
261   v->exportable = 1;
262   if (*name != '_' && (*name < 'A' || *name > 'Z')
263       && (*name < 'a' || *name > 'z'))
264     v->exportable = 0;
265   else
266     {
267       for (++name; *name != '\0'; ++name)
268         if (*name != '_' && (*name < 'a' || *name > 'z')
269             && (*name < 'A' || *name > 'Z') && !ISDIGIT(*name))
270           break;
271
272       if (*name != '\0')
273         v->exportable = 0;
274     }
275
276   return v;
277 }
278 \f
279
280 /* Undefine variable named NAME in SET. LENGTH is the length of NAME, which
281    does not need to be null-terminated. ORIGIN specifies the origin of the
282    variable (makefile, command line or environment). */
283
284 static void
285 free_variable_name_and_value (const void *item);
286
287 void
288 undefine_variable_in_set (const char *name, unsigned int length,
289                           enum variable_origin origin,
290                           struct variable_set *set)
291 {
292   struct variable *v;
293   struct variable **var_slot;
294   struct variable var_key;
295
296   if (set == NULL)
297     set = &global_variable_set;
298
299   var_key.name = (char *) name;
300   var_key.length = length;
301   var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
302
303   if (env_overrides && origin == o_env)
304     origin = o_env_override;
305
306   v = *var_slot;
307   if (! HASH_VACANT (v))
308     {
309       if (env_overrides && v->origin == o_env)
310         /* V came from in the environment.  Since it was defined
311            before the switches were parsed, it wasn't affected by -e.  */
312         v->origin = o_env_override;
313
314       /* If the definition is from a stronger source than this one, don't
315          undefine it.  */
316       if ((int) origin >= (int) v->origin)
317         {
318           hash_delete_at (&set->table, var_slot);
319           free_variable_name_and_value (v);
320         }
321     }
322 }
323
324 /* If the variable passed in is "special", handle its special nature.
325    Currently there are two such variables, both used for introspection:
326    .VARIABLES expands to a list of all the variables defined in this instance
327    of make.
328    .TARGETS expands to a list of all the targets defined in this
329    instance of make.
330    Returns the variable reference passed in.  */
331
332 #define EXPANSION_INCREMENT(_l)  ((((_l) / 500) + 1) * 500)
333
334 static struct variable *
335 lookup_special_var (struct variable *var)
336 {
337   static unsigned long last_var_count = 0;
338
339
340   /* This one actually turns out to be very hard, due to the way the parser
341      records targets.  The way it works is that target information is collected
342      internally until make knows the target is completely specified.  It unitl
343      it sees that some new construct (a new target or variable) is defined that
344      it knows the previous one is done.  In short, this means that if you do
345      this:
346
347        all:
348
349        TARGS := $(.TARGETS)
350
351      then $(TARGS) won't contain "all", because it's not until after the
352      variable is created that the previous target is completed.
353
354      Changing this would be a major pain.  I think a less complex way to do it
355      would be to pre-define the target files as soon as the first line is
356      parsed, then come back and do the rest of the definition as now.  That
357      would allow $(.TARGETS) to be correct without a major change to the way
358      the parser works.
359
360   if (streq (var->name, ".TARGETS"))
361     var->value = build_target_list (var->value);
362   else
363   */
364
365   if (streq (var->name, ".VARIABLES")
366       && global_variable_set.table.ht_fill != last_var_count)
367     {
368       unsigned long max = EXPANSION_INCREMENT (strlen (var->value));
369       unsigned long len;
370       char *p;
371       struct variable **vp = (struct variable **) global_variable_set.table.ht_vec;
372       struct variable **end = &vp[global_variable_set.table.ht_size];
373
374       /* Make sure we have at least MAX bytes in the allocated buffer.  */
375       var->value = xrealloc (var->value, max);
376
377       /* Walk through the hash of variables, constructing a list of names.  */
378       p = var->value;
379       len = 0;
380       for (; vp < end; ++vp)
381         if (!HASH_VACANT (*vp))
382           {
383             struct variable *v = *vp;
384             int l = v->length;
385
386             len += l + 1;
387             if (len > max)
388               {
389                 unsigned long off = p - var->value;
390
391                 max += EXPANSION_INCREMENT (l + 1);
392                 var->value = xrealloc (var->value, max);
393                 p = &var->value[off];
394               }
395
396             memcpy (p, v->name, l);
397             p += l;
398             *(p++) = ' ';
399           }
400       *(p-1) = '\0';
401
402       /* Remember how many variables are in our current count.  Since we never
403          remove variables from the list, this is a reliable way to know whether
404          the list is up to date or needs to be recomputed.  */
405
406       last_var_count = global_variable_set.table.ht_fill;
407     }
408
409   return var;
410 }
411
412 \f
413 /* Lookup a variable whose name is a string starting at NAME
414    and with LENGTH chars.  NAME need not be null-terminated.
415    Returns address of the `struct variable' containing all info
416    on the variable, or nil if no such variable is defined.  */
417
418 struct variable *
419 lookup_variable (const char *name, unsigned int length)
420 {
421   const struct variable_set_list *setlist;
422   struct variable var_key;
423   int is_parent = 0;
424
425   var_key.name = (char *) name;
426   var_key.length = length;
427
428   for (setlist = current_variable_set_list;
429        setlist != 0; setlist = setlist->next)
430     {
431       const struct variable_set *set = setlist->set;
432       struct variable *v;
433
434       v = (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
435       if (v && (!is_parent || !v->private_var))
436         return v->special ? lookup_special_var (v) : v;
437
438       is_parent |= setlist->next_is_parent;
439     }
440
441 #ifdef VMS
442   /* since we don't read envp[] on startup, try to get the
443      variable via getenv() here.  */
444   {
445     char *vname = alloca (length + 1);
446     char *value;
447     strncpy (vname, name, length);
448     vname[length] = 0;
449     value = getenv (vname);
450     if (value != 0)
451       {
452         char *sptr;
453         int scnt;
454
455         sptr = value;
456         scnt = 0;
457
458         while ((sptr = strchr (sptr, '$')))
459           {
460             scnt++;
461             sptr++;
462           }
463
464         if (scnt > 0)
465           {
466             char *nvalue;
467             char *nptr;
468
469             nvalue = alloca (strlen (value) + scnt + 1);
470             sptr = value;
471             nptr = nvalue;
472
473             while (*sptr)
474               {
475                 if (*sptr == '$')
476                   {
477                     *nptr++ = '$';
478                     *nptr++ = '$';
479                   }
480                 else
481                   {
482                     *nptr++ = *sptr;
483                   }
484                 sptr++;
485               }
486
487             *nptr = '\0';
488             return define_variable (vname, length, nvalue, o_env, 1);
489
490           }
491
492         return define_variable (vname, length, value, o_env, 1);
493       }
494   }
495 #endif /* VMS */
496
497   return 0;
498 }
499 \f
500 /* Lookup a variable whose name is a string starting at NAME
501    and with LENGTH chars in set SET.  NAME need not be null-terminated.
502    Returns address of the `struct variable' containing all info
503    on the variable, or nil if no such variable is defined.  */
504
505 struct variable *
506 lookup_variable_in_set (const char *name, unsigned int length,
507                         const struct variable_set *set)
508 {
509   struct variable var_key;
510
511   var_key.name = (char *) name;
512   var_key.length = length;
513
514   return (struct variable *) hash_find_item ((struct hash_table *) &set->table, &var_key);
515 }
516 \f
517 /* Initialize FILE's variable set list.  If FILE already has a variable set
518    list, the topmost variable set is left intact, but the the rest of the
519    chain is replaced with FILE->parent's setlist.  If FILE is a double-colon
520    rule, then we will use the "root" double-colon target's variable set as the
521    parent of FILE's variable set.
522
523    If we're READING a makefile, don't do the pattern variable search now,
524    since the pattern variable might not have been defined yet.  */
525
526 void
527 initialize_file_variables (struct file *file, int reading)
528 {
529   struct variable_set_list *l = file->variables;
530
531   if (l == 0)
532     {
533       l = (struct variable_set_list *)
534         xmalloc (sizeof (struct variable_set_list));
535       l->set = xmalloc (sizeof (struct variable_set));
536       hash_init (&l->set->table, PERFILE_VARIABLE_BUCKETS,
537                  variable_hash_1, variable_hash_2, variable_hash_cmp);
538       file->variables = l;
539     }
540
541   /* If this is a double-colon, then our "parent" is the "root" target for
542      this double-colon rule.  Since that rule has the same name, parent,
543      etc. we can just use its variables as the "next" for ours.  */
544
545   if (file->double_colon && file->double_colon != file)
546     {
547       initialize_file_variables (file->double_colon, reading);
548       l->next = file->double_colon->variables;
549       l->next_is_parent = 0;
550       return;
551     }
552
553   if (file->parent == 0)
554     l->next = &global_setlist;
555   else
556     {
557       initialize_file_variables (file->parent, reading);
558       l->next = file->parent->variables;
559     }
560   l->next_is_parent = 1;
561
562   /* If we're not reading makefiles and we haven't looked yet, see if
563      we can find pattern variables for this target.  */
564
565   if (!reading && !file->pat_searched)
566     {
567       struct pattern_var *p;
568
569       p = lookup_pattern_var (0, file->name);
570       if (p != 0)
571         {
572           struct variable_set_list *global = current_variable_set_list;
573
574           /* We found at least one.  Set up a new variable set to accumulate
575              all the pattern variables that match this target.  */
576
577           file->pat_variables = create_new_variable_set ();
578           current_variable_set_list = file->pat_variables;
579
580           do
581             {
582               /* We found one, so insert it into the set.  */
583
584               struct variable *v;
585
586               if (p->variable.flavor == f_simple)
587                 {
588                   v = define_variable_loc (
589                     p->variable.name, strlen (p->variable.name),
590                     p->variable.value, p->variable.origin,
591                     0, &p->variable.fileinfo);
592
593                   v->flavor = f_simple;
594                 }
595               else
596                 {
597                   v = do_variable_definition (
598                     &p->variable.fileinfo, p->variable.name,
599                     p->variable.value, p->variable.origin,
600                     p->variable.flavor, 1);
601                 }
602
603               /* Also mark it as a per-target and copy export status. */
604               v->per_target = p->variable.per_target;
605               v->export = p->variable.export;
606               v->private_var = p->variable.private_var;
607             }
608           while ((p = lookup_pattern_var (p, file->name)) != 0);
609
610           current_variable_set_list = global;
611         }
612       file->pat_searched = 1;
613     }
614
615   /* If we have a pattern variable match, set it up.  */
616
617   if (file->pat_variables != 0)
618     {
619       file->pat_variables->next = l->next;
620       file->pat_variables->next_is_parent = l->next_is_parent;
621       l->next = file->pat_variables;
622       l->next_is_parent = 0;
623     }
624 }
625 \f
626 /* Pop the top set off the current variable set list,
627    and free all its storage.  */
628
629 struct variable_set_list *
630 create_new_variable_set (void)
631 {
632   register struct variable_set_list *setlist;
633   register struct variable_set *set;
634
635   set = xmalloc (sizeof (struct variable_set));
636   hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
637              variable_hash_1, variable_hash_2, variable_hash_cmp);
638
639   setlist = (struct variable_set_list *)
640     xmalloc (sizeof (struct variable_set_list));
641   setlist->set = set;
642   setlist->next = current_variable_set_list;
643   setlist->next_is_parent = 0;
644
645   return setlist;
646 }
647
648 static void
649 free_variable_name_and_value (const void *item)
650 {
651   struct variable *v = (struct variable *) item;
652   free (v->name);
653   free (v->value);
654 }
655
656 void
657 free_variable_set (struct variable_set_list *list)
658 {
659   hash_map (&list->set->table, free_variable_name_and_value);
660   hash_free (&list->set->table, 1);
661   free (list->set);
662   free (list);
663 }
664
665 /* Create a new variable set and push it on the current setlist.
666    If we're pushing a global scope (that is, the current scope is the global
667    scope) then we need to "push" it the other way: file variable sets point
668    directly to the global_setlist so we need to replace that with the new one.
669  */
670
671 struct variable_set_list *
672 push_new_variable_scope (void)
673 {
674   current_variable_set_list = create_new_variable_set();
675   if (current_variable_set_list->next == &global_setlist)
676     {
677       /* It was the global, so instead of new -> &global we want to replace
678          &global with the new one and have &global -> new, with current still
679          pointing to &global  */
680       struct variable_set *set = current_variable_set_list->set;
681       current_variable_set_list->set = global_setlist.set;
682       global_setlist.set = set;
683       current_variable_set_list->next = global_setlist.next;
684       global_setlist.next = current_variable_set_list;
685       current_variable_set_list = &global_setlist;
686     }
687   return (current_variable_set_list);
688 }
689
690 void
691 pop_variable_scope (void)
692 {
693   struct variable_set_list *setlist;
694   struct variable_set *set;
695
696   /* Can't call this if there's no scope to pop!  */
697   assert(current_variable_set_list->next != NULL);
698
699   if (current_variable_set_list != &global_setlist)
700     {
701       /* We're not pointing to the global setlist, so pop this one.  */
702       setlist = current_variable_set_list;
703       set = setlist->set;
704       current_variable_set_list = setlist->next;
705     }
706   else
707     {
708       /* This set is the one in the global_setlist, but there is another global
709          set beyond that.  We want to copy that set to global_setlist, then
710          delete what used to be in global_setlist.  */
711       setlist = global_setlist.next;
712       set = global_setlist.set;
713       global_setlist.set = setlist->set;
714       global_setlist.next = setlist->next;
715       global_setlist.next_is_parent = setlist->next_is_parent;
716     }
717
718   /* Free the one we no longer need.  */
719   free (setlist);
720   hash_map (&set->table, free_variable_name_and_value);
721   hash_free (&set->table, 1);
722   free (set);
723 }
724 \f
725 /* Merge FROM_SET into TO_SET, freeing unused storage in FROM_SET.  */
726
727 static void
728 merge_variable_sets (struct variable_set *to_set,
729                      struct variable_set *from_set)
730 {
731   struct variable **from_var_slot = (struct variable **) from_set->table.ht_vec;
732   struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
733
734   for ( ; from_var_slot < from_var_end; from_var_slot++)
735     if (! HASH_VACANT (*from_var_slot))
736       {
737         struct variable *from_var = *from_var_slot;
738         struct variable **to_var_slot
739           = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
740         if (HASH_VACANT (*to_var_slot))
741           hash_insert_at (&to_set->table, from_var, to_var_slot);
742         else
743           {
744             /* GKM FIXME: delete in from_set->table */
745             free (from_var->value);
746             free (from_var);
747           }
748       }
749 }
750
751 /* Merge SETLIST1 into SETLIST0, freeing unused storage in SETLIST1.  */
752
753 void
754 merge_variable_set_lists (struct variable_set_list **setlist0,
755                           struct variable_set_list *setlist1)
756 {
757   struct variable_set_list *to = *setlist0;
758   struct variable_set_list *last0 = 0;
759
760   /* If there's nothing to merge, stop now.  */
761   if (!setlist1)
762     return;
763
764   /* This loop relies on the fact that all setlists terminate with the global
765      setlist (before NULL).  If that's not true, arguably we SHOULD die.  */
766   if (to)
767     while (setlist1 != &global_setlist && to != &global_setlist)
768       {
769         struct variable_set_list *from = setlist1;
770         setlist1 = setlist1->next;
771
772         merge_variable_sets (to->set, from->set);
773
774         last0 = to;
775         to = to->next;
776       }
777
778   if (setlist1 != &global_setlist)
779     {
780       if (last0 == 0)
781         *setlist0 = setlist1;
782       else
783         last0->next = setlist1;
784     }
785 }
786 \f
787 /* Define the automatic variables, and record the addresses
788    of their structures so we can change their values quickly.  */
789
790 void
791 define_automatic_variables (void)
792 {
793 #if defined(WINDOWS32) || defined(__EMX__)
794   extern char* default_shell;
795 #else
796   extern char default_shell[];
797 #endif
798   register struct variable *v;
799   char buf[200];
800
801   sprintf (buf, "%u", makelevel);
802   define_variable_cname (MAKELEVEL_NAME, buf, o_env, 0);
803
804   sprintf (buf, "%s%s%s",
805            version_string,
806            (remote_description == 0 || remote_description[0] == '\0')
807            ? "" : "-",
808            (remote_description == 0 || remote_description[0] == '\0')
809            ? "" : remote_description);
810   define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
811
812 #ifdef  __MSDOS__
813   /* Allow to specify a special shell just for Make,
814      and use $COMSPEC as the default $SHELL when appropriate.  */
815   {
816     static char shell_str[] = "SHELL";
817     const int shlen = sizeof (shell_str) - 1;
818     struct variable *mshp = lookup_variable ("MAKESHELL", 9);
819     struct variable *comp = lookup_variable ("COMSPEC", 7);
820
821     /* $(MAKESHELL) overrides $(SHELL) even if -e is in effect.  */
822     if (mshp)
823       (void) define_variable (shell_str, shlen,
824                               mshp->value, o_env_override, 0);
825     else if (comp)
826       {
827         /* $(COMSPEC) shouldn't override $(SHELL).  */
828         struct variable *shp = lookup_variable (shell_str, shlen);
829
830         if (!shp)
831           (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
832       }
833   }
834 #elif defined(__EMX__)
835   {
836     static char shell_str[] = "SHELL";
837     const int shlen = sizeof (shell_str) - 1;
838     struct variable *shell = lookup_variable (shell_str, shlen);
839     struct variable *replace = lookup_variable ("MAKESHELL", 9);
840
841     /* if $MAKESHELL is defined in the environment assume o_env_override */
842     if (replace && *replace->value && replace->origin == o_env)
843       replace->origin = o_env_override;
844
845     /* if $MAKESHELL is not defined use $SHELL but only if the variable
846        did not come from the environment */
847     if (!replace || !*replace->value)
848       if (shell && *shell->value && (shell->origin == o_env
849           || shell->origin == o_env_override))
850         {
851           /* overwrite whatever we got from the environment */
852           free(shell->value);
853           shell->value = xstrdup (default_shell);
854           shell->origin = o_default;
855         }
856
857     /* Some people do not like cmd to be used as the default
858        if $SHELL is not defined in the Makefile.
859        With -DNO_CMD_DEFAULT you can turn off this behaviour */
860 # ifndef NO_CMD_DEFAULT
861     /* otherwise use $COMSPEC */
862     if (!replace || !*replace->value)
863       replace = lookup_variable ("COMSPEC", 7);
864
865     /* otherwise use $OS2_SHELL */
866     if (!replace || !*replace->value)
867       replace = lookup_variable ("OS2_SHELL", 9);
868 # else
869 #   warning NO_CMD_DEFAULT: GNU make will not use CMD.EXE as default shell
870 # endif
871
872     if (replace && *replace->value)
873       /* overwrite $SHELL */
874       (void) define_variable (shell_str, shlen, replace->value,
875                               replace->origin, 0);
876     else
877       /* provide a definition if there is none */
878       (void) define_variable (shell_str, shlen, default_shell,
879                               o_default, 0);
880   }
881
882 #endif
883
884   /* This won't override any definition, but it will provide one if there
885      isn't one there.  */
886   v = define_variable_cname ("SHELL", default_shell, o_default, 0);
887 #ifdef __MSDOS__
888   v->export = v_export;  /*  Export always SHELL.  */
889 #endif
890
891   /* On MSDOS we do use SHELL from environment, since it isn't a standard
892      environment variable on MSDOS, so whoever sets it, does that on purpose.
893      On OS/2 we do not use SHELL from environment but we have already handled
894      that problem above. */
895 #if !defined(__MSDOS__) && !defined(__EMX__)
896   /* Don't let SHELL come from the environment.  */
897   if (*v->value == '\0' || v->origin == o_env || v->origin == o_env_override)
898     {
899       free (v->value);
900       v->origin = o_file;
901       v->value = xstrdup (default_shell);
902     }
903 #endif
904
905   /* Make sure MAKEFILES gets exported if it is set.  */
906   v = define_variable_cname ("MAKEFILES", "", o_default, 0);
907   v->export = v_ifset;
908
909   /* Define the magic D and F variables in terms of
910      the automatic variables they are variations of.  */
911
912 #ifdef VMS
913   define_variable_cname ("@D", "$(dir $@)", o_automatic, 1);
914   define_variable_cname ("%D", "$(dir $%)", o_automatic, 1);
915   define_variable_cname ("*D", "$(dir $*)", o_automatic, 1);
916   define_variable_cname ("<D", "$(dir $<)", o_automatic, 1);
917   define_variable_cname ("?D", "$(dir $?)", o_automatic, 1);
918   define_variable_cname ("^D", "$(dir $^)", o_automatic, 1);
919   define_variable_cname ("+D", "$(dir $+)", o_automatic, 1);
920 #else
921   define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
922   define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
923   define_variable_cname ("*D", "$(patsubst %/,%,$(dir $*))", o_automatic, 1);
924   define_variable_cname ("<D", "$(patsubst %/,%,$(dir $<))", o_automatic, 1);
925   define_variable_cname ("?D", "$(patsubst %/,%,$(dir $?))", o_automatic, 1);
926   define_variable_cname ("^D", "$(patsubst %/,%,$(dir $^))", o_automatic, 1);
927   define_variable_cname ("+D", "$(patsubst %/,%,$(dir $+))", o_automatic, 1);
928 #endif
929   define_variable_cname ("@F", "$(notdir $@)", o_automatic, 1);
930   define_variable_cname ("%F", "$(notdir $%)", o_automatic, 1);
931   define_variable_cname ("*F", "$(notdir $*)", o_automatic, 1);
932   define_variable_cname ("<F", "$(notdir $<)", o_automatic, 1);
933   define_variable_cname ("?F", "$(notdir $?)", o_automatic, 1);
934   define_variable_cname ("^F", "$(notdir $^)", o_automatic, 1);
935   define_variable_cname ("+F", "$(notdir $+)", o_automatic, 1);
936 }
937 \f
938 int export_all_variables;
939
940 /* Create a new environment for FILE's commands.
941    If FILE is nil, this is for the `shell' function.
942    The child's MAKELEVEL variable is incremented.  */
943
944 char **
945 target_environment (struct file *file)
946 {
947   struct variable_set_list *set_list;
948   register struct variable_set_list *s;
949   struct hash_table table;
950   struct variable **v_slot;
951   struct variable **v_end;
952   struct variable makelevel_key;
953   char **result_0;
954   char **result;
955
956   if (file == 0)
957     set_list = current_variable_set_list;
958   else
959     set_list = file->variables;
960
961   hash_init (&table, VARIABLE_BUCKETS,
962              variable_hash_1, variable_hash_2, variable_hash_cmp);
963
964   /* Run through all the variable sets in the list,
965      accumulating variables in TABLE.  */
966   for (s = set_list; s != 0; s = s->next)
967     {
968       struct variable_set *set = s->set;
969       v_slot = (struct variable **) set->table.ht_vec;
970       v_end = v_slot + set->table.ht_size;
971       for ( ; v_slot < v_end; v_slot++)
972         if (! HASH_VACANT (*v_slot))
973           {
974             struct variable **new_slot;
975             struct variable *v = *v_slot;
976
977             /* If this is a per-target variable and it hasn't been touched
978                already then look up the global version and take its export
979                value.  */
980             if (v->per_target && v->export == v_default)
981               {
982                 struct variable *gv;
983
984                 gv = lookup_variable_in_set (v->name, strlen(v->name),
985                                              &global_variable_set);
986                 if (gv)
987                   v->export = gv->export;
988               }
989
990             switch (v->export)
991               {
992               case v_default:
993                 if (v->origin == o_default || v->origin == o_automatic)
994                   /* Only export default variables by explicit request.  */
995                   continue;
996
997                 /* The variable doesn't have a name that can be exported.  */
998                 if (! v->exportable)
999                   continue;
1000
1001                 if (! export_all_variables
1002                     && v->origin != o_command
1003                     && v->origin != o_env && v->origin != o_env_override)
1004                   continue;
1005                 break;
1006
1007               case v_export:
1008                 break;
1009
1010               case v_noexport:
1011                 {
1012                   /* If this is the SHELL variable and it's not exported,
1013                      then add the value from our original environment, if
1014                      the original environment defined a value for SHELL.  */
1015                   extern struct variable shell_var;
1016                   if (streq (v->name, "SHELL") && shell_var.value)
1017                     {
1018                       v = &shell_var;
1019                       break;
1020                     }
1021                   continue;
1022                 }
1023
1024               case v_ifset:
1025                 if (v->origin == o_default)
1026                   continue;
1027                 break;
1028               }
1029
1030             new_slot = (struct variable **) hash_find_slot (&table, v);
1031             if (HASH_VACANT (*new_slot))
1032               hash_insert_at (&table, v, new_slot);
1033           }
1034     }
1035
1036   makelevel_key.name = MAKELEVEL_NAME;
1037   makelevel_key.length = MAKELEVEL_LENGTH;
1038   hash_delete (&table, &makelevel_key);
1039
1040   result = result_0 = xmalloc ((table.ht_fill + 2) * sizeof (char *));
1041
1042   v_slot = (struct variable **) table.ht_vec;
1043   v_end = v_slot + table.ht_size;
1044   for ( ; v_slot < v_end; v_slot++)
1045     if (! HASH_VACANT (*v_slot))
1046       {
1047         struct variable *v = *v_slot;
1048
1049         /* If V is recursively expanded and didn't come from the environment,
1050            expand its value.  If it came from the environment, it should
1051            go back into the environment unchanged.  */
1052         if (v->recursive
1053             && v->origin != o_env && v->origin != o_env_override)
1054           {
1055             char *value = recursively_expand_for_file (v, file);
1056 #ifdef WINDOWS32
1057             if (strcmp(v->name, "Path") == 0 ||
1058                 strcmp(v->name, "PATH") == 0)
1059               convert_Path_to_windows32(value, ';');
1060 #endif
1061             *result++ = xstrdup (concat (3, v->name, "=", value));
1062             free (value);
1063           }
1064         else
1065           {
1066 #ifdef WINDOWS32
1067             if (strcmp(v->name, "Path") == 0 ||
1068                 strcmp(v->name, "PATH") == 0)
1069               convert_Path_to_windows32(v->value, ';');
1070 #endif
1071             *result++ = xstrdup (concat (3, v->name, "=", v->value));
1072           }
1073       }
1074
1075   *result = xmalloc (100);
1076   sprintf (*result, "%s=%u", MAKELEVEL_NAME, makelevel + 1);
1077   *++result = 0;
1078
1079   hash_free (&table, 0);
1080
1081   return result_0;
1082 }
1083 \f
1084 static struct variable *
1085 set_special_var (struct variable *var)
1086 {
1087   if (streq (var->name, RECIPEPREFIX_NAME))
1088     {
1089       /* The user is resetting the command introduction prefix.  This has to
1090          happen immediately, so that subsequent rules are interpreted
1091          properly.  */
1092       cmd_prefix = var->value[0]=='\0' ? RECIPEPREFIX_DEFAULT : var->value[0];
1093     }
1094
1095   return var;
1096 }
1097 \f
1098 /* Given a variable, a value, and a flavor, define the variable.
1099    See the try_variable_definition() function for details on the parameters. */
1100
1101 struct variable *
1102 do_variable_definition (const struct floc *flocp, const char *varname,
1103                         const char *value, enum variable_origin origin,
1104                         enum variable_flavor flavor, int target_var)
1105 {
1106   const char *p;
1107   char *alloc_value = NULL;
1108   struct variable *v;
1109   int append = 0;
1110   int conditional = 0;
1111
1112   /* Calculate the variable's new value in VALUE.  */
1113
1114   switch (flavor)
1115     {
1116     default:
1117     case f_bogus:
1118       /* Should not be possible.  */
1119       abort ();
1120     case f_simple:
1121       /* A simple variable definition "var := value".  Expand the value.
1122          We have to allocate memory since otherwise it'll clobber the
1123          variable buffer, and we may still need that if we're looking at a
1124          target-specific variable.  */
1125       p = alloc_value = allocated_variable_expand (value);
1126       break;
1127     case f_conditional:
1128       /* A conditional variable definition "var ?= value".
1129          The value is set IFF the variable is not defined yet. */
1130       v = lookup_variable (varname, strlen (varname));
1131       if (v)
1132         return v->special ? set_special_var (v) : v;
1133
1134       conditional = 1;
1135       flavor = f_recursive;
1136       /* FALLTHROUGH */
1137     case f_recursive:
1138       /* A recursive variable definition "var = value".
1139          The value is used verbatim.  */
1140       p = value;
1141       break;
1142     case f_append:
1143       {
1144         /* If we have += but we're in a target variable context, we want to
1145            append only with other variables in the context of this target.  */
1146         if (target_var)
1147           {
1148             append = 1;
1149             v = lookup_variable_in_set (varname, strlen (varname),
1150                                         current_variable_set_list->set);
1151
1152             /* Don't append from the global set if a previous non-appending
1153                target-specific variable definition exists. */
1154             if (v && !v->append)
1155               append = 0;
1156           }
1157         else
1158           v = lookup_variable (varname, strlen (varname));
1159
1160         if (v == 0)
1161           {
1162             /* There was no old value.
1163                This becomes a normal recursive definition.  */
1164             p = value;
1165             flavor = f_recursive;
1166           }
1167         else
1168           {
1169             /* Paste the old and new values together in VALUE.  */
1170
1171             unsigned int oldlen, vallen;
1172             const char *val;
1173             char *tp = NULL;
1174
1175             val = value;
1176             if (v->recursive)
1177               /* The previous definition of the variable was recursive.
1178                  The new value is the unexpanded old and new values. */
1179               flavor = f_recursive;
1180             else
1181               /* The previous definition of the variable was simple.
1182                  The new value comes from the old value, which was expanded
1183                  when it was set; and from the expanded new value.  Allocate
1184                  memory for the expansion as we may still need the rest of the
1185                  buffer if we're looking at a target-specific variable.  */
1186               val = tp = allocated_variable_expand (val);
1187
1188             oldlen = strlen (v->value);
1189             vallen = strlen (val);
1190             p = alloc_value = xmalloc (oldlen + 1 + vallen + 1);
1191             memcpy (alloc_value, v->value, oldlen);
1192             alloc_value[oldlen] = ' ';
1193             memcpy (&alloc_value[oldlen + 1], val, vallen + 1);
1194
1195             if (tp)
1196               free (tp);
1197           }
1198       }
1199     }
1200
1201 #ifdef __MSDOS__
1202   /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
1203      non-Unix systems don't conform to this default configuration (in
1204      fact, most of them don't even have `/bin').  On the other hand,
1205      $SHELL in the environment, if set, points to the real pathname of
1206      the shell.
1207      Therefore, we generally won't let lines like "SHELL=/bin/sh" from
1208      the Makefile override $SHELL from the environment.  But first, we
1209      look for the basename of the shell in the directory where SHELL=
1210      points, and along the $PATH; if it is found in any of these places,
1211      we define $SHELL to be the actual pathname of the shell.  Thus, if
1212      you have bash.exe installed as d:/unix/bash.exe, and d:/unix is on
1213      your $PATH, then SHELL=/usr/local/bin/bash will have the effect of
1214      defining SHELL to be "d:/unix/bash.exe".  */
1215   if ((origin == o_file || origin == o_override)
1216       && strcmp (varname, "SHELL") == 0)
1217     {
1218       PATH_VAR (shellpath);
1219       extern char * __dosexec_find_on_path (const char *, char *[], char *);
1220
1221       /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc.  */
1222       if (__dosexec_find_on_path (p, NULL, shellpath))
1223         {
1224           char *tp;
1225
1226           for (tp = shellpath; *tp; tp++)
1227             if (*tp == '\\')
1228               *tp = '/';
1229
1230           v = define_variable_loc (varname, strlen (varname),
1231                                    shellpath, origin, flavor == f_recursive,
1232                                    flocp);
1233         }
1234       else
1235         {
1236           const char *shellbase, *bslash;
1237           struct variable *pathv = lookup_variable ("PATH", 4);
1238           char *path_string;
1239           char *fake_env[2];
1240           size_t pathlen = 0;
1241
1242           shellbase = strrchr (p, '/');
1243           bslash = strrchr (p, '\\');
1244           if (!shellbase || bslash > shellbase)
1245             shellbase = bslash;
1246           if (!shellbase && p[1] == ':')
1247             shellbase = p + 1;
1248           if (shellbase)
1249             shellbase++;
1250           else
1251             shellbase = p;
1252
1253           /* Search for the basename of the shell (with standard
1254              executable extensions) along the $PATH.  */
1255           if (pathv)
1256             pathlen = strlen (pathv->value);
1257           path_string = xmalloc (5 + pathlen + 2 + 1);
1258           /* On MSDOS, current directory is considered as part of $PATH.  */
1259           sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
1260           fake_env[0] = path_string;
1261           fake_env[1] = 0;
1262           if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
1263             {
1264               char *tp;
1265
1266               for (tp = shellpath; *tp; tp++)
1267                 if (*tp == '\\')
1268                   *tp = '/';
1269
1270               v = define_variable_loc (varname, strlen (varname),
1271                                        shellpath, origin,
1272                                        flavor == f_recursive, flocp);
1273             }
1274           else
1275             v = lookup_variable (varname, strlen (varname));
1276
1277           free (path_string);
1278         }
1279     }
1280   else
1281 #endif /* __MSDOS__ */
1282 #ifdef WINDOWS32
1283   if ((origin == o_file || origin == o_override || origin == o_command)
1284       && streq (varname, "SHELL"))
1285     {
1286       extern char *default_shell;
1287
1288       /* Call shell locator function. If it returns TRUE, then
1289          set no_default_sh_exe to indicate sh was found and
1290          set new value for SHELL variable.  */
1291
1292       if (find_and_set_default_shell (p))
1293         {
1294           v = define_variable_in_set (varname, strlen (varname), default_shell,
1295                                       origin, flavor == f_recursive,
1296                                       (target_var
1297                                        ? current_variable_set_list->set
1298                                        : NULL),
1299                                       flocp);
1300           no_default_sh_exe = 0;
1301         }
1302       else
1303         {
1304           char *tp = alloc_value;
1305
1306           alloc_value = allocated_variable_expand (p);
1307
1308           if (find_and_set_default_shell (alloc_value))
1309             {
1310               v = define_variable_in_set (varname, strlen (varname), p,
1311                                           origin, flavor == f_recursive,
1312                                           (target_var
1313                                            ? current_variable_set_list->set
1314                                            : NULL),
1315                                           flocp);
1316               no_default_sh_exe = 0;
1317             }
1318           else
1319             v = lookup_variable (varname, strlen (varname));
1320
1321           if (tp)
1322             free (tp);
1323         }
1324     }
1325   else
1326 #endif
1327
1328   /* If we are defining variables inside an $(eval ...), we might have a
1329      different variable context pushed, not the global context (maybe we're
1330      inside a $(call ...) or something.  Since this function is only ever
1331      invoked in places where we want to define globally visible variables,
1332      make sure we define this variable in the global set.  */
1333
1334   v = define_variable_in_set (varname, strlen (varname), p,
1335                               origin, flavor == f_recursive,
1336                               (target_var
1337                                ? current_variable_set_list->set : NULL),
1338                               flocp);
1339   v->append = append;
1340   v->conditional = conditional;
1341
1342   if (alloc_value)
1343     free (alloc_value);
1344
1345   return v->special ? set_special_var (v) : v;
1346 }
1347 \f
1348 /* Parse P (a null-terminated string) as a variable definition.
1349
1350    If it is not a variable definition, return NULL.
1351
1352    If it is a variable definition, return a pointer to the char after the
1353    assignment token and set *FLAVOR to the type of variable assignment.  */
1354
1355 char *
1356 parse_variable_definition (const char *p, enum variable_flavor *flavor)
1357 {
1358   int wspace = 0;
1359
1360   p = next_token (p);
1361
1362   while (1)
1363     {
1364       int c = *p++;
1365
1366       /* If we find a comment or EOS, it's not a variable definition.  */
1367       if (c == '\0' || c == '#')
1368         return NULL;
1369
1370       if (c == '$')
1371         {
1372           /* This begins a variable expansion reference.  Make sure we don't
1373              treat chars inside the reference as assignment tokens.  */
1374           char closeparen;
1375           int count;
1376           c = *p++;
1377           if (c == '(')
1378             closeparen = ')';
1379           else if (c == '{')
1380             closeparen = '}';
1381           else
1382             /* '$$' or '$X'.  Either way, nothing special to do here.  */
1383             continue;
1384
1385           /* P now points past the opening paren or brace.
1386              Count parens or braces until it is matched.  */
1387           count = 0;
1388           for (; *p != '\0'; ++p)
1389             {
1390               if (*p == c)
1391                 ++count;
1392               else if (*p == closeparen && --count < 0)
1393                 {
1394                   ++p;
1395                   break;
1396                 }
1397             }
1398           continue;
1399         }
1400
1401       /* If we find whitespace skip it, and remember we found it.  */
1402       if (isblank ((unsigned char)c))
1403         {
1404           wspace = 1;
1405           p = next_token (p);
1406           c = *p;
1407           if (c == '\0')
1408             return NULL;
1409           ++p;
1410         }
1411
1412
1413       if (c == '=')
1414         {
1415           *flavor = f_recursive;
1416           return (char *)p;
1417         }
1418
1419       /* Match assignment variants (:=, +=, ?=)  */
1420       if (*p == '=')
1421         {
1422           switch (c)
1423             {
1424               case ':':
1425                 *flavor = f_simple;
1426                 break;
1427               case '+':
1428                 *flavor = f_append;
1429                 break;
1430               case '?':
1431                 *flavor = f_conditional;
1432                 break;
1433               default:
1434                 /* If we skipped whitespace, non-assignments means no var.  */
1435                 if (wspace)
1436                   return NULL;
1437
1438                 /* Might be assignment, or might be $= or #=.  Check.  */
1439                 continue;
1440             }
1441           return (char *)++p;
1442         }
1443       else if (c == ':')
1444         /* A colon other than := is a rule line, not a variable defn.  */
1445         return NULL;
1446
1447       /* If we skipped whitespace, non-assignments means no var.  */
1448       if (wspace)
1449         return NULL;
1450     }
1451
1452   return (char *)p;
1453 }
1454 \f
1455 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1456
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.  */
1460
1461 struct variable *
1462 assign_variable_definition (struct variable *v, char *line)
1463 {
1464   char *beg;
1465   char *end;
1466   enum variable_flavor flavor;
1467   char *name;
1468
1469   beg = next_token (line);
1470   line = parse_variable_definition (beg, &flavor);
1471   if (!line)
1472     return NULL;
1473
1474   end = line - (flavor == f_recursive ? 1 : 2);
1475   while (end > beg && isblank ((unsigned char)end[-1]))
1476     --end;
1477   line = next_token (line);
1478   v->value = line;
1479   v->flavor = flavor;
1480
1481   /* Expand the name, so "$(foo)bar = baz" works.  */
1482   name = alloca (end - beg + 1);
1483   memcpy (name, beg, end - beg);
1484   name[end - beg] = '\0';
1485   v->name = allocated_variable_expand (name);
1486
1487   if (v->name[0] == '\0')
1488     fatal (&v->fileinfo, _("empty variable name"));
1489
1490   return v;
1491 }
1492 \f
1493 /* Try to interpret LINE (a null-terminated string) as a variable definition.
1494
1495    ORIGIN may be o_file, o_override, o_env, o_env_override,
1496    or o_command specifying that the variable definition comes
1497    from a makefile, an override directive, the environment with
1498    or without the -e switch, or the command line.
1499
1500    See the comments for assign_variable_definition().
1501
1502    If LINE was recognized as a variable definition, a pointer to its `struct
1503    variable' is returned.  If LINE is not a variable definition, NULL is
1504    returned.  */
1505
1506 struct variable *
1507 try_variable_definition (const struct floc *flocp, char *line,
1508                          enum variable_origin origin, int target_var)
1509 {
1510   struct variable v;
1511   struct variable *vp;
1512
1513   if (flocp != 0)
1514     v.fileinfo = *flocp;
1515   else
1516     v.fileinfo.filenm = 0;
1517
1518   if (!assign_variable_definition (&v, line))
1519     return 0;
1520
1521   vp = do_variable_definition (flocp, v.name, v.value,
1522                                origin, v.flavor, target_var);
1523
1524   free (v.name);
1525
1526   return vp;
1527 }
1528 \f
1529 /* Print information for variable V, prefixing it with PREFIX.  */
1530
1531 static void
1532 print_variable (const void *item, void *arg)
1533 {
1534   const struct variable *v = item;
1535   const char *prefix = arg;
1536   const char *origin;
1537
1538   switch (v->origin)
1539     {
1540     case o_default:
1541       origin = _("default");
1542       break;
1543     case o_env:
1544       origin = _("environment");
1545       break;
1546     case o_file:
1547       origin = _("makefile");
1548       break;
1549     case o_env_override:
1550       origin = _("environment under -e");
1551       break;
1552     case o_command:
1553       origin = _("command line");
1554       break;
1555     case o_override:
1556       origin = _("`override' directive");
1557       break;
1558     case o_automatic:
1559       origin = _("automatic");
1560       break;
1561     case o_invalid:
1562     default:
1563       abort ();
1564     }
1565   fputs ("# ", stdout);
1566   fputs (origin, stdout);
1567   if (v->private_var)
1568     fputs (" private", stdout);
1569   if (v->fileinfo.filenm)
1570     printf (_(" (from `%s', line %lu)"),
1571             v->fileinfo.filenm, v->fileinfo.lineno);
1572   putchar ('\n');
1573   fputs (prefix, stdout);
1574
1575   /* Is this a `define'?  */
1576   if (v->recursive && strchr (v->value, '\n') != 0)
1577     printf ("define %s\n%s\nendef\n", v->name, v->value);
1578   else
1579     {
1580       char *p;
1581
1582       printf ("%s %s= ", v->name, v->recursive ? v->append ? "+" : "" : ":");
1583
1584       /* Check if the value is just whitespace.  */
1585       p = next_token (v->value);
1586       if (p != v->value && *p == '\0')
1587         /* All whitespace.  */
1588         printf ("$(subst ,,%s)", v->value);
1589       else if (v->recursive)
1590         fputs (v->value, stdout);
1591       else
1592         /* Double up dollar signs.  */
1593         for (p = v->value; *p != '\0'; ++p)
1594           {
1595             if (*p == '$')
1596               putchar ('$');
1597             putchar (*p);
1598           }
1599       putchar ('\n');
1600     }
1601 }
1602
1603
1604 /* Print all the variables in SET.  PREFIX is printed before
1605    the actual variable definitions (everything else is comments).  */
1606
1607 void
1608 print_variable_set (struct variable_set *set, char *prefix)
1609 {
1610   hash_map_arg (&set->table, print_variable, prefix);
1611
1612   fputs (_("# variable set hash-table stats:\n"), stdout);
1613   fputs ("# ", stdout);
1614   hash_print_stats (&set->table, stdout);
1615   putc ('\n', stdout);
1616 }
1617
1618 /* Print the data base of variables.  */
1619
1620 void
1621 print_variable_data_base (void)
1622 {
1623   puts (_("\n# Variables\n"));
1624
1625   print_variable_set (&global_variable_set, "");
1626
1627   puts (_("\n# Pattern-specific Variable Values"));
1628
1629   {
1630     struct pattern_var *p;
1631     int rules = 0;
1632
1633     for (p = pattern_vars; p != 0; p = p->next)
1634       {
1635         ++rules;
1636         printf ("\n%s :\n", p->target);
1637         print_variable (&p->variable, "# ");
1638       }
1639
1640     if (rules == 0)
1641       puts (_("\n# No pattern-specific variable values."));
1642     else
1643       printf (_("\n# %u pattern-specific variable values"), rules);
1644   }
1645 }
1646
1647
1648 /* Print all the local variables of FILE.  */
1649
1650 void
1651 print_file_variables (const struct file *file)
1652 {
1653   if (file->variables != 0)
1654     print_variable_set (file->variables->set, "# ");
1655 }
1656
1657 #ifdef WINDOWS32
1658 void
1659 sync_Path_environment (void)
1660 {
1661   char *path = allocated_variable_expand ("$(PATH)");
1662   static char *environ_path = NULL;
1663
1664   if (!path)
1665     return;
1666
1667   /*
1668    * If done this before, don't leak memory unnecessarily.
1669    * Free the previous entry before allocating new one.
1670    */
1671   if (environ_path)
1672     free (environ_path);
1673
1674   /*
1675    * Create something WINDOWS32 world can grok
1676    */
1677   convert_Path_to_windows32 (path, ';');
1678   environ_path = xstrdup (concat (3, "PATH", "=", path));
1679   putenv (environ_path);
1680   free (path);
1681 }
1682 #endif