Ignore:
Timestamp:
Mar 12, 2018, 8:32:29 PM (7 years ago)
Author:
bird
Message:

Imported make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6) from https://git.savannah.gnu.org/git/make.git.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • vendor/gnumake/current/function.c

    r2596 r3138  
    11/* Builtin function expansion for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "variable.h"
     
    3230struct function_table_entry
    3331  {
     32    union {
     33      char *(*func_ptr) (char *output, char **argv, const char *fname);
     34      gmk_func_ptr alloc_func_ptr;
     35    } fptr;
    3436    const char *name;
    3537    unsigned char len;
    3638    unsigned char minimum_args;
    3739    unsigned char maximum_args;
    38     char expand_args;
    39     char *(*func_ptr) (char *output, char **argv, const char *fname);
     40    unsigned char expand_args:1;
     41    unsigned char alloc_fn:1;
    4042  };
    4143
     
    8789      o = variable_buffer_output (o, t, strlen (t));
    8890      if (rlen > 0)
    89         o = variable_buffer_output (o, replace, rlen);
     91        o = variable_buffer_output (o, replace, rlen);
    9092      return o;
    9193    }
     
    9496    {
    9597      if (by_word && slen == 0)
    96         /* When matching by words, the empty string should match
    97            the end of each word, rather than the end of the whole text.  */
    98         p = end_of_token (next_token (t));
     98        /* When matching by words, the empty string should match
     99           the end of each word, rather than the end of the whole text.  */
     100        p = end_of_token (next_token (t));
    99101      else
    100         {
    101           p = strstr (t, subst);
    102           if (p == 0)
    103             {
    104               /* No more matches.  Output everything left on the end.  */
    105               o = variable_buffer_output (o, t, strlen (t));
    106               return o;
    107             }
    108         }
     102        {
     103          p = strstr (t, subst);
     104          if (p == 0)
     105            {
     106              /* No more matches.  Output everything left on the end.  */
     107              o = variable_buffer_output (o, t, strlen (t));
     108              return o;
     109            }
     110        }
    109111
    110112      /* Output everything before this occurrence of the string to replace.  */
    111113      if (p > t)
    112         o = variable_buffer_output (o, t, p - t);
     114        o = variable_buffer_output (o, t, p - t);
    113115
    114116      /* If we're substituting only by fully matched words,
    115         or only at the ends of words, check that this case qualifies.  */
     117        or only at the ends of words, check that this case qualifies.  */
    116118      if (by_word
    117           && ((p > text && !isblank ((unsigned char)p[-1]))
    118               || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
    119         /* Struck out.  Output the rest of the string that is
    120            no longer to be replaced.  */
    121         o = variable_buffer_output (o, subst, slen);
     119          && ((p > text && !ISSPACE (p[-1]))
     120              || ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
     121        /* Struck out.  Output the rest of the string that is
     122           no longer to be replaced.  */
     123        o = variable_buffer_output (o, subst, slen);
    122124      else if (rlen > 0)
    123         /* Output the replacement string.  */
    124         o = variable_buffer_output (o, replace, rlen);
     125        /* Output the replacement string.  */
     126        o = variable_buffer_output (o, replace, rlen);
    125127
    126128      /* Advance T past the string to be replaced.  */
     
    170172    /* With no % in the pattern, this is just a simple substitution.  */
    171173    return subst_expand (o, text, pattern, replace,
    172                         strlen (pattern), strlen (replace), 1);
     174                        strlen (pattern), strlen (replace), 1);
    173175
    174176  /* Record the length of PATTERN before and after the %
     
    183185      /* Is it big enough to match?  */
    184186      if (len < pattern_prepercent_len + pattern_postpercent_len)
    185         fail = 1;
     187        fail = 1;
    186188
    187189      /* Does the prefix match? */
    188190      if (!fail && pattern_prepercent_len > 0
    189           && (*t != *pattern
    190               || t[pattern_prepercent_len - 1] != pattern_percent[-2]
    191               || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
    192         fail = 1;
     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;
    193195
    194196      /* Does the suffix match? */
    195197      if (!fail && pattern_postpercent_len > 0
    196           && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
    197               || t[len - pattern_postpercent_len] != *pattern_percent
    198               || !strneq (&t[len - pattern_postpercent_len],
    199                           pattern_percent, pattern_postpercent_len - 1)))
    200         fail = 1;
     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;
    201203
    202204      if (fail)
    203         /* It didn't match.  Output the string.  */
    204         o = variable_buffer_output (o, t, len);
     205        /* It didn't match.  Output the string.  */
     206        o = variable_buffer_output (o, t, len);
    205207      else
    206         {
    207           /* It matched.  Output the replacement.  */
    208 
    209           /* Output the part of the replacement before the %.  */
    210           o = variable_buffer_output (o, replace, replace_prepercent_len);
    211 
    212           if (replace_percent != 0)
    213             {
    214               /* Output the part of the matched string that
    215                 matched the % in the pattern.  */
    216               o = variable_buffer_output (o, t + pattern_prepercent_len,
    217                                           len - (pattern_prepercent_len
    218                                                 + pattern_postpercent_len));
    219               /* Output the part of the replacement after the %.  */
    220               o = variable_buffer_output (o, replace_percent,
    221                                           replace_postpercent_len);
    222             }
    223         }
     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        }
    224226
    225227      /* Output a space, but not if the replacement is "".  */
    226228      if (fail || replace_prepercent_len > 0
    227           || (replace_percent != 0 && len + replace_postpercent_len > 0))
    228         {
    229           o = variable_buffer_output (o, " ", 1);
    230           doneany = 1;
    231         }
     229          || (replace_percent != 0 && len + replace_postpercent_len > 0))
     230        {
     231          o = variable_buffer_output (o, " ", 1);
     232          doneany = 1;
     233        }
    232234    }
    233235  if (doneany)
     
    271273lookup_function (const char *s)
    272274{
     275  struct function_table_entry function_table_entry_key;
    273276  const char *e = s;
    274277
    275   while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
     278  while (STOP_SET (*e, MAP_USERFUNC))
    276279    e++;
    277   if (*e == '\0' || isblank ((unsigned char) *e))
    278     {
    279       struct function_table_entry function_table_entry_key;
    280       function_table_entry_key.name = s;
    281       function_table_entry_key.len = e - s;
    282 
    283       return hash_find_item (&function_table, &function_table_entry_key);
    284     }
    285   return 0;
     280
     281  if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
     282    return NULL;
     283
     284  function_table_entry_key.name = s;
     285  function_table_entry_key.len = e - s;
     286
     287  return hash_find_item (&function_table, &function_table_entry_key);
    286288}
    287289
     
    302304      percent = find_percent (new_chars);
    303305      if (percent == 0)
    304         return streq (new_chars, str);
     306        return streq (new_chars, str);
    305307      pattern = new_chars;
    306308    }
     
    337339    else if (*ptr == endparen)
    338340      {
    339         --count;
    340         if (count < 0)
    341           return NULL;
     341        --count;
     342        if (count < 0)
     343          return NULL;
    342344      }
    343345
     
    362364  unsigned int idx;
    363365
    364   chain = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
    365                           /* We do not want parse_file_seq to strip `./'s.
     366  chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
     367                          /* We do not want parse_file_seq to strip './'s.
    366368                             That would break examples like:
    367369                             $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)).  */
     
    436438      tp = find_next_token (&list1_iterator, &len1);
    437439      if (tp != 0)
    438         o = variable_buffer_output (o, tp, len1);
     440        o = variable_buffer_output (o, tp, len1);
    439441
    440442      pp = find_next_token (&list2_iterator, &len2);
    441443      if (pp != 0)
    442         o = variable_buffer_output (o, pp, len2);
     444        o = variable_buffer_output (o, pp, len2);
    443445
    444446      if (tp != 0 || pp != 0)
    445         {
    446           o = variable_buffer_output (o, " ", 1);
    447           doneany = 1;
    448         }
     447        {
     448          o = variable_buffer_output (o, " ", 1);
     449          doneany = 1;
     450        }
    449451    }
    450452  while (tp != 0 || pp != 0);
     
    469471      default:
    470472      case o_invalid:
    471         abort ();
    472         break;
     473        abort ();
     474        break;
    473475      case o_default:
    474         o = variable_buffer_output (o, "default", 7);
    475         break;
     476        o = variable_buffer_output (o, "default", 7);
     477        break;
    476478      case o_env:
    477         o = variable_buffer_output (o, "environment", 11);
    478         break;
     479        o = variable_buffer_output (o, "environment", 11);
     480        break;
    479481      case o_file:
    480         o = variable_buffer_output (o, "file", 4);
    481         break;
     482        o = variable_buffer_output (o, "file", 4);
     483        break;
    482484      case o_env_override:
    483         o = variable_buffer_output (o, "environment override", 20);
    484         break;
     485        o = variable_buffer_output (o, "environment override", 20);
     486        break;
    485487      case o_command:
    486         o = variable_buffer_output (o, "command line", 12);
    487         break;
     488        o = variable_buffer_output (o, "command line", 12);
     489        break;
    488490      case o_override:
    489         o = variable_buffer_output (o, "override", 8);
    490         break;
     491        o = variable_buffer_output (o, "override", 8);
     492        break;
    491493      case o_automatic:
    492         o = variable_buffer_output (o, "automatic", 9);
    493         break;
     494        o = variable_buffer_output (o, "automatic", 9);
     495        break;
    494496      }
    495497
     
    513515}
    514516
    515 #ifdef VMS
    516 # define IS_PATHSEP(c) ((c) == ']')
    517 #else
    518 # ifdef HAVE_DOS_PATHS
    519 #  define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
    520 # else
    521 #  define IS_PATHSEP(c) ((c) == '/')
    522 # endif
    523 #endif
    524 
    525517
    526518static char *
     
    533525  unsigned int len=0;
    534526
    535   int is_suffix = streq (funcname, "suffix");
     527  int is_suffix = funcname[0] == 's';
    536528  int is_notdir = !is_suffix;
     529  int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
     530#ifdef VMS
     531  /* For VMS list_iterator points to a comma separated list. To use the common
     532     [find_]next_token, create a local copy and replace the commas with
     533     spaces. Obviously, there is a problem if there is a ',' in the VMS filename
     534     (can only happen on ODS5), the same problem as with spaces in filenames,
     535     which seems to be present in make on all platforms. */
     536  char *vms_list_iterator = alloca(strlen(list_iterator) + 1);
     537  int i;
     538  for (i = 0; list_iterator[i]; i++)
     539    if (list_iterator[i] == ',')
     540      vms_list_iterator[i] = ' ';
     541    else
     542      vms_list_iterator[i] = list_iterator[i];
     543  vms_list_iterator[i] = list_iterator[i];
     544  while ((p2 = find_next_token((const char**) &vms_list_iterator, &len)) != 0)
     545#else
    537546  while ((p2 = find_next_token (&list_iterator, &len)) != 0)
    538     {
    539       const char *p = p2 + len;
    540 
    541 
    542       while (p >= p2 && (!is_suffix || *p != '.'))
    543         {
    544           if (IS_PATHSEP (*p))
    545             break;
    546           --p;
    547         }
     547#endif
     548    {
     549      const char *p = p2 + len - 1;
     550
     551      while (p >= p2 && ! STOP_SET (*p, stop))
     552        --p;
    548553
    549554      if (p >= p2)
    550         {
    551           if (is_notdir)
    552             ++p;
    553           else if (*p != '.')
    554             continue;
    555           o = variable_buffer_output (o, p, len - (p - p2));
    556         }
     555        {
     556          if (is_notdir)
     557            ++p;
     558          else if (*p != '.')
     559            continue;
     560          o = variable_buffer_output (o, p, len - (p - p2));
     561        }
    557562#ifdef HAVE_DOS_PATHS
    558563      /* Handle the case of "d:foo/bar".  */
    559       else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
    560         {
    561           p = p2 + 2;
    562           o = variable_buffer_output (o, p, len - (p - p2));
    563         }
     564      else if (is_notdir && p2[0] && p2[1] == ':')
     565        {
     566          p = p2 + 2;
     567          o = variable_buffer_output (o, p, len - (p - p2));
     568        }
    564569#endif
    565570      else if (is_notdir)
    566         o = variable_buffer_output (o, p2, len);
     571        o = variable_buffer_output (o, p2, len);
    567572
    568573      if (is_notdir || p >= p2)
    569         {
    570           o = variable_buffer_output (o, " ", 1);
    571           doneany = 1;
    572         }
     574        {
     575#ifdef VMS
     576          if (vms_comma_separator)
     577            o = variable_buffer_output (o, ",", 1);
     578          else
     579#endif
     580          o = variable_buffer_output (o, " ", 1);
     581
     582          doneany = 1;
     583        }
    573584    }
    574585
     
    587598  const char *p3 = argv[0];
    588599  const char *p2;
    589   int doneany=0;
    590   unsigned int len=0;
    591 
    592   int is_basename= streq (funcname, "basename");
    593   int is_dir= !is_basename;
    594 
     600  int doneany = 0;
     601  unsigned int len = 0;
     602
     603  int is_basename = funcname[0] == 'b';
     604  int is_dir = !is_basename;
     605  int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
     606#ifdef VMS
     607  /* As in func_notdir_suffix ... */
     608  char *vms_p3 = alloca (strlen(p3) + 1);
     609  int i;
     610  for (i = 0; p3[i]; i++)
     611    if (p3[i] == ',')
     612      vms_p3[i] = ' ';
     613    else
     614      vms_p3[i] = p3[i];
     615  vms_p3[i] = p3[i];
     616  while ((p2 = find_next_token((const char**) &vms_p3, &len)) != 0)
     617#else
    595618  while ((p2 = find_next_token (&p3, &len)) != 0)
    596     {
    597       const char *p = p2 + len;
    598       while (p >= p2 && (!is_basename  || *p != '.'))
    599         {
    600           if (IS_PATHSEP (*p))
    601             break;
    602           --p;
    603         }
     619#endif
     620    {
     621      const char *p = p2 + len - 1;
     622      while (p >= p2 && ! STOP_SET (*p, stop))
     623        --p;
    604624
    605625      if (p >= p2 && (is_dir))
     
    614634      else if (is_dir)
    615635#ifdef VMS
    616         o = variable_buffer_output (o, "[]", 2);
     636        {
     637          extern int vms_report_unix_paths;
     638          if (vms_report_unix_paths)
     639            o = variable_buffer_output (o, "./", 2);
     640          else
     641            o = variable_buffer_output (o, "[]", 2);
     642        }
    617643#else
    618644#ifndef _AMIGA
     
    626652        o = variable_buffer_output (o, p2, len);
    627653
    628       o = variable_buffer_output (o, " ", 1);
     654#ifdef VMS
     655      if (vms_comma_separator)
     656        o = variable_buffer_output (o, ",", 1);
     657      else
     658#endif
     659        o = variable_buffer_output (o, " ", 1);
     660
    629661      doneany = 1;
    630662    }
     
    642674  int fixlen = strlen (argv[0]);
    643675  const char *list_iterator = argv[1];
    644   int is_addprefix = streq (funcname, "addprefix");
     676  int is_addprefix = funcname[3] == 'p';
    645677  int is_addsuffix = !is_addprefix;
    646678
     
    652684    {
    653685      if (is_addprefix)
    654         o = variable_buffer_output (o, argv[0], fixlen);
     686        o = variable_buffer_output (o, argv[0], fixlen);
    655687      o = variable_buffer_output (o, p, len);
    656688      if (is_addsuffix)
    657         o = variable_buffer_output (o, argv[0], fixlen);
     689        o = variable_buffer_output (o, argv[0], fixlen);
    658690      o = variable_buffer_output (o, " ", 1);
    659691      doneany = 1;
     
    671703{
    672704  o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
    673                     strlen (argv[1]), 0);
     705                    strlen (argv[1]), 0);
    674706
    675707  return o;
     
    714746  char buf[20];
    715747
    716   while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
     748  while (find_next_token (&word_iterator, NULL) != 0)
    717749    ++i;
    718750
     
    731763strip_whitespace (const char **begpp, const char **endpp)
    732764{
    733   while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
     765  while (*begpp <= *endpp && ISSPACE (**begpp))
    734766    (*begpp) ++;
    735   while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
     767  while (*endpp >= *begpp && ISSPACE (**endpp))
    736768    (*endpp) --;
    737769  return (char *)*begpp;
     
    746778
    747779  for (; s <= end; ++s)
    748     if (!ISDIGIT (*s))  /* ISDIGIT only evals its arg once: see make.h.  */
     780    if (!ISDIGIT (*s))  /* ISDIGIT only evals its arg once: see makeint.h.  */
    749781      break;
    750782
    751783  if (s <= end || end - beg < 0)
    752     fatal (*expanding_var, "%s: '%s'", msg, beg);
     784    OSS (fatal, *expanding_var, "%s: '%s'", msg, beg);
    753785}
    754786
     
    763795
    764796  /* Check the first argument.  */
    765   check_numeric (argv[0], _("non-numeric first argument to `word' function"));
     797  check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
    766798  i = atoi (argv[0]);
    767799
    768800  if (i == 0)
    769     fatal (*expanding_var,
    770            _("first argument to `word' function must be greater than 0"));
     801    O (fatal, *expanding_var,
     802       _("first argument to 'word' function must be greater than 0"));
    771803
    772804  end_p = argv[1];
     
    788820  /* Check the arguments.  */
    789821  check_numeric (argv[0],
    790                  _("non-numeric first argument to `wordlist' function"));
     822                 _("non-numeric first argument to 'wordlist' function"));
    791823  check_numeric (argv[1],
    792                  _("non-numeric second argument to `wordlist' function"));
     824                 _("non-numeric second argument to 'wordlist' function"));
    793825
    794826  start = atoi (argv[0]);
    795827  if (start < 1)
    796     fatal (*expanding_var,
    797            "invalid first argument to `wordlist' function: `%d'", start);
     828    ON (fatal, *expanding_var,
     829        "invalid first argument to 'wordlist' function: '%d'", start);
    798830
    799831  count = atoi (argv[1]) - start + 1;
     
    846878  struct variable *var;
    847879
     880  /* Clean up the variable name by removing whitespace.  */
     881  char *vp = next_token (varname);
     882  end_of_token (vp)[0] = '\0';
     883
    848884  push_new_variable_scope ();
    849   var = define_variable (varname, strlen (varname), "", o_automatic, 0);
     885  var = define_variable (vp, strlen (vp), "", o_automatic, 0);
    850886
    851887  /* loop through LIST,  put the value in VAR and expand BODY */
     
    904940    return result;
    905941  return_STRING_COMPARE (((struct a_word const *) x)->str,
    906                         ((struct a_word const *) y)->str);
     942                        ((struct a_word const *) y)->str);
    907943}
    908944
     
    913949  char *percent;
    914950  int length;
    915   int save_c;
    916951};
    917952
     
    927962
    928963  struct hash_table a_word_table;
    929   int is_filter = streq (funcname, "filter");
     964  int is_filter = funcname[CSTRLEN ("filter")] == '\0';
    930965  const char *pat_iterator = argv[0];
    931966  const char *word_iterator = argv[1];
     
    936971  unsigned int len;
    937972
    938   /* Chop ARGV[0] up into patterns to match against the words.  */
     973  /* Chop ARGV[0] up into patterns to match against the words.
     974     We don't need to preserve it because our caller frees all the
     975     argument memory anyway.  */
    939976
    940977  pattail = &pathead;
     
    947984
    948985      if (*pat_iterator != '\0')
    949         ++pat_iterator;
     986        ++pat_iterator;
    950987
    951988      pat->str = p;
    952       pat->length = len;
    953       pat->save_c = p[len];
    954989      p[len] = '\0';
    955990      pat->percent = find_percent (p);
    956991      if (pat->percent == 0)
    957         literals++;
     992        literals++;
     993
     994      /* find_percent() might shorten the string so LEN is wrong.  */
     995      pat->length = strlen (pat->str);
    958996    }
    959997  *pattail = 0;
     
    9701008
    9711009      if (*word_iterator != '\0')
    972         ++word_iterator;
     1010        ++word_iterator;
    9731011
    9741012      p[len] = '\0';
     
    9881026                 a_word_hash_cmp);
    9891027      for (wp = wordhead; wp != 0; wp = wp->next)
    990         {
    991           struct a_word *owp = hash_insert (&a_word_table, wp);
    992           if (owp)
    993             wp->chain = owp;
    994         }
     1028        {
     1029          struct a_word *owp = hash_insert (&a_word_table, wp);
     1030          if (owp)
     1031            wp->chain = owp;
     1032        }
    9951033    }
    9961034
     
    10011039      /* Run each pattern through the words, killing words.  */
    10021040      for (pp = pathead; pp != 0; pp = pp->next)
    1003         {
    1004           if (pp->percent)
    1005             for (wp = wordhead; wp != 0; wp = wp->next)
    1006               wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
    1007           else if (hashing)
    1008             {
    1009               struct a_word a_word_key;
    1010               a_word_key.str = pp->str;
    1011               a_word_key.length = pp->length;
    1012               wp = hash_find_item (&a_word_table, &a_word_key);
    1013               while (wp)
    1014                 {
    1015                   wp->matched |= 1;
    1016                   wp = wp->chain;
    1017                 }
    1018             }
    1019           else
    1020             for (wp = wordhead; wp != 0; wp = wp->next)
    1021               wp->matched |= (wp->length == pp->length
    1022                               && strneq (pp->str, wp->str, wp->length));
    1023         }
     1041        {
     1042          if (pp->percent)
     1043            for (wp = wordhead; wp != 0; wp = wp->next)
     1044              wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
     1045          else if (hashing)
     1046            {
     1047              struct a_word a_word_key;
     1048              a_word_key.str = pp->str;
     1049              a_word_key.length = pp->length;
     1050              wp = hash_find_item (&a_word_table, &a_word_key);
     1051              while (wp)
     1052                {
     1053                  wp->matched |= 1;
     1054                  wp = wp->chain;
     1055                }
     1056            }
     1057          else
     1058            for (wp = wordhead; wp != 0; wp = wp->next)
     1059              wp->matched |= (wp->length == pp->length
     1060                              && strneq (pp->str, wp->str, wp->length));
     1061        }
    10241062
    10251063      /* Output the words that matched (or didn't, for filter-out).  */
    10261064      for (wp = wordhead; wp != 0; wp = wp->next)
    1027         if (is_filter ? wp->matched : !wp->matched)
    1028           {
    1029             o = variable_buffer_output (o, wp->str, strlen (wp->str));
    1030             o = variable_buffer_output (o, " ", 1);
    1031             doneany = 1;
    1032           }
     1065        if (is_filter ? wp->matched : !wp->matched)
     1066          {
     1067            o = variable_buffer_output (o, wp->str, strlen (wp->str));
     1068            o = variable_buffer_output (o, " ", 1);
     1069            doneany = 1;
     1070          }
    10331071
    10341072      if (doneany)
    1035         /* Kill the last space.  */
    1036         --o;
    1037     }
    1038 
    1039   for (pp = pathead; pp != 0; pp = pp->next)
    1040     pp->str[pp->length] = pp->save_c;
     1073        /* Kill the last space.  */
     1074        --o;
     1075    }
    10411076
    10421077  if (hashing)
     
    10581093      const char *word_start;
    10591094
    1060       while (isspace ((unsigned char)*p))
    1061         ++p;
     1095      NEXT_TOKEN (p);
    10621096      word_start = p;
    1063       for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
    1064         {}
     1097      for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
     1098        {}
    10651099      if (!i)
    1066         break;
     1100        break;
    10671101      o = variable_buffer_output (o, word_start, i);
    10681102      o = variable_buffer_output (o, " ", 1);
     
    11041138  strcpy (p, *argvp);
    11051139
    1106   switch (*funcname) {
     1140  switch (*funcname)
     1141    {
    11071142    case 'e':
    1108       fatal (reading_file, "%s", msg);
     1143      OS (fatal, reading_file, "%s", msg);
    11091144
    11101145    case 'w':
    1111       error (reading_file, "%s", msg);
     1146      OS (error, reading_file, "%s", msg);
    11121147      break;
    11131148
    11141149    case 'i':
    1115       printf ("%s\n", msg);
    1116       fflush(stdout);
     1150      outputs (0, msg);
     1151      outputs (0, "\n");
    11171152      break;
    11181153
    11191154    default:
    1120       fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
    1121   }
     1155      OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
     1156    }
    11221157
    11231158  /* The warning function expands to the empty string.  */
     
    11371172  char *p;
    11381173  unsigned int len;
    1139   int i;
    11401174
    11411175  /* Find the maximum number of words we'll have.  */
    11421176  t = argv[0];
    1143   wordi = 1;
    1144   while (*t != '\0')
    1145     {
    1146       char c = *(t++);
    1147 
    1148       if (! isspace ((unsigned char)c))
    1149         continue;
    1150 
     1177  wordi = 0;
     1178  while ((p = find_next_token (&t, NULL)) != 0)
     1179    {
     1180      ++t;
    11511181      ++wordi;
    1152 
    1153       while (isspace ((unsigned char)*t))
    1154         ++t;
    1155     }
    1156 
    1157   words = xmalloc (wordi * sizeof (char *));
     1182    }
     1183
     1184  words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
    11581185
    11591186  /* Now assign pointers to each string in the array.  */
     
    11691196  if (wordi)
    11701197    {
     1198      int i;
     1199
    11711200      /* Now sort the list of words.  */
    11721201      qsort (words, wordi, sizeof (char *), alpha_compare);
     
    13121341{
    13131342  char *expansion;
    1314   int result;
    13151343
    13161344  while (1)
     
    13181346      const char *begp = *argv;
    13191347      const char *endp = begp + strlen (*argv) - 1;
     1348      int result;
    13201349
    13211350      /* An empty condition is always false.  */
     
    13791408  install_variable_buffer (&buf, &len);
    13801409
    1381   eval_buffer (argv[0]);
     1410  eval_buffer (argv[0], NULL);
    13821411
    13831412  restore_variable_buffer (buf, len);
     
    13951424  /* Copy its value into the output buffer without expanding it.  */
    13961425  if (v)
    1397     o = variable_buffer_output (o, v->value, strlen(v->value));
     1426    o = variable_buffer_output (o, v->value, strlen (v->value));
    13981427
    13991428  return o;
     
    14011430
    14021431/*
    1403   \r  is replaced on UNIX as well. Is this desirable?
     1432  \r is replaced on UNIX as well. Is this desirable?
    14041433 */
    14051434static void
    1406 fold_newlines (char *buffer, unsigned int *length)
     1435fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
    14071436{
    14081437  char *dst = buffer;
    14091438  char *src = buffer;
    1410   char *last_nonnl = buffer -1;
     1439  char *last_nonnl = buffer - 1;
    14111440  src[*length] = 0;
    14121441  for (; *src != '\0'; ++src)
    14131442    {
    14141443      if (src[0] == '\r' && src[1] == '\n')
    1415         continue;
     1444        continue;
    14161445      if (*src == '\n')
    1417         {
    1418           *dst++ = ' ';
    1419         }
     1446        {
     1447          *dst++ = ' ';
     1448        }
    14201449      else
    1421         {
    1422           last_nonnl = dst;
    1423           *dst++ = *src;
    1424         }
    1425     }
     1450        {
     1451          last_nonnl = dst;
     1452          *dst++ = *src;
     1453        }
     1454    }
     1455
     1456  if (!trim_newlines && (last_nonnl < (dst - 2)))
     1457    last_nonnl = dst - 2;
     1458
    14261459  *(++last_nonnl) = '\0';
    14271460  *length = last_nonnl - buffer;
    14281461}
    14291462
    1430 
    1431 
    1432 int shell_function_pid = 0, shell_function_completed;
    1433 
     1463pid_t shell_function_pid = 0;
     1464static int shell_function_completed;
     1465
     1466void
     1467shell_completed (int exit_code, int exit_sig)
     1468{
     1469  char buf[256];
     1470
     1471  shell_function_pid = 0;
     1472  if (exit_sig == 0 && exit_code == 127)
     1473    shell_function_completed = -1;
     1474  else
     1475    shell_function_completed = 1;
     1476
     1477  sprintf (buf, "%d", exit_code);
     1478  define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
     1479}
    14341480
    14351481#ifdef WINDOWS32
     
    14411487
    14421488
    1443 void
    1444 windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
     1489int
     1490windows32_openpipe (int *pipedes, int errfd, pid_t *pid_p, char **command_argv, char **envp)
    14451491{
    14461492  SECURITY_ATTRIBUTES saAttr;
    1447   HANDLE hIn;
    1448   HANDLE hErr;
     1493  HANDLE hIn = INVALID_HANDLE_VALUE;
     1494  HANDLE hErr = INVALID_HANDLE_VALUE;
    14491495  HANDLE hChildOutRd;
    14501496  HANDLE hChildOutWr;
    1451   HANDLE hProcess;
    1452 
     1497  HANDLE hProcess, tmpIn, tmpErr;
     1498  DWORD e;
     1499
     1500  /* Set status for return.  */
     1501  pipedes[0] = pipedes[1] = -1;
     1502  *pid_p = (pid_t)-1;
    14531503
    14541504  saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
     
    14561506  saAttr.lpSecurityDescriptor = NULL;
    14571507
    1458   if (DuplicateHandle (GetCurrentProcess(),
    1459                       GetStdHandle(STD_INPUT_HANDLE),
    1460                       GetCurrentProcess(),
    1461                       &hIn,
    1462                       0,
    1463                       TRUE,
    1464                       DUPLICATE_SAME_ACCESS) == FALSE) {
    1465     fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
    1466            GetLastError());
    1467 
    1468   }
    1469   if (DuplicateHandle(GetCurrentProcess(),
    1470                       GetStdHandle(STD_ERROR_HANDLE),
    1471                       GetCurrentProcess(),
    1472                       &hErr,
    1473                       0,
    1474                       TRUE,
    1475                       DUPLICATE_SAME_ACCESS) == FALSE) {
    1476     fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
    1477            GetLastError());
    1478   }
    1479 
    1480   if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
    1481     fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
    1482 
    1483   hProcess = process_init_fd(hIn, hChildOutWr, hErr);
     1508  /* Standard handles returned by GetStdHandle can be NULL or
     1509     INVALID_HANDLE_VALUE if the parent process closed them.  If that
     1510     happens, we open the null device and pass its handle to
     1511     process_begin below as the corresponding handle to inherit.  */
     1512  tmpIn = GetStdHandle (STD_INPUT_HANDLE);
     1513  if (DuplicateHandle (GetCurrentProcess (), tmpIn,
     1514                       GetCurrentProcess (), &hIn,
     1515                       0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     1516    {
     1517      e = GetLastError ();
     1518      if (e == ERROR_INVALID_HANDLE)
     1519        {
     1520          tmpIn = CreateFile ("NUL", GENERIC_READ,
     1521                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     1522                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1523          if (tmpIn != INVALID_HANDLE_VALUE
     1524              && DuplicateHandle (GetCurrentProcess (), tmpIn,
     1525                                  GetCurrentProcess (), &hIn,
     1526                                  0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     1527            CloseHandle (tmpIn);
     1528        }
     1529      if (hIn == INVALID_HANDLE_VALUE)
     1530        {
     1531          ON (error, NILF,
     1532              _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
     1533          return -1;
     1534        }
     1535    }
     1536  tmpErr = (HANDLE)_get_osfhandle (errfd);
     1537  if (DuplicateHandle (GetCurrentProcess (), tmpErr,
     1538                       GetCurrentProcess (), &hErr,
     1539                       0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     1540    {
     1541      e = GetLastError ();
     1542      if (e == ERROR_INVALID_HANDLE)
     1543        {
     1544          tmpErr = CreateFile ("NUL", GENERIC_WRITE,
     1545                               FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     1546                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1547          if (tmpErr != INVALID_HANDLE_VALUE
     1548              && DuplicateHandle (GetCurrentProcess (), tmpErr,
     1549                                  GetCurrentProcess (), &hErr,
     1550                                  0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     1551            CloseHandle (tmpErr);
     1552        }
     1553      if (hErr == INVALID_HANDLE_VALUE)
     1554        {
     1555          ON (error, NILF,
     1556              _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
     1557          return -1;
     1558        }
     1559    }
     1560
     1561  if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
     1562    {
     1563      ON (error, NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
     1564      return -1;
     1565    }
     1566
     1567  hProcess = process_init_fd (hIn, hChildOutWr, hErr);
    14841568
    14851569  if (!hProcess)
    1486     fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
     1570    {
     1571      O (error, NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
     1572      return -1;
     1573    }
    14871574
    14881575  /* make sure that CreateProcess() has Path it needs */
    1489   sync_Path_environment();
    1490   /* `sync_Path_environment' may realloc `environ', so take note of
     1576  sync_Path_environment ();
     1577  /* 'sync_Path_environment' may realloc 'environ', so take note of
    14911578     the new value.  */
    14921579  envp = environ;
    14931580
    1494   if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
    1495     /* register process for wait */
    1496     process_register(hProcess);
    1497 
    1498     /* set the pid for returning to caller */
    1499     *pid_p = (pid_t) hProcess;
    1500 
    1501   /* set up to read data from child */
    1502   pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
    1503 
    1504   /* this will be closed almost right away */
    1505   pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
    1506   } else {
    1507     /* reap/cleanup the failed process */
    1508         process_cleanup(hProcess);
    1509 
    1510     /* close handles which were duplicated, they weren't used */
    1511         CloseHandle(hIn);
    1512         CloseHandle(hErr);
    1513 
    1514         /* close pipe handles, they won't be used */
    1515         CloseHandle(hChildOutRd);
    1516         CloseHandle(hChildOutWr);
    1517 
    1518     /* set status for return */
    1519     pipedes[0] = pipedes[1] = -1;
    1520     *pid_p = (pid_t)-1;
    1521   }
     1581  if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
     1582    {
     1583      /* register process for wait */
     1584      process_register (hProcess);
     1585
     1586      /* set the pid for returning to caller */
     1587      *pid_p = (pid_t) hProcess;
     1588
     1589      /* set up to read data from child */
     1590      pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
     1591
     1592      /* this will be closed almost right away */
     1593      pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
     1594      return 0;
     1595    }
     1596  else
     1597    {
     1598      /* reap/cleanup the failed process */
     1599      process_cleanup (hProcess);
     1600
     1601      /* close handles which were duplicated, they weren't used */
     1602      if (hIn != INVALID_HANDLE_VALUE)
     1603        CloseHandle (hIn);
     1604      if (hErr != INVALID_HANDLE_VALUE)
     1605        CloseHandle (hErr);
     1606
     1607      /* close pipe handles, they won't be used */
     1608      CloseHandle (hChildOutRd);
     1609      CloseHandle (hChildOutWr);
     1610
     1611      return -1;
     1612    }
    15221613}
    15231614#endif
     
    15291620{
    15301621  FILE *fpipe=0;
    1531   /* MSDOS can't fork, but it has `popen'.  */
     1622  /* MSDOS can't fork, but it has 'popen'.  */
    15321623  struct variable *sh = lookup_variable ("SHELL", 5);
    15331624  int e;
     
    15351626
    15361627  /* Make sure not to bother processing an empty line.  */
    1537   while (isblank ((unsigned char)*text))
    1538     ++text;
     1628  NEXT_TOKEN (text);
    15391629  if (*text == '\0')
    15401630    return 0;
     
    15441634      char buf[PATH_MAX + 7];
    15451635      /* This makes sure $SHELL value is used by $(shell), even
    1546         though the target environment is not passed to it.  */
     1636        though the target environment is not passed to it.  */
    15471637      sprintf (buf, "SHELL=%s", sh->value);
    15481638      putenv (buf);
     
    15631653      *pidp = -1;
    15641654      if (dos_status)
    1565         errno = EINTR;
     1655        errno = EINTR;
    15661656      else if (errno == 0)
    1567         errno = ENOMEM;
    1568       shell_function_completed = -1;
     1657        errno = ENOMEM;
     1658      if (fpipe)
     1659        pclose (fpipe);
     1660      shell_completed (127, 0);
    15691661    }
    15701662  else
     
    15731665      *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
    15741666      errno = e;
    1575       shell_function_completed = 1;
    15761667    }
    15771668  return fpipe;
     
    15861677
    15871678/* VMS can't do $(shell ...)  */
     1679
     1680char *
     1681func_shell_base (char *o, char **argv, int trim_newlines)
     1682{
     1683  fprintf (stderr, "This platform does not support shell\n");
     1684  die (MAKE_TROUBLE);
     1685  return NULL;
     1686}
     1687
    15881688#define func_shell 0
    15891689
    15901690#else
    15911691#ifndef _AMIGA
    1592 static char *
    1593 func_shell (char *o, char **argv, const char *funcname UNUSED)
     1692char *
     1693func_shell_base (char *o, char **argv, int trim_newlines)
    15941694{
    15951695  char *batch_filename = NULL;
    1596 
     1696  int errfd;
    15971697#ifdef __MSDOS__
    15981698  FILE *fpipe;
     
    16051705
    16061706#ifndef __MSDOS__
     1707#ifdef WINDOWS32
     1708  /* Reset just_print_flag.  This is needed on Windows when batch files
     1709     are used to run the commands, because we normally refrain from
     1710     creating batch files under -n.  */
     1711  int j_p_f = just_print_flag;
     1712  just_print_flag = 0;
     1713#endif
     1714
    16071715  /* Construct the argument list.  */
    16081716  command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
    16091717                                         &batch_filename);
    16101718  if (command_argv == 0)
    1611     return o;
     1719    {
     1720#ifdef WINDOWS32
     1721      just_print_flag = j_p_f;
    16121722#endif
    1613 
    1614   /* Using a target environment for `shell' loses in cases like:
    1615      export var = $(shell echo foobie)
    1616      because target_environment hits a loop trying to expand $(var)
    1617      to put it in the environment.  This is even more confusing when
    1618      var was not explicitly exported, but just appeared in the
    1619      calling environment.
     1723      return o;
     1724    }
     1725#endif /* !__MSDOS__ */
     1726
     1727  /* Using a target environment for 'shell' loses in cases like:
     1728       export var = $(shell echo foobie)
     1729       bad := $(var)
     1730     because target_environment hits a loop trying to expand $(var) to put it
     1731     in the environment.  This is even more confusing when 'var' was not
     1732     explicitly exported, but just appeared in the calling environment.
    16201733
    16211734     See Savannah bug #10593.
    16221735
    1623   envp = target_environment (NILF);
     1736  envp = target_environment (NULL);
    16241737  */
    16251738
     
    16301743    {
    16311744      char *p = alloca (strlen (reading_file->filenm)+11+4);
    1632       sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
     1745      sprintf (p, "%s:%lu: ", reading_file->filenm,
     1746               reading_file->lineno + reading_file->offset);
    16331747      error_prefix = p;
    16341748    }
    16351749  else
    16361750    error_prefix = "";
     1751
     1752  /* Set up the output in case the shell writes something.  */
     1753  output_start ();
     1754
     1755  errfd = (output_context && output_context->err >= 0
     1756           ? output_context->err : FD_STDERR);
    16371757
    16381758#if defined(__MSDOS__)
     
    16431763      return o;
    16441764    }
     1765
    16451766#elif defined(WINDOWS32)
    1646   windows32_openpipe (pipedes, &pid, command_argv, envp);
     1767  windows32_openpipe (pipedes, errfd, &pid, command_argv, envp);
     1768  /* Restore the value of just_print_flag.  */
     1769  just_print_flag = j_p_f;
     1770
    16471771  if (pipedes[0] < 0)
    16481772    {
    1649       /* open of the pipe failed, mark as failed execution */
    1650       shell_function_completed = -1;
    1651 
     1773      /* Open of the pipe failed, mark as failed execution. */
     1774      shell_completed (127, 0);
     1775      perror_with_name (error_prefix, "pipe");
    16521776      return o;
    16531777    }
    1654   else
     1778
    16551779#else
    16561780  if (pipe (pipedes) < 0)
     
    16601784    }
    16611785
    1662 # ifdef __EMX__
    1663   /* close some handles that are unnecessary for the child process */
     1786  /* Close handles that are unnecessary for the child process.  */
    16641787  CLOSE_ON_EXEC(pipedes[1]);
    16651788  CLOSE_ON_EXEC(pipedes[0]);
    1666   /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
    1667   pid = child_execute_job (0, pipedes[1], command_argv, envp);
     1789
     1790  {
     1791    struct output out;
     1792    out.syncout = 1;
     1793    out.out = pipedes[1];
     1794    out.err = errfd;
     1795
     1796    pid = child_execute_job (&out, 1, command_argv, envp);
     1797  }
     1798
    16681799  if (pid < 0)
    1669     perror_with_name (error_prefix, "spawn");
    1670 # else /* ! __EMX__ */
    1671   pid = vfork ();
    1672   if (pid < 0)
    1673     perror_with_name (error_prefix, "fork");
    1674   else if (pid == 0)
    1675     child_execute_job (0, pipedes[1], command_argv, envp);
    1676   else
    1677 # endif
     1800    {
     1801      perror_with_name (error_prefix, "fork");
     1802      return o;
     1803    }
    16781804#endif
    1679     {
    1680       /* We are the parent.  */
    1681       char *buffer;
    1682       unsigned int maxlen, i;
    1683       int cc;
    1684 
    1685       /* Record the PID for reap_children.  */
    1686       shell_function_pid = pid;
     1805
     1806  {
     1807    char *buffer;
     1808    unsigned int maxlen, i;
     1809    int cc;
     1810
     1811    /* Record the PID for reap_children.  */
     1812    shell_function_pid = pid;
    16871813#ifndef  __MSDOS__
    1688       shell_function_completed = 0;
    1689 
    1690       /* Free the storage only the child needed.  */
    1691       free (command_argv[0]);
    1692       free (command_argv);
    1693 
    1694       /* Close the write side of the pipe.  We test for -1, since
    1695         pipedes[1] is -1 on MS-Windows, and some versions of MS
    1696          libraries barf when `close' is called with -1.  */
    1697       if (pipedes[1] >= 0)
    1698         close (pipedes[1]);
     1814    shell_function_completed = 0;
     1815
     1816    /* Free the storage only the child needed.  */
     1817    free (command_argv[0]);
     1818    free (command_argv);
     1819
     1820    /* Close the write side of the pipe.  We test for -1, since
     1821      pipedes[1] is -1 on MS-Windows, and some versions of MS
     1822       libraries barf when 'close' is called with -1.  */
     1823    if (pipedes[1] >= 0)
     1824      close (pipedes[1]);
    16991825#endif
    17001826
    1701       /* Set up and read from the pipe.  */
    1702 
    1703       maxlen = 200;
    1704       buffer = xmalloc (maxlen + 1);
    1705 
    1706       /* Read from the pipe until it gets EOF.  */
    1707       for (i = 0; ; i += cc)
    1708         {
    1709           if (i == maxlen)
    1710             {
    1711               maxlen += 512;
    1712               buffer = xrealloc (buffer, maxlen + 1);
    1713             }
    1714 
    1715           EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
    1716           if (cc <= 0)
    1717             break;
    1718         }
    1719       buffer[i] = '\0';
    1720 
    1721       /* Close the read side of the pipe.  */
     1827    /* Set up and read from the pipe.  */
     1828
     1829    maxlen = 200;
     1830    buffer = xmalloc (maxlen + 1);
     1831
     1832    /* Read from the pipe until it gets EOF.  */
     1833    for (i = 0; ; i += cc)
     1834      {
     1835        if (i == maxlen)
     1836          {
     1837            maxlen += 512;
     1838            buffer = xrealloc (buffer, maxlen + 1);
     1839          }
     1840
     1841        EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
     1842        if (cc <= 0)
     1843          break;
     1844      }
     1845    buffer[i] = '\0';
     1846
     1847    /* Close the read side of the pipe.  */
    17221848#ifdef  __MSDOS__
    1723       if (fpipe)
    1724         (void) pclose (fpipe);
     1849    if (fpipe)
     1850      {
     1851        int st = pclose (fpipe);
     1852        shell_completed (st, 0);
     1853      }
    17251854#else
    1726       (void) close (pipedes[0]);
     1855    (void) close (pipedes[0]);
    17271856#endif
    17281857
    1729       /* Loop until child_handler or reap_children()  sets
    1730          shell_function_completed to the status of our child shell.  */
    1731       while (shell_function_completed == 0)
    1732         reap_children (1, 0);
    1733 
    1734       if (batch_filename) {
    1735         DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
    1736                        batch_filename));
    1737         remove (batch_filename);
    1738         free (batch_filename);
     1858    /* Loop until child_handler or reap_children()  sets
     1859       shell_function_completed to the status of our child shell.  */
     1860    while (shell_function_completed == 0)
     1861      reap_children (1, 0);
     1862
     1863    if (batch_filename)
     1864      {
     1865        DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
     1866                         batch_filename));
     1867        remove (batch_filename);
     1868        free (batch_filename);
    17391869      }
    1740       shell_function_pid = 0;
    1741 
    1742       /* The child_handler function will set shell_function_completed
    1743          to 1 when the child dies normally, or to -1 if it
    1744          dies with status 127, which is most likely an exec fail.  */
    1745 
    1746       if (shell_function_completed == -1)
    1747         {
    1748           /* This likely means that the execvp failed, so we should just
    1749              write the error message in the pipe from the child.  */
    1750           fputs (buffer, stderr);
    1751           fflush (stderr);
    1752         }
    1753       else
    1754         {
    1755           /* The child finished normally.  Replace all newlines in its output
    1756              with spaces, and put that in the variable output buffer.  */
    1757           fold_newlines (buffer, &i);
    1758           o = variable_buffer_output (o, buffer, i);
    1759         }
    1760 
    1761       free (buffer);
    1762     }
    1763 
    1764   return o;
    1765 }
    1766 
    1767 #else   /* _AMIGA */
     1870    shell_function_pid = 0;
     1871
     1872    /* shell_completed() will set shell_function_completed to 1 when the
     1873       child dies normally, or to -1 if it dies with status 127, which is
     1874      most likely an exec fail.  */
     1875
     1876    if (shell_function_completed == -1)
     1877      {
     1878        /* This likely means that the execvp failed, so we should just
     1879           write the error message in the pipe from the child.  */
     1880        fputs (buffer, stderr);
     1881        fflush (stderr);
     1882      }
     1883    else
     1884      {
     1885        /* The child finished normally.  Replace all newlines in its output
     1886           with spaces, and put that in the variable output buffer.  */
     1887        fold_newlines (buffer, &i, trim_newlines);
     1888        o = variable_buffer_output (o, buffer, i);
     1889      }
     1890
     1891    free (buffer);
     1892  }
     1893
     1894  return o;
     1895}
     1896
     1897#else   /* _AMIGA */
    17681898
    17691899/* Do the Amiga version of func_shell.  */
    17701900
    1771 static char *
    1772 func_shell (char *o, char **argv, const char *funcname)
     1901char *
     1902func_shell_base (char *o, char **argv, int trim_newlines)
    17731903{
    17741904  /* Amiga can't fork nor spawn, but I can start a program with
     
    18001930
    18011931  /* Note the mktemp() is a security hole, but this only runs on Amiga.
    1802      Ideally we would use main.c:open_tmpfile(), but this uses a special
     1932     Ideally we would use output_tmpfile(), but this uses a special
    18031933     Open(), not fopen(), and I'm not familiar enough with the code to mess
    18041934     with it.  */
     
    18351965    {
    18361966      if (i == maxlen)
    1837         {
    1838           maxlen += 512;
    1839           buffer = xrealloc (buffer, maxlen + 1);
    1840         }
     1967        {
     1968          maxlen += 512;
     1969          buffer = xrealloc (buffer, maxlen + 1);
     1970        }
    18411971
    18421972      cc = Read (child_stdout, &buffer[i], maxlen - i);
    18431973      if (cc > 0)
    1844         i += cc;
     1974        i += cc;
    18451975    } while (cc > 0);
    18461976
    18471977  Close (child_stdout);
    18481978
    1849   fold_newlines (buffer, &i);
     1979  fold_newlines (buffer, &i, trim_newlines);
    18501980  o = variable_buffer_output (o, buffer, i);
    18511981  free (buffer);
     
    18531983}
    18541984#endif  /* _AMIGA */
     1985
     1986static char *
     1987func_shell (char *o, char **argv, const char *funcname UNUSED)
     1988{
     1989  return func_shell_base (o, argv, 1);
     1990}
    18551991#endif  /* !VMS */
    18561992
     
    18581994
    18591995/*
    1860   equality. Return is string-boolean, ie, the empty string is false.
     1996  equality. Return is string-boolean, i.e., the empty string is false.
    18611997 */
    18621998static char *
    1863 func_eq (char *o, char **argv, char *funcname)
     1999func_eq (char *o, char **argv, char *funcname UNUSED)
    18642000{
    18652001  int result = ! strcmp (argv[0], argv[1]);
     
    18732009 */
    18742010static char *
    1875 func_not (char *o, char **argv, char *funcname)
     2011func_not (char *o, char **argv, char *funcname UNUSED)
    18762012{
    18772013  const char *s = argv[0];
    18782014  int result = 0;
    1879   while (isspace ((unsigned char)*s))
    1880     s++;
     2015  NEXT_TOKEN (s);
    18812016  result = ! (*s);
    18822017  o = variable_buffer_output (o,  result ? "1" : "", result);
     
    18882023
    18892024#ifdef HAVE_DOS_PATHS
    1890 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
    1891 #define ROOT_LEN 3
     2025# ifdef __CYGWIN__
     2026#  define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || STOP_SET (n[0], MAP_DIRSEP))
     2027# else
     2028#  define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
     2029# endif
     2030# define ROOT_LEN 3
    18922031#else
    18932032#define IS_ABSOLUTE(n) (n[0] == '/')
     
    18952034#endif
    18962035
    1897 /* Return the absolute name of file NAME which does not contain any `.',
    1898    `..' components nor any repeated path separators ('/').   */
     2036/* Return the absolute name of file NAME which does not contain any '.',
     2037   '..' components nor any repeated path separators ('/').   */
    18992038
    19002039static char *
     
    19142053      /* It is unlikely we would make it until here but just to make sure. */
    19152054      if (!starting_directory)
    1916         return NULL;
     2055        return NULL;
    19172056
    19182057      strcpy (apath, starting_directory);
    19192058
    19202059#ifdef HAVE_DOS_PATHS
    1921       if (IS_PATHSEP(name[0]))
    1922         {
    1923           if (IS_PATHSEP(name[1]))
    1924             {
    1925               /* A UNC.  Don't prepend a drive letter.  */
    1926               apath[0] = name[0];
    1927               apath[1] = name[1];
    1928               root_len = 2;
    1929             }
    1930           /* We have /foo, an absolute file name except for the drive
    1931              letter.  Assume the missing drive letter is the current
    1932              drive, which we can get if we remove from starting_directory
    1933              everything past the root directory.  */
    1934           apath[root_len] = '\0';
    1935         }
     2060      if (STOP_SET (name[0], MAP_DIRSEP))
     2061        {
     2062          if (STOP_SET (name[1], MAP_DIRSEP))
     2063            {
     2064              /* A UNC.  Don't prepend a drive letter.  */
     2065              apath[0] = name[0];
     2066              apath[1] = name[1];
     2067              root_len = 2;
     2068            }
     2069          /* We have /foo, an absolute file name except for the drive
     2070             letter.  Assume the missing drive letter is the current
     2071             drive, which we can get if we remove from starting_directory
     2072             everything past the root directory.  */
     2073          apath[root_len] = '\0';
     2074        }
    19362075#endif
    19372076
     
    19402079  else
    19412080    {
     2081#if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
     2082      if (STOP_SET (name[0], MAP_DIRSEP))
     2083        root_len = 1;
     2084#endif
    19422085      strncpy (apath, name, root_len);
    19432086      apath[root_len] = '\0';
     
    19462089      name += root_len;
    19472090#ifdef HAVE_DOS_PATHS
    1948       if (!IS_PATHSEP(apath[2]))
    1949         {
    1950           /* Convert d:foo into d:./foo and increase root_len.  */
    1951           apath[2] = '.';
    1952           apath[3] = '/';
    1953           dest++;
    1954           root_len++;
    1955           /* strncpy above copied one character too many.  */
    1956           name--;
    1957         }
     2091      if (! STOP_SET (apath[root_len - 1], MAP_DIRSEP))
     2092        {
     2093          /* Convert d:foo into d:./foo and increase root_len.  */
     2094          apath[2] = '.';
     2095          apath[3] = '/';
     2096          dest++;
     2097          root_len++;
     2098          /* strncpy above copied one character too many.  */
     2099          name--;
     2100        }
    19582101      else
    1959         apath[2] = '/'; /* make sure it's a forward slash */
     2102        apath[root_len - 1] = '/'; /* make sure it's a forward slash */
    19602103#endif
    19612104    }
     
    19662109
    19672110      /* Skip sequence of multiple path-separators.  */
    1968       while (IS_PATHSEP(*start))
    1969         ++start;
     2111      while (STOP_SET (*start, MAP_DIRSEP))
     2112        ++start;
    19702113
    19712114      /* Find end of path component.  */
    1972       for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
     2115      for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
    19732116        ;
    19742117
     
    19762119
    19772120      if (len == 0)
    1978         break;
     2121        break;
    19792122      else if (len == 1 && start[0] == '.')
    1980         /* nothing */;
     2123        /* nothing */;
    19812124      else if (len == 2 && start[0] == '.' && start[1] == '.')
    1982         {
    1983           /* Back up to previous component, ignore if at root already.  */
    1984           if (dest > apath + root_len)
    1985             for (--dest; !IS_PATHSEP(dest[-1]); --dest);
    1986         }
     2125        {
     2126          /* Back up to previous component, ignore if at root already.  */
     2127          if (dest > apath + root_len)
     2128            for (--dest; ! STOP_SET (dest[-1], MAP_DIRSEP); --dest)
     2129              ;
     2130        }
    19872131      else
    1988         {
    1989           if (!IS_PATHSEP(dest[-1]))
     2132        {
     2133          if (! STOP_SET (dest[-1], MAP_DIRSEP))
    19902134            *dest++ = '/';
    19912135
    1992           if (dest + len >= apath_limit)
     2136          if (dest + len >= apath_limit)
    19932137            return NULL;
    19942138
    1995           dest = memcpy (dest, start, len);
     2139          dest = memcpy (dest, start, len);
    19962140          dest += len;
    1997           *dest = '\0';
    1998         }
     2141          *dest = '\0';
     2142        }
    19992143    }
    20002144
    20012145  /* Unless it is root strip trailing separator.  */
    2002   if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
     2146  if (dest > apath + root_len && STOP_SET (dest[-1], MAP_DIRSEP))
    20032147    --dest;
    20042148
     
    20172161  int doneany = 0;
    20182162  unsigned int len = 0;
    2019 #ifndef HAVE_REALPATH
    2020   struct stat st;
    2021 #endif
    2022   PATH_VAR (in);
    2023   PATH_VAR (out);
    20242163
    20252164  while ((path = find_next_token (&p, &len)) != 0)
     
    20272166      if (len < GET_PATH_MAX)
    20282167        {
     2168          char *rp;
     2169          struct stat st;
     2170          PATH_VAR (in);
     2171          PATH_VAR (out);
     2172
    20292173          strncpy (in, path, len);
    20302174          in[len] = '\0';
    20312175
    2032           if (
    20332176#ifdef HAVE_REALPATH
    2034               realpath (in, out)
     2177          ENULLLOOP (rp, realpath (in, out));
    20352178#else
    2036               abspath (in, out) && stat (out, &st) == 0
     2179          rp = abspath (in, out);
    20372180#endif
    2038              )
     2181
     2182          if (rp)
    20392183            {
    2040               o = variable_buffer_output (o, out, strlen (out));
    2041               o = variable_buffer_output (o, " ", 1);
    2042               doneany = 1;
     2184              int r;
     2185              EINTRLOOP (r, stat (out, &st));
     2186              if (r == 0)
     2187                {
     2188                  o = variable_buffer_output (o, out, strlen (out));
     2189                  o = variable_buffer_output (o, " ", 1);
     2190                  doneany = 1;
     2191                }
    20432192            }
    20442193        }
     
    20482197  if (doneany)
    20492198    --o;
     2199
     2200  return o;
     2201}
     2202
     2203static char *
     2204func_file (char *o, char **argv, const char *funcname UNUSED)
     2205{
     2206  char *fn = argv[0];
     2207
     2208  if (fn[0] == '>')
     2209    {
     2210      FILE *fp;
     2211      const char *mode = "w";
     2212
     2213      /* We are writing a file.  */
     2214      ++fn;
     2215      if (fn[0] == '>')
     2216        {
     2217          mode = "a";
     2218          ++fn;
     2219        }
     2220      NEXT_TOKEN (fn);
     2221
     2222      if (fn[0] == '\0')
     2223        O (fatal, *expanding_var, _("file: missing filename"));
     2224
     2225      ENULLLOOP (fp, fopen (fn, mode));
     2226      if (fp == NULL)
     2227        OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
     2228
     2229      if (argv[1])
     2230        {
     2231          int l = strlen (argv[1]);
     2232          int nl = l == 0 || argv[1][l-1] != '\n';
     2233
     2234          if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
     2235            OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
     2236        }
     2237      if (fclose (fp))
     2238        OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
     2239    }
     2240  else if (fn[0] == '<')
     2241    {
     2242      char *preo = o;
     2243      FILE *fp;
     2244
     2245      ++fn;
     2246      NEXT_TOKEN (fn);
     2247      if (fn[0] == '\0')
     2248        O (fatal, *expanding_var, _("file: missing filename"));
     2249
     2250      if (argv[1])
     2251        O (fatal, *expanding_var, _("file: too many arguments"));
     2252
     2253      ENULLLOOP (fp, fopen (fn, "r"));
     2254      if (fp == NULL)
     2255        {
     2256          if (errno == ENOENT)
     2257            return o;
     2258          OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
     2259        }
     2260
     2261      while (1)
     2262        {
     2263          char buf[1024];
     2264          size_t l = fread (buf, 1, sizeof (buf), fp);
     2265          if (l > 0)
     2266            o = variable_buffer_output (o, buf, l);
     2267
     2268          if (ferror (fp))
     2269            if (errno != EINTR)
     2270              OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
     2271          if (feof (fp))
     2272            break;
     2273        }
     2274      if (fclose (fp))
     2275        OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
     2276
     2277      /* Remove trailing newline.  */
     2278      if (o > preo && o[-1] == '\n')
     2279        if (--o > preo && o[-1] == '\r')
     2280          --o;
     2281    }
     2282  else
     2283    OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
    20502284
    20512285  return o;
     
    20602294  int doneany = 0;
    20612295  unsigned int len = 0;
    2062   PATH_VAR (in);
    2063   PATH_VAR (out);
    20642296
    20652297  while ((path = find_next_token (&p, &len)) != 0)
     
    20672299      if (len < GET_PATH_MAX)
    20682300        {
     2301          PATH_VAR (in);
     2302          PATH_VAR (out);
     2303
    20692304          strncpy (in, path, len);
    20702305          in[len] = '\0';
     
    21002335static char *func_call (char *o, char **argv, const char *funcname);
    21012336
     2337#define FT_ENTRY(_name, _min, _max, _exp, _func) \
     2338  { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0 }
    21022339
    21032340static struct function_table_entry function_table_init[] =
    21042341{
    2105  /* Name/size */                    /* MIN MAX EXP? Function */
    2106   { STRING_SIZE_TUPLE("abspath"),       0,  1,  1,  func_abspath},
    2107   { STRING_SIZE_TUPLE("addprefix"),     2,  2,  1,  func_addsuffix_addprefix},
    2108   { STRING_SIZE_TUPLE("addsuffix"),     2,  2,  1,  func_addsuffix_addprefix},
    2109   { STRING_SIZE_TUPLE("basename"),      0,  1,  1,  func_basename_dir},
    2110   { STRING_SIZE_TUPLE("dir"),           0,  1,  1,  func_basename_dir},
    2111   { STRING_SIZE_TUPLE("notdir"),        0,  1,  1,  func_notdir_suffix},
    2112   { STRING_SIZE_TUPLE("subst"),         3,  3,  1,  func_subst},
    2113   { STRING_SIZE_TUPLE("suffix"),        0,  1,  1,  func_notdir_suffix},
    2114   { STRING_SIZE_TUPLE("filter"),        2,  2,  1,  func_filter_filterout},
    2115   { STRING_SIZE_TUPLE("filter-out"),    2,  2,  1,  func_filter_filterout},
    2116   { STRING_SIZE_TUPLE("findstring"),    2,  2,  1,  func_findstring},
    2117   { STRING_SIZE_TUPLE("firstword"),     0,  1,  1,  func_firstword},
    2118   { STRING_SIZE_TUPLE("flavor"),        0,  1,  1,  func_flavor},
    2119   { STRING_SIZE_TUPLE("join"),          2,  2,  1,  func_join},
    2120   { STRING_SIZE_TUPLE("lastword"),      0,  1,  1,  func_lastword},
    2121   { STRING_SIZE_TUPLE("patsubst"),      3,  3,  1,  func_patsubst},
    2122   { STRING_SIZE_TUPLE("realpath"),      0,  1,  1,  func_realpath},
    2123   { STRING_SIZE_TUPLE("shell"),         0,  1,  1,  func_shell},
    2124   { STRING_SIZE_TUPLE("sort"),          0,  1,  1,  func_sort},
    2125   { STRING_SIZE_TUPLE("strip"),         0,  1,  1,  func_strip},
    2126   { STRING_SIZE_TUPLE("wildcard"),      0,  1,  1,  func_wildcard},
    2127   { STRING_SIZE_TUPLE("word"),          2,  2,  1,  func_word},
    2128   { STRING_SIZE_TUPLE("wordlist"),      3,  3,  1,  func_wordlist},
    2129   { STRING_SIZE_TUPLE("words"),         0,  1,  1,  func_words},
    2130   { STRING_SIZE_TUPLE("origin"),        0,  1,  1,  func_origin},
    2131   { STRING_SIZE_TUPLE("foreach"),       3,  3,  0,  func_foreach},
    2132   { STRING_SIZE_TUPLE("call"),          1,  0,  1,  func_call},
    2133   { STRING_SIZE_TUPLE("info"),          0,  1,  1,  func_error},
    2134   { STRING_SIZE_TUPLE("error"),         0,  1,  1,  func_error},
    2135   { STRING_SIZE_TUPLE("warning"),       0,  1,  1,  func_error},
    2136   { STRING_SIZE_TUPLE("if"),            2,  3,  0,  func_if},
    2137   { STRING_SIZE_TUPLE("or"),            1,  0,  0,  func_or},
    2138   { STRING_SIZE_TUPLE("and"),           1,  0,  0,  func_and},
    2139   { STRING_SIZE_TUPLE("value"),         0,  1,  1,  func_value},
    2140   { STRING_SIZE_TUPLE("eval"),          0,  1,  1,  func_eval},
     2342 /*         Name            MIN MAX EXP? Function */
     2343  FT_ENTRY ("abspath",       0,  1,  1,  func_abspath),
     2344  FT_ENTRY ("addprefix",     2,  2,  1,  func_addsuffix_addprefix),
     2345  FT_ENTRY ("addsuffix",     2,  2,  1,  func_addsuffix_addprefix),
     2346  FT_ENTRY ("basename",      0,  1,  1,  func_basename_dir),
     2347  FT_ENTRY ("dir",           0,  1,  1,  func_basename_dir),
     2348  FT_ENTRY ("notdir",        0,  1,  1,  func_notdir_suffix),
     2349  FT_ENTRY ("subst",         3,  3,  1,  func_subst),
     2350  FT_ENTRY ("suffix",        0,  1,  1,  func_notdir_suffix),
     2351  FT_ENTRY ("filter",        2,  2,  1,  func_filter_filterout),
     2352  FT_ENTRY ("filter-out",    2,  2,  1,  func_filter_filterout),
     2353  FT_ENTRY ("findstring",    2,  2,  1,  func_findstring),
     2354  FT_ENTRY ("firstword",     0,  1,  1,  func_firstword),
     2355  FT_ENTRY ("flavor",        0,  1,  1,  func_flavor),
     2356  FT_ENTRY ("join",          2,  2,  1,  func_join),
     2357  FT_ENTRY ("lastword",      0,  1,  1,  func_lastword),
     2358  FT_ENTRY ("patsubst",      3,  3,  1,  func_patsubst),
     2359  FT_ENTRY ("realpath",      0,  1,  1,  func_realpath),
     2360  FT_ENTRY ("shell",         0,  1,  1,  func_shell),
     2361  FT_ENTRY ("sort",          0,  1,  1,  func_sort),
     2362  FT_ENTRY ("strip",         0,  1,  1,  func_strip),
     2363  FT_ENTRY ("wildcard",      0,  1,  1,  func_wildcard),
     2364  FT_ENTRY ("word",          2,  2,  1,  func_word),
     2365  FT_ENTRY ("wordlist",      3,  3,  1,  func_wordlist),
     2366  FT_ENTRY ("words",         0,  1,  1,  func_words),
     2367  FT_ENTRY ("origin",        0,  1,  1,  func_origin),
     2368  FT_ENTRY ("foreach",       3,  3,  0,  func_foreach),
     2369  FT_ENTRY ("call",          1,  0,  1,  func_call),
     2370  FT_ENTRY ("info",          0,  1,  1,  func_error),
     2371  FT_ENTRY ("error",         0,  1,  1,  func_error),
     2372  FT_ENTRY ("warning",       0,  1,  1,  func_error),
     2373  FT_ENTRY ("if",            2,  3,  0,  func_if),
     2374  FT_ENTRY ("or",            1,  0,  0,  func_or),
     2375  FT_ENTRY ("and",           1,  0,  0,  func_and),
     2376  FT_ENTRY ("value",         0,  1,  1,  func_value),
     2377  FT_ENTRY ("eval",          0,  1,  1,  func_eval),
     2378  FT_ENTRY ("file",          1,  2,  1,  func_file),
    21412379#ifdef EXPERIMENTAL
    2142   { STRING_SIZE_TUPLE("eq"),            2,  2,  1,  func_eq},
    2143   { STRING_SIZE_TUPLE("not"),           0,  1,  1,  func_not},
     2380  FT_ENTRY ("eq",            2,  2,  1,  func_eq),
     2381  FT_ENTRY ("not",           0,  1,  1,  func_not),
    21442382#endif
    21452383};
     
    21552393                         const struct function_table_entry *entry_p)
    21562394{
     2395  char *p;
     2396
    21572397  if (argc < (int)entry_p->minimum_args)
    2158     fatal (*expanding_var,
    2159            _("insufficient number of arguments (%d) to function `%s'"),
     2398    fatal (*expanding_var, strlen (entry_p->name),
     2399           _("insufficient number of arguments (%d) to function '%s'"),
    21602400           argc, entry_p->name);
    21612401
    2162   /* I suppose technically some function could do something with no
    2163      arguments, but so far none do, so just test it for all functions here
     2402  /* I suppose technically some function could do something with no arguments,
     2403     but so far no internal ones do, so just test it for all functions here
    21642404     rather than in each one.  We can change it later if necessary.  */
    21652405
    2166   if (!argc)
     2406  if (!argc && !entry_p->alloc_fn)
    21672407    return o;
    21682408
    2169   if (!entry_p->func_ptr)
    2170     fatal (*expanding_var,
    2171            _("unimplemented on this platform: function `%s'"), entry_p->name);
    2172 
    2173   return entry_p->func_ptr (o, argv, entry_p->name);
     2409  if (!entry_p->fptr.func_ptr)
     2410    OS (fatal, *expanding_var,
     2411        _("unimplemented on this platform: function '%s'"), entry_p->name);
     2412
     2413  if (!entry_p->alloc_fn)
     2414    return entry_p->fptr.func_ptr (o, argv, entry_p->name);
     2415
     2416  /* This function allocates memory and returns it to us.
     2417     Write it to the variable buffer, then free it.  */
     2418
     2419  p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
     2420  if (p)
     2421    {
     2422      o = variable_buffer_output (o, p, strlen (p));
     2423      free (p);
     2424    }
     2425
     2426  return o;
    21742427}
    21752428
     
    22022455     whitespace after the name).  */
    22032456
    2204   beg = next_token (beg + entry_p->len);
     2457  beg += entry_p->len;
     2458  NEXT_TOKEN (beg);
    22052459
    22062460  /* Find the end of the function invocation, counting nested use of
     
    22182472
    22192473  if (count >= 0)
    2220     fatal (*expanding_var,
    2221            _("unterminated call to function `%s': missing `%c'"),
    2222            entry_p->name, closeparen);
     2474    fatal (*expanding_var, strlen (entry_p->name),
     2475           _("unterminated call to function '%s': missing '%c'"),
     2476           entry_p->name, closeparen);
    22232477
    22242478  *stringp = end;
     
    22862540    for (argvp=argv; *argvp != 0; ++argvp)
    22872541      free (*argvp);
    2288   if (abeg)
     2542  else
    22892543    free (abeg);
    22902544
     
    23032557  static int max_args = 0;
    23042558  char *fname;
    2305   char *cp;
    23062559  char *body;
    23072560  int flen;
     
    23112564  struct variable *v;
    23122565
    2313   /* There is no way to define a variable with a space in the name, so strip
    2314      leading and trailing whitespace as a favor to the user.  */
    2315   fname = argv[0];
    2316   while (*fname != '\0' && isspace ((unsigned char)*fname))
    2317     ++fname;
    2318 
    2319   cp = fname + strlen (fname) - 1;
    2320   while (cp > fname && isspace ((unsigned char)*cp))
    2321     --cp;
    2322   cp[1] = '\0';
     2566  /* Clean up the name of the variable to be invoked.  */
     2567  fname = next_token (argv[0]);
     2568  end_of_token (fname)[0] = '\0';
    23232569
    23242570  /* Calling nothing is a no-op */
     
    23992645
    24002646void
     2647define_new_function (const floc *flocp, const char *name,
     2648                     unsigned int min, unsigned int max, unsigned int flags,
     2649                     gmk_func_ptr func)
     2650{
     2651  const char *e = name;
     2652  struct function_table_entry *ent;
     2653  size_t len;
     2654
     2655  while (STOP_SET (*e, MAP_USERFUNC))
     2656    e++;
     2657  len = e - name;
     2658
     2659  if (len == 0)
     2660    O (fatal, flocp, _("Empty function name"));
     2661  if (*name == '.' || *e != '\0')
     2662    OS (fatal, flocp, _("Invalid function name: %s"), name);
     2663  if (len > 255)
     2664    OS (fatal, flocp, _("Function name too long: %s"), name);
     2665  if (min > 255)
     2666    ONS (fatal, flocp,
     2667         _("Invalid minimum argument count (%u) for function %s"), min, name);
     2668  if (max > 255 || (max && max < min))
     2669    ONS (fatal, flocp,
     2670         _("Invalid maximum argument count (%u) for function %s"), max, name);
     2671
     2672  ent = xmalloc (sizeof (struct function_table_entry));
     2673  ent->name = name;
     2674  ent->len = len;
     2675  ent->minimum_args = min;
     2676  ent->maximum_args = max;
     2677  ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
     2678  ent->alloc_fn = 1;
     2679  ent->fptr.alloc_func_ptr = func;
     2680
     2681  hash_insert (&function_table, ent);
     2682}
     2683
     2684void
    24012685hash_init_function_table (void)
    24022686{
    24032687  hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
    2404              function_table_entry_hash_1, function_table_entry_hash_2,
    2405              function_table_entry_hash_cmp);
     2688             function_table_entry_hash_1, function_table_entry_hash_2,
     2689             function_table_entry_hash_cmp);
    24062690  hash_load (&function_table, function_table_init,
    2407              FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
    2408 }
     2691             FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
     2692}
Note: See TracChangeset for help on using the changeset viewer.