Ensure that .ONESHELL works with .SHELLFLAGS options containing whitespace.
[make.git] / function.c
blobd68bc4de7c52c27d9793f6a85a2fc3f1bee872c5
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
4 2012 Free Software Foundation, Inc.
5 This file is part of GNU Make.
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.
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.
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/>. */
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"
27 #ifdef _AMIGA
28 #include "amiga.h"
29 #endif
32 struct function_table_entry
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);
42 static unsigned long
43 function_table_entry_hash_1 (const void *keyv)
45 const struct function_table_entry *key = keyv;
46 return_STRING_N_HASH_1 (key->name, key->len);
49 static unsigned long
50 function_table_entry_hash_2 (const void *keyv)
52 const struct function_table_entry *key = keyv;
53 return_STRING_N_HASH_2 (key->name, key->len);
56 static int
57 function_table_entry_hash_cmp (const void *xv, const void *yv)
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);
67 static struct hash_table function_table;
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. */
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)
80 const char *t = text;
81 const char *p;
83 if (slen == 0 && !by_word)
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;
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
100 p = strstr (t, subst);
101 if (p == 0)
103 /* No more matches. Output everything left on the end. */
104 o = variable_buffer_output (o, t, strlen (t));
105 return o;
109 /* Output everything before this occurrence of the string to replace. */
110 if (p > t)
111 o = variable_buffer_output (o, t, p - t);
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);
125 /* Advance T past the string to be replaced. */
126 t = p + slen;
127 } while (*t != '\0');
129 return o;
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.
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)
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;
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)
158 replace_prepercent_len = replace_percent - replace - 1;
159 replace_postpercent_len = strlen (replace_percent);
161 else
163 replace_prepercent_len = strlen (replace);
164 replace_postpercent_len = 0;
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);
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);
177 while ((t = find_next_token (&text, &len)) != 0)
179 int fail = 0;
181 /* Is it big enough to match? */
182 if (len < pattern_prepercent_len + pattern_postpercent_len)
183 fail = 1;
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;
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;
200 if (fail)
201 /* It didn't match. Output the string. */
202 o = variable_buffer_output (o, t, len);
203 else
205 /* It matched. Output the replacement. */
207 /* Output the part of the replacement before the %. */
208 o = variable_buffer_output (o, replace, replace_prepercent_len);
210 if (replace_percent != 0)
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);
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))
227 o = variable_buffer_output (o, " ", 1);
228 doneany = 1;
231 if (doneany)
232 /* Kill the last space. */
233 --o;
235 return o;
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.
248 char *
249 patsubst_expand (char *o, const char *text, char *pattern, char *replace)
251 const char *pattern_percent = find_percent (pattern);
252 const char *replace_percent = find_percent (replace);
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;
260 return patsubst_expand_pat (o, text, pattern, replace,
261 pattern_percent, replace_percent);
265 /* Look up a function by name. */
267 static const struct function_table_entry *
268 lookup_function (const char *s)
270 const char *e = s;
272 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
273 e++;
274 if (*e == '\0' || isblank ((unsigned char) *e))
276 struct function_table_entry function_table_entry_key;
277 function_table_entry_key.name = s;
278 function_table_entry_key.len = e - s;
280 return hash_find_item (&function_table, &function_table_entry_key);
282 return 0;
286 /* Return 1 if PATTERN matches STR, 0 if not. */
289 pattern_matches (const char *pattern, const char *percent, const char *str)
291 unsigned int sfxlen, strlength;
293 if (percent == 0)
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;
304 sfxlen = strlen (percent + 1);
305 strlength = strlen (str);
307 if (strlength < (percent - pattern) + sfxlen
308 || !strneq (pattern, str, percent - pattern))
309 return 0;
311 return !strcmp (percent + 1, str + (strlength - sfxlen));
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.
319 If no next argument is found, return NULL.
322 static char *
323 find_next_argument (char startparen, char endparen,
324 const char *ptr, const char *end)
326 int count = 0;
328 for (; ptr < end; ++ptr)
329 if (*ptr == startparen)
330 ++count;
332 else if (*ptr == endparen)
334 --count;
335 if (count < 0)
336 return NULL;
339 else if (*ptr == ',' && !count)
340 return (char *)ptr;
342 /* We didn't find anything. */
343 return NULL;
347 /* Glob-expand LINE. The returned pointer is
348 only good until the next call to string_glob. */
350 static char *
351 string_glob (char *line)
353 static char *result = 0;
354 static unsigned int length;
355 struct nameseq *chain;
356 unsigned int idx;
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);
364 if (result == 0)
366 length = 100;
367 result = xmalloc (100);
370 idx = 0;
371 while (chain != 0)
373 struct nameseq *next = chain->next;
374 unsigned int len = strlen (chain->name);
376 if (idx + len + 1 > length)
378 length += (len + 1) * 2;
379 result = xrealloc (result, length);
381 memcpy (&result[idx], chain->name, len);
382 idx += len;
383 result[idx++] = ' ';
385 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
386 free ((char *)chain->name);
387 free (chain);
388 chain = next;
391 /* Kill the last space and terminate the string. */
392 if (idx == 0)
393 result[0] = '\0';
394 else
395 result[idx - 1] = '\0';
397 return result;
401 Builtin functions
404 static char *
405 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
407 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
408 return o;
412 static char *
413 func_join (char *o, char **argv, const char *funcname UNUSED)
415 int doneany = 0;
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];
427 unsigned int len1, len2;
429 tp = find_next_token (&list1_iterator, &len1);
430 if (tp != 0)
431 o = variable_buffer_output (o, tp, len1);
433 pp = find_next_token (&list2_iterator, &len2);
434 if (pp != 0)
435 o = variable_buffer_output (o, pp, len2);
437 if (tp != 0 || pp != 0)
439 o = variable_buffer_output (o, " ", 1);
440 doneany = 1;
443 while (tp != 0 || pp != 0);
444 if (doneany)
445 /* Kill the last blank. */
446 --o;
448 return o;
452 static char *
453 func_origin (char *o, char **argv, const char *funcname UNUSED)
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)
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;
489 return o;
492 static char *
493 func_flavor (char *o, char **argv, const char *funcname UNUSED)
495 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
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);
505 return o;
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
519 static char *
520 func_notdir_suffix (char *o, char **argv, const char *funcname)
522 /* Expand the argument. */
523 const char *list_iterator = argv[0];
524 const char *p2;
525 int doneany =0;
526 unsigned int len=0;
528 int is_suffix = streq (funcname, "suffix");
529 int is_notdir = !is_suffix;
530 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
532 const char *p = p2 + len;
535 while (p >= p2 && (!is_suffix || *p != '.'))
537 if (IS_PATHSEP (*p))
538 break;
539 --p;
542 if (p >= p2)
544 if (is_notdir)
545 ++p;
546 else if (*p != '.')
547 continue;
548 o = variable_buffer_output (o, p, len - (p - p2));
550 #ifdef HAVE_DOS_PATHS
551 /* Handle the case of "d:foo/bar". */
552 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
554 p = p2 + 2;
555 o = variable_buffer_output (o, p, len - (p - p2));
557 #endif
558 else if (is_notdir)
559 o = variable_buffer_output (o, p2, len);
561 if (is_notdir || p >= p2)
563 o = variable_buffer_output (o, " ", 1);
564 doneany = 1;
568 if (doneany)
569 /* Kill last space. */
570 --o;
572 return o;
576 static char *
577 func_basename_dir (char *o, char **argv, const char *funcname)
579 /* Expand the argument. */
580 const char *p3 = argv[0];
581 const char *p2;
582 int doneany=0;
583 unsigned int len=0;
585 int is_basename= streq (funcname, "basename");
586 int is_dir= !is_basename;
588 while ((p2 = find_next_token (&p3, &len)) != 0)
590 const char *p = p2 + len;
591 while (p >= p2 && (!is_basename || *p != '.'))
593 if (IS_PATHSEP (*p))
594 break;
595 --p;
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);
621 o = variable_buffer_output (o, " ", 1);
622 doneany = 1;
625 if (doneany)
626 /* Kill last space. */
627 --o;
629 return o;
632 static char *
633 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
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;
640 int doneany = 0;
641 const char *p;
642 unsigned int len;
644 while ((p = find_next_token (&list_iterator, &len)) != 0)
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;
655 if (doneany)
656 /* Kill last space. */
657 --o;
659 return o;
662 static char *
663 func_subst (char *o, char **argv, const char *funcname UNUSED)
665 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
666 strlen (argv[1]), 0);
668 return o;
672 static char *
673 func_firstword (char *o, char **argv, const char *funcname UNUSED)
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);
679 if (p != 0)
680 o = variable_buffer_output (o, p, i);
682 return o;
685 static char *
686 func_lastword (char *o, char **argv, const char *funcname UNUSED)
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;
693 while ((t = find_next_token (&words, &i)))
694 p = t;
696 if (p != 0)
697 o = variable_buffer_output (o, p, i);
699 return o;
702 static char *
703 func_words (char *o, char **argv, const char *funcname UNUSED)
705 int i = 0;
706 const char *word_iterator = argv[0];
707 char buf[20];
709 while (find_next_token (&word_iterator, NULL) != 0)
710 ++i;
712 sprintf (buf, "%d", i);
713 o = variable_buffer_output (o, buf, strlen (buf));
715 return o;
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.
723 char *
724 strip_whitespace (const char **begpp, const char **endpp)
726 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
727 (*begpp) ++;
728 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
729 (*endpp) --;
730 return (char *)*begpp;
733 static void
734 check_numeric (const char *s, const char *msg)
736 const char *end = s + strlen (s) - 1;
737 const char *beg = s;
738 strip_whitespace (&s, &end);
740 for (; s <= end; ++s)
741 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
742 break;
744 if (s <= end || end - beg < 0)
745 fatal (*expanding_var, "%s: '%s'", msg, beg);
750 static char *
751 func_word (char *o, char **argv, const char *funcname UNUSED)
753 const char *end_p;
754 const char *p;
755 int i;
757 /* Check the first argument. */
758 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
759 i = atoi (argv[0]);
761 if (i == 0)
762 fatal (*expanding_var,
763 _("first argument to `word' function must be greater than 0"));
765 end_p = argv[1];
766 while ((p = find_next_token (&end_p, 0)) != 0)
767 if (--i == 0)
768 break;
770 if (i == 0)
771 o = variable_buffer_output (o, p, end_p - p);
773 return o;
776 static char *
777 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
779 int start, count;
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"));
787 start = atoi (argv[0]);
788 if (start < 1)
789 fatal (*expanding_var,
790 "invalid first argument to `wordlist' function: `%d'", start);
792 count = atoi (argv[1]) - start + 1;
794 if (count > 0)
796 const char *p;
797 const char *end_p = argv[2];
799 /* Find the beginning of the "start"th word. */
800 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
803 if (p)
805 /* Find the end of the "count"th word from start. */
806 while (--count && (find_next_token (&end_p, 0) != 0))
809 /* Return the stuff in the middle. */
810 o = variable_buffer_output (o, p, end_p - p);
814 return o;
817 static char *
818 func_findstring (char *o, char **argv, const char *funcname UNUSED)
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]));
824 return o;
827 static char *
828 func_foreach (char *o, char **argv, const char *funcname UNUSED)
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];
835 int doneany = 0;
836 const char *list_iterator = list;
837 const char *p;
838 unsigned int len;
839 struct variable *var;
841 push_new_variable_scope ();
842 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
844 /* loop through LIST, put the value in VAR and expand BODY */
845 while ((p = find_next_token (&list_iterator, &len)) != 0)
847 char *result = 0;
849 free (var->value);
850 var->value = xstrndup (p, len);
852 result = allocated_variable_expand (body);
854 o = variable_buffer_output (o, result, strlen (result));
855 o = variable_buffer_output (o, " ", 1);
856 doneany = 1;
857 free (result);
860 if (doneany)
861 /* Kill the last space. */
862 --o;
864 pop_variable_scope ();
865 free (varname);
866 free (list);
868 return o;
871 struct a_word
873 struct a_word *next;
874 struct a_word *chain;
875 char *str;
876 int length;
877 int matched;
880 static unsigned long
881 a_word_hash_1 (const void *key)
883 return_STRING_HASH_1 (((struct a_word const *) key)->str);
886 static unsigned long
887 a_word_hash_2 (const void *key)
889 return_STRING_HASH_2 (((struct a_word const *) key)->str);
892 static int
893 a_word_hash_cmp (const void *x, const void *y)
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);
902 struct a_pattern
904 struct a_pattern *next;
905 char *str;
906 char *percent;
907 int length;
910 static char *
911 func_filter_filterout (char *o, char **argv, const char *funcname)
913 struct a_word *wordhead;
914 struct a_word **wordtail;
915 struct a_word *wp;
916 struct a_pattern *pathead;
917 struct a_pattern **pattail;
918 struct a_pattern *pp;
920 struct hash_table a_word_table;
921 int is_filter = streq (funcname, "filter");
922 const char *pat_iterator = argv[0];
923 const char *word_iterator = argv[1];
924 int literals = 0;
925 int words = 0;
926 int hashing = 0;
927 char *p;
928 unsigned int len;
930 /* Chop ARGV[0] up into patterns to match against the words.
931 We don't need to preserve it because our caller frees all the
932 argument memory anyway. */
934 pattail = &pathead;
935 while ((p = find_next_token (&pat_iterator, &len)) != 0)
937 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
939 *pattail = pat;
940 pattail = &pat->next;
942 if (*pat_iterator != '\0')
943 ++pat_iterator;
945 pat->str = p;
946 p[len] = '\0';
947 pat->percent = find_percent (p);
948 if (pat->percent == 0)
949 literals++;
951 /* find_percent() might shorten the string so LEN is wrong. */
952 pat->length = strlen (pat->str);
954 *pattail = 0;
956 /* Chop ARGV[1] up into words to match against the patterns. */
958 wordtail = &wordhead;
959 while ((p = find_next_token (&word_iterator, &len)) != 0)
961 struct a_word *word = alloca (sizeof (struct a_word));
963 *wordtail = word;
964 wordtail = &word->next;
966 if (*word_iterator != '\0')
967 ++word_iterator;
969 p[len] = '\0';
970 word->str = p;
971 word->length = len;
972 word->matched = 0;
973 word->chain = 0;
974 words++;
976 *wordtail = 0;
978 /* Only use a hash table if arg list lengths justifies the cost. */
979 hashing = (literals >= 2 && (literals * words) >= 10);
980 if (hashing)
982 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
983 a_word_hash_cmp);
984 for (wp = wordhead; wp != 0; wp = wp->next)
986 struct a_word *owp = hash_insert (&a_word_table, wp);
987 if (owp)
988 wp->chain = owp;
992 if (words)
994 int doneany = 0;
996 /* Run each pattern through the words, killing words. */
997 for (pp = pathead; pp != 0; pp = pp->next)
999 if (pp->percent)
1000 for (wp = wordhead; wp != 0; wp = wp->next)
1001 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1002 else if (hashing)
1004 struct a_word a_word_key;
1005 a_word_key.str = pp->str;
1006 a_word_key.length = pp->length;
1007 wp = hash_find_item (&a_word_table, &a_word_key);
1008 while (wp)
1010 wp->matched |= 1;
1011 wp = wp->chain;
1014 else
1015 for (wp = wordhead; wp != 0; wp = wp->next)
1016 wp->matched |= (wp->length == pp->length
1017 && strneq (pp->str, wp->str, wp->length));
1020 /* Output the words that matched (or didn't, for filter-out). */
1021 for (wp = wordhead; wp != 0; wp = wp->next)
1022 if (is_filter ? wp->matched : !wp->matched)
1024 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1025 o = variable_buffer_output (o, " ", 1);
1026 doneany = 1;
1029 if (doneany)
1030 /* Kill the last space. */
1031 --o;
1034 if (hashing)
1035 hash_free (&a_word_table, 0);
1037 return o;
1041 static char *
1042 func_strip (char *o, char **argv, const char *funcname UNUSED)
1044 const char *p = argv[0];
1045 int doneany = 0;
1047 while (*p != '\0')
1049 int i=0;
1050 const char *word_start;
1052 while (isspace ((unsigned char)*p))
1053 ++p;
1054 word_start = p;
1055 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1057 if (!i)
1058 break;
1059 o = variable_buffer_output (o, word_start, i);
1060 o = variable_buffer_output (o, " ", 1);
1061 doneany = 1;
1064 if (doneany)
1065 /* Kill the last space. */
1066 --o;
1068 return o;
1072 Print a warning or fatal message.
1074 static char *
1075 func_error (char *o, char **argv, const char *funcname)
1077 char **argvp;
1078 char *msg, *p;
1079 int len;
1081 /* The arguments will be broken on commas. Rather than create yet
1082 another special case where function arguments aren't broken up,
1083 just create a format string that puts them back together. */
1084 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1085 len += strlen (*argvp) + 2;
1087 p = msg = alloca (len + 1);
1089 for (argvp=argv; argvp[1] != 0; ++argvp)
1091 strcpy (p, *argvp);
1092 p += strlen (*argvp);
1093 *(p++) = ',';
1094 *(p++) = ' ';
1096 strcpy (p, *argvp);
1098 switch (*funcname) {
1099 case 'e':
1100 fatal (reading_file, "%s", msg);
1102 case 'w':
1103 error (reading_file, "%s", msg);
1104 break;
1106 case 'i':
1107 printf ("%s\n", msg);
1108 fflush(stdout);
1109 break;
1111 default:
1112 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1115 /* The warning function expands to the empty string. */
1116 return o;
1121 chop argv[0] into words, and sort them.
1123 static char *
1124 func_sort (char *o, char **argv, const char *funcname UNUSED)
1126 const char *t;
1127 char **words;
1128 int wordi;
1129 char *p;
1130 unsigned int len;
1131 int i;
1133 /* Find the maximum number of words we'll have. */
1134 t = argv[0];
1135 wordi = 0;
1136 while ((p = find_next_token (&t, NULL)) != 0)
1138 ++t;
1139 ++wordi;
1142 words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
1144 /* Now assign pointers to each string in the array. */
1145 t = argv[0];
1146 wordi = 0;
1147 while ((p = find_next_token (&t, &len)) != 0)
1149 ++t;
1150 p[len] = '\0';
1151 words[wordi++] = p;
1154 if (wordi)
1156 /* Now sort the list of words. */
1157 qsort (words, wordi, sizeof (char *), alpha_compare);
1159 /* Now write the sorted list, uniquified. */
1160 for (i = 0; i < wordi; ++i)
1162 len = strlen (words[i]);
1163 if (i == wordi - 1 || strlen (words[i + 1]) != len
1164 || strcmp (words[i], words[i + 1]))
1166 o = variable_buffer_output (o, words[i], len);
1167 o = variable_buffer_output (o, " ", 1);
1171 /* Kill the last space. */
1172 --o;
1175 free (words);
1177 return o;
1181 $(if condition,true-part[,false-part])
1183 CONDITION is false iff it evaluates to an empty string. White
1184 space before and after condition are stripped before evaluation.
1186 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1187 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1188 you can use $(if ...) to create side-effects (with $(shell ...), for
1189 example).
1192 static char *
1193 func_if (char *o, char **argv, const char *funcname UNUSED)
1195 const char *begp = argv[0];
1196 const char *endp = begp + strlen (argv[0]) - 1;
1197 int result = 0;
1199 /* Find the result of the condition: if we have a value, and it's not
1200 empty, the condition is true. If we don't have a value, or it's the
1201 empty string, then it's false. */
1203 strip_whitespace (&begp, &endp);
1205 if (begp <= endp)
1207 char *expansion = expand_argument (begp, endp+1);
1209 result = strlen (expansion);
1210 free (expansion);
1213 /* If the result is true (1) we want to eval the first argument, and if
1214 it's false (0) we want to eval the second. If the argument doesn't
1215 exist we do nothing, otherwise expand it and add to the buffer. */
1217 argv += 1 + !result;
1219 if (*argv)
1221 char *expansion = expand_argument (*argv, NULL);
1223 o = variable_buffer_output (o, expansion, strlen (expansion));
1225 free (expansion);
1228 return o;
1232 $(or condition1[,condition2[,condition3[...]]])
1234 A CONDITION is false iff it evaluates to an empty string. White
1235 space before and after CONDITION are stripped before evaluation.
1237 CONDITION1 is evaluated. If it's true, then this is the result of
1238 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1239 the conditions are true, the expansion is the empty string.
1241 Once a CONDITION is true no further conditions are evaluated
1242 (short-circuiting).
1245 static char *
1246 func_or (char *o, char **argv, const char *funcname UNUSED)
1248 for ( ; *argv ; ++argv)
1250 const char *begp = *argv;
1251 const char *endp = begp + strlen (*argv) - 1;
1252 char *expansion;
1253 int result = 0;
1255 /* Find the result of the condition: if it's false keep going. */
1257 strip_whitespace (&begp, &endp);
1259 if (begp > endp)
1260 continue;
1262 expansion = expand_argument (begp, endp+1);
1263 result = strlen (expansion);
1265 /* If the result is false keep going. */
1266 if (!result)
1268 free (expansion);
1269 continue;
1272 /* It's true! Keep this result and return. */
1273 o = variable_buffer_output (o, expansion, result);
1274 free (expansion);
1275 break;
1278 return o;
1282 $(and condition1[,condition2[,condition3[...]]])
1284 A CONDITION is false iff it evaluates to an empty string. White
1285 space before and after CONDITION are stripped before evaluation.
1287 CONDITION1 is evaluated. If it's false, then this is the result of
1288 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1289 the conditions are true, the expansion is the result of the last condition.
1291 Once a CONDITION is false no further conditions are evaluated
1292 (short-circuiting).
1295 static char *
1296 func_and (char *o, char **argv, const char *funcname UNUSED)
1298 char *expansion;
1299 int result;
1301 while (1)
1303 const char *begp = *argv;
1304 const char *endp = begp + strlen (*argv) - 1;
1306 /* An empty condition is always false. */
1307 strip_whitespace (&begp, &endp);
1308 if (begp > endp)
1309 return o;
1311 expansion = expand_argument (begp, endp+1);
1312 result = strlen (expansion);
1314 /* If the result is false, stop here: we're done. */
1315 if (!result)
1316 break;
1318 /* Otherwise the result is true. If this is the last one, keep this
1319 result and quit. Otherwise go on to the next one! */
1321 if (*(++argv))
1322 free (expansion);
1323 else
1325 o = variable_buffer_output (o, expansion, result);
1326 break;
1330 free (expansion);
1332 return o;
1335 static char *
1336 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1338 #ifdef _AMIGA
1339 o = wildcard_expansion (argv[0], o);
1340 #else
1341 char *p = string_glob (argv[0]);
1342 o = variable_buffer_output (o, p, strlen (p));
1343 #endif
1344 return o;
1348 $(eval <makefile string>)
1350 Always resolves to the empty string.
1352 Treat the arguments as a segment of makefile, and parse them.
1355 static char *
1356 func_eval (char *o, char **argv, const char *funcname UNUSED)
1358 char *buf;
1359 unsigned int len;
1361 /* Eval the buffer. Pop the current variable buffer setting so that the
1362 eval'd code can use its own without conflicting. */
1364 install_variable_buffer (&buf, &len);
1366 eval_buffer (argv[0]);
1368 restore_variable_buffer (buf, len);
1370 return o;
1374 static char *
1375 func_value (char *o, char **argv, const char *funcname UNUSED)
1377 /* Look up the variable. */
1378 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1380 /* Copy its value into the output buffer without expanding it. */
1381 if (v)
1382 o = variable_buffer_output (o, v->value, strlen(v->value));
1384 return o;
1388 \r is replaced on UNIX as well. Is this desirable?
1390 static void
1391 fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
1393 char *dst = buffer;
1394 char *src = buffer;
1395 char *last_nonnl = buffer - 1;
1396 src[*length] = 0;
1397 for (; *src != '\0'; ++src)
1399 if (src[0] == '\r' && src[1] == '\n')
1400 continue;
1401 if (*src == '\n')
1403 *dst++ = ' ';
1405 else
1407 last_nonnl = dst;
1408 *dst++ = *src;
1412 if (!trim_newlines && (last_nonnl < (dst - 2)))
1413 last_nonnl = dst - 2;
1415 *(++last_nonnl) = '\0';
1416 *length = last_nonnl - buffer;
1421 int shell_function_pid = 0, shell_function_completed;
1424 #ifdef WINDOWS32
1425 /*untested*/
1427 #include <windows.h>
1428 #include <io.h>
1429 #include "sub_proc.h"
1432 void
1433 windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
1435 SECURITY_ATTRIBUTES saAttr;
1436 HANDLE hIn = INVALID_HANDLE_VALUE;
1437 HANDLE hErr = INVALID_HANDLE_VALUE;
1438 HANDLE hChildOutRd;
1439 HANDLE hChildOutWr;
1440 HANDLE hProcess, tmpIn, tmpErr;
1441 DWORD e;
1443 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1444 saAttr.bInheritHandle = TRUE;
1445 saAttr.lpSecurityDescriptor = NULL;
1447 /* Standard handles returned by GetStdHandle can be NULL or
1448 INVALID_HANDLE_VALUE if the parent process closed them. If that
1449 happens, we open the null device and pass its handle to
1450 process_begin below as the corresponding handle to inherit. */
1451 tmpIn = GetStdHandle(STD_INPUT_HANDLE);
1452 if (DuplicateHandle (GetCurrentProcess(),
1453 tmpIn,
1454 GetCurrentProcess(),
1455 &hIn,
1457 TRUE,
1458 DUPLICATE_SAME_ACCESS) == FALSE) {
1459 if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
1460 tmpIn = CreateFile("NUL", GENERIC_READ,
1461 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1462 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1463 if (tmpIn != INVALID_HANDLE_VALUE
1464 && DuplicateHandle(GetCurrentProcess(),
1465 tmpIn,
1466 GetCurrentProcess(),
1467 &hIn,
1469 TRUE,
1470 DUPLICATE_SAME_ACCESS) == FALSE)
1471 CloseHandle(tmpIn);
1473 if (hIn == INVALID_HANDLE_VALUE)
1474 fatal (NILF, _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
1476 tmpErr = GetStdHandle(STD_ERROR_HANDLE);
1477 if (DuplicateHandle(GetCurrentProcess(),
1478 tmpErr,
1479 GetCurrentProcess(),
1480 &hErr,
1482 TRUE,
1483 DUPLICATE_SAME_ACCESS) == FALSE) {
1484 if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
1485 tmpErr = CreateFile("NUL", GENERIC_WRITE,
1486 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1487 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1488 if (tmpErr != INVALID_HANDLE_VALUE
1489 && DuplicateHandle(GetCurrentProcess(),
1490 tmpErr,
1491 GetCurrentProcess(),
1492 &hErr,
1494 TRUE,
1495 DUPLICATE_SAME_ACCESS) == FALSE)
1496 CloseHandle(tmpErr);
1498 if (hErr == INVALID_HANDLE_VALUE)
1499 fatal (NILF, _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
1502 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1503 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1505 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1507 if (!hProcess)
1508 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1510 /* make sure that CreateProcess() has Path it needs */
1511 sync_Path_environment();
1512 /* `sync_Path_environment' may realloc `environ', so take note of
1513 the new value. */
1514 envp = environ;
1516 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1517 /* register process for wait */
1518 process_register(hProcess);
1520 /* set the pid for returning to caller */
1521 *pid_p = (pid_t) hProcess;
1523 /* set up to read data from child */
1524 pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
1526 /* this will be closed almost right away */
1527 pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
1528 } else {
1529 /* reap/cleanup the failed process */
1530 process_cleanup(hProcess);
1532 /* close handles which were duplicated, they weren't used */
1533 if (hIn != INVALID_HANDLE_VALUE)
1534 CloseHandle(hIn);
1535 if (hErr != INVALID_HANDLE_VALUE)
1536 CloseHandle(hErr);
1538 /* close pipe handles, they won't be used */
1539 CloseHandle(hChildOutRd);
1540 CloseHandle(hChildOutWr);
1542 /* set status for return */
1543 pipedes[0] = pipedes[1] = -1;
1544 *pid_p = (pid_t)-1;
1547 #endif
1550 #ifdef __MSDOS__
1551 FILE *
1552 msdos_openpipe (int* pipedes, int *pidp, char *text)
1554 FILE *fpipe=0;
1555 /* MSDOS can't fork, but it has `popen'. */
1556 struct variable *sh = lookup_variable ("SHELL", 5);
1557 int e;
1558 extern int dos_command_running, dos_status;
1560 /* Make sure not to bother processing an empty line. */
1561 while (isblank ((unsigned char)*text))
1562 ++text;
1563 if (*text == '\0')
1564 return 0;
1566 if (sh)
1568 char buf[PATH_MAX + 7];
1569 /* This makes sure $SHELL value is used by $(shell), even
1570 though the target environment is not passed to it. */
1571 sprintf (buf, "SHELL=%s", sh->value);
1572 putenv (buf);
1575 e = errno;
1576 errno = 0;
1577 dos_command_running = 1;
1578 dos_status = 0;
1579 /* If dos_status becomes non-zero, it means the child process
1580 was interrupted by a signal, like SIGINT or SIGQUIT. See
1581 fatal_error_signal in commands.c. */
1582 fpipe = popen (text, "rt");
1583 dos_command_running = 0;
1584 if (!fpipe || dos_status)
1586 pipedes[0] = -1;
1587 *pidp = -1;
1588 if (dos_status)
1589 errno = EINTR;
1590 else if (errno == 0)
1591 errno = ENOMEM;
1592 shell_function_completed = -1;
1594 else
1596 pipedes[0] = fileno (fpipe);
1597 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1598 errno = e;
1599 shell_function_completed = 1;
1601 return fpipe;
1603 #endif
1606 Do shell spawning, with the naughty bits for different OSes.
1609 #ifdef VMS
1611 /* VMS can't do $(shell ...) */
1613 char *
1614 func_shell_base (char *o, char **argv, int trim_newlines)
1616 fprintf (stderr, "This platform does not support shell\n");
1617 die (EXIT_FAILURE);
1620 #define func_shell 0
1622 #else
1623 #ifndef _AMIGA
1624 char *
1625 func_shell_base (char *o, char **argv, int trim_newlines)
1627 char *batch_filename = NULL;
1629 #ifdef __MSDOS__
1630 FILE *fpipe;
1631 #endif
1632 char **command_argv;
1633 const char *error_prefix;
1634 char **envp;
1635 int pipedes[2];
1636 pid_t pid;
1638 #ifndef __MSDOS__
1639 #ifdef WINDOWS32
1640 /* Reset just_print_flag. This is needed on Windows when batch files
1641 are used to run the commands, because we normally refrain from
1642 creating batch files under -n. */
1643 int j_p_f = just_print_flag;
1645 just_print_flag = 0;
1646 #endif
1647 /* Construct the argument list. */
1648 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1649 &batch_filename);
1650 if (command_argv == 0)
1652 #ifdef WINDOWS32
1653 just_print_flag = j_p_f;
1654 #endif
1655 return o;
1657 #endif
1659 /* Using a target environment for `shell' loses in cases like:
1660 export var = $(shell echo foobie)
1661 because target_environment hits a loop trying to expand $(var)
1662 to put it in the environment. This is even more confusing when
1663 var was not explicitly exported, but just appeared in the
1664 calling environment.
1666 See Savannah bug #10593.
1668 envp = target_environment (NILF);
1671 envp = environ;
1673 /* For error messages. */
1674 if (reading_file && reading_file->filenm)
1676 char *p = alloca (strlen (reading_file->filenm)+11+4);
1677 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1678 error_prefix = p;
1680 else
1681 error_prefix = "";
1683 #if defined(__MSDOS__)
1684 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1685 if (pipedes[0] < 0)
1687 perror_with_name (error_prefix, "pipe");
1688 return o;
1690 #elif defined(WINDOWS32)
1691 windows32_openpipe (pipedes, &pid, command_argv, envp);
1692 /* Restore the value of just_print_flag. */
1693 just_print_flag = j_p_f;
1695 if (pipedes[0] < 0)
1697 /* Open of the pipe failed, mark as failed execution. */
1698 shell_function_completed = -1;
1699 return o;
1701 else
1702 #else
1703 if (pipe (pipedes) < 0)
1705 perror_with_name (error_prefix, "pipe");
1706 return o;
1709 # ifdef __EMX__
1710 /* close some handles that are unnecessary for the child process */
1711 CLOSE_ON_EXEC(pipedes[1]);
1712 CLOSE_ON_EXEC(pipedes[0]);
1713 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1714 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1715 if (pid < 0)
1716 perror_with_name (error_prefix, "spawn");
1717 # else /* ! __EMX__ */
1718 pid = fork ();
1719 if (pid < 0)
1720 perror_with_name (error_prefix, "fork");
1721 else if (pid == 0)
1722 child_execute_job (0, pipedes[1], command_argv, envp);
1723 else
1724 # endif
1725 #endif
1727 /* We are the parent. */
1728 char *buffer;
1729 unsigned int maxlen, i;
1730 int cc;
1732 /* Record the PID for reap_children. */
1733 shell_function_pid = pid;
1734 #ifndef __MSDOS__
1735 shell_function_completed = 0;
1737 /* Free the storage only the child needed. */
1738 free (command_argv[0]);
1739 free (command_argv);
1741 /* Close the write side of the pipe. We test for -1, since
1742 pipedes[1] is -1 on MS-Windows, and some versions of MS
1743 libraries barf when `close' is called with -1. */
1744 if (pipedes[1] >= 0)
1745 close (pipedes[1]);
1746 #endif
1748 /* Set up and read from the pipe. */
1750 maxlen = 200;
1751 buffer = xmalloc (maxlen + 1);
1753 /* Read from the pipe until it gets EOF. */
1754 for (i = 0; ; i += cc)
1756 if (i == maxlen)
1758 maxlen += 512;
1759 buffer = xrealloc (buffer, maxlen + 1);
1762 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1763 if (cc <= 0)
1764 break;
1766 buffer[i] = '\0';
1768 /* Close the read side of the pipe. */
1769 #ifdef __MSDOS__
1770 if (fpipe)
1771 (void) pclose (fpipe);
1772 #else
1773 (void) close (pipedes[0]);
1774 #endif
1776 /* Loop until child_handler or reap_children() sets
1777 shell_function_completed to the status of our child shell. */
1778 while (shell_function_completed == 0)
1779 reap_children (1, 0);
1781 if (batch_filename) {
1782 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1783 batch_filename));
1784 remove (batch_filename);
1785 free (batch_filename);
1787 shell_function_pid = 0;
1789 /* The child_handler function will set shell_function_completed
1790 to 1 when the child dies normally, or to -1 if it
1791 dies with status 127, which is most likely an exec fail. */
1793 if (shell_function_completed == -1)
1795 /* This likely means that the execvp failed, so we should just
1796 write the error message in the pipe from the child. */
1797 fputs (buffer, stderr);
1798 fflush (stderr);
1800 else
1802 /* The child finished normally. Replace all newlines in its output
1803 with spaces, and put that in the variable output buffer. */
1804 fold_newlines (buffer, &i, trim_newlines);
1805 o = variable_buffer_output (o, buffer, i);
1808 free (buffer);
1811 return o;
1814 #else /* _AMIGA */
1816 /* Do the Amiga version of func_shell. */
1818 char *
1819 func_shell_base (char *o, char **argv, int trim_newlines)
1821 /* Amiga can't fork nor spawn, but I can start a program with
1822 redirection of my choice. However, this means that we
1823 don't have an opportunity to reopen stdout to trap it. Thus,
1824 we save our own stdout onto a new descriptor and dup a temp
1825 file's descriptor onto our stdout temporarily. After we
1826 spawn the shell program, we dup our own stdout back to the
1827 stdout descriptor. The buffer reading is the same as above,
1828 except that we're now reading from a file. */
1830 #include <dos/dos.h>
1831 #include <proto/dos.h>
1833 BPTR child_stdout;
1834 char tmp_output[FILENAME_MAX];
1835 unsigned int maxlen = 200, i;
1836 int cc;
1837 char * buffer, * ptr;
1838 char ** aptr;
1839 int len = 0;
1840 char* batch_filename = NULL;
1842 /* Construct the argument list. */
1843 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1844 &batch_filename);
1845 if (command_argv == 0)
1846 return o;
1848 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1849 Ideally we would use main.c:open_tmpfile(), but this uses a special
1850 Open(), not fopen(), and I'm not familiar enough with the code to mess
1851 with it. */
1852 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1853 mktemp (tmp_output);
1854 child_stdout = Open (tmp_output, MODE_NEWFILE);
1856 for (aptr=command_argv; *aptr; aptr++)
1857 len += strlen (*aptr) + 1;
1859 buffer = xmalloc (len + 1);
1860 ptr = buffer;
1862 for (aptr=command_argv; *aptr; aptr++)
1864 strcpy (ptr, *aptr);
1865 ptr += strlen (ptr) + 1;
1866 *ptr ++ = ' ';
1867 *ptr = 0;
1870 ptr[-1] = '\n';
1872 Execute (buffer, NULL, child_stdout);
1873 free (buffer);
1875 Close (child_stdout);
1877 child_stdout = Open (tmp_output, MODE_OLDFILE);
1879 buffer = xmalloc (maxlen);
1880 i = 0;
1883 if (i == maxlen)
1885 maxlen += 512;
1886 buffer = xrealloc (buffer, maxlen + 1);
1889 cc = Read (child_stdout, &buffer[i], maxlen - i);
1890 if (cc > 0)
1891 i += cc;
1892 } while (cc > 0);
1894 Close (child_stdout);
1896 fold_newlines (buffer, &i, trim_newlines);
1897 o = variable_buffer_output (o, buffer, i);
1898 free (buffer);
1899 return o;
1901 #endif /* _AMIGA */
1903 char *
1904 func_shell (char *o, char **argv, const char *funcname UNUSED)
1906 return func_shell_base (o, argv, 1);
1908 #endif /* !VMS */
1910 #ifdef EXPERIMENTAL
1913 equality. Return is string-boolean, ie, the empty string is false.
1915 static char *
1916 func_eq (char *o, char **argv, char *funcname)
1918 int result = ! strcmp (argv[0], argv[1]);
1919 o = variable_buffer_output (o, result ? "1" : "", result);
1920 return o;
1925 string-boolean not operator.
1927 static char *
1928 func_not (char *o, char **argv, char *funcname)
1930 const char *s = argv[0];
1931 int result = 0;
1932 while (isspace ((unsigned char)*s))
1933 s++;
1934 result = ! (*s);
1935 o = variable_buffer_output (o, result ? "1" : "", result);
1936 return o;
1938 #endif
1941 #ifdef HAVE_DOS_PATHS
1942 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1943 #define ROOT_LEN 3
1944 #else
1945 #define IS_ABSOLUTE(n) (n[0] == '/')
1946 #define ROOT_LEN 1
1947 #endif
1949 /* Return the absolute name of file NAME which does not contain any `.',
1950 `..' components nor any repeated path separators ('/'). */
1952 static char *
1953 abspath (const char *name, char *apath)
1955 char *dest;
1956 const char *start, *end, *apath_limit;
1957 unsigned long root_len = ROOT_LEN;
1959 if (name[0] == '\0' || apath == NULL)
1960 return NULL;
1962 apath_limit = apath + GET_PATH_MAX;
1964 if (!IS_ABSOLUTE(name))
1966 /* It is unlikely we would make it until here but just to make sure. */
1967 if (!starting_directory)
1968 return NULL;
1970 strcpy (apath, starting_directory);
1972 #ifdef HAVE_DOS_PATHS
1973 if (IS_PATHSEP(name[0]))
1975 if (IS_PATHSEP(name[1]))
1977 /* A UNC. Don't prepend a drive letter. */
1978 apath[0] = name[0];
1979 apath[1] = name[1];
1980 root_len = 2;
1982 /* We have /foo, an absolute file name except for the drive
1983 letter. Assume the missing drive letter is the current
1984 drive, which we can get if we remove from starting_directory
1985 everything past the root directory. */
1986 apath[root_len] = '\0';
1988 #endif
1990 dest = strchr (apath, '\0');
1992 else
1994 strncpy (apath, name, root_len);
1995 apath[root_len] = '\0';
1996 dest = apath + root_len;
1997 /* Get past the root, since we already copied it. */
1998 name += root_len;
1999 #ifdef HAVE_DOS_PATHS
2000 if (!IS_PATHSEP(apath[2]))
2002 /* Convert d:foo into d:./foo and increase root_len. */
2003 apath[2] = '.';
2004 apath[3] = '/';
2005 dest++;
2006 root_len++;
2007 /* strncpy above copied one character too many. */
2008 name--;
2010 else
2011 apath[2] = '/'; /* make sure it's a forward slash */
2012 #endif
2015 for (start = end = name; *start != '\0'; start = end)
2017 unsigned long len;
2019 /* Skip sequence of multiple path-separators. */
2020 while (IS_PATHSEP(*start))
2021 ++start;
2023 /* Find end of path component. */
2024 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
2027 len = end - start;
2029 if (len == 0)
2030 break;
2031 else if (len == 1 && start[0] == '.')
2032 /* nothing */;
2033 else if (len == 2 && start[0] == '.' && start[1] == '.')
2035 /* Back up to previous component, ignore if at root already. */
2036 if (dest > apath + root_len)
2037 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
2039 else
2041 if (!IS_PATHSEP(dest[-1]))
2042 *dest++ = '/';
2044 if (dest + len >= apath_limit)
2045 return NULL;
2047 dest = memcpy (dest, start, len);
2048 dest += len;
2049 *dest = '\0';
2053 /* Unless it is root strip trailing separator. */
2054 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
2055 --dest;
2057 *dest = '\0';
2059 return apath;
2063 static char *
2064 func_realpath (char *o, char **argv, const char *funcname UNUSED)
2066 /* Expand the argument. */
2067 const char *p = argv[0];
2068 const char *path = 0;
2069 int doneany = 0;
2070 unsigned int len = 0;
2071 #ifndef HAVE_REALPATH
2072 struct stat st;
2073 #endif
2074 PATH_VAR (in);
2075 PATH_VAR (out);
2077 while ((path = find_next_token (&p, &len)) != 0)
2079 if (len < GET_PATH_MAX)
2081 strncpy (in, path, len);
2082 in[len] = '\0';
2084 if (
2085 #ifdef HAVE_REALPATH
2086 realpath (in, out)
2087 #else
2088 abspath (in, out) && stat (out, &st) == 0
2089 #endif
2092 o = variable_buffer_output (o, out, strlen (out));
2093 o = variable_buffer_output (o, " ", 1);
2094 doneany = 1;
2099 /* Kill last space. */
2100 if (doneany)
2101 --o;
2103 return o;
2106 static char *
2107 func_file (char *o, char **argv, const char *funcname UNUSED)
2109 char *fn = argv[0];
2111 if (fn[0] == '>')
2113 FILE *fp;
2114 const char *mode = "w";
2116 /* We are writing a file. */
2117 ++fn;
2118 if (fn[0] == '>')
2120 mode = "a";
2121 ++fn;
2123 fn = next_token (fn);
2125 fp = fopen (fn, mode);
2126 if (fp == NULL)
2127 fatal (reading_file, _("open: %s: %s"), fn, strerror (errno));
2128 else
2130 int l = strlen (argv[1]);
2131 int nl = (l == 0 || argv[1][l-1] != '\n');
2133 if (fputs (argv[1], fp) == EOF || (nl && fputc('\n', fp) == EOF))
2134 fatal (reading_file, _("write: %s: %s"), fn, strerror (errno));
2136 fclose (fp);
2139 else
2140 fatal (reading_file, _("Invalid file operation: %s"), fn);
2142 return o;
2145 static char *
2146 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2148 /* Expand the argument. */
2149 const char *p = argv[0];
2150 const char *path = 0;
2151 int doneany = 0;
2152 unsigned int len = 0;
2153 PATH_VAR (in);
2154 PATH_VAR (out);
2156 while ((path = find_next_token (&p, &len)) != 0)
2158 if (len < GET_PATH_MAX)
2160 strncpy (in, path, len);
2161 in[len] = '\0';
2163 if (abspath (in, out))
2165 o = variable_buffer_output (o, out, strlen (out));
2166 o = variable_buffer_output (o, " ", 1);
2167 doneany = 1;
2172 /* Kill last space. */
2173 if (doneany)
2174 --o;
2176 return o;
2179 /* Lookup table for builtin functions.
2181 This doesn't have to be sorted; we use a straight lookup. We might gain
2182 some efficiency by moving most often used functions to the start of the
2183 table.
2185 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2186 comma-separated values are treated as arguments.
2188 EXPAND_ARGS means that all arguments should be expanded before invocation.
2189 Functions that do namespace tricks (foreach) don't automatically expand. */
2191 static char *func_call (char *o, char **argv, const char *funcname);
2194 static struct function_table_entry function_table_init[] =
2196 /* Name/size */ /* MIN MAX EXP? Function */
2197 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2198 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2199 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2200 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2201 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2202 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2203 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2204 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2205 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2206 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2207 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2208 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2209 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2210 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2211 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2212 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2213 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2214 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2215 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2216 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2217 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2218 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2219 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2220 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2221 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2222 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2223 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2224 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2225 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2226 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2227 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2228 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2229 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2230 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2231 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2232 { STRING_SIZE_TUPLE("file"), 1, 2, 1, func_file},
2233 #ifdef EXPERIMENTAL
2234 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2235 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2236 #endif
2239 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2242 /* These must come after the definition of function_table. */
2244 static char *
2245 expand_builtin_function (char *o, int argc, char **argv,
2246 const struct function_table_entry *entry_p)
2248 if (argc < (int)entry_p->minimum_args)
2249 fatal (*expanding_var,
2250 _("insufficient number of arguments (%d) to function `%s'"),
2251 argc, entry_p->name);
2253 /* I suppose technically some function could do something with no
2254 arguments, but so far none do, so just test it for all functions here
2255 rather than in each one. We can change it later if necessary. */
2257 if (!argc)
2258 return o;
2260 if (!entry_p->func_ptr)
2261 fatal (*expanding_var,
2262 _("unimplemented on this platform: function `%s'"), entry_p->name);
2264 return entry_p->func_ptr (o, argv, entry_p->name);
2267 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2268 opening ( or { and is not null-terminated. If a function invocation
2269 is found, expand it into the buffer at *OP, updating *OP, incrementing
2270 *STRINGP past the reference and returning nonzero. If not, return zero. */
2273 handle_function (char **op, const char **stringp)
2275 const struct function_table_entry *entry_p;
2276 char openparen = (*stringp)[0];
2277 char closeparen = openparen == '(' ? ')' : '}';
2278 const char *beg;
2279 const char *end;
2280 int count = 0;
2281 char *abeg = NULL;
2282 char **argv, **argvp;
2283 int nargs;
2285 beg = *stringp + 1;
2287 entry_p = lookup_function (beg);
2289 if (!entry_p)
2290 return 0;
2292 /* We found a builtin function. Find the beginning of its arguments (skip
2293 whitespace after the name). */
2295 beg = next_token (beg + entry_p->len);
2297 /* Find the end of the function invocation, counting nested use of
2298 whichever kind of parens we use. Since we're looking, count commas
2299 to get a rough estimate of how many arguments we might have. The
2300 count might be high, but it'll never be low. */
2302 for (nargs=1, end=beg; *end != '\0'; ++end)
2303 if (*end == ',')
2304 ++nargs;
2305 else if (*end == openparen)
2306 ++count;
2307 else if (*end == closeparen && --count < 0)
2308 break;
2310 if (count >= 0)
2311 fatal (*expanding_var,
2312 _("unterminated call to function `%s': missing `%c'"),
2313 entry_p->name, closeparen);
2315 *stringp = end;
2317 /* Get some memory to store the arg pointers. */
2318 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2320 /* Chop the string into arguments, then a nul. As soon as we hit
2321 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2322 last argument.
2324 If we're expanding, store pointers to the expansion of each one. If
2325 not, make a duplicate of the string and point into that, nul-terminating
2326 each argument. */
2328 if (entry_p->expand_args)
2330 const char *p;
2331 for (p=beg, nargs=0; p <= end; ++argvp)
2333 const char *next;
2335 ++nargs;
2337 if (nargs == entry_p->maximum_args
2338 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2339 next = end;
2341 *argvp = expand_argument (p, next);
2342 p = next + 1;
2345 else
2347 int len = end - beg;
2348 char *p, *aend;
2350 abeg = xmalloc (len+1);
2351 memcpy (abeg, beg, len);
2352 abeg[len] = '\0';
2353 aend = abeg + len;
2355 for (p=abeg, nargs=0; p <= aend; ++argvp)
2357 char *next;
2359 ++nargs;
2361 if (nargs == entry_p->maximum_args
2362 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2363 next = aend;
2365 *argvp = p;
2366 *next = '\0';
2367 p = next + 1;
2370 *argvp = NULL;
2372 /* Finally! Run the function... */
2373 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2375 /* Free memory. */
2376 if (entry_p->expand_args)
2377 for (argvp=argv; *argvp != 0; ++argvp)
2378 free (*argvp);
2379 else if (abeg)
2380 free (abeg);
2382 return 1;
2386 /* User-defined functions. Expand the first argument as either a builtin
2387 function or a make variable, in the context of the rest of the arguments
2388 assigned to $1, $2, ... $N. $0 is the name of the function. */
2390 static char *
2391 func_call (char *o, char **argv, const char *funcname UNUSED)
2393 static int max_args = 0;
2394 char *fname;
2395 char *cp;
2396 char *body;
2397 int flen;
2398 int i;
2399 int saved_args;
2400 const struct function_table_entry *entry_p;
2401 struct variable *v;
2403 /* There is no way to define a variable with a space in the name, so strip
2404 leading and trailing whitespace as a favor to the user. */
2405 fname = argv[0];
2406 while (*fname != '\0' && isspace ((unsigned char)*fname))
2407 ++fname;
2409 cp = fname + strlen (fname) - 1;
2410 while (cp > fname && isspace ((unsigned char)*cp))
2411 --cp;
2412 cp[1] = '\0';
2414 /* Calling nothing is a no-op */
2415 if (*fname == '\0')
2416 return o;
2418 /* Are we invoking a builtin function? */
2420 entry_p = lookup_function (fname);
2421 if (entry_p)
2423 /* How many arguments do we have? */
2424 for (i=0; argv[i+1]; ++i)
2426 return expand_builtin_function (o, i, argv+1, entry_p);
2429 /* Not a builtin, so the first argument is the name of a variable to be
2430 expanded and interpreted as a function. Find it. */
2431 flen = strlen (fname);
2433 v = lookup_variable (fname, flen);
2435 if (v == 0)
2436 warn_undefined (fname, flen);
2438 if (v == 0 || *v->value == '\0')
2439 return o;
2441 body = alloca (flen + 4);
2442 body[0] = '$';
2443 body[1] = '(';
2444 memcpy (body + 2, fname, flen);
2445 body[flen+2] = ')';
2446 body[flen+3] = '\0';
2448 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2450 push_new_variable_scope ();
2452 for (i=0; *argv; ++i, ++argv)
2454 char num[11];
2456 sprintf (num, "%d", i);
2457 define_variable (num, strlen (num), *argv, o_automatic, 0);
2460 /* If the number of arguments we have is < max_args, it means we're inside
2461 a recursive invocation of $(call ...). Fill in the remaining arguments
2462 in the new scope with the empty value, to hide them from this
2463 invocation. */
2465 for (; i < max_args; ++i)
2467 char num[11];
2469 sprintf (num, "%d", i);
2470 define_variable (num, strlen (num), "", o_automatic, 0);
2473 /* Expand the body in the context of the arguments, adding the result to
2474 the variable buffer. */
2476 v->exp_count = EXP_COUNT_MAX;
2478 saved_args = max_args;
2479 max_args = i;
2480 o = variable_expand_string (o, body, flen+3);
2481 max_args = saved_args;
2483 v->exp_count = 0;
2485 pop_variable_scope ();
2487 return o + strlen (o);
2490 void
2491 define_new_function(const struct floc *flocp,
2492 const char *name, int min, int max, int expand,
2493 char *(*func)(char *, char **, const char *))
2495 size_t len = strlen (name);
2496 struct function_table_entry *ent = xmalloc (sizeof (struct function_table_entry));
2498 if (len > 255)
2499 fatal (flocp, _("Function name too long: %s\n"), name);
2500 if (min < 0 || min > 255)
2501 fatal (flocp, _("Invalid minimum argument count (%d) for function %s\n"),
2502 min, name);
2503 if (max < 0 || max > 255 || max < min)
2504 fatal (flocp, _("Invalid maximum argument count (%d) for function %s\n"),
2505 max, name);
2507 ent->name = name;
2508 ent->len = len;
2509 ent->minimum_args = min;
2510 ent->maximum_args = max;
2511 ent->expand_args = expand ? 1 : 0;
2512 ent->func_ptr = func;
2514 hash_insert (&function_table, ent);
2517 void
2518 hash_init_function_table (void)
2520 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2521 function_table_entry_hash_1, function_table_entry_hash_2,
2522 function_table_entry_hash_cmp);
2523 hash_load (&function_table, function_table_init,
2524 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));