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