Fixes for VMS from Hartmut Becker.
[make.git] / function.c
blob983df74f8ccf3d5930c54bec93619f82b711d1b2
1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1991-1997, 1999, 2002 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
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include "make.h"
21 #include "filedef.h"
22 #include "variable.h"
23 #include "dep.h"
24 #include "job.h"
25 #include "commands.h"
26 #include "debug.h"
28 #ifdef _AMIGA
29 #include "amiga.h"
30 #endif
33 struct function_table_entry
35 const char *name;
36 unsigned char len;
37 unsigned char minimum_args;
38 unsigned char maximum_args;
39 char expand_args;
40 char *(*func_ptr) PARAMS ((char *output, char **argv, const char *fname));
43 static unsigned long
44 function_table_entry_hash_1 (const void *keyv)
46 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
47 return_STRING_N_HASH_1 (key->name, key->len);
50 static unsigned long
51 function_table_entry_hash_2 (const void *keyv)
53 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
54 return_STRING_N_HASH_2 (key->name, key->len);
57 static int
58 function_table_entry_hash_cmp (const void *xv, const void *yv)
60 struct function_table_entry const *x = (struct function_table_entry const *) xv;
61 struct function_table_entry const *y = (struct function_table_entry const *) yv;
62 int result = x->len - y->len;
63 if (result)
64 return result;
65 return_STRING_N_COMPARE (x->name, y->name, x->len);
68 static struct hash_table function_table;
71 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
72 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
73 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
74 nonzero, substitutions are done only on matches which are complete
75 whitespace-delimited words. */
77 char *
78 subst_expand (char *o, char *text, char *subst, char *replace,
79 unsigned int slen, unsigned int rlen, int by_word)
81 char *t = text;
82 char *p;
84 if (slen == 0 && !by_word)
86 /* The first occurrence of "" in any string is its end. */
87 o = variable_buffer_output (o, t, strlen (t));
88 if (rlen > 0)
89 o = variable_buffer_output (o, replace, rlen);
90 return o;
95 if (by_word && slen == 0)
96 /* When matching by words, the empty string should match
97 the end of each word, rather than the end of the whole text. */
98 p = end_of_token (next_token (t));
99 else
101 p = strstr (t, subst);
102 if (p == 0)
104 /* No more matches. Output everything left on the end. */
105 o = variable_buffer_output (o, t, strlen (t));
106 return o;
110 /* Output everything before this occurrence of the string to replace. */
111 if (p > t)
112 o = variable_buffer_output (o, t, p - t);
114 /* If we're substituting only by fully matched words,
115 or only at the ends of words, check that this case qualifies. */
116 if (by_word
117 && ((p > text && !isblank ((unsigned char)p[-1]))
118 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
119 /* Struck out. Output the rest of the string that is
120 no longer to be replaced. */
121 o = variable_buffer_output (o, subst, slen);
122 else if (rlen > 0)
123 /* Output the replacement string. */
124 o = variable_buffer_output (o, replace, rlen);
126 /* Advance T past the string to be replaced. */
128 char *nt = p + slen;
129 t = nt;
131 } while (*t != '\0');
133 return o;
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.
147 char *
148 patsubst_expand (char *o, char *text, char *pattern, char *replace,
149 char *pattern_percent, char *replace_percent)
151 unsigned int pattern_prepercent_len, pattern_postpercent_len;
152 unsigned int replace_prepercent_len, replace_postpercent_len;
153 char *t;
154 unsigned int len;
155 int doneany = 0;
157 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
158 will be collapsed before we call subst_expand if PATTERN has no %. */
159 if (!replace_percent)
161 replace_percent = find_percent (replace);
162 if (replace_percent)
163 ++replace_percent;
166 /* Record the length of REPLACE before and after the % so we don't have to
167 compute these lengths more than once. */
168 if (replace_percent)
170 replace_prepercent_len = replace_percent - replace - 1;
171 replace_postpercent_len = strlen (replace_percent);
173 else
175 replace_prepercent_len = strlen (replace);
176 replace_postpercent_len = 0;
179 if (!pattern_percent)
181 pattern_percent = find_percent (pattern);
182 if (pattern_percent)
183 ++pattern_percent;
185 if (!pattern_percent)
186 /* With no % in the pattern, this is just a simple substitution. */
187 return subst_expand (o, text, pattern, replace,
188 strlen (pattern), strlen (replace), 1);
190 /* Record the length of PATTERN before and after the %
191 so we don't have to compute it more than once. */
192 pattern_prepercent_len = pattern_percent - pattern - 1;
193 pattern_postpercent_len = strlen (pattern_percent);
195 while ((t = find_next_token (&text, &len)) != 0)
197 int fail = 0;
199 /* Is it big enough to match? */
200 if (len < pattern_prepercent_len + pattern_postpercent_len)
201 fail = 1;
203 /* Does the prefix match? */
204 if (!fail && pattern_prepercent_len > 0
205 && (*t != *pattern
206 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
207 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
208 fail = 1;
210 /* Does the suffix match? */
211 if (!fail && pattern_postpercent_len > 0
212 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
213 || t[len - pattern_postpercent_len] != *pattern_percent
214 || !strneq (&t[len - pattern_postpercent_len],
215 pattern_percent, pattern_postpercent_len - 1)))
216 fail = 1;
218 if (fail)
219 /* It didn't match. Output the string. */
220 o = variable_buffer_output (o, t, len);
221 else
223 /* It matched. Output the replacement. */
225 /* Output the part of the replacement before the %. */
226 o = variable_buffer_output (o, replace, replace_prepercent_len);
228 if (replace_percent != 0)
230 /* Output the part of the matched string that
231 matched the % in the pattern. */
232 o = variable_buffer_output (o, t + pattern_prepercent_len,
233 len - (pattern_prepercent_len
234 + pattern_postpercent_len));
235 /* Output the part of the replacement after the %. */
236 o = variable_buffer_output (o, replace_percent,
237 replace_postpercent_len);
241 /* Output a space, but not if the replacement is "". */
242 if (fail || replace_prepercent_len > 0
243 || (replace_percent != 0 && len + replace_postpercent_len > 0))
245 o = variable_buffer_output (o, " ", 1);
246 doneany = 1;
249 if (doneany)
250 /* Kill the last space. */
251 --o;
253 return o;
257 /* Look up a function by name. */
259 static const struct function_table_entry *
260 lookup_function (const char *s)
262 const char *e = s;
264 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
265 e++;
266 if (*e == '\0' || isblank ((unsigned char) *e))
268 struct function_table_entry function_table_entry_key;
269 function_table_entry_key.name = s;
270 function_table_entry_key.len = e - s;
272 return hash_find_item (&function_table, &function_table_entry_key);
274 return 0;
278 /* Return 1 if PATTERN matches STR, 0 if not. */
281 pattern_matches (char *pattern, char *percent, char *str)
283 unsigned int sfxlen, strlength;
285 if (percent == 0)
287 unsigned int len = strlen (pattern) + 1;
288 char *new_chars = (char *) alloca (len);
289 bcopy (pattern, new_chars, len);
290 pattern = new_chars;
291 percent = find_percent (pattern);
292 if (percent == 0)
293 return streq (pattern, str);
296 sfxlen = strlen (percent + 1);
297 strlength = strlen (str);
299 if (strlength < (percent - pattern) + sfxlen
300 || !strneq (pattern, str, percent - pattern))
301 return 0;
303 return !strcmp (percent + 1, str + (strlength - sfxlen));
307 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
308 ENDPARENtheses), starting at PTR before END. Return a pointer to
309 next character.
311 If no next argument is found, return NULL.
314 static char *
315 find_next_argument (char startparen, char endparen,
316 const char *ptr, const char *end)
318 int count = 0;
320 for (; ptr < end; ++ptr)
321 if (*ptr == startparen)
322 ++count;
324 else if (*ptr == endparen)
326 --count;
327 if (count < 0)
328 return NULL;
331 else if (*ptr == ',' && !count)
332 return (char *)ptr;
334 /* We didn't find anything. */
335 return NULL;
339 /* Glob-expand LINE. The returned pointer is
340 only good until the next call to string_glob. */
342 static char *
343 string_glob (char *line)
345 static char *result = 0;
346 static unsigned int length;
347 register struct nameseq *chain;
348 register unsigned int idx;
350 chain = multi_glob (parse_file_seq
351 (&line, '\0', sizeof (struct nameseq),
352 /* We do not want parse_file_seq to strip `./'s.
353 That would break examples like:
354 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
356 sizeof (struct nameseq));
358 if (result == 0)
360 length = 100;
361 result = (char *) xmalloc (100);
364 idx = 0;
365 while (chain != 0)
367 register char *name = chain->name;
368 unsigned int len = strlen (name);
370 struct nameseq *next = chain->next;
371 free ((char *) chain);
372 chain = next;
374 /* multi_glob will pass names without globbing metacharacters
375 through as is, but we want only files that actually exist. */
376 if (file_exists_p (name))
378 if (idx + len + 1 > length)
380 length += (len + 1) * 2;
381 result = (char *) xrealloc (result, length);
383 bcopy (name, &result[idx], len);
384 idx += len;
385 result[idx++] = ' ';
388 free (name);
391 /* Kill the last space and terminate the string. */
392 if (idx == 0)
393 result[0] = '\0';
394 else
395 result[idx - 1] = '\0';
397 return result;
401 Builtin functions
404 static char *
405 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
407 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
408 return o;
412 static char *
413 func_join (char *o, char **argv, const char *funcname UNUSED)
415 int doneany = 0;
417 /* Write each word of the first argument directly followed
418 by the corresponding word of the second argument.
419 If the two arguments have a different number of words,
420 the excess words are just output separated by blanks. */
421 register char *tp;
422 register char *pp;
423 char *list1_iterator = argv[0];
424 char *list2_iterator = argv[1];
427 unsigned int len1, len2;
429 tp = find_next_token (&list1_iterator, &len1);
430 if (tp != 0)
431 o = variable_buffer_output (o, tp, len1);
433 pp = find_next_token (&list2_iterator, &len2);
434 if (pp != 0)
435 o = variable_buffer_output (o, pp, len2);
437 if (tp != 0 || pp != 0)
439 o = variable_buffer_output (o, " ", 1);
440 doneany = 1;
443 while (tp != 0 || pp != 0);
444 if (doneany)
445 /* Kill the last blank. */
446 --o;
448 return o;
452 static char *
453 func_origin (char *o, char **argv, const char *funcname UNUSED)
455 /* Expand the argument. */
456 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
457 if (v == 0)
458 o = variable_buffer_output (o, "undefined", 9);
459 else
460 switch (v->origin)
462 default:
463 case o_invalid:
464 abort ();
465 break;
466 case o_default:
467 o = variable_buffer_output (o, "default", 7);
468 break;
469 case o_env:
470 o = variable_buffer_output (o, "environment", 11);
471 break;
472 case o_file:
473 o = variable_buffer_output (o, "file", 4);
474 break;
475 case o_env_override:
476 o = variable_buffer_output (o, "environment override", 20);
477 break;
478 case o_command:
479 o = variable_buffer_output (o, "command line", 12);
480 break;
481 case o_override:
482 o = variable_buffer_output (o, "override", 8);
483 break;
484 case o_automatic:
485 o = variable_buffer_output (o, "automatic", 9);
486 break;
489 return o;
492 #ifdef VMS
493 # define IS_PATHSEP(c) ((c) == ']')
494 #else
495 # ifdef HAVE_DOS_PATHS
496 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
497 # else
498 # define IS_PATHSEP(c) ((c) == '/')
499 # endif
500 #endif
503 static char *
504 func_notdir_suffix (char *o, char **argv, const char *funcname)
506 /* Expand the argument. */
507 char *list_iterator = argv[0];
508 char *p2 =0;
509 int doneany =0;
510 unsigned int len=0;
512 int is_suffix = streq (funcname, "suffix");
513 int is_notdir = !is_suffix;
514 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
516 char *p = p2 + len;
519 while (p >= p2 && (!is_suffix || *p != '.'))
521 if (IS_PATHSEP (*p))
522 break;
523 --p;
526 if (p >= p2)
528 if (is_notdir)
529 ++p;
530 else if (*p != '.')
531 continue;
532 o = variable_buffer_output (o, p, len - (p - p2));
534 #ifdef HAVE_DOS_PATHS
535 /* Handle the case of "d:foo/bar". */
536 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
538 p = p2 + 2;
539 o = variable_buffer_output (o, p, len - (p - p2));
541 #endif
542 else if (is_notdir)
543 o = variable_buffer_output (o, p2, len);
545 if (is_notdir || p >= p2)
547 o = variable_buffer_output (o, " ", 1);
548 doneany = 1;
551 if (doneany)
552 /* Kill last space. */
553 --o;
556 return o;
561 static char *
562 func_basename_dir (char *o, char **argv, const char *funcname)
564 /* Expand the argument. */
565 char *p3 = argv[0];
566 char *p2=0;
567 int doneany=0;
568 unsigned int len=0;
569 char *p=0;
570 int is_basename= streq (funcname, "basename");
571 int is_dir= !is_basename;
573 while ((p2 = find_next_token (&p3, &len)) != 0)
575 p = p2 + len;
576 while (p >= p2 && (!is_basename || *p != '.'))
578 if (IS_PATHSEP (*p))
579 break;
580 --p;
583 if (p >= p2 && (is_dir))
584 o = variable_buffer_output (o, p2, ++p - p2);
585 else if (p >= p2 && (*p == '.'))
586 o = variable_buffer_output (o, p2, p - p2);
587 #ifdef HAVE_DOS_PATHS
588 /* Handle the "d:foobar" case */
589 else if (p2[0] && p2[1] == ':' && is_dir)
590 o = variable_buffer_output (o, p2, 2);
591 #endif
592 else if (is_dir)
593 #ifdef VMS
594 o = variable_buffer_output (o, "[]", 2);
595 #else
596 #ifndef _AMIGA
597 o = variable_buffer_output (o, "./", 2);
598 #else
599 ; /* Just a nop... */
600 #endif /* AMIGA */
601 #endif /* !VMS */
602 else
603 /* The entire name is the basename. */
604 o = variable_buffer_output (o, p2, len);
606 o = variable_buffer_output (o, " ", 1);
607 doneany = 1;
609 if (doneany)
610 /* Kill last space. */
611 --o;
614 return o;
617 static char *
618 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
620 int fixlen = strlen (argv[0]);
621 char *list_iterator = argv[1];
622 int is_addprefix = streq (funcname, "addprefix");
623 int is_addsuffix = !is_addprefix;
625 int doneany = 0;
626 char *p;
627 unsigned int len;
629 while ((p = find_next_token (&list_iterator, &len)) != 0)
631 if (is_addprefix)
632 o = variable_buffer_output (o, argv[0], fixlen);
633 o = variable_buffer_output (o, p, len);
634 if (is_addsuffix)
635 o = variable_buffer_output (o, argv[0], fixlen);
636 o = variable_buffer_output (o, " ", 1);
637 doneany = 1;
640 if (doneany)
641 /* Kill last space. */
642 --o;
644 return o;
647 static char *
648 func_subst (char *o, char **argv, const char *funcname UNUSED)
650 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
651 strlen (argv[1]), 0);
653 return o;
657 static char *
658 func_firstword (char *o, char **argv, const char *funcname UNUSED)
660 unsigned int i;
661 char *words = argv[0]; /* Use a temp variable for find_next_token */
662 char *p = find_next_token (&words, &i);
664 if (p != 0)
665 o = variable_buffer_output (o, p, i);
667 return o;
670 static char *
671 func_lastword (char *o, char **argv, const char *funcname UNUSED)
673 unsigned int i;
674 char *words = argv[0]; /* Use a temp variable for find_next_token */
675 char *p = 0;
676 char *t;
678 while ((t = find_next_token (&words, &i)))
679 p = t;
681 if (p != 0)
682 o = variable_buffer_output (o, p, i);
684 return o;
687 static char *
688 func_words (char *o, char **argv, const char *funcname UNUSED)
690 int i = 0;
691 char *word_iterator = argv[0];
692 char buf[20];
694 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
695 ++i;
697 sprintf (buf, "%d", i);
698 o = variable_buffer_output (o, buf, strlen (buf));
701 return o;
704 /* Set begpp to point to the first non-whitespace character of the string,
705 * and endpp to point to the last non-whitespace character of the string.
706 * If the string is empty or contains nothing but whitespace, endpp will be
707 * begpp-1.
709 char *
710 strip_whitespace (const char **begpp, const char **endpp)
712 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
713 (*begpp) ++;
714 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
715 (*endpp) --;
716 return (char *)*begpp;
719 static void
720 check_numeric (const char *s, const char *message)
722 const char *end = s + strlen (s) - 1;
723 const char *beg = s;
724 strip_whitespace (&s, &end);
726 for (; s <= end; ++s)
727 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
728 break;
730 if (s <= end || end - beg < 0)
731 fatal (reading_file, "%s: '%s'", message, beg);
736 static char *
737 func_word (char *o, char **argv, const char *funcname UNUSED)
739 char *end_p=0;
740 int i=0;
741 char *p=0;
743 /* Check the first argument. */
744 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
745 i = atoi (argv[0]);
747 if (i == 0)
748 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
751 end_p = argv[1];
752 while ((p = find_next_token (&end_p, 0)) != 0)
753 if (--i == 0)
754 break;
756 if (i == 0)
757 o = variable_buffer_output (o, p, end_p - p);
759 return o;
762 static char *
763 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
765 int start, count;
767 /* Check the arguments. */
768 check_numeric (argv[0],
769 _("non-numeric first argument to `wordlist' function"));
770 check_numeric (argv[1],
771 _("non-numeric second argument to `wordlist' function"));
773 start = atoi (argv[0]);
774 if (start < 1)
775 fatal (reading_file,
776 "invalid first argument to `wordlist' function: `%d'", start);
778 count = atoi (argv[1]) - start + 1;
780 if (count > 0)
782 char *p;
783 char *end_p = argv[2];
785 /* Find the beginning of the "start"th word. */
786 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
789 if (p)
791 /* Find the end of the "count"th word from start. */
792 while (--count && (find_next_token (&end_p, 0) != 0))
795 /* Return the stuff in the middle. */
796 o = variable_buffer_output (o, p, end_p - p);
800 return o;
803 static char*
804 func_findstring (char *o, char **argv, const char *funcname UNUSED)
806 /* Find the first occurrence of the first string in the second. */
807 if (strstr (argv[1], argv[0]) != 0)
808 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
810 return o;
813 static char *
814 func_foreach (char *o, char **argv, const char *funcname UNUSED)
816 /* expand only the first two. */
817 char *varname = expand_argument (argv[0], NULL);
818 char *list = expand_argument (argv[1], NULL);
819 char *body = argv[2];
821 int doneany = 0;
822 char *list_iterator = list;
823 char *p;
824 unsigned int len;
825 register struct variable *var;
827 push_new_variable_scope ();
828 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
830 /* loop through LIST, put the value in VAR and expand BODY */
831 while ((p = find_next_token (&list_iterator, &len)) != 0)
833 char *result = 0;
836 char save = p[len];
838 p[len] = '\0';
839 free (var->value);
840 var->value = (char *) xstrdup ((char*) p);
841 p[len] = save;
844 result = allocated_variable_expand (body);
846 o = variable_buffer_output (o, result, strlen (result));
847 o = variable_buffer_output (o, " ", 1);
848 doneany = 1;
849 free (result);
852 if (doneany)
853 /* Kill the last space. */
854 --o;
856 pop_variable_scope ();
857 free (varname);
858 free (list);
860 return o;
863 struct a_word
865 struct a_word *next;
866 struct a_word *chain;
867 char *str;
868 int length;
869 int matched;
872 static unsigned long
873 a_word_hash_1 (const void *key)
875 return_STRING_HASH_1 (((struct a_word const *) key)->str);
878 static unsigned long
879 a_word_hash_2 (const void *key)
881 return_STRING_HASH_2 (((struct a_word const *) key)->str);
884 static int
885 a_word_hash_cmp (const void *x, const void *y)
887 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
888 if (result)
889 return result;
890 return_STRING_COMPARE (((struct a_word const *) x)->str,
891 ((struct a_word const *) y)->str);
894 struct a_pattern
896 struct a_pattern *next;
897 char *str;
898 char *percent;
899 int length;
900 int save_c;
903 static char *
904 func_filter_filterout (char *o, char **argv, const char *funcname)
906 struct a_word *wordhead;
907 struct a_word **wordtail;
908 struct a_word *wp;
909 struct a_pattern *pathead;
910 struct a_pattern **pattail;
911 struct a_pattern *pp;
913 struct hash_table a_word_table;
914 int is_filter = streq (funcname, "filter");
915 char *pat_iterator = argv[0];
916 char *word_iterator = argv[1];
917 int literals = 0;
918 int words = 0;
919 int hashing = 0;
920 char *p;
921 unsigned int len;
923 /* Chop ARGV[0] up into patterns to match against the words. */
925 pattail = &pathead;
926 while ((p = find_next_token (&pat_iterator, &len)) != 0)
928 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
930 *pattail = pat;
931 pattail = &pat->next;
933 if (*pat_iterator != '\0')
934 ++pat_iterator;
936 pat->str = p;
937 pat->length = len;
938 pat->save_c = p[len];
939 p[len] = '\0';
940 pat->percent = find_percent (p);
941 if (pat->percent == 0)
942 literals++;
944 *pattail = 0;
946 /* Chop ARGV[1] up into words to match against the patterns. */
948 wordtail = &wordhead;
949 while ((p = find_next_token (&word_iterator, &len)) != 0)
951 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
953 *wordtail = word;
954 wordtail = &word->next;
956 if (*word_iterator != '\0')
957 ++word_iterator;
959 p[len] = '\0';
960 word->str = p;
961 word->length = len;
962 word->matched = 0;
963 word->chain = 0;
964 words++;
966 *wordtail = 0;
968 /* Only use a hash table if arg list lengths justifies the cost. */
969 hashing = (literals >= 2 && (literals * words) >= 10);
970 if (hashing)
972 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
973 for (wp = wordhead; wp != 0; wp = wp->next)
975 struct a_word *owp = hash_insert (&a_word_table, wp);
976 if (owp)
977 wp->chain = owp;
981 if (words)
983 int doneany = 0;
985 /* Run each pattern through the words, killing words. */
986 for (pp = pathead; pp != 0; pp = pp->next)
988 if (pp->percent)
989 for (wp = wordhead; wp != 0; wp = wp->next)
990 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
991 else if (hashing)
993 struct a_word a_word_key;
994 a_word_key.str = pp->str;
995 a_word_key.length = pp->length;
996 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
997 while (wp)
999 wp->matched |= 1;
1000 wp = wp->chain;
1003 else
1004 for (wp = wordhead; wp != 0; wp = wp->next)
1005 wp->matched |= (wp->length == pp->length
1006 && strneq (pp->str, wp->str, wp->length));
1009 /* Output the words that matched (or didn't, for filter-out). */
1010 for (wp = wordhead; wp != 0; wp = wp->next)
1011 if (is_filter ? wp->matched : !wp->matched)
1013 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1014 o = variable_buffer_output (o, " ", 1);
1015 doneany = 1;
1018 if (doneany)
1019 /* Kill the last space. */
1020 --o;
1023 for (pp = pathead; pp != 0; pp = pp->next)
1024 pp->str[pp->length] = pp->save_c;
1026 if (hashing)
1027 hash_free (&a_word_table, 0);
1029 return o;
1033 static char *
1034 func_strip (char *o, char **argv, const char *funcname UNUSED)
1036 char *p = argv[0];
1037 int doneany =0;
1039 while (*p != '\0')
1041 int i=0;
1042 char *word_start=0;
1044 while (isspace ((unsigned char)*p))
1045 ++p;
1046 word_start = p;
1047 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1049 if (!i)
1050 break;
1051 o = variable_buffer_output (o, word_start, i);
1052 o = variable_buffer_output (o, " ", 1);
1053 doneany = 1;
1056 if (doneany)
1057 /* Kill the last space. */
1058 --o;
1059 return o;
1063 Print a warning or fatal message.
1065 static char *
1066 func_error (char *o, char **argv, const char *funcname)
1068 char **argvp;
1069 char *msg, *p;
1070 int len;
1072 /* The arguments will be broken on commas. Rather than create yet
1073 another special case where function arguments aren't broken up,
1074 just create a format string that puts them back together. */
1075 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1076 len += strlen (*argvp) + 2;
1078 p = msg = (char *) alloca (len + 1);
1080 for (argvp=argv; argvp[1] != 0; ++argvp)
1082 strcpy (p, *argvp);
1083 p += strlen (*argvp);
1084 *(p++) = ',';
1085 *(p++) = ' ';
1087 strcpy (p, *argvp);
1089 switch (*funcname) {
1090 case 'e':
1091 fatal (reading_file, "%s", msg);
1093 case 'w':
1094 error (reading_file, "%s", msg);
1095 break;
1097 case 'i':
1098 printf ("%s\n", msg);
1099 break;
1101 default:
1102 fatal (reading_file, "Internal error: func_error: '%s'", funcname);
1105 /* The warning function expands to the empty string. */
1106 return o;
1111 chop argv[0] into words, and sort them.
1113 static char *
1114 func_sort (char *o, char **argv, const char *funcname UNUSED)
1116 char **words = 0;
1117 int nwords = 0;
1118 register int wordi = 0;
1120 /* Chop ARGV[0] into words and put them in WORDS. */
1121 char *t = argv[0];
1122 char *p;
1123 unsigned int len;
1124 int i;
1126 while ((p = find_next_token (&t, &len)) != 0)
1128 if (wordi >= nwords - 1)
1130 nwords = (2 * nwords) + 5;
1131 words = (char **) xrealloc ((char *) words,
1132 nwords * sizeof (char *));
1134 words[wordi++] = savestring (p, len);
1137 if (!wordi)
1138 return o;
1140 /* Now sort the list of words. */
1141 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1143 /* Now write the sorted list. */
1144 for (i = 0; i < wordi; ++i)
1146 len = strlen (words[i]);
1147 if (i == wordi - 1 || strlen (words[i + 1]) != len
1148 || strcmp (words[i], words[i + 1]))
1150 o = variable_buffer_output (o, words[i], len);
1151 o = variable_buffer_output (o, " ", 1);
1153 free (words[i]);
1155 /* Kill the last space. */
1156 --o;
1158 free (words);
1160 return o;
1164 $(if condition,true-part[,false-part])
1166 CONDITION is false iff it evaluates to an empty string. White
1167 space before and after condition are stripped before evaluation.
1169 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1170 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1171 you can use $(if ...) to create side-effects (with $(shell ...), for
1172 example).
1175 static char *
1176 func_if (char *o, char **argv, const char *funcname UNUSED)
1178 const char *begp = argv[0];
1179 const char *endp = begp + strlen (argv[0]) - 1;
1180 int result = 0;
1182 /* Find the result of the condition: if we have a value, and it's not
1183 empty, the condition is true. If we don't have a value, or it's the
1184 empty string, then it's false. */
1186 strip_whitespace (&begp, &endp);
1188 if (begp <= endp)
1190 char *expansion = expand_argument (begp, endp+1);
1192 result = strlen (expansion);
1193 free (expansion);
1196 /* If the result is true (1) we want to eval the first argument, and if
1197 it's false (0) we want to eval the second. If the argument doesn't
1198 exist we do nothing, otherwise expand it and add to the buffer. */
1200 argv += 1 + !result;
1202 if (argv[0])
1204 char *expansion;
1206 expansion = expand_argument (argv[0], NULL);
1208 o = variable_buffer_output (o, expansion, strlen (expansion));
1210 free (expansion);
1213 return o;
1216 static char *
1217 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1220 #ifdef _AMIGA
1221 o = wildcard_expansion (argv[0], o);
1222 #else
1223 char *p = string_glob (argv[0]);
1224 o = variable_buffer_output (o, p, strlen (p));
1225 #endif
1226 return o;
1230 $(eval <makefile string>)
1232 Always resolves to the empty string.
1234 Treat the arguments as a segment of makefile, and parse them.
1237 static char *
1238 func_eval (char *o, char **argv, const char *funcname UNUSED)
1240 char *buf;
1241 unsigned int len;
1243 /* Eval the buffer. Pop the current variable buffer setting so that the
1244 eval'd code can use its own without conflicting. */
1246 install_variable_buffer (&buf, &len);
1248 eval_buffer (argv[0]);
1250 restore_variable_buffer (buf, len);
1252 return o;
1256 static char *
1257 func_value (char *o, char **argv, const char *funcname UNUSED)
1259 /* Look up the variable. */
1260 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1262 /* Copy its value into the output buffer without expanding it. */
1263 if (v)
1264 o = variable_buffer_output (o, v->value, strlen(v->value));
1266 return o;
1270 \r is replaced on UNIX as well. Is this desirable?
1272 void
1273 fold_newlines (char *buffer, int *length)
1275 char *dst = buffer;
1276 char *src = buffer;
1277 char *last_nonnl = buffer -1;
1278 src[*length] = 0;
1279 for (; *src != '\0'; ++src)
1281 if (src[0] == '\r' && src[1] == '\n')
1282 continue;
1283 if (*src == '\n')
1285 *dst++ = ' ';
1287 else
1289 last_nonnl = dst;
1290 *dst++ = *src;
1293 *(++last_nonnl) = '\0';
1294 *length = last_nonnl - buffer;
1299 int shell_function_pid = 0, shell_function_completed;
1302 #ifdef WINDOWS32
1303 /*untested*/
1305 #include <windows.h>
1306 #include <io.h>
1307 #include "sub_proc.h"
1310 void
1311 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1313 SECURITY_ATTRIBUTES saAttr;
1314 HANDLE hIn;
1315 HANDLE hErr;
1316 HANDLE hChildOutRd;
1317 HANDLE hChildOutWr;
1318 HANDLE hProcess;
1321 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1322 saAttr.bInheritHandle = TRUE;
1323 saAttr.lpSecurityDescriptor = NULL;
1325 if (DuplicateHandle (GetCurrentProcess(),
1326 GetStdHandle(STD_INPUT_HANDLE),
1327 GetCurrentProcess(),
1328 &hIn,
1330 TRUE,
1331 DUPLICATE_SAME_ACCESS) == FALSE) {
1332 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1333 GetLastError());
1336 if (DuplicateHandle(GetCurrentProcess(),
1337 GetStdHandle(STD_ERROR_HANDLE),
1338 GetCurrentProcess(),
1339 &hErr,
1341 TRUE,
1342 DUPLICATE_SAME_ACCESS) == FALSE) {
1343 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1344 GetLastError());
1347 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1348 fatal (NILF, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1350 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1352 if (!hProcess)
1353 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1355 /* make sure that CreateProcess() has Path it needs */
1356 sync_Path_environment();
1358 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1359 /* register process for wait */
1360 process_register(hProcess);
1362 /* set the pid for returning to caller */
1363 *pid_p = (int) hProcess;
1365 /* set up to read data from child */
1366 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1368 /* this will be closed almost right away */
1369 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1370 } else {
1371 /* reap/cleanup the failed process */
1372 process_cleanup(hProcess);
1374 /* close handles which were duplicated, they weren't used */
1375 CloseHandle(hIn);
1376 CloseHandle(hErr);
1378 /* close pipe handles, they won't be used */
1379 CloseHandle(hChildOutRd);
1380 CloseHandle(hChildOutWr);
1382 /* set status for return */
1383 pipedes[0] = pipedes[1] = -1;
1384 *pid_p = -1;
1387 #endif
1390 #ifdef __MSDOS__
1391 FILE *
1392 msdos_openpipe (int* pipedes, int *pidp, char *text)
1394 FILE *fpipe=0;
1395 /* MSDOS can't fork, but it has `popen'. */
1396 struct variable *sh = lookup_variable ("SHELL", 5);
1397 int e;
1398 extern int dos_command_running, dos_status;
1400 /* Make sure not to bother processing an empty line. */
1401 while (isblank ((unsigned char)*text))
1402 ++text;
1403 if (*text == '\0')
1404 return 0;
1406 if (sh)
1408 char buf[PATH_MAX + 7];
1409 /* This makes sure $SHELL value is used by $(shell), even
1410 though the target environment is not passed to it. */
1411 sprintf (buf, "SHELL=%s", sh->value);
1412 putenv (buf);
1415 e = errno;
1416 errno = 0;
1417 dos_command_running = 1;
1418 dos_status = 0;
1419 /* If dos_status becomes non-zero, it means the child process
1420 was interrupted by a signal, like SIGINT or SIGQUIT. See
1421 fatal_error_signal in commands.c. */
1422 fpipe = popen (text, "rt");
1423 dos_command_running = 0;
1424 if (!fpipe || dos_status)
1426 pipedes[0] = -1;
1427 *pidp = -1;
1428 if (dos_status)
1429 errno = EINTR;
1430 else if (errno == 0)
1431 errno = ENOMEM;
1432 shell_function_completed = -1;
1434 else
1436 pipedes[0] = fileno (fpipe);
1437 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1438 errno = e;
1439 shell_function_completed = 1;
1441 return fpipe;
1443 #endif
1446 Do shell spawning, with the naughty bits for different OSes.
1449 #ifdef VMS
1451 /* VMS can't do $(shell ...) */
1452 #define func_shell 0
1454 #else
1455 #ifndef _AMIGA
1456 static char *
1457 func_shell (char *o, char **argv, const char *funcname UNUSED)
1459 char* batch_filename = NULL;
1460 unsigned int i;
1462 #ifdef __MSDOS__
1463 FILE *fpipe;
1464 #endif
1465 char **command_argv;
1466 char *error_prefix;
1467 char **envp;
1468 int pipedes[2];
1469 int pid;
1471 #ifndef __MSDOS__
1472 /* Construct the argument list. */
1473 command_argv = construct_command_argv (argv[0],
1474 (char **) NULL, (struct file *) 0,
1475 &batch_filename);
1476 if (command_argv == 0)
1477 return o;
1478 #endif
1480 /* Using a target environment for `shell' loses in cases like:
1481 export var = $(shell echo foobie)
1482 because target_environment hits a loop trying to expand $(var)
1483 to put it in the environment. This is even more confusing when
1484 var was not explicitly exported, but just appeared in the
1485 calling environment. */
1487 envp = environ;
1489 /* For error messages. */
1490 if (reading_file && reading_file->filenm)
1492 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1493 sprintf (error_prefix,
1494 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1496 else
1497 error_prefix = "";
1499 #ifdef WINDOWS32
1501 windows32_openpipe (pipedes, &pid, command_argv, envp);
1503 if (pipedes[0] < 0) {
1504 /* open of the pipe failed, mark as failed execution */
1505 shell_function_completed = -1;
1507 return o;
1508 } else
1510 #elif defined(__MSDOS__)
1512 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1513 if (pipedes[0] < 0)
1515 perror_with_name (error_prefix, "pipe");
1516 return o;
1519 #else
1521 if (pipe (pipedes) < 0)
1523 perror_with_name (error_prefix, "pipe");
1524 return o;
1527 # ifdef __EMX__
1529 /* close some handles that are unnecessary for the child process */
1530 CLOSE_ON_EXEC(pipedes[1]);
1531 CLOSE_ON_EXEC(pipedes[0]);
1532 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1533 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1534 if (pid < 0)
1535 perror_with_name (error_prefix, "spawn");
1537 # else /* ! __EMX__ */
1539 pid = vfork ();
1540 if (pid < 0)
1541 perror_with_name (error_prefix, "fork");
1542 else if (pid == 0)
1543 child_execute_job (0, pipedes[1], command_argv, envp);
1544 else
1546 # endif
1548 #endif
1550 /* We are the parent. */
1552 char *buffer;
1553 unsigned int maxlen;
1554 int cc;
1556 /* Record the PID for reap_children. */
1557 shell_function_pid = pid;
1558 #ifndef __MSDOS__
1559 shell_function_completed = 0;
1561 /* Free the storage only the child needed. */
1562 free (command_argv[0]);
1563 free ((char *) command_argv);
1565 /* Close the write side of the pipe. */
1566 (void) close (pipedes[1]);
1567 #endif
1569 /* Set up and read from the pipe. */
1571 maxlen = 200;
1572 buffer = (char *) xmalloc (maxlen + 1);
1574 /* Read from the pipe until it gets EOF. */
1575 for (i = 0; ; i += cc)
1577 if (i == maxlen)
1579 maxlen += 512;
1580 buffer = (char *) xrealloc (buffer, maxlen + 1);
1583 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1584 if (cc <= 0)
1585 break;
1587 buffer[i] = '\0';
1589 /* Close the read side of the pipe. */
1590 #ifdef __MSDOS__
1591 if (fpipe)
1592 (void) pclose (fpipe);
1593 #else
1594 (void) close (pipedes[0]);
1595 #endif
1597 /* Loop until child_handler or reap_children() sets
1598 shell_function_completed to the status of our child shell. */
1599 while (shell_function_completed == 0)
1600 reap_children (1, 0);
1602 if (batch_filename) {
1603 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1604 batch_filename));
1605 remove (batch_filename);
1606 free (batch_filename);
1608 shell_function_pid = 0;
1610 /* The child_handler function will set shell_function_completed
1611 to 1 when the child dies normally, or to -1 if it
1612 dies with status 127, which is most likely an exec fail. */
1614 if (shell_function_completed == -1)
1616 /* This most likely means that the execvp failed,
1617 so we should just write out the error message
1618 that came in over the pipe from the child. */
1619 fputs (buffer, stderr);
1620 fflush (stderr);
1622 else
1624 /* The child finished normally. Replace all
1625 newlines in its output with spaces, and put
1626 that in the variable output buffer. */
1627 fold_newlines (buffer, &i);
1628 o = variable_buffer_output (o, buffer, i);
1631 free (buffer);
1634 return o;
1637 #else /* _AMIGA */
1639 /* Do the Amiga version of func_shell. */
1641 static char *
1642 func_shell (char *o, char **argv, const char *funcname)
1644 /* Amiga can't fork nor spawn, but I can start a program with
1645 redirection of my choice. However, this means that we
1646 don't have an opportunity to reopen stdout to trap it. Thus,
1647 we save our own stdout onto a new descriptor and dup a temp
1648 file's descriptor onto our stdout temporarily. After we
1649 spawn the shell program, we dup our own stdout back to the
1650 stdout descriptor. The buffer reading is the same as above,
1651 except that we're now reading from a file. */
1653 #include <dos/dos.h>
1654 #include <proto/dos.h>
1656 BPTR child_stdout;
1657 char tmp_output[FILENAME_MAX];
1658 unsigned int maxlen = 200;
1659 int cc, i;
1660 char * buffer, * ptr;
1661 char ** aptr;
1662 int len = 0;
1663 char* batch_filename = NULL;
1665 /* Construct the argument list. */
1666 command_argv = construct_command_argv (argv[0], (char **) NULL,
1667 (struct file *) 0, &batch_filename);
1668 if (command_argv == 0)
1669 return o;
1671 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1672 Ideally we would use main.c:open_tmpfile(), but this uses a special
1673 Open(), not fopen(), and I'm not familiar enough with the code to mess
1674 with it. */
1675 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1676 mktemp (tmp_output);
1677 child_stdout = Open (tmp_output, MODE_NEWFILE);
1679 for (aptr=command_argv; *aptr; aptr++)
1680 len += strlen (*aptr) + 1;
1682 buffer = xmalloc (len + 1);
1683 ptr = buffer;
1685 for (aptr=command_argv; *aptr; aptr++)
1687 strcpy (ptr, *aptr);
1688 ptr += strlen (ptr) + 1;
1689 *ptr ++ = ' ';
1690 *ptr = 0;
1693 ptr[-1] = '\n';
1695 Execute (buffer, NULL, child_stdout);
1696 free (buffer);
1698 Close (child_stdout);
1700 child_stdout = Open (tmp_output, MODE_OLDFILE);
1702 buffer = xmalloc (maxlen);
1703 i = 0;
1706 if (i == maxlen)
1708 maxlen += 512;
1709 buffer = (char *) xrealloc (buffer, maxlen + 1);
1712 cc = Read (child_stdout, &buffer[i], maxlen - i);
1713 if (cc > 0)
1714 i += cc;
1715 } while (cc > 0);
1717 Close (child_stdout);
1719 fold_newlines (buffer, &i);
1720 o = variable_buffer_output (o, buffer, i);
1721 free (buffer);
1722 return o;
1724 #endif /* _AMIGA */
1725 #endif /* !VMS */
1727 #ifdef EXPERIMENTAL
1730 equality. Return is string-boolean, ie, the empty string is false.
1732 static char *
1733 func_eq (char *o, char **argv, char *funcname)
1735 int result = ! strcmp (argv[0], argv[1]);
1736 o = variable_buffer_output (o, result ? "1" : "", result);
1737 return o;
1742 string-boolean not operator.
1744 static char *
1745 func_not (char *o, char **argv, char *funcname)
1747 char *s = argv[0];
1748 int result = 0;
1749 while (isspace ((unsigned char)*s))
1750 s++;
1751 result = ! (*s);
1752 o = variable_buffer_output (o, result ? "1" : "", result);
1753 return o;
1755 #endif
1758 /* Return the absolute name of file NAME which does not contain any `.',
1759 `..' components nor any repeated path separators ('/'). */
1761 static char *
1762 abspath (const char *name, char *apath)
1764 char *dest;
1765 const char *start, *end, *apath_limit;
1767 if (name[0] == '\0' || apath == NULL)
1768 return NULL;
1770 apath_limit = apath + GET_PATH_MAX;
1772 if (name[0] != '/')
1774 /* It is unlikely we would make it until here but just to make sure. */
1775 if (!starting_directory)
1776 return NULL;
1778 strcpy (apath, starting_directory);
1780 dest = strchr (apath, '\0');
1782 else
1784 apath[0] = '/';
1785 dest = apath + 1;
1788 for (start = end = name; *start != '\0'; start = end)
1790 unsigned long len;
1792 /* Skip sequence of multiple path-separators. */
1793 while (*start == '/')
1794 ++start;
1796 /* Find end of path component. */
1797 for (end = start; *end != '\0' && *end != '/'; ++end)
1800 len = end - start;
1802 if (len == 0)
1803 break;
1804 else if (len == 1 && start[0] == '.')
1805 /* nothing */;
1806 else if (len == 2 && start[0] == '.' && start[1] == '.')
1808 /* Back up to previous component, ignore if at root already. */
1809 if (dest > apath + 1)
1810 while ((--dest)[-1] != '/');
1812 else
1814 if (dest[-1] != '/')
1815 *dest++ = '/';
1817 if (dest + len >= apath_limit)
1818 return NULL;
1820 dest = memcpy (dest, start, len);
1821 dest += len;
1822 *dest = '\0';
1826 /* Unless it is root strip trailing separator. */
1827 if (dest > apath + 1 && dest[-1] == '/')
1828 --dest;
1830 *dest = '\0';
1832 return apath;
1836 static char *
1837 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1839 /* Expand the argument. */
1840 char *p = argv[0];
1841 char *path = 0;
1842 int doneany = 0;
1843 unsigned int len = 0;
1844 PATH_VAR (in);
1845 PATH_VAR (out);
1847 while ((path = find_next_token (&p, &len)) != 0)
1849 if (len < GET_PATH_MAX)
1851 strncpy (in, path, len);
1852 in[len] = '\0';
1856 #ifdef HAVE_REALPATH
1857 realpath (in, out)
1858 #else
1859 abspath (in, out)
1860 #endif
1863 o = variable_buffer_output (o, out, strlen (out));
1864 o = variable_buffer_output (o, " ", 1);
1865 doneany = 1;
1870 /* Kill last space. */
1871 if (doneany)
1872 --o;
1874 return o;
1877 static char *
1878 func_abspath (char *o, char **argv, const char *funcname UNUSED)
1880 /* Expand the argument. */
1881 char *p = argv[0];
1882 char *path = 0;
1883 int doneany = 0;
1884 unsigned int len = 0;
1885 PATH_VAR (in);
1886 PATH_VAR (out);
1888 while ((path = find_next_token (&p, &len)) != 0)
1890 if (len < GET_PATH_MAX)
1892 strncpy (in, path, len);
1893 in[len] = '\0';
1895 if (abspath (in, out))
1897 o = variable_buffer_output (o, out, strlen (out));
1898 o = variable_buffer_output (o, " ", 1);
1899 doneany = 1;
1904 /* Kill last space. */
1905 if (doneany)
1906 --o;
1908 return o;
1911 /* Lookup table for builtin functions.
1913 This doesn't have to be sorted; we use a straight lookup. We might gain
1914 some efficiency by moving most often used functions to the start of the
1915 table.
1917 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1918 comma-separated values are treated as arguments.
1920 EXPAND_ARGS means that all arguments should be expanded before invocation.
1921 Functions that do namespace tricks (foreach) don't automatically expand. */
1923 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1926 static struct function_table_entry function_table_init[] =
1928 /* Name/size */ /* MIN MAX EXP? Function */
1929 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
1930 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1931 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1932 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1933 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1934 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1935 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1936 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1937 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1938 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1939 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1940 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1941 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1942 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
1943 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1944 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
1945 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1946 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1947 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1948 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1949 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1950 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1951 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1952 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1953 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1954 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1955 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
1956 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1957 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1958 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1959 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1960 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1961 #ifdef EXPERIMENTAL
1962 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1963 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1964 #endif
1967 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1970 /* These must come after the definition of function_table. */
1972 static char *
1973 expand_builtin_function (char *o, int argc, char **argv,
1974 const struct function_table_entry *entry_p)
1976 if (argc < (int)entry_p->minimum_args)
1977 fatal (reading_file,
1978 _("Insufficient number of arguments (%d) to function `%s'"),
1979 argc, entry_p->name);
1981 /* I suppose technically some function could do something with no
1982 arguments, but so far none do, so just test it for all functions here
1983 rather than in each one. We can change it later if necessary. */
1985 if (!argc)
1986 return o;
1988 if (!entry_p->func_ptr)
1989 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
1990 entry_p->name);
1992 return entry_p->func_ptr (o, argv, entry_p->name);
1995 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1996 opening ( or { and is not null-terminated. If a function invocation
1997 is found, expand it into the buffer at *OP, updating *OP, incrementing
1998 *STRINGP past the reference and returning nonzero. If not, return zero. */
2001 handle_function (char **op, char **stringp)
2003 const struct function_table_entry *entry_p;
2004 char openparen = (*stringp)[0];
2005 char closeparen = openparen == '(' ? ')' : '}';
2006 char *beg;
2007 char *end;
2008 int count = 0;
2009 register char *p;
2010 char **argv, **argvp;
2011 int nargs;
2013 beg = *stringp + 1;
2015 entry_p = lookup_function (beg);
2017 if (!entry_p)
2018 return 0;
2020 /* We found a builtin function. Find the beginning of its arguments (skip
2021 whitespace after the name). */
2023 beg = next_token (beg + entry_p->len);
2025 /* Find the end of the function invocation, counting nested use of
2026 whichever kind of parens we use. Since we're looking, count commas
2027 to get a rough estimate of how many arguments we might have. The
2028 count might be high, but it'll never be low. */
2030 for (nargs=1, end=beg; *end != '\0'; ++end)
2031 if (*end == ',')
2032 ++nargs;
2033 else if (*end == openparen)
2034 ++count;
2035 else if (*end == closeparen && --count < 0)
2036 break;
2038 if (count >= 0)
2039 fatal (reading_file,
2040 _("unterminated call to function `%s': missing `%c'"),
2041 entry_p->name, closeparen);
2043 *stringp = end;
2045 /* Get some memory to store the arg pointers. */
2046 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
2048 /* Chop the string into arguments, then a nul. As soon as we hit
2049 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2050 last argument.
2052 If we're expanding, store pointers to the expansion of each one. If
2053 not, make a duplicate of the string and point into that, nul-terminating
2054 each argument. */
2056 if (!entry_p->expand_args)
2058 int len = end - beg;
2060 p = xmalloc (len+1);
2061 memcpy (p, beg, len);
2062 p[len] = '\0';
2063 beg = p;
2064 end = beg + len;
2067 for (p=beg, nargs=0; p <= end; ++argvp)
2069 char *next;
2071 ++nargs;
2073 if (nargs == entry_p->maximum_args
2074 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2075 next = end;
2077 if (entry_p->expand_args)
2078 *argvp = expand_argument (p, next);
2079 else
2081 *argvp = p;
2082 *next = '\0';
2085 p = next + 1;
2087 *argvp = NULL;
2089 /* Finally! Run the function... */
2090 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2092 /* Free memory. */
2093 if (entry_p->expand_args)
2094 for (argvp=argv; *argvp != 0; ++argvp)
2095 free (*argvp);
2096 else
2097 free (beg);
2099 return 1;
2103 /* User-defined functions. Expand the first argument as either a builtin
2104 function or a make variable, in the context of the rest of the arguments
2105 assigned to $1, $2, ... $N. $0 is the name of the function. */
2107 static char *
2108 func_call (char *o, char **argv, const char *funcname UNUSED)
2110 static int max_args = 0;
2111 char *fname;
2112 char *cp;
2113 char *body;
2114 int flen;
2115 int i;
2116 int saved_args;
2117 const struct function_table_entry *entry_p;
2118 struct variable *v;
2120 /* There is no way to define a variable with a space in the name, so strip
2121 leading and trailing whitespace as a favor to the user. */
2122 fname = argv[0];
2123 while (*fname != '\0' && isspace ((unsigned char)*fname))
2124 ++fname;
2126 cp = fname + strlen (fname) - 1;
2127 while (cp > fname && isspace ((unsigned char)*cp))
2128 --cp;
2129 cp[1] = '\0';
2131 /* Calling nothing is a no-op */
2132 if (*fname == '\0')
2133 return o;
2135 /* Are we invoking a builtin function? */
2137 entry_p = lookup_function (fname);
2139 if (entry_p)
2141 /* How many arguments do we have? */
2142 for (i=0; argv[i+1]; ++i)
2145 return expand_builtin_function (o, i, argv+1, entry_p);
2148 /* Not a builtin, so the first argument is the name of a variable to be
2149 expanded and interpreted as a function. Find it. */
2150 flen = strlen (fname);
2152 v = lookup_variable (fname, flen);
2154 if (v == 0)
2155 warn_undefined (fname, flen);
2157 if (v == 0 || *v->value == '\0')
2158 return o;
2160 body = (char *) alloca (flen + 4);
2161 body[0] = '$';
2162 body[1] = '(';
2163 memcpy (body + 2, fname, flen);
2164 body[flen+2] = ')';
2165 body[flen+3] = '\0';
2167 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2169 push_new_variable_scope ();
2171 for (i=0; *argv; ++i, ++argv)
2173 char num[11];
2175 sprintf (num, "%d", i);
2176 define_variable (num, strlen (num), *argv, o_automatic, 0);
2179 /* If the number of arguments we have is < max_args, it means we're inside
2180 a recursive invocation of $(call ...). Fill in the remaining arguments
2181 in the new scope with the empty value, to hide them from this
2182 invocation. */
2184 for (; i < max_args; ++i)
2186 char num[11];
2188 sprintf (num, "%d", i);
2189 define_variable (num, strlen (num), "", o_automatic, 0);
2192 /* Expand the body in the context of the arguments, adding the result to
2193 the variable buffer. */
2195 v->exp_count = EXP_COUNT_MAX;
2197 saved_args = max_args;
2198 max_args = i;
2199 o = variable_expand_string (o, body, flen+3);
2200 max_args = saved_args;
2202 v->exp_count = 0;
2204 pop_variable_scope ();
2206 return o + strlen (o);
2209 void
2210 hash_init_function_table (void)
2212 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2213 function_table_entry_hash_1, function_table_entry_hash_2,
2214 function_table_entry_hash_cmp);
2215 hash_load (&function_table, function_table_init,
2216 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));