1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988-2013 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify it under the
6 terms of the GNU General Public License as published by the Free Software
7 Foundation; either version 3 of the License, or (at your option) any later
10 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along with
15 this program. If not, see <http://www.gnu.org/licenses/>. */
30 struct function_table_entry
33 char *(*func_ptr) (char *output, char **argv, const char *fname);
34 gmk_func_ptr alloc_func_ptr;
38 unsigned char minimum_args;
39 unsigned char maximum_args;
40 unsigned char expand_args:1;
41 unsigned char alloc_fn:1;
45 function_table_entry_hash_1 (const void *keyv)
47 const struct function_table_entry *key = keyv;
48 return_STRING_N_HASH_1 (key->name, key->len);
52 function_table_entry_hash_2 (const void *keyv)
54 const struct function_table_entry *key = keyv;
55 return_STRING_N_HASH_2 (key->name, key->len);
59 function_table_entry_hash_cmp (const void *xv, const void *yv)
61 const struct function_table_entry *x = xv;
62 const struct function_table_entry *y = yv;
63 int result = x->len - y->len;
66 return_STRING_N_COMPARE (x->name, y->name, x->len);
69 static struct hash_table function_table;
72 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
73 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
74 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
75 nonzero, substitutions are done only on matches which are complete
76 whitespace-delimited words. */
79 subst_expand (char *o, const char *text, const char *subst, const char *replace,
80 unsigned int slen, unsigned int rlen, int by_word)
85 if (slen == 0 && !by_word)
87 /* The first occurrence of "" in any string is its end. */
88 o = variable_buffer_output (o, t, strlen (t));
90 o = variable_buffer_output (o, replace, rlen);
96 if (by_word && slen == 0)
97 /* When matching by words, the empty string should match
98 the end of each word, rather than the end of the whole text. */
99 p = end_of_token (next_token (t));
102 p = strstr (t, subst);
105 /* No more matches. Output everything left on the end. */
106 o = variable_buffer_output (o, t, strlen (t));
111 /* Output everything before this occurrence of the string to replace. */
113 o = variable_buffer_output (o, t, p - t);
115 /* If we're substituting only by fully matched words,
116 or only at the ends of words, check that this case qualifies. */
118 && ((p > text && !isblank ((unsigned char)p[-1]))
119 || ! STOP_SET (p[slen], MAP_BLANK|MAP_NUL)))
120 /* Struck out. Output the rest of the string that is
121 no longer to be replaced. */
122 o = variable_buffer_output (o, subst, slen);
124 /* Output the replacement string. */
125 o = variable_buffer_output (o, replace, rlen);
127 /* Advance T past the string to be replaced. */
129 } while (*t != '\0');
135 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
136 and replacing strings matching PATTERN with REPLACE.
137 If PATTERN_PERCENT is not nil, PATTERN has already been
138 run through find_percent, and PATTERN_PERCENT is the result.
139 If REPLACE_PERCENT is not nil, REPLACE has already been
140 run through find_percent, and REPLACE_PERCENT is the result.
141 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
142 character _AFTER_ the %, not to the % itself.
146 patsubst_expand_pat (char *o, const char *text,
147 const char *pattern, const char *replace,
148 const char *pattern_percent, const char *replace_percent)
150 unsigned int pattern_prepercent_len, pattern_postpercent_len;
151 unsigned int replace_prepercent_len, replace_postpercent_len;
156 /* Record the length of REPLACE before and after the % so we don't have to
157 compute these lengths more than once. */
160 replace_prepercent_len = replace_percent - replace - 1;
161 replace_postpercent_len = strlen (replace_percent);
165 replace_prepercent_len = strlen (replace);
166 replace_postpercent_len = 0;
169 if (!pattern_percent)
170 /* With no % in the pattern, this is just a simple substitution. */
171 return subst_expand (o, text, pattern, replace,
172 strlen (pattern), strlen (replace), 1);
174 /* Record the length of PATTERN before and after the %
175 so we don't have to compute it more than once. */
176 pattern_prepercent_len = pattern_percent - pattern - 1;
177 pattern_postpercent_len = strlen (pattern_percent);
179 while ((t = find_next_token (&text, &len)) != 0)
183 /* Is it big enough to match? */
184 if (len < pattern_prepercent_len + pattern_postpercent_len)
187 /* Does the prefix match? */
188 if (!fail && pattern_prepercent_len > 0
190 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
191 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
194 /* Does the suffix match? */
195 if (!fail && pattern_postpercent_len > 0
196 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
197 || t[len - pattern_postpercent_len] != *pattern_percent
198 || !strneq (&t[len - pattern_postpercent_len],
199 pattern_percent, pattern_postpercent_len - 1)))
203 /* It didn't match. Output the string. */
204 o = variable_buffer_output (o, t, len);
207 /* It matched. Output the replacement. */
209 /* Output the part of the replacement before the %. */
210 o = variable_buffer_output (o, replace, replace_prepercent_len);
212 if (replace_percent != 0)
214 /* Output the part of the matched string that
215 matched the % in the pattern. */
216 o = variable_buffer_output (o, t + pattern_prepercent_len,
217 len - (pattern_prepercent_len
218 + pattern_postpercent_len));
219 /* Output the part of the replacement after the %. */
220 o = variable_buffer_output (o, replace_percent,
221 replace_postpercent_len);
225 /* Output a space, but not if the replacement is "". */
226 if (fail || replace_prepercent_len > 0
227 || (replace_percent != 0 && len + replace_postpercent_len > 0))
229 o = variable_buffer_output (o, " ", 1);
234 /* Kill the last space. */
240 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
241 and replacing strings matching PATTERN with REPLACE.
242 If PATTERN_PERCENT is not nil, PATTERN has already been
243 run through find_percent, and PATTERN_PERCENT is the result.
244 If REPLACE_PERCENT is not nil, REPLACE has already been
245 run through find_percent, and REPLACE_PERCENT is the result.
246 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
247 character _AFTER_ the %, not to the % itself.
251 patsubst_expand (char *o, const char *text, char *pattern, char *replace)
253 const char *pattern_percent = find_percent (pattern);
254 const char *replace_percent = find_percent (replace);
256 /* If there's a percent in the pattern or replacement skip it. */
262 return patsubst_expand_pat (o, text, pattern, replace,
263 pattern_percent, replace_percent);
267 /* Look up a function by name. */
269 static const struct function_table_entry *
270 lookup_function (const char *s)
272 struct function_table_entry function_table_entry_key;
275 while (STOP_SET (*e, MAP_USERFUNC))
278 if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
281 function_table_entry_key.name = s;
282 function_table_entry_key.len = e - s;
284 return hash_find_item (&function_table, &function_table_entry_key);
288 /* Return 1 if PATTERN matches STR, 0 if not. */
291 pattern_matches (const char *pattern, const char *percent, const char *str)
293 unsigned int sfxlen, strlength;
297 unsigned int len = strlen (pattern) + 1;
298 char *new_chars = alloca (len);
299 memcpy (new_chars, pattern, len);
300 percent = find_percent (new_chars);
302 return streq (new_chars, str);
306 sfxlen = strlen (percent + 1);
307 strlength = strlen (str);
309 if (strlength < (percent - pattern) + sfxlen
310 || !strneq (pattern, str, percent - pattern))
313 return !strcmp (percent + 1, str + (strlength - sfxlen));
317 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
318 ENDPARENtheses), starting at PTR before END. Return a pointer to
321 If no next argument is found, return NULL.
325 find_next_argument (char startparen, char endparen,
326 const char *ptr, const char *end)
330 for (; ptr < end; ++ptr)
331 if (*ptr == startparen)
334 else if (*ptr == endparen)
341 else if (*ptr == ',' && !count)
344 /* We didn't find anything. */
349 /* Glob-expand LINE. The returned pointer is
350 only good until the next call to string_glob. */
353 string_glob (char *line)
355 static char *result = 0;
356 static unsigned int length;
357 struct nameseq *chain;
360 chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
361 /* We do not want parse_file_seq to strip './'s.
362 That would break examples like:
363 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
364 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
369 result = xmalloc (100);
375 struct nameseq *next = chain->next;
376 unsigned int len = strlen (chain->name);
378 if (idx + len + 1 > length)
380 length += (len + 1) * 2;
381 result = xrealloc (result, length);
383 memcpy (&result[idx], chain->name, len);
387 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
388 free ((char *)chain->name);
393 /* Kill the last space and terminate the string. */
397 result[idx - 1] = '\0';
407 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
409 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
415 func_join (char *o, char **argv, const char *funcname UNUSED)
419 /* Write each word of the first argument directly followed
420 by the corresponding word of the second argument.
421 If the two arguments have a different number of words,
422 the excess words are just output separated by blanks. */
425 const char *list1_iterator = argv[0];
426 const char *list2_iterator = argv[1];
429 unsigned int len1, len2;
431 tp = find_next_token (&list1_iterator, &len1);
433 o = variable_buffer_output (o, tp, len1);
435 pp = find_next_token (&list2_iterator, &len2);
437 o = variable_buffer_output (o, pp, len2);
439 if (tp != 0 || pp != 0)
441 o = variable_buffer_output (o, " ", 1);
445 while (tp != 0 || pp != 0);
447 /* Kill the last blank. */
455 func_origin (char *o, char **argv, const char *funcname UNUSED)
457 /* Expand the argument. */
458 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
460 o = variable_buffer_output (o, "undefined", 9);
469 o = variable_buffer_output (o, "default", 7);
472 o = variable_buffer_output (o, "environment", 11);
475 o = variable_buffer_output (o, "file", 4);
478 o = variable_buffer_output (o, "environment override", 20);
481 o = variable_buffer_output (o, "command line", 12);
484 o = variable_buffer_output (o, "override", 8);
487 o = variable_buffer_output (o, "automatic", 9);
495 func_flavor (char *o, char **argv, const char *funcname UNUSED)
497 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
500 o = variable_buffer_output (o, "undefined", 9);
503 o = variable_buffer_output (o, "recursive", 9);
505 o = variable_buffer_output (o, "simple", 6);
512 func_notdir_suffix (char *o, char **argv, const char *funcname)
514 /* Expand the argument. */
515 const char *list_iterator = argv[0];
520 int is_suffix = funcname[0] == 's';
521 int is_notdir = !is_suffix;
522 int stop = MAP_PATHSEP | (is_suffix ? MAP_DOT : 0);
523 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
525 const char *p = p2 + len - 1;
527 while (p >= p2 && ! STOP_SET (*p, stop))
536 o = variable_buffer_output (o, p, len - (p - p2));
538 #ifdef HAVE_DOS_PATHS
539 /* Handle the case of "d:foo/bar". */
540 else if (is_notdir && p2[0] && p2[1] == ':')
543 o = variable_buffer_output (o, p, len - (p - p2));
547 o = variable_buffer_output (o, p2, len);
549 if (is_notdir || p >= p2)
551 o = variable_buffer_output (o, " ", 1);
557 /* Kill last space. */
565 func_basename_dir (char *o, char **argv, const char *funcname)
567 /* Expand the argument. */
568 const char *p3 = argv[0];
571 unsigned int len = 0;
573 int is_basename = funcname[0] == 'b';
574 int is_dir = !is_basename;
575 int stop = MAP_PATHSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
576 while ((p2 = find_next_token (&p3, &len)) != 0)
578 const char *p = p2 + len - 1;
579 while (p >= p2 && ! STOP_SET (*p, stop))
582 if (p >= p2 && (is_dir))
583 o = variable_buffer_output (o, p2, ++p - p2);
584 else if (p >= p2 && (*p == '.'))
585 o = variable_buffer_output (o, p2, p - p2);
586 #ifdef HAVE_DOS_PATHS
587 /* Handle the "d:foobar" case */
588 else if (p2[0] && p2[1] == ':' && is_dir)
589 o = variable_buffer_output (o, p2, 2);
593 o = variable_buffer_output (o, "[]", 2);
596 o = variable_buffer_output (o, "./", 2);
598 ; /* Just a nop... */
602 /* The entire name is the basename. */
603 o = variable_buffer_output (o, p2, len);
605 o = variable_buffer_output (o, " ", 1);
610 /* Kill last space. */
617 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
619 int fixlen = strlen (argv[0]);
620 const char *list_iterator = argv[1];
621 int is_addprefix = funcname[3] == 'p';
622 int is_addsuffix = !is_addprefix;
628 while ((p = find_next_token (&list_iterator, &len)) != 0)
631 o = variable_buffer_output (o, argv[0], fixlen);
632 o = variable_buffer_output (o, p, len);
634 o = variable_buffer_output (o, argv[0], fixlen);
635 o = variable_buffer_output (o, " ", 1);
640 /* Kill last space. */
647 func_subst (char *o, char **argv, const char *funcname UNUSED)
649 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
650 strlen (argv[1]), 0);
657 func_firstword (char *o, char **argv, const char *funcname UNUSED)
660 const char *words = argv[0]; /* Use a temp variable for find_next_token */
661 const char *p = find_next_token (&words, &i);
664 o = variable_buffer_output (o, p, i);
670 func_lastword (char *o, char **argv, const char *funcname UNUSED)
673 const char *words = argv[0]; /* Use a temp variable for find_next_token */
674 const char *p = NULL;
677 while ((t = find_next_token (&words, &i)))
681 o = variable_buffer_output (o, p, i);
687 func_words (char *o, char **argv, const char *funcname UNUSED)
690 const char *word_iterator = argv[0];
693 while (find_next_token (&word_iterator, NULL) != 0)
696 sprintf (buf, "%d", i);
697 o = variable_buffer_output (o, buf, strlen (buf));
702 /* Set begpp to point to the first non-whitespace character of the string,
703 * and endpp to point to the last non-whitespace character of the string.
704 * If the string is empty or contains nothing but whitespace, endpp will be
708 strip_whitespace (const char **begpp, const char **endpp)
710 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
712 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
714 return (char *)*begpp;
718 check_numeric (const char *s, const char *msg)
720 const char *end = s + strlen (s) - 1;
722 strip_whitespace (&s, &end);
724 for (; s <= end; ++s)
725 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see makeint.h. */
728 if (s <= end || end - beg < 0)
729 fatal (*expanding_var, "%s: '%s'", msg, beg);
735 func_word (char *o, char **argv, const char *funcname UNUSED)
741 /* Check the first argument. */
742 check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
746 fatal (*expanding_var,
747 _("first argument to 'word' function must be greater than 0"));
750 while ((p = find_next_token (&end_p, 0)) != 0)
755 o = variable_buffer_output (o, p, end_p - p);
761 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
765 /* Check the arguments. */
766 check_numeric (argv[0],
767 _("non-numeric first argument to 'wordlist' function"));
768 check_numeric (argv[1],
769 _("non-numeric second argument to 'wordlist' function"));
771 start = atoi (argv[0]);
773 fatal (*expanding_var,
774 "invalid first argument to 'wordlist' function: '%d'", start);
776 count = atoi (argv[1]) - start + 1;
781 const char *end_p = argv[2];
783 /* Find the beginning of the "start"th word. */
784 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
789 /* Find the end of the "count"th word from start. */
790 while (--count && (find_next_token (&end_p, 0) != 0))
793 /* Return the stuff in the middle. */
794 o = variable_buffer_output (o, p, end_p - p);
802 func_findstring (char *o, char **argv, const char *funcname UNUSED)
804 /* Find the first occurrence of the first string in the second. */
805 if (strstr (argv[1], argv[0]) != 0)
806 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
812 func_foreach (char *o, char **argv, const char *funcname UNUSED)
814 /* expand only the first two. */
815 char *varname = expand_argument (argv[0], NULL);
816 char *list = expand_argument (argv[1], NULL);
817 const char *body = argv[2];
820 const char *list_iterator = list;
823 struct variable *var;
825 push_new_variable_scope ();
826 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
828 /* loop through LIST, put the value in VAR and expand BODY */
829 while ((p = find_next_token (&list_iterator, &len)) != 0)
834 var->value = xstrndup (p, len);
836 result = allocated_variable_expand (body);
838 o = variable_buffer_output (o, result, strlen (result));
839 o = variable_buffer_output (o, " ", 1);
845 /* Kill the last space. */
848 pop_variable_scope ();
858 struct a_word *chain;
865 a_word_hash_1 (const void *key)
867 return_STRING_HASH_1 (((struct a_word const *) key)->str);
871 a_word_hash_2 (const void *key)
873 return_STRING_HASH_2 (((struct a_word const *) key)->str);
877 a_word_hash_cmp (const void *x, const void *y)
879 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
882 return_STRING_COMPARE (((struct a_word const *) x)->str,
883 ((struct a_word const *) y)->str);
888 struct a_pattern *next;
895 func_filter_filterout (char *o, char **argv, const char *funcname)
897 struct a_word *wordhead;
898 struct a_word **wordtail;
900 struct a_pattern *pathead;
901 struct a_pattern **pattail;
902 struct a_pattern *pp;
904 struct hash_table a_word_table;
905 int is_filter = funcname[CSTRLEN ("filter")] == '\0';
906 const char *pat_iterator = argv[0];
907 const char *word_iterator = argv[1];
914 /* Chop ARGV[0] up into patterns to match against the words.
915 We don't need to preserve it because our caller frees all the
916 argument memory anyway. */
919 while ((p = find_next_token (&pat_iterator, &len)) != 0)
921 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
924 pattail = &pat->next;
926 if (*pat_iterator != '\0')
931 pat->percent = find_percent (p);
932 if (pat->percent == 0)
935 /* find_percent() might shorten the string so LEN is wrong. */
936 pat->length = strlen (pat->str);
940 /* Chop ARGV[1] up into words to match against the patterns. */
942 wordtail = &wordhead;
943 while ((p = find_next_token (&word_iterator, &len)) != 0)
945 struct a_word *word = alloca (sizeof (struct a_word));
948 wordtail = &word->next;
950 if (*word_iterator != '\0')
962 /* Only use a hash table if arg list lengths justifies the cost. */
963 hashing = (literals >= 2 && (literals * words) >= 10);
966 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
968 for (wp = wordhead; wp != 0; wp = wp->next)
970 struct a_word *owp = hash_insert (&a_word_table, wp);
980 /* Run each pattern through the words, killing words. */
981 for (pp = pathead; pp != 0; pp = pp->next)
984 for (wp = wordhead; wp != 0; wp = wp->next)
985 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
988 struct a_word a_word_key;
989 a_word_key.str = pp->str;
990 a_word_key.length = pp->length;
991 wp = hash_find_item (&a_word_table, &a_word_key);
999 for (wp = wordhead; wp != 0; wp = wp->next)
1000 wp->matched |= (wp->length == pp->length
1001 && strneq (pp->str, wp->str, wp->length));
1004 /* Output the words that matched (or didn't, for filter-out). */
1005 for (wp = wordhead; wp != 0; wp = wp->next)
1006 if (is_filter ? wp->matched : !wp->matched)
1008 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1009 o = variable_buffer_output (o, " ", 1);
1014 /* Kill the last space. */
1019 hash_free (&a_word_table, 0);
1026 func_strip (char *o, char **argv, const char *funcname UNUSED)
1028 const char *p = argv[0];
1034 const char *word_start;
1036 while (isspace ((unsigned char)*p))
1039 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1043 o = variable_buffer_output (o, word_start, i);
1044 o = variable_buffer_output (o, " ", 1);
1049 /* Kill the last space. */
1056 Print a warning or fatal message.
1059 func_error (char *o, char **argv, const char *funcname)
1065 /* The arguments will be broken on commas. Rather than create yet
1066 another special case where function arguments aren't broken up,
1067 just create a format string that puts them back together. */
1068 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1069 len += strlen (*argvp) + 2;
1071 p = msg = alloca (len + 1);
1073 for (argvp=argv; argvp[1] != 0; ++argvp)
1076 p += strlen (*argvp);
1085 fatal (reading_file, "%s", msg);
1088 error (reading_file, "%s", msg);
1097 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1100 /* The warning function expands to the empty string. */
1106 chop argv[0] into words, and sort them.
1109 func_sort (char *o, char **argv, const char *funcname UNUSED)
1117 /* Find the maximum number of words we'll have. */
1120 while ((p = find_next_token (&t, NULL)) != 0)
1126 words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
1128 /* Now assign pointers to each string in the array. */
1131 while ((p = find_next_token (&t, &len)) != 0)
1142 /* Now sort the list of words. */
1143 qsort (words, wordi, sizeof (char *), alpha_compare);
1145 /* Now write the sorted list, uniquified. */
1146 for (i = 0; i < wordi; ++i)
1148 len = strlen (words[i]);
1149 if (i == wordi - 1 || strlen (words[i + 1]) != len
1150 || strcmp (words[i], words[i + 1]))
1152 o = variable_buffer_output (o, words[i], len);
1153 o = variable_buffer_output (o, " ", 1);
1157 /* Kill the last space. */
1167 $(if condition,true-part[,false-part])
1169 CONDITION is false iff it evaluates to an empty string. White
1170 space before and after condition are stripped before evaluation.
1172 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1173 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1174 you can use $(if ...) to create side-effects (with $(shell ...), for
1179 func_if (char *o, char **argv, const char *funcname UNUSED)
1181 const char *begp = argv[0];
1182 const char *endp = begp + strlen (argv[0]) - 1;
1185 /* Find the result of the condition: if we have a value, and it's not
1186 empty, the condition is true. If we don't have a value, or it's the
1187 empty string, then it's false. */
1189 strip_whitespace (&begp, &endp);
1193 char *expansion = expand_argument (begp, endp+1);
1195 result = strlen (expansion);
1199 /* If the result is true (1) we want to eval the first argument, and if
1200 it's false (0) we want to eval the second. If the argument doesn't
1201 exist we do nothing, otherwise expand it and add to the buffer. */
1203 argv += 1 + !result;
1207 char *expansion = expand_argument (*argv, NULL);
1209 o = variable_buffer_output (o, expansion, strlen (expansion));
1218 $(or condition1[,condition2[,condition3[...]]])
1220 A CONDITION is false iff it evaluates to an empty string. White
1221 space before and after CONDITION are stripped before evaluation.
1223 CONDITION1 is evaluated. If it's true, then this is the result of
1224 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1225 the conditions are true, the expansion is the empty string.
1227 Once a CONDITION is true no further conditions are evaluated
1232 func_or (char *o, char **argv, const char *funcname UNUSED)
1234 for ( ; *argv ; ++argv)
1236 const char *begp = *argv;
1237 const char *endp = begp + strlen (*argv) - 1;
1241 /* Find the result of the condition: if it's false keep going. */
1243 strip_whitespace (&begp, &endp);
1248 expansion = expand_argument (begp, endp+1);
1249 result = strlen (expansion);
1251 /* If the result is false keep going. */
1258 /* It's true! Keep this result and return. */
1259 o = variable_buffer_output (o, expansion, result);
1268 $(and condition1[,condition2[,condition3[...]]])
1270 A CONDITION is false iff it evaluates to an empty string. White
1271 space before and after CONDITION are stripped before evaluation.
1273 CONDITION1 is evaluated. If it's false, then this is the result of
1274 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1275 the conditions are true, the expansion is the result of the last condition.
1277 Once a CONDITION is false no further conditions are evaluated
1282 func_and (char *o, char **argv, const char *funcname UNUSED)
1288 const char *begp = *argv;
1289 const char *endp = begp + strlen (*argv) - 1;
1292 /* An empty condition is always false. */
1293 strip_whitespace (&begp, &endp);
1297 expansion = expand_argument (begp, endp+1);
1298 result = strlen (expansion);
1300 /* If the result is false, stop here: we're done. */
1304 /* Otherwise the result is true. If this is the last one, keep this
1305 result and quit. Otherwise go on to the next one! */
1311 o = variable_buffer_output (o, expansion, result);
1322 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1325 o = wildcard_expansion (argv[0], o);
1327 char *p = string_glob (argv[0]);
1328 o = variable_buffer_output (o, p, strlen (p));
1334 $(eval <makefile string>)
1336 Always resolves to the empty string.
1338 Treat the arguments as a segment of makefile, and parse them.
1342 func_eval (char *o, char **argv, const char *funcname UNUSED)
1347 /* Eval the buffer. Pop the current variable buffer setting so that the
1348 eval'd code can use its own without conflicting. */
1350 install_variable_buffer (&buf, &len);
1352 eval_buffer (argv[0], NULL);
1354 restore_variable_buffer (buf, len);
1361 func_value (char *o, char **argv, const char *funcname UNUSED)
1363 /* Look up the variable. */
1364 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1366 /* Copy its value into the output buffer without expanding it. */
1368 o = variable_buffer_output (o, v->value, strlen (v->value));
1374 \r is replaced on UNIX as well. Is this desirable?
1377 fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
1381 char *last_nonnl = buffer - 1;
1383 for (; *src != '\0'; ++src)
1385 if (src[0] == '\r' && src[1] == '\n')
1398 if (!trim_newlines && (last_nonnl < (dst - 2)))
1399 last_nonnl = dst - 2;
1401 *(++last_nonnl) = '\0';
1402 *length = last_nonnl - buffer;
1407 int shell_function_pid = 0, shell_function_completed;
1413 #include <windows.h>
1415 #include "sub_proc.h"
1419 windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
1421 SECURITY_ATTRIBUTES saAttr;
1422 HANDLE hIn = INVALID_HANDLE_VALUE;
1423 HANDLE hErr = INVALID_HANDLE_VALUE;
1426 HANDLE hProcess, tmpIn, tmpErr;
1429 /* Set status for return. */
1430 pipedes[0] = pipedes[1] = -1;
1433 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1434 saAttr.bInheritHandle = TRUE;
1435 saAttr.lpSecurityDescriptor = NULL;
1437 /* Standard handles returned by GetStdHandle can be NULL or
1438 INVALID_HANDLE_VALUE if the parent process closed them. If that
1439 happens, we open the null device and pass its handle to
1440 process_begin below as the corresponding handle to inherit. */
1441 tmpIn = GetStdHandle (STD_INPUT_HANDLE);
1442 if (DuplicateHandle (GetCurrentProcess (), tmpIn,
1443 GetCurrentProcess (), &hIn,
1444 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1446 e = GetLastError ();
1447 if (e == ERROR_INVALID_HANDLE)
1449 tmpIn = CreateFile ("NUL", GENERIC_READ,
1450 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1451 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1452 if (tmpIn != INVALID_HANDLE_VALUE
1453 && DuplicateHandle (GetCurrentProcess (), tmpIn,
1454 GetCurrentProcess (), &hIn,
1455 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1456 CloseHandle (tmpIn);
1458 if (hIn == INVALID_HANDLE_VALUE)
1460 error (NILF, _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
1464 tmpErr = GetStdHandle (STD_ERROR_HANDLE);
1465 if (DuplicateHandle (GetCurrentProcess (), tmpErr,
1466 GetCurrentProcess (), &hErr,
1467 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1469 e = GetLastError ();
1470 if (e == ERROR_INVALID_HANDLE)
1472 tmpErr = CreateFile ("NUL", GENERIC_WRITE,
1473 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1474 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1475 if (tmpErr != INVALID_HANDLE_VALUE
1476 && DuplicateHandle (GetCurrentProcess (), tmpErr,
1477 GetCurrentProcess (), &hErr,
1478 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1479 CloseHandle (tmpErr);
1481 if (hErr == INVALID_HANDLE_VALUE)
1483 error (NILF, _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
1488 if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
1490 error (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1494 hProcess = process_init_fd (hIn, hChildOutWr, hErr);
1498 error (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1502 /* make sure that CreateProcess() has Path it needs */
1503 sync_Path_environment ();
1504 /* 'sync_Path_environment' may realloc 'environ', so take note of
1508 if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
1510 /* register process for wait */
1511 process_register (hProcess);
1513 /* set the pid for returning to caller */
1514 *pid_p = (pid_t) hProcess;
1516 /* set up to read data from child */
1517 pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
1519 /* this will be closed almost right away */
1520 pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
1525 /* reap/cleanup the failed process */
1526 process_cleanup (hProcess);
1528 /* close handles which were duplicated, they weren't used */
1529 if (hIn != INVALID_HANDLE_VALUE)
1531 if (hErr != INVALID_HANDLE_VALUE)
1534 /* close pipe handles, they won't be used */
1535 CloseHandle (hChildOutRd);
1536 CloseHandle (hChildOutWr);
1546 msdos_openpipe (int* pipedes, int *pidp, char *text)
1549 /* MSDOS can't fork, but it has 'popen'. */
1550 struct variable *sh = lookup_variable ("SHELL", 5);
1552 extern int dos_command_running, dos_status;
1554 /* Make sure not to bother processing an empty line. */
1555 while (isblank ((unsigned char)*text))
1562 char buf[PATH_MAX + 7];
1563 /* This makes sure $SHELL value is used by $(shell), even
1564 though the target environment is not passed to it. */
1565 sprintf (buf, "SHELL=%s", sh->value);
1571 dos_command_running = 1;
1573 /* If dos_status becomes non-zero, it means the child process
1574 was interrupted by a signal, like SIGINT or SIGQUIT. See
1575 fatal_error_signal in commands.c. */
1576 fpipe = popen (text, "rt");
1577 dos_command_running = 0;
1578 if (!fpipe || dos_status)
1584 else if (errno == 0)
1586 shell_function_completed = -1;
1590 pipedes[0] = fileno (fpipe);
1591 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1593 shell_function_completed = 1;
1600 Do shell spawning, with the naughty bits for different OSes.
1605 /* VMS can't do $(shell ...) */
1608 func_shell_base (char *o, char **argv, int trim_newlines)
1610 fprintf (stderr, "This platform does not support shell\n");
1615 #define func_shell 0
1620 func_shell_base (char *o, char **argv, int trim_newlines)
1622 char *batch_filename = NULL;
1627 char **command_argv;
1628 const char *error_prefix;
1635 /* Reset just_print_flag. This is needed on Windows when batch files
1636 are used to run the commands, because we normally refrain from
1637 creating batch files under -n. */
1638 int j_p_f = just_print_flag;
1639 just_print_flag = 0;
1642 /* Construct the argument list. */
1643 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1645 if (command_argv == 0)
1648 just_print_flag = j_p_f;
1654 /* Using a target environment for 'shell' loses in cases like:
1655 export var = $(shell echo foobie)
1657 because target_environment hits a loop trying to expand $(var) to put it
1658 in the environment. This is even more confusing when 'var' was not
1659 explicitly exported, but just appeared in the calling environment.
1661 See Savannah bug #10593.
1663 envp = target_environment (NULL);
1668 /* For error messages. */
1669 if (reading_file && reading_file->filenm)
1671 char *p = alloca (strlen (reading_file->filenm)+11+4);
1672 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1678 /* Set up the output in case the shell writes something. */
1681 errfd = (output_context && output_context->err >= 0
1682 ? output_context->err : FD_STDERR);
1684 #if defined(__MSDOS__)
1685 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1688 perror_with_name (error_prefix, "pipe");
1691 #elif defined(WINDOWS32)
1692 windows32_openpipe (pipedes, &pid, command_argv, envp);
1693 /* Restore the value of just_print_flag. */
1694 just_print_flag = j_p_f;
1698 /* Open of the pipe failed, mark as failed execution. */
1699 shell_function_completed = -1;
1700 perror_with_name (error_prefix, "pipe");
1705 if (pipe (pipedes) < 0)
1707 perror_with_name (error_prefix, "pipe");
1712 /* close some handles that are unnecessary for the child process */
1713 CLOSE_ON_EXEC(pipedes[1]);
1714 CLOSE_ON_EXEC(pipedes[0]);
1715 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1716 pid = child_execute_job (FD_STDIN, pipedes[1], errfd, command_argv, envp);
1718 perror_with_name (error_prefix, "spawn");
1719 # else /* ! __EMX__ */
1722 perror_with_name (error_prefix, "fork");
1725 # ifdef SET_STACK_SIZE
1726 /* Reset limits, if necessary. */
1727 if (stack_limit.rlim_cur)
1728 setrlimit (RLIMIT_STACK, &stack_limit);
1730 child_execute_job (FD_STDIN, pipedes[1], errfd, command_argv, envp);
1736 /* We are the parent. */
1738 unsigned int maxlen, i;
1741 /* Record the PID for reap_children. */
1742 shell_function_pid = pid;
1744 shell_function_completed = 0;
1746 /* Free the storage only the child needed. */
1747 free (command_argv[0]);
1748 free (command_argv);
1750 /* Close the write side of the pipe. We test for -1, since
1751 pipedes[1] is -1 on MS-Windows, and some versions of MS
1752 libraries barf when 'close' is called with -1. */
1753 if (pipedes[1] >= 0)
1757 /* Set up and read from the pipe. */
1760 buffer = xmalloc (maxlen + 1);
1762 /* Read from the pipe until it gets EOF. */
1763 for (i = 0; ; i += cc)
1768 buffer = xrealloc (buffer, maxlen + 1);
1771 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1777 /* Close the read side of the pipe. */
1780 (void) pclose (fpipe);
1782 (void) close (pipedes[0]);
1785 /* Loop until child_handler or reap_children() sets
1786 shell_function_completed to the status of our child shell. */
1787 while (shell_function_completed == 0)
1788 reap_children (1, 0);
1792 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1794 remove (batch_filename);
1795 free (batch_filename);
1797 shell_function_pid = 0;
1799 /* The child_handler function will set shell_function_completed
1800 to 1 when the child dies normally, or to -1 if it
1801 dies with status 127, which is most likely an exec fail. */
1803 if (shell_function_completed == -1)
1805 /* This likely means that the execvp failed, so we should just
1806 write the error message in the pipe from the child. */
1807 fputs (buffer, stderr);
1812 /* The child finished normally. Replace all newlines in its output
1813 with spaces, and put that in the variable output buffer. */
1814 fold_newlines (buffer, &i, trim_newlines);
1815 o = variable_buffer_output (o, buffer, i);
1826 /* Do the Amiga version of func_shell. */
1829 func_shell_base (char *o, char **argv, int trim_newlines)
1831 /* Amiga can't fork nor spawn, but I can start a program with
1832 redirection of my choice. However, this means that we
1833 don't have an opportunity to reopen stdout to trap it. Thus,
1834 we save our own stdout onto a new descriptor and dup a temp
1835 file's descriptor onto our stdout temporarily. After we
1836 spawn the shell program, we dup our own stdout back to the
1837 stdout descriptor. The buffer reading is the same as above,
1838 except that we're now reading from a file. */
1840 #include <dos/dos.h>
1841 #include <proto/dos.h>
1844 char tmp_output[FILENAME_MAX];
1845 unsigned int maxlen = 200, i;
1847 char * buffer, * ptr;
1850 char* batch_filename = NULL;
1852 /* Construct the argument list. */
1853 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1855 if (command_argv == 0)
1858 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1859 Ideally we would use output_tmpfile(), but this uses a special
1860 Open(), not fopen(), and I'm not familiar enough with the code to mess
1862 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1863 mktemp (tmp_output);
1864 child_stdout = Open (tmp_output, MODE_NEWFILE);
1866 for (aptr=command_argv; *aptr; aptr++)
1867 len += strlen (*aptr) + 1;
1869 buffer = xmalloc (len + 1);
1872 for (aptr=command_argv; *aptr; aptr++)
1874 strcpy (ptr, *aptr);
1875 ptr += strlen (ptr) + 1;
1882 Execute (buffer, NULL, child_stdout);
1885 Close (child_stdout);
1887 child_stdout = Open (tmp_output, MODE_OLDFILE);
1889 buffer = xmalloc (maxlen);
1896 buffer = xrealloc (buffer, maxlen + 1);
1899 cc = Read (child_stdout, &buffer[i], maxlen - i);
1904 Close (child_stdout);
1906 fold_newlines (buffer, &i, trim_newlines);
1907 o = variable_buffer_output (o, buffer, i);
1914 func_shell (char *o, char **argv, const char *funcname UNUSED)
1916 return func_shell_base (o, argv, 1);
1923 equality. Return is string-boolean, i.e., the empty string is false.
1926 func_eq (char *o, char **argv, char *funcname UNUSED)
1928 int result = ! strcmp (argv[0], argv[1]);
1929 o = variable_buffer_output (o, result ? "1" : "", result);
1935 string-boolean not operator.
1938 func_not (char *o, char **argv, char *funcname UNUSED)
1940 const char *s = argv[0];
1942 while (isspace ((unsigned char)*s))
1945 o = variable_buffer_output (o, result ? "1" : "", result);
1951 #ifdef HAVE_DOS_PATHS
1953 # define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || STOP_SET (n[0], MAP_PATHSEP))
1955 # define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1959 #define IS_ABSOLUTE(n) (n[0] == '/')
1963 /* Return the absolute name of file NAME which does not contain any '.',
1964 '..' components nor any repeated path separators ('/'). */
1967 abspath (const char *name, char *apath)
1970 const char *start, *end, *apath_limit;
1971 unsigned long root_len = ROOT_LEN;
1973 if (name[0] == '\0' || apath == NULL)
1976 apath_limit = apath + GET_PATH_MAX;
1978 if (!IS_ABSOLUTE(name))
1980 /* It is unlikely we would make it until here but just to make sure. */
1981 if (!starting_directory)
1984 strcpy (apath, starting_directory);
1986 #ifdef HAVE_DOS_PATHS
1987 if (STOP_SET (name[0], MAP_PATHSEP))
1989 if (STOP_SET (name[1], MAP_PATHSEP))
1991 /* A UNC. Don't prepend a drive letter. */
1996 /* We have /foo, an absolute file name except for the drive
1997 letter. Assume the missing drive letter is the current
1998 drive, which we can get if we remove from starting_directory
1999 everything past the root directory. */
2000 apath[root_len] = '\0';
2004 dest = strchr (apath, '\0');
2008 #if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
2009 if (STOP_SET (name[0], MAP_PATHSEP))
2012 strncpy (apath, name, root_len);
2013 apath[root_len] = '\0';
2014 dest = apath + root_len;
2015 /* Get past the root, since we already copied it. */
2017 #ifdef HAVE_DOS_PATHS
2018 if (! STOP_SET (apath[root_len - 1], MAP_PATHSEP))
2020 /* Convert d:foo into d:./foo and increase root_len. */
2025 /* strncpy above copied one character too many. */
2029 apath[root_len - 1] = '/'; /* make sure it's a forward slash */
2033 for (start = end = name; *start != '\0'; start = end)
2037 /* Skip sequence of multiple path-separators. */
2038 while (STOP_SET (*start, MAP_PATHSEP))
2041 /* Find end of path component. */
2042 for (end = start; ! STOP_SET (*end, MAP_PATHSEP|MAP_NUL); ++end)
2049 else if (len == 1 && start[0] == '.')
2051 else if (len == 2 && start[0] == '.' && start[1] == '.')
2053 /* Back up to previous component, ignore if at root already. */
2054 if (dest > apath + root_len)
2055 for (--dest; ! STOP_SET (dest[-1], MAP_PATHSEP); --dest)
2060 if (! STOP_SET (dest[-1], MAP_PATHSEP))
2063 if (dest + len >= apath_limit)
2066 dest = memcpy (dest, start, len);
2072 /* Unless it is root strip trailing separator. */
2073 if (dest > apath + root_len && STOP_SET (dest[-1], MAP_PATHSEP))
2083 func_realpath (char *o, char **argv, const char *funcname UNUSED)
2085 /* Expand the argument. */
2086 const char *p = argv[0];
2087 const char *path = 0;
2089 unsigned int len = 0;
2091 while ((path = find_next_token (&p, &len)) != 0)
2093 if (len < GET_PATH_MAX)
2100 strncpy (in, path, len);
2103 #ifdef HAVE_REALPATH
2104 ENULLLOOP (rp, realpath (in, out));
2106 rp = abspath (in, out);
2112 EINTRLOOP (r, stat (out, &st));
2115 o = variable_buffer_output (o, out, strlen (out));
2116 o = variable_buffer_output (o, " ", 1);
2123 /* Kill last space. */
2131 func_file (char *o, char **argv, const char *funcname UNUSED)
2138 const char *mode = "w";
2140 /* We are writing a file. */
2147 fn = next_token (fn);
2149 fp = fopen (fn, mode);
2151 fatal (reading_file, _("open: %s: %s"), fn, strerror (errno));
2154 int l = strlen (argv[1]);
2155 int nl = (l == 0 || argv[1][l-1] != '\n');
2157 if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
2158 fatal (reading_file, _("write: %s: %s"), fn, strerror (errno));
2164 fatal (reading_file, _("Invalid file operation: %s"), fn);
2170 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2172 /* Expand the argument. */
2173 const char *p = argv[0];
2174 const char *path = 0;
2176 unsigned int len = 0;
2178 while ((path = find_next_token (&p, &len)) != 0)
2180 if (len < GET_PATH_MAX)
2185 strncpy (in, path, len);
2188 if (abspath (in, out))
2190 o = variable_buffer_output (o, out, strlen (out));
2191 o = variable_buffer_output (o, " ", 1);
2197 /* Kill last space. */
2204 /* Lookup table for builtin functions.
2206 This doesn't have to be sorted; we use a straight lookup. We might gain
2207 some efficiency by moving most often used functions to the start of the
2210 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2211 comma-separated values are treated as arguments.
2213 EXPAND_ARGS means that all arguments should be expanded before invocation.
2214 Functions that do namespace tricks (foreach) don't automatically expand. */
2216 static char *func_call (char *o, char **argv, const char *funcname);
2218 #define FT_ENTRY(_name, _min, _max, _exp, _func) \
2219 { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0 }
2221 static struct function_table_entry function_table_init[] =
2223 /* Name MIN MAX EXP? Function */
2224 FT_ENTRY ("abspath", 0, 1, 1, func_abspath),
2225 FT_ENTRY ("addprefix", 2, 2, 1, func_addsuffix_addprefix),
2226 FT_ENTRY ("addsuffix", 2, 2, 1, func_addsuffix_addprefix),
2227 FT_ENTRY ("basename", 0, 1, 1, func_basename_dir),
2228 FT_ENTRY ("dir", 0, 1, 1, func_basename_dir),
2229 FT_ENTRY ("notdir", 0, 1, 1, func_notdir_suffix),
2230 FT_ENTRY ("subst", 3, 3, 1, func_subst),
2231 FT_ENTRY ("suffix", 0, 1, 1, func_notdir_suffix),
2232 FT_ENTRY ("filter", 2, 2, 1, func_filter_filterout),
2233 FT_ENTRY ("filter-out", 2, 2, 1, func_filter_filterout),
2234 FT_ENTRY ("findstring", 2, 2, 1, func_findstring),
2235 FT_ENTRY ("firstword", 0, 1, 1, func_firstword),
2236 FT_ENTRY ("flavor", 0, 1, 1, func_flavor),
2237 FT_ENTRY ("join", 2, 2, 1, func_join),
2238 FT_ENTRY ("lastword", 0, 1, 1, func_lastword),
2239 FT_ENTRY ("patsubst", 3, 3, 1, func_patsubst),
2240 FT_ENTRY ("realpath", 0, 1, 1, func_realpath),
2241 FT_ENTRY ("shell", 0, 1, 1, func_shell),
2242 FT_ENTRY ("sort", 0, 1, 1, func_sort),
2243 FT_ENTRY ("strip", 0, 1, 1, func_strip),
2244 FT_ENTRY ("wildcard", 0, 1, 1, func_wildcard),
2245 FT_ENTRY ("word", 2, 2, 1, func_word),
2246 FT_ENTRY ("wordlist", 3, 3, 1, func_wordlist),
2247 FT_ENTRY ("words", 0, 1, 1, func_words),
2248 FT_ENTRY ("origin", 0, 1, 1, func_origin),
2249 FT_ENTRY ("foreach", 3, 3, 0, func_foreach),
2250 FT_ENTRY ("call", 1, 0, 1, func_call),
2251 FT_ENTRY ("info", 0, 1, 1, func_error),
2252 FT_ENTRY ("error", 0, 1, 1, func_error),
2253 FT_ENTRY ("warning", 0, 1, 1, func_error),
2254 FT_ENTRY ("if", 2, 3, 0, func_if),
2255 FT_ENTRY ("or", 1, 0, 0, func_or),
2256 FT_ENTRY ("and", 1, 0, 0, func_and),
2257 FT_ENTRY ("value", 0, 1, 1, func_value),
2258 FT_ENTRY ("eval", 0, 1, 1, func_eval),
2259 FT_ENTRY ("file", 1, 2, 1, func_file),
2261 FT_ENTRY ("eq", 2, 2, 1, func_eq),
2262 FT_ENTRY ("not", 0, 1, 1, func_not),
2266 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2269 /* These must come after the definition of function_table. */
2272 expand_builtin_function (char *o, int argc, char **argv,
2273 const struct function_table_entry *entry_p)
2277 if (argc < (int)entry_p->minimum_args)
2278 fatal (*expanding_var,
2279 _("insufficient number of arguments (%d) to function '%s'"),
2280 argc, entry_p->name);
2282 /* I suppose technically some function could do something with no arguments,
2283 but so far no internal ones do, so just test it for all functions here
2284 rather than in each one. We can change it later if necessary. */
2286 if (!argc && !entry_p->alloc_fn)
2289 if (!entry_p->fptr.func_ptr)
2290 fatal (*expanding_var,
2291 _("unimplemented on this platform: function '%s'"), entry_p->name);
2293 if (!entry_p->alloc_fn)
2294 return entry_p->fptr.func_ptr (o, argv, entry_p->name);
2296 /* This function allocates memory and returns it to us.
2297 Write it to the variable buffer, then free it. */
2299 p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
2302 o = variable_buffer_output (o, p, strlen (p));
2309 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2310 opening ( or { and is not null-terminated. If a function invocation
2311 is found, expand it into the buffer at *OP, updating *OP, incrementing
2312 *STRINGP past the reference and returning nonzero. If not, return zero. */
2315 handle_function (char **op, const char **stringp)
2317 const struct function_table_entry *entry_p;
2318 char openparen = (*stringp)[0];
2319 char closeparen = openparen == '(' ? ')' : '}';
2324 char **argv, **argvp;
2329 entry_p = lookup_function (beg);
2334 /* We found a builtin function. Find the beginning of its arguments (skip
2335 whitespace after the name). */
2337 beg = next_token (beg + entry_p->len);
2339 /* Find the end of the function invocation, counting nested use of
2340 whichever kind of parens we use. Since we're looking, count commas
2341 to get a rough estimate of how many arguments we might have. The
2342 count might be high, but it'll never be low. */
2344 for (nargs=1, end=beg; *end != '\0'; ++end)
2347 else if (*end == openparen)
2349 else if (*end == closeparen && --count < 0)
2353 fatal (*expanding_var,
2354 _("unterminated call to function '%s': missing '%c'"),
2355 entry_p->name, closeparen);
2359 /* Get some memory to store the arg pointers. */
2360 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2362 /* Chop the string into arguments, then a nul. As soon as we hit
2363 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2366 If we're expanding, store pointers to the expansion of each one. If
2367 not, make a duplicate of the string and point into that, nul-terminating
2370 if (entry_p->expand_args)
2373 for (p=beg, nargs=0; p <= end; ++argvp)
2379 if (nargs == entry_p->maximum_args
2380 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2383 *argvp = expand_argument (p, next);
2389 int len = end - beg;
2392 abeg = xmalloc (len+1);
2393 memcpy (abeg, beg, len);
2397 for (p=abeg, nargs=0; p <= aend; ++argvp)
2403 if (nargs == entry_p->maximum_args
2404 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2414 /* Finally! Run the function... */
2415 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2418 if (entry_p->expand_args)
2419 for (argvp=argv; *argvp != 0; ++argvp)
2428 /* User-defined functions. Expand the first argument as either a builtin
2429 function or a make variable, in the context of the rest of the arguments
2430 assigned to $1, $2, ... $N. $0 is the name of the function. */
2433 func_call (char *o, char **argv, const char *funcname UNUSED)
2435 static int max_args = 0;
2442 const struct function_table_entry *entry_p;
2445 /* There is no way to define a variable with a space in the name, so strip
2446 leading and trailing whitespace as a favor to the user. */
2448 while (isspace ((unsigned char)*fname))
2451 cp = fname + strlen (fname) - 1;
2452 while (cp > fname && isspace ((unsigned char)*cp))
2456 /* Calling nothing is a no-op */
2460 /* Are we invoking a builtin function? */
2462 entry_p = lookup_function (fname);
2465 /* How many arguments do we have? */
2466 for (i=0; argv[i+1]; ++i)
2468 return expand_builtin_function (o, i, argv+1, entry_p);
2471 /* Not a builtin, so the first argument is the name of a variable to be
2472 expanded and interpreted as a function. Find it. */
2473 flen = strlen (fname);
2475 v = lookup_variable (fname, flen);
2478 warn_undefined (fname, flen);
2480 if (v == 0 || *v->value == '\0')
2483 body = alloca (flen + 4);
2486 memcpy (body + 2, fname, flen);
2488 body[flen+3] = '\0';
2490 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2492 push_new_variable_scope ();
2494 for (i=0; *argv; ++i, ++argv)
2498 sprintf (num, "%d", i);
2499 define_variable (num, strlen (num), *argv, o_automatic, 0);
2502 /* If the number of arguments we have is < max_args, it means we're inside
2503 a recursive invocation of $(call ...). Fill in the remaining arguments
2504 in the new scope with the empty value, to hide them from this
2507 for (; i < max_args; ++i)
2511 sprintf (num, "%d", i);
2512 define_variable (num, strlen (num), "", o_automatic, 0);
2515 /* Expand the body in the context of the arguments, adding the result to
2516 the variable buffer. */
2518 v->exp_count = EXP_COUNT_MAX;
2520 saved_args = max_args;
2522 o = variable_expand_string (o, body, flen+3);
2523 max_args = saved_args;
2527 pop_variable_scope ();
2529 return o + strlen (o);
2533 define_new_function (const gmk_floc *flocp, const char *name,
2534 unsigned int min, unsigned int max, unsigned int flags,
2537 const char *e = name;
2538 struct function_table_entry *ent;
2541 while (STOP_SET (*e, MAP_USERFUNC))
2546 fatal (flocp, _("Empty function name\n"));
2547 if (*name == '.' || *e != '\0')
2548 fatal (flocp, _("Invalid function name: %s\n"), name);
2550 fatal (flocp, _("Function name too long: %s\n"), name);
2552 fatal (flocp, _("Invalid minimum argument count (%d) for function %s\n"),
2554 if (max > 255 || (max && max < min))
2555 fatal (flocp, _("Invalid maximum argument count (%d) for function %s\n"),
2558 ent = xmalloc (sizeof (struct function_table_entry));
2561 ent->minimum_args = min;
2562 ent->maximum_args = max;
2563 ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
2565 ent->fptr.alloc_func_ptr = func;
2567 hash_insert (&function_table, ent);
2571 hash_init_function_table (void)
2573 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2574 function_table_entry_hash_1, function_table_entry_hash_2,
2575 function_table_entry_hash_cmp);
2576 hash_load (&function_table, function_table_init,
2577 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));