- Update manual description for pattern rule search algorithm
[make.git] / function.c
blobd3acd8b6c99da277ba5ef1d96db2c89b6cdca022
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->name);
386 free (chain);
387 chain = next;
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]);
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 const char *tp;
421 const char *pp;
422 const char *list1_iterator = argv[0];
423 const 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 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 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 const char *list_iterator = argv[0];
523 const char *p2;
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 const 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;
567 if (doneany)
568 /* Kill last space. */
569 --o;
571 return o;
575 static char *
576 func_basename_dir (char *o, char **argv, const char *funcname)
578 /* Expand the argument. */
579 const char *p3 = argv[0];
580 const char *p2;
581 int doneany=0;
582 unsigned int len=0;
584 int is_basename= streq (funcname, "basename");
585 int is_dir= !is_basename;
587 while ((p2 = find_next_token (&p3, &len)) != 0)
589 const char *p = p2 + len;
590 while (p >= p2 && (!is_basename || *p != '.'))
592 if (IS_PATHSEP (*p))
593 break;
594 --p;
597 if (p >= p2 && (is_dir))
598 o = variable_buffer_output (o, p2, ++p - p2);
599 else if (p >= p2 && (*p == '.'))
600 o = variable_buffer_output (o, p2, p - p2);
601 #ifdef HAVE_DOS_PATHS
602 /* Handle the "d:foobar" case */
603 else if (p2[0] && p2[1] == ':' && is_dir)
604 o = variable_buffer_output (o, p2, 2);
605 #endif
606 else if (is_dir)
607 #ifdef VMS
608 o = variable_buffer_output (o, "[]", 2);
609 #else
610 #ifndef _AMIGA
611 o = variable_buffer_output (o, "./", 2);
612 #else
613 ; /* Just a nop... */
614 #endif /* AMIGA */
615 #endif /* !VMS */
616 else
617 /* The entire name is the basename. */
618 o = variable_buffer_output (o, p2, len);
620 o = variable_buffer_output (o, " ", 1);
621 doneany = 1;
624 if (doneany)
625 /* Kill last space. */
626 --o;
628 return o;
631 static char *
632 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
634 int fixlen = strlen (argv[0]);
635 const char *list_iterator = argv[1];
636 int is_addprefix = streq (funcname, "addprefix");
637 int is_addsuffix = !is_addprefix;
639 int doneany = 0;
640 const char *p;
641 unsigned int len;
643 while ((p = find_next_token (&list_iterator, &len)) != 0)
645 if (is_addprefix)
646 o = variable_buffer_output (o, argv[0], fixlen);
647 o = variable_buffer_output (o, p, len);
648 if (is_addsuffix)
649 o = variable_buffer_output (o, argv[0], fixlen);
650 o = variable_buffer_output (o, " ", 1);
651 doneany = 1;
654 if (doneany)
655 /* Kill last space. */
656 --o;
658 return o;
661 static char *
662 func_subst (char *o, char **argv, const char *funcname UNUSED)
664 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
665 strlen (argv[1]), 0);
667 return o;
671 static char *
672 func_firstword (char *o, char **argv, const char *funcname UNUSED)
674 unsigned int i;
675 const char *words = argv[0]; /* Use a temp variable for find_next_token */
676 const char *p = find_next_token (&words, &i);
678 if (p != 0)
679 o = variable_buffer_output (o, p, i);
681 return o;
684 static char *
685 func_lastword (char *o, char **argv, const char *funcname UNUSED)
687 unsigned int i;
688 const char *words = argv[0]; /* Use a temp variable for find_next_token */
689 const char *p = NULL;
690 const char *t;
692 while ((t = find_next_token (&words, &i)))
693 p = t;
695 if (p != 0)
696 o = variable_buffer_output (o, p, i);
698 return o;
701 static char *
702 func_words (char *o, char **argv, const char *funcname UNUSED)
704 int i = 0;
705 const char *word_iterator = argv[0];
706 char buf[20];
708 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
709 ++i;
711 sprintf (buf, "%d", i);
712 o = variable_buffer_output (o, buf, strlen (buf));
714 return o;
717 /* Set begpp to point to the first non-whitespace character of the string,
718 * and endpp to point to the last non-whitespace character of the string.
719 * If the string is empty or contains nothing but whitespace, endpp will be
720 * begpp-1.
722 char *
723 strip_whitespace (const char **begpp, const char **endpp)
725 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
726 (*begpp) ++;
727 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
728 (*endpp) --;
729 return (char *)*begpp;
732 static void
733 check_numeric (const char *s, const char *msg)
735 const char *end = s + strlen (s) - 1;
736 const char *beg = s;
737 strip_whitespace (&s, &end);
739 for (; s <= end; ++s)
740 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
741 break;
743 if (s <= end || end - beg < 0)
744 fatal (*expanding_var, "%s: '%s'", msg, beg);
749 static char *
750 func_word (char *o, char **argv, const char *funcname UNUSED)
752 const char *end_p;
753 const char *p;
754 int i;
756 /* Check the first argument. */
757 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
758 i = atoi (argv[0]);
760 if (i == 0)
761 fatal (*expanding_var,
762 _("first argument to `word' function must be greater than 0"));
764 end_p = argv[1];
765 while ((p = find_next_token (&end_p, 0)) != 0)
766 if (--i == 0)
767 break;
769 if (i == 0)
770 o = variable_buffer_output (o, p, end_p - p);
772 return o;
775 static char *
776 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
778 int start, count;
780 /* Check the arguments. */
781 check_numeric (argv[0],
782 _("non-numeric first argument to `wordlist' function"));
783 check_numeric (argv[1],
784 _("non-numeric second argument to `wordlist' function"));
786 start = atoi (argv[0]);
787 if (start < 1)
788 fatal (*expanding_var,
789 "invalid first argument to `wordlist' function: `%d'", start);
791 count = atoi (argv[1]) - start + 1;
793 if (count > 0)
795 const char *p;
796 const char *end_p = argv[2];
798 /* Find the beginning of the "start"th word. */
799 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
802 if (p)
804 /* Find the end of the "count"th word from start. */
805 while (--count && (find_next_token (&end_p, 0) != 0))
808 /* Return the stuff in the middle. */
809 o = variable_buffer_output (o, p, end_p - p);
813 return o;
816 static char *
817 func_findstring (char *o, char **argv, const char *funcname UNUSED)
819 /* Find the first occurrence of the first string in the second. */
820 if (strstr (argv[1], argv[0]) != 0)
821 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
823 return o;
826 static char *
827 func_foreach (char *o, char **argv, const char *funcname UNUSED)
829 /* expand only the first two. */
830 char *varname = expand_argument (argv[0], NULL);
831 char *list = expand_argument (argv[1], NULL);
832 const char *body = argv[2];
834 int doneany = 0;
835 const char *list_iterator = list;
836 const char *p;
837 unsigned int len;
838 struct variable *var;
840 push_new_variable_scope ();
841 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
843 /* loop through LIST, put the value in VAR and expand BODY */
844 while ((p = find_next_token (&list_iterator, &len)) != 0)
846 char *result = 0;
848 free (var->value);
849 var->value = xstrndup (p, len);
851 result = allocated_variable_expand (body);
853 o = variable_buffer_output (o, result, strlen (result));
854 o = variable_buffer_output (o, " ", 1);
855 doneany = 1;
856 free (result);
859 if (doneany)
860 /* Kill the last space. */
861 --o;
863 pop_variable_scope ();
864 free (varname);
865 free (list);
867 return o;
870 struct a_word
872 struct a_word *next;
873 struct a_word *chain;
874 char *str;
875 int length;
876 int matched;
879 static unsigned long
880 a_word_hash_1 (const void *key)
882 return_STRING_HASH_1 (((struct a_word const *) key)->str);
885 static unsigned long
886 a_word_hash_2 (const void *key)
888 return_STRING_HASH_2 (((struct a_word const *) key)->str);
891 static int
892 a_word_hash_cmp (const void *x, const void *y)
894 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
895 if (result)
896 return result;
897 return_STRING_COMPARE (((struct a_word const *) x)->str,
898 ((struct a_word const *) y)->str);
901 struct a_pattern
903 struct a_pattern *next;
904 char *str;
905 char *percent;
906 int length;
907 int save_c;
910 static char *
911 func_filter_filterout (char *o, char **argv, const char *funcname)
913 struct a_word *wordhead;
914 struct a_word **wordtail;
915 struct a_word *wp;
916 struct a_pattern *pathead;
917 struct a_pattern **pattail;
918 struct a_pattern *pp;
920 struct hash_table a_word_table;
921 int is_filter = streq (funcname, "filter");
922 const char *pat_iterator = argv[0];
923 const char *word_iterator = argv[1];
924 int literals = 0;
925 int words = 0;
926 int hashing = 0;
927 char *p;
928 unsigned int len;
930 /* Chop ARGV[0] up into patterns to match against the words. */
932 pattail = &pathead;
933 while ((p = find_next_token (&pat_iterator, &len)) != 0)
935 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
937 *pattail = pat;
938 pattail = &pat->next;
940 if (*pat_iterator != '\0')
941 ++pat_iterator;
943 pat->str = p;
944 pat->length = len;
945 pat->save_c = p[len];
946 p[len] = '\0';
947 pat->percent = find_percent (p);
948 if (pat->percent == 0)
949 literals++;
951 *pattail = 0;
953 /* Chop ARGV[1] up into words to match against the patterns. */
955 wordtail = &wordhead;
956 while ((p = find_next_token (&word_iterator, &len)) != 0)
958 struct a_word *word = alloca (sizeof (struct a_word));
960 *wordtail = word;
961 wordtail = &word->next;
963 if (*word_iterator != '\0')
964 ++word_iterator;
966 p[len] = '\0';
967 word->str = p;
968 word->length = len;
969 word->matched = 0;
970 word->chain = 0;
971 words++;
973 *wordtail = 0;
975 /* Only use a hash table if arg list lengths justifies the cost. */
976 hashing = (literals >= 2 && (literals * words) >= 10);
977 if (hashing)
979 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
980 a_word_hash_cmp);
981 for (wp = wordhead; wp != 0; wp = wp->next)
983 struct a_word *owp = hash_insert (&a_word_table, wp);
984 if (owp)
985 wp->chain = owp;
989 if (words)
991 int doneany = 0;
993 /* Run each pattern through the words, killing words. */
994 for (pp = pathead; pp != 0; pp = pp->next)
996 if (pp->percent)
997 for (wp = wordhead; wp != 0; wp = wp->next)
998 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
999 else if (hashing)
1001 struct a_word a_word_key;
1002 a_word_key.str = pp->str;
1003 a_word_key.length = pp->length;
1004 wp = hash_find_item (&a_word_table, &a_word_key);
1005 while (wp)
1007 wp->matched |= 1;
1008 wp = wp->chain;
1011 else
1012 for (wp = wordhead; wp != 0; wp = wp->next)
1013 wp->matched |= (wp->length == pp->length
1014 && strneq (pp->str, wp->str, wp->length));
1017 /* Output the words that matched (or didn't, for filter-out). */
1018 for (wp = wordhead; wp != 0; wp = wp->next)
1019 if (is_filter ? wp->matched : !wp->matched)
1021 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1022 o = variable_buffer_output (o, " ", 1);
1023 doneany = 1;
1026 if (doneany)
1027 /* Kill the last space. */
1028 --o;
1031 for (pp = pathead; pp != 0; pp = pp->next)
1032 pp->str[pp->length] = pp->save_c;
1034 if (hashing)
1035 hash_free (&a_word_table, 0);
1037 return o;
1041 static char *
1042 func_strip (char *o, char **argv, const char *funcname UNUSED)
1044 const char *p = argv[0];
1045 int doneany = 0;
1047 while (*p != '\0')
1049 int i=0;
1050 const char *word_start;
1052 while (isspace ((unsigned char)*p))
1053 ++p;
1054 word_start = p;
1055 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1057 if (!i)
1058 break;
1059 o = variable_buffer_output (o, word_start, i);
1060 o = variable_buffer_output (o, " ", 1);
1061 doneany = 1;
1064 if (doneany)
1065 /* Kill the last space. */
1066 --o;
1068 return o;
1072 Print a warning or fatal message.
1074 static char *
1075 func_error (char *o, char **argv, const char *funcname)
1077 char **argvp;
1078 char *msg, *p;
1079 int len;
1081 /* The arguments will be broken on commas. Rather than create yet
1082 another special case where function arguments aren't broken up,
1083 just create a format string that puts them back together. */
1084 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1085 len += strlen (*argvp) + 2;
1087 p = msg = alloca (len + 1);
1089 for (argvp=argv; argvp[1] != 0; ++argvp)
1091 strcpy (p, *argvp);
1092 p += strlen (*argvp);
1093 *(p++) = ',';
1094 *(p++) = ' ';
1096 strcpy (p, *argvp);
1098 switch (*funcname) {
1099 case 'e':
1100 fatal (reading_file, "%s", msg);
1102 case 'w':
1103 error (reading_file, "%s", msg);
1104 break;
1106 case 'i':
1107 printf ("%s\n", msg);
1108 fflush(stdout);
1109 break;
1111 default:
1112 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1115 /* The warning function expands to the empty string. */
1116 return o;
1121 chop argv[0] into words, and sort them.
1123 static char *
1124 func_sort (char *o, char **argv, const char *funcname UNUSED)
1126 const char *t;
1127 char **words;
1128 int wordi;
1129 char *p;
1130 unsigned int len;
1131 int i;
1133 /* Find the maximum number of words we'll have. */
1134 t = argv[0];
1135 wordi = 1;
1136 while (*t != '\0')
1138 char c = *(t++);
1140 if (! isspace ((unsigned char)c))
1141 continue;
1143 ++wordi;
1145 while (isspace ((unsigned char)*t))
1146 ++t;
1149 words = xmalloc (wordi * sizeof (char *));
1151 /* Now assign pointers to each string in the array. */
1152 t = argv[0];
1153 wordi = 0;
1154 while ((p = find_next_token (&t, &len)) != 0)
1156 ++t;
1157 p[len] = '\0';
1158 words[wordi++] = p;
1161 if (wordi)
1163 /* Now sort the list of words. */
1164 qsort (words, wordi, sizeof (char *), alpha_compare);
1166 /* Now write the sorted list, uniquified. */
1167 for (i = 0; i < wordi; ++i)
1169 len = strlen (words[i]);
1170 if (i == wordi - 1 || strlen (words[i + 1]) != len
1171 || strcmp (words[i], words[i + 1]))
1173 o = variable_buffer_output (o, words[i], len);
1174 o = variable_buffer_output (o, " ", 1);
1178 /* Kill the last space. */
1179 --o;
1182 free (words);
1184 return o;
1188 $(if condition,true-part[,false-part])
1190 CONDITION is false iff it evaluates to an empty string. White
1191 space before and after condition are stripped before evaluation.
1193 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1194 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1195 you can use $(if ...) to create side-effects (with $(shell ...), for
1196 example).
1199 static char *
1200 func_if (char *o, char **argv, const char *funcname UNUSED)
1202 const char *begp = argv[0];
1203 const char *endp = begp + strlen (argv[0]) - 1;
1204 int result = 0;
1206 /* Find the result of the condition: if we have a value, and it's not
1207 empty, the condition is true. If we don't have a value, or it's the
1208 empty string, then it's false. */
1210 strip_whitespace (&begp, &endp);
1212 if (begp <= endp)
1214 char *expansion = expand_argument (begp, endp+1);
1216 result = strlen (expansion);
1217 free (expansion);
1220 /* If the result is true (1) we want to eval the first argument, and if
1221 it's false (0) we want to eval the second. If the argument doesn't
1222 exist we do nothing, otherwise expand it and add to the buffer. */
1224 argv += 1 + !result;
1226 if (*argv)
1228 char *expansion = expand_argument (*argv, NULL);
1230 o = variable_buffer_output (o, expansion, strlen (expansion));
1232 free (expansion);
1235 return o;
1239 $(or condition1[,condition2[,condition3[...]]])
1241 A CONDITION is false iff it evaluates to an empty string. White
1242 space before and after CONDITION are stripped before evaluation.
1244 CONDITION1 is evaluated. If it's true, then this is the result of
1245 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1246 the conditions are true, the expansion is the empty string.
1248 Once a CONDITION is true no further conditions are evaluated
1249 (short-circuiting).
1252 static char *
1253 func_or (char *o, char **argv, const char *funcname UNUSED)
1255 for ( ; *argv ; ++argv)
1257 const char *begp = *argv;
1258 const char *endp = begp + strlen (*argv) - 1;
1259 char *expansion;
1260 int result = 0;
1262 /* Find the result of the condition: if it's false keep going. */
1264 strip_whitespace (&begp, &endp);
1266 if (begp > endp)
1267 continue;
1269 expansion = expand_argument (begp, endp+1);
1270 result = strlen (expansion);
1272 /* If the result is false keep going. */
1273 if (!result)
1275 free (expansion);
1276 continue;
1279 /* It's true! Keep this result and return. */
1280 o = variable_buffer_output (o, expansion, result);
1281 free (expansion);
1282 break;
1285 return o;
1289 $(and condition1[,condition2[,condition3[...]]])
1291 A CONDITION is false iff it evaluates to an empty string. White
1292 space before and after CONDITION are stripped before evaluation.
1294 CONDITION1 is evaluated. If it's false, then this is the result of
1295 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1296 the conditions are true, the expansion is the result of the last condition.
1298 Once a CONDITION is false no further conditions are evaluated
1299 (short-circuiting).
1302 static char *
1303 func_and (char *o, char **argv, const char *funcname UNUSED)
1305 char *expansion;
1306 int result;
1308 while (1)
1310 const char *begp = *argv;
1311 const char *endp = begp + strlen (*argv) - 1;
1313 /* An empty condition is always false. */
1314 strip_whitespace (&begp, &endp);
1315 if (begp > endp)
1316 return o;
1318 expansion = expand_argument (begp, endp+1);
1319 result = strlen (expansion);
1321 /* If the result is false, stop here: we're done. */
1322 if (!result)
1323 break;
1325 /* Otherwise the result is true. If this is the last one, keep this
1326 result and quit. Otherwise go on to the next one! */
1328 if (*(++argv))
1329 free (expansion);
1330 else
1332 o = variable_buffer_output (o, expansion, result);
1333 break;
1337 free (expansion);
1339 return o;
1342 static char *
1343 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1345 #ifdef _AMIGA
1346 o = wildcard_expansion (argv[0], o);
1347 #else
1348 char *p = string_glob (argv[0]);
1349 o = variable_buffer_output (o, p, strlen (p));
1350 #endif
1351 return o;
1355 $(eval <makefile string>)
1357 Always resolves to the empty string.
1359 Treat the arguments as a segment of makefile, and parse them.
1362 static char *
1363 func_eval (char *o, char **argv, const char *funcname UNUSED)
1365 char *buf;
1366 unsigned int len;
1368 /* Eval the buffer. Pop the current variable buffer setting so that the
1369 eval'd code can use its own without conflicting. */
1371 install_variable_buffer (&buf, &len);
1373 eval_buffer (argv[0]);
1375 restore_variable_buffer (buf, len);
1377 return o;
1381 static char *
1382 func_value (char *o, char **argv, const char *funcname UNUSED)
1384 /* Look up the variable. */
1385 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1387 /* Copy its value into the output buffer without expanding it. */
1388 if (v)
1389 o = variable_buffer_output (o, v->value, strlen(v->value));
1391 return o;
1395 \r is replaced on UNIX as well. Is this desirable?
1397 static void
1398 fold_newlines (char *buffer, unsigned int *length)
1400 char *dst = buffer;
1401 char *src = buffer;
1402 char *last_nonnl = buffer -1;
1403 src[*length] = 0;
1404 for (; *src != '\0'; ++src)
1406 if (src[0] == '\r' && src[1] == '\n')
1407 continue;
1408 if (*src == '\n')
1410 *dst++ = ' ';
1412 else
1414 last_nonnl = dst;
1415 *dst++ = *src;
1418 *(++last_nonnl) = '\0';
1419 *length = last_nonnl - buffer;
1424 int shell_function_pid = 0, shell_function_completed;
1427 #ifdef WINDOWS32
1428 /*untested*/
1430 #include <windows.h>
1431 #include <io.h>
1432 #include "sub_proc.h"
1435 void
1436 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1438 SECURITY_ATTRIBUTES saAttr;
1439 HANDLE hIn;
1440 HANDLE hErr;
1441 HANDLE hChildOutRd;
1442 HANDLE hChildOutWr;
1443 HANDLE hProcess;
1446 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1447 saAttr.bInheritHandle = TRUE;
1448 saAttr.lpSecurityDescriptor = NULL;
1450 if (DuplicateHandle (GetCurrentProcess(),
1451 GetStdHandle(STD_INPUT_HANDLE),
1452 GetCurrentProcess(),
1453 &hIn,
1455 TRUE,
1456 DUPLICATE_SAME_ACCESS) == FALSE) {
1457 fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
1458 GetLastError());
1461 if (DuplicateHandle(GetCurrentProcess(),
1462 GetStdHandle(STD_ERROR_HANDLE),
1463 GetCurrentProcess(),
1464 &hErr,
1466 TRUE,
1467 DUPLICATE_SAME_ACCESS) == FALSE) {
1468 fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
1469 GetLastError());
1472 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1473 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1475 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1477 if (!hProcess)
1478 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1480 /* make sure that CreateProcess() has Path it needs */
1481 sync_Path_environment();
1482 /* `sync_Path_environment' may realloc `environ', so take note of
1483 the new value. */
1484 envp = environ;
1486 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1487 /* register process for wait */
1488 process_register(hProcess);
1490 /* set the pid for returning to caller */
1491 *pid_p = (int) hProcess;
1493 /* set up to read data from child */
1494 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1496 /* this will be closed almost right away */
1497 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1498 } else {
1499 /* reap/cleanup the failed process */
1500 process_cleanup(hProcess);
1502 /* close handles which were duplicated, they weren't used */
1503 CloseHandle(hIn);
1504 CloseHandle(hErr);
1506 /* close pipe handles, they won't be used */
1507 CloseHandle(hChildOutRd);
1508 CloseHandle(hChildOutWr);
1510 /* set status for return */
1511 pipedes[0] = pipedes[1] = -1;
1512 *pid_p = -1;
1515 #endif
1518 #ifdef __MSDOS__
1519 FILE *
1520 msdos_openpipe (int* pipedes, int *pidp, char *text)
1522 FILE *fpipe=0;
1523 /* MSDOS can't fork, but it has `popen'. */
1524 struct variable *sh = lookup_variable ("SHELL", 5);
1525 int e;
1526 extern int dos_command_running, dos_status;
1528 /* Make sure not to bother processing an empty line. */
1529 while (isblank ((unsigned char)*text))
1530 ++text;
1531 if (*text == '\0')
1532 return 0;
1534 if (sh)
1536 char buf[PATH_MAX + 7];
1537 /* This makes sure $SHELL value is used by $(shell), even
1538 though the target environment is not passed to it. */
1539 sprintf (buf, "SHELL=%s", sh->value);
1540 putenv (buf);
1543 e = errno;
1544 errno = 0;
1545 dos_command_running = 1;
1546 dos_status = 0;
1547 /* If dos_status becomes non-zero, it means the child process
1548 was interrupted by a signal, like SIGINT or SIGQUIT. See
1549 fatal_error_signal in commands.c. */
1550 fpipe = popen (text, "rt");
1551 dos_command_running = 0;
1552 if (!fpipe || dos_status)
1554 pipedes[0] = -1;
1555 *pidp = -1;
1556 if (dos_status)
1557 errno = EINTR;
1558 else if (errno == 0)
1559 errno = ENOMEM;
1560 shell_function_completed = -1;
1562 else
1564 pipedes[0] = fileno (fpipe);
1565 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1566 errno = e;
1567 shell_function_completed = 1;
1569 return fpipe;
1571 #endif
1574 Do shell spawning, with the naughty bits for different OSes.
1577 #ifdef VMS
1579 /* VMS can't do $(shell ...) */
1580 #define func_shell 0
1582 #else
1583 #ifndef _AMIGA
1584 static char *
1585 func_shell (char *o, char **argv, const char *funcname UNUSED)
1587 char *batch_filename = NULL;
1589 #ifdef __MSDOS__
1590 FILE *fpipe;
1591 #endif
1592 char **command_argv;
1593 const char *error_prefix;
1594 char **envp;
1595 int pipedes[2];
1596 int pid;
1598 #ifndef __MSDOS__
1599 /* Construct the argument list. */
1600 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1601 &batch_filename);
1602 if (command_argv == 0)
1603 return o;
1604 #endif
1606 /* Using a target environment for `shell' loses in cases like:
1607 export var = $(shell echo foobie)
1608 because target_environment hits a loop trying to expand $(var)
1609 to put it in the environment. This is even more confusing when
1610 var was not explicitly exported, but just appeared in the
1611 calling environment.
1613 See Savannah bug #10593.
1615 envp = target_environment (NILF);
1618 envp = environ;
1620 /* For error messages. */
1621 if (reading_file && reading_file->filenm)
1623 char *p = alloca (strlen (reading_file->filenm)+11+4);
1624 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1625 error_prefix = p;
1627 else
1628 error_prefix = "";
1630 #if defined(__MSDOS__)
1631 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1632 if (pipedes[0] < 0)
1634 perror_with_name (error_prefix, "pipe");
1635 return o;
1637 #elif defined(WINDOWS32)
1638 windows32_openpipe (pipedes, &pid, command_argv, envp);
1639 if (pipedes[0] < 0)
1641 /* open of the pipe failed, mark as failed execution */
1642 shell_function_completed = -1;
1644 return o;
1646 else
1647 #else
1648 if (pipe (pipedes) < 0)
1650 perror_with_name (error_prefix, "pipe");
1651 return o;
1654 # ifdef __EMX__
1655 /* close some handles that are unnecessary for the child process */
1656 CLOSE_ON_EXEC(pipedes[1]);
1657 CLOSE_ON_EXEC(pipedes[0]);
1658 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1659 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1660 if (pid < 0)
1661 perror_with_name (error_prefix, "spawn");
1662 # 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
1669 # endif
1670 #endif
1672 /* We are the parent. */
1673 char *buffer;
1674 unsigned int maxlen, i;
1675 int cc;
1677 /* Record the PID for reap_children. */
1678 shell_function_pid = pid;
1679 #ifndef __MSDOS__
1680 shell_function_completed = 0;
1682 /* Free the storage only the child needed. */
1683 free (command_argv[0]);
1684 free (command_argv);
1686 /* Close the write side of the pipe. We test for -1, since
1687 pipedes[1] is -1 on MS-Windows, and some versions of MS
1688 libraries barf when `close' is called with -1. */
1689 if (pipedes[1] >= 0)
1690 close (pipedes[1]);
1691 #endif
1693 /* Set up and read from the pipe. */
1695 maxlen = 200;
1696 buffer = xmalloc (maxlen + 1);
1698 /* Read from the pipe until it gets EOF. */
1699 for (i = 0; ; i += cc)
1701 if (i == maxlen)
1703 maxlen += 512;
1704 buffer = xrealloc (buffer, maxlen + 1);
1707 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1708 if (cc <= 0)
1709 break;
1711 buffer[i] = '\0';
1713 /* Close the read side of the pipe. */
1714 #ifdef __MSDOS__
1715 if (fpipe)
1716 (void) pclose (fpipe);
1717 #else
1718 (void) close (pipedes[0]);
1719 #endif
1721 /* Loop until child_handler or reap_children() sets
1722 shell_function_completed to the status of our child shell. */
1723 while (shell_function_completed == 0)
1724 reap_children (1, 0);
1726 if (batch_filename) {
1727 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1728 batch_filename));
1729 remove (batch_filename);
1730 free (batch_filename);
1732 shell_function_pid = 0;
1734 /* The child_handler function will set shell_function_completed
1735 to 1 when the child dies normally, or to -1 if it
1736 dies with status 127, which is most likely an exec fail. */
1738 if (shell_function_completed == -1)
1740 /* This likely means that the execvp failed, so we should just
1741 write the error message in the pipe from the child. */
1742 fputs (buffer, stderr);
1743 fflush (stderr);
1745 else
1747 /* The child finished normally. Replace all newlines in its output
1748 with spaces, and put that in the variable output buffer. */
1749 fold_newlines (buffer, &i);
1750 o = variable_buffer_output (o, buffer, i);
1753 free (buffer);
1756 return o;
1759 #else /* _AMIGA */
1761 /* Do the Amiga version of func_shell. */
1763 static char *
1764 func_shell (char *o, char **argv, const char *funcname)
1766 /* Amiga can't fork nor spawn, but I can start a program with
1767 redirection of my choice. However, this means that we
1768 don't have an opportunity to reopen stdout to trap it. Thus,
1769 we save our own stdout onto a new descriptor and dup a temp
1770 file's descriptor onto our stdout temporarily. After we
1771 spawn the shell program, we dup our own stdout back to the
1772 stdout descriptor. The buffer reading is the same as above,
1773 except that we're now reading from a file. */
1775 #include <dos/dos.h>
1776 #include <proto/dos.h>
1778 BPTR child_stdout;
1779 char tmp_output[FILENAME_MAX];
1780 unsigned int maxlen = 200, i;
1781 int cc;
1782 char * buffer, * ptr;
1783 char ** aptr;
1784 int len = 0;
1785 char* batch_filename = NULL;
1787 /* Construct the argument list. */
1788 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1789 &batch_filename);
1790 if (command_argv == 0)
1791 return o;
1793 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1794 Ideally we would use main.c:open_tmpfile(), but this uses a special
1795 Open(), not fopen(), and I'm not familiar enough with the code to mess
1796 with it. */
1797 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1798 mktemp (tmp_output);
1799 child_stdout = Open (tmp_output, MODE_NEWFILE);
1801 for (aptr=command_argv; *aptr; aptr++)
1802 len += strlen (*aptr) + 1;
1804 buffer = xmalloc (len + 1);
1805 ptr = buffer;
1807 for (aptr=command_argv; *aptr; aptr++)
1809 strcpy (ptr, *aptr);
1810 ptr += strlen (ptr) + 1;
1811 *ptr ++ = ' ';
1812 *ptr = 0;
1815 ptr[-1] = '\n';
1817 Execute (buffer, NULL, child_stdout);
1818 free (buffer);
1820 Close (child_stdout);
1822 child_stdout = Open (tmp_output, MODE_OLDFILE);
1824 buffer = xmalloc (maxlen);
1825 i = 0;
1828 if (i == maxlen)
1830 maxlen += 512;
1831 buffer = xrealloc (buffer, maxlen + 1);
1834 cc = Read (child_stdout, &buffer[i], maxlen - i);
1835 if (cc > 0)
1836 i += cc;
1837 } while (cc > 0);
1839 Close (child_stdout);
1841 fold_newlines (buffer, &i);
1842 o = variable_buffer_output (o, buffer, i);
1843 free (buffer);
1844 return o;
1846 #endif /* _AMIGA */
1847 #endif /* !VMS */
1849 #ifdef EXPERIMENTAL
1852 equality. Return is string-boolean, ie, the empty string is false.
1854 static char *
1855 func_eq (char *o, char **argv, char *funcname)
1857 int result = ! strcmp (argv[0], argv[1]);
1858 o = variable_buffer_output (o, result ? "1" : "", result);
1859 return o;
1864 string-boolean not operator.
1866 static char *
1867 func_not (char *o, char **argv, char *funcname)
1869 const char *s = argv[0];
1870 int result = 0;
1871 while (isspace ((unsigned char)*s))
1872 s++;
1873 result = ! (*s);
1874 o = variable_buffer_output (o, result ? "1" : "", result);
1875 return o;
1877 #endif
1880 #ifdef HAVE_DOS_PATHS
1881 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1882 #define ROOT_LEN 3
1883 #else
1884 #define IS_ABSOLUTE(n) (n[0] == '/')
1885 #define ROOT_LEN 1
1886 #endif
1888 /* Return the absolute name of file NAME which does not contain any `.',
1889 `..' components nor any repeated path separators ('/'). */
1891 static char *
1892 abspath (const char *name, char *apath)
1894 char *dest;
1895 const char *start, *end, *apath_limit;
1896 unsigned long root_len = ROOT_LEN;
1898 if (name[0] == '\0' || apath == NULL)
1899 return NULL;
1901 apath_limit = apath + GET_PATH_MAX;
1903 if (!IS_ABSOLUTE(name))
1905 /* It is unlikely we would make it until here but just to make sure. */
1906 if (!starting_directory)
1907 return NULL;
1909 strcpy (apath, starting_directory);
1911 #ifdef HAVE_DOS_PATHS
1912 if (IS_PATHSEP(name[0]))
1914 /* We have /foo, an absolute file name except for the drive
1915 letter. Assume the missing drive letter is the current
1916 drive, which we can get if we remove from starting_directory
1917 everything past the root directory. */
1918 apath[root_len] = '\0';
1920 #endif
1922 dest = strchr (apath, '\0');
1924 else
1926 strncpy (apath, name, root_len);
1927 apath[root_len] = '\0';
1928 dest = apath + root_len;
1929 /* Get past the root, since we already copied it. */
1930 name += root_len;
1931 #ifdef HAVE_DOS_PATHS
1932 if (!IS_PATHSEP(apath[2]))
1934 /* Convert d:foo into d:./foo and increase root_len. */
1935 apath[2] = '.';
1936 apath[3] = '/';
1937 dest++;
1938 root_len++;
1939 /* strncpy above copied one character too many. */
1940 name--;
1942 else
1943 apath[2] = '/'; /* make sure it's a forward slash */
1944 #endif
1947 for (start = end = name; *start != '\0'; start = end)
1949 unsigned long len;
1951 /* Skip sequence of multiple path-separators. */
1952 while (IS_PATHSEP(*start))
1953 ++start;
1955 /* Find end of path component. */
1956 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
1959 len = end - start;
1961 if (len == 0)
1962 break;
1963 else if (len == 1 && start[0] == '.')
1964 /* nothing */;
1965 else if (len == 2 && start[0] == '.' && start[1] == '.')
1967 /* Back up to previous component, ignore if at root already. */
1968 if (dest > apath + root_len)
1969 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
1971 else
1973 if (!IS_PATHSEP(dest[-1]))
1974 *dest++ = '/';
1976 if (dest + len >= apath_limit)
1977 return NULL;
1979 dest = memcpy (dest, start, len);
1980 dest += len;
1981 *dest = '\0';
1985 /* Unless it is root strip trailing separator. */
1986 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
1987 --dest;
1989 *dest = '\0';
1991 return apath;
1995 static char *
1996 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1998 /* Expand the argument. */
1999 const char *p = argv[0];
2000 const char *path = 0;
2001 int doneany = 0;
2002 unsigned int len = 0;
2003 #ifndef HAVE_REALPATH
2004 struct stat st;
2005 #endif
2006 PATH_VAR (in);
2007 PATH_VAR (out);
2009 while ((path = find_next_token (&p, &len)) != 0)
2011 if (len < GET_PATH_MAX)
2013 strncpy (in, path, len);
2014 in[len] = '\0';
2016 if (
2017 #ifdef HAVE_REALPATH
2018 realpath (in, out)
2019 #else
2020 abspath (in, out) && stat (out, &st) == 0
2021 #endif
2024 o = variable_buffer_output (o, out, strlen (out));
2025 o = variable_buffer_output (o, " ", 1);
2026 doneany = 1;
2031 /* Kill last space. */
2032 if (doneany)
2033 --o;
2035 return o;
2038 static char *
2039 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2041 /* Expand the argument. */
2042 const char *p = argv[0];
2043 const char *path = 0;
2044 int doneany = 0;
2045 unsigned int len = 0;
2046 PATH_VAR (in);
2047 PATH_VAR (out);
2049 while ((path = find_next_token (&p, &len)) != 0)
2051 if (len < GET_PATH_MAX)
2053 strncpy (in, path, len);
2054 in[len] = '\0';
2056 if (abspath (in, out))
2058 o = variable_buffer_output (o, out, strlen (out));
2059 o = variable_buffer_output (o, " ", 1);
2060 doneany = 1;
2065 /* Kill last space. */
2066 if (doneany)
2067 --o;
2069 return o;
2072 /* Lookup table for builtin functions.
2074 This doesn't have to be sorted; we use a straight lookup. We might gain
2075 some efficiency by moving most often used functions to the start of the
2076 table.
2078 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2079 comma-separated values are treated as arguments.
2081 EXPAND_ARGS means that all arguments should be expanded before invocation.
2082 Functions that do namespace tricks (foreach) don't automatically expand. */
2084 static char *func_call (char *o, char **argv, const char *funcname);
2087 static struct function_table_entry function_table_init[] =
2089 /* Name/size */ /* MIN MAX EXP? Function */
2090 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2091 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2092 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2093 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2094 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2095 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2096 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2097 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2098 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2099 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2100 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2101 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2102 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2103 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2104 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2105 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2106 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2107 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2108 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2109 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2110 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2111 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2112 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2113 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2114 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2115 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2116 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2117 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2118 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2119 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2120 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2121 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2122 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2123 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2124 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2125 #ifdef EXPERIMENTAL
2126 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2127 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2128 #endif
2131 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2134 /* These must come after the definition of function_table. */
2136 static char *
2137 expand_builtin_function (char *o, int argc, char **argv,
2138 const struct function_table_entry *entry_p)
2140 if (argc < (int)entry_p->minimum_args)
2141 fatal (*expanding_var,
2142 _("insufficient number of arguments (%d) to function `%s'"),
2143 argc, entry_p->name);
2145 /* I suppose technically some function could do something with no
2146 arguments, but so far none do, so just test it for all functions here
2147 rather than in each one. We can change it later if necessary. */
2149 if (!argc)
2150 return o;
2152 if (!entry_p->func_ptr)
2153 fatal (*expanding_var,
2154 _("unimplemented on this platform: function `%s'"), entry_p->name);
2156 return entry_p->func_ptr (o, argv, entry_p->name);
2159 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2160 opening ( or { and is not null-terminated. If a function invocation
2161 is found, expand it into the buffer at *OP, updating *OP, incrementing
2162 *STRINGP past the reference and returning nonzero. If not, return zero. */
2165 handle_function (char **op, const char **stringp)
2167 const struct function_table_entry *entry_p;
2168 char openparen = (*stringp)[0];
2169 char closeparen = openparen == '(' ? ')' : '}';
2170 const char *beg;
2171 const char *end;
2172 int count = 0;
2173 char *abeg = NULL;
2174 char **argv, **argvp;
2175 int nargs;
2177 beg = *stringp + 1;
2179 entry_p = lookup_function (beg);
2181 if (!entry_p)
2182 return 0;
2184 /* We found a builtin function. Find the beginning of its arguments (skip
2185 whitespace after the name). */
2187 beg = next_token (beg + entry_p->len);
2189 /* Find the end of the function invocation, counting nested use of
2190 whichever kind of parens we use. Since we're looking, count commas
2191 to get a rough estimate of how many arguments we might have. The
2192 count might be high, but it'll never be low. */
2194 for (nargs=1, end=beg; *end != '\0'; ++end)
2195 if (*end == ',')
2196 ++nargs;
2197 else if (*end == openparen)
2198 ++count;
2199 else if (*end == closeparen && --count < 0)
2200 break;
2202 if (count >= 0)
2203 fatal (*expanding_var,
2204 _("unterminated call to function `%s': missing `%c'"),
2205 entry_p->name, closeparen);
2207 *stringp = end;
2209 /* Get some memory to store the arg pointers. */
2210 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2212 /* Chop the string into arguments, then a nul. As soon as we hit
2213 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2214 last argument.
2216 If we're expanding, store pointers to the expansion of each one. If
2217 not, make a duplicate of the string and point into that, nul-terminating
2218 each argument. */
2220 if (entry_p->expand_args)
2222 const char *p;
2223 for (p=beg, nargs=0; p <= end; ++argvp)
2225 const char *next;
2227 ++nargs;
2229 if (nargs == entry_p->maximum_args
2230 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2231 next = end;
2233 *argvp = expand_argument (p, next);
2234 p = next + 1;
2237 else
2239 int len = end - beg;
2240 char *p, *aend;
2242 abeg = xmalloc (len+1);
2243 memcpy (abeg, beg, len);
2244 abeg[len] = '\0';
2245 aend = abeg + len;
2247 for (p=abeg, nargs=0; p <= aend; ++argvp)
2249 char *next;
2251 ++nargs;
2253 if (nargs == entry_p->maximum_args
2254 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2255 next = aend;
2257 *argvp = p;
2258 *next = '\0';
2259 p = next + 1;
2262 *argvp = NULL;
2264 /* Finally! Run the function... */
2265 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2267 /* Free memory. */
2268 if (entry_p->expand_args)
2269 for (argvp=argv; *argvp != 0; ++argvp)
2270 free (*argvp);
2271 if (abeg)
2272 free (abeg);
2274 return 1;
2278 /* User-defined functions. Expand the first argument as either a builtin
2279 function or a make variable, in the context of the rest of the arguments
2280 assigned to $1, $2, ... $N. $0 is the name of the function. */
2282 static char *
2283 func_call (char *o, char **argv, const char *funcname UNUSED)
2285 static int max_args = 0;
2286 char *fname;
2287 char *cp;
2288 char *body;
2289 int flen;
2290 int i;
2291 int saved_args;
2292 const struct function_table_entry *entry_p;
2293 struct variable *v;
2295 /* There is no way to define a variable with a space in the name, so strip
2296 leading and trailing whitespace as a favor to the user. */
2297 fname = argv[0];
2298 while (*fname != '\0' && isspace ((unsigned char)*fname))
2299 ++fname;
2301 cp = fname + strlen (fname) - 1;
2302 while (cp > fname && isspace ((unsigned char)*cp))
2303 --cp;
2304 cp[1] = '\0';
2306 /* Calling nothing is a no-op */
2307 if (*fname == '\0')
2308 return o;
2310 /* Are we invoking a builtin function? */
2312 entry_p = lookup_function (fname);
2313 if (entry_p)
2315 /* How many arguments do we have? */
2316 for (i=0; argv[i+1]; ++i)
2318 return expand_builtin_function (o, i, argv+1, entry_p);
2321 /* Not a builtin, so the first argument is the name of a variable to be
2322 expanded and interpreted as a function. Find it. */
2323 flen = strlen (fname);
2325 v = lookup_variable (fname, flen);
2327 if (v == 0)
2328 warn_undefined (fname, flen);
2330 if (v == 0 || *v->value == '\0')
2331 return o;
2333 body = alloca (flen + 4);
2334 body[0] = '$';
2335 body[1] = '(';
2336 memcpy (body + 2, fname, flen);
2337 body[flen+2] = ')';
2338 body[flen+3] = '\0';
2340 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2342 push_new_variable_scope ();
2344 for (i=0; *argv; ++i, ++argv)
2346 char num[11];
2348 sprintf (num, "%d", i);
2349 define_variable (num, strlen (num), *argv, o_automatic, 0);
2352 /* If the number of arguments we have is < max_args, it means we're inside
2353 a recursive invocation of $(call ...). Fill in the remaining arguments
2354 in the new scope with the empty value, to hide them from this
2355 invocation. */
2357 for (; i < max_args; ++i)
2359 char num[11];
2361 sprintf (num, "%d", i);
2362 define_variable (num, strlen (num), "", o_automatic, 0);
2365 /* Expand the body in the context of the arguments, adding the result to
2366 the variable buffer. */
2368 v->exp_count = EXP_COUNT_MAX;
2370 saved_args = max_args;
2371 max_args = i;
2372 o = variable_expand_string (o, body, flen+3);
2373 max_args = saved_args;
2375 v->exp_count = 0;
2377 pop_variable_scope ();
2379 return o + strlen (o);
2382 void
2383 hash_init_function_table (void)
2385 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2386 function_table_entry_hash_1, function_table_entry_hash_2,
2387 function_table_entry_hash_cmp);
2388 hash_load (&function_table, function_table_init,
2389 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));