(root)/
make-4.4/
src/
function.c
       1  /* Builtin function expansion 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  #include "filedef.h"
      19  #include "variable.h"
      20  #include "dep.h"
      21  #include "job.h"
      22  #include "os.h"
      23  #include "commands.h"
      24  #include "debug.h"
      25  
      26  #ifdef _AMIGA
      27  #include "amiga.h"
      28  #endif
      29  
      30  
      31  struct function_table_entry
      32    {
      33      union {
      34        char *(*func_ptr) (char *output, char **argv, const char *fname);
      35        gmk_func_ptr alloc_func_ptr;
      36      } fptr;
      37      const char *name;
      38      unsigned char len;
      39      unsigned char minimum_args;
      40      unsigned char maximum_args;
      41      unsigned int expand_args:1;
      42      unsigned int alloc_fn:1;
      43      unsigned int adds_command:1;
      44    };
      45  
      46  static unsigned long
      47  function_table_entry_hash_1 (const void *keyv)
      48  {
      49    const struct function_table_entry *key = keyv;
      50    return_STRING_N_HASH_1 (key->name, key->len);
      51  }
      52  
      53  static unsigned long
      54  function_table_entry_hash_2 (const void *keyv)
      55  {
      56    const struct function_table_entry *key = keyv;
      57    return_STRING_N_HASH_2 (key->name, key->len);
      58  }
      59  
      60  static int
      61  function_table_entry_hash_cmp (const void *xv, const void *yv)
      62  {
      63    const struct function_table_entry *x = xv;
      64    const struct function_table_entry *y = yv;
      65    int result = x->len - y->len;
      66    if (result)
      67      return result;
      68    return_STRING_N_COMPARE (x->name, y->name, x->len);
      69  }
      70  
      71  static struct hash_table function_table;
      72  
      73  
      74  /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
      75     each occurrence of SUBST with REPLACE. TEXT is null-terminated.  SLEN is
      76     the length of SUBST and RLEN is the length of REPLACE.  If BY_WORD is
      77     nonzero, substitutions are done only on matches which are complete
      78     whitespace-delimited words.  */
      79  
      80  char *
      81  subst_expand (char *o, const char *text, const char *subst, const char *replace,
      82                size_t slen, size_t rlen, int by_word)
      83  {
      84    const char *t = text;
      85    const char *p;
      86  
      87    if (slen == 0 && !by_word)
      88      {
      89        /* The first occurrence of "" in any string is its end.  */
      90        o = variable_buffer_output (o, t, strlen (t));
      91        if (rlen > 0)
      92          o = variable_buffer_output (o, replace, rlen);
      93        return o;
      94      }
      95  
      96    do
      97      {
      98        if (by_word && slen == 0)
      99          /* When matching by words, the empty string should match
     100             the end of each word, rather than the end of the whole text.  */
     101          p = end_of_token (next_token (t));
     102        else
     103          {
     104            p = strstr (t, subst);
     105            if (p == 0)
     106              {
     107                /* No more matches.  Output everything left on the end.  */
     108                o = variable_buffer_output (o, t, strlen (t));
     109                return o;
     110              }
     111          }
     112  
     113        /* Output everything before this occurrence of the string to replace.  */
     114        if (p > t)
     115          o = variable_buffer_output (o, t, p - t);
     116  
     117        /* If we're substituting only by fully matched words,
     118           or only at the ends of words, check that this case qualifies.  */
     119        if (by_word
     120            && ((p > text && !ISSPACE (p[-1]))
     121                || ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
     122          /* Struck out.  Output the rest of the string that is
     123             no longer to be replaced.  */
     124          o = variable_buffer_output (o, subst, slen);
     125        else if (rlen > 0)
     126          /* Output the replacement string.  */
     127          o = variable_buffer_output (o, replace, rlen);
     128  
     129        /* Advance T past the string to be replaced.  */
     130        t = p + slen;
     131      } while (*t != '\0');
     132  
     133    return o;
     134  }
     135  
     136  
     137  /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
     138     and replacing strings matching PATTERN with REPLACE.
     139     If PATTERN_PERCENT is not nil, PATTERN has already been
     140     run through find_percent, and PATTERN_PERCENT is the result.
     141     If REPLACE_PERCENT is not nil, REPLACE has already been
     142     run through find_percent, and REPLACE_PERCENT is the result.
     143     Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
     144     character _AFTER_ the %, not to the % itself.
     145  */
     146  
     147  char *
     148  patsubst_expand_pat (char *o, const char *text,
     149                       const char *pattern, const char *replace,
     150                       const char *pattern_percent, const char *replace_percent)
     151  {
     152    size_t pattern_prepercent_len, pattern_postpercent_len;
     153    size_t replace_prepercent_len, replace_postpercent_len;
     154    const char *t;
     155    size_t len;
     156    int doneany = 0;
     157  
     158    /* Record the length of REPLACE before and after the % so we don't have to
     159       compute these lengths more than once.  */
     160    if (replace_percent)
     161      {
     162        replace_prepercent_len = replace_percent - replace - 1;
     163        replace_postpercent_len = strlen (replace_percent);
     164      }
     165    else
     166      {
     167        replace_prepercent_len = strlen (replace);
     168        replace_postpercent_len = 0;
     169      }
     170  
     171    if (!pattern_percent)
     172      /* With no % in the pattern, this is just a simple substitution.  */
     173      return subst_expand (o, text, pattern, replace,
     174                           strlen (pattern), strlen (replace), 1);
     175  
     176    /* Record the length of PATTERN before and after the %
     177       so we don't have to compute it more than once.  */
     178    pattern_prepercent_len = pattern_percent - pattern - 1;
     179    pattern_postpercent_len = strlen (pattern_percent);
     180  
     181    while ((t = find_next_token (&text, &len)) != 0)
     182      {
     183        int fail = 0;
     184  
     185        /* Is it big enough to match?  */
     186        if (len < pattern_prepercent_len + pattern_postpercent_len)
     187          fail = 1;
     188  
     189        /* Does the prefix match? */
     190        if (!fail && pattern_prepercent_len > 0
     191            && (*t != *pattern
     192                || t[pattern_prepercent_len - 1] != pattern_percent[-2]
     193                || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
     194          fail = 1;
     195  
     196        /* Does the suffix match? */
     197        if (!fail && pattern_postpercent_len > 0
     198            && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
     199                || t[len - pattern_postpercent_len] != *pattern_percent
     200                || !strneq (&t[len - pattern_postpercent_len],
     201                            pattern_percent, pattern_postpercent_len - 1)))
     202          fail = 1;
     203  
     204        if (fail)
     205          /* It didn't match.  Output the string.  */
     206          o = variable_buffer_output (o, t, len);
     207        else
     208          {
     209            /* It matched.  Output the replacement.  */
     210  
     211            /* Output the part of the replacement before the %.  */
     212            o = variable_buffer_output (o, replace, replace_prepercent_len);
     213  
     214            if (replace_percent != 0)
     215              {
     216                /* Output the part of the matched string that
     217                   matched the % in the pattern.  */
     218                o = variable_buffer_output (o, t + pattern_prepercent_len,
     219                                            len - (pattern_prepercent_len
     220                                                   + pattern_postpercent_len));
     221                /* Output the part of the replacement after the %.  */
     222                o = variable_buffer_output (o, replace_percent,
     223                                            replace_postpercent_len);
     224              }
     225          }
     226  
     227        /* Output a space, but not if the replacement is "".  */
     228        if (fail || replace_prepercent_len > 0
     229            || (replace_percent != 0 && len + replace_postpercent_len > 0))
     230          {
     231            o = variable_buffer_output (o, " ", 1);
     232            doneany = 1;
     233          }
     234      }
     235    if (doneany)
     236      /* Kill the last space.  */
     237      --o;
     238  
     239    return o;
     240  }
     241  
     242  /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
     243     and replacing strings matching PATTERN with REPLACE.
     244     If PATTERN_PERCENT is not nil, PATTERN has already been
     245     run through find_percent, and PATTERN_PERCENT is the result.
     246     If REPLACE_PERCENT is not nil, REPLACE has already been
     247     run through find_percent, and REPLACE_PERCENT is the result.
     248     Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
     249     character _AFTER_ the %, not to the % itself.
     250  */
     251  
     252  char *
     253  patsubst_expand (char *o, const char *text, char *pattern, char *replace)
     254  {
     255    const char *pattern_percent = find_percent (pattern);
     256    const char *replace_percent = find_percent (replace);
     257  
     258    /* If there's a percent in the pattern or replacement skip it.  */
     259    if (replace_percent)
     260      ++replace_percent;
     261    if (pattern_percent)
     262      ++pattern_percent;
     263  
     264    return patsubst_expand_pat (o, text, pattern, replace,
     265                                pattern_percent, replace_percent);
     266  }
     267  
     268  
     269  /* Look up a function by name.  */
     270  
     271  static const struct function_table_entry *
     272  lookup_function (const char *s)
     273  {
     274    struct function_table_entry function_table_entry_key;
     275    const char *e = s;
     276  
     277    while (STOP_SET (*e, MAP_USERFUNC))
     278      e++;
     279  
     280    if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
     281      return NULL;
     282  
     283    function_table_entry_key.name = s;
     284    function_table_entry_key.len = (unsigned char) (e - s);
     285  
     286    return hash_find_item (&function_table, &function_table_entry_key);
     287  }
     288  
     289  
     290  /* Return 1 if PATTERN matches STR, 0 if not.  */
     291  
     292  int
     293  pattern_matches (const char *pattern, const char *percent, const char *str)
     294  {
     295    size_t sfxlen, strlength;
     296  
     297    if (percent == 0)
     298      {
     299        size_t len = strlen (pattern) + 1;
     300        char *new_chars = alloca (len);
     301        memcpy (new_chars, pattern, len);
     302        percent = find_percent (new_chars);
     303        if (percent == 0)
     304          return streq (new_chars, str);
     305        pattern = new_chars;
     306      }
     307  
     308    sfxlen = strlen (percent + 1);
     309    strlength = strlen (str);
     310  
     311    if (strlength < (percent - pattern) + sfxlen
     312        || !strneq (pattern, str, percent - pattern))
     313      return 0;
     314  
     315    return !strcmp (percent + 1, str + (strlength - sfxlen));
     316  }
     317  
     318  
     319  /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
     320     ENDPARENtheses), starting at PTR before END.  Return a pointer to
     321     next character.
     322  
     323     If no next argument is found, return NULL.
     324  */
     325  
     326  static char *
     327  find_next_argument (char startparen, char endparen,
     328                      const char *ptr, const char *end)
     329  {
     330    int count = 0;
     331  
     332    for (; ptr < end; ++ptr)
     333      if (!STOP_SET (*ptr, MAP_VARSEP|MAP_COMMA))
     334        continue;
     335  
     336      else if (*ptr == startparen)
     337        ++count;
     338  
     339      else if (*ptr == endparen)
     340        {
     341          --count;
     342          if (count < 0)
     343            return NULL;
     344        }
     345  
     346      else if (*ptr == ',' && !count)
     347        return (char *)ptr;
     348  
     349    /* We didn't find anything.  */
     350    return NULL;
     351  }
     352  
     353  
     354  /* Glob-expand LINE.  The returned pointer is
     355     only good until the next call to string_glob.  */
     356  
     357  static char *
     358  string_glob (char *line)
     359  {
     360    static char *result = 0;
     361    static size_t length;
     362    struct nameseq *chain;
     363    size_t idx;
     364  
     365    chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
     366                            /* We do not want parse_file_seq to strip './'s.
     367                               That would break examples like:
     368                               $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)).  */
     369                            PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
     370  
     371    if (result == 0)
     372      {
     373        length = 100;
     374        result = xmalloc (100);
     375      }
     376  
     377    idx = 0;
     378    while (chain != 0)
     379      {
     380        struct nameseq *next = chain->next;
     381        size_t len = strlen (chain->name);
     382  
     383        if (idx + len + 1 > length)
     384          {
     385            length += (len + 1) * 2;
     386            result = xrealloc (result, length);
     387          }
     388        memcpy (&result[idx], chain->name, len);
     389        idx += len;
     390        result[idx++] = ' ';
     391  
     392        /* Because we used PARSEFS_NOCACHE above, we have to free() NAME.  */
     393        free ((char *)chain->name);
     394        free (chain);
     395        chain = next;
     396      }
     397  
     398    /* Kill the last space and terminate the string.  */
     399    if (idx == 0)
     400      result[0] = '\0';
     401    else
     402      result[idx - 1] = '\0';
     403  
     404    return result;
     405  }
     406  
     407  /*
     408    Builtin functions
     409   */
     410  
     411  static char *
     412  func_patsubst (char *o, char **argv, const char *funcname UNUSED)
     413  {
     414    o = patsubst_expand (o, argv[2], argv[0], argv[1]);
     415    return o;
     416  }
     417  
     418  
     419  static char *
     420  func_join (char *o, char **argv, const char *funcname UNUSED)
     421  {
     422    int doneany = 0;
     423  
     424    /* Write each word of the first argument directly followed
     425       by the corresponding word of the second argument.
     426       If the two arguments have a different number of words,
     427       the excess words are just output separated by blanks.  */
     428    const char *tp;
     429    const char *pp;
     430    const char *list1_iterator = argv[0];
     431    const char *list2_iterator = argv[1];
     432    do
     433      {
     434        size_t len1, len2;
     435  
     436        tp = find_next_token (&list1_iterator, &len1);
     437        if (tp != 0)
     438          o = variable_buffer_output (o, tp, len1);
     439  
     440        pp = find_next_token (&list2_iterator, &len2);
     441        if (pp != 0)
     442          o = variable_buffer_output (o, pp, len2);
     443  
     444        if (tp != 0 || pp != 0)
     445          {
     446            o = variable_buffer_output (o, " ", 1);
     447            doneany = 1;
     448          }
     449      }
     450    while (tp != 0 || pp != 0);
     451    if (doneany)
     452      /* Kill the last blank.  */
     453      --o;
     454  
     455    return o;
     456  }
     457  
     458  
     459  static char *
     460  func_origin (char *o, char **argv, const char *funcname UNUSED)
     461  {
     462    /* Expand the argument.  */
     463    struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
     464    if (v == 0)
     465      o = variable_buffer_output (o, "undefined", 9);
     466    else
     467      switch (v->origin)
     468        {
     469        case o_invalid:
     470          abort ();
     471          break;
     472        case o_default:
     473          o = variable_buffer_output (o, "default", 7);
     474          break;
     475        case o_env:
     476          o = variable_buffer_output (o, "environment", 11);
     477          break;
     478        case o_file:
     479          o = variable_buffer_output (o, "file", 4);
     480          break;
     481        case o_env_override:
     482          o = variable_buffer_output (o, "environment override", 20);
     483          break;
     484        case o_command:
     485          o = variable_buffer_output (o, "command line", 12);
     486          break;
     487        case o_override:
     488          o = variable_buffer_output (o, "override", 8);
     489          break;
     490        case o_automatic:
     491          o = variable_buffer_output (o, "automatic", 9);
     492          break;
     493        }
     494  
     495    return o;
     496  }
     497  
     498  static char *
     499  func_flavor (char *o, char **argv, const char *funcname UNUSED)
     500  {
     501    struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
     502  
     503    if (v == 0)
     504      o = variable_buffer_output (o, "undefined", 9);
     505    else
     506      if (v->recursive)
     507        o = variable_buffer_output (o, "recursive", 9);
     508      else
     509        o = variable_buffer_output (o, "simple", 6);
     510  
     511    return o;
     512  }
     513  
     514  
     515  static char *
     516  func_notdir_suffix (char *o, char **argv, const char *funcname)
     517  {
     518    /* Expand the argument.  */
     519    const char *list_iterator = argv[0];
     520    const char *p2;
     521    int doneany =0;
     522    size_t len=0;
     523  
     524    int is_suffix = funcname[0] == 's';
     525    int is_notdir = !is_suffix;
     526    int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
     527  #ifdef VMS
     528    /* For VMS list_iterator points to a comma separated list. To use the common
     529       [find_]next_token, create a local copy and replace the commas with
     530       spaces. Obviously, there is a problem if there is a ',' in the VMS filename
     531       (can only happen on ODS5), the same problem as with spaces in filenames,
     532       which seems to be present in make on all platforms. */
     533    char *vms_list_iterator = alloca(strlen(list_iterator) + 1);
     534    int i;
     535    for (i = 0; list_iterator[i]; i++)
     536      if (list_iterator[i] == ',')
     537        vms_list_iterator[i] = ' ';
     538      else
     539        vms_list_iterator[i] = list_iterator[i];
     540    vms_list_iterator[i] = list_iterator[i];
     541    while ((p2 = find_next_token((const char**) &vms_list_iterator, &len)) != 0)
     542  #else
     543    while ((p2 = find_next_token (&list_iterator, &len)) != 0)
     544  #endif
     545      {
     546        const char *p = p2 + len - 1;
     547  
     548        while (p >= p2 && ! STOP_SET (*p, stop))
     549          --p;
     550  
     551        if (p >= p2)
     552          {
     553            if (is_notdir)
     554              ++p;
     555            else if (*p != '.')
     556              continue;
     557            o = variable_buffer_output (o, p, len - (p - p2));
     558          }
     559  #ifdef HAVE_DOS_PATHS
     560        /* Handle the case of "d:foo/bar".  */
     561        else if (is_notdir && p2[0] && p2[1] == ':')
     562          {
     563            p = p2 + 2;
     564            o = variable_buffer_output (o, p, len - (p - p2));
     565          }
     566  #endif
     567        else if (is_notdir)
     568          o = variable_buffer_output (o, p2, len);
     569  
     570        if (is_notdir || p >= p2)
     571          {
     572  #ifdef VMS
     573            if (vms_comma_separator)
     574              o = variable_buffer_output (o, ",", 1);
     575            else
     576  #endif
     577            o = variable_buffer_output (o, " ", 1);
     578  
     579            doneany = 1;
     580          }
     581      }
     582  
     583    if (doneany)
     584      /* Kill last space.  */
     585      --o;
     586  
     587    return o;
     588  }
     589  
     590  
     591  static char *
     592  func_basename_dir (char *o, char **argv, const char *funcname)
     593  {
     594    /* Expand the argument.  */
     595    const char *p3 = argv[0];
     596    const char *p2;
     597    int doneany = 0;
     598    size_t len = 0;
     599  
     600    int is_basename = funcname[0] == 'b';
     601    int is_dir = !is_basename;
     602    int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
     603  #ifdef VMS
     604    /* As in func_notdir_suffix ... */
     605    char *vms_p3 = alloca (strlen(p3) + 1);
     606    int i;
     607    for (i = 0; p3[i]; i++)
     608      if (p3[i] == ',')
     609        vms_p3[i] = ' ';
     610      else
     611        vms_p3[i] = p3[i];
     612    vms_p3[i] = p3[i];
     613    while ((p2 = find_next_token((const char**) &vms_p3, &len)) != 0)
     614  #else
     615    while ((p2 = find_next_token (&p3, &len)) != 0)
     616  #endif
     617      {
     618        const char *p = p2 + len - 1;
     619        while (p >= p2 && ! STOP_SET (*p, stop))
     620          --p;
     621  
     622        if (p >= p2 && (is_dir))
     623          o = variable_buffer_output (o, p2, ++p - p2);
     624        else if (p >= p2 && (*p == '.'))
     625          o = variable_buffer_output (o, p2, p - p2);
     626  #ifdef HAVE_DOS_PATHS
     627        /* Handle the "d:foobar" case */
     628        else if (p2[0] && p2[1] == ':' && is_dir)
     629          o = variable_buffer_output (o, p2, 2);
     630  #endif
     631        else if (is_dir)
     632  #ifdef VMS
     633          {
     634            extern int vms_report_unix_paths;
     635            if (vms_report_unix_paths)
     636              o = variable_buffer_output (o, "./", 2);
     637            else
     638              o = variable_buffer_output (o, "[]", 2);
     639          }
     640  #else
     641  #ifndef _AMIGA
     642        o = variable_buffer_output (o, "./", 2);
     643  #else
     644        ; /* Just a nop...  */
     645  #endif /* AMIGA */
     646  #endif /* !VMS */
     647        else
     648          /* The entire name is the basename.  */
     649          o = variable_buffer_output (o, p2, len);
     650  
     651  #ifdef VMS
     652        if (vms_comma_separator)
     653          o = variable_buffer_output (o, ",", 1);
     654        else
     655  #endif
     656          o = variable_buffer_output (o, " ", 1);
     657  
     658        doneany = 1;
     659      }
     660  
     661    if (doneany)
     662      /* Kill last space.  */
     663      --o;
     664  
     665    return o;
     666  }
     667  
     668  static char *
     669  func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
     670  {
     671    size_t fixlen = strlen (argv[0]);
     672    const char *list_iterator = argv[1];
     673    int is_addprefix = funcname[3] == 'p';
     674    int is_addsuffix = !is_addprefix;
     675  
     676    int doneany = 0;
     677    const char *p;
     678    size_t len;
     679  
     680    while ((p = find_next_token (&list_iterator, &len)) != 0)
     681      {
     682        if (is_addprefix)
     683          o = variable_buffer_output (o, argv[0], fixlen);
     684        o = variable_buffer_output (o, p, len);
     685        if (is_addsuffix)
     686          o = variable_buffer_output (o, argv[0], fixlen);
     687        o = variable_buffer_output (o, " ", 1);
     688        doneany = 1;
     689      }
     690  
     691    if (doneany)
     692      /* Kill last space.  */
     693      --o;
     694  
     695    return o;
     696  }
     697  
     698  static char *
     699  func_subst (char *o, char **argv, const char *funcname UNUSED)
     700  {
     701    o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
     702                      strlen (argv[1]), 0);
     703  
     704    return o;
     705  }
     706  
     707  
     708  static char *
     709  func_firstword (char *o, char **argv, const char *funcname UNUSED)
     710  {
     711    size_t i;
     712    const char *words = argv[0];    /* Use a temp variable for find_next_token */
     713    const char *p = find_next_token (&words, &i);
     714  
     715    if (p != 0)
     716      o = variable_buffer_output (o, p, i);
     717  
     718    return o;
     719  }
     720  
     721  static char *
     722  func_lastword (char *o, char **argv, const char *funcname UNUSED)
     723  {
     724    size_t i;
     725    const char *words = argv[0];    /* Use a temp variable for find_next_token */
     726    const char *p = NULL;
     727    const char *t;
     728  
     729    while ((t = find_next_token (&words, &i)) != NULL)
     730      p = t;
     731  
     732    if (p != 0)
     733      o = variable_buffer_output (o, p, i);
     734  
     735    return o;
     736  }
     737  
     738  static char *
     739  func_words (char *o, char **argv, const char *funcname UNUSED)
     740  {
     741    unsigned int i = 0;
     742    const char *word_iterator = argv[0];
     743    char buf[INTSTR_LENGTH];
     744  
     745    while (find_next_token (&word_iterator, NULL) != 0)
     746      ++i;
     747  
     748    sprintf (buf, "%u", i);
     749    o = variable_buffer_output (o, buf, strlen (buf));
     750  
     751    return o;
     752  }
     753  
     754  /* Set begpp to point to the first non-whitespace character of the string,
     755   * and endpp to point to the last non-whitespace character of the string.
     756   * If the string is empty or contains nothing but whitespace, endpp will be
     757   * begpp-1.
     758   */
     759  char *
     760  strip_whitespace (const char **begpp, const char **endpp)
     761  {
     762    while (*begpp <= *endpp && ISSPACE (**begpp))
     763      (*begpp) ++;
     764    while (*endpp >= *begpp && ISSPACE (**endpp))
     765      (*endpp) --;
     766    return (char *)*begpp;
     767  }
     768  
     769  static long long
     770  parse_numeric (const char *s, const char *msg)
     771  {
     772    const char *beg = s;
     773    const char *end = s + strlen (s) - 1;
     774    char *endp;
     775    long long num;
     776    strip_whitespace (&beg, &end);
     777  
     778    if (beg > end)
     779      OS (fatal, *expanding_var, _("%s: empty value"), msg);
     780  
     781    errno = 0;
     782    num = strtoll (beg, &endp, 10);
     783    if (errno == ERANGE)
     784      OSS (fatal, *expanding_var, _("%s: '%s' out of range"), msg, s);
     785    else if (endp == beg || endp <= end)
     786      /* Empty or non-numeric input */
     787      OSS (fatal, *expanding_var, "%s: '%s'", msg, s);
     788  
     789    return num;
     790  }
     791  
     792  static char *
     793  func_word (char *o, char **argv, const char *funcname UNUSED)
     794  {
     795    const char *end_p;
     796    const char *p;
     797    long long i;
     798  
     799    i = parse_numeric (argv[0],
     800                       _("invalid first argument to 'word' function"));
     801    if (i < 1)
     802      O (fatal, *expanding_var,
     803         _("first argument to 'word' function must be greater than 0"));
     804  
     805    end_p = argv[1];
     806    while ((p = find_next_token (&end_p, 0)) != 0)
     807      if (--i == 0)
     808        break;
     809  
     810    if (i == 0)
     811      o = variable_buffer_output (o, p, end_p - p);
     812  
     813    return o;
     814  }
     815  
     816  static char *
     817  func_wordlist (char *o, char **argv, const char *funcname UNUSED)
     818  {
     819    char buf[INTSTR_LENGTH + 1];
     820    long long start, stop, count;
     821    const char* badfirst = _("invalid first argument to 'wordlist' function");
     822    const char* badsecond = _("invalid second argument to 'wordlist' function");
     823  
     824    start = parse_numeric (argv[0], badfirst);
     825    if (start < 1)
     826      OSS (fatal, *expanding_var, "%s: '%s'", badfirst, make_lltoa (start, buf));
     827  
     828    stop = parse_numeric (argv[1], badsecond);
     829    if (stop < 0)
     830      OSS (fatal, *expanding_var, "%s: '%s'", badsecond, make_lltoa (stop, buf));
     831  
     832    count = stop - start + 1;
     833  
     834    if (count > 0)
     835      {
     836        const char *p;
     837        const char *end_p = argv[2];
     838  
     839        /* Find the beginning of the "start"th word.  */
     840        while (((p = find_next_token (&end_p, 0)) != 0) && --start)
     841          ;
     842  
     843        if (p)
     844          {
     845            /* Find the end of the "count"th word from start.  */
     846            while (--count && (find_next_token (&end_p, 0) != 0))
     847              ;
     848  
     849            /* Return the stuff in the middle.  */
     850            o = variable_buffer_output (o, p, end_p - p);
     851          }
     852      }
     853  
     854    return o;
     855  }
     856  
     857  static char *
     858  func_findstring (char *o, char **argv, const char *funcname UNUSED)
     859  {
     860    /* Find the first occurrence of the first string in the second.  */
     861    if (strstr (argv[1], argv[0]) != 0)
     862      o = variable_buffer_output (o, argv[0], strlen (argv[0]));
     863  
     864    return o;
     865  }
     866  
     867  static char *
     868  func_foreach (char *o, char **argv, const char *funcname UNUSED)
     869  {
     870    /* expand only the first two.  */
     871    char *varname = expand_argument (argv[0], NULL);
     872    char *list = expand_argument (argv[1], NULL);
     873    const char *body = argv[2];
     874  
     875    int doneany = 0;
     876    const char *list_iterator = list;
     877    const char *p;
     878    size_t len;
     879    struct variable *var;
     880  
     881    /* Clean up the variable name by removing whitespace.  */
     882    char *vp = next_token (varname);
     883    end_of_token (vp)[0] = '\0';
     884  
     885    push_new_variable_scope ();
     886    var = define_variable (vp, strlen (vp), "", o_automatic, 0);
     887  
     888    /* loop through LIST,  put the value in VAR and expand BODY */
     889    while ((p = find_next_token (&list_iterator, &len)) != 0)
     890      {
     891        char *result = 0;
     892  
     893        free (var->value);
     894        var->value = xstrndup (p, len);
     895  
     896        result = allocated_variable_expand (body);
     897  
     898        o = variable_buffer_output (o, result, strlen (result));
     899        o = variable_buffer_output (o, " ", 1);
     900        doneany = 1;
     901        free (result);
     902      }
     903  
     904    if (doneany)
     905      /* Kill the last space.  */
     906      --o;
     907  
     908    pop_variable_scope ();
     909    free (varname);
     910    free (list);
     911  
     912    return o;
     913  }
     914  
     915  static char *
     916  func_let (char *o, char **argv, const char *funcname UNUSED)
     917  {
     918    /* expand only the first two.  */
     919    char *varnames = expand_argument (argv[0], NULL);
     920    char *list = expand_argument (argv[1], NULL);
     921    const char *body = argv[2];
     922  
     923    const char *vp;
     924    const char *vp_next = varnames;
     925    const char *list_iterator = list;
     926    char *p;
     927    size_t len;
     928    size_t vlen;
     929  
     930    push_new_variable_scope ();
     931  
     932    /* loop through LIST for all but the last VARNAME */
     933    vp = find_next_token (&vp_next, &vlen);
     934    NEXT_TOKEN (vp_next);
     935    while (*vp_next != '\0')
     936      {
     937        p = find_next_token (&list_iterator, &len);
     938        if (*list_iterator != '\0')
     939          {
     940            ++list_iterator;
     941            p[len] = '\0';
     942          }
     943        define_variable (vp, vlen, p ? p : "", o_automatic, 0);
     944  
     945        vp = find_next_token (&vp_next, &vlen);
     946        NEXT_TOKEN (vp_next);
     947      }
     948  
     949    /* set the last VARNAME to the remainder of LIST */
     950    if (vp)
     951      define_variable (vp, vlen, next_token (list_iterator), o_automatic, 0);
     952  
     953    /* Expand the body in the context of the arguments, adding the result to
     954       the variable buffer.  */
     955  
     956    o = variable_expand_string (o, body, SIZE_MAX);
     957  
     958    pop_variable_scope ();
     959    free (varnames);
     960    free (list);
     961  
     962    return o + strlen (o);
     963  }
     964  
     965  struct a_word
     966  {
     967    struct a_word *chain;
     968    char *str;
     969    size_t length;
     970    int matched;
     971  };
     972  
     973  static unsigned long
     974  a_word_hash_1 (const void *key)
     975  {
     976    return_STRING_HASH_1 (((struct a_word const *) key)->str);
     977  }
     978  
     979  static unsigned long
     980  a_word_hash_2 (const void *key)
     981  {
     982    return_STRING_HASH_2 (((struct a_word const *) key)->str);
     983  }
     984  
     985  static int
     986  a_word_hash_cmp (const void *x, const void *y)
     987  {
     988    const struct a_word *ax = x;
     989    const struct a_word *ay = y;
     990  
     991    if (ax->length != ay->length)
     992      return ax->length > ay->length ? 1 : -1;
     993  
     994    return_STRING_N_COMPARE (ax->str, ay->str, ax->length);
     995  }
     996  
     997  struct a_pattern
     998  {
     999    char *str;
    1000    char *percent;
    1001    size_t length;
    1002  };
    1003  
    1004  static char *
    1005  func_filter_filterout (char *o, char **argv, const char *funcname)
    1006  {
    1007    struct a_word *words;
    1008    struct a_word *word_end;
    1009    struct a_word *wp;
    1010    struct a_pattern *patterns;
    1011    struct a_pattern *pat_end;
    1012    struct a_pattern *pp;
    1013    unsigned long pat_count = 0, word_count = 0;
    1014  
    1015    struct hash_table a_word_table;
    1016    int is_filter = funcname[CSTRLEN ("filter")] == '\0';
    1017    const char *cp;
    1018    int literals = 0;
    1019    int hashing = 0;
    1020    char *p;
    1021    size_t len;
    1022    int doneany = 0;
    1023  
    1024    /* Find the number of words and get memory for them.  */
    1025    cp = argv[1];
    1026    while ((p = find_next_token (&cp, NULL)) != 0)
    1027      ++word_count;
    1028  
    1029    if (!word_count)
    1030      return o;
    1031  
    1032    words = xcalloc (word_count * sizeof (struct a_word));
    1033    word_end = words + word_count;
    1034  
    1035    /* Find the number of patterns and get memory for them.  */
    1036    cp = argv[0];
    1037    while ((p = find_next_token (&cp, NULL)) != 0)
    1038      ++pat_count;
    1039  
    1040    patterns = xcalloc (pat_count * sizeof (struct a_pattern));
    1041    pat_end = patterns + pat_count;
    1042  
    1043    /* Chop argv[0] up into patterns to match against the words.  */
    1044  
    1045    cp = argv[0];
    1046    pp = patterns;
    1047    while ((p = find_next_token (&cp, &len)) != 0)
    1048      {
    1049        if (*cp != '\0')
    1050          ++cp;
    1051  
    1052        p[len] = '\0';
    1053        pp->str = p;
    1054        pp->percent = find_percent (p);
    1055        if (pp->percent == 0)
    1056          literals++;
    1057        /* find_percent() might shorten the string so LEN is wrong.  */
    1058        pp->length = strlen (pp->str);
    1059  
    1060        ++pp;
    1061      }
    1062  
    1063    /* Chop ARGV[1] up into words to match against the patterns.  */
    1064  
    1065    cp = argv[1];
    1066    wp = words;
    1067    while ((p = find_next_token (&cp, &len)) != 0)
    1068      {
    1069        if (*cp != '\0')
    1070          ++cp;
    1071  
    1072        p[len] = '\0';
    1073        wp->str = p;
    1074        wp->length = len;
    1075        ++wp;
    1076      }
    1077  
    1078    /* Only use a hash table if arg list lengths justifies the cost.  */
    1079    hashing = (literals > 1 && (literals * word_count) >= 10);
    1080    if (hashing)
    1081      {
    1082        hash_init (&a_word_table, word_count, a_word_hash_1, a_word_hash_2,
    1083                   a_word_hash_cmp);
    1084        for (wp = words; wp < word_end; ++wp)
    1085          {
    1086            struct a_word *owp = hash_insert (&a_word_table, wp);
    1087            if (owp)
    1088              wp->chain = owp;
    1089          }
    1090      }
    1091  
    1092    /* Run each pattern through the words, killing words.  */
    1093    for (pp = patterns; pp < pat_end; ++pp)
    1094      {
    1095        if (pp->percent)
    1096          for (wp = words; wp < word_end; ++wp)
    1097            wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
    1098        else if (hashing)
    1099          {
    1100            struct a_word a_word_key;
    1101            a_word_key.str = pp->str;
    1102            a_word_key.length = pp->length;
    1103            wp = hash_find_item (&a_word_table, &a_word_key);
    1104            while (wp)
    1105              {
    1106                wp->matched |= 1;
    1107                wp = wp->chain;
    1108              }
    1109          }
    1110        else
    1111          for (wp = words; wp < word_end; ++wp)
    1112            wp->matched |= (wp->length == pp->length
    1113                            && memcmp (pp->str, wp->str, wp->length) == 0);
    1114      }
    1115  
    1116    /* Output the words that matched (or didn't, for filter-out).  */
    1117    for (wp = words; wp < word_end; ++wp)
    1118      if (is_filter ? wp->matched : !wp->matched)
    1119        {
    1120          o = variable_buffer_output (o, wp->str, strlen (wp->str));
    1121          o = variable_buffer_output (o, " ", 1);
    1122          doneany = 1;
    1123        }
    1124  
    1125    if (doneany)
    1126      /* Kill the last space.  */
    1127      --o;
    1128  
    1129    if (hashing)
    1130      hash_free (&a_word_table, 0);
    1131  
    1132    free (patterns);
    1133    free (words);
    1134  
    1135    return o;
    1136  }
    1137  
    1138  
    1139  static char *
    1140  func_strip (char *o, char **argv, const char *funcname UNUSED)
    1141  {
    1142    const char *p = argv[0];
    1143    int doneany = 0;
    1144  
    1145    while (*p != '\0')
    1146      {
    1147        int i=0;
    1148        const char *word_start;
    1149  
    1150        NEXT_TOKEN (p);
    1151        word_start = p;
    1152        for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
    1153          {}
    1154        if (!i)
    1155          break;
    1156        o = variable_buffer_output (o, word_start, i);
    1157        o = variable_buffer_output (o, " ", 1);
    1158        doneany = 1;
    1159      }
    1160  
    1161    if (doneany)
    1162      /* Kill the last space.  */
    1163      --o;
    1164  
    1165    return o;
    1166  }
    1167  
    1168  /*
    1169    Print a warning or fatal message.
    1170  */
    1171  static char *
    1172  func_error (char *o, char **argv, const char *funcname)
    1173  {
    1174    switch (*funcname)
    1175      {
    1176      case 'e':
    1177        OS (fatal, reading_file, "%s", argv[0]);
    1178  
    1179      case 'w':
    1180        OS (error, reading_file, "%s", argv[0]);
    1181        break;
    1182  
    1183      case 'i':
    1184        {
    1185          size_t len = strlen (argv[0]);
    1186          char *msg = alloca (len + 2);
    1187          memcpy (msg, argv[0], len);
    1188          msg[len] = '\n';
    1189          msg[len + 1] = '\0';
    1190          outputs (0, msg);
    1191          break;
    1192        }
    1193  
    1194      default:
    1195        OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
    1196      }
    1197  
    1198    /* The warning function expands to the empty string.  */
    1199    return o;
    1200  }
    1201  
    1202  
    1203  /*
    1204    chop argv[0] into words, and sort them.
    1205   */
    1206  static char *
    1207  func_sort (char *o, char **argv, const char *funcname UNUSED)
    1208  {
    1209    const char *t;
    1210    char **words;
    1211    int wordi;
    1212    char *p;
    1213    size_t len;
    1214  
    1215    /* Find the maximum number of words we'll have.  */
    1216    t = argv[0];
    1217    wordi = 0;
    1218    while ((p = find_next_token (&t, NULL)) != 0)
    1219      {
    1220        ++t;
    1221        ++wordi;
    1222      }
    1223  
    1224    words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
    1225  
    1226    /* Now assign pointers to each string in the array.  */
    1227    t = argv[0];
    1228    wordi = 0;
    1229    while ((p = find_next_token (&t, &len)) != 0)
    1230      {
    1231        ++t;
    1232        p[len] = '\0';
    1233        words[wordi++] = p;
    1234      }
    1235  
    1236    if (wordi)
    1237      {
    1238        int i;
    1239  
    1240        /* Now sort the list of words.  */
    1241        qsort (words, wordi, sizeof (char *), alpha_compare);
    1242  
    1243        /* Now write the sorted list, uniquified.  */
    1244        for (i = 0; i < wordi; ++i)
    1245          {
    1246            len = strlen (words[i]);
    1247            if (i == wordi - 1 || strlen (words[i + 1]) != len
    1248                || memcmp (words[i], words[i + 1], len))
    1249              {
    1250                o = variable_buffer_output (o, words[i], len);
    1251                o = variable_buffer_output (o, " ", 1);
    1252              }
    1253          }
    1254  
    1255        /* Kill the last space.  */
    1256        --o;
    1257      }
    1258  
    1259    free (words);
    1260  
    1261    return o;
    1262  }
    1263  
    1264  /*
    1265    Traverse NUMBER consisting of optional leading white space, optional
    1266    sign, digits, and optional trailing white space.
    1267    If number is not of the proper form, diagnose with MSG.  Otherwise,
    1268    return the address of of the first character after NUMBER, store
    1269    into *SIGN an integer consistent with the number's sign (-1, 0, or 1)
    1270    and store into *NUMSTART the address of NUMBER's first nonzero digit
    1271    (if NUMBER contains only zero digits, store the address of the first
    1272    character after NUMBER).
    1273  */
    1274  static const char *
    1275  parse_textint (const char *number, const char *msg,
    1276                 int *sign, const char **numstart)
    1277  {
    1278    const char *after_sign, *after_number;
    1279    const char *p = next_token (number);
    1280    int negative = *p == '-';
    1281    int nonzero;
    1282  
    1283    if (*p == '\0')
    1284      OS (fatal, *expanding_var, _("%s: empty value"), msg);
    1285  
    1286    p += negative || *p == '+';
    1287    after_sign = p;
    1288  
    1289    while (*p == '0')
    1290      p++;
    1291    *numstart = p;
    1292  
    1293    while (ISDIGIT (*p))
    1294      ++p;
    1295    after_number = p;
    1296    nonzero = *numstart != after_number;
    1297    *sign = negative ? -nonzero : nonzero;
    1298  
    1299    /* Check for extra non-whitespace stuff after the value.  */
    1300    if (after_number == after_sign || *next_token (p) != '\0')
    1301      OSS (fatal, *expanding_var, "%s: '%s'", msg, number);
    1302  
    1303    return after_number;
    1304  }
    1305  
    1306  
    1307  /*
    1308    $(intcmp lhs,rhs[,lt-part[,eq-part[,gt-part]]])
    1309  
    1310    LHS and RHS must be integer values (leading/trailing whitespace is ignored).
    1311    If none of LT-PART, EQ-PART, or GT-PART are given then the function expands
    1312    to empty if LHS and RHS are not equal, or the numeric value if they are equal.
    1313    LT-PART is evaluated when LHS is strictly less than RHS, EQ-PART is evaluated
    1314    when LHS is equal to RHS, and GT-part is evaluated when LHS is strictly
    1315    greater than RHS.
    1316    If GT-PART is not provided, it defaults to EQ-PART.  When neither EQ-PART
    1317    nor GT-PART are provided, the function expands to empty if LHS is not
    1318    strictly less than RHS.
    1319  */
    1320  
    1321  static char *
    1322  func_intcmp (char *o, char **argv, const char *funcname UNUSED)
    1323  {
    1324    int lsign, rsign;
    1325    const char *lnum, *rnum;
    1326    char *lhs_str = expand_argument (argv[0], NULL);
    1327    char *rhs_str = expand_argument (argv[1], NULL);
    1328    const char *llim = parse_textint (lhs_str, _("non-numeric first argument to 'intcmp' function"), &lsign, &lnum);
    1329    const char *rlim = parse_textint (rhs_str, _("non-numeric second argument to 'intcmp' function"), &rsign, &rnum);
    1330    ptrdiff_t llen = llim - lnum;
    1331    ptrdiff_t rlen = rlim - rnum;
    1332    int cmp = lsign - rsign;
    1333  
    1334    if (cmp == 0)
    1335      {
    1336        cmp = (llen > rlen) - (llen < rlen);
    1337        if (cmp == 0)
    1338          cmp = memcmp (lnum, rnum, llen);
    1339      }
    1340  
    1341    argv += 2;
    1342  
    1343    /* Handle the special case where there are only two arguments.  */
    1344    if (!*argv && cmp == 0)
    1345      {
    1346        if (lsign < 0)
    1347          o = variable_buffer_output (o, "-", 1);
    1348        o = variable_buffer_output(o, lnum - !lsign, llen + !lsign);
    1349      }
    1350  
    1351    free (lhs_str);
    1352    free (rhs_str);
    1353  
    1354    if (*argv && cmp >= 0)
    1355      {
    1356        ++argv;
    1357        if (cmp > 0 && *argv && *(argv + 1))
    1358          ++argv;
    1359      }
    1360  
    1361    if (*argv)
    1362      {
    1363        char *expansion = expand_argument (*argv, NULL);
    1364  
    1365        o = variable_buffer_output (o, expansion, strlen (expansion));
    1366  
    1367        free (expansion);
    1368      }
    1369  
    1370    return o;
    1371  }
    1372  
    1373  /*
    1374    $(if condition,true-part[,false-part])
    1375  
    1376    CONDITION is false iff it evaluates to an empty string.  White
    1377    space before and after condition are stripped before evaluation.
    1378  
    1379    If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
    1380    evaluated (if it exists).  Because only one of the two PARTs is evaluated,
    1381    you can use $(if ...) to create side-effects (with $(shell ...), for
    1382    example).
    1383  */
    1384  
    1385  static char *
    1386  func_if (char *o, char **argv, const char *funcname UNUSED)
    1387  {
    1388    const char *begp = argv[0];
    1389    const char *endp = begp + strlen (argv[0]) - 1;
    1390    int result = 0;
    1391  
    1392    /* Find the result of the condition: if we have a value, and it's not
    1393       empty, the condition is true.  If we don't have a value, or it's the
    1394       empty string, then it's false.  */
    1395  
    1396    strip_whitespace (&begp, &endp);
    1397  
    1398    if (begp <= endp)
    1399      {
    1400        char *expansion = expand_argument (begp, endp+1);
    1401  
    1402        result = expansion[0] != '\0';
    1403        free (expansion);
    1404      }
    1405  
    1406    /* If the result is true (1) we want to eval the first argument, and if
    1407       it's false (0) we want to eval the second.  If the argument doesn't
    1408       exist we do nothing, otherwise expand it and add to the buffer.  */
    1409  
    1410    argv += 1 + !result;
    1411  
    1412    if (*argv)
    1413      {
    1414        char *expansion = expand_argument (*argv, NULL);
    1415  
    1416        o = variable_buffer_output (o, expansion, strlen (expansion));
    1417  
    1418        free (expansion);
    1419      }
    1420  
    1421    return o;
    1422  }
    1423  
    1424  /*
    1425    $(or condition1[,condition2[,condition3[...]]])
    1426  
    1427    A CONDITION is false iff it evaluates to an empty string.  White
    1428    space before and after CONDITION are stripped before evaluation.
    1429  
    1430    CONDITION1 is evaluated.  If it's true, then this is the result of
    1431    expansion.  If it's false, CONDITION2 is evaluated, and so on.  If none of
    1432    the conditions are true, the expansion is the empty string.
    1433  
    1434    Once a CONDITION is true no further conditions are evaluated
    1435    (short-circuiting).
    1436  */
    1437  
    1438  static char *
    1439  func_or (char *o, char **argv, const char *funcname UNUSED)
    1440  {
    1441    for ( ; *argv ; ++argv)
    1442      {
    1443        const char *begp = *argv;
    1444        const char *endp = begp + strlen (*argv) - 1;
    1445        char *expansion;
    1446        size_t result = 0;
    1447  
    1448        /* Find the result of the condition: if it's false keep going.  */
    1449  
    1450        strip_whitespace (&begp, &endp);
    1451  
    1452        if (begp > endp)
    1453          continue;
    1454  
    1455        expansion = expand_argument (begp, endp+1);
    1456        result = strlen (expansion);
    1457  
    1458        /* If the result is false keep going.  */
    1459        if (!result)
    1460          {
    1461            free (expansion);
    1462            continue;
    1463          }
    1464  
    1465        /* It's true!  Keep this result and return.  */
    1466        o = variable_buffer_output (o, expansion, result);
    1467        free (expansion);
    1468        break;
    1469      }
    1470  
    1471    return o;
    1472  }
    1473  
    1474  /*
    1475    $(and condition1[,condition2[,condition3[...]]])
    1476  
    1477    A CONDITION is false iff it evaluates to an empty string.  White
    1478    space before and after CONDITION are stripped before evaluation.
    1479  
    1480    CONDITION1 is evaluated.  If it's false, then this is the result of
    1481    expansion.  If it's true, CONDITION2 is evaluated, and so on.  If all of
    1482    the conditions are true, the expansion is the result of the last condition.
    1483  
    1484    Once a CONDITION is false no further conditions are evaluated
    1485    (short-circuiting).
    1486  */
    1487  
    1488  static char *
    1489  func_and (char *o, char **argv, const char *funcname UNUSED)
    1490  {
    1491    char *expansion;
    1492  
    1493    while (1)
    1494      {
    1495        const char *begp = *argv;
    1496        const char *endp = begp + strlen (*argv) - 1;
    1497        size_t result;
    1498  
    1499        /* An empty condition is always false.  */
    1500        strip_whitespace (&begp, &endp);
    1501        if (begp > endp)
    1502          return o;
    1503  
    1504        expansion = expand_argument (begp, endp+1);
    1505        result = strlen (expansion);
    1506  
    1507        /* If the result is false, stop here: we're done.  */
    1508        if (!result)
    1509          break;
    1510  
    1511        /* Otherwise the result is true.  If this is the last one, keep this
    1512           result and quit.  Otherwise go on to the next one!  */
    1513  
    1514        if (*(++argv))
    1515          free (expansion);
    1516        else
    1517          {
    1518            o = variable_buffer_output (o, expansion, result);
    1519            break;
    1520          }
    1521      }
    1522  
    1523    free (expansion);
    1524  
    1525    return o;
    1526  }
    1527  
    1528  static char *
    1529  func_wildcard (char *o, char **argv, const char *funcname UNUSED)
    1530  {
    1531  #ifdef _AMIGA
    1532     o = wildcard_expansion (argv[0], o);
    1533  #else
    1534     char *p = string_glob (argv[0]);
    1535     o = variable_buffer_output (o, p, strlen (p));
    1536  #endif
    1537     return o;
    1538  }
    1539  
    1540  /*
    1541    $(eval <makefile string>)
    1542  
    1543    Always resolves to the empty string.
    1544  
    1545    Treat the arguments as a segment of makefile, and parse them.
    1546  */
    1547  
    1548  static char *
    1549  func_eval (char *o, char **argv, const char *funcname UNUSED)
    1550  {
    1551    char *buf;
    1552    size_t len;
    1553  
    1554    /* Eval the buffer.  Pop the current variable buffer setting so that the
    1555       eval'd code can use its own without conflicting.  */
    1556  
    1557    install_variable_buffer (&buf, &len);
    1558  
    1559    eval_buffer (argv[0], NULL);
    1560  
    1561    restore_variable_buffer (buf, len);
    1562  
    1563    return o;
    1564  }
    1565  
    1566  
    1567  static char *
    1568  func_value (char *o, char **argv, const char *funcname UNUSED)
    1569  {
    1570    /* Look up the variable.  */
    1571    struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
    1572  
    1573    /* Copy its value into the output buffer without expanding it.  */
    1574    if (v)
    1575      o = variable_buffer_output (o, v->value, strlen (v->value));
    1576  
    1577    return o;
    1578  }
    1579  
    1580  /*
    1581    \r is replaced on UNIX as well. Is this desirable?
    1582   */
    1583  static void
    1584  fold_newlines (char *buffer, size_t *length, int trim_newlines)
    1585  {
    1586    char *dst = buffer;
    1587    char *src = buffer;
    1588    char *last_nonnl = buffer - 1;
    1589    src[*length] = 0;
    1590    for (; *src != '\0'; ++src)
    1591      {
    1592        if (src[0] == '\r' && src[1] == '\n')
    1593          continue;
    1594        if (*src == '\n')
    1595          {
    1596            *dst++ = ' ';
    1597          }
    1598        else
    1599          {
    1600            last_nonnl = dst;
    1601            *dst++ = *src;
    1602          }
    1603      }
    1604  
    1605    if (!trim_newlines && (last_nonnl < (dst - 2)))
    1606      last_nonnl = dst - 2;
    1607  
    1608    *(++last_nonnl) = '\0';
    1609    *length = last_nonnl - buffer;
    1610  }
    1611  
    1612  pid_t shell_function_pid = 0;
    1613  static int shell_function_completed;
    1614  
    1615  void
    1616  shell_completed (int exit_code, int exit_sig)
    1617  {
    1618    char buf[INTSTR_LENGTH];
    1619  
    1620    shell_function_pid = 0;
    1621    if (exit_sig == 0 && exit_code == 127)
    1622      shell_function_completed = -1;
    1623    else
    1624      shell_function_completed = 1;
    1625  
    1626    if (exit_code == 0 && exit_sig > 0)
    1627      exit_code = 128 + exit_sig;
    1628  
    1629    sprintf (buf, "%d", exit_code);
    1630    define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
    1631  }
    1632  
    1633  #ifdef WINDOWS32
    1634  /*untested*/
    1635  
    1636  #include <windows.h>
    1637  #include <io.h>
    1638  #include "sub_proc.h"
    1639  
    1640  
    1641  int
    1642  windows32_openpipe (int *pipedes, int errfd, pid_t *pid_p, char **command_argv, char **envp)
    1643  {
    1644    SECURITY_ATTRIBUTES saAttr;
    1645    HANDLE hIn = INVALID_HANDLE_VALUE;
    1646    HANDLE hErr = INVALID_HANDLE_VALUE;
    1647    HANDLE hChildOutRd;
    1648    HANDLE hChildOutWr;
    1649    HANDLE hProcess, tmpIn, tmpErr;
    1650    DWORD e;
    1651  
    1652    /* Set status for return.  */
    1653    pipedes[0] = pipedes[1] = -1;
    1654    *pid_p = (pid_t)-1;
    1655  
    1656    saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
    1657    saAttr.bInheritHandle = TRUE;
    1658    saAttr.lpSecurityDescriptor = NULL;
    1659  
    1660    /* Standard handles returned by GetStdHandle can be NULL or
    1661       INVALID_HANDLE_VALUE if the parent process closed them.  If that
    1662       happens, we open the null device and pass its handle to
    1663       process_begin below as the corresponding handle to inherit.  */
    1664    tmpIn = GetStdHandle (STD_INPUT_HANDLE);
    1665    if (DuplicateHandle (GetCurrentProcess (), tmpIn,
    1666                         GetCurrentProcess (), &hIn,
    1667                         0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
    1668      {
    1669        e = GetLastError ();
    1670        if (e == ERROR_INVALID_HANDLE)
    1671          {
    1672            tmpIn = CreateFile ("NUL", GENERIC_READ,
    1673                                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
    1674                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    1675            if (tmpIn != INVALID_HANDLE_VALUE
    1676                && DuplicateHandle (GetCurrentProcess (), tmpIn,
    1677                                    GetCurrentProcess (), &hIn,
    1678                                    0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
    1679              CloseHandle (tmpIn);
    1680          }
    1681        if (hIn == INVALID_HANDLE_VALUE)
    1682          {
    1683            ON (error, NILF,
    1684                _("windows32_openpipe: DuplicateHandle(In) failed (e=%lu)\n"), e);
    1685            return -1;
    1686          }
    1687      }
    1688    tmpErr = (HANDLE)_get_osfhandle (errfd);
    1689    if (DuplicateHandle (GetCurrentProcess (), tmpErr,
    1690                         GetCurrentProcess (), &hErr,
    1691                         0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
    1692      {
    1693        e = GetLastError ();
    1694        if (e == ERROR_INVALID_HANDLE)
    1695          {
    1696            tmpErr = CreateFile ("NUL", GENERIC_WRITE,
    1697                                 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
    1698                                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    1699            if (tmpErr != INVALID_HANDLE_VALUE
    1700                && DuplicateHandle (GetCurrentProcess (), tmpErr,
    1701                                    GetCurrentProcess (), &hErr,
    1702                                    0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
    1703              CloseHandle (tmpErr);
    1704          }
    1705        if (hErr == INVALID_HANDLE_VALUE)
    1706          {
    1707            ON (error, NILF,
    1708                _("windows32_openpipe: DuplicateHandle(Err) failed (e=%lu)\n"), e);
    1709            return -1;
    1710          }
    1711      }
    1712  
    1713    if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
    1714      {
    1715        ON (error, NILF, _("CreatePipe() failed (e=%lu)\n"), GetLastError());
    1716        return -1;
    1717      }
    1718  
    1719    hProcess = process_init_fd (hIn, hChildOutWr, hErr);
    1720  
    1721    if (!hProcess)
    1722      {
    1723        O (error, NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
    1724        return -1;
    1725      }
    1726  
    1727    if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
    1728      {
    1729        /* register process for wait */
    1730        process_register (hProcess);
    1731  
    1732        /* set the pid for returning to caller */
    1733        *pid_p = (pid_t) hProcess;
    1734  
    1735        /* set up to read data from child */
    1736        pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
    1737  
    1738        /* this will be closed almost right away */
    1739        pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
    1740        return 0;
    1741      }
    1742    else
    1743      {
    1744        /* reap/cleanup the failed process */
    1745        process_cleanup (hProcess);
    1746  
    1747        /* close handles which were duplicated, they weren't used */
    1748        if (hIn != INVALID_HANDLE_VALUE)
    1749          CloseHandle (hIn);
    1750        if (hErr != INVALID_HANDLE_VALUE)
    1751          CloseHandle (hErr);
    1752  
    1753        /* close pipe handles, they won't be used */
    1754        CloseHandle (hChildOutRd);
    1755        CloseHandle (hChildOutWr);
    1756  
    1757        return -1;
    1758      }
    1759  }
    1760  #endif
    1761  
    1762  
    1763  #ifdef __MSDOS__
    1764  FILE *
    1765  msdos_openpipe (int* pipedes, int *pidp, char *text)
    1766  {
    1767    FILE *fpipe=0;
    1768    /* MSDOS can't fork, but it has 'popen'.  */
    1769    struct variable *sh = lookup_variable ("SHELL", 5);
    1770    int e;
    1771    extern int dos_command_running, dos_status;
    1772  
    1773    /* Make sure not to bother processing an empty line.  */
    1774    NEXT_TOKEN (text);
    1775    if (*text == '\0')
    1776      return 0;
    1777  
    1778    if (sh)
    1779      {
    1780        char buf[PATH_MAX + 7];
    1781        /* This makes sure $SHELL value is used by $(shell), even
    1782           though the target environment is not passed to it.  */
    1783        sprintf (buf, "SHELL=%s", sh->value);
    1784        putenv (buf);
    1785      }
    1786  
    1787    e = errno;
    1788    errno = 0;
    1789    dos_command_running = 1;
    1790    dos_status = 0;
    1791    /* If dos_status becomes non-zero, it means the child process
    1792       was interrupted by a signal, like SIGINT or SIGQUIT.  See
    1793       fatal_error_signal in commands.c.  */
    1794    fpipe = popen (text, "rt");
    1795    dos_command_running = 0;
    1796    if (!fpipe || dos_status)
    1797      {
    1798        pipedes[0] = -1;
    1799        *pidp = -1;
    1800        if (dos_status)
    1801          errno = EINTR;
    1802        else if (errno == 0)
    1803          errno = ENOMEM;
    1804        if (fpipe)
    1805          pclose (fpipe);
    1806        shell_completed (127, 0);
    1807      }
    1808    else
    1809      {
    1810        pipedes[0] = fileno (fpipe);
    1811        *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
    1812        errno = e;
    1813      }
    1814    return fpipe;
    1815  }
    1816  #endif
    1817  
    1818  /*
    1819    Do shell spawning, with the naughty bits for different OSes.
    1820   */
    1821  
    1822  #ifdef VMS
    1823  
    1824  /* VMS can't do $(shell ...)  */
    1825  
    1826  char *
    1827  func_shell_base (char *o, char **argv, int trim_newlines)
    1828  {
    1829    fprintf (stderr, "This platform does not support shell\n");
    1830    die (MAKE_TROUBLE);
    1831    return NULL;
    1832  }
    1833  
    1834  #define func_shell 0
    1835  
    1836  #else
    1837  #ifndef _AMIGA
    1838  char *
    1839  func_shell_base (char *o, char **argv, int trim_newlines)
    1840  {
    1841    struct childbase child = {0};
    1842    char *batch_filename = NULL;
    1843    int errfd;
    1844  #ifdef __MSDOS__
    1845    FILE *fpipe;
    1846  #endif
    1847    char **command_argv = NULL;
    1848    int pipedes[2];
    1849    pid_t pid;
    1850  
    1851  #ifndef __MSDOS__
    1852  #ifdef WINDOWS32
    1853    /* Reset just_print_flag.  This is needed on Windows when batch files
    1854       are used to run the commands, because we normally refrain from
    1855       creating batch files under -n.  */
    1856    int j_p_f = just_print_flag;
    1857    just_print_flag = 0;
    1858  #endif
    1859  
    1860    /* Construct the argument list.  */
    1861    command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
    1862                                           &batch_filename);
    1863    if (command_argv == 0)
    1864      {
    1865  #ifdef WINDOWS32
    1866        just_print_flag = j_p_f;
    1867  #endif
    1868        return o;
    1869      }
    1870  #endif /* !__MSDOS__ */
    1871  
    1872    /* Set up the output in case the shell writes something.  */
    1873    output_start ();
    1874  
    1875    errfd = (output_context && output_context->err >= 0
    1876             ? output_context->err : FD_STDERR);
    1877  
    1878    child.environment = target_environment (NULL, 0);
    1879  
    1880  #if defined(__MSDOS__)
    1881    fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
    1882    if (pipedes[0] < 0)
    1883      {
    1884        OS (error, reading_file, "pipe: %s", strerror (errno));
    1885        pid = -1;
    1886        goto done;
    1887      }
    1888  
    1889  #elif defined(WINDOWS32)
    1890    windows32_openpipe (pipedes, errfd, &pid, command_argv, child.environment);
    1891    /* Restore the value of just_print_flag.  */
    1892    just_print_flag = j_p_f;
    1893  
    1894    if (pipedes[0] < 0)
    1895      {
    1896        /* Open of the pipe failed, mark as failed execution.  */
    1897        shell_completed (127, 0);
    1898        OS (error, reading_file, "pipe: %s", strerror (errno));
    1899        pid = -1;
    1900        goto done;
    1901      }
    1902  
    1903  #else
    1904    if (pipe (pipedes) < 0)
    1905      {
    1906        OS (error, reading_file, "pipe: %s", strerror (errno));
    1907        pid = -1;
    1908        goto done;
    1909      }
    1910  
    1911    /* Close handles that are unnecessary for the child process.  */
    1912    fd_noinherit (pipedes[1]);
    1913    fd_noinherit (pipedes[0]);
    1914  
    1915    child.output.syncout = 1;
    1916    child.output.out = pipedes[1];
    1917    child.output.err = errfd;
    1918  
    1919    pid = child_execute_job (&child, 1, command_argv);
    1920  
    1921    if (pid < 0)
    1922      {
    1923        shell_completed (127, 0);
    1924        goto done;
    1925      }
    1926  #endif
    1927  
    1928    {
    1929      char *buffer;
    1930      size_t maxlen, i;
    1931      int cc;
    1932  
    1933      /* Record the PID for reap_children.  */
    1934      shell_function_pid = pid;
    1935  #ifndef  __MSDOS__
    1936      shell_function_completed = 0;
    1937  
    1938      /* Close the write side of the pipe.  We test for -1, since
    1939         pipedes[1] is -1 on MS-Windows, and some versions of MS
    1940         libraries barf when 'close' is called with -1.  */
    1941      if (pipedes[1] >= 0)
    1942        close (pipedes[1]);
    1943  #endif
    1944  
    1945      /* Set up and read from the pipe.  */
    1946  
    1947      maxlen = 200;
    1948      buffer = xmalloc (maxlen + 1);
    1949  
    1950      /* Read from the pipe until it gets EOF.  */
    1951      for (i = 0; ; i += cc)
    1952        {
    1953          if (i == maxlen)
    1954            {
    1955              maxlen += 512;
    1956              buffer = xrealloc (buffer, maxlen + 1);
    1957            }
    1958  
    1959          EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
    1960          if (cc <= 0)
    1961            break;
    1962        }
    1963      buffer[i] = '\0';
    1964  
    1965      /* Close the read side of the pipe.  */
    1966  #ifdef  __MSDOS__
    1967      if (fpipe)
    1968        {
    1969          int st = pclose (fpipe);
    1970          shell_completed (st, 0);
    1971        }
    1972  #else
    1973      (void) close (pipedes[0]);
    1974  #endif
    1975  
    1976      /* Loop until child_handler or reap_children()  sets
    1977         shell_function_completed to the status of our child shell.  */
    1978      while (shell_function_completed == 0)
    1979        reap_children (1, 0);
    1980  
    1981      if (batch_filename)
    1982        {
    1983          DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
    1984                           batch_filename));
    1985          remove (batch_filename);
    1986          free (batch_filename);
    1987        }
    1988      shell_function_pid = 0;
    1989  
    1990      /* Replace all newlines in the command's output with spaces, and put that
    1991         in the variable output buffer.  */
    1992      fold_newlines (buffer, &i, trim_newlines);
    1993      o = variable_buffer_output (o, buffer, i);
    1994  
    1995      free (buffer);
    1996    }
    1997  
    1998   done:
    1999    if (command_argv)
    2000      {
    2001        /* Free the storage only the child needed.  */
    2002        free (command_argv[0]);
    2003        free (command_argv);
    2004      }
    2005  
    2006    free_childbase (&child);
    2007  
    2008    return o;
    2009  }
    2010  
    2011  #else   /* _AMIGA */
    2012  
    2013  /* Do the Amiga version of func_shell.  */
    2014  
    2015  char *
    2016  func_shell_base (char *o, char **argv, int trim_newlines)
    2017  {
    2018    /* Amiga can't fork nor spawn, but I can start a program with
    2019       redirection of my choice.  However, this means that we
    2020       don't have an opportunity to reopen stdout to trap it.  Thus,
    2021       we save our own stdout onto a new descriptor and dup a temp
    2022       file's descriptor onto our stdout temporarily.  After we
    2023       spawn the shell program, we dup our own stdout back to the
    2024       stdout descriptor.  The buffer reading is the same as above,
    2025       except that we're now reading from a file.  */
    2026  
    2027  #include <dos/dos.h>
    2028  #include <proto/dos.h>
    2029  
    2030    BPTR child_stdout;
    2031    char tmp_output[FILENAME_MAX];
    2032    size_t maxlen = 200, i;
    2033    int cc;
    2034    char * buffer, * ptr;
    2035    char ** aptr;
    2036    size_t len = 0;
    2037    char* batch_filename = NULL;
    2038  
    2039    /* Construct the argument list.  */
    2040    command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
    2041                                           &batch_filename);
    2042    if (command_argv == 0)
    2043      return o;
    2044  
    2045    /* Note the mktemp() is a security hole, but this only runs on Amiga.
    2046       Ideally we would use get_tmpfile(), but this uses a special Open(), not
    2047       fopen(), and I'm not familiar enough with the code to mess with it.  */
    2048    strcpy (tmp_output, "t:MakeshXXXXXXXX");
    2049    mktemp (tmp_output);
    2050    child_stdout = Open (tmp_output, MODE_NEWFILE);
    2051  
    2052    for (aptr=command_argv; *aptr; aptr++)
    2053      len += strlen (*aptr) + 1;
    2054  
    2055    buffer = xmalloc (len + 1);
    2056    ptr = buffer;
    2057  
    2058    for (aptr=command_argv; *aptr; aptr++)
    2059      {
    2060        strcpy (ptr, *aptr);
    2061        ptr += strlen (ptr) + 1;
    2062        *(ptr++) = ' ';
    2063        *ptr = '\0';
    2064      }
    2065  
    2066    ptr[-1] = '\n';
    2067  
    2068    Execute (buffer, NULL, child_stdout);
    2069    free (buffer);
    2070  
    2071    Close (child_stdout);
    2072  
    2073    child_stdout = Open (tmp_output, MODE_OLDFILE);
    2074  
    2075    buffer = xmalloc (maxlen);
    2076    i = 0;
    2077    do
    2078      {
    2079        if (i == maxlen)
    2080          {
    2081            maxlen += 512;
    2082            buffer = xrealloc (buffer, maxlen + 1);
    2083          }
    2084  
    2085        cc = Read (child_stdout, &buffer[i], maxlen - i);
    2086        if (cc > 0)
    2087          i += cc;
    2088      } while (cc > 0);
    2089  
    2090    Close (child_stdout);
    2091  
    2092    fold_newlines (buffer, &i, trim_newlines);
    2093    o = variable_buffer_output (o, buffer, i);
    2094    free (buffer);
    2095    return o;
    2096  }
    2097  #endif  /* _AMIGA */
    2098  
    2099  static char *
    2100  func_shell (char *o, char **argv, const char *funcname UNUSED)
    2101  {
    2102    return func_shell_base (o, argv, 1);
    2103  }
    2104  #endif  /* !VMS */
    2105  
    2106  #ifdef EXPERIMENTAL
    2107  
    2108  /*
    2109    equality. Return is string-boolean, i.e., the empty string is false.
    2110   */
    2111  static char *
    2112  func_eq (char *o, char **argv, char *funcname UNUSED)
    2113  {
    2114    int result = ! strcmp (argv[0], argv[1]);
    2115    o = variable_buffer_output (o,  result ? "1" : "", result);
    2116    return o;
    2117  }
    2118  
    2119  
    2120  /*
    2121    string-boolean not operator.
    2122   */
    2123  static char *
    2124  func_not (char *o, char **argv, char *funcname UNUSED)
    2125  {
    2126    const char *s = argv[0];
    2127    int result = 0;
    2128    NEXT_TOKEN (s);
    2129    result = ! (*s);
    2130    o = variable_buffer_output (o,  result ? "1" : "", result);
    2131    return o;
    2132  }
    2133  #endif
    2134  
    2135  
    2136  #ifdef HAVE_DOS_PATHS
    2137  # ifdef __CYGWIN__
    2138  #  define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || ISDIRSEP (n[0]))
    2139  # else
    2140  #  define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
    2141  # endif
    2142  # define ROOT_LEN 3
    2143  #else
    2144  # define IS_ABSOLUTE(n) (n[0] == '/')
    2145  # define ROOT_LEN 1
    2146  #endif
    2147  
    2148  /* Return the absolute name of file NAME which does not contain any '.',
    2149     '..' components nor any repeated path separators ('/').   */
    2150  
    2151  static char *
    2152  abspath (const char *name, char *apath)
    2153  {
    2154    char *dest;
    2155    const char *start, *end, *apath_limit;
    2156    unsigned long root_len = ROOT_LEN;
    2157  
    2158    if (name[0] == '\0')
    2159      return NULL;
    2160  
    2161    apath_limit = apath + GET_PATH_MAX;
    2162  
    2163    if (!IS_ABSOLUTE(name))
    2164      {
    2165        /* It is unlikely we would make it until here but just to make sure. */
    2166        if (!starting_directory)
    2167          return NULL;
    2168  
    2169        strcpy (apath, starting_directory);
    2170  
    2171  #ifdef HAVE_DOS_PATHS
    2172        if (ISDIRSEP (name[0]))
    2173          {
    2174            if (ISDIRSEP (name[1]))
    2175              {
    2176                /* A UNC.  Don't prepend a drive letter.  */
    2177                apath[0] = name[0];
    2178                apath[1] = name[1];
    2179                root_len = 2;
    2180              }
    2181            /* We have /foo, an absolute file name except for the drive
    2182               letter.  Assume the missing drive letter is the current
    2183               drive, which we can get if we remove from starting_directory
    2184               everything past the root directory.  */
    2185            apath[root_len] = '\0';
    2186          }
    2187  #endif
    2188  
    2189        dest = strchr (apath, '\0');
    2190      }
    2191    else
    2192      {
    2193  #if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
    2194        if (ISDIRSEP (name[0]))
    2195          root_len = 1;
    2196  #endif
    2197        memcpy (apath, name, root_len);
    2198        apath[root_len] = '\0';
    2199        dest = apath + root_len;
    2200        /* Get past the root, since we already copied it.  */
    2201        name += root_len;
    2202  #ifdef HAVE_DOS_PATHS
    2203        if (! ISDIRSEP (apath[root_len - 1]))
    2204          {
    2205            /* Convert d:foo into d:./foo and increase root_len.  */
    2206            apath[2] = '.';
    2207            apath[3] = '/';
    2208            dest++;
    2209            root_len++;
    2210            /* strncpy above copied one character too many.  */
    2211            name--;
    2212          }
    2213        else
    2214          apath[root_len - 1] = '/'; /* make sure it's a forward slash */
    2215  #endif
    2216      }
    2217  
    2218    for (start = end = name; *start != '\0'; start = end)
    2219      {
    2220        size_t len;
    2221  
    2222        /* Skip sequence of multiple path-separators.  */
    2223        while (ISDIRSEP (*start))
    2224          ++start;
    2225  
    2226        /* Find end of path component.  */
    2227        for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
    2228          ;
    2229  
    2230        len = end - start;
    2231  
    2232        if (len == 0)
    2233          break;
    2234        else if (len == 1 && start[0] == '.')
    2235          /* nothing */;
    2236        else if (len == 2 && start[0] == '.' && start[1] == '.')
    2237          {
    2238            /* Back up to previous component, ignore if at root already.  */
    2239            if (dest > apath + root_len)
    2240              for (--dest; ! ISDIRSEP (dest[-1]); --dest)
    2241                ;
    2242          }
    2243        else
    2244          {
    2245            if (! ISDIRSEP (dest[-1]))
    2246              *dest++ = '/';
    2247  
    2248            if (dest + len >= apath_limit)
    2249              return NULL;
    2250  
    2251            dest = mempcpy (dest, start, len);
    2252            *dest = '\0';
    2253          }
    2254      }
    2255  
    2256    /* Unless it is root strip trailing separator.  */
    2257    if (dest > apath + root_len && ISDIRSEP (dest[-1]))
    2258      --dest;
    2259  
    2260    *dest = '\0';
    2261  
    2262    return apath;
    2263  }
    2264  
    2265  
    2266  static char *
    2267  func_realpath (char *o, char **argv, const char *funcname UNUSED)
    2268  {
    2269    /* Expand the argument.  */
    2270    const char *p = argv[0];
    2271    const char *path = 0;
    2272    int doneany = 0;
    2273    size_t len = 0;
    2274  
    2275    while ((path = find_next_token (&p, &len)) != 0)
    2276      {
    2277        if (len < GET_PATH_MAX)
    2278          {
    2279            char *rp;
    2280            struct stat st;
    2281            PATH_VAR (in);
    2282            PATH_VAR (out);
    2283  
    2284            strncpy (in, path, len);
    2285            in[len] = '\0';
    2286  
    2287  #ifdef HAVE_REALPATH
    2288            ENULLLOOP (rp, realpath (in, out));
    2289  # if defined _AIX
    2290            /* AIX realpath() doesn't remove trailing slashes correctly.  */
    2291            if (rp)
    2292              {
    2293                char *ep = rp + strlen (rp) - 1;
    2294                while (ep > rp && ep[0] == '/')
    2295                  *(ep--) = '\0';
    2296              }
    2297  # endif
    2298  #else
    2299            rp = abspath (in, out);
    2300  #endif
    2301  
    2302            if (rp)
    2303              {
    2304                int r;
    2305                EINTRLOOP (r, stat (out, &st));
    2306                if (r == 0)
    2307                  {
    2308                    o = variable_buffer_output (o, out, strlen (out));
    2309                    o = variable_buffer_output (o, " ", 1);
    2310                    doneany = 1;
    2311                  }
    2312              }
    2313          }
    2314      }
    2315  
    2316    /* Kill last space.  */
    2317    if (doneany)
    2318      --o;
    2319  
    2320    return o;
    2321  }
    2322  
    2323  static char *
    2324  func_file (char *o, char **argv, const char *funcname UNUSED)
    2325  {
    2326    char *fn = argv[0];
    2327  
    2328    if (fn[0] == '>')
    2329      {
    2330        FILE *fp;
    2331        const char *mode = "w";
    2332  
    2333        /* We are writing a file.  */
    2334        ++fn;
    2335        if (fn[0] == '>')
    2336          {
    2337            mode = "a";
    2338            ++fn;
    2339          }
    2340        NEXT_TOKEN (fn);
    2341  
    2342        if (fn[0] == '\0')
    2343          O (fatal, *expanding_var, _("file: missing filename"));
    2344  
    2345        ENULLLOOP (fp, fopen (fn, mode));
    2346        if (fp == NULL)
    2347          OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
    2348  
    2349        /* We've changed the contents of a directory, possibly.
    2350           Another option would be to look up the directory we changed and reset
    2351           its counter to 0.  */
    2352        ++command_count;
    2353  
    2354        if (argv[1])
    2355          {
    2356            size_t l = strlen (argv[1]);
    2357            int nl = l == 0 || argv[1][l-1] != '\n';
    2358  
    2359            if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
    2360              OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
    2361          }
    2362        if (fclose (fp))
    2363          OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
    2364      }
    2365    else if (fn[0] == '<')
    2366      {
    2367        size_t n = 0;
    2368        FILE *fp;
    2369  
    2370        ++fn;
    2371        NEXT_TOKEN (fn);
    2372        if (fn[0] == '\0')
    2373          O (fatal, *expanding_var, _("file: missing filename"));
    2374  
    2375        if (argv[1])
    2376          O (fatal, *expanding_var, _("file: too many arguments"));
    2377  
    2378        ENULLLOOP (fp, fopen (fn, "r"));
    2379        if (fp == NULL)
    2380          {
    2381            if (errno == ENOENT)
    2382              return o;
    2383            OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
    2384          }
    2385  
    2386        while (1)
    2387          {
    2388            char buf[1024];
    2389            size_t l = fread (buf, 1, sizeof (buf), fp);
    2390            if (l > 0)
    2391              {
    2392                o = variable_buffer_output (o, buf, l);
    2393                n += l;
    2394              }
    2395            if (ferror (fp))
    2396              if (errno != EINTR)
    2397                OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
    2398            if (feof (fp))
    2399              break;
    2400          }
    2401        if (fclose (fp))
    2402          OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
    2403  
    2404        /* Remove trailing newline.  */
    2405        if (n && o[-1] == '\n')
    2406          o -= 1 + (n > 1 && o[-2] == '\r');
    2407      }
    2408    else
    2409      OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
    2410  
    2411    return o;
    2412  }
    2413  
    2414  static char *
    2415  func_abspath (char *o, char **argv, const char *funcname UNUSED)
    2416  {
    2417    /* Expand the argument.  */
    2418    const char *p = argv[0];
    2419    const char *path = 0;
    2420    int doneany = 0;
    2421    size_t len = 0;
    2422  
    2423    while ((path = find_next_token (&p, &len)) != 0)
    2424      {
    2425        if (len < GET_PATH_MAX)
    2426          {
    2427            PATH_VAR (in);
    2428            PATH_VAR (out);
    2429  
    2430            strncpy (in, path, len);
    2431            in[len] = '\0';
    2432  
    2433            if (abspath (in, out))
    2434              {
    2435                o = variable_buffer_output (o, out, strlen (out));
    2436                o = variable_buffer_output (o, " ", 1);
    2437                doneany = 1;
    2438              }
    2439          }
    2440      }
    2441  
    2442    /* Kill last space.  */
    2443    if (doneany)
    2444      --o;
    2445  
    2446    return o;
    2447  }
    2448  
    2449  /* Lookup table for builtin functions.
    2450  
    2451     This doesn't have to be sorted; we use a straight lookup.  We might gain
    2452     some efficiency by moving most often used functions to the start of the
    2453     table.
    2454  
    2455     If MAXIMUM_ARGS is 0, that means there is no maximum and all
    2456     comma-separated values are treated as arguments.
    2457  
    2458     EXPAND_ARGS means that all arguments should be expanded before invocation.
    2459     Functions that do namespace tricks (foreach, let) don't automatically
    2460     expand.  */
    2461  
    2462  static char *func_call (char *o, char **argv, const char *funcname);
    2463  
    2464  #define FT_ENTRY(_name, _min, _max, _exp, _func) \
    2465    { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0, 0 }
    2466  
    2467  static struct function_table_entry function_table_init[] =
    2468  {
    2469   /*         Name            MIN MAX EXP? Function */
    2470    FT_ENTRY ("abspath",       0,  1,  1,  func_abspath),
    2471    FT_ENTRY ("addprefix",     2,  2,  1,  func_addsuffix_addprefix),
    2472    FT_ENTRY ("addsuffix",     2,  2,  1,  func_addsuffix_addprefix),
    2473    FT_ENTRY ("basename",      0,  1,  1,  func_basename_dir),
    2474    FT_ENTRY ("dir",           0,  1,  1,  func_basename_dir),
    2475    FT_ENTRY ("notdir",        0,  1,  1,  func_notdir_suffix),
    2476    FT_ENTRY ("subst",         3,  3,  1,  func_subst),
    2477    FT_ENTRY ("suffix",        0,  1,  1,  func_notdir_suffix),
    2478    FT_ENTRY ("filter",        2,  2,  1,  func_filter_filterout),
    2479    FT_ENTRY ("filter-out",    2,  2,  1,  func_filter_filterout),
    2480    FT_ENTRY ("findstring",    2,  2,  1,  func_findstring),
    2481    FT_ENTRY ("firstword",     0,  1,  1,  func_firstword),
    2482    FT_ENTRY ("flavor",        0,  1,  1,  func_flavor),
    2483    FT_ENTRY ("join",          2,  2,  1,  func_join),
    2484    FT_ENTRY ("lastword",      0,  1,  1,  func_lastword),
    2485    FT_ENTRY ("patsubst",      3,  3,  1,  func_patsubst),
    2486    FT_ENTRY ("realpath",      0,  1,  1,  func_realpath),
    2487    FT_ENTRY ("shell",         0,  1,  1,  func_shell),
    2488    FT_ENTRY ("sort",          0,  1,  1,  func_sort),
    2489    FT_ENTRY ("strip",         0,  1,  1,  func_strip),
    2490    FT_ENTRY ("wildcard",      0,  1,  1,  func_wildcard),
    2491    FT_ENTRY ("word",          2,  2,  1,  func_word),
    2492    FT_ENTRY ("wordlist",      3,  3,  1,  func_wordlist),
    2493    FT_ENTRY ("words",         0,  1,  1,  func_words),
    2494    FT_ENTRY ("origin",        0,  1,  1,  func_origin),
    2495    FT_ENTRY ("foreach",       3,  3,  0,  func_foreach),
    2496    FT_ENTRY ("let",           3,  3,  0,  func_let),
    2497    FT_ENTRY ("call",          1,  0,  1,  func_call),
    2498    FT_ENTRY ("info",          0,  1,  1,  func_error),
    2499    FT_ENTRY ("error",         0,  1,  1,  func_error),
    2500    FT_ENTRY ("warning",       0,  1,  1,  func_error),
    2501    FT_ENTRY ("intcmp",        2,  5,  0,  func_intcmp),
    2502    FT_ENTRY ("if",            2,  3,  0,  func_if),
    2503    FT_ENTRY ("or",            1,  0,  0,  func_or),
    2504    FT_ENTRY ("and",           1,  0,  0,  func_and),
    2505    FT_ENTRY ("value",         0,  1,  1,  func_value),
    2506    FT_ENTRY ("eval",          0,  1,  1,  func_eval),
    2507    FT_ENTRY ("file",          1,  2,  1,  func_file),
    2508  #ifdef EXPERIMENTAL
    2509    FT_ENTRY ("eq",            2,  2,  1,  func_eq),
    2510    FT_ENTRY ("not",           0,  1,  1,  func_not),
    2511  #endif
    2512  };
    2513  
    2514  #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
    2515  
    2516  
    2517  /* These must come after the definition of function_table.  */
    2518  
    2519  static char *
    2520  expand_builtin_function (char *o, unsigned int argc, char **argv,
    2521                           const struct function_table_entry *entry_p)
    2522  {
    2523    char *p;
    2524  
    2525    if (argc < entry_p->minimum_args)
    2526      fatal (*expanding_var, strlen (entry_p->name),
    2527             _("insufficient number of arguments (%u) to function '%s'"),
    2528             argc, entry_p->name);
    2529  
    2530    /* I suppose technically some function could do something with no arguments,
    2531       but so far no internal ones do, so just test it for all functions here
    2532       rather than in each one.  We can change it later if necessary.  */
    2533  
    2534    if (!argc && !entry_p->alloc_fn)
    2535      return o;
    2536  
    2537    if (!entry_p->fptr.func_ptr)
    2538      OS (fatal, *expanding_var,
    2539          _("unimplemented on this platform: function '%s'"), entry_p->name);
    2540  
    2541    if (entry_p->adds_command)
    2542      ++command_count;
    2543  
    2544    if (!entry_p->alloc_fn)
    2545      return entry_p->fptr.func_ptr (o, argv, entry_p->name);
    2546  
    2547    /* This function allocates memory and returns it to us.
    2548       Write it to the variable buffer, then free it.  */
    2549  
    2550    p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
    2551    if (p)
    2552      {
    2553        o = variable_buffer_output (o, p, strlen (p));
    2554        free (p);
    2555      }
    2556  
    2557    return o;
    2558  }
    2559  
    2560  /* Check for a function invocation in *STRINGP.  *STRINGP points at the
    2561     opening ( or { and is not null-terminated.  If a function invocation
    2562     is found, expand it into the buffer at *OP, updating *OP, incrementing
    2563     *STRINGP past the reference and returning nonzero.  If not, return zero.  */
    2564  
    2565  int
    2566  handle_function (char **op, const char **stringp)
    2567  {
    2568    const struct function_table_entry *entry_p;
    2569    char openparen = (*stringp)[0];
    2570    char closeparen = openparen == '(' ? ')' : '}';
    2571    const char *beg;
    2572    const char *end;
    2573    int count = 0;
    2574    char *abeg = NULL;
    2575    char **argv, **argvp;
    2576    unsigned int nargs;
    2577  
    2578    beg = *stringp + 1;
    2579  
    2580    entry_p = lookup_function (beg);
    2581  
    2582    if (!entry_p)
    2583      return 0;
    2584  
    2585    /* We found a builtin function.  Find the beginning of its arguments (skip
    2586       whitespace after the name).  */
    2587  
    2588    beg += entry_p->len;
    2589    NEXT_TOKEN (beg);
    2590  
    2591    /* Find the end of the function invocation, counting nested use of
    2592       whichever kind of parens we use.  Since we're looking, count commas
    2593       to get a rough estimate of how many arguments we might have.  The
    2594       count might be high, but it'll never be low.  */
    2595  
    2596    for (nargs=1, end=beg; *end != '\0'; ++end)
    2597      if (!STOP_SET (*end, MAP_VARSEP|MAP_COMMA))
    2598        continue;
    2599      else if (*end == ',')
    2600        ++nargs;
    2601      else if (*end == openparen)
    2602        ++count;
    2603      else if (*end == closeparen && --count < 0)
    2604        break;
    2605  
    2606    if (count >= 0)
    2607      fatal (*expanding_var, strlen (entry_p->name),
    2608             _("unterminated call to function '%s': missing '%c'"),
    2609             entry_p->name, closeparen);
    2610  
    2611    *stringp = end;
    2612  
    2613    /* Get some memory to store the arg pointers.  */
    2614    argvp = argv = alloca (sizeof (char *) * (nargs + 2));
    2615  
    2616    /* Chop the string into arguments, then a nul.  As soon as we hit
    2617       MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
    2618       last argument.
    2619  
    2620       If we're expanding, store pointers to the expansion of each one.  If
    2621       not, make a duplicate of the string and point into that, nul-terminating
    2622       each argument.  */
    2623  
    2624    if (entry_p->expand_args)
    2625      {
    2626        const char *p;
    2627        for (p=beg, nargs=0; p <= end; ++argvp)
    2628          {
    2629            const char *next;
    2630  
    2631            ++nargs;
    2632  
    2633            if (nargs == entry_p->maximum_args
    2634                || ((next = find_next_argument (openparen, closeparen, p, end)) == NULL))
    2635              next = end;
    2636  
    2637            *argvp = expand_argument (p, next);
    2638            p = next + 1;
    2639          }
    2640      }
    2641    else
    2642      {
    2643        size_t len = end - beg;
    2644        char *p, *aend;
    2645  
    2646        abeg = xmalloc (len+1);
    2647        aend = mempcpy (abeg, beg, len);
    2648        *aend = '\0';
    2649  
    2650        for (p=abeg, nargs=0; p <= aend; ++argvp)
    2651          {
    2652            char *next;
    2653  
    2654            ++nargs;
    2655  
    2656            if (nargs == entry_p->maximum_args
    2657                || ((next = find_next_argument (openparen, closeparen, p, aend)) == NULL))
    2658              next = aend;
    2659  
    2660            *argvp = p;
    2661            *next = '\0';
    2662            p = next + 1;
    2663          }
    2664      }
    2665    *argvp = NULL;
    2666  
    2667    /* Finally!  Run the function...  */
    2668    *op = expand_builtin_function (*op, nargs, argv, entry_p);
    2669  
    2670    /* Free memory.  */
    2671    if (entry_p->expand_args)
    2672      for (argvp=argv; *argvp != 0; ++argvp)
    2673        free (*argvp);
    2674    else
    2675      free (abeg);
    2676  
    2677    return 1;
    2678  }
    2679  
    2680  
    2681  /* User-defined functions.  Expand the first argument as either a builtin
    2682     function or a make variable, in the context of the rest of the arguments
    2683     assigned to $1, $2, ... $N.  $0 is the name of the function.  */
    2684  
    2685  static char *
    2686  func_call (char *o, char **argv, const char *funcname UNUSED)
    2687  {
    2688    static unsigned int max_args = 0;
    2689    char *fname;
    2690    char *body;
    2691    size_t flen;
    2692    unsigned int i;
    2693    int saved_args;
    2694    const struct function_table_entry *entry_p;
    2695    struct variable *v;
    2696  
    2697    /* Clean up the name of the variable to be invoked.  */
    2698    fname = next_token (argv[0]);
    2699    end_of_token (fname)[0] = '\0';
    2700  
    2701    /* Calling nothing is a no-op */
    2702    if (*fname == '\0')
    2703      return o;
    2704  
    2705    /* Are we invoking a builtin function?  */
    2706  
    2707    entry_p = lookup_function (fname);
    2708    if (entry_p)
    2709      {
    2710        /* How many arguments do we have?  */
    2711        for (i=0; argv[i+1]; ++i)
    2712          ;
    2713        return expand_builtin_function (o, i, argv+1, entry_p);
    2714      }
    2715  
    2716    /* Not a builtin, so the first argument is the name of a variable to be
    2717       expanded and interpreted as a function.  Find it.  */
    2718    flen = strlen (fname);
    2719  
    2720    v = lookup_variable (fname, flen);
    2721  
    2722    if (v == 0)
    2723      warn_undefined (fname, flen);
    2724  
    2725    if (v == 0 || *v->value == '\0')
    2726      return o;
    2727  
    2728    body = alloca (flen + 4);
    2729    body[0] = '$';
    2730    body[1] = '(';
    2731    memcpy (body + 2, fname, flen);
    2732    body[flen+2] = ')';
    2733    body[flen+3] = '\0';
    2734  
    2735    /* Set up arguments $(1) .. $(N).  $(0) is the function name.  */
    2736  
    2737    push_new_variable_scope ();
    2738  
    2739    for (i=0; *argv; ++i, ++argv)
    2740      {
    2741        char num[INTSTR_LENGTH];
    2742  
    2743        sprintf (num, "%u", i);
    2744        define_variable (num, strlen (num), *argv, o_automatic, 0);
    2745      }
    2746  
    2747    /* If the number of arguments we have is < max_args, it means we're inside
    2748       a recursive invocation of $(call ...).  Fill in the remaining arguments
    2749       in the new scope with the empty value, to hide them from this
    2750       invocation.  */
    2751  
    2752    for (; i < max_args; ++i)
    2753      {
    2754        char num[INTSTR_LENGTH];
    2755  
    2756        sprintf (num, "%u", i);
    2757        define_variable (num, strlen (num), "", o_automatic, 0);
    2758      }
    2759  
    2760    /* Expand the body in the context of the arguments, adding the result to
    2761       the variable buffer.  */
    2762  
    2763    v->exp_count = EXP_COUNT_MAX;
    2764  
    2765    saved_args = max_args;
    2766    max_args = i;
    2767    o = variable_expand_string (o, body, flen+3);
    2768    max_args = saved_args;
    2769  
    2770    v->exp_count = 0;
    2771  
    2772    pop_variable_scope ();
    2773  
    2774    return o + strlen (o);
    2775  }
    2776  
    2777  void
    2778  define_new_function (const floc *flocp, const char *name,
    2779                       unsigned int min, unsigned int max, unsigned int flags,
    2780                       gmk_func_ptr func)
    2781  {
    2782    const char *e = name;
    2783    struct function_table_entry *ent;
    2784    size_t len;
    2785  
    2786    while (STOP_SET (*e, MAP_USERFUNC))
    2787      e++;
    2788    len = e - name;
    2789  
    2790    if (len == 0)
    2791      O (fatal, flocp, _("Empty function name"));
    2792    if (*name == '.' || *e != '\0')
    2793      OS (fatal, flocp, _("Invalid function name: %s"), name);
    2794    if (len > 255)
    2795      OS (fatal, flocp, _("Function name too long: %s"), name);
    2796    if (min > 255)
    2797      ONS (fatal, flocp,
    2798           _("Invalid minimum argument count (%u) for function %s"), min, name);
    2799    if (max > 255 || (max && max < min))
    2800      ONS (fatal, flocp,
    2801           _("Invalid maximum argument count (%u) for function %s"), max, name);
    2802  
    2803    ent = xmalloc (sizeof (struct function_table_entry));
    2804    ent->name = name;
    2805    ent->len = (unsigned char) len;
    2806    ent->minimum_args = (unsigned char) min;
    2807    ent->maximum_args = (unsigned char) max;
    2808    ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
    2809    ent->alloc_fn = 1;
    2810    /* We don't know what this function will do.  */
    2811    ent->adds_command = 1;
    2812    ent->fptr.alloc_func_ptr = func;
    2813  
    2814    ent = hash_insert (&function_table, ent);
    2815    free (ent);
    2816  }
    2817  
    2818  void
    2819  hash_init_function_table (void)
    2820  {
    2821    hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
    2822               function_table_entry_hash_1, function_table_entry_hash_2,
    2823               function_table_entry_hash_cmp);
    2824    hash_load (&function_table, function_table_init,
    2825               FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
    2826  }