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