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