* Update to GPLv3
[make.git] / function.c
blob4be234009a3b083e665b7e015b6d8df242d46e9e
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
4 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 = multi_glob (parse_file_seq
359 (&line, '\0', sizeof (struct nameseq),
360 /* We do not want parse_file_seq to strip `./'s.
361 That would break examples like:
362 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
364 sizeof (struct nameseq));
366 if (result == 0)
368 length = 100;
369 result = xmalloc (100);
372 idx = 0;
373 while (chain != 0)
375 const char *name = chain->name;
376 unsigned int len = strlen (name);
378 struct nameseq *next = chain->next;
379 free (chain);
380 chain = next;
382 /* multi_glob will pass names without globbing metacharacters
383 through as is, but we want only files that actually exist. */
384 if (file_exists_p (name))
386 if (idx + len + 1 > length)
388 length += (len + 1) * 2;
389 result = xrealloc (result, length);
391 memcpy (&result[idx], name, len);
392 idx += len;
393 result[idx++] = ' ';
397 /* Kill the last space and terminate the string. */
398 if (idx == 0)
399 result[0] = '\0';
400 else
401 result[idx - 1] = '\0';
403 return result;
407 Builtin functions
410 static char *
411 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
413 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
414 return o;
418 static char *
419 func_join (char *o, char **argv, const char *funcname UNUSED)
421 int doneany = 0;
423 /* Write each word of the first argument directly followed
424 by the corresponding word of the second argument.
425 If the two arguments have a different number of words,
426 the excess words are just output separated by blanks. */
427 const char *tp;
428 const char *pp;
429 const char *list1_iterator = argv[0];
430 const char *list2_iterator = argv[1];
433 unsigned int len1, len2;
435 tp = find_next_token (&list1_iterator, &len1);
436 if (tp != 0)
437 o = variable_buffer_output (o, tp, len1);
439 pp = find_next_token (&list2_iterator, &len2);
440 if (pp != 0)
441 o = variable_buffer_output (o, pp, len2);
443 if (tp != 0 || pp != 0)
445 o = variable_buffer_output (o, " ", 1);
446 doneany = 1;
449 while (tp != 0 || pp != 0);
450 if (doneany)
451 /* Kill the last blank. */
452 --o;
454 return o;
458 static char *
459 func_origin (char *o, char **argv, const char *funcname UNUSED)
461 /* Expand the argument. */
462 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
463 if (v == 0)
464 o = variable_buffer_output (o, "undefined", 9);
465 else
466 switch (v->origin)
468 default:
469 case o_invalid:
470 abort ();
471 break;
472 case o_default:
473 o = variable_buffer_output (o, "default", 7);
474 break;
475 case o_env:
476 o = variable_buffer_output (o, "environment", 11);
477 break;
478 case o_file:
479 o = variable_buffer_output (o, "file", 4);
480 break;
481 case o_env_override:
482 o = variable_buffer_output (o, "environment override", 20);
483 break;
484 case o_command:
485 o = variable_buffer_output (o, "command line", 12);
486 break;
487 case o_override:
488 o = variable_buffer_output (o, "override", 8);
489 break;
490 case o_automatic:
491 o = variable_buffer_output (o, "automatic", 9);
492 break;
495 return o;
498 static char *
499 func_flavor (char *o, char **argv, const char *funcname UNUSED)
501 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
503 if (v == 0)
504 o = variable_buffer_output (o, "undefined", 9);
505 else
506 if (v->recursive)
507 o = variable_buffer_output (o, "recursive", 9);
508 else
509 o = variable_buffer_output (o, "simple", 6);
511 return o;
514 #ifdef VMS
515 # define IS_PATHSEP(c) ((c) == ']')
516 #else
517 # ifdef HAVE_DOS_PATHS
518 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
519 # else
520 # define IS_PATHSEP(c) ((c) == '/')
521 # endif
522 #endif
525 static char *
526 func_notdir_suffix (char *o, char **argv, const char *funcname)
528 /* Expand the argument. */
529 const char *list_iterator = argv[0];
530 const char *p2;
531 int doneany =0;
532 unsigned int len=0;
534 int is_suffix = streq (funcname, "suffix");
535 int is_notdir = !is_suffix;
536 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
538 const char *p = p2 + len;
541 while (p >= p2 && (!is_suffix || *p != '.'))
543 if (IS_PATHSEP (*p))
544 break;
545 --p;
548 if (p >= p2)
550 if (is_notdir)
551 ++p;
552 else if (*p != '.')
553 continue;
554 o = variable_buffer_output (o, p, len - (p - p2));
556 #ifdef HAVE_DOS_PATHS
557 /* Handle the case of "d:foo/bar". */
558 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
560 p = p2 + 2;
561 o = variable_buffer_output (o, p, len - (p - p2));
563 #endif
564 else if (is_notdir)
565 o = variable_buffer_output (o, p2, len);
567 if (is_notdir || p >= p2)
569 o = variable_buffer_output (o, " ", 1);
570 doneany = 1;
574 if (doneany)
575 /* Kill last space. */
576 --o;
578 return o;
582 static char *
583 func_basename_dir (char *o, char **argv, const char *funcname)
585 /* Expand the argument. */
586 const char *p3 = argv[0];
587 const char *p2;
588 int doneany=0;
589 unsigned int len=0;
591 int is_basename= streq (funcname, "basename");
592 int is_dir= !is_basename;
594 while ((p2 = find_next_token (&p3, &len)) != 0)
596 const char *p = p2 + len;
597 while (p >= p2 && (!is_basename || *p != '.'))
599 if (IS_PATHSEP (*p))
600 break;
601 --p;
604 if (p >= p2 && (is_dir))
605 o = variable_buffer_output (o, p2, ++p - p2);
606 else if (p >= p2 && (*p == '.'))
607 o = variable_buffer_output (o, p2, p - p2);
608 #ifdef HAVE_DOS_PATHS
609 /* Handle the "d:foobar" case */
610 else if (p2[0] && p2[1] == ':' && is_dir)
611 o = variable_buffer_output (o, p2, 2);
612 #endif
613 else if (is_dir)
614 #ifdef VMS
615 o = variable_buffer_output (o, "[]", 2);
616 #else
617 #ifndef _AMIGA
618 o = variable_buffer_output (o, "./", 2);
619 #else
620 ; /* Just a nop... */
621 #endif /* AMIGA */
622 #endif /* !VMS */
623 else
624 /* The entire name is the basename. */
625 o = variable_buffer_output (o, p2, len);
627 o = variable_buffer_output (o, " ", 1);
628 doneany = 1;
631 if (doneany)
632 /* Kill last space. */
633 --o;
635 return o;
638 static char *
639 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
641 int fixlen = strlen (argv[0]);
642 const char *list_iterator = argv[1];
643 int is_addprefix = streq (funcname, "addprefix");
644 int is_addsuffix = !is_addprefix;
646 int doneany = 0;
647 const char *p;
648 unsigned int len;
650 while ((p = find_next_token (&list_iterator, &len)) != 0)
652 if (is_addprefix)
653 o = variable_buffer_output (o, argv[0], fixlen);
654 o = variable_buffer_output (o, p, len);
655 if (is_addsuffix)
656 o = variable_buffer_output (o, argv[0], fixlen);
657 o = variable_buffer_output (o, " ", 1);
658 doneany = 1;
661 if (doneany)
662 /* Kill last space. */
663 --o;
665 return o;
668 static char *
669 func_subst (char *o, char **argv, const char *funcname UNUSED)
671 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
672 strlen (argv[1]), 0);
674 return o;
678 static char *
679 func_firstword (char *o, char **argv, const char *funcname UNUSED)
681 unsigned int i;
682 const char *words = argv[0]; /* Use a temp variable for find_next_token */
683 const char *p = find_next_token (&words, &i);
685 if (p != 0)
686 o = variable_buffer_output (o, p, i);
688 return o;
691 static char *
692 func_lastword (char *o, char **argv, const char *funcname UNUSED)
694 unsigned int i;
695 const char *words = argv[0]; /* Use a temp variable for find_next_token */
696 const char *p = NULL;
697 const char *t;
699 while ((t = find_next_token (&words, &i)))
700 p = t;
702 if (p != 0)
703 o = variable_buffer_output (o, p, i);
705 return o;
708 static char *
709 func_words (char *o, char **argv, const char *funcname UNUSED)
711 int i = 0;
712 const char *word_iterator = argv[0];
713 char buf[20];
715 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
716 ++i;
718 sprintf (buf, "%d", i);
719 o = variable_buffer_output (o, buf, strlen (buf));
721 return o;
724 /* Set begpp to point to the first non-whitespace character of the string,
725 * and endpp to point to the last non-whitespace character of the string.
726 * If the string is empty or contains nothing but whitespace, endpp will be
727 * begpp-1.
729 char *
730 strip_whitespace (const char **begpp, const char **endpp)
732 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
733 (*begpp) ++;
734 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
735 (*endpp) --;
736 return (char *)*begpp;
739 static void
740 check_numeric (const char *s, const char *msg)
742 const char *end = s + strlen (s) - 1;
743 const char *beg = s;
744 strip_whitespace (&s, &end);
746 for (; s <= end; ++s)
747 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
748 break;
750 if (s <= end || end - beg < 0)
751 fatal (*expanding_var, "%s: '%s'", msg, beg);
756 static char *
757 func_word (char *o, char **argv, const char *funcname UNUSED)
759 const char *end_p;
760 const char *p;
761 int i;
763 /* Check the first argument. */
764 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
765 i = atoi (argv[0]);
767 if (i == 0)
768 fatal (*expanding_var,
769 _("first argument to `word' function must be greater than 0"));
771 end_p = argv[1];
772 while ((p = find_next_token (&end_p, 0)) != 0)
773 if (--i == 0)
774 break;
776 if (i == 0)
777 o = variable_buffer_output (o, p, end_p - p);
779 return o;
782 static char *
783 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
785 int start, count;
787 /* Check the arguments. */
788 check_numeric (argv[0],
789 _("non-numeric first argument to `wordlist' function"));
790 check_numeric (argv[1],
791 _("non-numeric second argument to `wordlist' function"));
793 start = atoi (argv[0]);
794 if (start < 1)
795 fatal (*expanding_var,
796 "invalid first argument to `wordlist' function: `%d'", start);
798 count = atoi (argv[1]) - start + 1;
800 if (count > 0)
802 const char *p;
803 const char *end_p = argv[2];
805 /* Find the beginning of the "start"th word. */
806 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
809 if (p)
811 /* Find the end of the "count"th word from start. */
812 while (--count && (find_next_token (&end_p, 0) != 0))
815 /* Return the stuff in the middle. */
816 o = variable_buffer_output (o, p, end_p - p);
820 return o;
823 static char *
824 func_findstring (char *o, char **argv, const char *funcname UNUSED)
826 /* Find the first occurrence of the first string in the second. */
827 if (strstr (argv[1], argv[0]) != 0)
828 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
830 return o;
833 static char *
834 func_foreach (char *o, char **argv, const char *funcname UNUSED)
836 /* expand only the first two. */
837 char *varname = expand_argument (argv[0], NULL);
838 char *list = expand_argument (argv[1], NULL);
839 const char *body = argv[2];
841 int doneany = 0;
842 const char *list_iterator = list;
843 const char *p;
844 unsigned int len;
845 struct variable *var;
847 push_new_variable_scope ();
848 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
850 /* loop through LIST, put the value in VAR and expand BODY */
851 while ((p = find_next_token (&list_iterator, &len)) != 0)
853 char *result = 0;
855 free (var->value);
856 var->value = savestring (p, len);
858 result = allocated_variable_expand (body);
860 o = variable_buffer_output (o, result, strlen (result));
861 o = variable_buffer_output (o, " ", 1);
862 doneany = 1;
863 free (result);
866 if (doneany)
867 /* Kill the last space. */
868 --o;
870 pop_variable_scope ();
871 free (varname);
872 free (list);
874 return o;
877 struct a_word
879 struct a_word *next;
880 struct a_word *chain;
881 char *str;
882 int length;
883 int matched;
886 static unsigned long
887 a_word_hash_1 (const void *key)
889 return_STRING_HASH_1 (((struct a_word const *) key)->str);
892 static unsigned long
893 a_word_hash_2 (const void *key)
895 return_STRING_HASH_2 (((struct a_word const *) key)->str);
898 static int
899 a_word_hash_cmp (const void *x, const void *y)
901 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
902 if (result)
903 return result;
904 return_STRING_COMPARE (((struct a_word const *) x)->str,
905 ((struct a_word const *) y)->str);
908 struct a_pattern
910 struct a_pattern *next;
911 char *str;
912 char *percent;
913 int length;
914 int save_c;
917 static char *
918 func_filter_filterout (char *o, char **argv, const char *funcname)
920 struct a_word *wordhead;
921 struct a_word **wordtail;
922 struct a_word *wp;
923 struct a_pattern *pathead;
924 struct a_pattern **pattail;
925 struct a_pattern *pp;
927 struct hash_table a_word_table;
928 int is_filter = streq (funcname, "filter");
929 const char *pat_iterator = argv[0];
930 const char *word_iterator = argv[1];
931 int literals = 0;
932 int words = 0;
933 int hashing = 0;
934 char *p;
935 unsigned int len;
937 /* Chop ARGV[0] up into patterns to match against the words. */
939 pattail = &pathead;
940 while ((p = find_next_token (&pat_iterator, &len)) != 0)
942 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
944 *pattail = pat;
945 pattail = &pat->next;
947 if (*pat_iterator != '\0')
948 ++pat_iterator;
950 pat->str = p;
951 pat->length = len;
952 pat->save_c = p[len];
953 p[len] = '\0';
954 pat->percent = find_percent (p);
955 if (pat->percent == 0)
956 literals++;
958 *pattail = 0;
960 /* Chop ARGV[1] up into words to match against the patterns. */
962 wordtail = &wordhead;
963 while ((p = find_next_token (&word_iterator, &len)) != 0)
965 struct a_word *word = alloca (sizeof (struct a_word));
967 *wordtail = word;
968 wordtail = &word->next;
970 if (*word_iterator != '\0')
971 ++word_iterator;
973 p[len] = '\0';
974 word->str = p;
975 word->length = len;
976 word->matched = 0;
977 word->chain = 0;
978 words++;
980 *wordtail = 0;
982 /* Only use a hash table if arg list lengths justifies the cost. */
983 hashing = (literals >= 2 && (literals * words) >= 10);
984 if (hashing)
986 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
987 a_word_hash_cmp);
988 for (wp = wordhead; wp != 0; wp = wp->next)
990 struct a_word *owp = hash_insert (&a_word_table, wp);
991 if (owp)
992 wp->chain = owp;
996 if (words)
998 int doneany = 0;
1000 /* Run each pattern through the words, killing words. */
1001 for (pp = pathead; pp != 0; pp = pp->next)
1003 if (pp->percent)
1004 for (wp = wordhead; wp != 0; wp = wp->next)
1005 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1006 else if (hashing)
1008 struct a_word a_word_key;
1009 a_word_key.str = pp->str;
1010 a_word_key.length = pp->length;
1011 wp = hash_find_item (&a_word_table, &a_word_key);
1012 while (wp)
1014 wp->matched |= 1;
1015 wp = wp->chain;
1018 else
1019 for (wp = wordhead; wp != 0; wp = wp->next)
1020 wp->matched |= (wp->length == pp->length
1021 && strneq (pp->str, wp->str, wp->length));
1024 /* Output the words that matched (or didn't, for filter-out). */
1025 for (wp = wordhead; wp != 0; wp = wp->next)
1026 if (is_filter ? wp->matched : !wp->matched)
1028 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1029 o = variable_buffer_output (o, " ", 1);
1030 doneany = 1;
1033 if (doneany)
1034 /* Kill the last space. */
1035 --o;
1038 for (pp = pathead; pp != 0; pp = pp->next)
1039 pp->str[pp->length] = pp->save_c;
1041 if (hashing)
1042 hash_free (&a_word_table, 0);
1044 return o;
1048 static char *
1049 func_strip (char *o, char **argv, const char *funcname UNUSED)
1051 const char *p = argv[0];
1052 int doneany = 0;
1054 while (*p != '\0')
1056 int i=0;
1057 const char *word_start;
1059 while (isspace ((unsigned char)*p))
1060 ++p;
1061 word_start = p;
1062 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1064 if (!i)
1065 break;
1066 o = variable_buffer_output (o, word_start, i);
1067 o = variable_buffer_output (o, " ", 1);
1068 doneany = 1;
1071 if (doneany)
1072 /* Kill the last space. */
1073 --o;
1075 return o;
1079 Print a warning or fatal message.
1081 static char *
1082 func_error (char *o, char **argv, const char *funcname)
1084 char **argvp;
1085 char *msg, *p;
1086 int len;
1088 /* The arguments will be broken on commas. Rather than create yet
1089 another special case where function arguments aren't broken up,
1090 just create a format string that puts them back together. */
1091 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1092 len += strlen (*argvp) + 2;
1094 p = msg = alloca (len + 1);
1096 for (argvp=argv; argvp[1] != 0; ++argvp)
1098 strcpy (p, *argvp);
1099 p += strlen (*argvp);
1100 *(p++) = ',';
1101 *(p++) = ' ';
1103 strcpy (p, *argvp);
1105 switch (*funcname) {
1106 case 'e':
1107 fatal (reading_file, "%s", msg);
1109 case 'w':
1110 error (reading_file, "%s", msg);
1111 break;
1113 case 'i':
1114 printf ("%s\n", msg);
1115 fflush(stdout);
1116 break;
1118 default:
1119 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1122 /* The warning function expands to the empty string. */
1123 return o;
1128 chop argv[0] into words, and sort them.
1130 static char *
1131 func_sort (char *o, char **argv, const char *funcname UNUSED)
1133 const char *t;
1134 char **words;
1135 int wordi;
1136 char *p;
1137 unsigned int len;
1138 int i;
1140 /* Find the maximum number of words we'll have. */
1141 t = argv[0];
1142 wordi = 1;
1143 while (*t != '\0')
1145 char c = *(t++);
1147 if (! isspace ((unsigned char)c))
1148 continue;
1150 ++wordi;
1152 while (isspace ((unsigned char)*t))
1153 ++t;
1156 words = xmalloc (wordi * sizeof (char *));
1158 /* Now assign pointers to each string in the array. */
1159 t = argv[0];
1160 wordi = 0;
1161 while ((p = find_next_token (&t, &len)) != 0)
1163 ++t;
1164 p[len] = '\0';
1165 words[wordi++] = p;
1168 if (wordi)
1170 /* Now sort the list of words. */
1171 qsort (words, wordi, sizeof (char *), alpha_compare);
1173 /* Now write the sorted list, uniquified. */
1174 for (i = 0; i < wordi; ++i)
1176 len = strlen (words[i]);
1177 if (i == wordi - 1 || strlen (words[i + 1]) != len
1178 || strcmp (words[i], words[i + 1]))
1180 o = variable_buffer_output (o, words[i], len);
1181 o = variable_buffer_output (o, " ", 1);
1185 /* Kill the last space. */
1186 --o;
1189 free (words);
1191 return o;
1195 $(if condition,true-part[,false-part])
1197 CONDITION is false iff it evaluates to an empty string. White
1198 space before and after condition are stripped before evaluation.
1200 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1201 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1202 you can use $(if ...) to create side-effects (with $(shell ...), for
1203 example).
1206 static char *
1207 func_if (char *o, char **argv, const char *funcname UNUSED)
1209 const char *begp = argv[0];
1210 const char *endp = begp + strlen (argv[0]) - 1;
1211 int result = 0;
1213 /* Find the result of the condition: if we have a value, and it's not
1214 empty, the condition is true. If we don't have a value, or it's the
1215 empty string, then it's false. */
1217 strip_whitespace (&begp, &endp);
1219 if (begp <= endp)
1221 char *expansion = expand_argument (begp, endp+1);
1223 result = strlen (expansion);
1224 free (expansion);
1227 /* If the result is true (1) we want to eval the first argument, and if
1228 it's false (0) we want to eval the second. If the argument doesn't
1229 exist we do nothing, otherwise expand it and add to the buffer. */
1231 argv += 1 + !result;
1233 if (*argv)
1235 char *expansion = expand_argument (*argv, NULL);
1237 o = variable_buffer_output (o, expansion, strlen (expansion));
1239 free (expansion);
1242 return o;
1246 $(or condition1[,condition2[,condition3[...]]])
1248 A CONDITION is false iff it evaluates to an empty string. White
1249 space before and after CONDITION are stripped before evaluation.
1251 CONDITION1 is evaluated. If it's true, then this is the result of
1252 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1253 the conditions are true, the expansion is the empty string.
1255 Once a CONDITION is true no further conditions are evaluated
1256 (short-circuiting).
1259 static char *
1260 func_or (char *o, char **argv, const char *funcname UNUSED)
1262 for ( ; *argv ; ++argv)
1264 const char *begp = *argv;
1265 const char *endp = begp + strlen (*argv) - 1;
1266 char *expansion;
1267 int result = 0;
1269 /* Find the result of the condition: if it's false keep going. */
1271 strip_whitespace (&begp, &endp);
1273 if (begp > endp)
1274 continue;
1276 expansion = expand_argument (begp, endp+1);
1277 result = strlen (expansion);
1279 /* If the result is false keep going. */
1280 if (!result)
1282 free (expansion);
1283 continue;
1286 /* It's true! Keep this result and return. */
1287 o = variable_buffer_output (o, expansion, result);
1288 free (expansion);
1289 break;
1292 return o;
1296 $(and condition1[,condition2[,condition3[...]]])
1298 A CONDITION is false iff it evaluates to an empty string. White
1299 space before and after CONDITION are stripped before evaluation.
1301 CONDITION1 is evaluated. If it's false, then this is the result of
1302 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1303 the conditions are true, the expansion is the result of the last condition.
1305 Once a CONDITION is false no further conditions are evaluated
1306 (short-circuiting).
1309 static char *
1310 func_and (char *o, char **argv, const char *funcname UNUSED)
1312 char *expansion;
1313 int result;
1315 while (1)
1317 const char *begp = *argv;
1318 const char *endp = begp + strlen (*argv) - 1;
1320 /* An empty condition is always false. */
1321 strip_whitespace (&begp, &endp);
1322 if (begp > endp)
1323 return o;
1325 expansion = expand_argument (begp, endp+1);
1326 result = strlen (expansion);
1328 /* If the result is false, stop here: we're done. */
1329 if (!result)
1330 break;
1332 /* Otherwise the result is true. If this is the last one, keep this
1333 result and quit. Otherwise go on to the next one! */
1335 if (*(++argv))
1336 free (expansion);
1337 else
1339 o = variable_buffer_output (o, expansion, result);
1340 break;
1344 free (expansion);
1346 return o;
1349 static char *
1350 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1352 #ifdef _AMIGA
1353 o = wildcard_expansion (argv[0], o);
1354 #else
1355 char *p = string_glob (argv[0]);
1356 o = variable_buffer_output (o, p, strlen (p));
1357 #endif
1358 return o;
1362 $(eval <makefile string>)
1364 Always resolves to the empty string.
1366 Treat the arguments as a segment of makefile, and parse them.
1369 static char *
1370 func_eval (char *o, char **argv, const char *funcname UNUSED)
1372 char *buf;
1373 unsigned int len;
1375 /* Eval the buffer. Pop the current variable buffer setting so that the
1376 eval'd code can use its own without conflicting. */
1378 install_variable_buffer (&buf, &len);
1380 eval_buffer (argv[0]);
1382 restore_variable_buffer (buf, len);
1384 return o;
1388 static char *
1389 func_value (char *o, char **argv, const char *funcname UNUSED)
1391 /* Look up the variable. */
1392 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1394 /* Copy its value into the output buffer without expanding it. */
1395 if (v)
1396 o = variable_buffer_output (o, v->value, strlen(v->value));
1398 return o;
1402 \r is replaced on UNIX as well. Is this desirable?
1404 static void
1405 fold_newlines (char *buffer, unsigned int *length)
1407 char *dst = buffer;
1408 char *src = buffer;
1409 char *last_nonnl = buffer -1;
1410 src[*length] = 0;
1411 for (; *src != '\0'; ++src)
1413 if (src[0] == '\r' && src[1] == '\n')
1414 continue;
1415 if (*src == '\n')
1417 *dst++ = ' ';
1419 else
1421 last_nonnl = dst;
1422 *dst++ = *src;
1425 *(++last_nonnl) = '\0';
1426 *length = last_nonnl - buffer;
1431 int shell_function_pid = 0, shell_function_completed;
1434 #ifdef WINDOWS32
1435 /*untested*/
1437 #include <windows.h>
1438 #include <io.h>
1439 #include "sub_proc.h"
1442 void
1443 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1445 SECURITY_ATTRIBUTES saAttr;
1446 HANDLE hIn;
1447 HANDLE hErr;
1448 HANDLE hChildOutRd;
1449 HANDLE hChildOutWr;
1450 HANDLE hProcess;
1453 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1454 saAttr.bInheritHandle = TRUE;
1455 saAttr.lpSecurityDescriptor = NULL;
1457 if (DuplicateHandle (GetCurrentProcess(),
1458 GetStdHandle(STD_INPUT_HANDLE),
1459 GetCurrentProcess(),
1460 &hIn,
1462 TRUE,
1463 DUPLICATE_SAME_ACCESS) == FALSE) {
1464 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1465 GetLastError());
1468 if (DuplicateHandle(GetCurrentProcess(),
1469 GetStdHandle(STD_ERROR_HANDLE),
1470 GetCurrentProcess(),
1471 &hErr,
1473 TRUE,
1474 DUPLICATE_SAME_ACCESS) == FALSE) {
1475 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1476 GetLastError());
1479 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1480 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1482 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1484 if (!hProcess)
1485 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1487 /* make sure that CreateProcess() has Path it needs */
1488 sync_Path_environment();
1490 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1491 /* register process for wait */
1492 process_register(hProcess);
1494 /* set the pid for returning to caller */
1495 *pid_p = (int) hProcess;
1497 /* set up to read data from child */
1498 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1500 /* this will be closed almost right away */
1501 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1502 } else {
1503 /* reap/cleanup the failed process */
1504 process_cleanup(hProcess);
1506 /* close handles which were duplicated, they weren't used */
1507 CloseHandle(hIn);
1508 CloseHandle(hErr);
1510 /* close pipe handles, they won't be used */
1511 CloseHandle(hChildOutRd);
1512 CloseHandle(hChildOutWr);
1514 /* set status for return */
1515 pipedes[0] = pipedes[1] = -1;
1516 *pid_p = -1;
1519 #endif
1522 #ifdef __MSDOS__
1523 FILE *
1524 msdos_openpipe (int* pipedes, int *pidp, char *text)
1526 FILE *fpipe=0;
1527 /* MSDOS can't fork, but it has `popen'. */
1528 struct variable *sh = lookup_variable ("SHELL", 5);
1529 int e;
1530 extern int dos_command_running, dos_status;
1532 /* Make sure not to bother processing an empty line. */
1533 while (isblank ((unsigned char)*text))
1534 ++text;
1535 if (*text == '\0')
1536 return 0;
1538 if (sh)
1540 char buf[PATH_MAX + 7];
1541 /* This makes sure $SHELL value is used by $(shell), even
1542 though the target environment is not passed to it. */
1543 sprintf (buf, "SHELL=%s", sh->value);
1544 putenv (buf);
1547 e = errno;
1548 errno = 0;
1549 dos_command_running = 1;
1550 dos_status = 0;
1551 /* If dos_status becomes non-zero, it means the child process
1552 was interrupted by a signal, like SIGINT or SIGQUIT. See
1553 fatal_error_signal in commands.c. */
1554 fpipe = popen (text, "rt");
1555 dos_command_running = 0;
1556 if (!fpipe || dos_status)
1558 pipedes[0] = -1;
1559 *pidp = -1;
1560 if (dos_status)
1561 errno = EINTR;
1562 else if (errno == 0)
1563 errno = ENOMEM;
1564 shell_function_completed = -1;
1566 else
1568 pipedes[0] = fileno (fpipe);
1569 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1570 errno = e;
1571 shell_function_completed = 1;
1573 return fpipe;
1575 #endif
1578 Do shell spawning, with the naughty bits for different OSes.
1581 #ifdef VMS
1583 /* VMS can't do $(shell ...) */
1584 #define func_shell 0
1586 #else
1587 #ifndef _AMIGA
1588 static char *
1589 func_shell (char *o, char **argv, const char *funcname UNUSED)
1591 char *batch_filename = NULL;
1593 #ifdef __MSDOS__
1594 FILE *fpipe;
1595 #endif
1596 char **command_argv;
1597 const char *error_prefix;
1598 char **envp;
1599 int pipedes[2];
1600 int pid;
1602 #ifndef __MSDOS__
1603 /* Construct the argument list. */
1604 command_argv = construct_command_argv (argv[0], NULL, NULL, &batch_filename);
1605 if (command_argv == 0)
1606 return o;
1607 #endif
1609 /* Using a target environment for `shell' loses in cases like:
1610 export var = $(shell echo foobie)
1611 because target_environment hits a loop trying to expand $(var)
1612 to put it in the environment. This is even more confusing when
1613 var was not explicitly exported, but just appeared in the
1614 calling environment.
1616 See Savannah bug #10593.
1618 envp = target_environment (NILF);
1621 envp = environ;
1623 /* For error messages. */
1624 if (reading_file && reading_file->filenm)
1626 char *p = alloca (strlen (reading_file->filenm)+11+4);
1627 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1628 error_prefix = p;
1630 else
1631 error_prefix = "";
1633 #if defined(__MSDOS__)
1634 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1635 if (pipedes[0] < 0)
1637 perror_with_name (error_prefix, "pipe");
1638 return o;
1640 #elif defined(WINDOWS32)
1641 windows32_openpipe (pipedes, &pid, command_argv, envp);
1642 if (pipedes[0] < 0)
1644 /* open of the pipe failed, mark as failed execution */
1645 shell_function_completed = -1;
1647 return o;
1649 else
1650 #else
1651 if (pipe (pipedes) < 0)
1653 perror_with_name (error_prefix, "pipe");
1654 return o;
1657 # ifdef __EMX__
1658 /* close some handles that are unnecessary for the child process */
1659 CLOSE_ON_EXEC(pipedes[1]);
1660 CLOSE_ON_EXEC(pipedes[0]);
1661 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1662 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1663 if (pid < 0)
1664 perror_with_name (error_prefix, "spawn");
1665 # else /* ! __EMX__ */
1666 pid = vfork ();
1667 if (pid < 0)
1668 perror_with_name (error_prefix, "fork");
1669 else if (pid == 0)
1670 child_execute_job (0, pipedes[1], command_argv, envp);
1671 else
1672 # endif
1673 #endif
1675 /* We are the parent. */
1676 char *buffer;
1677 unsigned int maxlen, i;
1678 int cc;
1680 /* Record the PID for reap_children. */
1681 shell_function_pid = pid;
1682 #ifndef __MSDOS__
1683 shell_function_completed = 0;
1685 /* Free the storage only the child needed. */
1686 free (command_argv[0]);
1687 free (command_argv);
1689 /* Close the write side of the pipe. */
1690 close (pipedes[1]);
1691 #endif
1693 /* Set up and read from the pipe. */
1695 maxlen = 200;
1696 buffer = xmalloc (maxlen + 1);
1698 /* Read from the pipe until it gets EOF. */
1699 for (i = 0; ; i += cc)
1701 if (i == maxlen)
1703 maxlen += 512;
1704 buffer = xrealloc (buffer, maxlen + 1);
1707 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1708 if (cc <= 0)
1709 break;
1711 buffer[i] = '\0';
1713 /* Close the read side of the pipe. */
1714 #ifdef __MSDOS__
1715 if (fpipe)
1716 (void) pclose (fpipe);
1717 #else
1718 (void) close (pipedes[0]);
1719 #endif
1721 /* Loop until child_handler or reap_children() sets
1722 shell_function_completed to the status of our child shell. */
1723 while (shell_function_completed == 0)
1724 reap_children (1, 0);
1726 if (batch_filename) {
1727 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1728 batch_filename));
1729 remove (batch_filename);
1730 free (batch_filename);
1732 shell_function_pid = 0;
1734 /* The child_handler function will set shell_function_completed
1735 to 1 when the child dies normally, or to -1 if it
1736 dies with status 127, which is most likely an exec fail. */
1738 if (shell_function_completed == -1)
1740 /* This likely means that the execvp failed, so we should just
1741 write the error message in the pipe from the child. */
1742 fputs (buffer, stderr);
1743 fflush (stderr);
1745 else
1747 /* The child finished normally. Replace all newlines in its output
1748 with spaces, and put that in the variable output buffer. */
1749 fold_newlines (buffer, &i);
1750 o = variable_buffer_output (o, buffer, i);
1753 free (buffer);
1756 return o;
1759 #else /* _AMIGA */
1761 /* Do the Amiga version of func_shell. */
1763 static char *
1764 func_shell (char *o, char **argv, const char *funcname)
1766 /* Amiga can't fork nor spawn, but I can start a program with
1767 redirection of my choice. However, this means that we
1768 don't have an opportunity to reopen stdout to trap it. Thus,
1769 we save our own stdout onto a new descriptor and dup a temp
1770 file's descriptor onto our stdout temporarily. After we
1771 spawn the shell program, we dup our own stdout back to the
1772 stdout descriptor. The buffer reading is the same as above,
1773 except that we're now reading from a file. */
1775 #include <dos/dos.h>
1776 #include <proto/dos.h>
1778 BPTR child_stdout;
1779 char tmp_output[FILENAME_MAX];
1780 unsigned int maxlen = 200, i;
1781 int cc;
1782 char * buffer, * ptr;
1783 char ** aptr;
1784 int len = 0;
1785 char* batch_filename = NULL;
1787 /* Construct the argument list. */
1788 command_argv = construct_command_argv (argv[0], (char **) NULL,
1789 (struct file *) 0, &batch_filename);
1790 if (command_argv == 0)
1791 return o;
1793 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1794 Ideally we would use main.c:open_tmpfile(), but this uses a special
1795 Open(), not fopen(), and I'm not familiar enough with the code to mess
1796 with it. */
1797 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1798 mktemp (tmp_output);
1799 child_stdout = Open (tmp_output, MODE_NEWFILE);
1801 for (aptr=command_argv; *aptr; aptr++)
1802 len += strlen (*aptr) + 1;
1804 buffer = xmalloc (len + 1);
1805 ptr = buffer;
1807 for (aptr=command_argv; *aptr; aptr++)
1809 strcpy (ptr, *aptr);
1810 ptr += strlen (ptr) + 1;
1811 *ptr ++ = ' ';
1812 *ptr = 0;
1815 ptr[-1] = '\n';
1817 Execute (buffer, NULL, child_stdout);
1818 free (buffer);
1820 Close (child_stdout);
1822 child_stdout = Open (tmp_output, MODE_OLDFILE);
1824 buffer = xmalloc (maxlen);
1825 i = 0;
1828 if (i == maxlen)
1830 maxlen += 512;
1831 buffer = xrealloc (buffer, maxlen + 1);
1834 cc = Read (child_stdout, &buffer[i], maxlen - i);
1835 if (cc > 0)
1836 i += cc;
1837 } while (cc > 0);
1839 Close (child_stdout);
1841 fold_newlines (buffer, &i);
1842 o = variable_buffer_output (o, buffer, i);
1843 free (buffer);
1844 return o;
1846 #endif /* _AMIGA */
1847 #endif /* !VMS */
1849 #ifdef EXPERIMENTAL
1852 equality. Return is string-boolean, ie, the empty string is false.
1854 static char *
1855 func_eq (char *o, char **argv, char *funcname)
1857 int result = ! strcmp (argv[0], argv[1]);
1858 o = variable_buffer_output (o, result ? "1" : "", result);
1859 return o;
1864 string-boolean not operator.
1866 static char *
1867 func_not (char *o, char **argv, char *funcname)
1869 const char *s = argv[0];
1870 int result = 0;
1871 while (isspace ((unsigned char)*s))
1872 s++;
1873 result = ! (*s);
1874 o = variable_buffer_output (o, result ? "1" : "", result);
1875 return o;
1877 #endif
1880 /* Return the absolute name of file NAME which does not contain any `.',
1881 `..' components nor any repeated path separators ('/'). */
1883 static char *
1884 abspath (const char *name, char *apath)
1886 char *dest;
1887 const char *start, *end, *apath_limit;
1889 if (name[0] == '\0' || apath == NULL)
1890 return NULL;
1892 apath_limit = apath + GET_PATH_MAX;
1894 if (name[0] != '/')
1896 /* It is unlikely we would make it until here but just to make sure. */
1897 if (!starting_directory)
1898 return NULL;
1900 strcpy (apath, starting_directory);
1902 dest = strchr (apath, '\0');
1904 else
1906 apath[0] = '/';
1907 dest = apath + 1;
1910 for (start = end = name; *start != '\0'; start = end)
1912 unsigned long len;
1914 /* Skip sequence of multiple path-separators. */
1915 while (*start == '/')
1916 ++start;
1918 /* Find end of path component. */
1919 for (end = start; *end != '\0' && *end != '/'; ++end)
1922 len = end - start;
1924 if (len == 0)
1925 break;
1926 else if (len == 1 && start[0] == '.')
1927 /* nothing */;
1928 else if (len == 2 && start[0] == '.' && start[1] == '.')
1930 /* Back up to previous component, ignore if at root already. */
1931 if (dest > apath + 1)
1932 while ((--dest)[-1] != '/');
1934 else
1936 if (dest[-1] != '/')
1937 *dest++ = '/';
1939 if (dest + len >= apath_limit)
1940 return NULL;
1942 dest = memcpy (dest, start, len);
1943 dest += len;
1944 *dest = '\0';
1948 /* Unless it is root strip trailing separator. */
1949 if (dest > apath + 1 && dest[-1] == '/')
1950 --dest;
1952 *dest = '\0';
1954 return apath;
1958 static char *
1959 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1961 /* Expand the argument. */
1962 const char *p = argv[0];
1963 const char *path = 0;
1964 int doneany = 0;
1965 unsigned int len = 0;
1966 PATH_VAR (in);
1967 PATH_VAR (out);
1969 while ((path = find_next_token (&p, &len)) != 0)
1971 if (len < GET_PATH_MAX)
1973 strncpy (in, path, len);
1974 in[len] = '\0';
1976 if (
1977 #ifdef HAVE_REALPATH
1978 realpath (in, out)
1979 #else
1980 abspath (in, out)
1981 #endif
1984 o = variable_buffer_output (o, out, strlen (out));
1985 o = variable_buffer_output (o, " ", 1);
1986 doneany = 1;
1991 /* Kill last space. */
1992 if (doneany)
1993 --o;
1995 return o;
1998 static char *
1999 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2001 /* Expand the argument. */
2002 const char *p = argv[0];
2003 const char *path = 0;
2004 int doneany = 0;
2005 unsigned int len = 0;
2006 PATH_VAR (in);
2007 PATH_VAR (out);
2009 while ((path = find_next_token (&p, &len)) != 0)
2011 if (len < GET_PATH_MAX)
2013 strncpy (in, path, len);
2014 in[len] = '\0';
2016 if (abspath (in, out))
2018 o = variable_buffer_output (o, out, strlen (out));
2019 o = variable_buffer_output (o, " ", 1);
2020 doneany = 1;
2025 /* Kill last space. */
2026 if (doneany)
2027 --o;
2029 return o;
2032 /* Lookup table for builtin functions.
2034 This doesn't have to be sorted; we use a straight lookup. We might gain
2035 some efficiency by moving most often used functions to the start of the
2036 table.
2038 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2039 comma-separated values are treated as arguments.
2041 EXPAND_ARGS means that all arguments should be expanded before invocation.
2042 Functions that do namespace tricks (foreach) don't automatically expand. */
2044 static char *func_call (char *o, char **argv, const char *funcname);
2047 static struct function_table_entry function_table_init[] =
2049 /* Name/size */ /* MIN MAX EXP? Function */
2050 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2051 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2052 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2053 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2054 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2055 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2056 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2057 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2058 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2059 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2060 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2061 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2062 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2063 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2064 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2065 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2066 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2067 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2068 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2069 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2070 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2071 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2072 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2073 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2074 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2075 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2076 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2077 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2078 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2079 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2080 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2081 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2082 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2083 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2084 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2085 #ifdef EXPERIMENTAL
2086 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2087 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2088 #endif
2091 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2094 /* These must come after the definition of function_table. */
2096 static char *
2097 expand_builtin_function (char *o, int argc, char **argv,
2098 const struct function_table_entry *entry_p)
2100 if (argc < (int)entry_p->minimum_args)
2101 fatal (*expanding_var,
2102 _("insufficient number of arguments (%d) to function `%s'"),
2103 argc, entry_p->name);
2105 /* I suppose technically some function could do something with no
2106 arguments, but so far none do, so just test it for all functions here
2107 rather than in each one. We can change it later if necessary. */
2109 if (!argc)
2110 return o;
2112 if (!entry_p->func_ptr)
2113 fatal (*expanding_var,
2114 _("unimplemented on this platform: function `%s'"), entry_p->name);
2116 return entry_p->func_ptr (o, argv, entry_p->name);
2119 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2120 opening ( or { and is not null-terminated. If a function invocation
2121 is found, expand it into the buffer at *OP, updating *OP, incrementing
2122 *STRINGP past the reference and returning nonzero. If not, return zero. */
2125 handle_function (char **op, const char **stringp)
2127 const struct function_table_entry *entry_p;
2128 char openparen = (*stringp)[0];
2129 char closeparen = openparen == '(' ? ')' : '}';
2130 const char *beg;
2131 const char *end;
2132 int count = 0;
2133 char *abeg = NULL;
2134 char **argv, **argvp;
2135 int nargs;
2137 beg = *stringp + 1;
2139 entry_p = lookup_function (beg);
2141 if (!entry_p)
2142 return 0;
2144 /* We found a builtin function. Find the beginning of its arguments (skip
2145 whitespace after the name). */
2147 beg = next_token (beg + entry_p->len);
2149 /* Find the end of the function invocation, counting nested use of
2150 whichever kind of parens we use. Since we're looking, count commas
2151 to get a rough estimate of how many arguments we might have. The
2152 count might be high, but it'll never be low. */
2154 for (nargs=1, end=beg; *end != '\0'; ++end)
2155 if (*end == ',')
2156 ++nargs;
2157 else if (*end == openparen)
2158 ++count;
2159 else if (*end == closeparen && --count < 0)
2160 break;
2162 if (count >= 0)
2163 fatal (*expanding_var,
2164 _("unterminated call to function `%s': missing `%c'"),
2165 entry_p->name, closeparen);
2167 *stringp = end;
2169 /* Get some memory to store the arg pointers. */
2170 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2172 /* Chop the string into arguments, then a nul. As soon as we hit
2173 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2174 last argument.
2176 If we're expanding, store pointers to the expansion of each one. If
2177 not, make a duplicate of the string and point into that, nul-terminating
2178 each argument. */
2180 if (entry_p->expand_args)
2182 const char *p;
2183 for (p=beg, nargs=0; p <= end; ++argvp)
2185 const char *next;
2187 ++nargs;
2189 if (nargs == entry_p->maximum_args
2190 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2191 next = end;
2193 *argvp = expand_argument (p, next);
2194 p = next + 1;
2197 else
2199 int len = end - beg;
2200 char *p, *aend;
2202 abeg = xmalloc (len+1);
2203 memcpy (abeg, beg, len);
2204 abeg[len] = '\0';
2205 aend = abeg + len;
2207 for (p=abeg, nargs=0; p <= aend; ++argvp)
2209 char *next;
2211 ++nargs;
2213 if (nargs == entry_p->maximum_args
2214 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2215 next = aend;
2217 *argvp = p;
2218 *next = '\0';
2219 p = next + 1;
2222 *argvp = NULL;
2224 /* Finally! Run the function... */
2225 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2227 /* Free memory. */
2228 if (entry_p->expand_args)
2229 for (argvp=argv; *argvp != 0; ++argvp)
2230 free (*argvp);
2231 if (abeg)
2232 free (abeg);
2234 return 1;
2238 /* User-defined functions. Expand the first argument as either a builtin
2239 function or a make variable, in the context of the rest of the arguments
2240 assigned to $1, $2, ... $N. $0 is the name of the function. */
2242 static char *
2243 func_call (char *o, char **argv, const char *funcname UNUSED)
2245 static int max_args = 0;
2246 char *fname;
2247 char *cp;
2248 char *body;
2249 int flen;
2250 int i;
2251 int saved_args;
2252 const struct function_table_entry *entry_p;
2253 struct variable *v;
2255 /* There is no way to define a variable with a space in the name, so strip
2256 leading and trailing whitespace as a favor to the user. */
2257 fname = argv[0];
2258 while (*fname != '\0' && isspace ((unsigned char)*fname))
2259 ++fname;
2261 cp = fname + strlen (fname) - 1;
2262 while (cp > fname && isspace ((unsigned char)*cp))
2263 --cp;
2264 cp[1] = '\0';
2266 /* Calling nothing is a no-op */
2267 if (*fname == '\0')
2268 return o;
2270 /* Are we invoking a builtin function? */
2272 entry_p = lookup_function (fname);
2273 if (entry_p)
2275 /* How many arguments do we have? */
2276 for (i=0; argv[i+1]; ++i)
2278 return expand_builtin_function (o, i, argv+1, entry_p);
2281 /* Not a builtin, so the first argument is the name of a variable to be
2282 expanded and interpreted as a function. Find it. */
2283 flen = strlen (fname);
2285 v = lookup_variable (fname, flen);
2287 if (v == 0)
2288 warn_undefined (fname, flen);
2290 if (v == 0 || *v->value == '\0')
2291 return o;
2293 body = alloca (flen + 4);
2294 body[0] = '$';
2295 body[1] = '(';
2296 memcpy (body + 2, fname, flen);
2297 body[flen+2] = ')';
2298 body[flen+3] = '\0';
2300 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2302 push_new_variable_scope ();
2304 for (i=0; *argv; ++i, ++argv)
2306 char num[11];
2308 sprintf (num, "%d", i);
2309 define_variable (num, strlen (num), *argv, o_automatic, 0);
2312 /* If the number of arguments we have is < max_args, it means we're inside
2313 a recursive invocation of $(call ...). Fill in the remaining arguments
2314 in the new scope with the empty value, to hide them from this
2315 invocation. */
2317 for (; i < max_args; ++i)
2319 char num[11];
2321 sprintf (num, "%d", i);
2322 define_variable (num, strlen (num), "", o_automatic, 0);
2325 /* Expand the body in the context of the arguments, adding the result to
2326 the variable buffer. */
2328 v->exp_count = EXP_COUNT_MAX;
2330 saved_args = max_args;
2331 max_args = i;
2332 o = variable_expand_string (o, body, flen+3);
2333 max_args = saved_args;
2335 v->exp_count = 0;
2337 pop_variable_scope ();
2339 return o + strlen (o);
2342 void
2343 hash_init_function_table (void)
2345 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2346 function_table_entry_hash_1, function_table_entry_hash_2,
2347 function_table_entry_hash_cmp);
2348 hash_load (&function_table, function_table_init,
2349 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));