1/* Builtin function expansion for GNU Make.
2Copyright (C) 1988, 1989, 1991-1997, 1999, 2002 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation; either version 2, or (at your option)
8any later version.
9
10GNU Make is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with GNU Make; see the file COPYING.  If not, write to
17the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18Boston, MA 02111-1307, USA.  */
19
20#include "make.h"
21#include "filedef.h"
22#include "variable.h"
23#include "dep.h"
24#include "job.h"
25#include "commands.h"
26#include "debug.h"
27
28#ifdef _AMIGA
29#include "amiga.h"
30#endif
31
32
33struct function_table_entry
34  {
35    const char *name;
36    unsigned char len;
37    unsigned char minimum_args;
38    unsigned char maximum_args;
39    char expand_args;
40    char *(*func_ptr) PARAMS ((char *output, char **argv, const char *fname));
41  };
42
43static unsigned long
44function_table_entry_hash_1 (keyv)
45    const void *keyv;
46{
47  struct function_table_entry const *key = (struct function_table_entry const *) keyv;
48  return_STRING_N_HASH_1 (key->name, key->len);
49}
50
51static unsigned long
52function_table_entry_hash_2 (keyv)
53    const void *keyv;
54{
55  struct function_table_entry const *key = (struct function_table_entry const *) keyv;
56  return_STRING_N_HASH_2 (key->name, key->len);
57}
58
59static int
60function_table_entry_hash_cmp (xv, yv)
61    const void *xv;
62    const void *yv;
63{
64  struct function_table_entry const *x = (struct function_table_entry const *) xv;
65  struct function_table_entry const *y = (struct function_table_entry const *) yv;
66  int result = x->len - y->len;
67  if (result)
68    return result;
69  return_STRING_N_COMPARE (x->name, y->name, x->len);
70}
71
72static struct hash_table function_table;
73
74
75/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
76   each occurrence of SUBST with REPLACE. TEXT is null-terminated.  SLEN is
77   the length of SUBST and RLEN is the length of REPLACE.  If BY_WORD is
78   nonzero, substitutions are done only on matches which are complete
79   whitespace-delimited words.  If SUFFIX_ONLY is nonzero, substitutions are
80   done only at the ends of whitespace-delimited words.  */
81
82char *
83subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
84     char *o;
85     char *text;
86     char *subst, *replace;
87     unsigned int slen, rlen;
88     int by_word, suffix_only;
89{
90  register char *t = text;
91  register char *p;
92
93  if (slen == 0 && !by_word && !suffix_only)
94    {
95      /* The first occurrence of "" in any string is its end.  */
96      o = variable_buffer_output (o, t, strlen (t));
97      if (rlen > 0)
98	o = variable_buffer_output (o, replace, rlen);
99      return o;
100    }
101
102  do
103    {
104      if ((by_word | suffix_only) && slen == 0)
105	/* When matching by words, the empty string should match
106	   the end of each word, rather than the end of the whole text.  */
107	p = end_of_token (next_token (t));
108      else
109	{
110	  p = sindex (t, 0, subst, slen);
111	  if (p == 0)
112	    {
113	      /* No more matches.  Output everything left on the end.  */
114	      o = variable_buffer_output (o, t, strlen (t));
115	      return o;
116	    }
117	}
118
119      /* Output everything before this occurrence of the string to replace.  */
120      if (p > t)
121	o = variable_buffer_output (o, t, p - t);
122
123      /* If we're substituting only by fully matched words,
124	 or only at the ends of words, check that this case qualifies.  */
125      if ((by_word
126	   && ((p > t && !isblank ((unsigned char)p[-1]))
127	       || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
128	  || (suffix_only
129	      && (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
130	/* Struck out.  Output the rest of the string that is
131	   no longer to be replaced.  */
132	o = variable_buffer_output (o, subst, slen);
133      else if (rlen > 0)
134	/* Output the replacement string.  */
135	o = variable_buffer_output (o, replace, rlen);
136
137      /* Advance T past the string to be replaced.  */
138      t = p + slen;
139    } while (*t != '\0');
140
141  return o;
142}
143
144
145/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
146   and replacing strings matching PATTERN with REPLACE.
147   If PATTERN_PERCENT is not nil, PATTERN has already been
148   run through find_percent, and PATTERN_PERCENT is the result.
149   If REPLACE_PERCENT is not nil, REPLACE has already been
150   run through find_percent, and REPLACE_PERCENT is the result.  */
151
152char *
153patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
154     char *o;
155     char *text;
156     register char *pattern, *replace;
157     register char *pattern_percent, *replace_percent;
158{
159  unsigned int pattern_prepercent_len, pattern_postpercent_len;
160  unsigned int replace_prepercent_len, replace_postpercent_len = 0;
161  char *t;
162  unsigned int len;
163  int doneany = 0;
164
165  /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
166     will be collapsed before we call subst_expand if PATTERN has no %.  */
167  if (replace_percent == 0)
168    replace_percent = find_percent (replace);
169  if (replace_percent != 0)
170    {
171      /* Record the length of REPLACE before and after the % so
172	 we don't have to compute these lengths more than once.  */
173      replace_prepercent_len = replace_percent - replace;
174      replace_postpercent_len = strlen (replace_percent + 1);
175    }
176  else
177    /* We store the length of the replacement
178       so we only need to compute it once.  */
179    replace_prepercent_len = strlen (replace);
180
181  if (pattern_percent == 0)
182    pattern_percent = find_percent (pattern);
183  if (pattern_percent == 0)
184    /* With no % in the pattern, this is just a simple substitution.  */
185    return subst_expand (o, text, pattern, replace,
186			 strlen (pattern), strlen (replace), 1, 0);
187
188  /* Record the length of PATTERN before and after the %
189     so we don't have to compute it more than once.  */
190  pattern_prepercent_len = pattern_percent - pattern;
191  pattern_postpercent_len = strlen (pattern_percent + 1);
192
193  while ((t = find_next_token (&text, &len)) != 0)
194    {
195      int fail = 0;
196
197      /* Is it big enough to match?  */
198      if (len < pattern_prepercent_len + pattern_postpercent_len)
199	fail = 1;
200
201      /* Does the prefix match? */
202      if (!fail && pattern_prepercent_len > 0
203	  && (*t != *pattern
204	      || t[pattern_prepercent_len - 1] != pattern_percent[-1]
205	      || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
206	fail = 1;
207
208      /* Does the suffix match? */
209      if (!fail && pattern_postpercent_len > 0
210	  && (t[len - 1] != pattern_percent[pattern_postpercent_len]
211	      || t[len - pattern_postpercent_len] != pattern_percent[1]
212	      || !strneq (&t[len - pattern_postpercent_len],
213			  &pattern_percent[1], pattern_postpercent_len - 1)))
214	fail = 1;
215
216      if (fail)
217	/* It didn't match.  Output the string.  */
218	o = variable_buffer_output (o, t, len);
219      else
220	{
221	  /* It matched.  Output the replacement.  */
222
223	  /* Output the part of the replacement before the %.  */
224	  o = variable_buffer_output (o, replace, replace_prepercent_len);
225
226	  if (replace_percent != 0)
227	    {
228	      /* Output the part of the matched string that
229		 matched the % in the pattern.  */
230	      o = variable_buffer_output (o, t + pattern_prepercent_len,
231					  len - (pattern_prepercent_len
232						 + pattern_postpercent_len));
233	      /* Output the part of the replacement after the %.  */
234	      o = variable_buffer_output (o, replace_percent + 1,
235					  replace_postpercent_len);
236	    }
237	}
238
239      /* Output a space, but not if the replacement is "".  */
240      if (fail || replace_prepercent_len > 0
241	  || (replace_percent != 0 && len + replace_postpercent_len > 0))
242	{
243	  o = variable_buffer_output (o, " ", 1);
244	  doneany = 1;
245	}
246    }
247  if (doneany)
248    /* Kill the last space.  */
249    --o;
250
251  return o;
252}
253
254
255/* Look up a function by name.  */
256
257static const struct function_table_entry *
258lookup_function (s)
259     const char *s;
260{
261  const char *e = s;
262
263  while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
264    e++;
265  if (*e == '\0' || isblank ((unsigned char) *e))
266    {
267      struct function_table_entry function_table_entry_key;
268      function_table_entry_key.name = s;
269      function_table_entry_key.len = e - s;
270
271      return hash_find_item (&function_table, &function_table_entry_key);
272    }
273  return 0;
274}
275
276
277/* Return 1 if PATTERN matches STR, 0 if not.  */
278
279int
280pattern_matches (pattern, percent, str)
281     register char *pattern, *percent, *str;
282{
283  unsigned int sfxlen, strlength;
284
285  if (percent == 0)
286    {
287      unsigned int len = strlen (pattern) + 1;
288      char *new_chars = (char *) alloca (len);
289      bcopy (pattern, new_chars, len);
290      pattern = new_chars;
291      percent = find_percent (pattern);
292      if (percent == 0)
293	return streq (pattern, str);
294    }
295
296  sfxlen = strlen (percent + 1);
297  strlength = strlen (str);
298
299  if (strlength < (percent - pattern) + sfxlen
300      || !strneq (pattern, str, percent - pattern))
301    return 0;
302
303  return !strcmp (percent + 1, str + (strlength - sfxlen));
304}
305
306
307/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
308   ENDPARENtheses), starting at PTR before END.  Return a pointer to
309   next character.
310
311   If no next argument is found, return NULL.
312*/
313
314static char *
315find_next_argument (startparen, endparen, ptr, end)
316     char startparen;
317     char endparen;
318     const char *ptr;
319     const char *end;
320{
321  int count = 0;
322
323  for (; ptr < end; ++ptr)
324    if (*ptr == startparen)
325      ++count;
326
327    else if (*ptr == endparen)
328      {
329	--count;
330	if (count < 0)
331	  return NULL;
332      }
333
334    else if (*ptr == ',' && !count)
335      return (char *)ptr;
336
337  /* We didn't find anything.  */
338  return NULL;
339}
340
341
342/* Glob-expand LINE.  The returned pointer is
343   only good until the next call to string_glob.  */
344
345static char *
346string_glob (line)
347     char *line;
348{
349  static char *result = 0;
350  static unsigned int length;
351  register struct nameseq *chain;
352  register unsigned int idx;
353
354  chain = multi_glob (parse_file_seq
355		      (&line, '\0', sizeof (struct nameseq),
356		       /* We do not want parse_file_seq to strip `./'s.
357			  That would break examples like:
358			  $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)).  */
359		       0),
360		      sizeof (struct nameseq));
361
362  if (result == 0)
363    {
364      length = 100;
365      result = (char *) xmalloc (100);
366    }
367
368  idx = 0;
369  while (chain != 0)
370    {
371      register char *name = chain->name;
372      unsigned int len = strlen (name);
373
374      struct nameseq *next = chain->next;
375      free ((char *) chain);
376      chain = next;
377
378      /* multi_glob will pass names without globbing metacharacters
379	 through as is, but we want only files that actually exist.  */
380      if (file_exists_p (name))
381	{
382	  if (idx + len + 1 > length)
383	    {
384	      length += (len + 1) * 2;
385	      result = (char *) xrealloc (result, length);
386	    }
387	  bcopy (name, &result[idx], len);
388	  idx += len;
389	  result[idx++] = ' ';
390	}
391
392      free (name);
393    }
394
395  /* Kill the last space and terminate the string.  */
396  if (idx == 0)
397    result[0] = '\0';
398  else
399    result[idx - 1] = '\0';
400
401  return result;
402}
403
404/*
405  Builtin functions
406 */
407
408static char *
409func_patsubst (o, argv, funcname)
410     char *o;
411     char **argv;
412     const char *funcname;
413{
414  o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
415  return o;
416}
417
418
419static char *
420func_join (o, argv, funcname)
421     char *o;
422     char **argv;
423     const char *funcname;
424{
425  int doneany = 0;
426
427  /* Write each word of the first argument directly followed
428     by the corresponding word of the second argument.
429     If the two arguments have a different number of words,
430     the excess words are just output separated by blanks.  */
431  register char *tp;
432  register char *pp;
433  char *list1_iterator = argv[0];
434  char *list2_iterator = argv[1];
435  do
436    {
437      unsigned int len1, len2;
438
439      tp = find_next_token (&list1_iterator, &len1);
440      if (tp != 0)
441	o = variable_buffer_output (o, tp, len1);
442
443      pp = find_next_token (&list2_iterator, &len2);
444      if (pp != 0)
445	o = variable_buffer_output (o, pp, len2);
446
447      if (tp != 0 || pp != 0)
448	{
449	  o = variable_buffer_output (o, " ", 1);
450	  doneany = 1;
451	}
452    }
453  while (tp != 0 || pp != 0);
454  if (doneany)
455    /* Kill the last blank.  */
456    --o;
457
458  return o;
459}
460
461
462static char *
463func_origin (o, argv, funcname)
464     char *o;
465     char **argv;
466     const char *funcname;
467{
468  /* Expand the argument.  */
469  register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
470  if (v == 0)
471    o = variable_buffer_output (o, "undefined", 9);
472  else
473    switch (v->origin)
474      {
475      default:
476      case o_invalid:
477	abort ();
478	break;
479      case o_default:
480	o = variable_buffer_output (o, "default", 7);
481	break;
482      case o_env:
483	o = variable_buffer_output (o, "environment", 11);
484	break;
485      case o_file:
486	o = variable_buffer_output (o, "file", 4);
487	break;
488      case o_env_override:
489	o = variable_buffer_output (o, "environment override", 20);
490	break;
491      case o_command:
492	o = variable_buffer_output (o, "command line", 12);
493	break;
494      case o_override:
495	o = variable_buffer_output (o, "override", 8);
496	break;
497      case o_automatic:
498	o = variable_buffer_output (o, "automatic", 9);
499	break;
500      }
501
502  return o;
503}
504
505#ifdef VMS
506# define IS_PATHSEP(c) ((c) == ']')
507#else
508# ifdef HAVE_DOS_PATHS
509#  define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
510# else
511#  define IS_PATHSEP(c) ((c) == '/')
512# endif
513#endif
514
515
516static char *
517func_notdir_suffix (o, argv, funcname)
518     char *o;
519     char **argv;
520     const char *funcname;
521{
522  /* Expand the argument.  */
523  char *list_iterator = argv[0];
524  char *p2 =0;
525  int doneany =0;
526  unsigned int len=0;
527
528  int is_suffix = streq (funcname, "suffix");
529  int is_notdir = !is_suffix;
530  while ((p2 = find_next_token (&list_iterator, &len)) != 0)
531    {
532      char *p = p2 + len;
533
534
535      while (p >= p2 && (!is_suffix || *p != '.'))
536	{
537	  if (IS_PATHSEP (*p))
538	    break;
539	  --p;
540	}
541
542      if (p >= p2)
543	{
544	  if (is_notdir)
545	    ++p;
546	  else if (*p != '.')
547	    continue;
548	  o = variable_buffer_output (o, p, len - (p - p2));
549	}
550#ifdef HAVE_DOS_PATHS
551      /* Handle the case of "d:foo/bar".  */
552      else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
553	{
554	  p = p2 + 2;
555	  o = variable_buffer_output (o, p, len - (p - p2));
556	}
557#endif
558      else if (is_notdir)
559	o = variable_buffer_output (o, p2, len);
560
561      if (is_notdir || p >= p2)
562	{
563	  o = variable_buffer_output (o, " ", 1);
564	  doneany = 1;
565	}
566    }
567  if (doneany)
568    /* Kill last space.  */
569    --o;
570
571
572  return o;
573
574}
575
576
577static char *
578func_basename_dir (o, argv, funcname)
579     char *o;
580     char **argv;
581     const char *funcname;
582{
583  /* Expand the argument.  */
584  char *p3 = argv[0];
585  char *p2=0;
586  int doneany=0;
587  unsigned int len=0;
588  char *p=0;
589  int is_basename= streq (funcname, "basename");
590  int is_dir= !is_basename;
591
592  while ((p2 = find_next_token (&p3, &len)) != 0)
593	{
594	  p = p2 + len;
595	  while (p >= p2 && (!is_basename  || *p != '.'))
596	    {
597	      if (IS_PATHSEP (*p))
598		break;
599	      	    --p;
600	    }
601
602	  if (p >= p2 && (is_dir))
603	    o = variable_buffer_output (o, p2, ++p - p2);
604	  else if (p >= p2 && (*p == '.'))
605	    o = variable_buffer_output (o, p2, p - p2);
606#ifdef HAVE_DOS_PATHS
607	/* Handle the "d:foobar" case */
608	  else if (p2[0] && p2[1] == ':' && is_dir)
609	    o = variable_buffer_output (o, p2, 2);
610#endif
611	  else if (is_dir)
612#ifdef VMS
613	    o = variable_buffer_output (o, "[]", 2);
614#else
615#ifndef _AMIGA
616	    o = variable_buffer_output (o, "./", 2);
617#else
618	    ; /* Just a nop...  */
619#endif /* AMIGA */
620#endif /* !VMS */
621	  else
622	    /* The entire name is the basename.  */
623	    o = variable_buffer_output (o, p2, len);
624
625	  o = variable_buffer_output (o, " ", 1);
626	  doneany = 1;
627	}
628      if (doneany)
629	/* Kill last space.  */
630	--o;
631
632
633 return o;
634}
635
636static char *
637func_addsuffix_addprefix (o, argv, funcname)
638     char *o;
639     char **argv;
640     const char *funcname;
641{
642  int fixlen = strlen (argv[0]);
643  char *list_iterator = argv[1];
644  int is_addprefix = streq (funcname, "addprefix");
645  int is_addsuffix = !is_addprefix;
646
647  int doneany = 0;
648  char *p;
649  unsigned int len;
650
651  while ((p = find_next_token (&list_iterator, &len)) != 0)
652    {
653      if (is_addprefix)
654	o = variable_buffer_output (o, argv[0], fixlen);
655      o = variable_buffer_output (o, p, len);
656      if (is_addsuffix)
657	o = variable_buffer_output (o, argv[0], fixlen);
658      o = variable_buffer_output (o, " ", 1);
659      doneany = 1;
660    }
661
662  if (doneany)
663    /* Kill last space.  */
664    --o;
665
666  return o;
667}
668
669static char *
670func_subst (o, argv, funcname)
671     char *o;
672     char **argv;
673     const char *funcname;
674{
675  o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
676		    strlen (argv[1]), 0, 0);
677
678  return o;
679}
680
681
682static char *
683func_firstword (o, argv, funcname)
684     char *o;
685     char **argv;
686     const char *funcname;
687{
688  unsigned int i;
689  char *words = argv[0];    /* Use a temp variable for find_next_token */
690  char *p = find_next_token (&words, &i);
691
692  if (p != 0)
693    o = variable_buffer_output (o, p, i);
694
695  return o;
696}
697
698
699static char *
700func_words (o, argv, funcname)
701     char *o;
702     char **argv;
703     const char *funcname;
704{
705  int i = 0;
706  char *word_iterator = argv[0];
707  char buf[20];
708
709  while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
710    ++i;
711
712  sprintf (buf, "%d", i);
713  o = variable_buffer_output (o, buf, strlen (buf));
714
715
716  return o;
717}
718
719char *
720strip_whitespace (begpp, endpp)
721     char **begpp;
722     char **endpp;
723{
724  while (isspace ((unsigned char)**begpp) && *begpp <= *endpp)
725    (*begpp) ++;
726  while (isspace ((unsigned char)**endpp) && *endpp >= *begpp)
727    (*endpp) --;
728  return *begpp;
729}
730
731int
732is_numeric (p)
733     char *p;
734{
735  char *end = p + strlen (p) - 1;
736  char *beg = p;
737  strip_whitespace (&p, &end);
738
739  while (p <= end)
740    if (!ISDIGIT (*(p++)))  /* ISDIGIT only evals its arg once: see make.h.  */
741      return 0;
742
743  return (end - beg >= 0);
744}
745
746void
747check_numeric (s, message)
748     char *s;
749     char *message;
750{
751  if (!is_numeric (s))
752    fatal (reading_file, message);
753}
754
755
756
757static char *
758func_word (o, argv, funcname)
759     char *o;
760     char **argv;
761     const char *funcname;
762{
763  char *end_p=0;
764  int i=0;
765  char *p=0;
766
767  /* Check the first argument.  */
768  check_numeric (argv[0], _("non-numeric first argument to `word' function"));
769  i =  atoi (argv[0]);
770
771  if (i == 0)
772    fatal (reading_file, _("first argument to `word' function must be greater than 0"));
773
774
775  end_p = argv[1];
776  while ((p = find_next_token (&end_p, 0)) != 0)
777    if (--i == 0)
778      break;
779
780  if (i == 0)
781    o = variable_buffer_output (o, p, end_p - p);
782
783  return o;
784}
785
786static char *
787func_wordlist (o, argv, funcname)
788     char *o;
789     char **argv;
790     const char *funcname;
791{
792  int start, count;
793
794  /* Check the arguments.  */
795  check_numeric (argv[0],
796		 _("non-numeric first argument to `wordlist' function"));
797  check_numeric (argv[1],
798		 _("non-numeric second argument to `wordlist' function"));
799
800  start = atoi (argv[0]);
801  count = atoi (argv[1]) - start + 1;
802
803  if (count > 0)
804    {
805      char *p;
806      char *end_p = argv[2];
807
808      /* Find the beginning of the "start"th word.  */
809      while (((p = find_next_token (&end_p, 0)) != 0) && --start)
810        ;
811
812      if (p)
813        {
814          /* Find the end of the "count"th word from start.  */
815          while (--count && (find_next_token (&end_p, 0) != 0))
816            ;
817
818          /* Return the stuff in the middle.  */
819          o = variable_buffer_output (o, p, end_p - p);
820        }
821    }
822
823  return o;
824}
825
826static char*
827func_findstring (o, argv, funcname)
828     char *o;
829     char **argv;
830     const char *funcname;
831{
832  /* Find the first occurrence of the first string in the second.  */
833  int i = strlen (argv[0]);
834  if (sindex (argv[1], 0, argv[0], i) != 0)
835    o = variable_buffer_output (o, argv[0], i);
836
837  return o;
838}
839
840static char *
841func_foreach (o, argv, funcname)
842     char *o;
843     char **argv;
844     const char *funcname;
845{
846  /* expand only the first two.  */
847  char *varname = expand_argument (argv[0], NULL);
848  char *list = expand_argument (argv[1], NULL);
849  char *body = argv[2];
850
851  int doneany = 0;
852  char *list_iterator = list;
853  char *p;
854  unsigned int len;
855  register struct variable *var;
856
857  push_new_variable_scope ();
858  var = define_variable (varname, strlen (varname), "", o_automatic, 0);
859
860  /* loop through LIST,  put the value in VAR and expand BODY */
861  while ((p = find_next_token (&list_iterator, &len)) != 0)
862    {
863      char *result = 0;
864
865      {
866	char save = p[len];
867
868	p[len] = '\0';
869	free (var->value);
870	var->value = (char *) xstrdup ((char*) p);
871	p[len] = save;
872      }
873
874      result = allocated_variable_expand (body);
875
876      o = variable_buffer_output (o, result, strlen (result));
877      o = variable_buffer_output (o, " ", 1);
878      doneany = 1;
879      free (result);
880    }
881
882  if (doneany)
883    /* Kill the last space.  */
884    --o;
885
886  pop_variable_scope ();
887  free (varname);
888  free (list);
889
890  return o;
891}
892
893struct a_word
894{
895  struct a_word *next;
896  struct a_word *chain;
897  char *str;
898  int length;
899  int matched;
900};
901
902static unsigned long
903a_word_hash_1 (key)
904    const void *key;
905{
906  return_STRING_HASH_1 (((struct a_word const *) key)->str);
907}
908
909static unsigned long
910a_word_hash_2 (key)
911    const void *key;
912{
913  return_STRING_HASH_2 (((struct a_word const *) key)->str);
914}
915
916static int
917a_word_hash_cmp (x, y)
918    const void *x;
919    const void *y;
920{
921  int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
922  if (result)
923    return result;
924  return_STRING_COMPARE (((struct a_word const *) x)->str,
925			 ((struct a_word const *) y)->str);
926}
927
928struct a_pattern
929{
930  struct a_pattern *next;
931  char *str;
932  char *percent;
933  int length;
934  int save_c;
935};
936
937static char *
938func_filter_filterout (o, argv, funcname)
939     char *o;
940     char **argv;
941     const char *funcname;
942{
943  struct a_word *wordhead;
944  struct a_word **wordtail;
945  struct a_word *wp;
946  struct a_pattern *pathead;
947  struct a_pattern **pattail;
948  struct a_pattern *pp;
949
950  struct hash_table a_word_table;
951  int is_filter = streq (funcname, "filter");
952  char *pat_iterator = argv[0];
953  char *word_iterator = argv[1];
954  int literals = 0;
955  int words = 0;
956  int hashing = 0;
957  char *p;
958  unsigned int len;
959
960  /* Chop ARGV[0] up into patterns to match against the words.  */
961
962  pattail = &pathead;
963  while ((p = find_next_token (&pat_iterator, &len)) != 0)
964    {
965      struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
966
967      *pattail = pat;
968      pattail = &pat->next;
969
970      if (*pat_iterator != '\0')
971	++pat_iterator;
972
973      pat->str = p;
974      pat->length = len;
975      pat->save_c = p[len];
976      p[len] = '\0';
977      pat->percent = find_percent (p);
978      if (pat->percent == 0)
979	literals++;
980    }
981  *pattail = 0;
982
983  /* Chop ARGV[1] up into words to match against the patterns.  */
984
985  wordtail = &wordhead;
986  while ((p = find_next_token (&word_iterator, &len)) != 0)
987    {
988      struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
989
990      *wordtail = word;
991      wordtail = &word->next;
992
993      if (*word_iterator != '\0')
994	++word_iterator;
995
996      p[len] = '\0';
997      word->str = p;
998      word->length = len;
999      word->matched = 0;
1000      word->chain = 0;
1001      words++;
1002    }
1003  *wordtail = 0;
1004
1005  /* Only use a hash table if arg list lengths justifies the cost.  */
1006  hashing = (literals >= 2 && (literals * words) >= 10);
1007  if (hashing)
1008    {
1009      hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
1010      for (wp = wordhead; wp != 0; wp = wp->next)
1011	{
1012	  struct a_word *owp = hash_insert (&a_word_table, wp);
1013	  if (owp)
1014	    wp->chain = owp;
1015	}
1016    }
1017
1018  if (words)
1019    {
1020      int doneany = 0;
1021
1022      /* Run each pattern through the words, killing words.  */
1023      for (pp = pathead; pp != 0; pp = pp->next)
1024	{
1025	  if (pp->percent)
1026	    for (wp = wordhead; wp != 0; wp = wp->next)
1027	      wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1028	  else if (hashing)
1029	    {
1030	      struct a_word a_word_key;
1031	      a_word_key.str = pp->str;
1032	      a_word_key.length = pp->length;
1033	      wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1034	      while (wp)
1035		{
1036		  wp->matched |= 1;
1037		  wp = wp->chain;
1038		}
1039	    }
1040	  else
1041	    for (wp = wordhead; wp != 0; wp = wp->next)
1042	      wp->matched |= (wp->length == pp->length
1043			      && strneq (pp->str, wp->str, wp->length));
1044	}
1045
1046      /* Output the words that matched (or didn't, for filter-out).  */
1047      for (wp = wordhead; wp != 0; wp = wp->next)
1048	if (is_filter ? wp->matched : !wp->matched)
1049	  {
1050	    o = variable_buffer_output (o, wp->str, strlen (wp->str));
1051	    o = variable_buffer_output (o, " ", 1);
1052	    doneany = 1;
1053	  }
1054
1055      if (doneany)
1056	/* Kill the last space.  */
1057	--o;
1058    }
1059
1060  for (pp = pathead; pp != 0; pp = pp->next)
1061    pp->str[pp->length] = pp->save_c;
1062
1063  if (hashing)
1064    hash_free (&a_word_table, 0);
1065
1066  return o;
1067}
1068
1069
1070static char *
1071func_strip (o, argv, funcname)
1072     char *o;
1073     char **argv;
1074     const char *funcname;
1075{
1076  char *p = argv[0];
1077  int doneany =0;
1078
1079  while (*p != '\0')
1080    {
1081      int i=0;
1082      char *word_start=0;
1083
1084      while (isspace ((unsigned char)*p))
1085	++p;
1086      word_start = p;
1087      for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1088	{}
1089      if (!i)
1090	break;
1091      o = variable_buffer_output (o, word_start, i);
1092      o = variable_buffer_output (o, " ", 1);
1093      doneany = 1;
1094    }
1095
1096  if (doneany)
1097    /* Kill the last space.  */
1098    --o;
1099  return o;
1100}
1101
1102/*
1103  Print a warning or fatal message.
1104*/
1105static char *
1106func_error (o, argv, funcname)
1107     char *o;
1108     char **argv;
1109     const char *funcname;
1110{
1111  char **argvp;
1112  char *msg, *p;
1113  int len;
1114
1115  /* The arguments will be broken on commas.  Rather than create yet
1116     another special case where function arguments aren't broken up,
1117     just create a format string that puts them back together.  */
1118  for (len=0, argvp=argv; *argvp != 0; ++argvp)
1119    len += strlen (*argvp) + 2;
1120
1121  p = msg = (char *) alloca (len + 1);
1122
1123  for (argvp=argv; argvp[1] != 0; ++argvp)
1124    {
1125      strcpy (p, *argvp);
1126      p += strlen (*argvp);
1127      *(p++) = ',';
1128      *(p++) = ' ';
1129    }
1130  strcpy (p, *argvp);
1131
1132  if (*funcname == 'e')
1133    fatal (reading_file, "%s", msg);
1134
1135  /* The warning function expands to the empty string.  */
1136  error (reading_file, "%s", msg);
1137
1138  return o;
1139}
1140
1141
1142/*
1143  chop argv[0] into words, and sort them.
1144 */
1145static char *
1146func_sort (o, argv, funcname)
1147     char *o;
1148     char **argv;
1149     const char *funcname;
1150{
1151  char **words = 0;
1152  int nwords = 0;
1153  register int wordi = 0;
1154
1155  /* Chop ARGV[0] into words and put them in WORDS.  */
1156  char *t = argv[0];
1157  char *p;
1158  unsigned int len;
1159  int i;
1160
1161  while ((p = find_next_token (&t, &len)) != 0)
1162    {
1163      if (wordi >= nwords - 1)
1164	{
1165	  nwords = (2 * nwords) + 5;
1166	  words = (char **) xrealloc ((char *) words,
1167				      nwords * sizeof (char *));
1168	}
1169      words[wordi++] = savestring (p, len);
1170    }
1171
1172  if (!wordi)
1173    return o;
1174
1175  /* Now sort the list of words.  */
1176  qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1177
1178  /* Now write the sorted list.  */
1179  for (i = 0; i < wordi; ++i)
1180    {
1181      len = strlen (words[i]);
1182      if (i == wordi - 1 || strlen (words[i + 1]) != len
1183          || strcmp (words[i], words[i + 1]))
1184        {
1185          o = variable_buffer_output (o, words[i], len);
1186          o = variable_buffer_output (o, " ", 1);
1187        }
1188      free (words[i]);
1189    }
1190  /* Kill the last space.  */
1191  --o;
1192
1193  free (words);
1194
1195  return o;
1196}
1197
1198/*
1199  $(if condition,true-part[,false-part])
1200
1201  CONDITION is false iff it evaluates to an empty string.  White
1202  space before and after condition are stripped before evaluation.
1203
1204  If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1205  evaluated (if it exists).  Because only one of the two PARTs is evaluated,
1206  you can use $(if ...) to create side-effects (with $(shell ...), for
1207  example).
1208*/
1209
1210static char *
1211func_if (o, argv, funcname)
1212     char *o;
1213     char **argv;
1214     const char *funcname;
1215{
1216  char *begp = argv[0];
1217  char *endp = begp + strlen (argv[0]);
1218  int result = 0;
1219
1220  /* Find the result of the condition: if we have a value, and it's not
1221     empty, the condition is true.  If we don't have a value, or it's the
1222     empty string, then it's false.  */
1223
1224  strip_whitespace (&begp, &endp);
1225
1226  if (begp < endp)
1227    {
1228      char *expansion = expand_argument (begp, NULL);
1229
1230      result = strlen (expansion);
1231      free (expansion);
1232    }
1233
1234  /* If the result is true (1) we want to eval the first argument, and if
1235     it's false (0) we want to eval the second.  If the argument doesn't
1236     exist we do nothing, otherwise expand it and add to the buffer.  */
1237
1238  argv += 1 + !result;
1239
1240  if (argv[0])
1241    {
1242      char *expansion;
1243
1244      expansion = expand_argument (argv[0], NULL);
1245
1246      o = variable_buffer_output (o, expansion, strlen (expansion));
1247
1248      free (expansion);
1249    }
1250
1251  return o;
1252}
1253
1254static char *
1255func_wildcard (o, argv, funcname)
1256     char *o;
1257     char **argv;
1258     const char *funcname;
1259{
1260
1261#ifdef _AMIGA
1262   o = wildcard_expansion (argv[0], o);
1263#else
1264   char *p = string_glob (argv[0]);
1265   o = variable_buffer_output (o, p, strlen (p));
1266#endif
1267   return o;
1268}
1269
1270/*
1271  $(eval <makefile string>)
1272
1273  Always resolves to the empty string.
1274
1275  Treat the arguments as a segment of makefile, and parse them.
1276*/
1277
1278static char *
1279func_eval (o, argv, funcname)
1280     char *o;
1281     char **argv;
1282     const char *funcname;
1283{
1284  eval_buffer (argv[0]);
1285
1286  return o;
1287}
1288
1289
1290static char *
1291func_value (o, argv, funcname)
1292     char *o;
1293     char **argv;
1294     const char *funcname;
1295{
1296  /* Look up the variable.  */
1297  struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1298
1299  /* Copy its value into the output buffer without expanding it.  */
1300  if (v)
1301    o = variable_buffer_output (o, v->value, strlen(v->value));
1302
1303  return o;
1304}
1305
1306/*
1307  \r  is replaced on UNIX as well. Is this desirable?
1308 */
1309void
1310fold_newlines (buffer, length)
1311     char *buffer;
1312     int *length;
1313{
1314  char *dst = buffer;
1315  char *src = buffer;
1316  char *last_nonnl = buffer -1;
1317  src[*length] = 0;
1318  for (; *src != '\0'; ++src)
1319    {
1320      if (src[0] == '\r' && src[1] == '\n')
1321	continue;
1322      if (*src == '\n')
1323	{
1324	  *dst++ = ' ';
1325	}
1326      else
1327	{
1328	  last_nonnl = dst;
1329	  *dst++ = *src;
1330	}
1331    }
1332  *(++last_nonnl) = '\0';
1333  *length = last_nonnl - buffer;
1334}
1335
1336
1337
1338int shell_function_pid = 0, shell_function_completed;
1339
1340
1341#ifdef WINDOWS32
1342/*untested*/
1343
1344#include <windows.h>
1345#include <io.h>
1346#include "sub_proc.h"
1347
1348
1349void
1350windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1351{
1352  SECURITY_ATTRIBUTES saAttr;
1353  HANDLE hIn;
1354  HANDLE hErr;
1355  HANDLE hChildOutRd;
1356  HANDLE hChildOutWr;
1357  HANDLE hProcess;
1358
1359
1360  saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1361  saAttr.bInheritHandle = TRUE;
1362  saAttr.lpSecurityDescriptor = NULL;
1363
1364  if (DuplicateHandle (GetCurrentProcess(),
1365		      GetStdHandle(STD_INPUT_HANDLE),
1366		      GetCurrentProcess(),
1367		      &hIn,
1368		      0,
1369		      TRUE,
1370		      DUPLICATE_SAME_ACCESS) == FALSE) {
1371    fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1372	   GetLastError());
1373
1374  }
1375  if (DuplicateHandle(GetCurrentProcess(),
1376		      GetStdHandle(STD_ERROR_HANDLE),
1377		      GetCurrentProcess(),
1378		      &hErr,
1379		      0,
1380		      TRUE,
1381		      DUPLICATE_SAME_ACCESS) == FALSE) {
1382    fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1383	   GetLastError());
1384  }
1385
1386  if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1387    fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1388
1389  hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1390
1391  if (!hProcess)
1392    fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1393
1394  /* make sure that CreateProcess() has Path it needs */
1395  sync_Path_environment();
1396
1397  if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1398    /* register process for wait */
1399    process_register(hProcess);
1400
1401    /* set the pid for returning to caller */
1402    *pid_p = (int) hProcess;
1403
1404  /* set up to read data from child */
1405  pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1406
1407  /* this will be closed almost right away */
1408  pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1409  } else {
1410    /* reap/cleanup the failed process */
1411	process_cleanup(hProcess);
1412
1413    /* close handles which were duplicated, they weren't used */
1414	CloseHandle(hIn);
1415	CloseHandle(hErr);
1416
1417	/* close pipe handles, they won't be used */
1418	CloseHandle(hChildOutRd);
1419	CloseHandle(hChildOutWr);
1420
1421    /* set status for return */
1422    pipedes[0] = pipedes[1] = -1;
1423    *pid_p = -1;
1424  }
1425}
1426#endif
1427
1428
1429#ifdef __MSDOS__
1430FILE *
1431msdos_openpipe (int* pipedes, int *pidp, char *text)
1432{
1433  FILE *fpipe=0;
1434  /* MSDOS can't fork, but it has `popen'.  */
1435  struct variable *sh = lookup_variable ("SHELL", 5);
1436  int e;
1437  extern int dos_command_running, dos_status;
1438
1439  /* Make sure not to bother processing an empty line.  */
1440  while (isblank ((unsigned char)*text))
1441    ++text;
1442  if (*text == '\0')
1443    return 0;
1444
1445  if (sh)
1446    {
1447      char buf[PATH_MAX + 7];
1448      /* This makes sure $SHELL value is used by $(shell), even
1449	 though the target environment is not passed to it.  */
1450      sprintf (buf, "SHELL=%s", sh->value);
1451      putenv (buf);
1452    }
1453
1454  e = errno;
1455  errno = 0;
1456  dos_command_running = 1;
1457  dos_status = 0;
1458  /* If dos_status becomes non-zero, it means the child process
1459     was interrupted by a signal, like SIGINT or SIGQUIT.  See
1460     fatal_error_signal in commands.c.  */
1461  fpipe = popen (text, "rt");
1462  dos_command_running = 0;
1463  if (!fpipe || dos_status)
1464    {
1465      pipedes[0] = -1;
1466      *pidp = -1;
1467      if (dos_status)
1468	errno = EINTR;
1469      else if (errno == 0)
1470	errno = ENOMEM;
1471      shell_function_completed = -1;
1472    }
1473  else
1474    {
1475      pipedes[0] = fileno (fpipe);
1476      *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1477      errno = e;
1478      shell_function_completed = 1;
1479    }
1480  return fpipe;
1481}
1482#endif
1483
1484/*
1485  Do shell spawning, with the naughty bits for different OSes.
1486 */
1487
1488#ifdef VMS
1489
1490/* VMS can't do $(shell ...)  */
1491#define func_shell 0
1492
1493#else
1494#ifndef _AMIGA
1495static char *
1496func_shell (o, argv, funcname)
1497     char *o;
1498     char **argv;
1499     const char *funcname;
1500{
1501  char* batch_filename = NULL;
1502  int i;
1503
1504#ifdef __MSDOS__
1505  FILE *fpipe;
1506#endif
1507  char **command_argv;
1508  char *error_prefix;
1509  char **envp;
1510  int pipedes[2];
1511  int pid;
1512
1513#ifndef __MSDOS__
1514  /* Construct the argument list.  */
1515  command_argv = construct_command_argv (argv[0],
1516					 (char **) NULL, (struct file *) 0,
1517                                         &batch_filename);
1518  if (command_argv == 0)
1519    return o;
1520#endif
1521
1522  /* Using a target environment for `shell' loses in cases like:
1523     export var = $(shell echo foobie)
1524     because target_environment hits a loop trying to expand $(var)
1525     to put it in the environment.  This is even more confusing when
1526     var was not explicitly exported, but just appeared in the
1527     calling environment.  */
1528
1529  envp = environ;
1530
1531  /* For error messages.  */
1532  if (reading_file != 0)
1533    {
1534      error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1535      sprintf (error_prefix,
1536	       "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1537    }
1538  else
1539    error_prefix = "";
1540
1541#ifdef WINDOWS32
1542  windows32_openpipe (pipedes, &pid, command_argv, envp);
1543
1544  if (pipedes[0] < 0) {
1545	/* open of the pipe failed, mark as failed execution */
1546    shell_function_completed = -1;
1547
1548	return o;
1549  } else
1550#else /* WINDOWS32 */
1551
1552# ifdef __MSDOS__
1553  fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1554  if (pipedes[0] < 0)
1555    {
1556      perror_with_name (error_prefix, "pipe");
1557      return o;
1558    }
1559# else
1560  if (pipe (pipedes) < 0)
1561    {
1562      perror_with_name (error_prefix, "pipe");
1563      return o;
1564    }
1565
1566  pid = vfork ();
1567  if (pid < 0)
1568    perror_with_name (error_prefix, "fork");
1569  else if (pid == 0)
1570    child_execute_job (0, pipedes[1], command_argv, envp);
1571  else
1572# endif /* ! __MSDOS__ */
1573
1574#endif /* WINDOWS32 */
1575    {
1576      /* We are the parent.  */
1577
1578      char *buffer;
1579      unsigned int maxlen;
1580      int cc;
1581
1582      /* Record the PID for reap_children.  */
1583      shell_function_pid = pid;
1584#ifndef  __MSDOS__
1585      shell_function_completed = 0;
1586
1587      /* Free the storage only the child needed.  */
1588      free (command_argv[0]);
1589      free ((char *) command_argv);
1590
1591      /* Close the write side of the pipe.  */
1592      (void) close (pipedes[1]);
1593#endif
1594
1595      /* Set up and read from the pipe.  */
1596
1597      maxlen = 200;
1598      buffer = (char *) xmalloc (maxlen + 1);
1599
1600      /* Read from the pipe until it gets EOF.  */
1601      for (i = 0; ; i += cc)
1602	{
1603	  if (i == maxlen)
1604	    {
1605	      maxlen += 512;
1606	      buffer = (char *) xrealloc (buffer, maxlen + 1);
1607	    }
1608
1609	  cc = read (pipedes[0], &buffer[i], maxlen - i);
1610	  if (cc <= 0)
1611	    break;
1612	}
1613      buffer[i] = '\0';
1614
1615      /* Close the read side of the pipe.  */
1616#ifdef  __MSDOS__
1617      if (fpipe)
1618	(void) pclose (fpipe);
1619#else
1620      (void) close (pipedes[0]);
1621#endif
1622
1623      /* Loop until child_handler sets shell_function_completed
1624	 to the status of our child shell.  */
1625      while (shell_function_completed == 0)
1626	reap_children (1, 0);
1627
1628      if (batch_filename) {
1629	DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1630                       batch_filename));
1631	remove (batch_filename);
1632	free (batch_filename);
1633      }
1634      shell_function_pid = 0;
1635
1636      /* The child_handler function will set shell_function_completed
1637	 to 1 when the child dies normally, or to -1 if it
1638	 dies with status 127, which is most likely an exec fail.  */
1639
1640      if (shell_function_completed == -1)
1641	{
1642	  /* This most likely means that the execvp failed,
1643	     so we should just write out the error message
1644	     that came in over the pipe from the child.  */
1645	  fputs (buffer, stderr);
1646	  fflush (stderr);
1647	}
1648      else
1649	{
1650	  /* The child finished normally.  Replace all
1651	     newlines in its output with spaces, and put
1652	     that in the variable output buffer.  */
1653	  fold_newlines (buffer, &i);
1654	  o = variable_buffer_output (o, buffer, i);
1655	}
1656
1657      free (buffer);
1658    }
1659
1660  return o;
1661}
1662
1663#else	/* _AMIGA */
1664
1665/* Do the Amiga version of func_shell.  */
1666
1667static char *
1668func_shell (char *o, char **argv, const char *funcname)
1669{
1670  /* Amiga can't fork nor spawn, but I can start a program with
1671     redirection of my choice.  However, this means that we
1672     don't have an opportunity to reopen stdout to trap it.  Thus,
1673     we save our own stdout onto a new descriptor and dup a temp
1674     file's descriptor onto our stdout temporarily.  After we
1675     spawn the shell program, we dup our own stdout back to the
1676     stdout descriptor.  The buffer reading is the same as above,
1677     except that we're now reading from a file.  */
1678
1679#include <dos/dos.h>
1680#include <proto/dos.h>
1681
1682  BPTR child_stdout;
1683  char tmp_output[FILENAME_MAX];
1684  unsigned int maxlen = 200;
1685  int cc, i;
1686  char * buffer, * ptr;
1687  char ** aptr;
1688  int len = 0;
1689  char* batch_filename = NULL;
1690
1691  /* Construct the argument list.  */
1692  command_argv = construct_command_argv (argv[0], (char **) NULL,
1693                                         (struct file *) 0, &batch_filename);
1694  if (command_argv == 0)
1695    return o;
1696
1697  /* Note the mktemp() is a security hole, but this only runs on Amiga.
1698     Ideally we would use main.c:open_tmpfile(), but this uses a special
1699     Open(), not fopen(), and I'm not familiar enough with the code to mess
1700     with it.  */
1701  strcpy (tmp_output, "t:MakeshXXXXXXXX");
1702  mktemp (tmp_output);
1703  child_stdout = Open (tmp_output, MODE_NEWFILE);
1704
1705  for (aptr=command_argv; *aptr; aptr++)
1706    len += strlen (*aptr) + 1;
1707
1708  buffer = xmalloc (len + 1);
1709  ptr = buffer;
1710
1711  for (aptr=command_argv; *aptr; aptr++)
1712    {
1713      strcpy (ptr, *aptr);
1714      ptr += strlen (ptr) + 1;
1715      *ptr ++ = ' ';
1716      *ptr = 0;
1717    }
1718
1719  ptr[-1] = '\n';
1720
1721  Execute (buffer, NULL, child_stdout);
1722  free (buffer);
1723
1724  Close (child_stdout);
1725
1726  child_stdout = Open (tmp_output, MODE_OLDFILE);
1727
1728  buffer = xmalloc (maxlen);
1729  i = 0;
1730  do
1731    {
1732      if (i == maxlen)
1733	{
1734	  maxlen += 512;
1735	  buffer = (char *) xrealloc (buffer, maxlen + 1);
1736	}
1737
1738      cc = Read (child_stdout, &buffer[i], maxlen - i);
1739      if (cc > 0)
1740	i += cc;
1741    } while (cc > 0);
1742
1743  Close (child_stdout);
1744
1745  fold_newlines (buffer, &i);
1746  o = variable_buffer_output (o, buffer, i);
1747  free (buffer);
1748  return o;
1749}
1750#endif  /* _AMIGA */
1751#endif  /* !VMS */
1752
1753#ifdef EXPERIMENTAL
1754
1755/*
1756  equality. Return is string-boolean, ie, the empty string is false.
1757 */
1758static char *
1759func_eq (char* o, char **argv, char *funcname)
1760{
1761  int result = ! strcmp (argv[0], argv[1]);
1762  o = variable_buffer_output (o,  result ? "1" : "", result);
1763  return o;
1764}
1765
1766
1767/*
1768  string-boolean not operator.
1769 */
1770static char *
1771func_not (char* o, char **argv, char *funcname)
1772{
1773  char * s = argv[0];
1774  int result = 0;
1775  while (isspace ((unsigned char)*s))
1776    s++;
1777  result = ! (*s);
1778  o = variable_buffer_output (o,  result ? "1" : "", result);
1779  return o;
1780}
1781#endif
1782
1783
1784/* Lookup table for builtin functions.
1785
1786   This doesn't have to be sorted; we use a straight lookup.  We might gain
1787   some efficiency by moving most often used functions to the start of the
1788   table.
1789
1790   If MAXIMUM_ARGS is 0, that means there is no maximum and all
1791   comma-separated values are treated as arguments.
1792
1793   EXPAND_ARGS means that all arguments should be expanded before invocation.
1794   Functions that do namespace tricks (foreach) don't automatically expand.  */
1795
1796static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1797
1798
1799static struct function_table_entry function_table_init[] =
1800{
1801 /* Name/size */                    /* MIN MAX EXP? Function */
1802  { STRING_SIZE_TUPLE("addprefix"),     2,  2,  1,  func_addsuffix_addprefix},
1803  { STRING_SIZE_TUPLE("addsuffix"),     2,  2,  1,  func_addsuffix_addprefix},
1804  { STRING_SIZE_TUPLE("basename"),      0,  1,  1,  func_basename_dir},
1805  { STRING_SIZE_TUPLE("dir"),           0,  1,  1,  func_basename_dir},
1806  { STRING_SIZE_TUPLE("notdir"),        0,  1,  1,  func_notdir_suffix},
1807  { STRING_SIZE_TUPLE("subst"),         3,  3,  1,  func_subst},
1808  { STRING_SIZE_TUPLE("suffix"),        0,  1,  1,  func_notdir_suffix},
1809  { STRING_SIZE_TUPLE("filter"),        2,  2,  1,  func_filter_filterout},
1810  { STRING_SIZE_TUPLE("filter-out"),    2,  2,  1,  func_filter_filterout},
1811  { STRING_SIZE_TUPLE("findstring"),    2,  2,  1,  func_findstring},
1812  { STRING_SIZE_TUPLE("firstword"),     0,  1,  1,  func_firstword},
1813  { STRING_SIZE_TUPLE("join"),          2,  2,  1,  func_join},
1814  { STRING_SIZE_TUPLE("patsubst"),      3,  3,  1,  func_patsubst},
1815  { STRING_SIZE_TUPLE("shell"),         0,  1,  1,  func_shell},
1816  { STRING_SIZE_TUPLE("sort"),          0,  1,  1,  func_sort},
1817  { STRING_SIZE_TUPLE("strip"),         0,  1,  1,  func_strip},
1818  { STRING_SIZE_TUPLE("wildcard"),      0,  1,  1,  func_wildcard},
1819  { STRING_SIZE_TUPLE("word"),          2,  2,  1,  func_word},
1820  { STRING_SIZE_TUPLE("wordlist"),      3,  3,  1,  func_wordlist},
1821  { STRING_SIZE_TUPLE("words"),         0,  1,  1,  func_words},
1822  { STRING_SIZE_TUPLE("origin"),        0,  1,  1,  func_origin},
1823  { STRING_SIZE_TUPLE("foreach"),       3,  3,  0,  func_foreach},
1824  { STRING_SIZE_TUPLE("call"),          1,  0,  1,  func_call},
1825  { STRING_SIZE_TUPLE("error"),         0,  1,  1,  func_error},
1826  { STRING_SIZE_TUPLE("warning"),       0,  1,  1,  func_error},
1827  { STRING_SIZE_TUPLE("if"),            2,  3,  0,  func_if},
1828  { STRING_SIZE_TUPLE("value"),         0,  1,  1,  func_value},
1829  { STRING_SIZE_TUPLE("eval"),          0,  1,  1,  func_eval},
1830#ifdef EXPERIMENTAL
1831  { STRING_SIZE_TUPLE("eq"),            2,  2,  1,  func_eq},
1832  { STRING_SIZE_TUPLE("not"),           0,  1,  1,  func_not},
1833#endif
1834};
1835
1836#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1837
1838
1839/* These must come after the definition of function_table.  */
1840
1841static char *
1842expand_builtin_function (o, argc, argv, entry_p)
1843     char *o;
1844     int argc;
1845     char **argv;
1846     struct function_table_entry *entry_p;
1847{
1848  if (argc < (int)entry_p->minimum_args)
1849    fatal (reading_file,
1850           _("Insufficient number of arguments (%d) to function `%s'"),
1851           argc, entry_p->name);
1852
1853  /* I suppose technically some function could do something with no
1854     arguments, but so far none do, so just test it for all functions here
1855     rather than in each one.  We can change it later if necessary.  */
1856
1857  if (!argc)
1858    return o;
1859
1860  if (!entry_p->func_ptr)
1861    fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1862           entry_p->name);
1863
1864  return entry_p->func_ptr (o, argv, entry_p->name);
1865}
1866
1867/* Check for a function invocation in *STRINGP.  *STRINGP points at the
1868   opening ( or { and is not null-terminated.  If a function invocation
1869   is found, expand it into the buffer at *OP, updating *OP, incrementing
1870   *STRINGP past the reference and returning nonzero.  If not, return zero.  */
1871
1872int
1873handle_function (op, stringp)
1874     char **op;
1875     char **stringp;
1876{
1877  const struct function_table_entry *entry_p;
1878  char openparen = (*stringp)[0];
1879  char closeparen = openparen == '(' ? ')' : '}';
1880  char *beg;
1881  char *end;
1882  int count = 0;
1883  register char *p;
1884  char **argv, **argvp;
1885  int nargs;
1886
1887  beg = *stringp + 1;
1888
1889  entry_p = lookup_function (beg);
1890
1891  if (!entry_p)
1892    return 0;
1893
1894  /* We found a builtin function.  Find the beginning of its arguments (skip
1895     whitespace after the name).  */
1896
1897  beg = next_token (beg + entry_p->len);
1898
1899  /* Find the end of the function invocation, counting nested use of
1900     whichever kind of parens we use.  Since we're looking, count commas
1901     to get a rough estimate of how many arguments we might have.  The
1902     count might be high, but it'll never be low.  */
1903
1904  for (nargs=1, end=beg; *end != '\0'; ++end)
1905    if (*end == ',')
1906      ++nargs;
1907    else if (*end == openparen)
1908      ++count;
1909    else if (*end == closeparen && --count < 0)
1910      break;
1911
1912  if (count >= 0)
1913    fatal (reading_file,
1914	   _("unterminated call to function `%s': missing `%c'"),
1915	   entry_p->name, closeparen);
1916
1917  *stringp = end;
1918
1919  /* Get some memory to store the arg pointers.  */
1920  argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
1921
1922  /* Chop the string into arguments, then a nul.  As soon as we hit
1923     MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1924     last argument.
1925
1926     If we're expanding, store pointers to the expansion of each one.  If
1927     not, make a duplicate of the string and point into that, nul-terminating
1928     each argument.  */
1929
1930  if (!entry_p->expand_args)
1931    {
1932      int len = end - beg;
1933
1934      p = xmalloc (len+1);
1935      memcpy (p, beg, len);
1936      p[len] = '\0';
1937      beg = p;
1938      end = beg + len;
1939    }
1940
1941  for (p=beg, nargs=0; p <= end; ++argvp)
1942    {
1943      char *next;
1944
1945      ++nargs;
1946
1947      if (nargs == entry_p->maximum_args
1948          || (! (next = find_next_argument (openparen, closeparen, p, end))))
1949        next = end;
1950
1951      if (entry_p->expand_args)
1952        *argvp = expand_argument (p, next);
1953      else
1954        {
1955          *argvp = p;
1956          *next = '\0';
1957        }
1958
1959      p = next + 1;
1960    }
1961  *argvp = NULL;
1962
1963  /* Finally!  Run the function...  */
1964  *op = expand_builtin_function (*op, nargs, argv, entry_p);
1965
1966  /* Free memory.  */
1967  if (entry_p->expand_args)
1968    for (argvp=argv; *argvp != 0; ++argvp)
1969      free (*argvp);
1970  else
1971    free (beg);
1972
1973  return 1;
1974}
1975
1976
1977/* User-defined functions.  Expand the first argument as either a builtin
1978   function or a make variable, in the context of the rest of the arguments
1979   assigned to $1, $2, ... $N.  $0 is the name of the function.  */
1980
1981static char *
1982func_call (o, argv, funcname)
1983     char *o;
1984     char **argv;
1985     const char *funcname;
1986{
1987  char *fname;
1988  char *cp;
1989  char *body;
1990  int flen;
1991  int i;
1992  const struct function_table_entry *entry_p;
1993  struct variable *v;
1994
1995  /* There is no way to define a variable with a space in the name, so strip
1996     leading and trailing whitespace as a favor to the user.  */
1997  fname = argv[0];
1998  while (*fname != '\0' && isspace ((unsigned char)*fname))
1999    ++fname;
2000
2001  cp = fname + strlen (fname) - 1;
2002  while (cp > fname && isspace ((unsigned char)*cp))
2003    --cp;
2004  cp[1] = '\0';
2005
2006  /* Calling nothing is a no-op */
2007  if (*fname == '\0')
2008    return o;
2009
2010  /* Are we invoking a builtin function?  */
2011
2012  entry_p = lookup_function (fname);
2013
2014  if (entry_p)
2015    {
2016      /* How many arguments do we have?  */
2017      for (i=0; argv[i+1]; ++i)
2018  	;
2019
2020      return expand_builtin_function (o, i, argv+1, entry_p);
2021    }
2022
2023  /* Not a builtin, so the first argument is the name of a variable to be
2024     expanded and interpreted as a function.  Find it.  */
2025  flen = strlen (fname);
2026
2027  v = lookup_variable (fname, flen);
2028
2029  if (v == 0)
2030    warn_undefined (fname, flen);
2031
2032  if (v == 0 || *v->value == '\0')
2033    return o;
2034
2035  body = (char *) alloca (flen + 4);
2036  body[0] = '$';
2037  body[1] = '(';
2038  memcpy (body + 2, fname, flen);
2039  body[flen+2] = ')';
2040  body[flen+3] = '\0';
2041
2042  /* Set up arguments $(1) .. $(N).  $(0) is the function name.  */
2043
2044  push_new_variable_scope ();
2045
2046  for (i=0; *argv; ++i, ++argv)
2047    {
2048      char num[11];
2049
2050      sprintf (num, "%d", i);
2051      define_variable (num, strlen (num), *argv, o_automatic, 0);
2052    }
2053
2054  /* Expand the body in the context of the arguments, adding the result to
2055     the variable buffer.  */
2056
2057  v->exp_count = EXP_COUNT_MAX;
2058
2059  o = variable_expand_string (o, body, flen+3);
2060
2061  v->exp_count = 0;
2062
2063  pop_variable_scope ();
2064
2065  return o + strlen (o);
2066}
2067
2068void
2069hash_init_function_table ()
2070{
2071  hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2072	     function_table_entry_hash_1, function_table_entry_hash_2,
2073	     function_table_entry_hash_cmp);
2074  hash_load (&function_table, function_table_init,
2075	     FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
2076}
2077