Numerous updates to tests for issues found on Cygwin and Windows.
[make.git] / function.c
blob07cbbffd897579a72b5326be0fef0c8a2f6828e9
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 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 2, or (at your option) any later version.
11 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along with
16 GNU Make; see the file COPYING. If not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
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) PARAMS ((char *output, char **argv, const char *fname));
42 static unsigned long
43 function_table_entry_hash_1 (const void *keyv)
45 struct function_table_entry const *key = (struct function_table_entry const *) 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 struct function_table_entry const *key = (struct function_table_entry const *) 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 struct function_table_entry const *x = (struct function_table_entry const *) xv;
60 struct function_table_entry const *y = (struct function_table_entry const *) 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, char *text, char *subst, char *replace,
78 unsigned int slen, unsigned int rlen, int by_word)
80 char *t = text;
81 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. */
127 char *nt = p + slen;
128 t = nt;
130 } while (*t != '\0');
132 return o;
136 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
137 and replacing strings matching PATTERN with REPLACE.
138 If PATTERN_PERCENT is not nil, PATTERN has already been
139 run through find_percent, and PATTERN_PERCENT is the result.
140 If REPLACE_PERCENT is not nil, REPLACE has already been
141 run through find_percent, and REPLACE_PERCENT is the result.
142 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
143 character _AFTER_ the %, not to the % itself.
146 char *
147 patsubst_expand (char *o, char *text, char *pattern, char *replace,
148 char *pattern_percent, char *replace_percent)
150 unsigned int pattern_prepercent_len, pattern_postpercent_len;
151 unsigned int replace_prepercent_len, replace_postpercent_len;
152 char *t;
153 unsigned int len;
154 int doneany = 0;
156 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
157 will be collapsed before we call subst_expand if PATTERN has no %. */
158 if (!replace_percent)
160 replace_percent = find_percent (replace);
161 if (replace_percent)
162 ++replace_percent;
165 /* Record the length of REPLACE before and after the % so we don't have to
166 compute these lengths more than once. */
167 if (replace_percent)
169 replace_prepercent_len = replace_percent - replace - 1;
170 replace_postpercent_len = strlen (replace_percent);
172 else
174 replace_prepercent_len = strlen (replace);
175 replace_postpercent_len = 0;
178 if (!pattern_percent)
180 pattern_percent = find_percent (pattern);
181 if (pattern_percent)
182 ++pattern_percent;
184 if (!pattern_percent)
185 /* With no % in the pattern, this is just a simple substitution. */
186 return subst_expand (o, text, pattern, replace,
187 strlen (pattern), strlen (replace), 1);
189 /* Record the length of PATTERN before and after the %
190 so we don't have to compute it more than once. */
191 pattern_prepercent_len = pattern_percent - pattern - 1;
192 pattern_postpercent_len = strlen (pattern_percent);
194 while ((t = find_next_token (&text, &len)) != 0)
196 int fail = 0;
198 /* Is it big enough to match? */
199 if (len < pattern_prepercent_len + pattern_postpercent_len)
200 fail = 1;
202 /* Does the prefix match? */
203 if (!fail && pattern_prepercent_len > 0
204 && (*t != *pattern
205 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
206 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
207 fail = 1;
209 /* Does the suffix match? */
210 if (!fail && pattern_postpercent_len > 0
211 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
212 || t[len - pattern_postpercent_len] != *pattern_percent
213 || !strneq (&t[len - pattern_postpercent_len],
214 pattern_percent, pattern_postpercent_len - 1)))
215 fail = 1;
217 if (fail)
218 /* It didn't match. Output the string. */
219 o = variable_buffer_output (o, t, len);
220 else
222 /* It matched. Output the replacement. */
224 /* Output the part of the replacement before the %. */
225 o = variable_buffer_output (o, replace, replace_prepercent_len);
227 if (replace_percent != 0)
229 /* Output the part of the matched string that
230 matched the % in the pattern. */
231 o = variable_buffer_output (o, t + pattern_prepercent_len,
232 len - (pattern_prepercent_len
233 + pattern_postpercent_len));
234 /* Output the part of the replacement after the %. */
235 o = variable_buffer_output (o, replace_percent,
236 replace_postpercent_len);
240 /* Output a space, but not if the replacement is "". */
241 if (fail || replace_prepercent_len > 0
242 || (replace_percent != 0 && len + replace_postpercent_len > 0))
244 o = variable_buffer_output (o, " ", 1);
245 doneany = 1;
248 if (doneany)
249 /* Kill the last space. */
250 --o;
252 return o;
256 /* Look up a function by name. */
258 static const struct function_table_entry *
259 lookup_function (const char *s)
261 const char *e = s;
263 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
264 e++;
265 if (*e == '\0' || isblank ((unsigned char) *e))
267 struct function_table_entry function_table_entry_key;
268 function_table_entry_key.name = s;
269 function_table_entry_key.len = e - s;
271 return hash_find_item (&function_table, &function_table_entry_key);
273 return 0;
277 /* Return 1 if PATTERN matches STR, 0 if not. */
280 pattern_matches (char *pattern, char *percent, char *str)
282 unsigned int sfxlen, strlength;
284 if (percent == 0)
286 unsigned int len = strlen (pattern) + 1;
287 char *new_chars = (char *) alloca (len);
288 bcopy (pattern, new_chars, len);
289 pattern = new_chars;
290 percent = find_percent (pattern);
291 if (percent == 0)
292 return streq (pattern, str);
295 sfxlen = strlen (percent + 1);
296 strlength = strlen (str);
298 if (strlength < (percent - pattern) + sfxlen
299 || !strneq (pattern, str, percent - pattern))
300 return 0;
302 return !strcmp (percent + 1, str + (strlength - sfxlen));
306 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
307 ENDPARENtheses), starting at PTR before END. Return a pointer to
308 next character.
310 If no next argument is found, return NULL.
313 static char *
314 find_next_argument (char startparen, char endparen,
315 const char *ptr, const char *end)
317 int count = 0;
319 for (; ptr < end; ++ptr)
320 if (*ptr == startparen)
321 ++count;
323 else if (*ptr == endparen)
325 --count;
326 if (count < 0)
327 return NULL;
330 else if (*ptr == ',' && !count)
331 return (char *)ptr;
333 /* We didn't find anything. */
334 return NULL;
338 /* Glob-expand LINE. The returned pointer is
339 only good until the next call to string_glob. */
341 static char *
342 string_glob (char *line)
344 static char *result = 0;
345 static unsigned int length;
346 register struct nameseq *chain;
347 register unsigned int idx;
349 chain = multi_glob (parse_file_seq
350 (&line, '\0', sizeof (struct nameseq),
351 /* We do not want parse_file_seq to strip `./'s.
352 That would break examples like:
353 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
355 sizeof (struct nameseq));
357 if (result == 0)
359 length = 100;
360 result = (char *) xmalloc (100);
363 idx = 0;
364 while (chain != 0)
366 register char *name = chain->name;
367 unsigned int len = strlen (name);
369 struct nameseq *next = chain->next;
370 free ((char *) chain);
371 chain = next;
373 /* multi_glob will pass names without globbing metacharacters
374 through as is, but we want only files that actually exist. */
375 if (file_exists_p (name))
377 if (idx + len + 1 > length)
379 length += (len + 1) * 2;
380 result = (char *) xrealloc (result, length);
382 bcopy (name, &result[idx], len);
383 idx += len;
384 result[idx++] = ' ';
387 free (name);
390 /* Kill the last space and terminate the string. */
391 if (idx == 0)
392 result[0] = '\0';
393 else
394 result[idx - 1] = '\0';
396 return result;
400 Builtin functions
403 static char *
404 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
406 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
407 return o;
411 static char *
412 func_join (char *o, char **argv, const char *funcname UNUSED)
414 int doneany = 0;
416 /* Write each word of the first argument directly followed
417 by the corresponding word of the second argument.
418 If the two arguments have a different number of words,
419 the excess words are just output separated by blanks. */
420 register char *tp;
421 register char *pp;
422 char *list1_iterator = argv[0];
423 char *list2_iterator = argv[1];
426 unsigned int len1, len2;
428 tp = find_next_token (&list1_iterator, &len1);
429 if (tp != 0)
430 o = variable_buffer_output (o, tp, len1);
432 pp = find_next_token (&list2_iterator, &len2);
433 if (pp != 0)
434 o = variable_buffer_output (o, pp, len2);
436 if (tp != 0 || pp != 0)
438 o = variable_buffer_output (o, " ", 1);
439 doneany = 1;
442 while (tp != 0 || pp != 0);
443 if (doneany)
444 /* Kill the last blank. */
445 --o;
447 return o;
451 static char *
452 func_origin (char *o, char **argv, const char *funcname UNUSED)
454 /* Expand the argument. */
455 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
456 if (v == 0)
457 o = variable_buffer_output (o, "undefined", 9);
458 else
459 switch (v->origin)
461 default:
462 case o_invalid:
463 abort ();
464 break;
465 case o_default:
466 o = variable_buffer_output (o, "default", 7);
467 break;
468 case o_env:
469 o = variable_buffer_output (o, "environment", 11);
470 break;
471 case o_file:
472 o = variable_buffer_output (o, "file", 4);
473 break;
474 case o_env_override:
475 o = variable_buffer_output (o, "environment override", 20);
476 break;
477 case o_command:
478 o = variable_buffer_output (o, "command line", 12);
479 break;
480 case o_override:
481 o = variable_buffer_output (o, "override", 8);
482 break;
483 case o_automatic:
484 o = variable_buffer_output (o, "automatic", 9);
485 break;
488 return o;
491 static char *
492 func_flavor (char *o, char **argv, const char *funcname UNUSED)
494 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
496 if (v == 0)
497 o = variable_buffer_output (o, "undefined", 9);
498 else
499 if (v->recursive)
500 o = variable_buffer_output (o, "recursive", 9);
501 else
502 o = variable_buffer_output (o, "simple", 6);
504 return o;
507 #ifdef VMS
508 # define IS_PATHSEP(c) ((c) == ']')
509 #else
510 # ifdef HAVE_DOS_PATHS
511 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
512 # else
513 # define IS_PATHSEP(c) ((c) == '/')
514 # endif
515 #endif
518 static char *
519 func_notdir_suffix (char *o, char **argv, const char *funcname)
521 /* Expand the argument. */
522 char *list_iterator = argv[0];
523 char *p2 =0;
524 int doneany =0;
525 unsigned int len=0;
527 int is_suffix = streq (funcname, "suffix");
528 int is_notdir = !is_suffix;
529 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
531 char *p = p2 + len;
534 while (p >= p2 && (!is_suffix || *p != '.'))
536 if (IS_PATHSEP (*p))
537 break;
538 --p;
541 if (p >= p2)
543 if (is_notdir)
544 ++p;
545 else if (*p != '.')
546 continue;
547 o = variable_buffer_output (o, p, len - (p - p2));
549 #ifdef HAVE_DOS_PATHS
550 /* Handle the case of "d:foo/bar". */
551 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
553 p = p2 + 2;
554 o = variable_buffer_output (o, p, len - (p - p2));
556 #endif
557 else if (is_notdir)
558 o = variable_buffer_output (o, p2, len);
560 if (is_notdir || p >= p2)
562 o = variable_buffer_output (o, " ", 1);
563 doneany = 1;
566 if (doneany)
567 /* Kill last space. */
568 --o;
571 return o;
576 static char *
577 func_basename_dir (char *o, char **argv, const char *funcname)
579 /* Expand the argument. */
580 char *p3 = argv[0];
581 char *p2=0;
582 int doneany=0;
583 unsigned int len=0;
584 char *p=0;
585 int is_basename= streq (funcname, "basename");
586 int is_dir= !is_basename;
588 while ((p2 = find_next_token (&p3, &len)) != 0)
590 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;
624 if (doneany)
625 /* Kill last space. */
626 --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 char *list_iterator = argv[1];
637 int is_addprefix = streq (funcname, "addprefix");
638 int is_addsuffix = !is_addprefix;
640 int doneany = 0;
641 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 char *words = argv[0]; /* Use a temp variable for find_next_token */
677 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 char *words = argv[0]; /* Use a temp variable for find_next_token */
690 char *p = 0;
691 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 char *word_iterator = argv[0];
707 char buf[20];
709 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
710 ++i;
712 sprintf (buf, "%d", i);
713 o = variable_buffer_output (o, buf, strlen (buf));
716 return o;
719 /* Set begpp to point to the first non-whitespace character of the string,
720 * and endpp to point to the last non-whitespace character of the string.
721 * If the string is empty or contains nothing but whitespace, endpp will be
722 * begpp-1.
724 char *
725 strip_whitespace (const char **begpp, const char **endpp)
727 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
728 (*begpp) ++;
729 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
730 (*endpp) --;
731 return (char *)*begpp;
734 static void
735 check_numeric (const char *s, const char *message)
737 const char *end = s + strlen (s) - 1;
738 const char *beg = s;
739 strip_whitespace (&s, &end);
741 for (; s <= end; ++s)
742 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
743 break;
745 if (s <= end || end - beg < 0)
746 fatal (*expanding_var, "%s: '%s'", message, beg);
751 static char *
752 func_word (char *o, char **argv, const char *funcname UNUSED)
754 char *end_p=0;
755 int i=0;
756 char *p=0;
758 /* Check the first argument. */
759 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
760 i = atoi (argv[0]);
762 if (i == 0)
763 fatal (*expanding_var,
764 _("first argument to `word' function must be greater than 0"));
767 end_p = argv[1];
768 while ((p = find_next_token (&end_p, 0)) != 0)
769 if (--i == 0)
770 break;
772 if (i == 0)
773 o = variable_buffer_output (o, p, end_p - p);
775 return o;
778 static char *
779 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
781 int start, count;
783 /* Check the arguments. */
784 check_numeric (argv[0],
785 _("non-numeric first argument to `wordlist' function"));
786 check_numeric (argv[1],
787 _("non-numeric second argument to `wordlist' function"));
789 start = atoi (argv[0]);
790 if (start < 1)
791 fatal (*expanding_var,
792 "invalid first argument to `wordlist' function: `%d'", start);
794 count = atoi (argv[1]) - start + 1;
796 if (count > 0)
798 char *p;
799 char *end_p = argv[2];
801 /* Find the beginning of the "start"th word. */
802 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
805 if (p)
807 /* Find the end of the "count"th word from start. */
808 while (--count && (find_next_token (&end_p, 0) != 0))
811 /* Return the stuff in the middle. */
812 o = variable_buffer_output (o, p, end_p - p);
816 return o;
819 static char*
820 func_findstring (char *o, char **argv, const char *funcname UNUSED)
822 /* Find the first occurrence of the first string in the second. */
823 if (strstr (argv[1], argv[0]) != 0)
824 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
826 return o;
829 static char *
830 func_foreach (char *o, char **argv, const char *funcname UNUSED)
832 /* expand only the first two. */
833 char *varname = expand_argument (argv[0], NULL);
834 char *list = expand_argument (argv[1], NULL);
835 char *body = argv[2];
837 int doneany = 0;
838 char *list_iterator = list;
839 char *p;
840 unsigned int len;
841 register struct variable *var;
843 push_new_variable_scope ();
844 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
846 /* loop through LIST, put the value in VAR and expand BODY */
847 while ((p = find_next_token (&list_iterator, &len)) != 0)
849 char *result = 0;
852 char save = p[len];
854 p[len] = '\0';
855 free (var->value);
856 var->value = (char *) xstrdup ((char*) p);
857 p[len] = save;
860 result = allocated_variable_expand (body);
862 o = variable_buffer_output (o, result, strlen (result));
863 o = variable_buffer_output (o, " ", 1);
864 doneany = 1;
865 free (result);
868 if (doneany)
869 /* Kill the last space. */
870 --o;
872 pop_variable_scope ();
873 free (varname);
874 free (list);
876 return o;
879 struct a_word
881 struct a_word *next;
882 struct a_word *chain;
883 char *str;
884 int length;
885 int matched;
888 static unsigned long
889 a_word_hash_1 (const void *key)
891 return_STRING_HASH_1 (((struct a_word const *) key)->str);
894 static unsigned long
895 a_word_hash_2 (const void *key)
897 return_STRING_HASH_2 (((struct a_word const *) key)->str);
900 static int
901 a_word_hash_cmp (const void *x, const void *y)
903 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
904 if (result)
905 return result;
906 return_STRING_COMPARE (((struct a_word const *) x)->str,
907 ((struct a_word const *) y)->str);
910 struct a_pattern
912 struct a_pattern *next;
913 char *str;
914 char *percent;
915 int length;
916 int save_c;
919 static char *
920 func_filter_filterout (char *o, char **argv, const char *funcname)
922 struct a_word *wordhead;
923 struct a_word **wordtail;
924 struct a_word *wp;
925 struct a_pattern *pathead;
926 struct a_pattern **pattail;
927 struct a_pattern *pp;
929 struct hash_table a_word_table;
930 int is_filter = streq (funcname, "filter");
931 char *pat_iterator = argv[0];
932 char *word_iterator = argv[1];
933 int literals = 0;
934 int words = 0;
935 int hashing = 0;
936 char *p;
937 unsigned int len;
939 /* Chop ARGV[0] up into patterns to match against the words. */
941 pattail = &pathead;
942 while ((p = find_next_token (&pat_iterator, &len)) != 0)
944 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
946 *pattail = pat;
947 pattail = &pat->next;
949 if (*pat_iterator != '\0')
950 ++pat_iterator;
952 pat->str = p;
953 pat->length = len;
954 pat->save_c = p[len];
955 p[len] = '\0';
956 pat->percent = find_percent (p);
957 if (pat->percent == 0)
958 literals++;
960 *pattail = 0;
962 /* Chop ARGV[1] up into words to match against the patterns. */
964 wordtail = &wordhead;
965 while ((p = find_next_token (&word_iterator, &len)) != 0)
967 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
969 *wordtail = word;
970 wordtail = &word->next;
972 if (*word_iterator != '\0')
973 ++word_iterator;
975 p[len] = '\0';
976 word->str = p;
977 word->length = len;
978 word->matched = 0;
979 word->chain = 0;
980 words++;
982 *wordtail = 0;
984 /* Only use a hash table if arg list lengths justifies the cost. */
985 hashing = (literals >= 2 && (literals * words) >= 10);
986 if (hashing)
988 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
989 for (wp = wordhead; wp != 0; wp = wp->next)
991 struct a_word *owp = hash_insert (&a_word_table, wp);
992 if (owp)
993 wp->chain = owp;
997 if (words)
999 int doneany = 0;
1001 /* Run each pattern through the words, killing words. */
1002 for (pp = pathead; pp != 0; pp = pp->next)
1004 if (pp->percent)
1005 for (wp = wordhead; wp != 0; wp = wp->next)
1006 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1007 else if (hashing)
1009 struct a_word a_word_key;
1010 a_word_key.str = pp->str;
1011 a_word_key.length = pp->length;
1012 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1013 while (wp)
1015 wp->matched |= 1;
1016 wp = wp->chain;
1019 else
1020 for (wp = wordhead; wp != 0; wp = wp->next)
1021 wp->matched |= (wp->length == pp->length
1022 && strneq (pp->str, wp->str, wp->length));
1025 /* Output the words that matched (or didn't, for filter-out). */
1026 for (wp = wordhead; wp != 0; wp = wp->next)
1027 if (is_filter ? wp->matched : !wp->matched)
1029 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1030 o = variable_buffer_output (o, " ", 1);
1031 doneany = 1;
1034 if (doneany)
1035 /* Kill the last space. */
1036 --o;
1039 for (pp = pathead; pp != 0; pp = pp->next)
1040 pp->str[pp->length] = pp->save_c;
1042 if (hashing)
1043 hash_free (&a_word_table, 0);
1045 return o;
1049 static char *
1050 func_strip (char *o, char **argv, const char *funcname UNUSED)
1052 char *p = argv[0];
1053 int doneany =0;
1055 while (*p != '\0')
1057 int i=0;
1058 char *word_start=0;
1060 while (isspace ((unsigned char)*p))
1061 ++p;
1062 word_start = p;
1063 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1065 if (!i)
1066 break;
1067 o = variable_buffer_output (o, word_start, i);
1068 o = variable_buffer_output (o, " ", 1);
1069 doneany = 1;
1072 if (doneany)
1073 /* Kill the last space. */
1074 --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 = (char *) 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 char **words = 0;
1134 int nwords = 0;
1135 register int wordi = 0;
1137 /* Chop ARGV[0] into words and put them in WORDS. */
1138 char *t = argv[0];
1139 char *p;
1140 unsigned int len;
1141 int i;
1143 while ((p = find_next_token (&t, &len)) != 0)
1145 if (wordi >= nwords - 1)
1147 nwords = (2 * nwords) + 5;
1148 words = (char **) xrealloc ((char *) words,
1149 nwords * sizeof (char *));
1151 words[wordi++] = savestring (p, len);
1154 if (!wordi)
1155 return o;
1157 /* Now sort the list of words. */
1158 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1160 /* Now write the sorted list. */
1161 for (i = 0; i < wordi; ++i)
1163 len = strlen (words[i]);
1164 if (i == wordi - 1 || strlen (words[i + 1]) != len
1165 || strcmp (words[i], words[i + 1]))
1167 o = variable_buffer_output (o, words[i], len);
1168 o = variable_buffer_output (o, " ", 1);
1170 free (words[i]);
1172 /* Kill the last space. */
1173 --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[0])
1221 char *expansion;
1223 expansion = expand_argument (argv[0], NULL);
1225 o = variable_buffer_output (o, expansion, strlen (expansion));
1227 free (expansion);
1230 return o;
1234 $(or condition1[,condition2[,condition3[...]]])
1236 A CONDITION is false iff it evaluates to an empty string. White
1237 space before and after CONDITION are stripped before evaluation.
1239 CONDITION1 is evaluated. If it's true, then this is the result of
1240 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1241 the conditions are true, the expansion is the empty string.
1243 Once a CONDITION is true no further conditions are evaluated
1244 (short-circuiting).
1247 static char *
1248 func_or (char *o, char **argv, const char *funcname UNUSED)
1250 for ( ; *argv ; ++argv)
1252 const char *begp = *argv;
1253 const char *endp = begp + strlen (*argv) - 1;
1254 char *expansion;
1255 int result = 0;
1257 /* Find the result of the condition: if it's false keep going. */
1259 strip_whitespace (&begp, &endp);
1261 if (begp > endp)
1262 continue;
1264 expansion = expand_argument (begp, endp+1);
1265 result = strlen (expansion);
1267 /* If the result is false keep going. */
1268 if (!result)
1270 free (expansion);
1271 continue;
1274 /* It's true! Keep this result and return. */
1275 o = variable_buffer_output (o, expansion, result);
1276 free (expansion);
1277 break;
1280 return o;
1284 $(and condition1[,condition2[,condition3[...]]])
1286 A CONDITION is false iff it evaluates to an empty string. White
1287 space before and after CONDITION are stripped before evaluation.
1289 CONDITION1 is evaluated. If it's false, then this is the result of
1290 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1291 the conditions are true, the expansion is the result of the last condition.
1293 Once a CONDITION is false no further conditions are evaluated
1294 (short-circuiting).
1297 static char *
1298 func_and (char *o, char **argv, const char *funcname UNUSED)
1300 char *expansion;
1301 int result;
1303 while (1)
1305 const char *begp = *argv;
1306 const char *endp = begp + strlen (*argv) - 1;
1308 /* An empty condition is always false. */
1309 strip_whitespace (&begp, &endp);
1310 if (begp > endp)
1311 return o;
1313 expansion = expand_argument (begp, endp+1);
1314 result = strlen (expansion);
1316 /* If the result is false, stop here: we're done. */
1317 if (!result)
1318 break;
1320 /* Otherwise the result is true. If this is the last one, keep this
1321 result and quit. Otherwise go on to the next one! */
1323 if (*(++argv))
1324 free (expansion);
1325 else
1327 o = variable_buffer_output (o, expansion, result);
1328 break;
1332 free (expansion);
1334 return o;
1337 static char *
1338 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1341 #ifdef _AMIGA
1342 o = wildcard_expansion (argv[0], o);
1343 #else
1344 char *p = string_glob (argv[0]);
1345 o = variable_buffer_output (o, p, strlen (p));
1346 #endif
1347 return o;
1351 $(eval <makefile string>)
1353 Always resolves to the empty string.
1355 Treat the arguments as a segment of makefile, and parse them.
1358 static char *
1359 func_eval (char *o, char **argv, const char *funcname UNUSED)
1361 char *buf;
1362 unsigned int len;
1364 /* Eval the buffer. Pop the current variable buffer setting so that the
1365 eval'd code can use its own without conflicting. */
1367 install_variable_buffer (&buf, &len);
1369 eval_buffer (argv[0]);
1371 restore_variable_buffer (buf, len);
1373 return o;
1377 static char *
1378 func_value (char *o, char **argv, const char *funcname UNUSED)
1380 /* Look up the variable. */
1381 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1383 /* Copy its value into the output buffer without expanding it. */
1384 if (v)
1385 o = variable_buffer_output (o, v->value, strlen(v->value));
1387 return o;
1391 \r is replaced on UNIX as well. Is this desirable?
1393 void
1394 fold_newlines (char *buffer, int *length)
1396 char *dst = buffer;
1397 char *src = buffer;
1398 char *last_nonnl = buffer -1;
1399 src[*length] = 0;
1400 for (; *src != '\0'; ++src)
1402 if (src[0] == '\r' && src[1] == '\n')
1403 continue;
1404 if (*src == '\n')
1406 *dst++ = ' ';
1408 else
1410 last_nonnl = dst;
1411 *dst++ = *src;
1414 *(++last_nonnl) = '\0';
1415 *length = last_nonnl - buffer;
1420 int shell_function_pid = 0, shell_function_completed;
1423 #ifdef WINDOWS32
1424 /*untested*/
1426 #include <windows.h>
1427 #include <io.h>
1428 #include "sub_proc.h"
1431 void
1432 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1434 SECURITY_ATTRIBUTES saAttr;
1435 HANDLE hIn;
1436 HANDLE hErr;
1437 HANDLE hChildOutRd;
1438 HANDLE hChildOutWr;
1439 HANDLE hProcess;
1442 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1443 saAttr.bInheritHandle = TRUE;
1444 saAttr.lpSecurityDescriptor = NULL;
1446 if (DuplicateHandle (GetCurrentProcess(),
1447 GetStdHandle(STD_INPUT_HANDLE),
1448 GetCurrentProcess(),
1449 &hIn,
1451 TRUE,
1452 DUPLICATE_SAME_ACCESS) == FALSE) {
1453 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1454 GetLastError());
1457 if (DuplicateHandle(GetCurrentProcess(),
1458 GetStdHandle(STD_ERROR_HANDLE),
1459 GetCurrentProcess(),
1460 &hErr,
1462 TRUE,
1463 DUPLICATE_SAME_ACCESS) == FALSE) {
1464 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1465 GetLastError());
1468 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1469 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1471 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1473 if (!hProcess)
1474 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1476 /* make sure that CreateProcess() has Path it needs */
1477 sync_Path_environment();
1479 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1480 /* register process for wait */
1481 process_register(hProcess);
1483 /* set the pid for returning to caller */
1484 *pid_p = (int) hProcess;
1486 /* set up to read data from child */
1487 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1489 /* this will be closed almost right away */
1490 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1491 } else {
1492 /* reap/cleanup the failed process */
1493 process_cleanup(hProcess);
1495 /* close handles which were duplicated, they weren't used */
1496 CloseHandle(hIn);
1497 CloseHandle(hErr);
1499 /* close pipe handles, they won't be used */
1500 CloseHandle(hChildOutRd);
1501 CloseHandle(hChildOutWr);
1503 /* set status for return */
1504 pipedes[0] = pipedes[1] = -1;
1505 *pid_p = -1;
1508 #endif
1511 #ifdef __MSDOS__
1512 FILE *
1513 msdos_openpipe (int* pipedes, int *pidp, char *text)
1515 FILE *fpipe=0;
1516 /* MSDOS can't fork, but it has `popen'. */
1517 struct variable *sh = lookup_variable ("SHELL", 5);
1518 int e;
1519 extern int dos_command_running, dos_status;
1521 /* Make sure not to bother processing an empty line. */
1522 while (isblank ((unsigned char)*text))
1523 ++text;
1524 if (*text == '\0')
1525 return 0;
1527 if (sh)
1529 char buf[PATH_MAX + 7];
1530 /* This makes sure $SHELL value is used by $(shell), even
1531 though the target environment is not passed to it. */
1532 sprintf (buf, "SHELL=%s", sh->value);
1533 putenv (buf);
1536 e = errno;
1537 errno = 0;
1538 dos_command_running = 1;
1539 dos_status = 0;
1540 /* If dos_status becomes non-zero, it means the child process
1541 was interrupted by a signal, like SIGINT or SIGQUIT. See
1542 fatal_error_signal in commands.c. */
1543 fpipe = popen (text, "rt");
1544 dos_command_running = 0;
1545 if (!fpipe || dos_status)
1547 pipedes[0] = -1;
1548 *pidp = -1;
1549 if (dos_status)
1550 errno = EINTR;
1551 else if (errno == 0)
1552 errno = ENOMEM;
1553 shell_function_completed = -1;
1555 else
1557 pipedes[0] = fileno (fpipe);
1558 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1559 errno = e;
1560 shell_function_completed = 1;
1562 return fpipe;
1564 #endif
1567 Do shell spawning, with the naughty bits for different OSes.
1570 #ifdef VMS
1572 /* VMS can't do $(shell ...) */
1573 #define func_shell 0
1575 #else
1576 #ifndef _AMIGA
1577 static char *
1578 func_shell (char *o, char **argv, const char *funcname UNUSED)
1580 char* batch_filename = NULL;
1581 unsigned int i;
1583 #ifdef __MSDOS__
1584 FILE *fpipe;
1585 #endif
1586 char **command_argv;
1587 char *error_prefix;
1588 char **envp;
1589 int pipedes[2];
1590 int pid;
1592 #ifndef __MSDOS__
1593 /* Construct the argument list. */
1594 command_argv = construct_command_argv (argv[0],
1595 (char **) NULL, (struct file *) 0,
1596 &batch_filename);
1597 if (command_argv == 0)
1598 return o;
1599 #endif
1601 /* Using a target environment for `shell' loses in cases like:
1602 export var = $(shell echo foobie)
1603 because target_environment hits a loop trying to expand $(var)
1604 to put it in the environment. This is even more confusing when
1605 var was not explicitly exported, but just appeared in the
1606 calling environment.
1608 envp = target_environment (NILF);
1611 envp = environ;
1613 /* For error messages. */
1614 if (reading_file && reading_file->filenm)
1616 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1617 sprintf (error_prefix,
1618 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1620 else
1621 error_prefix = "";
1623 #ifdef WINDOWS32
1625 windows32_openpipe (pipedes, &pid, command_argv, envp);
1627 if (pipedes[0] < 0) {
1628 /* open of the pipe failed, mark as failed execution */
1629 shell_function_completed = -1;
1631 return o;
1632 } else
1634 #elif defined(__MSDOS__)
1636 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1637 if (pipedes[0] < 0)
1639 perror_with_name (error_prefix, "pipe");
1640 return o;
1643 #else
1645 if (pipe (pipedes) < 0)
1647 perror_with_name (error_prefix, "pipe");
1648 return o;
1651 # ifdef __EMX__
1653 /* close some handles that are unnecessary for the child process */
1654 CLOSE_ON_EXEC(pipedes[1]);
1655 CLOSE_ON_EXEC(pipedes[0]);
1656 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1657 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1658 if (pid < 0)
1659 perror_with_name (error_prefix, "spawn");
1661 # else /* ! __EMX__ */
1663 pid = vfork ();
1664 if (pid < 0)
1665 perror_with_name (error_prefix, "fork");
1666 else if (pid == 0)
1667 child_execute_job (0, pipedes[1], command_argv, envp);
1668 else
1670 # endif
1672 #endif
1674 /* We are the parent. */
1676 char *buffer;
1677 unsigned int maxlen;
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 ((char *) command_argv);
1689 /* Close the write side of the pipe. */
1690 (void) close (pipedes[1]);
1691 #endif
1693 /* Set up and read from the pipe. */
1695 maxlen = 200;
1696 buffer = (char *) 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 = (char *) 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 most likely means that the execvp failed,
1741 so we should just write out the error message
1742 that came in over the pipe from the child. */
1743 fputs (buffer, stderr);
1744 fflush (stderr);
1746 else
1748 /* The child finished normally. Replace all
1749 newlines in its output with spaces, and put
1750 that in the variable output buffer. */
1751 fold_newlines (buffer, &i);
1752 o = variable_buffer_output (o, buffer, i);
1755 free (buffer);
1758 return o;
1761 #else /* _AMIGA */
1763 /* Do the Amiga version of func_shell. */
1765 static char *
1766 func_shell (char *o, char **argv, const char *funcname)
1768 /* Amiga can't fork nor spawn, but I can start a program with
1769 redirection of my choice. However, this means that we
1770 don't have an opportunity to reopen stdout to trap it. Thus,
1771 we save our own stdout onto a new descriptor and dup a temp
1772 file's descriptor onto our stdout temporarily. After we
1773 spawn the shell program, we dup our own stdout back to the
1774 stdout descriptor. The buffer reading is the same as above,
1775 except that we're now reading from a file. */
1777 #include <dos/dos.h>
1778 #include <proto/dos.h>
1780 BPTR child_stdout;
1781 char tmp_output[FILENAME_MAX];
1782 unsigned int maxlen = 200;
1783 int cc, i;
1784 char * buffer, * ptr;
1785 char ** aptr;
1786 int len = 0;
1787 char* batch_filename = NULL;
1789 /* Construct the argument list. */
1790 command_argv = construct_command_argv (argv[0], (char **) NULL,
1791 (struct file *) 0, &batch_filename);
1792 if (command_argv == 0)
1793 return o;
1795 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1796 Ideally we would use main.c:open_tmpfile(), but this uses a special
1797 Open(), not fopen(), and I'm not familiar enough with the code to mess
1798 with it. */
1799 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1800 mktemp (tmp_output);
1801 child_stdout = Open (tmp_output, MODE_NEWFILE);
1803 for (aptr=command_argv; *aptr; aptr++)
1804 len += strlen (*aptr) + 1;
1806 buffer = xmalloc (len + 1);
1807 ptr = buffer;
1809 for (aptr=command_argv; *aptr; aptr++)
1811 strcpy (ptr, *aptr);
1812 ptr += strlen (ptr) + 1;
1813 *ptr ++ = ' ';
1814 *ptr = 0;
1817 ptr[-1] = '\n';
1819 Execute (buffer, NULL, child_stdout);
1820 free (buffer);
1822 Close (child_stdout);
1824 child_stdout = Open (tmp_output, MODE_OLDFILE);
1826 buffer = xmalloc (maxlen);
1827 i = 0;
1830 if (i == maxlen)
1832 maxlen += 512;
1833 buffer = (char *) xrealloc (buffer, maxlen + 1);
1836 cc = Read (child_stdout, &buffer[i], maxlen - i);
1837 if (cc > 0)
1838 i += cc;
1839 } while (cc > 0);
1841 Close (child_stdout);
1843 fold_newlines (buffer, &i);
1844 o = variable_buffer_output (o, buffer, i);
1845 free (buffer);
1846 return o;
1848 #endif /* _AMIGA */
1849 #endif /* !VMS */
1851 #ifdef EXPERIMENTAL
1854 equality. Return is string-boolean, ie, the empty string is false.
1856 static char *
1857 func_eq (char *o, char **argv, char *funcname)
1859 int result = ! strcmp (argv[0], argv[1]);
1860 o = variable_buffer_output (o, result ? "1" : "", result);
1861 return o;
1866 string-boolean not operator.
1868 static char *
1869 func_not (char *o, char **argv, char *funcname)
1871 char *s = argv[0];
1872 int result = 0;
1873 while (isspace ((unsigned char)*s))
1874 s++;
1875 result = ! (*s);
1876 o = variable_buffer_output (o, result ? "1" : "", result);
1877 return o;
1879 #endif
1882 /* Return the absolute name of file NAME which does not contain any `.',
1883 `..' components nor any repeated path separators ('/'). */
1885 static char *
1886 abspath (const char *name, char *apath)
1888 char *dest;
1889 const char *start, *end, *apath_limit;
1891 if (name[0] == '\0' || apath == NULL)
1892 return NULL;
1894 apath_limit = apath + GET_PATH_MAX;
1896 if (name[0] != '/')
1898 /* It is unlikely we would make it until here but just to make sure. */
1899 if (!starting_directory)
1900 return NULL;
1902 strcpy (apath, starting_directory);
1904 dest = strchr (apath, '\0');
1906 else
1908 apath[0] = '/';
1909 dest = apath + 1;
1912 for (start = end = name; *start != '\0'; start = end)
1914 unsigned long len;
1916 /* Skip sequence of multiple path-separators. */
1917 while (*start == '/')
1918 ++start;
1920 /* Find end of path component. */
1921 for (end = start; *end != '\0' && *end != '/'; ++end)
1924 len = end - start;
1926 if (len == 0)
1927 break;
1928 else if (len == 1 && start[0] == '.')
1929 /* nothing */;
1930 else if (len == 2 && start[0] == '.' && start[1] == '.')
1932 /* Back up to previous component, ignore if at root already. */
1933 if (dest > apath + 1)
1934 while ((--dest)[-1] != '/');
1936 else
1938 if (dest[-1] != '/')
1939 *dest++ = '/';
1941 if (dest + len >= apath_limit)
1942 return NULL;
1944 dest = memcpy (dest, start, len);
1945 dest += len;
1946 *dest = '\0';
1950 /* Unless it is root strip trailing separator. */
1951 if (dest > apath + 1 && dest[-1] == '/')
1952 --dest;
1954 *dest = '\0';
1956 return apath;
1960 static char *
1961 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1963 /* Expand the argument. */
1964 char *p = argv[0];
1965 char *path = 0;
1966 int doneany = 0;
1967 unsigned int len = 0;
1968 PATH_VAR (in);
1969 PATH_VAR (out);
1971 while ((path = find_next_token (&p, &len)) != 0)
1973 if (len < GET_PATH_MAX)
1975 strncpy (in, path, len);
1976 in[len] = '\0';
1980 #ifdef HAVE_REALPATH
1981 realpath (in, out)
1982 #else
1983 abspath (in, out)
1984 #endif
1987 o = variable_buffer_output (o, out, strlen (out));
1988 o = variable_buffer_output (o, " ", 1);
1989 doneany = 1;
1994 /* Kill last space. */
1995 if (doneany)
1996 --o;
1998 return o;
2001 static char *
2002 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2004 /* Expand the argument. */
2005 char *p = argv[0];
2006 char *path = 0;
2007 int doneany = 0;
2008 unsigned int len = 0;
2009 PATH_VAR (in);
2010 PATH_VAR (out);
2012 while ((path = find_next_token (&p, &len)) != 0)
2014 if (len < GET_PATH_MAX)
2016 strncpy (in, path, len);
2017 in[len] = '\0';
2019 if (abspath (in, out))
2021 o = variable_buffer_output (o, out, strlen (out));
2022 o = variable_buffer_output (o, " ", 1);
2023 doneany = 1;
2028 /* Kill last space. */
2029 if (doneany)
2030 --o;
2032 return o;
2035 /* Lookup table for builtin functions.
2037 This doesn't have to be sorted; we use a straight lookup. We might gain
2038 some efficiency by moving most often used functions to the start of the
2039 table.
2041 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2042 comma-separated values are treated as arguments.
2044 EXPAND_ARGS means that all arguments should be expanded before invocation.
2045 Functions that do namespace tricks (foreach) don't automatically expand. */
2047 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
2050 static struct function_table_entry function_table_init[] =
2052 /* Name/size */ /* MIN MAX EXP? Function */
2053 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2054 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2055 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2056 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2057 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2058 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2059 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2060 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2061 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2062 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2063 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2064 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2065 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2066 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2067 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2068 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2069 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2070 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2071 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2072 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2073 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2074 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2075 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2076 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2077 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2078 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2079 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2080 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2081 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2082 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2083 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2084 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2085 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2086 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2087 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2088 #ifdef EXPERIMENTAL
2089 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2090 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2091 #endif
2094 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2097 /* These must come after the definition of function_table. */
2099 static char *
2100 expand_builtin_function (char *o, int argc, char **argv,
2101 const struct function_table_entry *entry_p)
2103 if (argc < (int)entry_p->minimum_args)
2104 fatal (*expanding_var,
2105 _("insufficient number of arguments (%d) to function `%s'"),
2106 argc, entry_p->name);
2108 /* I suppose technically some function could do something with no
2109 arguments, but so far none do, so just test it for all functions here
2110 rather than in each one. We can change it later if necessary. */
2112 if (!argc)
2113 return o;
2115 if (!entry_p->func_ptr)
2116 fatal (*expanding_var,
2117 _("unimplemented on this platform: function `%s'"), entry_p->name);
2119 return entry_p->func_ptr (o, argv, entry_p->name);
2122 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2123 opening ( or { and is not null-terminated. If a function invocation
2124 is found, expand it into the buffer at *OP, updating *OP, incrementing
2125 *STRINGP past the reference and returning nonzero. If not, return zero. */
2128 handle_function (char **op, char **stringp)
2130 const struct function_table_entry *entry_p;
2131 char openparen = (*stringp)[0];
2132 char closeparen = openparen == '(' ? ')' : '}';
2133 char *beg;
2134 char *end;
2135 int count = 0;
2136 register char *p;
2137 char **argv, **argvp;
2138 int nargs;
2140 beg = *stringp + 1;
2142 entry_p = lookup_function (beg);
2144 if (!entry_p)
2145 return 0;
2147 /* We found a builtin function. Find the beginning of its arguments (skip
2148 whitespace after the name). */
2150 beg = next_token (beg + entry_p->len);
2152 /* Find the end of the function invocation, counting nested use of
2153 whichever kind of parens we use. Since we're looking, count commas
2154 to get a rough estimate of how many arguments we might have. The
2155 count might be high, but it'll never be low. */
2157 for (nargs=1, end=beg; *end != '\0'; ++end)
2158 if (*end == ',')
2159 ++nargs;
2160 else if (*end == openparen)
2161 ++count;
2162 else if (*end == closeparen && --count < 0)
2163 break;
2165 if (count >= 0)
2166 fatal (*expanding_var,
2167 _("unterminated call to function `%s': missing `%c'"),
2168 entry_p->name, closeparen);
2170 *stringp = end;
2172 /* Get some memory to store the arg pointers. */
2173 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
2175 /* Chop the string into arguments, then a nul. As soon as we hit
2176 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2177 last argument.
2179 If we're expanding, store pointers to the expansion of each one. If
2180 not, make a duplicate of the string and point into that, nul-terminating
2181 each argument. */
2183 if (!entry_p->expand_args)
2185 int len = end - beg;
2187 p = xmalloc (len+1);
2188 memcpy (p, beg, len);
2189 p[len] = '\0';
2190 beg = p;
2191 end = beg + len;
2194 for (p=beg, nargs=0; p <= end; ++argvp)
2196 char *next;
2198 ++nargs;
2200 if (nargs == entry_p->maximum_args
2201 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2202 next = end;
2204 if (entry_p->expand_args)
2205 *argvp = expand_argument (p, next);
2206 else
2208 *argvp = p;
2209 *next = '\0';
2212 p = next + 1;
2214 *argvp = NULL;
2216 /* Finally! Run the function... */
2217 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2219 /* Free memory. */
2220 if (entry_p->expand_args)
2221 for (argvp=argv; *argvp != 0; ++argvp)
2222 free (*argvp);
2223 else
2224 free (beg);
2226 return 1;
2230 /* User-defined functions. Expand the first argument as either a builtin
2231 function or a make variable, in the context of the rest of the arguments
2232 assigned to $1, $2, ... $N. $0 is the name of the function. */
2234 static char *
2235 func_call (char *o, char **argv, const char *funcname UNUSED)
2237 static int max_args = 0;
2238 char *fname;
2239 char *cp;
2240 char *body;
2241 int flen;
2242 int i;
2243 int saved_args;
2244 const struct function_table_entry *entry_p;
2245 struct variable *v;
2247 /* There is no way to define a variable with a space in the name, so strip
2248 leading and trailing whitespace as a favor to the user. */
2249 fname = argv[0];
2250 while (*fname != '\0' && isspace ((unsigned char)*fname))
2251 ++fname;
2253 cp = fname + strlen (fname) - 1;
2254 while (cp > fname && isspace ((unsigned char)*cp))
2255 --cp;
2256 cp[1] = '\0';
2258 /* Calling nothing is a no-op */
2259 if (*fname == '\0')
2260 return o;
2262 /* Are we invoking a builtin function? */
2264 entry_p = lookup_function (fname);
2266 if (entry_p)
2268 /* How many arguments do we have? */
2269 for (i=0; argv[i+1]; ++i)
2272 return expand_builtin_function (o, i, argv+1, entry_p);
2275 /* Not a builtin, so the first argument is the name of a variable to be
2276 expanded and interpreted as a function. Find it. */
2277 flen = strlen (fname);
2279 v = lookup_variable (fname, flen);
2281 if (v == 0)
2282 warn_undefined (fname, flen);
2284 if (v == 0 || *v->value == '\0')
2285 return o;
2287 body = (char *) alloca (flen + 4);
2288 body[0] = '$';
2289 body[1] = '(';
2290 memcpy (body + 2, fname, flen);
2291 body[flen+2] = ')';
2292 body[flen+3] = '\0';
2294 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2296 push_new_variable_scope ();
2298 for (i=0; *argv; ++i, ++argv)
2300 char num[11];
2302 sprintf (num, "%d", i);
2303 define_variable (num, strlen (num), *argv, o_automatic, 0);
2306 /* If the number of arguments we have is < max_args, it means we're inside
2307 a recursive invocation of $(call ...). Fill in the remaining arguments
2308 in the new scope with the empty value, to hide them from this
2309 invocation. */
2311 for (; i < max_args; ++i)
2313 char num[11];
2315 sprintf (num, "%d", i);
2316 define_variable (num, strlen (num), "", o_automatic, 0);
2319 /* Expand the body in the context of the arguments, adding the result to
2320 the variable buffer. */
2322 v->exp_count = EXP_COUNT_MAX;
2324 saved_args = max_args;
2325 max_args = i;
2326 o = variable_expand_string (o, body, flen+3);
2327 max_args = saved_args;
2329 v->exp_count = 0;
2331 pop_variable_scope ();
2333 return o + strlen (o);
2336 void
2337 hash_init_function_table (void)
2339 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2340 function_table_entry_hash_1, function_table_entry_hash_2,
2341 function_table_entry_hash_cmp);
2342 hash_load (&function_table, function_table_init,
2343 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));