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