- Fix broken handling of order-only prereqs in secondary expansion
[make.git] / function.c
bloba2adc315e576072a08175f55edf97a6bcb1485ce
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 = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
359 /* We do not want parse_file_seq to strip `./'s.
360 That would break examples like:
361 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
362 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
364 if (result == 0)
366 length = 100;
367 result = xmalloc (100);
370 idx = 0;
371 while (chain != 0)
373 struct nameseq *next = chain->next;
374 unsigned int len = strlen (chain->name);
376 if (idx + len + 1 > length)
378 length += (len + 1) * 2;
379 result = xrealloc (result, length);
381 memcpy (&result[idx], chain->name, len);
382 idx += len;
383 result[idx++] = ' ';
385 free (chain);
386 chain = next;
389 /* Kill the last space and terminate the string. */
390 if (idx == 0)
391 result[0] = '\0';
392 else
393 result[idx - 1] = '\0';
395 return result;
399 Builtin functions
402 static char *
403 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
405 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
406 return o;
410 static char *
411 func_join (char *o, char **argv, const char *funcname UNUSED)
413 int doneany = 0;
415 /* Write each word of the first argument directly followed
416 by the corresponding word of the second argument.
417 If the two arguments have a different number of words,
418 the excess words are just output separated by blanks. */
419 const char *tp;
420 const char *pp;
421 const char *list1_iterator = argv[0];
422 const char *list2_iterator = argv[1];
425 unsigned int len1, len2;
427 tp = find_next_token (&list1_iterator, &len1);
428 if (tp != 0)
429 o = variable_buffer_output (o, tp, len1);
431 pp = find_next_token (&list2_iterator, &len2);
432 if (pp != 0)
433 o = variable_buffer_output (o, pp, len2);
435 if (tp != 0 || pp != 0)
437 o = variable_buffer_output (o, " ", 1);
438 doneany = 1;
441 while (tp != 0 || pp != 0);
442 if (doneany)
443 /* Kill the last blank. */
444 --o;
446 return o;
450 static char *
451 func_origin (char *o, char **argv, const char *funcname UNUSED)
453 /* Expand the argument. */
454 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
455 if (v == 0)
456 o = variable_buffer_output (o, "undefined", 9);
457 else
458 switch (v->origin)
460 default:
461 case o_invalid:
462 abort ();
463 break;
464 case o_default:
465 o = variable_buffer_output (o, "default", 7);
466 break;
467 case o_env:
468 o = variable_buffer_output (o, "environment", 11);
469 break;
470 case o_file:
471 o = variable_buffer_output (o, "file", 4);
472 break;
473 case o_env_override:
474 o = variable_buffer_output (o, "environment override", 20);
475 break;
476 case o_command:
477 o = variable_buffer_output (o, "command line", 12);
478 break;
479 case o_override:
480 o = variable_buffer_output (o, "override", 8);
481 break;
482 case o_automatic:
483 o = variable_buffer_output (o, "automatic", 9);
484 break;
487 return o;
490 static char *
491 func_flavor (char *o, char **argv, const char *funcname UNUSED)
493 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
495 if (v == 0)
496 o = variable_buffer_output (o, "undefined", 9);
497 else
498 if (v->recursive)
499 o = variable_buffer_output (o, "recursive", 9);
500 else
501 o = variable_buffer_output (o, "simple", 6);
503 return o;
506 #ifdef VMS
507 # define IS_PATHSEP(c) ((c) == ']')
508 #else
509 # ifdef HAVE_DOS_PATHS
510 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
511 # else
512 # define IS_PATHSEP(c) ((c) == '/')
513 # endif
514 #endif
517 static char *
518 func_notdir_suffix (char *o, char **argv, const char *funcname)
520 /* Expand the argument. */
521 const char *list_iterator = argv[0];
522 const char *p2;
523 int doneany =0;
524 unsigned int len=0;
526 int is_suffix = streq (funcname, "suffix");
527 int is_notdir = !is_suffix;
528 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
530 const char *p = p2 + len;
533 while (p >= p2 && (!is_suffix || *p != '.'))
535 if (IS_PATHSEP (*p))
536 break;
537 --p;
540 if (p >= p2)
542 if (is_notdir)
543 ++p;
544 else if (*p != '.')
545 continue;
546 o = variable_buffer_output (o, p, len - (p - p2));
548 #ifdef HAVE_DOS_PATHS
549 /* Handle the case of "d:foo/bar". */
550 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
552 p = p2 + 2;
553 o = variable_buffer_output (o, p, len - (p - p2));
555 #endif
556 else if (is_notdir)
557 o = variable_buffer_output (o, p2, len);
559 if (is_notdir || p >= p2)
561 o = variable_buffer_output (o, " ", 1);
562 doneany = 1;
566 if (doneany)
567 /* Kill last space. */
568 --o;
570 return o;
574 static char *
575 func_basename_dir (char *o, char **argv, const char *funcname)
577 /* Expand the argument. */
578 const char *p3 = argv[0];
579 const char *p2;
580 int doneany=0;
581 unsigned int len=0;
583 int is_basename= streq (funcname, "basename");
584 int is_dir= !is_basename;
586 while ((p2 = find_next_token (&p3, &len)) != 0)
588 const char *p = p2 + len;
589 while (p >= p2 && (!is_basename || *p != '.'))
591 if (IS_PATHSEP (*p))
592 break;
593 --p;
596 if (p >= p2 && (is_dir))
597 o = variable_buffer_output (o, p2, ++p - p2);
598 else if (p >= p2 && (*p == '.'))
599 o = variable_buffer_output (o, p2, p - p2);
600 #ifdef HAVE_DOS_PATHS
601 /* Handle the "d:foobar" case */
602 else if (p2[0] && p2[1] == ':' && is_dir)
603 o = variable_buffer_output (o, p2, 2);
604 #endif
605 else if (is_dir)
606 #ifdef VMS
607 o = variable_buffer_output (o, "[]", 2);
608 #else
609 #ifndef _AMIGA
610 o = variable_buffer_output (o, "./", 2);
611 #else
612 ; /* Just a nop... */
613 #endif /* AMIGA */
614 #endif /* !VMS */
615 else
616 /* The entire name is the basename. */
617 o = variable_buffer_output (o, p2, len);
619 o = variable_buffer_output (o, " ", 1);
620 doneany = 1;
623 if (doneany)
624 /* Kill last space. */
625 --o;
627 return o;
630 static char *
631 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
633 int fixlen = strlen (argv[0]);
634 const char *list_iterator = argv[1];
635 int is_addprefix = streq (funcname, "addprefix");
636 int is_addsuffix = !is_addprefix;
638 int doneany = 0;
639 const char *p;
640 unsigned int len;
642 while ((p = find_next_token (&list_iterator, &len)) != 0)
644 if (is_addprefix)
645 o = variable_buffer_output (o, argv[0], fixlen);
646 o = variable_buffer_output (o, p, len);
647 if (is_addsuffix)
648 o = variable_buffer_output (o, argv[0], fixlen);
649 o = variable_buffer_output (o, " ", 1);
650 doneany = 1;
653 if (doneany)
654 /* Kill last space. */
655 --o;
657 return o;
660 static char *
661 func_subst (char *o, char **argv, const char *funcname UNUSED)
663 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
664 strlen (argv[1]), 0);
666 return o;
670 static char *
671 func_firstword (char *o, char **argv, const char *funcname UNUSED)
673 unsigned int i;
674 const char *words = argv[0]; /* Use a temp variable for find_next_token */
675 const char *p = find_next_token (&words, &i);
677 if (p != 0)
678 o = variable_buffer_output (o, p, i);
680 return o;
683 static char *
684 func_lastword (char *o, char **argv, const char *funcname UNUSED)
686 unsigned int i;
687 const char *words = argv[0]; /* Use a temp variable for find_next_token */
688 const char *p = NULL;
689 const char *t;
691 while ((t = find_next_token (&words, &i)))
692 p = t;
694 if (p != 0)
695 o = variable_buffer_output (o, p, i);
697 return o;
700 static char *
701 func_words (char *o, char **argv, const char *funcname UNUSED)
703 int i = 0;
704 const char *word_iterator = argv[0];
705 char buf[20];
707 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
708 ++i;
710 sprintf (buf, "%d", i);
711 o = variable_buffer_output (o, buf, strlen (buf));
713 return o;
716 /* Set begpp to point to the first non-whitespace character of the string,
717 * and endpp to point to the last non-whitespace character of the string.
718 * If the string is empty or contains nothing but whitespace, endpp will be
719 * begpp-1.
721 char *
722 strip_whitespace (const char **begpp, const char **endpp)
724 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
725 (*begpp) ++;
726 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
727 (*endpp) --;
728 return (char *)*begpp;
731 static void
732 check_numeric (const char *s, const char *msg)
734 const char *end = s + strlen (s) - 1;
735 const char *beg = s;
736 strip_whitespace (&s, &end);
738 for (; s <= end; ++s)
739 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
740 break;
742 if (s <= end || end - beg < 0)
743 fatal (*expanding_var, "%s: '%s'", msg, beg);
748 static char *
749 func_word (char *o, char **argv, const char *funcname UNUSED)
751 const char *end_p;
752 const char *p;
753 int i;
755 /* Check the first argument. */
756 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
757 i = atoi (argv[0]);
759 if (i == 0)
760 fatal (*expanding_var,
761 _("first argument to `word' function must be greater than 0"));
763 end_p = argv[1];
764 while ((p = find_next_token (&end_p, 0)) != 0)
765 if (--i == 0)
766 break;
768 if (i == 0)
769 o = variable_buffer_output (o, p, end_p - p);
771 return o;
774 static char *
775 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
777 int start, count;
779 /* Check the arguments. */
780 check_numeric (argv[0],
781 _("non-numeric first argument to `wordlist' function"));
782 check_numeric (argv[1],
783 _("non-numeric second argument to `wordlist' function"));
785 start = atoi (argv[0]);
786 if (start < 1)
787 fatal (*expanding_var,
788 "invalid first argument to `wordlist' function: `%d'", start);
790 count = atoi (argv[1]) - start + 1;
792 if (count > 0)
794 const char *p;
795 const char *end_p = argv[2];
797 /* Find the beginning of the "start"th word. */
798 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
801 if (p)
803 /* Find the end of the "count"th word from start. */
804 while (--count && (find_next_token (&end_p, 0) != 0))
807 /* Return the stuff in the middle. */
808 o = variable_buffer_output (o, p, end_p - p);
812 return o;
815 static char *
816 func_findstring (char *o, char **argv, const char *funcname UNUSED)
818 /* Find the first occurrence of the first string in the second. */
819 if (strstr (argv[1], argv[0]) != 0)
820 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
822 return o;
825 static char *
826 func_foreach (char *o, char **argv, const char *funcname UNUSED)
828 /* expand only the first two. */
829 char *varname = expand_argument (argv[0], NULL);
830 char *list = expand_argument (argv[1], NULL);
831 const char *body = argv[2];
833 int doneany = 0;
834 const char *list_iterator = list;
835 const char *p;
836 unsigned int len;
837 struct variable *var;
839 push_new_variable_scope ();
840 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
842 /* loop through LIST, put the value in VAR and expand BODY */
843 while ((p = find_next_token (&list_iterator, &len)) != 0)
845 char *result = 0;
847 free (var->value);
848 var->value = xstrndup (p, len);
850 result = allocated_variable_expand (body);
852 o = variable_buffer_output (o, result, strlen (result));
853 o = variable_buffer_output (o, " ", 1);
854 doneany = 1;
855 free (result);
858 if (doneany)
859 /* Kill the last space. */
860 --o;
862 pop_variable_scope ();
863 free (varname);
864 free (list);
866 return o;
869 struct a_word
871 struct a_word *next;
872 struct a_word *chain;
873 char *str;
874 int length;
875 int matched;
878 static unsigned long
879 a_word_hash_1 (const void *key)
881 return_STRING_HASH_1 (((struct a_word const *) key)->str);
884 static unsigned long
885 a_word_hash_2 (const void *key)
887 return_STRING_HASH_2 (((struct a_word const *) key)->str);
890 static int
891 a_word_hash_cmp (const void *x, const void *y)
893 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
894 if (result)
895 return result;
896 return_STRING_COMPARE (((struct a_word const *) x)->str,
897 ((struct a_word const *) y)->str);
900 struct a_pattern
902 struct a_pattern *next;
903 char *str;
904 char *percent;
905 int length;
906 int save_c;
909 static char *
910 func_filter_filterout (char *o, char **argv, const char *funcname)
912 struct a_word *wordhead;
913 struct a_word **wordtail;
914 struct a_word *wp;
915 struct a_pattern *pathead;
916 struct a_pattern **pattail;
917 struct a_pattern *pp;
919 struct hash_table a_word_table;
920 int is_filter = streq (funcname, "filter");
921 const char *pat_iterator = argv[0];
922 const char *word_iterator = argv[1];
923 int literals = 0;
924 int words = 0;
925 int hashing = 0;
926 char *p;
927 unsigned int len;
929 /* Chop ARGV[0] up into patterns to match against the words. */
931 pattail = &pathead;
932 while ((p = find_next_token (&pat_iterator, &len)) != 0)
934 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
936 *pattail = pat;
937 pattail = &pat->next;
939 if (*pat_iterator != '\0')
940 ++pat_iterator;
942 pat->str = p;
943 pat->length = len;
944 pat->save_c = p[len];
945 p[len] = '\0';
946 pat->percent = find_percent (p);
947 if (pat->percent == 0)
948 literals++;
950 *pattail = 0;
952 /* Chop ARGV[1] up into words to match against the patterns. */
954 wordtail = &wordhead;
955 while ((p = find_next_token (&word_iterator, &len)) != 0)
957 struct a_word *word = alloca (sizeof (struct a_word));
959 *wordtail = word;
960 wordtail = &word->next;
962 if (*word_iterator != '\0')
963 ++word_iterator;
965 p[len] = '\0';
966 word->str = p;
967 word->length = len;
968 word->matched = 0;
969 word->chain = 0;
970 words++;
972 *wordtail = 0;
974 /* Only use a hash table if arg list lengths justifies the cost. */
975 hashing = (literals >= 2 && (literals * words) >= 10);
976 if (hashing)
978 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
979 a_word_hash_cmp);
980 for (wp = wordhead; wp != 0; wp = wp->next)
982 struct a_word *owp = hash_insert (&a_word_table, wp);
983 if (owp)
984 wp->chain = owp;
988 if (words)
990 int doneany = 0;
992 /* Run each pattern through the words, killing words. */
993 for (pp = pathead; pp != 0; pp = pp->next)
995 if (pp->percent)
996 for (wp = wordhead; wp != 0; wp = wp->next)
997 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
998 else if (hashing)
1000 struct a_word a_word_key;
1001 a_word_key.str = pp->str;
1002 a_word_key.length = pp->length;
1003 wp = hash_find_item (&a_word_table, &a_word_key);
1004 while (wp)
1006 wp->matched |= 1;
1007 wp = wp->chain;
1010 else
1011 for (wp = wordhead; wp != 0; wp = wp->next)
1012 wp->matched |= (wp->length == pp->length
1013 && strneq (pp->str, wp->str, wp->length));
1016 /* Output the words that matched (or didn't, for filter-out). */
1017 for (wp = wordhead; wp != 0; wp = wp->next)
1018 if (is_filter ? wp->matched : !wp->matched)
1020 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1021 o = variable_buffer_output (o, " ", 1);
1022 doneany = 1;
1025 if (doneany)
1026 /* Kill the last space. */
1027 --o;
1030 for (pp = pathead; pp != 0; pp = pp->next)
1031 pp->str[pp->length] = pp->save_c;
1033 if (hashing)
1034 hash_free (&a_word_table, 0);
1036 return o;
1040 static char *
1041 func_strip (char *o, char **argv, const char *funcname UNUSED)
1043 const char *p = argv[0];
1044 int doneany = 0;
1046 while (*p != '\0')
1048 int i=0;
1049 const char *word_start;
1051 while (isspace ((unsigned char)*p))
1052 ++p;
1053 word_start = p;
1054 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1056 if (!i)
1057 break;
1058 o = variable_buffer_output (o, word_start, i);
1059 o = variable_buffer_output (o, " ", 1);
1060 doneany = 1;
1063 if (doneany)
1064 /* Kill the last space. */
1065 --o;
1067 return o;
1071 Print a warning or fatal message.
1073 static char *
1074 func_error (char *o, char **argv, const char *funcname)
1076 char **argvp;
1077 char *msg, *p;
1078 int len;
1080 /* The arguments will be broken on commas. Rather than create yet
1081 another special case where function arguments aren't broken up,
1082 just create a format string that puts them back together. */
1083 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1084 len += strlen (*argvp) + 2;
1086 p = msg = alloca (len + 1);
1088 for (argvp=argv; argvp[1] != 0; ++argvp)
1090 strcpy (p, *argvp);
1091 p += strlen (*argvp);
1092 *(p++) = ',';
1093 *(p++) = ' ';
1095 strcpy (p, *argvp);
1097 switch (*funcname) {
1098 case 'e':
1099 fatal (reading_file, "%s", msg);
1101 case 'w':
1102 error (reading_file, "%s", msg);
1103 break;
1105 case 'i':
1106 printf ("%s\n", msg);
1107 fflush(stdout);
1108 break;
1110 default:
1111 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1114 /* The warning function expands to the empty string. */
1115 return o;
1120 chop argv[0] into words, and sort them.
1122 static char *
1123 func_sort (char *o, char **argv, const char *funcname UNUSED)
1125 const char *t;
1126 char **words;
1127 int wordi;
1128 char *p;
1129 unsigned int len;
1130 int i;
1132 /* Find the maximum number of words we'll have. */
1133 t = argv[0];
1134 wordi = 1;
1135 while (*t != '\0')
1137 char c = *(t++);
1139 if (! isspace ((unsigned char)c))
1140 continue;
1142 ++wordi;
1144 while (isspace ((unsigned char)*t))
1145 ++t;
1148 words = xmalloc (wordi * sizeof (char *));
1150 /* Now assign pointers to each string in the array. */
1151 t = argv[0];
1152 wordi = 0;
1153 while ((p = find_next_token (&t, &len)) != 0)
1155 ++t;
1156 p[len] = '\0';
1157 words[wordi++] = p;
1160 if (wordi)
1162 /* Now sort the list of words. */
1163 qsort (words, wordi, sizeof (char *), alpha_compare);
1165 /* Now write the sorted list, uniquified. */
1166 for (i = 0; i < wordi; ++i)
1168 len = strlen (words[i]);
1169 if (i == wordi - 1 || strlen (words[i + 1]) != len
1170 || strcmp (words[i], words[i + 1]))
1172 o = variable_buffer_output (o, words[i], len);
1173 o = variable_buffer_output (o, " ", 1);
1177 /* Kill the last space. */
1178 --o;
1181 free (words);
1183 return o;
1187 $(if condition,true-part[,false-part])
1189 CONDITION is false iff it evaluates to an empty string. White
1190 space before and after condition are stripped before evaluation.
1192 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1193 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1194 you can use $(if ...) to create side-effects (with $(shell ...), for
1195 example).
1198 static char *
1199 func_if (char *o, char **argv, const char *funcname UNUSED)
1201 const char *begp = argv[0];
1202 const char *endp = begp + strlen (argv[0]) - 1;
1203 int result = 0;
1205 /* Find the result of the condition: if we have a value, and it's not
1206 empty, the condition is true. If we don't have a value, or it's the
1207 empty string, then it's false. */
1209 strip_whitespace (&begp, &endp);
1211 if (begp <= endp)
1213 char *expansion = expand_argument (begp, endp+1);
1215 result = strlen (expansion);
1216 free (expansion);
1219 /* If the result is true (1) we want to eval the first argument, and if
1220 it's false (0) we want to eval the second. If the argument doesn't
1221 exist we do nothing, otherwise expand it and add to the buffer. */
1223 argv += 1 + !result;
1225 if (*argv)
1227 char *expansion = expand_argument (*argv, NULL);
1229 o = variable_buffer_output (o, expansion, strlen (expansion));
1231 free (expansion);
1234 return o;
1238 $(or condition1[,condition2[,condition3[...]]])
1240 A CONDITION is false iff it evaluates to an empty string. White
1241 space before and after CONDITION are stripped before evaluation.
1243 CONDITION1 is evaluated. If it's true, then this is the result of
1244 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1245 the conditions are true, the expansion is the empty string.
1247 Once a CONDITION is true no further conditions are evaluated
1248 (short-circuiting).
1251 static char *
1252 func_or (char *o, char **argv, const char *funcname UNUSED)
1254 for ( ; *argv ; ++argv)
1256 const char *begp = *argv;
1257 const char *endp = begp + strlen (*argv) - 1;
1258 char *expansion;
1259 int result = 0;
1261 /* Find the result of the condition: if it's false keep going. */
1263 strip_whitespace (&begp, &endp);
1265 if (begp > endp)
1266 continue;
1268 expansion = expand_argument (begp, endp+1);
1269 result = strlen (expansion);
1271 /* If the result is false keep going. */
1272 if (!result)
1274 free (expansion);
1275 continue;
1278 /* It's true! Keep this result and return. */
1279 o = variable_buffer_output (o, expansion, result);
1280 free (expansion);
1281 break;
1284 return o;
1288 $(and condition1[,condition2[,condition3[...]]])
1290 A CONDITION is false iff it evaluates to an empty string. White
1291 space before and after CONDITION are stripped before evaluation.
1293 CONDITION1 is evaluated. If it's false, then this is the result of
1294 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1295 the conditions are true, the expansion is the result of the last condition.
1297 Once a CONDITION is false no further conditions are evaluated
1298 (short-circuiting).
1301 static char *
1302 func_and (char *o, char **argv, const char *funcname UNUSED)
1304 char *expansion;
1305 int result;
1307 while (1)
1309 const char *begp = *argv;
1310 const char *endp = begp + strlen (*argv) - 1;
1312 /* An empty condition is always false. */
1313 strip_whitespace (&begp, &endp);
1314 if (begp > endp)
1315 return o;
1317 expansion = expand_argument (begp, endp+1);
1318 result = strlen (expansion);
1320 /* If the result is false, stop here: we're done. */
1321 if (!result)
1322 break;
1324 /* Otherwise the result is true. If this is the last one, keep this
1325 result and quit. Otherwise go on to the next one! */
1327 if (*(++argv))
1328 free (expansion);
1329 else
1331 o = variable_buffer_output (o, expansion, result);
1332 break;
1336 free (expansion);
1338 return o;
1341 static char *
1342 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1344 #ifdef _AMIGA
1345 o = wildcard_expansion (argv[0], o);
1346 #else
1347 char *p = string_glob (argv[0]);
1348 o = variable_buffer_output (o, p, strlen (p));
1349 #endif
1350 return o;
1354 $(eval <makefile string>)
1356 Always resolves to the empty string.
1358 Treat the arguments as a segment of makefile, and parse them.
1361 static char *
1362 func_eval (char *o, char **argv, const char *funcname UNUSED)
1364 char *buf;
1365 unsigned int len;
1367 /* Eval the buffer. Pop the current variable buffer setting so that the
1368 eval'd code can use its own without conflicting. */
1370 install_variable_buffer (&buf, &len);
1372 eval_buffer (argv[0]);
1374 restore_variable_buffer (buf, len);
1376 return o;
1380 static char *
1381 func_value (char *o, char **argv, const char *funcname UNUSED)
1383 /* Look up the variable. */
1384 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1386 /* Copy its value into the output buffer without expanding it. */
1387 if (v)
1388 o = variable_buffer_output (o, v->value, strlen(v->value));
1390 return o;
1394 \r is replaced on UNIX as well. Is this desirable?
1396 static void
1397 fold_newlines (char *buffer, unsigned int *length)
1399 char *dst = buffer;
1400 char *src = buffer;
1401 char *last_nonnl = buffer -1;
1402 src[*length] = 0;
1403 for (; *src != '\0'; ++src)
1405 if (src[0] == '\r' && src[1] == '\n')
1406 continue;
1407 if (*src == '\n')
1409 *dst++ = ' ';
1411 else
1413 last_nonnl = dst;
1414 *dst++ = *src;
1417 *(++last_nonnl) = '\0';
1418 *length = last_nonnl - buffer;
1423 int shell_function_pid = 0, shell_function_completed;
1426 #ifdef WINDOWS32
1427 /*untested*/
1429 #include <windows.h>
1430 #include <io.h>
1431 #include "sub_proc.h"
1434 void
1435 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1437 SECURITY_ATTRIBUTES saAttr;
1438 HANDLE hIn;
1439 HANDLE hErr;
1440 HANDLE hChildOutRd;
1441 HANDLE hChildOutWr;
1442 HANDLE hProcess;
1445 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1446 saAttr.bInheritHandle = TRUE;
1447 saAttr.lpSecurityDescriptor = NULL;
1449 if (DuplicateHandle (GetCurrentProcess(),
1450 GetStdHandle(STD_INPUT_HANDLE),
1451 GetCurrentProcess(),
1452 &hIn,
1454 TRUE,
1455 DUPLICATE_SAME_ACCESS) == FALSE) {
1456 fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
1457 GetLastError());
1460 if (DuplicateHandle(GetCurrentProcess(),
1461 GetStdHandle(STD_ERROR_HANDLE),
1462 GetCurrentProcess(),
1463 &hErr,
1465 TRUE,
1466 DUPLICATE_SAME_ACCESS) == FALSE) {
1467 fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
1468 GetLastError());
1471 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1472 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1474 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1476 if (!hProcess)
1477 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1479 /* make sure that CreateProcess() has Path it needs */
1480 sync_Path_environment();
1481 /* `sync_Path_environment' may realloc `environ', so take note of
1482 the new value. */
1483 envp = environ;
1485 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1486 /* register process for wait */
1487 process_register(hProcess);
1489 /* set the pid for returning to caller */
1490 *pid_p = (int) hProcess;
1492 /* set up to read data from child */
1493 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1495 /* this will be closed almost right away */
1496 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1497 } else {
1498 /* reap/cleanup the failed process */
1499 process_cleanup(hProcess);
1501 /* close handles which were duplicated, they weren't used */
1502 CloseHandle(hIn);
1503 CloseHandle(hErr);
1505 /* close pipe handles, they won't be used */
1506 CloseHandle(hChildOutRd);
1507 CloseHandle(hChildOutWr);
1509 /* set status for return */
1510 pipedes[0] = pipedes[1] = -1;
1511 *pid_p = -1;
1514 #endif
1517 #ifdef __MSDOS__
1518 FILE *
1519 msdos_openpipe (int* pipedes, int *pidp, char *text)
1521 FILE *fpipe=0;
1522 /* MSDOS can't fork, but it has `popen'. */
1523 struct variable *sh = lookup_variable ("SHELL", 5);
1524 int e;
1525 extern int dos_command_running, dos_status;
1527 /* Make sure not to bother processing an empty line. */
1528 while (isblank ((unsigned char)*text))
1529 ++text;
1530 if (*text == '\0')
1531 return 0;
1533 if (sh)
1535 char buf[PATH_MAX + 7];
1536 /* This makes sure $SHELL value is used by $(shell), even
1537 though the target environment is not passed to it. */
1538 sprintf (buf, "SHELL=%s", sh->value);
1539 putenv (buf);
1542 e = errno;
1543 errno = 0;
1544 dos_command_running = 1;
1545 dos_status = 0;
1546 /* If dos_status becomes non-zero, it means the child process
1547 was interrupted by a signal, like SIGINT or SIGQUIT. See
1548 fatal_error_signal in commands.c. */
1549 fpipe = popen (text, "rt");
1550 dos_command_running = 0;
1551 if (!fpipe || dos_status)
1553 pipedes[0] = -1;
1554 *pidp = -1;
1555 if (dos_status)
1556 errno = EINTR;
1557 else if (errno == 0)
1558 errno = ENOMEM;
1559 shell_function_completed = -1;
1561 else
1563 pipedes[0] = fileno (fpipe);
1564 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1565 errno = e;
1566 shell_function_completed = 1;
1568 return fpipe;
1570 #endif
1573 Do shell spawning, with the naughty bits for different OSes.
1576 #ifdef VMS
1578 /* VMS can't do $(shell ...) */
1579 #define func_shell 0
1581 #else
1582 #ifndef _AMIGA
1583 static char *
1584 func_shell (char *o, char **argv, const char *funcname UNUSED)
1586 char *batch_filename = NULL;
1588 #ifdef __MSDOS__
1589 FILE *fpipe;
1590 #endif
1591 char **command_argv;
1592 const char *error_prefix;
1593 char **envp;
1594 int pipedes[2];
1595 int pid;
1597 #ifndef __MSDOS__
1598 /* Construct the argument list. */
1599 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1600 &batch_filename);
1601 if (command_argv == 0)
1602 return o;
1603 #endif
1605 /* Using a target environment for `shell' loses in cases like:
1606 export var = $(shell echo foobie)
1607 because target_environment hits a loop trying to expand $(var)
1608 to put it in the environment. This is even more confusing when
1609 var was not explicitly exported, but just appeared in the
1610 calling environment.
1612 See Savannah bug #10593.
1614 envp = target_environment (NILF);
1617 envp = environ;
1619 /* For error messages. */
1620 if (reading_file && reading_file->filenm)
1622 char *p = alloca (strlen (reading_file->filenm)+11+4);
1623 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1624 error_prefix = p;
1626 else
1627 error_prefix = "";
1629 #if defined(__MSDOS__)
1630 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1631 if (pipedes[0] < 0)
1633 perror_with_name (error_prefix, "pipe");
1634 return o;
1636 #elif defined(WINDOWS32)
1637 windows32_openpipe (pipedes, &pid, command_argv, envp);
1638 if (pipedes[0] < 0)
1640 /* open of the pipe failed, mark as failed execution */
1641 shell_function_completed = -1;
1643 return o;
1645 else
1646 #else
1647 if (pipe (pipedes) < 0)
1649 perror_with_name (error_prefix, "pipe");
1650 return o;
1653 # ifdef __EMX__
1654 /* close some handles that are unnecessary for the child process */
1655 CLOSE_ON_EXEC(pipedes[1]);
1656 CLOSE_ON_EXEC(pipedes[0]);
1657 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1658 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1659 if (pid < 0)
1660 perror_with_name (error_prefix, "spawn");
1661 # else /* ! __EMX__ */
1662 pid = vfork ();
1663 if (pid < 0)
1664 perror_with_name (error_prefix, "fork");
1665 else if (pid == 0)
1666 child_execute_job (0, pipedes[1], command_argv, envp);
1667 else
1668 # endif
1669 #endif
1671 /* We are the parent. */
1672 char *buffer;
1673 unsigned int maxlen, i;
1674 int cc;
1676 /* Record the PID for reap_children. */
1677 shell_function_pid = pid;
1678 #ifndef __MSDOS__
1679 shell_function_completed = 0;
1681 /* Free the storage only the child needed. */
1682 free (command_argv[0]);
1683 free (command_argv);
1685 /* Close the write side of the pipe. We test for -1, since
1686 pipedes[1] is -1 on MS-Windows, and some versions of MS
1687 libraries barf when `close' is called with -1. */
1688 if (pipedes[1] >= 0)
1689 close (pipedes[1]);
1690 #endif
1692 /* Set up and read from the pipe. */
1694 maxlen = 200;
1695 buffer = xmalloc (maxlen + 1);
1697 /* Read from the pipe until it gets EOF. */
1698 for (i = 0; ; i += cc)
1700 if (i == maxlen)
1702 maxlen += 512;
1703 buffer = xrealloc (buffer, maxlen + 1);
1706 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1707 if (cc <= 0)
1708 break;
1710 buffer[i] = '\0';
1712 /* Close the read side of the pipe. */
1713 #ifdef __MSDOS__
1714 if (fpipe)
1715 (void) pclose (fpipe);
1716 #else
1717 (void) close (pipedes[0]);
1718 #endif
1720 /* Loop until child_handler or reap_children() sets
1721 shell_function_completed to the status of our child shell. */
1722 while (shell_function_completed == 0)
1723 reap_children (1, 0);
1725 if (batch_filename) {
1726 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1727 batch_filename));
1728 remove (batch_filename);
1729 free (batch_filename);
1731 shell_function_pid = 0;
1733 /* The child_handler function will set shell_function_completed
1734 to 1 when the child dies normally, or to -1 if it
1735 dies with status 127, which is most likely an exec fail. */
1737 if (shell_function_completed == -1)
1739 /* This likely means that the execvp failed, so we should just
1740 write the error message in the pipe from the child. */
1741 fputs (buffer, stderr);
1742 fflush (stderr);
1744 else
1746 /* The child finished normally. Replace all newlines in its output
1747 with spaces, and put that in the variable output buffer. */
1748 fold_newlines (buffer, &i);
1749 o = variable_buffer_output (o, buffer, i);
1752 free (buffer);
1755 return o;
1758 #else /* _AMIGA */
1760 /* Do the Amiga version of func_shell. */
1762 static char *
1763 func_shell (char *o, char **argv, const char *funcname)
1765 /* Amiga can't fork nor spawn, but I can start a program with
1766 redirection of my choice. However, this means that we
1767 don't have an opportunity to reopen stdout to trap it. Thus,
1768 we save our own stdout onto a new descriptor and dup a temp
1769 file's descriptor onto our stdout temporarily. After we
1770 spawn the shell program, we dup our own stdout back to the
1771 stdout descriptor. The buffer reading is the same as above,
1772 except that we're now reading from a file. */
1774 #include <dos/dos.h>
1775 #include <proto/dos.h>
1777 BPTR child_stdout;
1778 char tmp_output[FILENAME_MAX];
1779 unsigned int maxlen = 200, i;
1780 int cc;
1781 char * buffer, * ptr;
1782 char ** aptr;
1783 int len = 0;
1784 char* batch_filename = NULL;
1786 /* Construct the argument list. */
1787 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1788 &batch_filename);
1789 if (command_argv == 0)
1790 return o;
1792 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1793 Ideally we would use main.c:open_tmpfile(), but this uses a special
1794 Open(), not fopen(), and I'm not familiar enough with the code to mess
1795 with it. */
1796 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1797 mktemp (tmp_output);
1798 child_stdout = Open (tmp_output, MODE_NEWFILE);
1800 for (aptr=command_argv; *aptr; aptr++)
1801 len += strlen (*aptr) + 1;
1803 buffer = xmalloc (len + 1);
1804 ptr = buffer;
1806 for (aptr=command_argv; *aptr; aptr++)
1808 strcpy (ptr, *aptr);
1809 ptr += strlen (ptr) + 1;
1810 *ptr ++ = ' ';
1811 *ptr = 0;
1814 ptr[-1] = '\n';
1816 Execute (buffer, NULL, child_stdout);
1817 free (buffer);
1819 Close (child_stdout);
1821 child_stdout = Open (tmp_output, MODE_OLDFILE);
1823 buffer = xmalloc (maxlen);
1824 i = 0;
1827 if (i == maxlen)
1829 maxlen += 512;
1830 buffer = xrealloc (buffer, maxlen + 1);
1833 cc = Read (child_stdout, &buffer[i], maxlen - i);
1834 if (cc > 0)
1835 i += cc;
1836 } while (cc > 0);
1838 Close (child_stdout);
1840 fold_newlines (buffer, &i);
1841 o = variable_buffer_output (o, buffer, i);
1842 free (buffer);
1843 return o;
1845 #endif /* _AMIGA */
1846 #endif /* !VMS */
1848 #ifdef EXPERIMENTAL
1851 equality. Return is string-boolean, ie, the empty string is false.
1853 static char *
1854 func_eq (char *o, char **argv, char *funcname)
1856 int result = ! strcmp (argv[0], argv[1]);
1857 o = variable_buffer_output (o, result ? "1" : "", result);
1858 return o;
1863 string-boolean not operator.
1865 static char *
1866 func_not (char *o, char **argv, char *funcname)
1868 const char *s = argv[0];
1869 int result = 0;
1870 while (isspace ((unsigned char)*s))
1871 s++;
1872 result = ! (*s);
1873 o = variable_buffer_output (o, result ? "1" : "", result);
1874 return o;
1876 #endif
1879 #ifdef HAVE_DOS_PATHS
1880 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1881 #define ROOT_LEN 3
1882 #else
1883 #define IS_ABSOLUTE(n) (n[0] == '/')
1884 #define ROOT_LEN 1
1885 #endif
1887 /* Return the absolute name of file NAME which does not contain any `.',
1888 `..' components nor any repeated path separators ('/'). */
1890 static char *
1891 abspath (const char *name, char *apath)
1893 char *dest;
1894 const char *start, *end, *apath_limit;
1895 unsigned long root_len = ROOT_LEN;
1897 if (name[0] == '\0' || apath == NULL)
1898 return NULL;
1900 apath_limit = apath + GET_PATH_MAX;
1902 if (!IS_ABSOLUTE(name))
1904 /* It is unlikely we would make it until here but just to make sure. */
1905 if (!starting_directory)
1906 return NULL;
1908 strcpy (apath, starting_directory);
1910 #ifdef HAVE_DOS_PATHS
1911 if (IS_PATHSEP(name[0]))
1913 /* We have /foo, an absolute file name except for the drive
1914 letter. Assume the missing drive letter is the current
1915 drive, which we can get if we remove from starting_directory
1916 everything past the root directory. */
1917 apath[root_len] = '\0';
1919 #endif
1921 dest = strchr (apath, '\0');
1923 else
1925 strncpy (apath, name, root_len);
1926 apath[root_len] = '\0';
1927 dest = apath + root_len;
1928 /* Get past the root, since we already copied it. */
1929 name += root_len;
1930 #ifdef HAVE_DOS_PATHS
1931 if (!IS_PATHSEP(apath[2]))
1933 /* Convert d:foo into d:./foo and increase root_len. */
1934 apath[2] = '.';
1935 apath[3] = '/';
1936 dest++;
1937 root_len++;
1938 /* strncpy above copied one character too many. */
1939 name--;
1941 else
1942 apath[2] = '/'; /* make sure it's a forward slash */
1943 #endif
1946 for (start = end = name; *start != '\0'; start = end)
1948 unsigned long len;
1950 /* Skip sequence of multiple path-separators. */
1951 while (IS_PATHSEP(*start))
1952 ++start;
1954 /* Find end of path component. */
1955 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
1958 len = end - start;
1960 if (len == 0)
1961 break;
1962 else if (len == 1 && start[0] == '.')
1963 /* nothing */;
1964 else if (len == 2 && start[0] == '.' && start[1] == '.')
1966 /* Back up to previous component, ignore if at root already. */
1967 if (dest > apath + root_len)
1968 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
1970 else
1972 if (!IS_PATHSEP(dest[-1]))
1973 *dest++ = '/';
1975 if (dest + len >= apath_limit)
1976 return NULL;
1978 dest = memcpy (dest, start, len);
1979 dest += len;
1980 *dest = '\0';
1984 /* Unless it is root strip trailing separator. */
1985 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
1986 --dest;
1988 *dest = '\0';
1990 return apath;
1994 static char *
1995 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1997 /* Expand the argument. */
1998 const char *p = argv[0];
1999 const char *path = 0;
2000 int doneany = 0;
2001 unsigned int len = 0;
2002 #ifndef HAVE_REALPATH
2003 struct stat st;
2004 #endif
2005 PATH_VAR (in);
2006 PATH_VAR (out);
2008 while ((path = find_next_token (&p, &len)) != 0)
2010 if (len < GET_PATH_MAX)
2012 strncpy (in, path, len);
2013 in[len] = '\0';
2015 if (
2016 #ifdef HAVE_REALPATH
2017 realpath (in, out)
2018 #else
2019 abspath (in, out) && stat (out, &st) == 0
2020 #endif
2023 o = variable_buffer_output (o, out, strlen (out));
2024 o = variable_buffer_output (o, " ", 1);
2025 doneany = 1;
2030 /* Kill last space. */
2031 if (doneany)
2032 --o;
2034 return o;
2037 static char *
2038 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2040 /* Expand the argument. */
2041 const char *p = argv[0];
2042 const char *path = 0;
2043 int doneany = 0;
2044 unsigned int len = 0;
2045 PATH_VAR (in);
2046 PATH_VAR (out);
2048 while ((path = find_next_token (&p, &len)) != 0)
2050 if (len < GET_PATH_MAX)
2052 strncpy (in, path, len);
2053 in[len] = '\0';
2055 if (abspath (in, out))
2057 o = variable_buffer_output (o, out, strlen (out));
2058 o = variable_buffer_output (o, " ", 1);
2059 doneany = 1;
2064 /* Kill last space. */
2065 if (doneany)
2066 --o;
2068 return o;
2071 /* Lookup table for builtin functions.
2073 This doesn't have to be sorted; we use a straight lookup. We might gain
2074 some efficiency by moving most often used functions to the start of the
2075 table.
2077 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2078 comma-separated values are treated as arguments.
2080 EXPAND_ARGS means that all arguments should be expanded before invocation.
2081 Functions that do namespace tricks (foreach) don't automatically expand. */
2083 static char *func_call (char *o, char **argv, const char *funcname);
2086 static struct function_table_entry function_table_init[] =
2088 /* Name/size */ /* MIN MAX EXP? Function */
2089 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2090 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2091 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2092 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2093 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2094 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2095 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2096 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2097 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2098 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2099 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2100 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2101 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2102 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2103 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2104 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2105 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2106 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2107 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2108 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2109 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2110 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2111 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2112 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2113 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2114 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2115 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2116 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2117 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2118 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2119 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2120 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2121 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2122 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2123 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2124 #ifdef EXPERIMENTAL
2125 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2126 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2127 #endif
2130 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2133 /* These must come after the definition of function_table. */
2135 static char *
2136 expand_builtin_function (char *o, int argc, char **argv,
2137 const struct function_table_entry *entry_p)
2139 if (argc < (int)entry_p->minimum_args)
2140 fatal (*expanding_var,
2141 _("insufficient number of arguments (%d) to function `%s'"),
2142 argc, entry_p->name);
2144 /* I suppose technically some function could do something with no
2145 arguments, but so far none do, so just test it for all functions here
2146 rather than in each one. We can change it later if necessary. */
2148 if (!argc)
2149 return o;
2151 if (!entry_p->func_ptr)
2152 fatal (*expanding_var,
2153 _("unimplemented on this platform: function `%s'"), entry_p->name);
2155 return entry_p->func_ptr (o, argv, entry_p->name);
2158 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2159 opening ( or { and is not null-terminated. If a function invocation
2160 is found, expand it into the buffer at *OP, updating *OP, incrementing
2161 *STRINGP past the reference and returning nonzero. If not, return zero. */
2164 handle_function (char **op, const char **stringp)
2166 const struct function_table_entry *entry_p;
2167 char openparen = (*stringp)[0];
2168 char closeparen = openparen == '(' ? ')' : '}';
2169 const char *beg;
2170 const char *end;
2171 int count = 0;
2172 char *abeg = NULL;
2173 char **argv, **argvp;
2174 int nargs;
2176 beg = *stringp + 1;
2178 entry_p = lookup_function (beg);
2180 if (!entry_p)
2181 return 0;
2183 /* We found a builtin function. Find the beginning of its arguments (skip
2184 whitespace after the name). */
2186 beg = next_token (beg + entry_p->len);
2188 /* Find the end of the function invocation, counting nested use of
2189 whichever kind of parens we use. Since we're looking, count commas
2190 to get a rough estimate of how many arguments we might have. The
2191 count might be high, but it'll never be low. */
2193 for (nargs=1, end=beg; *end != '\0'; ++end)
2194 if (*end == ',')
2195 ++nargs;
2196 else if (*end == openparen)
2197 ++count;
2198 else if (*end == closeparen && --count < 0)
2199 break;
2201 if (count >= 0)
2202 fatal (*expanding_var,
2203 _("unterminated call to function `%s': missing `%c'"),
2204 entry_p->name, closeparen);
2206 *stringp = end;
2208 /* Get some memory to store the arg pointers. */
2209 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2211 /* Chop the string into arguments, then a nul. As soon as we hit
2212 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2213 last argument.
2215 If we're expanding, store pointers to the expansion of each one. If
2216 not, make a duplicate of the string and point into that, nul-terminating
2217 each argument. */
2219 if (entry_p->expand_args)
2221 const char *p;
2222 for (p=beg, nargs=0; p <= end; ++argvp)
2224 const char *next;
2226 ++nargs;
2228 if (nargs == entry_p->maximum_args
2229 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2230 next = end;
2232 *argvp = expand_argument (p, next);
2233 p = next + 1;
2236 else
2238 int len = end - beg;
2239 char *p, *aend;
2241 abeg = xmalloc (len+1);
2242 memcpy (abeg, beg, len);
2243 abeg[len] = '\0';
2244 aend = abeg + len;
2246 for (p=abeg, nargs=0; p <= aend; ++argvp)
2248 char *next;
2250 ++nargs;
2252 if (nargs == entry_p->maximum_args
2253 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2254 next = aend;
2256 *argvp = p;
2257 *next = '\0';
2258 p = next + 1;
2261 *argvp = NULL;
2263 /* Finally! Run the function... */
2264 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2266 /* Free memory. */
2267 if (entry_p->expand_args)
2268 for (argvp=argv; *argvp != 0; ++argvp)
2269 free (*argvp);
2270 if (abeg)
2271 free (abeg);
2273 return 1;
2277 /* User-defined functions. Expand the first argument as either a builtin
2278 function or a make variable, in the context of the rest of the arguments
2279 assigned to $1, $2, ... $N. $0 is the name of the function. */
2281 static char *
2282 func_call (char *o, char **argv, const char *funcname UNUSED)
2284 static int max_args = 0;
2285 char *fname;
2286 char *cp;
2287 char *body;
2288 int flen;
2289 int i;
2290 int saved_args;
2291 const struct function_table_entry *entry_p;
2292 struct variable *v;
2294 /* There is no way to define a variable with a space in the name, so strip
2295 leading and trailing whitespace as a favor to the user. */
2296 fname = argv[0];
2297 while (*fname != '\0' && isspace ((unsigned char)*fname))
2298 ++fname;
2300 cp = fname + strlen (fname) - 1;
2301 while (cp > fname && isspace ((unsigned char)*cp))
2302 --cp;
2303 cp[1] = '\0';
2305 /* Calling nothing is a no-op */
2306 if (*fname == '\0')
2307 return o;
2309 /* Are we invoking a builtin function? */
2311 entry_p = lookup_function (fname);
2312 if (entry_p)
2314 /* How many arguments do we have? */
2315 for (i=0; argv[i+1]; ++i)
2317 return expand_builtin_function (o, i, argv+1, entry_p);
2320 /* Not a builtin, so the first argument is the name of a variable to be
2321 expanded and interpreted as a function. Find it. */
2322 flen = strlen (fname);
2324 v = lookup_variable (fname, flen);
2326 if (v == 0)
2327 warn_undefined (fname, flen);
2329 if (v == 0 || *v->value == '\0')
2330 return o;
2332 body = alloca (flen + 4);
2333 body[0] = '$';
2334 body[1] = '(';
2335 memcpy (body + 2, fname, flen);
2336 body[flen+2] = ')';
2337 body[flen+3] = '\0';
2339 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2341 push_new_variable_scope ();
2343 for (i=0; *argv; ++i, ++argv)
2345 char num[11];
2347 sprintf (num, "%d", i);
2348 define_variable (num, strlen (num), *argv, o_automatic, 0);
2351 /* If the number of arguments we have is < max_args, it means we're inside
2352 a recursive invocation of $(call ...). Fill in the remaining arguments
2353 in the new scope with the empty value, to hide them from this
2354 invocation. */
2356 for (; i < max_args; ++i)
2358 char num[11];
2360 sprintf (num, "%d", i);
2361 define_variable (num, strlen (num), "", o_automatic, 0);
2364 /* Expand the body in the context of the arguments, adding the result to
2365 the variable buffer. */
2367 v->exp_count = EXP_COUNT_MAX;
2369 saved_args = max_args;
2370 max_args = i;
2371 o = variable_expand_string (o, body, flen+3);
2372 max_args = saved_args;
2374 v->exp_count = 0;
2376 pop_variable_scope ();
2378 return o + strlen (o);
2381 void
2382 hash_init_function_table (void)
2384 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2385 function_table_entry_hash_1, function_table_entry_hash_2,
2386 function_table_entry_hash_cmp);
2387 hash_load (&function_table, function_table_init,
2388 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));