Keep the command line on the heap to avoid stack overflow.
[make.git] / function.c
blob325d9304387a64c38aeb84ca547e9f46a2cc94aa
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988-2012 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
8 version.
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/>. */
17 #include "make.h"
18 #include "filedef.h"
19 #include "variable.h"
20 #include "dep.h"
21 #include "job.h"
22 #include "commands.h"
23 #include "debug.h"
25 #ifdef _AMIGA
26 #include "amiga.h"
27 #endif
30 struct function_table_entry
32 const char *name;
33 unsigned char len;
34 unsigned char minimum_args;
35 unsigned char maximum_args;
36 char expand_args;
37 char *(*func_ptr) (char *output, char **argv, const char *fname);
40 static unsigned long
41 function_table_entry_hash_1 (const void *keyv)
43 const struct function_table_entry *key = keyv;
44 return_STRING_N_HASH_1 (key->name, key->len);
47 static unsigned long
48 function_table_entry_hash_2 (const void *keyv)
50 const struct function_table_entry *key = keyv;
51 return_STRING_N_HASH_2 (key->name, key->len);
54 static int
55 function_table_entry_hash_cmp (const void *xv, const void *yv)
57 const struct function_table_entry *x = xv;
58 const struct function_table_entry *y = yv;
59 int result = x->len - y->len;
60 if (result)
61 return result;
62 return_STRING_N_COMPARE (x->name, y->name, x->len);
65 static struct hash_table function_table;
68 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
69 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
70 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
71 nonzero, substitutions are done only on matches which are complete
72 whitespace-delimited words. */
74 char *
75 subst_expand (char *o, const char *text, const char *subst, const char *replace,
76 unsigned int slen, unsigned int rlen, int by_word)
78 const char *t = text;
79 const char *p;
81 if (slen == 0 && !by_word)
83 /* The first occurrence of "" in any string is its end. */
84 o = variable_buffer_output (o, t, strlen (t));
85 if (rlen > 0)
86 o = variable_buffer_output (o, replace, rlen);
87 return o;
92 if (by_word && slen == 0)
93 /* When matching by words, the empty string should match
94 the end of each word, rather than the end of the whole text. */
95 p = end_of_token (next_token (t));
96 else
98 p = strstr (t, subst);
99 if (p == 0)
101 /* No more matches. Output everything left on the end. */
102 o = variable_buffer_output (o, t, strlen (t));
103 return o;
107 /* Output everything before this occurrence of the string to replace. */
108 if (p > t)
109 o = variable_buffer_output (o, t, p - t);
111 /* If we're substituting only by fully matched words,
112 or only at the ends of words, check that this case qualifies. */
113 if (by_word
114 && ((p > text && !isblank ((unsigned char)p[-1]))
115 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
116 /* Struck out. Output the rest of the string that is
117 no longer to be replaced. */
118 o = variable_buffer_output (o, subst, slen);
119 else if (rlen > 0)
120 /* Output the replacement string. */
121 o = variable_buffer_output (o, replace, rlen);
123 /* Advance T past the string to be replaced. */
124 t = p + slen;
125 } while (*t != '\0');
127 return o;
131 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
132 and replacing strings matching PATTERN with REPLACE.
133 If PATTERN_PERCENT is not nil, PATTERN has already been
134 run through find_percent, and PATTERN_PERCENT is the result.
135 If REPLACE_PERCENT is not nil, REPLACE has already been
136 run through find_percent, and REPLACE_PERCENT is the result.
137 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
138 character _AFTER_ the %, not to the % itself.
141 char *
142 patsubst_expand_pat (char *o, const char *text,
143 const char *pattern, const char *replace,
144 const char *pattern_percent, const char *replace_percent)
146 unsigned int pattern_prepercent_len, pattern_postpercent_len;
147 unsigned int replace_prepercent_len, replace_postpercent_len;
148 const char *t;
149 unsigned int len;
150 int doneany = 0;
152 /* Record the length of REPLACE before and after the % so we don't have to
153 compute these lengths more than once. */
154 if (replace_percent)
156 replace_prepercent_len = replace_percent - replace - 1;
157 replace_postpercent_len = strlen (replace_percent);
159 else
161 replace_prepercent_len = strlen (replace);
162 replace_postpercent_len = 0;
165 if (!pattern_percent)
166 /* With no % in the pattern, this is just a simple substitution. */
167 return subst_expand (o, text, pattern, replace,
168 strlen (pattern), strlen (replace), 1);
170 /* Record the length of PATTERN before and after the %
171 so we don't have to compute it more than once. */
172 pattern_prepercent_len = pattern_percent - pattern - 1;
173 pattern_postpercent_len = strlen (pattern_percent);
175 while ((t = find_next_token (&text, &len)) != 0)
177 int fail = 0;
179 /* Is it big enough to match? */
180 if (len < pattern_prepercent_len + pattern_postpercent_len)
181 fail = 1;
183 /* Does the prefix match? */
184 if (!fail && pattern_prepercent_len > 0
185 && (*t != *pattern
186 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
187 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
188 fail = 1;
190 /* Does the suffix match? */
191 if (!fail && pattern_postpercent_len > 0
192 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
193 || t[len - pattern_postpercent_len] != *pattern_percent
194 || !strneq (&t[len - pattern_postpercent_len],
195 pattern_percent, pattern_postpercent_len - 1)))
196 fail = 1;
198 if (fail)
199 /* It didn't match. Output the string. */
200 o = variable_buffer_output (o, t, len);
201 else
203 /* It matched. Output the replacement. */
205 /* Output the part of the replacement before the %. */
206 o = variable_buffer_output (o, replace, replace_prepercent_len);
208 if (replace_percent != 0)
210 /* Output the part of the matched string that
211 matched the % in the pattern. */
212 o = variable_buffer_output (o, t + pattern_prepercent_len,
213 len - (pattern_prepercent_len
214 + pattern_postpercent_len));
215 /* Output the part of the replacement after the %. */
216 o = variable_buffer_output (o, replace_percent,
217 replace_postpercent_len);
221 /* Output a space, but not if the replacement is "". */
222 if (fail || replace_prepercent_len > 0
223 || (replace_percent != 0 && len + replace_postpercent_len > 0))
225 o = variable_buffer_output (o, " ", 1);
226 doneany = 1;
229 if (doneany)
230 /* Kill the last space. */
231 --o;
233 return o;
236 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
237 and replacing strings matching PATTERN with REPLACE.
238 If PATTERN_PERCENT is not nil, PATTERN has already been
239 run through find_percent, and PATTERN_PERCENT is the result.
240 If REPLACE_PERCENT is not nil, REPLACE has already been
241 run through find_percent, and REPLACE_PERCENT is the result.
242 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
243 character _AFTER_ the %, not to the % itself.
246 char *
247 patsubst_expand (char *o, const char *text, char *pattern, char *replace)
249 const char *pattern_percent = find_percent (pattern);
250 const char *replace_percent = find_percent (replace);
252 /* If there's a percent in the pattern or replacement skip it. */
253 if (replace_percent)
254 ++replace_percent;
255 if (pattern_percent)
256 ++pattern_percent;
258 return patsubst_expand_pat (o, text, pattern, replace,
259 pattern_percent, replace_percent);
263 /* Look up a function by name. */
265 static const struct function_table_entry *
266 lookup_function (const char *s)
268 const char *e = s;
270 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
271 e++;
272 if (*e == '\0' || isblank ((unsigned char) *e))
274 struct function_table_entry function_table_entry_key;
275 function_table_entry_key.name = s;
276 function_table_entry_key.len = e - s;
278 return hash_find_item (&function_table, &function_table_entry_key);
280 return 0;
284 /* Return 1 if PATTERN matches STR, 0 if not. */
287 pattern_matches (const char *pattern, const char *percent, const char *str)
289 unsigned int sfxlen, strlength;
291 if (percent == 0)
293 unsigned int len = strlen (pattern) + 1;
294 char *new_chars = alloca (len);
295 memcpy (new_chars, pattern, len);
296 percent = find_percent (new_chars);
297 if (percent == 0)
298 return streq (new_chars, str);
299 pattern = new_chars;
302 sfxlen = strlen (percent + 1);
303 strlength = strlen (str);
305 if (strlength < (percent - pattern) + sfxlen
306 || !strneq (pattern, str, percent - pattern))
307 return 0;
309 return !strcmp (percent + 1, str + (strlength - sfxlen));
313 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
314 ENDPARENtheses), starting at PTR before END. Return a pointer to
315 next character.
317 If no next argument is found, return NULL.
320 static char *
321 find_next_argument (char startparen, char endparen,
322 const char *ptr, const char *end)
324 int count = 0;
326 for (; ptr < end; ++ptr)
327 if (*ptr == startparen)
328 ++count;
330 else if (*ptr == endparen)
332 --count;
333 if (count < 0)
334 return NULL;
337 else if (*ptr == ',' && !count)
338 return (char *)ptr;
340 /* We didn't find anything. */
341 return NULL;
345 /* Glob-expand LINE. The returned pointer is
346 only good until the next call to string_glob. */
348 static char *
349 string_glob (char *line)
351 static char *result = 0;
352 static unsigned int length;
353 struct nameseq *chain;
354 unsigned int idx;
356 chain = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
357 /* We do not want parse_file_seq to strip './'s.
358 That would break examples like:
359 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
360 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
362 if (result == 0)
364 length = 100;
365 result = xmalloc (100);
368 idx = 0;
369 while (chain != 0)
371 struct nameseq *next = chain->next;
372 unsigned int len = strlen (chain->name);
374 if (idx + len + 1 > length)
376 length += (len + 1) * 2;
377 result = xrealloc (result, length);
379 memcpy (&result[idx], chain->name, len);
380 idx += len;
381 result[idx++] = ' ';
383 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
384 free ((char *)chain->name);
385 free (chain);
386 chain = next;
389 /* Kill the last space and terminate the string. */
390 if (idx == 0)
391 result[0] = '\0';
392 else
393 result[idx - 1] = '\0';
395 return result;
399 Builtin functions
402 static char *
403 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
405 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
406 return o;
410 static char *
411 func_join (char *o, char **argv, const char *funcname UNUSED)
413 int doneany = 0;
415 /* Write each word of the first argument directly followed
416 by the corresponding word of the second argument.
417 If the two arguments have a different number of words,
418 the excess words are just output separated by blanks. */
419 const char *tp;
420 const char *pp;
421 const char *list1_iterator = argv[0];
422 const char *list2_iterator = argv[1];
425 unsigned int len1, len2;
427 tp = find_next_token (&list1_iterator, &len1);
428 if (tp != 0)
429 o = variable_buffer_output (o, tp, len1);
431 pp = find_next_token (&list2_iterator, &len2);
432 if (pp != 0)
433 o = variable_buffer_output (o, pp, len2);
435 if (tp != 0 || pp != 0)
437 o = variable_buffer_output (o, " ", 1);
438 doneany = 1;
441 while (tp != 0 || pp != 0);
442 if (doneany)
443 /* Kill the last blank. */
444 --o;
446 return o;
450 static char *
451 func_origin (char *o, char **argv, const char *funcname UNUSED)
453 /* Expand the argument. */
454 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
455 if (v == 0)
456 o = variable_buffer_output (o, "undefined", 9);
457 else
458 switch (v->origin)
460 default:
461 case o_invalid:
462 abort ();
463 break;
464 case o_default:
465 o = variable_buffer_output (o, "default", 7);
466 break;
467 case o_env:
468 o = variable_buffer_output (o, "environment", 11);
469 break;
470 case o_file:
471 o = variable_buffer_output (o, "file", 4);
472 break;
473 case o_env_override:
474 o = variable_buffer_output (o, "environment override", 20);
475 break;
476 case o_command:
477 o = variable_buffer_output (o, "command line", 12);
478 break;
479 case o_override:
480 o = variable_buffer_output (o, "override", 8);
481 break;
482 case o_automatic:
483 o = variable_buffer_output (o, "automatic", 9);
484 break;
487 return o;
490 static char *
491 func_flavor (char *o, char **argv, const char *funcname UNUSED)
493 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
495 if (v == 0)
496 o = variable_buffer_output (o, "undefined", 9);
497 else
498 if (v->recursive)
499 o = variable_buffer_output (o, "recursive", 9);
500 else
501 o = variable_buffer_output (o, "simple", 6);
503 return o;
506 #ifdef VMS
507 # define IS_PATHSEP(c) ((c) == ']')
508 #else
509 # ifdef HAVE_DOS_PATHS
510 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
511 # else
512 # define IS_PATHSEP(c) ((c) == '/')
513 # endif
514 #endif
517 static char *
518 func_notdir_suffix (char *o, char **argv, const char *funcname)
520 /* Expand the argument. */
521 const char *list_iterator = argv[0];
522 const char *p2;
523 int doneany =0;
524 unsigned int len=0;
526 int is_suffix = funcname[0] == 's';
527 int is_notdir = !is_suffix;
528 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
530 const char *p = p2 + len;
533 while (p >= p2 && (!is_suffix || *p != '.'))
535 if (IS_PATHSEP (*p))
536 break;
537 --p;
540 if (p >= p2)
542 if (is_notdir)
543 ++p;
544 else if (*p != '.')
545 continue;
546 o = variable_buffer_output (o, p, len - (p - p2));
548 #ifdef HAVE_DOS_PATHS
549 /* Handle the case of "d:foo/bar". */
550 else if (is_notdir && p2[0] && p2[1] == ':')
552 p = p2 + 2;
553 o = variable_buffer_output (o, p, len - (p - p2));
555 #endif
556 else if (is_notdir)
557 o = variable_buffer_output (o, p2, len);
559 if (is_notdir || p >= p2)
561 o = variable_buffer_output (o, " ", 1);
562 doneany = 1;
566 if (doneany)
567 /* Kill last space. */
568 --o;
570 return o;
574 static char *
575 func_basename_dir (char *o, char **argv, const char *funcname)
577 /* Expand the argument. */
578 const char *p3 = argv[0];
579 const char *p2;
580 int doneany = 0;
581 unsigned int len = 0;
583 int is_basename = funcname[0] == 'b';
584 int is_dir = !is_basename;
586 while ((p2 = find_next_token (&p3, &len)) != 0)
588 const char *p = p2 + len;
589 while (p >= p2 && (!is_basename || *p != '.'))
591 if (IS_PATHSEP (*p))
592 break;
593 --p;
596 if (p >= p2 && (is_dir))
597 o = variable_buffer_output (o, p2, ++p - p2);
598 else if (p >= p2 && (*p == '.'))
599 o = variable_buffer_output (o, p2, p - p2);
600 #ifdef HAVE_DOS_PATHS
601 /* Handle the "d:foobar" case */
602 else if (p2[0] && p2[1] == ':' && is_dir)
603 o = variable_buffer_output (o, p2, 2);
604 #endif
605 else if (is_dir)
606 #ifdef VMS
607 o = variable_buffer_output (o, "[]", 2);
608 #else
609 #ifndef _AMIGA
610 o = variable_buffer_output (o, "./", 2);
611 #else
612 ; /* Just a nop... */
613 #endif /* AMIGA */
614 #endif /* !VMS */
615 else
616 /* The entire name is the basename. */
617 o = variable_buffer_output (o, p2, len);
619 o = variable_buffer_output (o, " ", 1);
620 doneany = 1;
623 if (doneany)
624 /* Kill last space. */
625 --o;
627 return o;
630 static char *
631 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
633 int fixlen = strlen (argv[0]);
634 const char *list_iterator = argv[1];
635 int is_addprefix = funcname[3] == 'p';
636 int is_addsuffix = !is_addprefix;
638 int doneany = 0;
639 const char *p;
640 unsigned int len;
642 while ((p = find_next_token (&list_iterator, &len)) != 0)
644 if (is_addprefix)
645 o = variable_buffer_output (o, argv[0], fixlen);
646 o = variable_buffer_output (o, p, len);
647 if (is_addsuffix)
648 o = variable_buffer_output (o, argv[0], fixlen);
649 o = variable_buffer_output (o, " ", 1);
650 doneany = 1;
653 if (doneany)
654 /* Kill last space. */
655 --o;
657 return o;
660 static char *
661 func_subst (char *o, char **argv, const char *funcname UNUSED)
663 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
664 strlen (argv[1]), 0);
666 return o;
670 static char *
671 func_firstword (char *o, char **argv, const char *funcname UNUSED)
673 unsigned int i;
674 const char *words = argv[0]; /* Use a temp variable for find_next_token */
675 const char *p = find_next_token (&words, &i);
677 if (p != 0)
678 o = variable_buffer_output (o, p, i);
680 return o;
683 static char *
684 func_lastword (char *o, char **argv, const char *funcname UNUSED)
686 unsigned int i;
687 const char *words = argv[0]; /* Use a temp variable for find_next_token */
688 const char *p = NULL;
689 const char *t;
691 while ((t = find_next_token (&words, &i)))
692 p = t;
694 if (p != 0)
695 o = variable_buffer_output (o, p, i);
697 return o;
700 static char *
701 func_words (char *o, char **argv, const char *funcname UNUSED)
703 int i = 0;
704 const char *word_iterator = argv[0];
705 char buf[20];
707 while (find_next_token (&word_iterator, NULL) != 0)
708 ++i;
710 sprintf (buf, "%d", i);
711 o = variable_buffer_output (o, buf, strlen (buf));
713 return o;
716 /* Set begpp to point to the first non-whitespace character of the string,
717 * and endpp to point to the last non-whitespace character of the string.
718 * If the string is empty or contains nothing but whitespace, endpp will be
719 * begpp-1.
721 char *
722 strip_whitespace (const char **begpp, const char **endpp)
724 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
725 (*begpp) ++;
726 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
727 (*endpp) --;
728 return (char *)*begpp;
731 static void
732 check_numeric (const char *s, const char *msg)
734 const char *end = s + strlen (s) - 1;
735 const char *beg = s;
736 strip_whitespace (&s, &end);
738 for (; s <= end; ++s)
739 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
740 break;
742 if (s <= end || end - beg < 0)
743 fatal (*expanding_var, "%s: '%s'", msg, beg);
748 static char *
749 func_word (char *o, char **argv, const char *funcname UNUSED)
751 const char *end_p;
752 const char *p;
753 int i;
755 /* Check the first argument. */
756 check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
757 i = atoi (argv[0]);
759 if (i == 0)
760 fatal (*expanding_var,
761 _("first argument to 'word' function must be greater than 0"));
763 end_p = argv[1];
764 while ((p = find_next_token (&end_p, 0)) != 0)
765 if (--i == 0)
766 break;
768 if (i == 0)
769 o = variable_buffer_output (o, p, end_p - p);
771 return o;
774 static char *
775 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
777 int start, count;
779 /* Check the arguments. */
780 check_numeric (argv[0],
781 _("non-numeric first argument to 'wordlist' function"));
782 check_numeric (argv[1],
783 _("non-numeric second argument to 'wordlist' function"));
785 start = atoi (argv[0]);
786 if (start < 1)
787 fatal (*expanding_var,
788 "invalid first argument to 'wordlist' function: '%d'", start);
790 count = atoi (argv[1]) - start + 1;
792 if (count > 0)
794 const char *p;
795 const char *end_p = argv[2];
797 /* Find the beginning of the "start"th word. */
798 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
801 if (p)
803 /* Find the end of the "count"th word from start. */
804 while (--count && (find_next_token (&end_p, 0) != 0))
807 /* Return the stuff in the middle. */
808 o = variable_buffer_output (o, p, end_p - p);
812 return o;
815 static char *
816 func_findstring (char *o, char **argv, const char *funcname UNUSED)
818 /* Find the first occurrence of the first string in the second. */
819 if (strstr (argv[1], argv[0]) != 0)
820 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
822 return o;
825 static char *
826 func_foreach (char *o, char **argv, const char *funcname UNUSED)
828 /* expand only the first two. */
829 char *varname = expand_argument (argv[0], NULL);
830 char *list = expand_argument (argv[1], NULL);
831 const char *body = argv[2];
833 int doneany = 0;
834 const char *list_iterator = list;
835 const char *p;
836 unsigned int len;
837 struct variable *var;
839 push_new_variable_scope ();
840 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
842 /* loop through LIST, put the value in VAR and expand BODY */
843 while ((p = find_next_token (&list_iterator, &len)) != 0)
845 char *result = 0;
847 free (var->value);
848 var->value = xstrndup (p, len);
850 result = allocated_variable_expand (body);
852 o = variable_buffer_output (o, result, strlen (result));
853 o = variable_buffer_output (o, " ", 1);
854 doneany = 1;
855 free (result);
858 if (doneany)
859 /* Kill the last space. */
860 --o;
862 pop_variable_scope ();
863 free (varname);
864 free (list);
866 return o;
869 struct a_word
871 struct a_word *next;
872 struct a_word *chain;
873 char *str;
874 int length;
875 int matched;
878 static unsigned long
879 a_word_hash_1 (const void *key)
881 return_STRING_HASH_1 (((struct a_word const *) key)->str);
884 static unsigned long
885 a_word_hash_2 (const void *key)
887 return_STRING_HASH_2 (((struct a_word const *) key)->str);
890 static int
891 a_word_hash_cmp (const void *x, const void *y)
893 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
894 if (result)
895 return result;
896 return_STRING_COMPARE (((struct a_word const *) x)->str,
897 ((struct a_word const *) y)->str);
900 struct a_pattern
902 struct a_pattern *next;
903 char *str;
904 char *percent;
905 int length;
908 static char *
909 func_filter_filterout (char *o, char **argv, const char *funcname)
911 struct a_word *wordhead;
912 struct a_word **wordtail;
913 struct a_word *wp;
914 struct a_pattern *pathead;
915 struct a_pattern **pattail;
916 struct a_pattern *pp;
918 struct hash_table a_word_table;
919 int is_filter = funcname[CSTRLEN ("filter")] == '\0';
920 const char *pat_iterator = argv[0];
921 const char *word_iterator = argv[1];
922 int literals = 0;
923 int words = 0;
924 int hashing = 0;
925 char *p;
926 unsigned int len;
928 /* Chop ARGV[0] up into patterns to match against the words.
929 We don't need to preserve it because our caller frees all the
930 argument memory anyway. */
932 pattail = &pathead;
933 while ((p = find_next_token (&pat_iterator, &len)) != 0)
935 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
937 *pattail = pat;
938 pattail = &pat->next;
940 if (*pat_iterator != '\0')
941 ++pat_iterator;
943 pat->str = p;
944 p[len] = '\0';
945 pat->percent = find_percent (p);
946 if (pat->percent == 0)
947 literals++;
949 /* find_percent() might shorten the string so LEN is wrong. */
950 pat->length = strlen (pat->str);
952 *pattail = 0;
954 /* Chop ARGV[1] up into words to match against the patterns. */
956 wordtail = &wordhead;
957 while ((p = find_next_token (&word_iterator, &len)) != 0)
959 struct a_word *word = alloca (sizeof (struct a_word));
961 *wordtail = word;
962 wordtail = &word->next;
964 if (*word_iterator != '\0')
965 ++word_iterator;
967 p[len] = '\0';
968 word->str = p;
969 word->length = len;
970 word->matched = 0;
971 word->chain = 0;
972 words++;
974 *wordtail = 0;
976 /* Only use a hash table if arg list lengths justifies the cost. */
977 hashing = (literals >= 2 && (literals * words) >= 10);
978 if (hashing)
980 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
981 a_word_hash_cmp);
982 for (wp = wordhead; wp != 0; wp = wp->next)
984 struct a_word *owp = hash_insert (&a_word_table, wp);
985 if (owp)
986 wp->chain = owp;
990 if (words)
992 int doneany = 0;
994 /* Run each pattern through the words, killing words. */
995 for (pp = pathead; pp != 0; pp = pp->next)
997 if (pp->percent)
998 for (wp = wordhead; wp != 0; wp = wp->next)
999 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1000 else if (hashing)
1002 struct a_word a_word_key;
1003 a_word_key.str = pp->str;
1004 a_word_key.length = pp->length;
1005 wp = hash_find_item (&a_word_table, &a_word_key);
1006 while (wp)
1008 wp->matched |= 1;
1009 wp = wp->chain;
1012 else
1013 for (wp = wordhead; wp != 0; wp = wp->next)
1014 wp->matched |= (wp->length == pp->length
1015 && strneq (pp->str, wp->str, wp->length));
1018 /* Output the words that matched (or didn't, for filter-out). */
1019 for (wp = wordhead; wp != 0; wp = wp->next)
1020 if (is_filter ? wp->matched : !wp->matched)
1022 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1023 o = variable_buffer_output (o, " ", 1);
1024 doneany = 1;
1027 if (doneany)
1028 /* Kill the last space. */
1029 --o;
1032 if (hashing)
1033 hash_free (&a_word_table, 0);
1035 return o;
1039 static char *
1040 func_strip (char *o, char **argv, const char *funcname UNUSED)
1042 const char *p = argv[0];
1043 int doneany = 0;
1045 while (*p != '\0')
1047 int i=0;
1048 const char *word_start;
1050 while (isspace ((unsigned char)*p))
1051 ++p;
1052 word_start = p;
1053 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1055 if (!i)
1056 break;
1057 o = variable_buffer_output (o, word_start, i);
1058 o = variable_buffer_output (o, " ", 1);
1059 doneany = 1;
1062 if (doneany)
1063 /* Kill the last space. */
1064 --o;
1066 return o;
1070 Print a warning or fatal message.
1072 static char *
1073 func_error (char *o, char **argv, const char *funcname)
1075 char **argvp;
1076 char *msg, *p;
1077 int len;
1079 /* The arguments will be broken on commas. Rather than create yet
1080 another special case where function arguments aren't broken up,
1081 just create a format string that puts them back together. */
1082 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1083 len += strlen (*argvp) + 2;
1085 p = msg = alloca (len + 1);
1087 for (argvp=argv; argvp[1] != 0; ++argvp)
1089 strcpy (p, *argvp);
1090 p += strlen (*argvp);
1091 *(p++) = ',';
1092 *(p++) = ' ';
1094 strcpy (p, *argvp);
1096 switch (*funcname) {
1097 case 'e':
1098 fatal (reading_file, "%s", msg);
1100 case 'w':
1101 error (reading_file, "%s", msg);
1102 break;
1104 case 'i':
1105 printf ("%s\n", msg);
1106 fflush(stdout);
1107 break;
1109 default:
1110 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1113 /* The warning function expands to the empty string. */
1114 return o;
1119 chop argv[0] into words, and sort them.
1121 static char *
1122 func_sort (char *o, char **argv, const char *funcname UNUSED)
1124 const char *t;
1125 char **words;
1126 int wordi;
1127 char *p;
1128 unsigned int len;
1129 int i;
1131 /* Find the maximum number of words we'll have. */
1132 t = argv[0];
1133 wordi = 0;
1134 while ((p = find_next_token (&t, NULL)) != 0)
1136 ++t;
1137 ++wordi;
1140 words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
1142 /* Now assign pointers to each string in the array. */
1143 t = argv[0];
1144 wordi = 0;
1145 while ((p = find_next_token (&t, &len)) != 0)
1147 ++t;
1148 p[len] = '\0';
1149 words[wordi++] = p;
1152 if (wordi)
1154 /* Now sort the list of words. */
1155 qsort (words, wordi, sizeof (char *), alpha_compare);
1157 /* Now write the sorted list, uniquified. */
1158 for (i = 0; i < wordi; ++i)
1160 len = strlen (words[i]);
1161 if (i == wordi - 1 || strlen (words[i + 1]) != len
1162 || strcmp (words[i], words[i + 1]))
1164 o = variable_buffer_output (o, words[i], len);
1165 o = variable_buffer_output (o, " ", 1);
1169 /* Kill the last space. */
1170 --o;
1173 free (words);
1175 return o;
1179 $(if condition,true-part[,false-part])
1181 CONDITION is false iff it evaluates to an empty string. White
1182 space before and after condition are stripped before evaluation.
1184 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1185 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1186 you can use $(if ...) to create side-effects (with $(shell ...), for
1187 example).
1190 static char *
1191 func_if (char *o, char **argv, const char *funcname UNUSED)
1193 const char *begp = argv[0];
1194 const char *endp = begp + strlen (argv[0]) - 1;
1195 int result = 0;
1197 /* Find the result of the condition: if we have a value, and it's not
1198 empty, the condition is true. If we don't have a value, or it's the
1199 empty string, then it's false. */
1201 strip_whitespace (&begp, &endp);
1203 if (begp <= endp)
1205 char *expansion = expand_argument (begp, endp+1);
1207 result = strlen (expansion);
1208 free (expansion);
1211 /* If the result is true (1) we want to eval the first argument, and if
1212 it's false (0) we want to eval the second. If the argument doesn't
1213 exist we do nothing, otherwise expand it and add to the buffer. */
1215 argv += 1 + !result;
1217 if (*argv)
1219 char *expansion = expand_argument (*argv, NULL);
1221 o = variable_buffer_output (o, expansion, strlen (expansion));
1223 free (expansion);
1226 return o;
1230 $(or condition1[,condition2[,condition3[...]]])
1232 A CONDITION is false iff it evaluates to an empty string. White
1233 space before and after CONDITION are stripped before evaluation.
1235 CONDITION1 is evaluated. If it's true, then this is the result of
1236 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1237 the conditions are true, the expansion is the empty string.
1239 Once a CONDITION is true no further conditions are evaluated
1240 (short-circuiting).
1243 static char *
1244 func_or (char *o, char **argv, const char *funcname UNUSED)
1246 for ( ; *argv ; ++argv)
1248 const char *begp = *argv;
1249 const char *endp = begp + strlen (*argv) - 1;
1250 char *expansion;
1251 int result = 0;
1253 /* Find the result of the condition: if it's false keep going. */
1255 strip_whitespace (&begp, &endp);
1257 if (begp > endp)
1258 continue;
1260 expansion = expand_argument (begp, endp+1);
1261 result = strlen (expansion);
1263 /* If the result is false keep going. */
1264 if (!result)
1266 free (expansion);
1267 continue;
1270 /* It's true! Keep this result and return. */
1271 o = variable_buffer_output (o, expansion, result);
1272 free (expansion);
1273 break;
1276 return o;
1280 $(and condition1[,condition2[,condition3[...]]])
1282 A CONDITION is false iff it evaluates to an empty string. White
1283 space before and after CONDITION are stripped before evaluation.
1285 CONDITION1 is evaluated. If it's false, then this is the result of
1286 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1287 the conditions are true, the expansion is the result of the last condition.
1289 Once a CONDITION is false no further conditions are evaluated
1290 (short-circuiting).
1293 static char *
1294 func_and (char *o, char **argv, const char *funcname UNUSED)
1296 char *expansion;
1297 int result;
1299 while (1)
1301 const char *begp = *argv;
1302 const char *endp = begp + strlen (*argv) - 1;
1304 /* An empty condition is always false. */
1305 strip_whitespace (&begp, &endp);
1306 if (begp > endp)
1307 return o;
1309 expansion = expand_argument (begp, endp+1);
1310 result = strlen (expansion);
1312 /* If the result is false, stop here: we're done. */
1313 if (!result)
1314 break;
1316 /* Otherwise the result is true. If this is the last one, keep this
1317 result and quit. Otherwise go on to the next one! */
1319 if (*(++argv))
1320 free (expansion);
1321 else
1323 o = variable_buffer_output (o, expansion, result);
1324 break;
1328 free (expansion);
1330 return o;
1333 static char *
1334 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1336 #ifdef _AMIGA
1337 o = wildcard_expansion (argv[0], o);
1338 #else
1339 char *p = string_glob (argv[0]);
1340 o = variable_buffer_output (o, p, strlen (p));
1341 #endif
1342 return o;
1346 $(eval <makefile string>)
1348 Always resolves to the empty string.
1350 Treat the arguments as a segment of makefile, and parse them.
1353 static char *
1354 func_eval (char *o, char **argv, const char *funcname UNUSED)
1356 char *buf;
1357 unsigned int len;
1359 /* Eval the buffer. Pop the current variable buffer setting so that the
1360 eval'd code can use its own without conflicting. */
1362 install_variable_buffer (&buf, &len);
1364 eval_buffer (argv[0]);
1366 restore_variable_buffer (buf, len);
1368 return o;
1372 static char *
1373 func_value (char *o, char **argv, const char *funcname UNUSED)
1375 /* Look up the variable. */
1376 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1378 /* Copy its value into the output buffer without expanding it. */
1379 if (v)
1380 o = variable_buffer_output (o, v->value, strlen(v->value));
1382 return o;
1386 \r is replaced on UNIX as well. Is this desirable?
1388 static void
1389 fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
1391 char *dst = buffer;
1392 char *src = buffer;
1393 char *last_nonnl = buffer - 1;
1394 src[*length] = 0;
1395 for (; *src != '\0'; ++src)
1397 if (src[0] == '\r' && src[1] == '\n')
1398 continue;
1399 if (*src == '\n')
1401 *dst++ = ' ';
1403 else
1405 last_nonnl = dst;
1406 *dst++ = *src;
1410 if (!trim_newlines && (last_nonnl < (dst - 2)))
1411 last_nonnl = dst - 2;
1413 *(++last_nonnl) = '\0';
1414 *length = last_nonnl - buffer;
1419 int shell_function_pid = 0, shell_function_completed;
1422 #ifdef WINDOWS32
1423 /*untested*/
1425 #include <windows.h>
1426 #include <io.h>
1427 #include "sub_proc.h"
1430 void
1431 windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
1433 SECURITY_ATTRIBUTES saAttr;
1434 HANDLE hIn = INVALID_HANDLE_VALUE;
1435 HANDLE hErr = INVALID_HANDLE_VALUE;
1436 HANDLE hChildOutRd;
1437 HANDLE hChildOutWr;
1438 HANDLE hProcess, tmpIn, tmpErr;
1439 DWORD e;
1441 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1442 saAttr.bInheritHandle = TRUE;
1443 saAttr.lpSecurityDescriptor = NULL;
1445 /* Standard handles returned by GetStdHandle can be NULL or
1446 INVALID_HANDLE_VALUE if the parent process closed them. If that
1447 happens, we open the null device and pass its handle to
1448 process_begin below as the corresponding handle to inherit. */
1449 tmpIn = GetStdHandle(STD_INPUT_HANDLE);
1450 if (DuplicateHandle (GetCurrentProcess(),
1451 tmpIn,
1452 GetCurrentProcess(),
1453 &hIn,
1455 TRUE,
1456 DUPLICATE_SAME_ACCESS) == FALSE) {
1457 if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
1458 tmpIn = CreateFile("NUL", GENERIC_READ,
1459 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1460 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1461 if (tmpIn != INVALID_HANDLE_VALUE
1462 && DuplicateHandle(GetCurrentProcess(),
1463 tmpIn,
1464 GetCurrentProcess(),
1465 &hIn,
1467 TRUE,
1468 DUPLICATE_SAME_ACCESS) == FALSE)
1469 CloseHandle(tmpIn);
1471 if (hIn == INVALID_HANDLE_VALUE)
1472 fatal (NILF, _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
1474 tmpErr = GetStdHandle(STD_ERROR_HANDLE);
1475 if (DuplicateHandle(GetCurrentProcess(),
1476 tmpErr,
1477 GetCurrentProcess(),
1478 &hErr,
1480 TRUE,
1481 DUPLICATE_SAME_ACCESS) == FALSE) {
1482 if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
1483 tmpErr = CreateFile("NUL", GENERIC_WRITE,
1484 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1485 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1486 if (tmpErr != INVALID_HANDLE_VALUE
1487 && DuplicateHandle(GetCurrentProcess(),
1488 tmpErr,
1489 GetCurrentProcess(),
1490 &hErr,
1492 TRUE,
1493 DUPLICATE_SAME_ACCESS) == FALSE)
1494 CloseHandle(tmpErr);
1496 if (hErr == INVALID_HANDLE_VALUE)
1497 fatal (NILF, _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
1500 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1501 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1503 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1505 if (!hProcess)
1506 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1508 /* make sure that CreateProcess() has Path it needs */
1509 sync_Path_environment();
1510 /* 'sync_Path_environment' may realloc 'environ', so take note of
1511 the new value. */
1512 envp = environ;
1514 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1515 /* register process for wait */
1516 process_register(hProcess);
1518 /* set the pid for returning to caller */
1519 *pid_p = (pid_t) hProcess;
1521 /* set up to read data from child */
1522 pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
1524 /* this will be closed almost right away */
1525 pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
1526 } else {
1527 /* reap/cleanup the failed process */
1528 process_cleanup(hProcess);
1530 /* close handles which were duplicated, they weren't used */
1531 if (hIn != INVALID_HANDLE_VALUE)
1532 CloseHandle(hIn);
1533 if (hErr != INVALID_HANDLE_VALUE)
1534 CloseHandle(hErr);
1536 /* close pipe handles, they won't be used */
1537 CloseHandle(hChildOutRd);
1538 CloseHandle(hChildOutWr);
1540 /* set status for return */
1541 pipedes[0] = pipedes[1] = -1;
1542 *pid_p = (pid_t)-1;
1545 #endif
1548 #ifdef __MSDOS__
1549 FILE *
1550 msdos_openpipe (int* pipedes, int *pidp, char *text)
1552 FILE *fpipe=0;
1553 /* MSDOS can't fork, but it has 'popen'. */
1554 struct variable *sh = lookup_variable ("SHELL", 5);
1555 int e;
1556 extern int dos_command_running, dos_status;
1558 /* Make sure not to bother processing an empty line. */
1559 while (isblank ((unsigned char)*text))
1560 ++text;
1561 if (*text == '\0')
1562 return 0;
1564 if (sh)
1566 char buf[PATH_MAX + 7];
1567 /* This makes sure $SHELL value is used by $(shell), even
1568 though the target environment is not passed to it. */
1569 sprintf (buf, "SHELL=%s", sh->value);
1570 putenv (buf);
1573 e = errno;
1574 errno = 0;
1575 dos_command_running = 1;
1576 dos_status = 0;
1577 /* If dos_status becomes non-zero, it means the child process
1578 was interrupted by a signal, like SIGINT or SIGQUIT. See
1579 fatal_error_signal in commands.c. */
1580 fpipe = popen (text, "rt");
1581 dos_command_running = 0;
1582 if (!fpipe || dos_status)
1584 pipedes[0] = -1;
1585 *pidp = -1;
1586 if (dos_status)
1587 errno = EINTR;
1588 else if (errno == 0)
1589 errno = ENOMEM;
1590 shell_function_completed = -1;
1592 else
1594 pipedes[0] = fileno (fpipe);
1595 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1596 errno = e;
1597 shell_function_completed = 1;
1599 return fpipe;
1601 #endif
1604 Do shell spawning, with the naughty bits for different OSes.
1607 #ifdef VMS
1609 /* VMS can't do $(shell ...) */
1611 char *
1612 func_shell_base (char *o, char **argv, int trim_newlines)
1614 fprintf (stderr, "This platform does not support shell\n");
1615 die (EXIT_FAILURE);
1618 #define func_shell 0
1620 #else
1621 #ifndef _AMIGA
1622 char *
1623 func_shell_base (char *o, char **argv, int trim_newlines)
1625 char *batch_filename = NULL;
1627 #ifdef __MSDOS__
1628 FILE *fpipe;
1629 #endif
1630 char **command_argv;
1631 const char *error_prefix;
1632 char **envp;
1633 int pipedes[2];
1634 pid_t pid;
1636 #ifndef __MSDOS__
1637 #ifdef WINDOWS32
1638 /* Reset just_print_flag. This is needed on Windows when batch files
1639 are used to run the commands, because we normally refrain from
1640 creating batch files under -n. */
1641 int j_p_f = just_print_flag;
1643 just_print_flag = 0;
1644 #endif
1645 /* Construct the argument list. */
1646 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1647 &batch_filename);
1648 if (command_argv == 0)
1650 #ifdef WINDOWS32
1651 just_print_flag = j_p_f;
1652 #endif
1653 return o;
1655 #endif
1657 /* Using a target environment for 'shell' loses in cases like:
1658 export var = $(shell echo foobie)
1659 because target_environment hits a loop trying to expand $(var)
1660 to put it in the environment. This is even more confusing when
1661 var was not explicitly exported, but just appeared in the
1662 calling environment.
1664 See Savannah bug #10593.
1666 envp = target_environment (NILF);
1669 envp = environ;
1671 /* For error messages. */
1672 if (reading_file && reading_file->filenm)
1674 char *p = alloca (strlen (reading_file->filenm)+11+4);
1675 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1676 error_prefix = p;
1678 else
1679 error_prefix = "";
1681 #if defined(__MSDOS__)
1682 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1683 if (pipedes[0] < 0)
1685 perror_with_name (error_prefix, "pipe");
1686 return o;
1688 #elif defined(WINDOWS32)
1689 windows32_openpipe (pipedes, &pid, command_argv, envp);
1690 /* Restore the value of just_print_flag. */
1691 just_print_flag = j_p_f;
1693 if (pipedes[0] < 0)
1695 /* Open of the pipe failed, mark as failed execution. */
1696 shell_function_completed = -1;
1697 return o;
1699 else
1700 #else
1701 if (pipe (pipedes) < 0)
1703 perror_with_name (error_prefix, "pipe");
1704 return o;
1707 # ifdef __EMX__
1708 /* close some handles that are unnecessary for the child process */
1709 CLOSE_ON_EXEC(pipedes[1]);
1710 CLOSE_ON_EXEC(pipedes[0]);
1711 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1712 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1713 if (pid < 0)
1714 perror_with_name (error_prefix, "spawn");
1715 # else /* ! __EMX__ */
1716 pid = fork ();
1717 if (pid < 0)
1718 perror_with_name (error_prefix, "fork");
1719 else if (pid == 0)
1720 child_execute_job (0, pipedes[1], command_argv, envp);
1721 else
1722 # endif
1723 #endif
1725 /* We are the parent. */
1726 char *buffer;
1727 unsigned int maxlen, i;
1728 int cc;
1730 /* Record the PID for reap_children. */
1731 shell_function_pid = pid;
1732 #ifndef __MSDOS__
1733 shell_function_completed = 0;
1735 /* Free the storage only the child needed. */
1736 free (command_argv[0]);
1737 free (command_argv);
1739 /* Close the write side of the pipe. We test for -1, since
1740 pipedes[1] is -1 on MS-Windows, and some versions of MS
1741 libraries barf when 'close' is called with -1. */
1742 if (pipedes[1] >= 0)
1743 close (pipedes[1]);
1744 #endif
1746 /* Set up and read from the pipe. */
1748 maxlen = 200;
1749 buffer = xmalloc (maxlen + 1);
1751 /* Read from the pipe until it gets EOF. */
1752 for (i = 0; ; i += cc)
1754 if (i == maxlen)
1756 maxlen += 512;
1757 buffer = xrealloc (buffer, maxlen + 1);
1760 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1761 if (cc <= 0)
1762 break;
1764 buffer[i] = '\0';
1766 /* Close the read side of the pipe. */
1767 #ifdef __MSDOS__
1768 if (fpipe)
1769 (void) pclose (fpipe);
1770 #else
1771 (void) close (pipedes[0]);
1772 #endif
1774 /* Loop until child_handler or reap_children() sets
1775 shell_function_completed to the status of our child shell. */
1776 while (shell_function_completed == 0)
1777 reap_children (1, 0);
1779 if (batch_filename) {
1780 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1781 batch_filename));
1782 remove (batch_filename);
1783 free (batch_filename);
1785 shell_function_pid = 0;
1787 /* The child_handler function will set shell_function_completed
1788 to 1 when the child dies normally, or to -1 if it
1789 dies with status 127, which is most likely an exec fail. */
1791 if (shell_function_completed == -1)
1793 /* This likely means that the execvp failed, so we should just
1794 write the error message in the pipe from the child. */
1795 fputs (buffer, stderr);
1796 fflush (stderr);
1798 else
1800 /* The child finished normally. Replace all newlines in its output
1801 with spaces, and put that in the variable output buffer. */
1802 fold_newlines (buffer, &i, trim_newlines);
1803 o = variable_buffer_output (o, buffer, i);
1806 free (buffer);
1809 return o;
1812 #else /* _AMIGA */
1814 /* Do the Amiga version of func_shell. */
1816 char *
1817 func_shell_base (char *o, char **argv, int trim_newlines)
1819 /* Amiga can't fork nor spawn, but I can start a program with
1820 redirection of my choice. However, this means that we
1821 don't have an opportunity to reopen stdout to trap it. Thus,
1822 we save our own stdout onto a new descriptor and dup a temp
1823 file's descriptor onto our stdout temporarily. After we
1824 spawn the shell program, we dup our own stdout back to the
1825 stdout descriptor. The buffer reading is the same as above,
1826 except that we're now reading from a file. */
1828 #include <dos/dos.h>
1829 #include <proto/dos.h>
1831 BPTR child_stdout;
1832 char tmp_output[FILENAME_MAX];
1833 unsigned int maxlen = 200, i;
1834 int cc;
1835 char * buffer, * ptr;
1836 char ** aptr;
1837 int len = 0;
1838 char* batch_filename = NULL;
1840 /* Construct the argument list. */
1841 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1842 &batch_filename);
1843 if (command_argv == 0)
1844 return o;
1846 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1847 Ideally we would use main.c:open_tmpfile(), but this uses a special
1848 Open(), not fopen(), and I'm not familiar enough with the code to mess
1849 with it. */
1850 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1851 mktemp (tmp_output);
1852 child_stdout = Open (tmp_output, MODE_NEWFILE);
1854 for (aptr=command_argv; *aptr; aptr++)
1855 len += strlen (*aptr) + 1;
1857 buffer = xmalloc (len + 1);
1858 ptr = buffer;
1860 for (aptr=command_argv; *aptr; aptr++)
1862 strcpy (ptr, *aptr);
1863 ptr += strlen (ptr) + 1;
1864 *ptr ++ = ' ';
1865 *ptr = 0;
1868 ptr[-1] = '\n';
1870 Execute (buffer, NULL, child_stdout);
1871 free (buffer);
1873 Close (child_stdout);
1875 child_stdout = Open (tmp_output, MODE_OLDFILE);
1877 buffer = xmalloc (maxlen);
1878 i = 0;
1881 if (i == maxlen)
1883 maxlen += 512;
1884 buffer = xrealloc (buffer, maxlen + 1);
1887 cc = Read (child_stdout, &buffer[i], maxlen - i);
1888 if (cc > 0)
1889 i += cc;
1890 } while (cc > 0);
1892 Close (child_stdout);
1894 fold_newlines (buffer, &i, trim_newlines);
1895 o = variable_buffer_output (o, buffer, i);
1896 free (buffer);
1897 return o;
1899 #endif /* _AMIGA */
1901 char *
1902 func_shell (char *o, char **argv, const char *funcname UNUSED)
1904 return func_shell_base (o, argv, 1);
1906 #endif /* !VMS */
1908 #ifdef EXPERIMENTAL
1911 equality. Return is string-boolean, ie, the empty string is false.
1913 static char *
1914 func_eq (char *o, char **argv, char *funcname UNUSED)
1916 int result = ! strcmp (argv[0], argv[1]);
1917 o = variable_buffer_output (o, result ? "1" : "", result);
1918 return o;
1923 string-boolean not operator.
1925 static char *
1926 func_not (char *o, char **argv, char *funcname UNUSED)
1928 const char *s = argv[0];
1929 int result = 0;
1930 while (isspace ((unsigned char)*s))
1931 s++;
1932 result = ! (*s);
1933 o = variable_buffer_output (o, result ? "1" : "", result);
1934 return o;
1936 #endif
1939 #ifdef HAVE_DOS_PATHS
1940 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1941 #define ROOT_LEN 3
1942 #else
1943 #define IS_ABSOLUTE(n) (n[0] == '/')
1944 #define ROOT_LEN 1
1945 #endif
1947 /* Return the absolute name of file NAME which does not contain any '.',
1948 '..' components nor any repeated path separators ('/'). */
1950 static char *
1951 abspath (const char *name, char *apath)
1953 char *dest;
1954 const char *start, *end, *apath_limit;
1955 unsigned long root_len = ROOT_LEN;
1957 if (name[0] == '\0' || apath == NULL)
1958 return NULL;
1960 apath_limit = apath + GET_PATH_MAX;
1962 if (!IS_ABSOLUTE(name))
1964 /* It is unlikely we would make it until here but just to make sure. */
1965 if (!starting_directory)
1966 return NULL;
1968 strcpy (apath, starting_directory);
1970 #ifdef HAVE_DOS_PATHS
1971 if (IS_PATHSEP(name[0]))
1973 if (IS_PATHSEP(name[1]))
1975 /* A UNC. Don't prepend a drive letter. */
1976 apath[0] = name[0];
1977 apath[1] = name[1];
1978 root_len = 2;
1980 /* We have /foo, an absolute file name except for the drive
1981 letter. Assume the missing drive letter is the current
1982 drive, which we can get if we remove from starting_directory
1983 everything past the root directory. */
1984 apath[root_len] = '\0';
1986 #endif
1988 dest = strchr (apath, '\0');
1990 else
1992 strncpy (apath, name, root_len);
1993 apath[root_len] = '\0';
1994 dest = apath + root_len;
1995 /* Get past the root, since we already copied it. */
1996 name += root_len;
1997 #ifdef HAVE_DOS_PATHS
1998 if (!IS_PATHSEP(apath[2]))
2000 /* Convert d:foo into d:./foo and increase root_len. */
2001 apath[2] = '.';
2002 apath[3] = '/';
2003 dest++;
2004 root_len++;
2005 /* strncpy above copied one character too many. */
2006 name--;
2008 else
2009 apath[2] = '/'; /* make sure it's a forward slash */
2010 #endif
2013 for (start = end = name; *start != '\0'; start = end)
2015 unsigned long len;
2017 /* Skip sequence of multiple path-separators. */
2018 while (IS_PATHSEP(*start))
2019 ++start;
2021 /* Find end of path component. */
2022 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
2025 len = end - start;
2027 if (len == 0)
2028 break;
2029 else if (len == 1 && start[0] == '.')
2030 /* nothing */;
2031 else if (len == 2 && start[0] == '.' && start[1] == '.')
2033 /* Back up to previous component, ignore if at root already. */
2034 if (dest > apath + root_len)
2035 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
2037 else
2039 if (!IS_PATHSEP(dest[-1]))
2040 *dest++ = '/';
2042 if (dest + len >= apath_limit)
2043 return NULL;
2045 dest = memcpy (dest, start, len);
2046 dest += len;
2047 *dest = '\0';
2051 /* Unless it is root strip trailing separator. */
2052 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
2053 --dest;
2055 *dest = '\0';
2057 return apath;
2061 static char *
2062 func_realpath (char *o, char **argv, const char *funcname UNUSED)
2064 /* Expand the argument. */
2065 const char *p = argv[0];
2066 const char *path = 0;
2067 int doneany = 0;
2068 unsigned int len = 0;
2069 struct stat st;
2070 PATH_VAR (in);
2071 PATH_VAR (out);
2073 while ((path = find_next_token (&p, &len)) != 0)
2075 if (len < GET_PATH_MAX)
2077 strncpy (in, path, len);
2078 in[len] = '\0';
2080 if (
2081 #ifdef HAVE_REALPATH
2082 realpath (in, out)
2083 #else
2084 abspath (in, out)
2085 #endif
2086 && stat (out, &st) == 0)
2088 o = variable_buffer_output (o, out, strlen (out));
2089 o = variable_buffer_output (o, " ", 1);
2090 doneany = 1;
2095 /* Kill last space. */
2096 if (doneany)
2097 --o;
2099 return o;
2102 static char *
2103 func_file (char *o, char **argv, const char *funcname UNUSED)
2105 char *fn = argv[0];
2107 if (fn[0] == '>')
2109 FILE *fp;
2110 const char *mode = "w";
2112 /* We are writing a file. */
2113 ++fn;
2114 if (fn[0] == '>')
2116 mode = "a";
2117 ++fn;
2119 fn = next_token (fn);
2121 fp = fopen (fn, mode);
2122 if (fp == NULL)
2123 fatal (reading_file, _("open: %s: %s"), fn, strerror (errno));
2124 else
2126 int l = strlen (argv[1]);
2127 int nl = (l == 0 || argv[1][l-1] != '\n');
2129 if (fputs (argv[1], fp) == EOF || (nl && fputc('\n', fp) == EOF))
2130 fatal (reading_file, _("write: %s: %s"), fn, strerror (errno));
2132 fclose (fp);
2135 else
2136 fatal (reading_file, _("Invalid file operation: %s"), fn);
2138 return o;
2141 static char *
2142 func_abspath (char *o, char **argv, const char *funcname UNUSED)
2144 /* Expand the argument. */
2145 const char *p = argv[0];
2146 const char *path = 0;
2147 int doneany = 0;
2148 unsigned int len = 0;
2149 PATH_VAR (in);
2150 PATH_VAR (out);
2152 while ((path = find_next_token (&p, &len)) != 0)
2154 if (len < GET_PATH_MAX)
2156 strncpy (in, path, len);
2157 in[len] = '\0';
2159 if (abspath (in, out))
2161 o = variable_buffer_output (o, out, strlen (out));
2162 o = variable_buffer_output (o, " ", 1);
2163 doneany = 1;
2168 /* Kill last space. */
2169 if (doneany)
2170 --o;
2172 return o;
2175 /* Lookup table for builtin functions.
2177 This doesn't have to be sorted; we use a straight lookup. We might gain
2178 some efficiency by moving most often used functions to the start of the
2179 table.
2181 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2182 comma-separated values are treated as arguments.
2184 EXPAND_ARGS means that all arguments should be expanded before invocation.
2185 Functions that do namespace tricks (foreach) don't automatically expand. */
2187 static char *func_call (char *o, char **argv, const char *funcname);
2190 static struct function_table_entry function_table_init[] =
2192 /* Name/size */ /* MIN MAX EXP? Function */
2193 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2194 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2195 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2196 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2197 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2198 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2199 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2200 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2201 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2202 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2203 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2204 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2205 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2206 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2207 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2208 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2209 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2210 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2211 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2212 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2213 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2214 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2215 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2216 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2217 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2218 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2219 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2220 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2221 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2222 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2223 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2224 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2225 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2226 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2227 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2228 { STRING_SIZE_TUPLE("file"), 1, 2, 1, func_file},
2229 #ifdef EXPERIMENTAL
2230 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2231 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2232 #endif
2235 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2238 /* These must come after the definition of function_table. */
2240 static char *
2241 expand_builtin_function (char *o, int argc, char **argv,
2242 const struct function_table_entry *entry_p)
2244 if (argc < (int)entry_p->minimum_args)
2245 fatal (*expanding_var,
2246 _("insufficient number of arguments (%d) to function '%s'"),
2247 argc, entry_p->name);
2249 /* I suppose technically some function could do something with no
2250 arguments, but so far none do, so just test it for all functions here
2251 rather than in each one. We can change it later if necessary. */
2253 if (!argc)
2254 return o;
2256 if (!entry_p->func_ptr)
2257 fatal (*expanding_var,
2258 _("unimplemented on this platform: function '%s'"), entry_p->name);
2260 return entry_p->func_ptr (o, argv, entry_p->name);
2263 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2264 opening ( or { and is not null-terminated. If a function invocation
2265 is found, expand it into the buffer at *OP, updating *OP, incrementing
2266 *STRINGP past the reference and returning nonzero. If not, return zero. */
2269 handle_function (char **op, const char **stringp)
2271 const struct function_table_entry *entry_p;
2272 char openparen = (*stringp)[0];
2273 char closeparen = openparen == '(' ? ')' : '}';
2274 const char *beg;
2275 const char *end;
2276 int count = 0;
2277 char *abeg = NULL;
2278 char **argv, **argvp;
2279 int nargs;
2281 beg = *stringp + 1;
2283 entry_p = lookup_function (beg);
2285 if (!entry_p)
2286 return 0;
2288 /* We found a builtin function. Find the beginning of its arguments (skip
2289 whitespace after the name). */
2291 beg = next_token (beg + entry_p->len);
2293 /* Find the end of the function invocation, counting nested use of
2294 whichever kind of parens we use. Since we're looking, count commas
2295 to get a rough estimate of how many arguments we might have. The
2296 count might be high, but it'll never be low. */
2298 for (nargs=1, end=beg; *end != '\0'; ++end)
2299 if (*end == ',')
2300 ++nargs;
2301 else if (*end == openparen)
2302 ++count;
2303 else if (*end == closeparen && --count < 0)
2304 break;
2306 if (count >= 0)
2307 fatal (*expanding_var,
2308 _("unterminated call to function '%s': missing '%c'"),
2309 entry_p->name, closeparen);
2311 *stringp = end;
2313 /* Get some memory to store the arg pointers. */
2314 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2316 /* Chop the string into arguments, then a nul. As soon as we hit
2317 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2318 last argument.
2320 If we're expanding, store pointers to the expansion of each one. If
2321 not, make a duplicate of the string and point into that, nul-terminating
2322 each argument. */
2324 if (entry_p->expand_args)
2326 const char *p;
2327 for (p=beg, nargs=0; p <= end; ++argvp)
2329 const char *next;
2331 ++nargs;
2333 if (nargs == entry_p->maximum_args
2334 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2335 next = end;
2337 *argvp = expand_argument (p, next);
2338 p = next + 1;
2341 else
2343 int len = end - beg;
2344 char *p, *aend;
2346 abeg = xmalloc (len+1);
2347 memcpy (abeg, beg, len);
2348 abeg[len] = '\0';
2349 aend = abeg + len;
2351 for (p=abeg, nargs=0; p <= aend; ++argvp)
2353 char *next;
2355 ++nargs;
2357 if (nargs == entry_p->maximum_args
2358 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2359 next = aend;
2361 *argvp = p;
2362 *next = '\0';
2363 p = next + 1;
2366 *argvp = NULL;
2368 /* Finally! Run the function... */
2369 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2371 /* Free memory. */
2372 if (entry_p->expand_args)
2373 for (argvp=argv; *argvp != 0; ++argvp)
2374 free (*argvp);
2375 else if (abeg)
2376 free (abeg);
2378 return 1;
2382 /* User-defined functions. Expand the first argument as either a builtin
2383 function or a make variable, in the context of the rest of the arguments
2384 assigned to $1, $2, ... $N. $0 is the name of the function. */
2386 static char *
2387 func_call (char *o, char **argv, const char *funcname UNUSED)
2389 static int max_args = 0;
2390 char *fname;
2391 char *cp;
2392 char *body;
2393 int flen;
2394 int i;
2395 int saved_args;
2396 const struct function_table_entry *entry_p;
2397 struct variable *v;
2399 /* There is no way to define a variable with a space in the name, so strip
2400 leading and trailing whitespace as a favor to the user. */
2401 fname = argv[0];
2402 while (*fname != '\0' && isspace ((unsigned char)*fname))
2403 ++fname;
2405 cp = fname + strlen (fname) - 1;
2406 while (cp > fname && isspace ((unsigned char)*cp))
2407 --cp;
2408 cp[1] = '\0';
2410 /* Calling nothing is a no-op */
2411 if (*fname == '\0')
2412 return o;
2414 /* Are we invoking a builtin function? */
2416 entry_p = lookup_function (fname);
2417 if (entry_p)
2419 /* How many arguments do we have? */
2420 for (i=0; argv[i+1]; ++i)
2422 return expand_builtin_function (o, i, argv+1, entry_p);
2425 /* Not a builtin, so the first argument is the name of a variable to be
2426 expanded and interpreted as a function. Find it. */
2427 flen = strlen (fname);
2429 v = lookup_variable (fname, flen);
2431 if (v == 0)
2432 warn_undefined (fname, flen);
2434 if (v == 0 || *v->value == '\0')
2435 return o;
2437 body = alloca (flen + 4);
2438 body[0] = '$';
2439 body[1] = '(';
2440 memcpy (body + 2, fname, flen);
2441 body[flen+2] = ')';
2442 body[flen+3] = '\0';
2444 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2446 push_new_variable_scope ();
2448 for (i=0; *argv; ++i, ++argv)
2450 char num[11];
2452 sprintf (num, "%d", i);
2453 define_variable (num, strlen (num), *argv, o_automatic, 0);
2456 /* If the number of arguments we have is < max_args, it means we're inside
2457 a recursive invocation of $(call ...). Fill in the remaining arguments
2458 in the new scope with the empty value, to hide them from this
2459 invocation. */
2461 for (; i < max_args; ++i)
2463 char num[11];
2465 sprintf (num, "%d", i);
2466 define_variable (num, strlen (num), "", o_automatic, 0);
2469 /* Expand the body in the context of the arguments, adding the result to
2470 the variable buffer. */
2472 v->exp_count = EXP_COUNT_MAX;
2474 saved_args = max_args;
2475 max_args = i;
2476 o = variable_expand_string (o, body, flen+3);
2477 max_args = saved_args;
2479 v->exp_count = 0;
2481 pop_variable_scope ();
2483 return o + strlen (o);
2486 void
2487 define_new_function(const struct floc *flocp,
2488 const char *name, int min, int max, int expand,
2489 char *(*func)(char *, char **, const char *))
2491 size_t len = strlen (name);
2492 struct function_table_entry *ent = xmalloc (sizeof (struct function_table_entry));
2494 if (len > 255)
2495 fatal (flocp, _("Function name too long: %s\n"), name);
2496 if (min < 0 || min > 255)
2497 fatal (flocp, _("Invalid minimum argument count (%d) for function %s\n"),
2498 min, name);
2499 if (max < 0 || max > 255 || max < min)
2500 fatal (flocp, _("Invalid maximum argument count (%d) for function %s\n"),
2501 max, name);
2503 ent->name = name;
2504 ent->len = len;
2505 ent->minimum_args = min;
2506 ent->maximum_args = max;
2507 ent->expand_args = expand ? 1 : 0;
2508 ent->func_ptr = func;
2510 hash_insert (&function_table, ent);
2513 void
2514 hash_init_function_table (void)
2516 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2517 function_table_entry_hash_1, function_table_entry_hash_2,
2518 function_table_entry_hash_cmp);
2519 hash_load (&function_table, function_table_init,
2520 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));