Fix a bug where a variable could be used without being initialized in W32.
[make.git] / function.c
blob95872f01405fb93197af164d9c0684172c73b96f
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 static char *
493 func_flavor (char *o, char **argv, const char *funcname UNUSED)
495 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
497 if (v == 0)
498 o = variable_buffer_output (o, "undefined", 9);
499 else
500 if (v->recursive)
501 o = variable_buffer_output (o, "recursive", 9);
502 else
503 o = variable_buffer_output (o, "simple", 6);
505 return o;
508 #ifdef VMS
509 # define IS_PATHSEP(c) ((c) == ']')
510 #else
511 # ifdef HAVE_DOS_PATHS
512 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
513 # else
514 # define IS_PATHSEP(c) ((c) == '/')
515 # endif
516 #endif
519 static char *
520 func_notdir_suffix (char *o, char **argv, const char *funcname)
522 /* Expand the argument. */
523 char *list_iterator = argv[0];
524 char *p2 =0;
525 int doneany =0;
526 unsigned int len=0;
528 int is_suffix = streq (funcname, "suffix");
529 int is_notdir = !is_suffix;
530 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
532 char *p = p2 + len;
535 while (p >= p2 && (!is_suffix || *p != '.'))
537 if (IS_PATHSEP (*p))
538 break;
539 --p;
542 if (p >= p2)
544 if (is_notdir)
545 ++p;
546 else if (*p != '.')
547 continue;
548 o = variable_buffer_output (o, p, len - (p - p2));
550 #ifdef HAVE_DOS_PATHS
551 /* Handle the case of "d:foo/bar". */
552 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
554 p = p2 + 2;
555 o = variable_buffer_output (o, p, len - (p - p2));
557 #endif
558 else if (is_notdir)
559 o = variable_buffer_output (o, p2, len);
561 if (is_notdir || p >= p2)
563 o = variable_buffer_output (o, " ", 1);
564 doneany = 1;
567 if (doneany)
568 /* Kill last space. */
569 --o;
572 return o;
577 static char *
578 func_basename_dir (char *o, char **argv, const char *funcname)
580 /* Expand the argument. */
581 char *p3 = argv[0];
582 char *p2=0;
583 int doneany=0;
584 unsigned int len=0;
585 char *p=0;
586 int is_basename= streq (funcname, "basename");
587 int is_dir= !is_basename;
589 while ((p2 = find_next_token (&p3, &len)) != 0)
591 p = p2 + len;
592 while (p >= p2 && (!is_basename || *p != '.'))
594 if (IS_PATHSEP (*p))
595 break;
596 --p;
599 if (p >= p2 && (is_dir))
600 o = variable_buffer_output (o, p2, ++p - p2);
601 else if (p >= p2 && (*p == '.'))
602 o = variable_buffer_output (o, p2, p - p2);
603 #ifdef HAVE_DOS_PATHS
604 /* Handle the "d:foobar" case */
605 else if (p2[0] && p2[1] == ':' && is_dir)
606 o = variable_buffer_output (o, p2, 2);
607 #endif
608 else if (is_dir)
609 #ifdef VMS
610 o = variable_buffer_output (o, "[]", 2);
611 #else
612 #ifndef _AMIGA
613 o = variable_buffer_output (o, "./", 2);
614 #else
615 ; /* Just a nop... */
616 #endif /* AMIGA */
617 #endif /* !VMS */
618 else
619 /* The entire name is the basename. */
620 o = variable_buffer_output (o, p2, len);
622 o = variable_buffer_output (o, " ", 1);
623 doneany = 1;
625 if (doneany)
626 /* Kill last space. */
627 --o;
630 return o;
633 static char *
634 func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
636 int fixlen = strlen (argv[0]);
637 char *list_iterator = argv[1];
638 int is_addprefix = streq (funcname, "addprefix");
639 int is_addsuffix = !is_addprefix;
641 int doneany = 0;
642 char *p;
643 unsigned int len;
645 while ((p = find_next_token (&list_iterator, &len)) != 0)
647 if (is_addprefix)
648 o = variable_buffer_output (o, argv[0], fixlen);
649 o = variable_buffer_output (o, p, len);
650 if (is_addsuffix)
651 o = variable_buffer_output (o, argv[0], fixlen);
652 o = variable_buffer_output (o, " ", 1);
653 doneany = 1;
656 if (doneany)
657 /* Kill last space. */
658 --o;
660 return o;
663 static char *
664 func_subst (char *o, char **argv, const char *funcname UNUSED)
666 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
667 strlen (argv[1]), 0);
669 return o;
673 static char *
674 func_firstword (char *o, char **argv, const char *funcname UNUSED)
676 unsigned int i;
677 char *words = argv[0]; /* Use a temp variable for find_next_token */
678 char *p = find_next_token (&words, &i);
680 if (p != 0)
681 o = variable_buffer_output (o, p, i);
683 return o;
686 static char *
687 func_lastword (char *o, char **argv, const char *funcname UNUSED)
689 unsigned int i;
690 char *words = argv[0]; /* Use a temp variable for find_next_token */
691 char *p = 0;
692 char *t;
694 while ((t = find_next_token (&words, &i)))
695 p = t;
697 if (p != 0)
698 o = variable_buffer_output (o, p, i);
700 return o;
703 static char *
704 func_words (char *o, char **argv, const char *funcname UNUSED)
706 int i = 0;
707 char *word_iterator = argv[0];
708 char buf[20];
710 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
711 ++i;
713 sprintf (buf, "%d", i);
714 o = variable_buffer_output (o, buf, strlen (buf));
717 return o;
720 /* Set begpp to point to the first non-whitespace character of the string,
721 * and endpp to point to the last non-whitespace character of the string.
722 * If the string is empty or contains nothing but whitespace, endpp will be
723 * begpp-1.
725 char *
726 strip_whitespace (const char **begpp, const char **endpp)
728 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
729 (*begpp) ++;
730 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
731 (*endpp) --;
732 return (char *)*begpp;
735 static void
736 check_numeric (const char *s, const char *message)
738 const char *end = s + strlen (s) - 1;
739 const char *beg = s;
740 strip_whitespace (&s, &end);
742 for (; s <= end; ++s)
743 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
744 break;
746 if (s <= end || end - beg < 0)
747 fatal (reading_file, "%s: '%s'", message, beg);
752 static char *
753 func_word (char *o, char **argv, const char *funcname UNUSED)
755 char *end_p=0;
756 int i=0;
757 char *p=0;
759 /* Check the first argument. */
760 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
761 i = atoi (argv[0]);
763 if (i == 0)
764 fatal (reading_file, _("first argument to `word' function must be greater than 0"));
767 end_p = argv[1];
768 while ((p = find_next_token (&end_p, 0)) != 0)
769 if (--i == 0)
770 break;
772 if (i == 0)
773 o = variable_buffer_output (o, p, end_p - p);
775 return o;
778 static char *
779 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
781 int start, count;
783 /* Check the arguments. */
784 check_numeric (argv[0],
785 _("non-numeric first argument to `wordlist' function"));
786 check_numeric (argv[1],
787 _("non-numeric second argument to `wordlist' function"));
789 start = atoi (argv[0]);
790 if (start < 1)
791 fatal (reading_file,
792 "invalid first argument to `wordlist' function: `%d'", start);
794 count = atoi (argv[1]) - start + 1;
796 if (count > 0)
798 char *p;
799 char *end_p = argv[2];
801 /* Find the beginning of the "start"th word. */
802 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
805 if (p)
807 /* Find the end of the "count"th word from start. */
808 while (--count && (find_next_token (&end_p, 0) != 0))
811 /* Return the stuff in the middle. */
812 o = variable_buffer_output (o, p, end_p - p);
816 return o;
819 static char*
820 func_findstring (char *o, char **argv, const char *funcname UNUSED)
822 /* Find the first occurrence of the first string in the second. */
823 if (strstr (argv[1], argv[0]) != 0)
824 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
826 return o;
829 static char *
830 func_foreach (char *o, char **argv, const char *funcname UNUSED)
832 /* expand only the first two. */
833 char *varname = expand_argument (argv[0], NULL);
834 char *list = expand_argument (argv[1], NULL);
835 char *body = argv[2];
837 int doneany = 0;
838 char *list_iterator = list;
839 char *p;
840 unsigned int len;
841 register struct variable *var;
843 push_new_variable_scope ();
844 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
846 /* loop through LIST, put the value in VAR and expand BODY */
847 while ((p = find_next_token (&list_iterator, &len)) != 0)
849 char *result = 0;
852 char save = p[len];
854 p[len] = '\0';
855 free (var->value);
856 var->value = (char *) xstrdup ((char*) p);
857 p[len] = save;
860 result = allocated_variable_expand (body);
862 o = variable_buffer_output (o, result, strlen (result));
863 o = variable_buffer_output (o, " ", 1);
864 doneany = 1;
865 free (result);
868 if (doneany)
869 /* Kill the last space. */
870 --o;
872 pop_variable_scope ();
873 free (varname);
874 free (list);
876 return o;
879 struct a_word
881 struct a_word *next;
882 struct a_word *chain;
883 char *str;
884 int length;
885 int matched;
888 static unsigned long
889 a_word_hash_1 (const void *key)
891 return_STRING_HASH_1 (((struct a_word const *) key)->str);
894 static unsigned long
895 a_word_hash_2 (const void *key)
897 return_STRING_HASH_2 (((struct a_word const *) key)->str);
900 static int
901 a_word_hash_cmp (const void *x, const void *y)
903 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
904 if (result)
905 return result;
906 return_STRING_COMPARE (((struct a_word const *) x)->str,
907 ((struct a_word const *) y)->str);
910 struct a_pattern
912 struct a_pattern *next;
913 char *str;
914 char *percent;
915 int length;
916 int save_c;
919 static char *
920 func_filter_filterout (char *o, char **argv, const char *funcname)
922 struct a_word *wordhead;
923 struct a_word **wordtail;
924 struct a_word *wp;
925 struct a_pattern *pathead;
926 struct a_pattern **pattail;
927 struct a_pattern *pp;
929 struct hash_table a_word_table;
930 int is_filter = streq (funcname, "filter");
931 char *pat_iterator = argv[0];
932 char *word_iterator = argv[1];
933 int literals = 0;
934 int words = 0;
935 int hashing = 0;
936 char *p;
937 unsigned int len;
939 /* Chop ARGV[0] up into patterns to match against the words. */
941 pattail = &pathead;
942 while ((p = find_next_token (&pat_iterator, &len)) != 0)
944 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
946 *pattail = pat;
947 pattail = &pat->next;
949 if (*pat_iterator != '\0')
950 ++pat_iterator;
952 pat->str = p;
953 pat->length = len;
954 pat->save_c = p[len];
955 p[len] = '\0';
956 pat->percent = find_percent (p);
957 if (pat->percent == 0)
958 literals++;
960 *pattail = 0;
962 /* Chop ARGV[1] up into words to match against the patterns. */
964 wordtail = &wordhead;
965 while ((p = find_next_token (&word_iterator, &len)) != 0)
967 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
969 *wordtail = word;
970 wordtail = &word->next;
972 if (*word_iterator != '\0')
973 ++word_iterator;
975 p[len] = '\0';
976 word->str = p;
977 word->length = len;
978 word->matched = 0;
979 word->chain = 0;
980 words++;
982 *wordtail = 0;
984 /* Only use a hash table if arg list lengths justifies the cost. */
985 hashing = (literals >= 2 && (literals * words) >= 10);
986 if (hashing)
988 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
989 for (wp = wordhead; wp != 0; wp = wp->next)
991 struct a_word *owp = hash_insert (&a_word_table, wp);
992 if (owp)
993 wp->chain = owp;
997 if (words)
999 int doneany = 0;
1001 /* Run each pattern through the words, killing words. */
1002 for (pp = pathead; pp != 0; pp = pp->next)
1004 if (pp->percent)
1005 for (wp = wordhead; wp != 0; wp = wp->next)
1006 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1007 else if (hashing)
1009 struct a_word a_word_key;
1010 a_word_key.str = pp->str;
1011 a_word_key.length = pp->length;
1012 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1013 while (wp)
1015 wp->matched |= 1;
1016 wp = wp->chain;
1019 else
1020 for (wp = wordhead; wp != 0; wp = wp->next)
1021 wp->matched |= (wp->length == pp->length
1022 && strneq (pp->str, wp->str, wp->length));
1025 /* Output the words that matched (or didn't, for filter-out). */
1026 for (wp = wordhead; wp != 0; wp = wp->next)
1027 if (is_filter ? wp->matched : !wp->matched)
1029 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1030 o = variable_buffer_output (o, " ", 1);
1031 doneany = 1;
1034 if (doneany)
1035 /* Kill the last space. */
1036 --o;
1039 for (pp = pathead; pp != 0; pp = pp->next)
1040 pp->str[pp->length] = pp->save_c;
1042 if (hashing)
1043 hash_free (&a_word_table, 0);
1045 return o;
1049 static char *
1050 func_strip (char *o, char **argv, const char *funcname UNUSED)
1052 char *p = argv[0];
1053 int doneany =0;
1055 while (*p != '\0')
1057 int i=0;
1058 char *word_start=0;
1060 while (isspace ((unsigned char)*p))
1061 ++p;
1062 word_start = p;
1063 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1065 if (!i)
1066 break;
1067 o = variable_buffer_output (o, word_start, i);
1068 o = variable_buffer_output (o, " ", 1);
1069 doneany = 1;
1072 if (doneany)
1073 /* Kill the last space. */
1074 --o;
1075 return o;
1079 Print a warning or fatal message.
1081 static char *
1082 func_error (char *o, char **argv, const char *funcname)
1084 char **argvp;
1085 char *msg, *p;
1086 int len;
1088 /* The arguments will be broken on commas. Rather than create yet
1089 another special case where function arguments aren't broken up,
1090 just create a format string that puts them back together. */
1091 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1092 len += strlen (*argvp) + 2;
1094 p = msg = (char *) alloca (len + 1);
1096 for (argvp=argv; argvp[1] != 0; ++argvp)
1098 strcpy (p, *argvp);
1099 p += strlen (*argvp);
1100 *(p++) = ',';
1101 *(p++) = ' ';
1103 strcpy (p, *argvp);
1105 switch (*funcname) {
1106 case 'e':
1107 fatal (reading_file, "%s", msg);
1109 case 'w':
1110 error (reading_file, "%s", msg);
1111 break;
1113 case 'i':
1114 printf ("%s\n", msg);
1115 fflush(stdout);
1116 break;
1118 default:
1119 fatal (reading_file, "Internal error: func_error: '%s'", funcname);
1122 /* The warning function expands to the empty string. */
1123 return o;
1128 chop argv[0] into words, and sort them.
1130 static char *
1131 func_sort (char *o, char **argv, const char *funcname UNUSED)
1133 char **words = 0;
1134 int nwords = 0;
1135 register int wordi = 0;
1137 /* Chop ARGV[0] into words and put them in WORDS. */
1138 char *t = argv[0];
1139 char *p;
1140 unsigned int len;
1141 int i;
1143 while ((p = find_next_token (&t, &len)) != 0)
1145 if (wordi >= nwords - 1)
1147 nwords = (2 * nwords) + 5;
1148 words = (char **) xrealloc ((char *) words,
1149 nwords * sizeof (char *));
1151 words[wordi++] = savestring (p, len);
1154 if (!wordi)
1155 return o;
1157 /* Now sort the list of words. */
1158 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1160 /* Now write the sorted list. */
1161 for (i = 0; i < wordi; ++i)
1163 len = strlen (words[i]);
1164 if (i == wordi - 1 || strlen (words[i + 1]) != len
1165 || strcmp (words[i], words[i + 1]))
1167 o = variable_buffer_output (o, words[i], len);
1168 o = variable_buffer_output (o, " ", 1);
1170 free (words[i]);
1172 /* Kill the last space. */
1173 --o;
1175 free (words);
1177 return o;
1181 $(if condition,true-part[,false-part])
1183 CONDITION is false iff it evaluates to an empty string. White
1184 space before and after condition are stripped before evaluation.
1186 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1187 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1188 you can use $(if ...) to create side-effects (with $(shell ...), for
1189 example).
1192 static char *
1193 func_if (char *o, char **argv, const char *funcname UNUSED)
1195 const char *begp = argv[0];
1196 const char *endp = begp + strlen (argv[0]) - 1;
1197 int result = 0;
1199 /* Find the result of the condition: if we have a value, and it's not
1200 empty, the condition is true. If we don't have a value, or it's the
1201 empty string, then it's false. */
1203 strip_whitespace (&begp, &endp);
1205 if (begp <= endp)
1207 char *expansion = expand_argument (begp, endp+1);
1209 result = strlen (expansion);
1210 free (expansion);
1213 /* If the result is true (1) we want to eval the first argument, and if
1214 it's false (0) we want to eval the second. If the argument doesn't
1215 exist we do nothing, otherwise expand it and add to the buffer. */
1217 argv += 1 + !result;
1219 if (argv[0])
1221 char *expansion;
1223 expansion = expand_argument (argv[0], NULL);
1225 o = variable_buffer_output (o, expansion, strlen (expansion));
1227 free (expansion);
1230 return o;
1233 static char *
1234 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1237 #ifdef _AMIGA
1238 o = wildcard_expansion (argv[0], o);
1239 #else
1240 char *p = string_glob (argv[0]);
1241 o = variable_buffer_output (o, p, strlen (p));
1242 #endif
1243 return o;
1247 $(eval <makefile string>)
1249 Always resolves to the empty string.
1251 Treat the arguments as a segment of makefile, and parse them.
1254 static char *
1255 func_eval (char *o, char **argv, const char *funcname UNUSED)
1257 char *buf;
1258 unsigned int len;
1260 /* Eval the buffer. Pop the current variable buffer setting so that the
1261 eval'd code can use its own without conflicting. */
1263 install_variable_buffer (&buf, &len);
1265 eval_buffer (argv[0]);
1267 restore_variable_buffer (buf, len);
1269 return o;
1273 static char *
1274 func_value (char *o, char **argv, const char *funcname UNUSED)
1276 /* Look up the variable. */
1277 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1279 /* Copy its value into the output buffer without expanding it. */
1280 if (v)
1281 o = variable_buffer_output (o, v->value, strlen(v->value));
1283 return o;
1287 \r is replaced on UNIX as well. Is this desirable?
1289 void
1290 fold_newlines (char *buffer, int *length)
1292 char *dst = buffer;
1293 char *src = buffer;
1294 char *last_nonnl = buffer -1;
1295 src[*length] = 0;
1296 for (; *src != '\0'; ++src)
1298 if (src[0] == '\r' && src[1] == '\n')
1299 continue;
1300 if (*src == '\n')
1302 *dst++ = ' ';
1304 else
1306 last_nonnl = dst;
1307 *dst++ = *src;
1310 *(++last_nonnl) = '\0';
1311 *length = last_nonnl - buffer;
1316 int shell_function_pid = 0, shell_function_completed;
1319 #ifdef WINDOWS32
1320 /*untested*/
1322 #include <windows.h>
1323 #include <io.h>
1324 #include "sub_proc.h"
1327 void
1328 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1330 SECURITY_ATTRIBUTES saAttr;
1331 HANDLE hIn;
1332 HANDLE hErr;
1333 HANDLE hChildOutRd;
1334 HANDLE hChildOutWr;
1335 HANDLE hProcess;
1338 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1339 saAttr.bInheritHandle = TRUE;
1340 saAttr.lpSecurityDescriptor = NULL;
1342 if (DuplicateHandle (GetCurrentProcess(),
1343 GetStdHandle(STD_INPUT_HANDLE),
1344 GetCurrentProcess(),
1345 &hIn,
1347 TRUE,
1348 DUPLICATE_SAME_ACCESS) == FALSE) {
1349 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1350 GetLastError());
1353 if (DuplicateHandle(GetCurrentProcess(),
1354 GetStdHandle(STD_ERROR_HANDLE),
1355 GetCurrentProcess(),
1356 &hErr,
1358 TRUE,
1359 DUPLICATE_SAME_ACCESS) == FALSE) {
1360 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1361 GetLastError());
1364 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1365 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1367 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1369 if (!hProcess)
1370 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1372 /* make sure that CreateProcess() has Path it needs */
1373 sync_Path_environment();
1375 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1376 /* register process for wait */
1377 process_register(hProcess);
1379 /* set the pid for returning to caller */
1380 *pid_p = (int) hProcess;
1382 /* set up to read data from child */
1383 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1385 /* this will be closed almost right away */
1386 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1387 } else {
1388 /* reap/cleanup the failed process */
1389 process_cleanup(hProcess);
1391 /* close handles which were duplicated, they weren't used */
1392 CloseHandle(hIn);
1393 CloseHandle(hErr);
1395 /* close pipe handles, they won't be used */
1396 CloseHandle(hChildOutRd);
1397 CloseHandle(hChildOutWr);
1399 /* set status for return */
1400 pipedes[0] = pipedes[1] = -1;
1401 *pid_p = -1;
1404 #endif
1407 #ifdef __MSDOS__
1408 FILE *
1409 msdos_openpipe (int* pipedes, int *pidp, char *text)
1411 FILE *fpipe=0;
1412 /* MSDOS can't fork, but it has `popen'. */
1413 struct variable *sh = lookup_variable ("SHELL", 5);
1414 int e;
1415 extern int dos_command_running, dos_status;
1417 /* Make sure not to bother processing an empty line. */
1418 while (isblank ((unsigned char)*text))
1419 ++text;
1420 if (*text == '\0')
1421 return 0;
1423 if (sh)
1425 char buf[PATH_MAX + 7];
1426 /* This makes sure $SHELL value is used by $(shell), even
1427 though the target environment is not passed to it. */
1428 sprintf (buf, "SHELL=%s", sh->value);
1429 putenv (buf);
1432 e = errno;
1433 errno = 0;
1434 dos_command_running = 1;
1435 dos_status = 0;
1436 /* If dos_status becomes non-zero, it means the child process
1437 was interrupted by a signal, like SIGINT or SIGQUIT. See
1438 fatal_error_signal in commands.c. */
1439 fpipe = popen (text, "rt");
1440 dos_command_running = 0;
1441 if (!fpipe || dos_status)
1443 pipedes[0] = -1;
1444 *pidp = -1;
1445 if (dos_status)
1446 errno = EINTR;
1447 else if (errno == 0)
1448 errno = ENOMEM;
1449 shell_function_completed = -1;
1451 else
1453 pipedes[0] = fileno (fpipe);
1454 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1455 errno = e;
1456 shell_function_completed = 1;
1458 return fpipe;
1460 #endif
1463 Do shell spawning, with the naughty bits for different OSes.
1466 #ifdef VMS
1468 /* VMS can't do $(shell ...) */
1469 #define func_shell 0
1471 #else
1472 #ifndef _AMIGA
1473 static char *
1474 func_shell (char *o, char **argv, const char *funcname UNUSED)
1476 char* batch_filename = NULL;
1477 unsigned int i;
1479 #ifdef __MSDOS__
1480 FILE *fpipe;
1481 #endif
1482 char **command_argv;
1483 char *error_prefix;
1484 char **envp;
1485 int pipedes[2];
1486 int pid;
1488 #ifndef __MSDOS__
1489 /* Construct the argument list. */
1490 command_argv = construct_command_argv (argv[0],
1491 (char **) NULL, (struct file *) 0,
1492 &batch_filename);
1493 if (command_argv == 0)
1494 return o;
1495 #endif
1497 /* Using a target environment for `shell' loses in cases like:
1498 export var = $(shell echo foobie)
1499 because target_environment hits a loop trying to expand $(var)
1500 to put it in the environment. This is even more confusing when
1501 var was not explicitly exported, but just appeared in the
1502 calling environment.
1504 envp = target_environment (NILF);
1507 envp = environ;
1509 /* For error messages. */
1510 if (reading_file && reading_file->filenm)
1512 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1513 sprintf (error_prefix,
1514 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1516 else
1517 error_prefix = "";
1519 #ifdef WINDOWS32
1521 windows32_openpipe (pipedes, &pid, command_argv, envp);
1523 if (pipedes[0] < 0) {
1524 /* open of the pipe failed, mark as failed execution */
1525 shell_function_completed = -1;
1527 return o;
1528 } else
1530 #elif defined(__MSDOS__)
1532 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1533 if (pipedes[0] < 0)
1535 perror_with_name (error_prefix, "pipe");
1536 return o;
1539 #else
1541 if (pipe (pipedes) < 0)
1543 perror_with_name (error_prefix, "pipe");
1544 return o;
1547 # ifdef __EMX__
1549 /* close some handles that are unnecessary for the child process */
1550 CLOSE_ON_EXEC(pipedes[1]);
1551 CLOSE_ON_EXEC(pipedes[0]);
1552 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1553 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1554 if (pid < 0)
1555 perror_with_name (error_prefix, "spawn");
1557 # else /* ! __EMX__ */
1559 pid = vfork ();
1560 if (pid < 0)
1561 perror_with_name (error_prefix, "fork");
1562 else if (pid == 0)
1563 child_execute_job (0, pipedes[1], command_argv, envp);
1564 else
1566 # endif
1568 #endif
1570 /* We are the parent. */
1572 char *buffer;
1573 unsigned int maxlen;
1574 int cc;
1576 /* Record the PID for reap_children. */
1577 shell_function_pid = pid;
1578 #ifndef __MSDOS__
1579 shell_function_completed = 0;
1581 /* Free the storage only the child needed. */
1582 free (command_argv[0]);
1583 free ((char *) command_argv);
1585 /* Close the write side of the pipe. */
1586 (void) close (pipedes[1]);
1587 #endif
1589 /* Set up and read from the pipe. */
1591 maxlen = 200;
1592 buffer = (char *) xmalloc (maxlen + 1);
1594 /* Read from the pipe until it gets EOF. */
1595 for (i = 0; ; i += cc)
1597 if (i == maxlen)
1599 maxlen += 512;
1600 buffer = (char *) xrealloc (buffer, maxlen + 1);
1603 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1604 if (cc <= 0)
1605 break;
1607 buffer[i] = '\0';
1609 /* Close the read side of the pipe. */
1610 #ifdef __MSDOS__
1611 if (fpipe)
1612 (void) pclose (fpipe);
1613 #else
1614 (void) close (pipedes[0]);
1615 #endif
1617 /* Loop until child_handler or reap_children() sets
1618 shell_function_completed to the status of our child shell. */
1619 while (shell_function_completed == 0)
1620 reap_children (1, 0);
1622 if (batch_filename) {
1623 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1624 batch_filename));
1625 remove (batch_filename);
1626 free (batch_filename);
1628 shell_function_pid = 0;
1630 /* The child_handler function will set shell_function_completed
1631 to 1 when the child dies normally, or to -1 if it
1632 dies with status 127, which is most likely an exec fail. */
1634 if (shell_function_completed == -1)
1636 /* This most likely means that the execvp failed,
1637 so we should just write out the error message
1638 that came in over the pipe from the child. */
1639 fputs (buffer, stderr);
1640 fflush (stderr);
1642 else
1644 /* The child finished normally. Replace all
1645 newlines in its output with spaces, and put
1646 that in the variable output buffer. */
1647 fold_newlines (buffer, &i);
1648 o = variable_buffer_output (o, buffer, i);
1651 free (buffer);
1654 return o;
1657 #else /* _AMIGA */
1659 /* Do the Amiga version of func_shell. */
1661 static char *
1662 func_shell (char *o, char **argv, const char *funcname)
1664 /* Amiga can't fork nor spawn, but I can start a program with
1665 redirection of my choice. However, this means that we
1666 don't have an opportunity to reopen stdout to trap it. Thus,
1667 we save our own stdout onto a new descriptor and dup a temp
1668 file's descriptor onto our stdout temporarily. After we
1669 spawn the shell program, we dup our own stdout back to the
1670 stdout descriptor. The buffer reading is the same as above,
1671 except that we're now reading from a file. */
1673 #include <dos/dos.h>
1674 #include <proto/dos.h>
1676 BPTR child_stdout;
1677 char tmp_output[FILENAME_MAX];
1678 unsigned int maxlen = 200;
1679 int cc, i;
1680 char * buffer, * ptr;
1681 char ** aptr;
1682 int len = 0;
1683 char* batch_filename = NULL;
1685 /* Construct the argument list. */
1686 command_argv = construct_command_argv (argv[0], (char **) NULL,
1687 (struct file *) 0, &batch_filename);
1688 if (command_argv == 0)
1689 return o;
1691 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1692 Ideally we would use main.c:open_tmpfile(), but this uses a special
1693 Open(), not fopen(), and I'm not familiar enough with the code to mess
1694 with it. */
1695 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1696 mktemp (tmp_output);
1697 child_stdout = Open (tmp_output, MODE_NEWFILE);
1699 for (aptr=command_argv; *aptr; aptr++)
1700 len += strlen (*aptr) + 1;
1702 buffer = xmalloc (len + 1);
1703 ptr = buffer;
1705 for (aptr=command_argv; *aptr; aptr++)
1707 strcpy (ptr, *aptr);
1708 ptr += strlen (ptr) + 1;
1709 *ptr ++ = ' ';
1710 *ptr = 0;
1713 ptr[-1] = '\n';
1715 Execute (buffer, NULL, child_stdout);
1716 free (buffer);
1718 Close (child_stdout);
1720 child_stdout = Open (tmp_output, MODE_OLDFILE);
1722 buffer = xmalloc (maxlen);
1723 i = 0;
1726 if (i == maxlen)
1728 maxlen += 512;
1729 buffer = (char *) xrealloc (buffer, maxlen + 1);
1732 cc = Read (child_stdout, &buffer[i], maxlen - i);
1733 if (cc > 0)
1734 i += cc;
1735 } while (cc > 0);
1737 Close (child_stdout);
1739 fold_newlines (buffer, &i);
1740 o = variable_buffer_output (o, buffer, i);
1741 free (buffer);
1742 return o;
1744 #endif /* _AMIGA */
1745 #endif /* !VMS */
1747 #ifdef EXPERIMENTAL
1750 equality. Return is string-boolean, ie, the empty string is false.
1752 static char *
1753 func_eq (char *o, char **argv, char *funcname)
1755 int result = ! strcmp (argv[0], argv[1]);
1756 o = variable_buffer_output (o, result ? "1" : "", result);
1757 return o;
1762 string-boolean not operator.
1764 static char *
1765 func_not (char *o, char **argv, char *funcname)
1767 char *s = argv[0];
1768 int result = 0;
1769 while (isspace ((unsigned char)*s))
1770 s++;
1771 result = ! (*s);
1772 o = variable_buffer_output (o, result ? "1" : "", result);
1773 return o;
1775 #endif
1778 /* Return the absolute name of file NAME which does not contain any `.',
1779 `..' components nor any repeated path separators ('/'). */
1781 static char *
1782 abspath (const char *name, char *apath)
1784 char *dest;
1785 const char *start, *end, *apath_limit;
1787 if (name[0] == '\0' || apath == NULL)
1788 return NULL;
1790 apath_limit = apath + GET_PATH_MAX;
1792 if (name[0] != '/')
1794 /* It is unlikely we would make it until here but just to make sure. */
1795 if (!starting_directory)
1796 return NULL;
1798 strcpy (apath, starting_directory);
1800 dest = strchr (apath, '\0');
1802 else
1804 apath[0] = '/';
1805 dest = apath + 1;
1808 for (start = end = name; *start != '\0'; start = end)
1810 unsigned long len;
1812 /* Skip sequence of multiple path-separators. */
1813 while (*start == '/')
1814 ++start;
1816 /* Find end of path component. */
1817 for (end = start; *end != '\0' && *end != '/'; ++end)
1820 len = end - start;
1822 if (len == 0)
1823 break;
1824 else if (len == 1 && start[0] == '.')
1825 /* nothing */;
1826 else if (len == 2 && start[0] == '.' && start[1] == '.')
1828 /* Back up to previous component, ignore if at root already. */
1829 if (dest > apath + 1)
1830 while ((--dest)[-1] != '/');
1832 else
1834 if (dest[-1] != '/')
1835 *dest++ = '/';
1837 if (dest + len >= apath_limit)
1838 return NULL;
1840 dest = memcpy (dest, start, len);
1841 dest += len;
1842 *dest = '\0';
1846 /* Unless it is root strip trailing separator. */
1847 if (dest > apath + 1 && dest[-1] == '/')
1848 --dest;
1850 *dest = '\0';
1852 return apath;
1856 static char *
1857 func_realpath (char *o, char **argv, const char *funcname UNUSED)
1859 /* Expand the argument. */
1860 char *p = argv[0];
1861 char *path = 0;
1862 int doneany = 0;
1863 unsigned int len = 0;
1864 PATH_VAR (in);
1865 PATH_VAR (out);
1867 while ((path = find_next_token (&p, &len)) != 0)
1869 if (len < GET_PATH_MAX)
1871 strncpy (in, path, len);
1872 in[len] = '\0';
1876 #ifdef HAVE_REALPATH
1877 realpath (in, out)
1878 #else
1879 abspath (in, out)
1880 #endif
1883 o = variable_buffer_output (o, out, strlen (out));
1884 o = variable_buffer_output (o, " ", 1);
1885 doneany = 1;
1890 /* Kill last space. */
1891 if (doneany)
1892 --o;
1894 return o;
1897 static char *
1898 func_abspath (char *o, char **argv, const char *funcname UNUSED)
1900 /* Expand the argument. */
1901 char *p = argv[0];
1902 char *path = 0;
1903 int doneany = 0;
1904 unsigned int len = 0;
1905 PATH_VAR (in);
1906 PATH_VAR (out);
1908 while ((path = find_next_token (&p, &len)) != 0)
1910 if (len < GET_PATH_MAX)
1912 strncpy (in, path, len);
1913 in[len] = '\0';
1915 if (abspath (in, out))
1917 o = variable_buffer_output (o, out, strlen (out));
1918 o = variable_buffer_output (o, " ", 1);
1919 doneany = 1;
1924 /* Kill last space. */
1925 if (doneany)
1926 --o;
1928 return o;
1931 /* Lookup table for builtin functions.
1933 This doesn't have to be sorted; we use a straight lookup. We might gain
1934 some efficiency by moving most often used functions to the start of the
1935 table.
1937 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1938 comma-separated values are treated as arguments.
1940 EXPAND_ARGS means that all arguments should be expanded before invocation.
1941 Functions that do namespace tricks (foreach) don't automatically expand. */
1943 static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
1946 static struct function_table_entry function_table_init[] =
1948 /* Name/size */ /* MIN MAX EXP? Function */
1949 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
1950 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
1951 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
1952 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
1953 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
1954 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
1955 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
1956 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
1957 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
1958 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
1959 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
1960 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
1961 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
1962 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
1963 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
1964 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
1965 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
1966 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
1967 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
1968 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
1969 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
1970 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
1971 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
1972 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
1973 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
1974 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
1975 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
1976 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
1977 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
1978 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
1979 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
1980 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
1981 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
1982 #ifdef EXPERIMENTAL
1983 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
1984 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
1985 #endif
1988 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1991 /* These must come after the definition of function_table. */
1993 static char *
1994 expand_builtin_function (char *o, int argc, char **argv,
1995 const struct function_table_entry *entry_p)
1997 if (argc < (int)entry_p->minimum_args)
1998 fatal (reading_file,
1999 _("Insufficient number of arguments (%d) to function `%s'"),
2000 argc, entry_p->name);
2002 /* I suppose technically some function could do something with no
2003 arguments, but so far none do, so just test it for all functions here
2004 rather than in each one. We can change it later if necessary. */
2006 if (!argc)
2007 return o;
2009 if (!entry_p->func_ptr)
2010 fatal (reading_file, _("Unimplemented on this platform: function `%s'"),
2011 entry_p->name);
2013 return entry_p->func_ptr (o, argv, entry_p->name);
2016 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2017 opening ( or { and is not null-terminated. If a function invocation
2018 is found, expand it into the buffer at *OP, updating *OP, incrementing
2019 *STRINGP past the reference and returning nonzero. If not, return zero. */
2022 handle_function (char **op, char **stringp)
2024 const struct function_table_entry *entry_p;
2025 char openparen = (*stringp)[0];
2026 char closeparen = openparen == '(' ? ')' : '}';
2027 char *beg;
2028 char *end;
2029 int count = 0;
2030 register char *p;
2031 char **argv, **argvp;
2032 int nargs;
2034 beg = *stringp + 1;
2036 entry_p = lookup_function (beg);
2038 if (!entry_p)
2039 return 0;
2041 /* We found a builtin function. Find the beginning of its arguments (skip
2042 whitespace after the name). */
2044 beg = next_token (beg + entry_p->len);
2046 /* Find the end of the function invocation, counting nested use of
2047 whichever kind of parens we use. Since we're looking, count commas
2048 to get a rough estimate of how many arguments we might have. The
2049 count might be high, but it'll never be low. */
2051 for (nargs=1, end=beg; *end != '\0'; ++end)
2052 if (*end == ',')
2053 ++nargs;
2054 else if (*end == openparen)
2055 ++count;
2056 else if (*end == closeparen && --count < 0)
2057 break;
2059 if (count >= 0)
2060 fatal (reading_file,
2061 _("unterminated call to function `%s': missing `%c'"),
2062 entry_p->name, closeparen);
2064 *stringp = end;
2066 /* Get some memory to store the arg pointers. */
2067 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
2069 /* Chop the string into arguments, then a nul. As soon as we hit
2070 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2071 last argument.
2073 If we're expanding, store pointers to the expansion of each one. If
2074 not, make a duplicate of the string and point into that, nul-terminating
2075 each argument. */
2077 if (!entry_p->expand_args)
2079 int len = end - beg;
2081 p = xmalloc (len+1);
2082 memcpy (p, beg, len);
2083 p[len] = '\0';
2084 beg = p;
2085 end = beg + len;
2088 for (p=beg, nargs=0; p <= end; ++argvp)
2090 char *next;
2092 ++nargs;
2094 if (nargs == entry_p->maximum_args
2095 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2096 next = end;
2098 if (entry_p->expand_args)
2099 *argvp = expand_argument (p, next);
2100 else
2102 *argvp = p;
2103 *next = '\0';
2106 p = next + 1;
2108 *argvp = NULL;
2110 /* Finally! Run the function... */
2111 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2113 /* Free memory. */
2114 if (entry_p->expand_args)
2115 for (argvp=argv; *argvp != 0; ++argvp)
2116 free (*argvp);
2117 else
2118 free (beg);
2120 return 1;
2124 /* User-defined functions. Expand the first argument as either a builtin
2125 function or a make variable, in the context of the rest of the arguments
2126 assigned to $1, $2, ... $N. $0 is the name of the function. */
2128 static char *
2129 func_call (char *o, char **argv, const char *funcname UNUSED)
2131 static int max_args = 0;
2132 char *fname;
2133 char *cp;
2134 char *body;
2135 int flen;
2136 int i;
2137 int saved_args;
2138 const struct function_table_entry *entry_p;
2139 struct variable *v;
2141 /* There is no way to define a variable with a space in the name, so strip
2142 leading and trailing whitespace as a favor to the user. */
2143 fname = argv[0];
2144 while (*fname != '\0' && isspace ((unsigned char)*fname))
2145 ++fname;
2147 cp = fname + strlen (fname) - 1;
2148 while (cp > fname && isspace ((unsigned char)*cp))
2149 --cp;
2150 cp[1] = '\0';
2152 /* Calling nothing is a no-op */
2153 if (*fname == '\0')
2154 return o;
2156 /* Are we invoking a builtin function? */
2158 entry_p = lookup_function (fname);
2160 if (entry_p)
2162 /* How many arguments do we have? */
2163 for (i=0; argv[i+1]; ++i)
2166 return expand_builtin_function (o, i, argv+1, entry_p);
2169 /* Not a builtin, so the first argument is the name of a variable to be
2170 expanded and interpreted as a function. Find it. */
2171 flen = strlen (fname);
2173 v = lookup_variable (fname, flen);
2175 if (v == 0)
2176 warn_undefined (fname, flen);
2178 if (v == 0 || *v->value == '\0')
2179 return o;
2181 body = (char *) alloca (flen + 4);
2182 body[0] = '$';
2183 body[1] = '(';
2184 memcpy (body + 2, fname, flen);
2185 body[flen+2] = ')';
2186 body[flen+3] = '\0';
2188 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2190 push_new_variable_scope ();
2192 for (i=0; *argv; ++i, ++argv)
2194 char num[11];
2196 sprintf (num, "%d", i);
2197 define_variable (num, strlen (num), *argv, o_automatic, 0);
2200 /* If the number of arguments we have is < max_args, it means we're inside
2201 a recursive invocation of $(call ...). Fill in the remaining arguments
2202 in the new scope with the empty value, to hide them from this
2203 invocation. */
2205 for (; i < max_args; ++i)
2207 char num[11];
2209 sprintf (num, "%d", i);
2210 define_variable (num, strlen (num), "", o_automatic, 0);
2213 /* Expand the body in the context of the arguments, adding the result to
2214 the variable buffer. */
2216 v->exp_count = EXP_COUNT_MAX;
2218 saved_args = max_args;
2219 max_args = i;
2220 o = variable_expand_string (o, body, flen+3);
2221 max_args = saved_args;
2223 v->exp_count = 0;
2225 pop_variable_scope ();
2227 return o + strlen (o);
2230 void
2231 hash_init_function_table (void)
2233 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2234 function_table_entry_hash_1, function_table_entry_hash_2,
2235 function_table_entry_hash_cmp);
2236 hash_load (&function_table, function_table_init,
2237 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));