1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988-2022 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 <https://www.gnu.org/licenses/>. */
31 struct function_table_entry
34 char *(*func_ptr) (char *output, char **argv, const char *fname);
35 gmk_func_ptr alloc_func_ptr;
39 unsigned char minimum_args;
40 unsigned char maximum_args;
41 unsigned int expand_args:1;
42 unsigned int alloc_fn:1;
43 unsigned int adds_command:1;
47 function_table_entry_hash_1 (const void *keyv)
49 const struct function_table_entry *key = keyv;
50 return_STRING_N_HASH_1 (key->name, key->len);
54 function_table_entry_hash_2 (const void *keyv)
56 const struct function_table_entry *key = keyv;
57 return_STRING_N_HASH_2 (key->name, key->len);
61 function_table_entry_hash_cmp (const void *xv, const void *yv)
63 const struct function_table_entry *x = xv;
64 const struct function_table_entry *y = yv;
65 int result = x->len - y->len;
68 return_STRING_N_COMPARE (x->name, y->name, x->len);
71 static struct hash_table function_table;
74 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
75 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
76 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
77 nonzero, substitutions are done only on matches which are complete
78 whitespace-delimited words. */
81 subst_expand (char *o, const char *text, const char *subst, const char *replace,
82 size_t slen, size_t rlen, int by_word)
87 if (slen == 0 && !by_word)
89 /* The first occurrence of "" in any string is its end. */
90 o = variable_buffer_output (o, t, strlen (t));
92 o = variable_buffer_output (o, replace, rlen);
98 if (by_word && slen == 0)
99 /* When matching by words, the empty string should match
100 the end of each word, rather than the end of the whole text. */
101 p = end_of_token (next_token (t));
104 p = strstr (t, subst);
107 /* No more matches. Output everything left on the end. */
108 o = variable_buffer_output (o, t, strlen (t));
113 /* Output everything before this occurrence of the string to replace. */
115 o = variable_buffer_output (o, t, p - t);
117 /* If we're substituting only by fully matched words,
118 or only at the ends of words, check that this case qualifies. */
120 && ((p > text && !ISSPACE (p[-1]))
121 || ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
122 /* Struck out. Output the rest of the string that is
123 no longer to be replaced. */
124 o = variable_buffer_output (o, subst, slen);
126 /* Output the replacement string. */
127 o = variable_buffer_output (o, replace, rlen);
129 /* Advance T past the string to be replaced. */
131 } while (*t != '\0');
137 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
138 and replacing strings matching PATTERN with REPLACE.
139 If PATTERN_PERCENT is not nil, PATTERN has already been
140 run through find_percent, and PATTERN_PERCENT is the result.
141 If REPLACE_PERCENT is not nil, REPLACE has already been
142 run through find_percent, and REPLACE_PERCENT is the result.
143 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
144 character _AFTER_ the %, not to the % itself.
148 patsubst_expand_pat (char *o, const char *text,
149 const char *pattern, const char *replace,
150 const char *pattern_percent, const char *replace_percent)
152 size_t pattern_prepercent_len, pattern_postpercent_len;
153 size_t replace_prepercent_len, replace_postpercent_len;
158 /* Record the length of REPLACE before and after the % so we don't have to
159 compute these lengths more than once. */
162 replace_prepercent_len = replace_percent - replace - 1;
163 replace_postpercent_len = strlen (replace_percent);
167 replace_prepercent_len = strlen (replace);
168 replace_postpercent_len = 0;
171 if (!pattern_percent)
172 /* With no % in the pattern, this is just a simple substitution. */
173 return subst_expand (o, text, pattern, replace,
174 strlen (pattern), strlen (replace), 1);
176 /* Record the length of PATTERN before and after the %
177 so we don't have to compute it more than once. */
178 pattern_prepercent_len = pattern_percent - pattern - 1;
179 pattern_postpercent_len = strlen (pattern_percent);
181 while ((t = find_next_token (&text, &len)) != 0)
185 /* Is it big enough to match? */
186 if (len < pattern_prepercent_len + pattern_postpercent_len)
189 /* Does the prefix match? */
190 if (!fail && pattern_prepercent_len > 0
192 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
193 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
196 /* Does the suffix match? */
197 if (!fail && pattern_postpercent_len > 0
198 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
199 || t[len - pattern_postpercent_len] != *pattern_percent
200 || !strneq (&t[len - pattern_postpercent_len],
201 pattern_percent, pattern_postpercent_len - 1)))
205 /* It didn't match. Output the string. */
206 o = variable_buffer_output (o, t, len);
209 /* It matched. Output the replacement. */
211 /* Output the part of the replacement before the %. */
212 o = variable_buffer_output (o, replace, replace_prepercent_len);
214 if (replace_percent != 0)
216 /* Output the part of the matched string that
217 matched the % in the pattern. */
218 o = variable_buffer_output (o, t + pattern_prepercent_len,
219 len - (pattern_prepercent_len
220 + pattern_postpercent_len));
221 /* Output the part of the replacement after the %. */
222 o = variable_buffer_output (o, replace_percent,
223 replace_postpercent_len);
227 /* Output a space, but not if the replacement is "". */
228 if (fail || replace_prepercent_len > 0
229 || (replace_percent != 0 && len + replace_postpercent_len > 0))
231 o = variable_buffer_output (o, " ", 1);
236 /* Kill the last space. */
242 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
243 and replacing strings matching PATTERN with REPLACE.
244 If PATTERN_PERCENT is not nil, PATTERN has already been
245 run through find_percent, and PATTERN_PERCENT is the result.
246 If REPLACE_PERCENT is not nil, REPLACE has already been
247 run through find_percent, and REPLACE_PERCENT is the result.
248 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
249 character _AFTER_ the %, not to the % itself.
253 patsubst_expand (char *o, const char *text, char *pattern, char *replace)
255 const char *pattern_percent = find_percent (pattern);
256 const char *replace_percent = find_percent (replace);
258 /* If there's a percent in the pattern or replacement skip it. */
264 return patsubst_expand_pat (o, text, pattern, replace,
265 pattern_percent, replace_percent);
269 /* Look up a function by name. */
271 static const struct function_table_entry *
272 lookup_function (const char *s)
274 struct function_table_entry function_table_entry_key;
277 while (STOP_SET (*e, MAP_USERFUNC))
280 if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
283 function_table_entry_key.name = s;
284 function_table_entry_key.len = (unsigned char) (e - s);
286 return hash_find_item (&function_table, &function_table_entry_key);
290 /* Return 1 if PATTERN matches STR, 0 if not. */
293 pattern_matches (const char *pattern, const char *percent, const char *str)
295 size_t sfxlen, strlength;
299 size_t len = strlen (pattern) + 1;
300 char *new_chars = alloca (len);
301 memcpy (new_chars, pattern, len);
302 percent = find_percent (new_chars);
304 return streq (new_chars, str);
308 sfxlen = strlen (percent + 1);
309 strlength = strlen (str);
311 if (strlength < (percent - pattern) + sfxlen
312 || !strneq (pattern, str, percent - pattern))
315 return !strcmp (percent + 1, str + (strlength - sfxlen));
319 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
320 ENDPARENtheses), starting at PTR before END. Return a pointer to
323 If no next argument is found, return NULL.
327 find_next_argument (char startparen, char endparen,
328 const char *ptr, const char *end)
332 for (; ptr < end; ++ptr)
333 if (!STOP_SET (*ptr, MAP_VARSEP|MAP_COMMA))
336 else if (*ptr == startparen)
339 else if (*ptr == endparen)
346 else if (*ptr == ',' && !count)
349 /* We didn't find anything. */
354 /* Glob-expand LINE. The returned pointer is
355 only good until the next call to string_glob. */
358 string_glob (char *line)
360 static char *result = 0;
361 static size_t length;
362 struct nameseq *chain;
365 chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
366 /* We do not want parse_file_seq to strip './'s.
367 That would break examples like:
368 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
369 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
374 result = xmalloc (100);
380 struct nameseq *next = chain->next;
381 size_t len = strlen (chain->name);
383 if (idx + len + 1 > length)
385 length += (len + 1) * 2;
386 result = xrealloc (result, length);
388 memcpy (&result[idx], chain->name, len);
392 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
393 free ((char *)chain->name);
398 /* Kill the last space and terminate the string. */
402 result[idx - 1] = '\0';
412 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
414 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
420 func_join (char *o, char **argv, const char *funcname UNUSED)
424 /* Write each word of the first argument directly followed
425 by the corresponding word of the second argument.
426 If the two arguments have a different number of words,
427 the excess words are just output separated by blanks. */
430 const char *list1_iterator = argv[0];
431 const char *list2_iterator = argv[1];
436 tp = find_next_token (&list1_iterator, &len1);
438 o = variable_buffer_output (o, tp, len1);
440 pp = find_next_token (&list2_iterator, &len2);
442 o = variable_buffer_output (o, pp, len2);
444 if (tp != 0 || pp != 0)
446 o = variable_buffer_output (o, " ", 1);
450 while (tp != 0 || pp != 0);
452 /* Kill the last blank. */
460 func_origin (char *o, char **argv, const char *funcname UNUSED)
462 /* Expand the argument. */
463 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
465 o = variable_buffer_output (o, "undefined", 9);
473 o = variable_buffer_output (o, "default", 7);
476 o = variable_buffer_output (o, "environment", 11);
479 o = variable_buffer_output (o, "file", 4);
482 o = variable_buffer_output (o, "environment override", 20);
485 o = variable_buffer_output (o, "command line", 12);
488 o = variable_buffer_output (o, "override", 8);
491 o = variable_buffer_output (o, "automatic", 9);
499 func_flavor (char *o, char **argv, const char *funcname UNUSED)
501 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
504 o = variable_buffer_output (o, "undefined", 9);
507 o = variable_buffer_output (o, "recursive", 9);
509 o = variable_buffer_output (o, "simple", 6);
516 func_notdir_suffix (char *o, char **argv, const char *funcname)
518 /* Expand the argument. */
519 const char *list_iterator = argv[0];
524 int is_suffix = funcname[0] == 's';
525 int is_notdir = !is_suffix;
526 int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
528 /* For VMS list_iterator points to a comma separated list. To use the common
529 [find_]next_token, create a local copy and replace the commas with
530 spaces. Obviously, there is a problem if there is a ',' in the VMS filename
531 (can only happen on ODS5), the same problem as with spaces in filenames,
532 which seems to be present in make on all platforms. */
533 char *vms_list_iterator = alloca(strlen(list_iterator) + 1);
535 for (i = 0; list_iterator[i]; i++)
536 if (list_iterator[i] == ',')
537 vms_list_iterator[i] = ' ';
539 vms_list_iterator[i] = list_iterator[i];
540 vms_list_iterator[i] = list_iterator[i];
541 while ((p2 = find_next_token((const char**) &vms_list_iterator, &len)) != 0)
543 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
546 const char *p = p2 + len - 1;
548 while (p >= p2 && ! STOP_SET (*p, stop))
557 o = variable_buffer_output (o, p, len - (p - p2));
559 #ifdef HAVE_DOS_PATHS
560 /* Handle the case of "d:foo/bar". */
561 else if (is_notdir && p2[0] && p2[1] == ':')
564 o = variable_buffer_output (o, p, len - (p - p2));
568 o = variable_buffer_output (o, p2, len);
570 if (is_notdir || p >= p2)
573 if (vms_comma_separator)
574 o = variable_buffer_output (o, ",", 1);
577 o = variable_buffer_output (o, " ", 1);
584 /* Kill last space. */
592 func_basename_dir (char *o, char **argv, const char *funcname)
594 /* Expand the argument. */
595 const char *p3 = argv[0];
600 int is_basename = funcname[0] == 'b';
601 int is_dir = !is_basename;
602 int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
604 /* As in func_notdir_suffix ... */
605 char *vms_p3 = alloca (strlen(p3) + 1);
607 for (i = 0; p3[i]; i++)
613 while ((p2 = find_next_token((const char**) &vms_p3, &len)) != 0)
615 while ((p2 = find_next_token (&p3, &len)) != 0)
618 const char *p = p2 + len - 1;
619 while (p >= p2 && ! STOP_SET (*p, stop))
622 if (p >= p2 && (is_dir))
623 o = variable_buffer_output (o, p2, ++p - p2);
624 else if (p >= p2 && (*p == '.'))
625 o = variable_buffer_output (o, p2, p - p2);
626 #ifdef HAVE_DOS_PATHS
627 /* Handle the "d:foobar" case */
628 else if (p2[0] && p2[1] == ':' && is_dir)
629 o = variable_buffer_output (o, p2, 2);
634 extern int vms_report_unix_paths;
635 if (vms_report_unix_paths)
636 o = variable_buffer_output (o, "./", 2);
638 o = variable_buffer_output (o, "[]", 2);
642 o = variable_buffer_output (o, "./", 2);
644 ; /* Just a nop... */
648 /* The entire name is the basename. */
649 o = variable_buffer_output (o, p2, len);
652 if (vms_comma_separator)
653 o = variable_buffer_output (o, ",", 1);
656 o = variable_buffer_output (o, " ", 1);
662 /* Kill last space. */
669 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
671 size_t fixlen = strlen (argv[0]);
672 const char *list_iterator = argv[1];
673 int is_addprefix = funcname[3] == 'p';
674 int is_addsuffix = !is_addprefix;
680 while ((p = find_next_token (&list_iterator, &len)) != 0)
683 o = variable_buffer_output (o, argv[0], fixlen);
684 o = variable_buffer_output (o, p, len);
686 o = variable_buffer_output (o, argv[0], fixlen);
687 o = variable_buffer_output (o, " ", 1);
692 /* Kill last space. */
699 func_subst (char *o, char **argv, const char *funcname UNUSED)
701 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
702 strlen (argv[1]), 0);
709 func_firstword (char *o, char **argv, const char *funcname UNUSED)
712 const char *words = argv[0]; /* Use a temp variable for find_next_token */
713 const char *p = find_next_token (&words, &i);
716 o = variable_buffer_output (o, p, i);
722 func_lastword (char *o, char **argv, const char *funcname UNUSED)
725 const char *words = argv[0]; /* Use a temp variable for find_next_token */
726 const char *p = NULL;
729 while ((t = find_next_token (&words, &i)) != NULL)
733 o = variable_buffer_output (o, p, i);
739 func_words (char *o, char **argv, const char *funcname UNUSED)
742 const char *word_iterator = argv[0];
743 char buf[INTSTR_LENGTH];
745 while (find_next_token (&word_iterator, NULL) != 0)
748 sprintf (buf, "%u", i);
749 o = variable_buffer_output (o, buf, strlen (buf));
754 /* Set begpp to point to the first non-whitespace character of the string,
755 * and endpp to point to the last non-whitespace character of the string.
756 * If the string is empty or contains nothing but whitespace, endpp will be
760 strip_whitespace (const char **begpp, const char **endpp)
762 while (*begpp <= *endpp && ISSPACE (**begpp))
764 while (*endpp >= *begpp && ISSPACE (**endpp))
766 return (char *)*begpp;
770 parse_numeric (const char *s, const char *msg)
773 const char *end = s + strlen (s) - 1;
776 strip_whitespace (&beg, &end);
779 OS (fatal, *expanding_var, _("%s: empty value"), msg);
782 num = strtoll (beg, &endp, 10);
784 OSS (fatal, *expanding_var, _("%s: '%s' out of range"), msg, s);
785 else if (endp == beg || endp <= end)
786 /* Empty or non-numeric input */
787 OSS (fatal, *expanding_var, "%s: '%s'", msg, s);
793 func_word (char *o, char **argv, const char *funcname UNUSED)
799 i = parse_numeric (argv[0],
800 _("invalid first argument to 'word' function"));
802 O (fatal, *expanding_var,
803 _("first argument to 'word' function must be greater than 0"));
806 while ((p = find_next_token (&end_p, 0)) != 0)
811 o = variable_buffer_output (o, p, end_p - p);
817 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
819 char buf[INTSTR_LENGTH + 1];
820 long long start, stop, count;
821 const char* badfirst = _("invalid first argument to 'wordlist' function");
822 const char* badsecond = _("invalid second argument to 'wordlist' function");
824 start = parse_numeric (argv[0], badfirst);
826 OSS (fatal, *expanding_var, "%s: '%s'", badfirst, make_lltoa (start, buf));
828 stop = parse_numeric (argv[1], badsecond);
830 OSS (fatal, *expanding_var, "%s: '%s'", badsecond, make_lltoa (stop, buf));
832 count = stop - start + 1;
837 const char *end_p = argv[2];
839 /* Find the beginning of the "start"th word. */
840 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
845 /* Find the end of the "count"th word from start. */
846 while (--count && (find_next_token (&end_p, 0) != 0))
849 /* Return the stuff in the middle. */
850 o = variable_buffer_output (o, p, end_p - p);
858 func_findstring (char *o, char **argv, const char *funcname UNUSED)
860 /* Find the first occurrence of the first string in the second. */
861 if (strstr (argv[1], argv[0]) != 0)
862 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
868 func_foreach (char *o, char **argv, const char *funcname UNUSED)
870 /* expand only the first two. */
871 char *varname = expand_argument (argv[0], NULL);
872 char *list = expand_argument (argv[1], NULL);
873 const char *body = argv[2];
876 const char *list_iterator = list;
879 struct variable *var;
881 /* Clean up the variable name by removing whitespace. */
882 char *vp = next_token (varname);
883 end_of_token (vp)[0] = '\0';
885 push_new_variable_scope ();
886 var = define_variable (vp, strlen (vp), "", o_automatic, 0);
888 /* loop through LIST, put the value in VAR and expand BODY */
889 while ((p = find_next_token (&list_iterator, &len)) != 0)
894 var->value = xstrndup (p, len);
896 result = allocated_variable_expand (body);
898 o = variable_buffer_output (o, result, strlen (result));
899 o = variable_buffer_output (o, " ", 1);
905 /* Kill the last space. */
908 pop_variable_scope ();
916 func_let (char *o, char **argv, const char *funcname UNUSED)
918 /* expand only the first two. */
919 char *varnames = expand_argument (argv[0], NULL);
920 char *list = expand_argument (argv[1], NULL);
921 const char *body = argv[2];
924 const char *vp_next = varnames;
925 const char *list_iterator = list;
930 push_new_variable_scope ();
932 /* loop through LIST for all but the last VARNAME */
933 vp = find_next_token (&vp_next, &vlen);
934 NEXT_TOKEN (vp_next);
935 while (*vp_next != '\0')
937 p = find_next_token (&list_iterator, &len);
938 if (*list_iterator != '\0')
943 define_variable (vp, vlen, p ? p : "", o_automatic, 0);
945 vp = find_next_token (&vp_next, &vlen);
946 NEXT_TOKEN (vp_next);
949 /* set the last VARNAME to the remainder of LIST */
951 define_variable (vp, vlen, next_token (list_iterator), o_automatic, 0);
953 /* Expand the body in the context of the arguments, adding the result to
954 the variable buffer. */
956 o = variable_expand_string (o, body, SIZE_MAX);
958 pop_variable_scope ();
962 return o + strlen (o);
967 struct a_word *chain;
974 a_word_hash_1 (const void *key)
976 return_STRING_HASH_1 (((struct a_word const *) key)->str);
980 a_word_hash_2 (const void *key)
982 return_STRING_HASH_2 (((struct a_word const *) key)->str);
986 a_word_hash_cmp (const void *x, const void *y)
988 const struct a_word *ax = x;
989 const struct a_word *ay = y;
991 if (ax->length != ay->length)
992 return ax->length > ay->length ? 1 : -1;
994 return_STRING_N_COMPARE (ax->str, ay->str, ax->length);
1005 func_filter_filterout (char *o, char **argv, const char *funcname)
1007 struct a_word *words;
1008 struct a_word *word_end;
1010 struct a_pattern *patterns;
1011 struct a_pattern *pat_end;
1012 struct a_pattern *pp;
1013 unsigned long pat_count = 0, word_count = 0;
1015 struct hash_table a_word_table;
1016 int is_filter = funcname[CSTRLEN ("filter")] == '\0';
1024 /* Find the number of words and get memory for them. */
1026 while ((p = find_next_token (&cp, NULL)) != 0)
1032 words = xcalloc (word_count * sizeof (struct a_word));
1033 word_end = words + word_count;
1035 /* Find the number of patterns and get memory for them. */
1037 while ((p = find_next_token (&cp, NULL)) != 0)
1040 patterns = xcalloc (pat_count * sizeof (struct a_pattern));
1041 pat_end = patterns + pat_count;
1043 /* Chop argv[0] up into patterns to match against the words. */
1047 while ((p = find_next_token (&cp, &len)) != 0)
1054 pp->percent = find_percent (p);
1055 if (pp->percent == 0)
1057 /* find_percent() might shorten the string so LEN is wrong. */
1058 pp->length = strlen (pp->str);
1063 /* Chop ARGV[1] up into words to match against the patterns. */
1067 while ((p = find_next_token (&cp, &len)) != 0)
1078 /* Only use a hash table if arg list lengths justifies the cost. */
1079 hashing = (literals > 1 && (literals * word_count) >= 10);
1082 hash_init (&a_word_table, word_count, a_word_hash_1, a_word_hash_2,
1084 for (wp = words; wp < word_end; ++wp)
1086 struct a_word *owp = hash_insert (&a_word_table, wp);
1092 /* Run each pattern through the words, killing words. */
1093 for (pp = patterns; pp < pat_end; ++pp)
1096 for (wp = words; wp < word_end; ++wp)
1097 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1100 struct a_word a_word_key;
1101 a_word_key.str = pp->str;
1102 a_word_key.length = pp->length;
1103 wp = hash_find_item (&a_word_table, &a_word_key);
1111 for (wp = words; wp < word_end; ++wp)
1112 wp->matched |= (wp->length == pp->length
1113 && memcmp (pp->str, wp->str, wp->length) == 0);
1116 /* Output the words that matched (or didn't, for filter-out). */
1117 for (wp = words; wp < word_end; ++wp)
1118 if (is_filter ? wp->matched : !wp->matched)
1120 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1121 o = variable_buffer_output (o, " ", 1);
1126 /* Kill the last space. */
1130 hash_free (&a_word_table, 0);
1140 func_strip (char *o, char **argv, const char *funcname UNUSED)
1142 const char *p = argv[0];
1148 const char *word_start;
1152 for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
1156 o = variable_buffer_output (o, word_start, i);
1157 o = variable_buffer_output (o, " ", 1);
1162 /* Kill the last space. */
1169 Print a warning or fatal message.
1172 func_error (char *o, char **argv, const char *funcname)
1177 OS (fatal, reading_file, "%s", argv[0]);
1180 OS (error, reading_file, "%s", argv[0]);
1185 size_t len = strlen (argv[0]);
1186 char *msg = alloca (len + 2);
1187 memcpy (msg, argv[0], len);
1189 msg[len + 1] = '\0';
1195 OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
1198 /* The warning function expands to the empty string. */
1204 chop argv[0] into words, and sort them.
1207 func_sort (char *o, char **argv, const char *funcname UNUSED)
1215 /* Find the maximum number of words we'll have. */
1218 while ((p = find_next_token (&t, NULL)) != 0)
1224 words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
1226 /* Now assign pointers to each string in the array. */
1229 while ((p = find_next_token (&t, &len)) != 0)
1240 /* Now sort the list of words. */
1241 qsort (words, wordi, sizeof (char *), alpha_compare);
1243 /* Now write the sorted list, uniquified. */
1244 for (i = 0; i < wordi; ++i)
1246 len = strlen (words[i]);
1247 if (i == wordi - 1 || strlen (words[i + 1]) != len
1248 || memcmp (words[i], words[i + 1], len))
1250 o = variable_buffer_output (o, words[i], len);
1251 o = variable_buffer_output (o, " ", 1);
1255 /* Kill the last space. */
1265 Traverse NUMBER consisting of optional leading white space, optional
1266 sign, digits, and optional trailing white space.
1267 If number is not of the proper form, diagnose with MSG. Otherwise,
1268 return the address of of the first character after NUMBER, store
1269 into *SIGN an integer consistent with the number's sign (-1, 0, or 1)
1270 and store into *NUMSTART the address of NUMBER's first nonzero digit
1271 (if NUMBER contains only zero digits, store the address of the first
1272 character after NUMBER).
1275 parse_textint (const char *number, const char *msg,
1276 int *sign, const char **numstart)
1278 const char *after_sign, *after_number;
1279 const char *p = next_token (number);
1280 int negative = *p == '-';
1284 OS (fatal, *expanding_var, _("%s: empty value"), msg);
1286 p += negative || *p == '+';
1293 while (ISDIGIT (*p))
1296 nonzero = *numstart != after_number;
1297 *sign = negative ? -nonzero : nonzero;
1299 /* Check for extra non-whitespace stuff after the value. */
1300 if (after_number == after_sign || *next_token (p) != '\0')
1301 OSS (fatal, *expanding_var, "%s: '%s'", msg, number);
1303 return after_number;
1308 $(intcmp lhs,rhs[,lt-part[,eq-part[,gt-part]]])
1310 LHS and RHS must be integer values (leading/trailing whitespace is ignored).
1311 If none of LT-PART, EQ-PART, or GT-PART are given then the function expands
1312 to empty if LHS and RHS are not equal, or the numeric value if they are equal.
1313 LT-PART is evaluated when LHS is strictly less than RHS, EQ-PART is evaluated
1314 when LHS is equal to RHS, and GT-part is evaluated when LHS is strictly
1316 If GT-PART is not provided, it defaults to EQ-PART. When neither EQ-PART
1317 nor GT-PART are provided, the function expands to empty if LHS is not
1318 strictly less than RHS.
1322 func_intcmp (char *o, char **argv, const char *funcname UNUSED)
1325 const char *lnum, *rnum;
1326 char *lhs_str = expand_argument (argv[0], NULL);
1327 char *rhs_str = expand_argument (argv[1], NULL);
1328 const char *llim = parse_textint (lhs_str, _("non-numeric first argument to 'intcmp' function"), &lsign, &lnum);
1329 const char *rlim = parse_textint (rhs_str, _("non-numeric second argument to 'intcmp' function"), &rsign, &rnum);
1330 ptrdiff_t llen = llim - lnum;
1331 ptrdiff_t rlen = rlim - rnum;
1332 int cmp = lsign - rsign;
1336 cmp = (llen > rlen) - (llen < rlen);
1338 cmp = memcmp (lnum, rnum, llen);
1343 /* Handle the special case where there are only two arguments. */
1344 if (!*argv && cmp == 0)
1347 o = variable_buffer_output (o, "-", 1);
1348 o = variable_buffer_output(o, lnum - !lsign, llen + !lsign);
1354 if (*argv && cmp >= 0)
1357 if (cmp > 0 && *argv && *(argv + 1))
1363 char *expansion = expand_argument (*argv, NULL);
1365 o = variable_buffer_output (o, expansion, strlen (expansion));
1374 $(if condition,true-part[,false-part])
1376 CONDITION is false iff it evaluates to an empty string. White
1377 space before and after condition are stripped before evaluation.
1379 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1380 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1381 you can use $(if ...) to create side-effects (with $(shell ...), for
1386 func_if (char *o, char **argv, const char *funcname UNUSED)
1388 const char *begp = argv[0];
1389 const char *endp = begp + strlen (argv[0]) - 1;
1392 /* Find the result of the condition: if we have a value, and it's not
1393 empty, the condition is true. If we don't have a value, or it's the
1394 empty string, then it's false. */
1396 strip_whitespace (&begp, &endp);
1400 char *expansion = expand_argument (begp, endp+1);
1402 result = expansion[0] != '\0';
1406 /* If the result is true (1) we want to eval the first argument, and if
1407 it's false (0) we want to eval the second. If the argument doesn't
1408 exist we do nothing, otherwise expand it and add to the buffer. */
1410 argv += 1 + !result;
1414 char *expansion = expand_argument (*argv, NULL);
1416 o = variable_buffer_output (o, expansion, strlen (expansion));
1425 $(or condition1[,condition2[,condition3[...]]])
1427 A CONDITION is false iff it evaluates to an empty string. White
1428 space before and after CONDITION are stripped before evaluation.
1430 CONDITION1 is evaluated. If it's true, then this is the result of
1431 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1432 the conditions are true, the expansion is the empty string.
1434 Once a CONDITION is true no further conditions are evaluated
1439 func_or (char *o, char **argv, const char *funcname UNUSED)
1441 for ( ; *argv ; ++argv)
1443 const char *begp = *argv;
1444 const char *endp = begp + strlen (*argv) - 1;
1448 /* Find the result of the condition: if it's false keep going. */
1450 strip_whitespace (&begp, &endp);
1455 expansion = expand_argument (begp, endp+1);
1456 result = strlen (expansion);
1458 /* If the result is false keep going. */
1465 /* It's true! Keep this result and return. */
1466 o = variable_buffer_output (o, expansion, result);
1475 $(and condition1[,condition2[,condition3[...]]])
1477 A CONDITION is false iff it evaluates to an empty string. White
1478 space before and after CONDITION are stripped before evaluation.
1480 CONDITION1 is evaluated. If it's false, then this is the result of
1481 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1482 the conditions are true, the expansion is the result of the last condition.
1484 Once a CONDITION is false no further conditions are evaluated
1489 func_and (char *o, char **argv, const char *funcname UNUSED)
1495 const char *begp = *argv;
1496 const char *endp = begp + strlen (*argv) - 1;
1499 /* An empty condition is always false. */
1500 strip_whitespace (&begp, &endp);
1504 expansion = expand_argument (begp, endp+1);
1505 result = strlen (expansion);
1507 /* If the result is false, stop here: we're done. */
1511 /* Otherwise the result is true. If this is the last one, keep this
1512 result and quit. Otherwise go on to the next one! */
1518 o = variable_buffer_output (o, expansion, result);
1529 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1532 o = wildcard_expansion (argv[0], o);
1534 char *p = string_glob (argv[0]);
1535 o = variable_buffer_output (o, p, strlen (p));
1541 $(eval <makefile string>)
1543 Always resolves to the empty string.
1545 Treat the arguments as a segment of makefile, and parse them.
1549 func_eval (char *o, char **argv, const char *funcname UNUSED)
1554 /* Eval the buffer. Pop the current variable buffer setting so that the
1555 eval'd code can use its own without conflicting. */
1557 install_variable_buffer (&buf, &len);
1559 eval_buffer (argv[0], NULL);
1561 restore_variable_buffer (buf, len);
1568 func_value (char *o, char **argv, const char *funcname UNUSED)
1570 /* Look up the variable. */
1571 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1573 /* Copy its value into the output buffer without expanding it. */
1575 o = variable_buffer_output (o, v->value, strlen (v->value));
1581 \r is replaced on UNIX as well. Is this desirable?
1584 fold_newlines (char *buffer, size_t *length, int trim_newlines)
1588 char *last_nonnl = buffer - 1;
1590 for (; *src != '\0'; ++src)
1592 if (src[0] == '\r' && src[1] == '\n')
1605 if (!trim_newlines && (last_nonnl < (dst - 2)))
1606 last_nonnl = dst - 2;
1608 *(++last_nonnl) = '\0';
1609 *length = last_nonnl - buffer;
1612 pid_t shell_function_pid = 0;
1613 static int shell_function_completed;
1616 shell_completed (int exit_code, int exit_sig)
1618 char buf[INTSTR_LENGTH];
1620 shell_function_pid = 0;
1621 if (exit_sig == 0 && exit_code == 127)
1622 shell_function_completed = -1;
1624 shell_function_completed = 1;
1626 if (exit_code == 0 && exit_sig > 0)
1627 exit_code = 128 + exit_sig;
1629 sprintf (buf, "%d", exit_code);
1630 define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
1636 #include <windows.h>
1638 #include "sub_proc.h"
1642 windows32_openpipe (int *pipedes, int errfd, pid_t *pid_p, char **command_argv, char **envp)
1644 SECURITY_ATTRIBUTES saAttr;
1645 HANDLE hIn = INVALID_HANDLE_VALUE;
1646 HANDLE hErr = INVALID_HANDLE_VALUE;
1649 HANDLE hProcess, tmpIn, tmpErr;
1652 /* Set status for return. */
1653 pipedes[0] = pipedes[1] = -1;
1656 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1657 saAttr.bInheritHandle = TRUE;
1658 saAttr.lpSecurityDescriptor = NULL;
1660 /* Standard handles returned by GetStdHandle can be NULL or
1661 INVALID_HANDLE_VALUE if the parent process closed them. If that
1662 happens, we open the null device and pass its handle to
1663 process_begin below as the corresponding handle to inherit. */
1664 tmpIn = GetStdHandle (STD_INPUT_HANDLE);
1665 if (DuplicateHandle (GetCurrentProcess (), tmpIn,
1666 GetCurrentProcess (), &hIn,
1667 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1669 e = GetLastError ();
1670 if (e == ERROR_INVALID_HANDLE)
1672 tmpIn = CreateFile ("NUL", GENERIC_READ,
1673 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1674 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1675 if (tmpIn != INVALID_HANDLE_VALUE
1676 && DuplicateHandle (GetCurrentProcess (), tmpIn,
1677 GetCurrentProcess (), &hIn,
1678 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1679 CloseHandle (tmpIn);
1681 if (hIn == INVALID_HANDLE_VALUE)
1684 _("windows32_openpipe: DuplicateHandle(In) failed (e=%lu)\n"), e);
1688 tmpErr = (HANDLE)_get_osfhandle (errfd);
1689 if (DuplicateHandle (GetCurrentProcess (), tmpErr,
1690 GetCurrentProcess (), &hErr,
1691 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1693 e = GetLastError ();
1694 if (e == ERROR_INVALID_HANDLE)
1696 tmpErr = CreateFile ("NUL", GENERIC_WRITE,
1697 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1698 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1699 if (tmpErr != INVALID_HANDLE_VALUE
1700 && DuplicateHandle (GetCurrentProcess (), tmpErr,
1701 GetCurrentProcess (), &hErr,
1702 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
1703 CloseHandle (tmpErr);
1705 if (hErr == INVALID_HANDLE_VALUE)
1708 _("windows32_openpipe: DuplicateHandle(Err) failed (e=%lu)\n"), e);
1713 if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
1715 ON (error, NILF, _("CreatePipe() failed (e=%lu)\n"), GetLastError());
1719 hProcess = process_init_fd (hIn, hChildOutWr, hErr);
1723 O (error, NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1727 if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
1729 /* register process for wait */
1730 process_register (hProcess);
1732 /* set the pid for returning to caller */
1733 *pid_p = (pid_t) hProcess;
1735 /* set up to read data from child */
1736 pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
1738 /* this will be closed almost right away */
1739 pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
1744 /* reap/cleanup the failed process */
1745 process_cleanup (hProcess);
1747 /* close handles which were duplicated, they weren't used */
1748 if (hIn != INVALID_HANDLE_VALUE)
1750 if (hErr != INVALID_HANDLE_VALUE)
1753 /* close pipe handles, they won't be used */
1754 CloseHandle (hChildOutRd);
1755 CloseHandle (hChildOutWr);
1765 msdos_openpipe (int* pipedes, int *pidp, char *text)
1768 /* MSDOS can't fork, but it has 'popen'. */
1769 struct variable *sh = lookup_variable ("SHELL", 5);
1771 extern int dos_command_running, dos_status;
1773 /* Make sure not to bother processing an empty line. */
1780 char buf[PATH_MAX + 7];
1781 /* This makes sure $SHELL value is used by $(shell), even
1782 though the target environment is not passed to it. */
1783 sprintf (buf, "SHELL=%s", sh->value);
1789 dos_command_running = 1;
1791 /* If dos_status becomes non-zero, it means the child process
1792 was interrupted by a signal, like SIGINT or SIGQUIT. See
1793 fatal_error_signal in commands.c. */
1794 fpipe = popen (text, "rt");
1795 dos_command_running = 0;
1796 if (!fpipe || dos_status)
1802 else if (errno == 0)
1806 shell_completed (127, 0);
1810 pipedes[0] = fileno (fpipe);
1811 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1819 Do shell spawning, with the naughty bits for different OSes.
1824 /* VMS can't do $(shell ...) */
1827 func_shell_base (char *o, char **argv, int trim_newlines)
1829 fprintf (stderr, "This platform does not support shell\n");
1834 #define func_shell 0
1839 func_shell_base (char *o, char **argv, int trim_newlines)
1841 struct childbase child = {0};
1842 char *batch_filename = NULL;
1847 char **command_argv = NULL;
1853 /* Reset just_print_flag. This is needed on Windows when batch files
1854 are used to run the commands, because we normally refrain from
1855 creating batch files under -n. */
1856 int j_p_f = just_print_flag;
1857 just_print_flag = 0;
1860 /* Construct the argument list. */
1861 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1863 if (command_argv == 0)
1866 just_print_flag = j_p_f;
1870 #endif /* !__MSDOS__ */
1872 /* Set up the output in case the shell writes something. */
1875 errfd = (output_context && output_context->err >= 0
1876 ? output_context->err : FD_STDERR);
1878 child.environment = target_environment (NULL, 0);
1880 #if defined(__MSDOS__)
1881 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1884 OS (error, reading_file, "pipe: %s", strerror (errno));
1889 #elif defined(WINDOWS32)
1890 windows32_openpipe (pipedes, errfd, &pid, command_argv, child.environment);
1891 /* Restore the value of just_print_flag. */
1892 just_print_flag = j_p_f;
1896 /* Open of the pipe failed, mark as failed execution. */
1897 shell_completed (127, 0);
1898 OS (error, reading_file, "pipe: %s", strerror (errno));
1904 if (pipe (pipedes) < 0)
1906 OS (error, reading_file, "pipe: %s", strerror (errno));
1911 /* Close handles that are unnecessary for the child process. */
1912 fd_noinherit (pipedes[1]);
1913 fd_noinherit (pipedes[0]);
1915 child.output.syncout = 1;
1916 child.output.out = pipedes[1];
1917 child.output.err = errfd;
1919 pid = child_execute_job (&child, 1, command_argv);
1923 shell_completed (127, 0);
1933 /* Record the PID for reap_children. */
1934 shell_function_pid = pid;
1936 shell_function_completed = 0;
1938 /* Close the write side of the pipe. We test for -1, since
1939 pipedes[1] is -1 on MS-Windows, and some versions of MS
1940 libraries barf when 'close' is called with -1. */
1941 if (pipedes[1] >= 0)
1945 /* Set up and read from the pipe. */
1948 buffer = xmalloc (maxlen + 1);
1950 /* Read from the pipe until it gets EOF. */
1951 for (i = 0; ; i += cc)
1956 buffer = xrealloc (buffer, maxlen + 1);
1959 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1965 /* Close the read side of the pipe. */
1969 int st = pclose (fpipe);
1970 shell_completed (st, 0);
1973 (void) close (pipedes[0]);
1976 /* Loop until child_handler or reap_children() sets
1977 shell_function_completed to the status of our child shell. */
1978 while (shell_function_completed == 0)
1979 reap_children (1, 0);
1983 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1985 remove (batch_filename);
1986 free (batch_filename);
1988 shell_function_pid = 0;
1990 /* Replace all newlines in the command's output with spaces, and put that
1991 in the variable output buffer. */
1992 fold_newlines (buffer, &i, trim_newlines);
1993 o = variable_buffer_output (o, buffer, i);
2001 /* Free the storage only the child needed. */
2002 free (command_argv[0]);
2003 free (command_argv);
2006 free_childbase (&child);
2013 /* Do the Amiga version of func_shell. */
2016 func_shell_base (char *o, char **argv, int trim_newlines)
2018 /* Amiga can't fork nor spawn, but I can start a program with
2019 redirection of my choice. However, this means that we
2020 don't have an opportunity to reopen stdout to trap it. Thus,
2021 we save our own stdout onto a new descriptor and dup a temp
2022 file's descriptor onto our stdout temporarily. After we
2023 spawn the shell program, we dup our own stdout back to the
2024 stdout descriptor. The buffer reading is the same as above,
2025 except that we're now reading from a file. */
2027 #include <dos/dos.h>
2028 #include <proto/dos.h>
2031 char tmp_output[FILENAME_MAX];
2032 size_t maxlen = 200, i;
2034 char * buffer, * ptr;
2037 char* batch_filename = NULL;
2039 /* Construct the argument list. */
2040 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2042 if (command_argv == 0)
2045 /* Note the mktemp() is a security hole, but this only runs on Amiga.
2046 Ideally we would use get_tmpfile(), but this uses a special Open(), not
2047 fopen(), and I'm not familiar enough with the code to mess with it. */
2048 strcpy (tmp_output, "t:MakeshXXXXXXXX");
2049 mktemp (tmp_output);
2050 child_stdout = Open (tmp_output, MODE_NEWFILE);
2052 for (aptr=command_argv; *aptr; aptr++)
2053 len += strlen (*aptr) + 1;
2055 buffer = xmalloc (len + 1);
2058 for (aptr=command_argv; *aptr; aptr++)
2060 strcpy (ptr, *aptr);
2061 ptr += strlen (ptr) + 1;
2068 Execute (buffer, NULL, child_stdout);
2071 Close (child_stdout);
2073 child_stdout = Open (tmp_output, MODE_OLDFILE);
2075 buffer = xmalloc (maxlen);
2082 buffer = xrealloc (buffer, maxlen + 1);
2085 cc = Read (child_stdout, &buffer[i], maxlen - i);
2090 Close (child_stdout);
2092 fold_newlines (buffer, &i, trim_newlines);
2093 o = variable_buffer_output (o, buffer, i);
2100 func_shell (char *o, char **argv, const char *funcname UNUSED)
2102 return func_shell_base (o, argv, 1);
2109 equality. Return is string-boolean, i.e., the empty string is false.
2112 func_eq (char *o, char **argv, char *funcname UNUSED)
2114 int result = ! strcmp (argv[0], argv[1]);
2115 o = variable_buffer_output (o, result ? "1" : "", result);
2121 string-boolean not operator.
2124 func_not (char *o, char **argv, char *funcname UNUSED)
2126 const char *s = argv[0];
2130 o = variable_buffer_output (o, result ? "1" : "", result);
2136 #ifdef HAVE_DOS_PATHS
2138 # define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || ISDIRSEP (n[0]))
2140 # define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
2144 # define IS_ABSOLUTE(n) (n[0] == '/')
2148 /* Return the absolute name of file NAME which does not contain any '.',
2149 '..' components nor any repeated path separators ('/'). */
2152 abspath (const char *name, char *apath)
2155 const char *start, *end, *apath_limit;
2156 unsigned long root_len = ROOT_LEN;
2158 if (name[0] == '\0')
2161 apath_limit = apath + GET_PATH_MAX;
2163 if (!IS_ABSOLUTE(name))
2165 /* It is unlikely we would make it until here but just to make sure. */
2166 if (!starting_directory)
2169 strcpy (apath, starting_directory);
2171 #ifdef HAVE_DOS_PATHS
2172 if (ISDIRSEP (name[0]))
2174 if (ISDIRSEP (name[1]))
2176 /* A UNC. Don't prepend a drive letter. */
2181 /* We have /foo, an absolute file name except for the drive
2182 letter. Assume the missing drive letter is the current
2183 drive, which we can get if we remove from starting_directory
2184 everything past the root directory. */
2185 apath[root_len] = '\0';
2189 dest = strchr (apath, '\0');
2193 #if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
2194 if (ISDIRSEP (name[0]))
2197 memcpy (apath, name, root_len);
2198 apath[root_len] = '\0';
2199 dest = apath + root_len;
2200 /* Get past the root, since we already copied it. */
2202 #ifdef HAVE_DOS_PATHS
2203 if (! ISDIRSEP (apath[root_len - 1]))
2205 /* Convert d:foo into d:./foo and increase root_len. */
2210 /* strncpy above copied one character too many. */
2214 apath[root_len - 1] = '/'; /* make sure it's a forward slash */
2218 for (start = end = name; *start != '\0'; start = end)
2222 /* Skip sequence of multiple path-separators. */
2223 while (ISDIRSEP (*start))
2226 /* Find end of path component. */
2227 for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
2234 else if (len == 1 && start[0] == '.')
2236 else if (len == 2 && start[0] == '.' && start[1] == '.')
2238 /* Back up to previous component, ignore if at root already. */
2239 if (dest > apath + root_len)
2240 for (--dest; ! ISDIRSEP (dest[-1]); --dest)
2245 if (! ISDIRSEP (dest[-1]))
2248 if (dest + len >= apath_limit)
2251 dest = mempcpy (dest, start, len);
2256 /* Unless it is root strip trailing separator. */
2257 if (dest > apath + root_len && ISDIRSEP (dest[-1]))
2267 func_realpath (char *o, char **argv, const char *funcname UNUSED)
2269 /* Expand the argument. */
2270 const char *p = argv[0];
2271 const char *path = 0;
2275 while ((path = find_next_token (&p, &len)) != 0)
2277 if (len < GET_PATH_MAX)
2284 strncpy (in, path, len);
2287 #ifdef HAVE_REALPATH
2288 ENULLLOOP (rp, realpath (in, out));
2290 /* AIX realpath() doesn't remove trailing slashes correctly. */
2293 char *ep = rp + strlen (rp) - 1;
2294 while (ep > rp && ep[0] == '/')
2299 rp = abspath (in, out);
2305 EINTRLOOP (r, stat (out, &st));
2308 o = variable_buffer_output (o, out, strlen (out));
2309 o = variable_buffer_output (o, " ", 1);
2316 /* Kill last space. */
2324 func_file (char *o, char **argv, const char *funcname UNUSED)
2331 const char *mode = "w";
2333 /* We are writing a file. */
2343 O (fatal, *expanding_var, _("file: missing filename"));
2345 ENULLLOOP (fp, fopen (fn, mode));
2347 OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
2349 /* We've changed the contents of a directory, possibly.
2350 Another option would be to look up the directory we changed and reset
2351 its counter to 0. */
2356 size_t l = strlen (argv[1]);
2357 int nl = l == 0 || argv[1][l-1] != '\n';
2359 if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
2360 OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
2363 OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
2365 else if (fn[0] == '<')
2373 O (fatal, *expanding_var, _("file: missing filename"));
2376 O (fatal, *expanding_var, _("file: too many arguments"));
2378 ENULLLOOP (fp, fopen (fn, "r"));
2381 if (errno == ENOENT)
2383 OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
2389 size_t l = fread (buf, 1, sizeof (buf), fp);
2392 o = variable_buffer_output (o, buf, l);
2397 OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
2402 OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
2404 /* Remove trailing newline. */
2405 if (n && o[-1] == '\n')
2406 o -= 1 + (n > 1 && o[-2] == '\r');
2409 OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
2415 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2417 /* Expand the argument. */
2418 const char *p = argv[0];
2419 const char *path = 0;
2423 while ((path = find_next_token (&p, &len)) != 0)
2425 if (len < GET_PATH_MAX)
2430 strncpy (in, path, len);
2433 if (abspath (in, out))
2435 o = variable_buffer_output (o, out, strlen (out));
2436 o = variable_buffer_output (o, " ", 1);
2442 /* Kill last space. */
2449 /* Lookup table for builtin functions.
2451 This doesn't have to be sorted; we use a straight lookup. We might gain
2452 some efficiency by moving most often used functions to the start of the
2455 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2456 comma-separated values are treated as arguments.
2458 EXPAND_ARGS means that all arguments should be expanded before invocation.
2459 Functions that do namespace tricks (foreach, let) don't automatically
2462 static char *func_call (char *o, char **argv, const char *funcname);
2464 #define FT_ENTRY(_name, _min, _max, _exp, _func) \
2465 { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0, 0 }
2467 static struct function_table_entry function_table_init[] =
2469 /* Name MIN MAX EXP? Function */
2470 FT_ENTRY ("abspath", 0, 1, 1, func_abspath),
2471 FT_ENTRY ("addprefix", 2, 2, 1, func_addsuffix_addprefix),
2472 FT_ENTRY ("addsuffix", 2, 2, 1, func_addsuffix_addprefix),
2473 FT_ENTRY ("basename", 0, 1, 1, func_basename_dir),
2474 FT_ENTRY ("dir", 0, 1, 1, func_basename_dir),
2475 FT_ENTRY ("notdir", 0, 1, 1, func_notdir_suffix),
2476 FT_ENTRY ("subst", 3, 3, 1, func_subst),
2477 FT_ENTRY ("suffix", 0, 1, 1, func_notdir_suffix),
2478 FT_ENTRY ("filter", 2, 2, 1, func_filter_filterout),
2479 FT_ENTRY ("filter-out", 2, 2, 1, func_filter_filterout),
2480 FT_ENTRY ("findstring", 2, 2, 1, func_findstring),
2481 FT_ENTRY ("firstword", 0, 1, 1, func_firstword),
2482 FT_ENTRY ("flavor", 0, 1, 1, func_flavor),
2483 FT_ENTRY ("join", 2, 2, 1, func_join),
2484 FT_ENTRY ("lastword", 0, 1, 1, func_lastword),
2485 FT_ENTRY ("patsubst", 3, 3, 1, func_patsubst),
2486 FT_ENTRY ("realpath", 0, 1, 1, func_realpath),
2487 FT_ENTRY ("shell", 0, 1, 1, func_shell),
2488 FT_ENTRY ("sort", 0, 1, 1, func_sort),
2489 FT_ENTRY ("strip", 0, 1, 1, func_strip),
2490 FT_ENTRY ("wildcard", 0, 1, 1, func_wildcard),
2491 FT_ENTRY ("word", 2, 2, 1, func_word),
2492 FT_ENTRY ("wordlist", 3, 3, 1, func_wordlist),
2493 FT_ENTRY ("words", 0, 1, 1, func_words),
2494 FT_ENTRY ("origin", 0, 1, 1, func_origin),
2495 FT_ENTRY ("foreach", 3, 3, 0, func_foreach),
2496 FT_ENTRY ("let", 3, 3, 0, func_let),
2497 FT_ENTRY ("call", 1, 0, 1, func_call),
2498 FT_ENTRY ("info", 0, 1, 1, func_error),
2499 FT_ENTRY ("error", 0, 1, 1, func_error),
2500 FT_ENTRY ("warning", 0, 1, 1, func_error),
2501 FT_ENTRY ("intcmp", 2, 5, 0, func_intcmp),
2502 FT_ENTRY ("if", 2, 3, 0, func_if),
2503 FT_ENTRY ("or", 1, 0, 0, func_or),
2504 FT_ENTRY ("and", 1, 0, 0, func_and),
2505 FT_ENTRY ("value", 0, 1, 1, func_value),
2506 FT_ENTRY ("eval", 0, 1, 1, func_eval),
2507 FT_ENTRY ("file", 1, 2, 1, func_file),
2509 FT_ENTRY ("eq", 2, 2, 1, func_eq),
2510 FT_ENTRY ("not", 0, 1, 1, func_not),
2514 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2517 /* These must come after the definition of function_table. */
2520 expand_builtin_function (char *o, unsigned int argc, char **argv,
2521 const struct function_table_entry *entry_p)
2525 if (argc < entry_p->minimum_args)
2526 fatal (*expanding_var, strlen (entry_p->name),
2527 _("insufficient number of arguments (%u) to function '%s'"),
2528 argc, entry_p->name);
2530 /* I suppose technically some function could do something with no arguments,
2531 but so far no internal ones do, so just test it for all functions here
2532 rather than in each one. We can change it later if necessary. */
2534 if (!argc && !entry_p->alloc_fn)
2537 if (!entry_p->fptr.func_ptr)
2538 OS (fatal, *expanding_var,
2539 _("unimplemented on this platform: function '%s'"), entry_p->name);
2541 if (entry_p->adds_command)
2544 if (!entry_p->alloc_fn)
2545 return entry_p->fptr.func_ptr (o, argv, entry_p->name);
2547 /* This function allocates memory and returns it to us.
2548 Write it to the variable buffer, then free it. */
2550 p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
2553 o = variable_buffer_output (o, p, strlen (p));
2560 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2561 opening ( or { and is not null-terminated. If a function invocation
2562 is found, expand it into the buffer at *OP, updating *OP, incrementing
2563 *STRINGP past the reference and returning nonzero. If not, return zero. */
2566 handle_function (char **op, const char **stringp)
2568 const struct function_table_entry *entry_p;
2569 char openparen = (*stringp)[0];
2570 char closeparen = openparen == '(' ? ')' : '}';
2575 char **argv, **argvp;
2580 entry_p = lookup_function (beg);
2585 /* We found a builtin function. Find the beginning of its arguments (skip
2586 whitespace after the name). */
2588 beg += entry_p->len;
2591 /* Find the end of the function invocation, counting nested use of
2592 whichever kind of parens we use. Since we're looking, count commas
2593 to get a rough estimate of how many arguments we might have. The
2594 count might be high, but it'll never be low. */
2596 for (nargs=1, end=beg; *end != '\0'; ++end)
2597 if (!STOP_SET (*end, MAP_VARSEP|MAP_COMMA))
2599 else if (*end == ',')
2601 else if (*end == openparen)
2603 else if (*end == closeparen && --count < 0)
2607 fatal (*expanding_var, strlen (entry_p->name),
2608 _("unterminated call to function '%s': missing '%c'"),
2609 entry_p->name, closeparen);
2613 /* Get some memory to store the arg pointers. */
2614 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2616 /* Chop the string into arguments, then a nul. As soon as we hit
2617 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2620 If we're expanding, store pointers to the expansion of each one. If
2621 not, make a duplicate of the string and point into that, nul-terminating
2624 if (entry_p->expand_args)
2627 for (p=beg, nargs=0; p <= end; ++argvp)
2633 if (nargs == entry_p->maximum_args
2634 || ((next = find_next_argument (openparen, closeparen, p, end)) == NULL))
2637 *argvp = expand_argument (p, next);
2643 size_t len = end - beg;
2646 abeg = xmalloc (len+1);
2647 aend = mempcpy (abeg, beg, len);
2650 for (p=abeg, nargs=0; p <= aend; ++argvp)
2656 if (nargs == entry_p->maximum_args
2657 || ((next = find_next_argument (openparen, closeparen, p, aend)) == NULL))
2667 /* Finally! Run the function... */
2668 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2671 if (entry_p->expand_args)
2672 for (argvp=argv; *argvp != 0; ++argvp)
2681 /* User-defined functions. Expand the first argument as either a builtin
2682 function or a make variable, in the context of the rest of the arguments
2683 assigned to $1, $2, ... $N. $0 is the name of the function. */
2686 func_call (char *o, char **argv, const char *funcname UNUSED)
2688 static unsigned int max_args = 0;
2694 const struct function_table_entry *entry_p;
2697 /* Clean up the name of the variable to be invoked. */
2698 fname = next_token (argv[0]);
2699 end_of_token (fname)[0] = '\0';
2701 /* Calling nothing is a no-op */
2705 /* Are we invoking a builtin function? */
2707 entry_p = lookup_function (fname);
2710 /* How many arguments do we have? */
2711 for (i=0; argv[i+1]; ++i)
2713 return expand_builtin_function (o, i, argv+1, entry_p);
2716 /* Not a builtin, so the first argument is the name of a variable to be
2717 expanded and interpreted as a function. Find it. */
2718 flen = strlen (fname);
2720 v = lookup_variable (fname, flen);
2723 warn_undefined (fname, flen);
2725 if (v == 0 || *v->value == '\0')
2728 body = alloca (flen + 4);
2731 memcpy (body + 2, fname, flen);
2733 body[flen+3] = '\0';
2735 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2737 push_new_variable_scope ();
2739 for (i=0; *argv; ++i, ++argv)
2741 char num[INTSTR_LENGTH];
2743 sprintf (num, "%u", i);
2744 define_variable (num, strlen (num), *argv, o_automatic, 0);
2747 /* If the number of arguments we have is < max_args, it means we're inside
2748 a recursive invocation of $(call ...). Fill in the remaining arguments
2749 in the new scope with the empty value, to hide them from this
2752 for (; i < max_args; ++i)
2754 char num[INTSTR_LENGTH];
2756 sprintf (num, "%u", i);
2757 define_variable (num, strlen (num), "", o_automatic, 0);
2760 /* Expand the body in the context of the arguments, adding the result to
2761 the variable buffer. */
2763 v->exp_count = EXP_COUNT_MAX;
2765 saved_args = max_args;
2767 o = variable_expand_string (o, body, flen+3);
2768 max_args = saved_args;
2772 pop_variable_scope ();
2774 return o + strlen (o);
2778 define_new_function (const floc *flocp, const char *name,
2779 unsigned int min, unsigned int max, unsigned int flags,
2782 const char *e = name;
2783 struct function_table_entry *ent;
2786 while (STOP_SET (*e, MAP_USERFUNC))
2791 O (fatal, flocp, _("Empty function name"));
2792 if (*name == '.' || *e != '\0')
2793 OS (fatal, flocp, _("Invalid function name: %s"), name);
2795 OS (fatal, flocp, _("Function name too long: %s"), name);
2798 _("Invalid minimum argument count (%u) for function %s"), min, name);
2799 if (max > 255 || (max && max < min))
2801 _("Invalid maximum argument count (%u) for function %s"), max, name);
2803 ent = xmalloc (sizeof (struct function_table_entry));
2805 ent->len = (unsigned char) len;
2806 ent->minimum_args = (unsigned char) min;
2807 ent->maximum_args = (unsigned char) max;
2808 ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
2810 /* We don't know what this function will do. */
2811 ent->adds_command = 1;
2812 ent->fptr.alloc_func_ptr = func;
2814 ent = hash_insert (&function_table, ent);
2819 hash_init_function_table (void)
2821 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2822 function_table_entry_hash_1, function_table_entry_hash_2,
2823 function_table_entry_hash_cmp);
2824 hash_load (&function_table, function_table_init,
2825 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));