1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
4 2012 Free Software Foundation, Inc.
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
32 struct function_table_entry
36 unsigned char minimum_args
;
37 unsigned char maximum_args
;
39 char *(*func_ptr
) (char *output
, char **argv
, const char *fname
);
43 function_table_entry_hash_1 (const void *keyv
)
45 const struct function_table_entry
*key
= keyv
;
46 return_STRING_N_HASH_1 (key
->name
, key
->len
);
50 function_table_entry_hash_2 (const void *keyv
)
52 const struct function_table_entry
*key
= keyv
;
53 return_STRING_N_HASH_2 (key
->name
, key
->len
);
57 function_table_entry_hash_cmp (const void *xv
, const void *yv
)
59 const struct function_table_entry
*x
= xv
;
60 const struct function_table_entry
*y
= yv
;
61 int result
= x
->len
- y
->len
;
64 return_STRING_N_COMPARE (x
->name
, y
->name
, x
->len
);
67 static struct hash_table function_table
;
70 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
71 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
72 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
73 nonzero, substitutions are done only on matches which are complete
74 whitespace-delimited words. */
77 subst_expand (char *o
, const char *text
, const char *subst
, const char *replace
,
78 unsigned int slen
, unsigned int rlen
, int by_word
)
83 if (slen
== 0 && !by_word
)
85 /* The first occurrence of "" in any string is its end. */
86 o
= variable_buffer_output (o
, t
, strlen (t
));
88 o
= variable_buffer_output (o
, replace
, rlen
);
94 if (by_word
&& slen
== 0)
95 /* When matching by words, the empty string should match
96 the end of each word, rather than the end of the whole text. */
97 p
= end_of_token (next_token (t
));
100 p
= strstr (t
, subst
);
103 /* No more matches. Output everything left on the end. */
104 o
= variable_buffer_output (o
, t
, strlen (t
));
109 /* Output everything before this occurrence of the string to replace. */
111 o
= variable_buffer_output (o
, t
, p
- t
);
113 /* If we're substituting only by fully matched words,
114 or only at the ends of words, check that this case qualifies. */
116 && ((p
> text
&& !isblank ((unsigned char)p
[-1]))
117 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
118 /* Struck out. Output the rest of the string that is
119 no longer to be replaced. */
120 o
= variable_buffer_output (o
, subst
, slen
);
122 /* Output the replacement string. */
123 o
= variable_buffer_output (o
, replace
, rlen
);
125 /* Advance T past the string to be replaced. */
127 } while (*t
!= '\0');
133 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
134 and replacing strings matching PATTERN with REPLACE.
135 If PATTERN_PERCENT is not nil, PATTERN has already been
136 run through find_percent, and PATTERN_PERCENT is the result.
137 If REPLACE_PERCENT is not nil, REPLACE has already been
138 run through find_percent, and REPLACE_PERCENT is the result.
139 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
140 character _AFTER_ the %, not to the % itself.
144 patsubst_expand_pat (char *o
, const char *text
,
145 const char *pattern
, const char *replace
,
146 const char *pattern_percent
, const char *replace_percent
)
148 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
149 unsigned int replace_prepercent_len
, replace_postpercent_len
;
154 /* Record the length of REPLACE before and after the % so we don't have to
155 compute these lengths more than once. */
158 replace_prepercent_len
= replace_percent
- replace
- 1;
159 replace_postpercent_len
= strlen (replace_percent
);
163 replace_prepercent_len
= strlen (replace
);
164 replace_postpercent_len
= 0;
167 if (!pattern_percent
)
168 /* With no % in the pattern, this is just a simple substitution. */
169 return subst_expand (o
, text
, pattern
, replace
,
170 strlen (pattern
), strlen (replace
), 1);
172 /* Record the length of PATTERN before and after the %
173 so we don't have to compute it more than once. */
174 pattern_prepercent_len
= pattern_percent
- pattern
- 1;
175 pattern_postpercent_len
= strlen (pattern_percent
);
177 while ((t
= find_next_token (&text
, &len
)) != 0)
181 /* Is it big enough to match? */
182 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
185 /* Does the prefix match? */
186 if (!fail
&& pattern_prepercent_len
> 0
188 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-2]
189 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
192 /* Does the suffix match? */
193 if (!fail
&& pattern_postpercent_len
> 0
194 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
- 1]
195 || t
[len
- pattern_postpercent_len
] != *pattern_percent
196 || !strneq (&t
[len
- pattern_postpercent_len
],
197 pattern_percent
, pattern_postpercent_len
- 1)))
201 /* It didn't match. Output the string. */
202 o
= variable_buffer_output (o
, t
, len
);
205 /* It matched. Output the replacement. */
207 /* Output the part of the replacement before the %. */
208 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
210 if (replace_percent
!= 0)
212 /* Output the part of the matched string that
213 matched the % in the pattern. */
214 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
215 len
- (pattern_prepercent_len
216 + pattern_postpercent_len
));
217 /* Output the part of the replacement after the %. */
218 o
= variable_buffer_output (o
, replace_percent
,
219 replace_postpercent_len
);
223 /* Output a space, but not if the replacement is "". */
224 if (fail
|| replace_prepercent_len
> 0
225 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
227 o
= variable_buffer_output (o
, " ", 1);
232 /* Kill the last space. */
238 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
239 and replacing strings matching PATTERN with REPLACE.
240 If PATTERN_PERCENT is not nil, PATTERN has already been
241 run through find_percent, and PATTERN_PERCENT is the result.
242 If REPLACE_PERCENT is not nil, REPLACE has already been
243 run through find_percent, and REPLACE_PERCENT is the result.
244 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
245 character _AFTER_ the %, not to the % itself.
249 patsubst_expand (char *o
, const char *text
, char *pattern
, char *replace
)
251 const char *pattern_percent
= find_percent (pattern
);
252 const char *replace_percent
= find_percent (replace
);
254 /* If there's a percent in the pattern or replacement skip it. */
260 return patsubst_expand_pat (o
, text
, pattern
, replace
,
261 pattern_percent
, replace_percent
);
265 /* Look up a function by name. */
267 static const struct function_table_entry
*
268 lookup_function (const char *s
)
272 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
274 if (*e
== '\0' || isblank ((unsigned char) *e
))
276 struct function_table_entry function_table_entry_key
;
277 function_table_entry_key
.name
= s
;
278 function_table_entry_key
.len
= e
- s
;
280 return hash_find_item (&function_table
, &function_table_entry_key
);
286 /* Return 1 if PATTERN matches STR, 0 if not. */
289 pattern_matches (const char *pattern
, const char *percent
, const char *str
)
291 unsigned int sfxlen
, strlength
;
295 unsigned int len
= strlen (pattern
) + 1;
296 char *new_chars
= alloca (len
);
297 memcpy (new_chars
, pattern
, len
);
298 percent
= find_percent (new_chars
);
300 return streq (new_chars
, str
);
304 sfxlen
= strlen (percent
+ 1);
305 strlength
= strlen (str
);
307 if (strlength
< (percent
- pattern
) + sfxlen
308 || !strneq (pattern
, str
, percent
- pattern
))
311 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
315 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
316 ENDPARENtheses), starting at PTR before END. Return a pointer to
319 If no next argument is found, return NULL.
323 find_next_argument (char startparen
, char endparen
,
324 const char *ptr
, const char *end
)
328 for (; ptr
< end
; ++ptr
)
329 if (*ptr
== startparen
)
332 else if (*ptr
== endparen
)
339 else if (*ptr
== ',' && !count
)
342 /* We didn't find anything. */
347 /* Glob-expand LINE. The returned pointer is
348 only good until the next call to string_glob. */
351 string_glob (char *line
)
353 static char *result
= 0;
354 static unsigned int length
;
355 struct nameseq
*chain
;
358 chain
= PARSE_FILE_SEQ (&line
, struct nameseq
, '\0', NULL
,
359 /* We do not want parse_file_seq to strip `./'s.
360 That would break examples like:
361 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
362 PARSEFS_NOSTRIP
|PARSEFS_NOCACHE
|PARSEFS_EXISTS
);
367 result
= xmalloc (100);
373 struct nameseq
*next
= chain
->next
;
374 unsigned int len
= strlen (chain
->name
);
376 if (idx
+ len
+ 1 > length
)
378 length
+= (len
+ 1) * 2;
379 result
= xrealloc (result
, length
);
381 memcpy (&result
[idx
], chain
->name
, len
);
385 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
386 free ((char *)chain
->name
);
391 /* Kill the last space and terminate the string. */
395 result
[idx
- 1] = '\0';
405 func_patsubst (char *o
, char **argv
, const char *funcname UNUSED
)
407 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1]);
413 func_join (char *o
, char **argv
, const char *funcname UNUSED
)
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. */
423 const char *list1_iterator
= argv
[0];
424 const char *list2_iterator
= argv
[1];
427 unsigned int len1
, len2
;
429 tp
= find_next_token (&list1_iterator
, &len1
);
431 o
= variable_buffer_output (o
, tp
, len1
);
433 pp
= find_next_token (&list2_iterator
, &len2
);
435 o
= variable_buffer_output (o
, pp
, len2
);
437 if (tp
!= 0 || pp
!= 0)
439 o
= variable_buffer_output (o
, " ", 1);
443 while (tp
!= 0 || pp
!= 0);
445 /* Kill the last blank. */
453 func_origin (char *o
, char **argv
, const char *funcname UNUSED
)
455 /* Expand the argument. */
456 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
458 o
= variable_buffer_output (o
, "undefined", 9);
467 o
= variable_buffer_output (o
, "default", 7);
470 o
= variable_buffer_output (o
, "environment", 11);
473 o
= variable_buffer_output (o
, "file", 4);
476 o
= variable_buffer_output (o
, "environment override", 20);
479 o
= variable_buffer_output (o
, "command line", 12);
482 o
= variable_buffer_output (o
, "override", 8);
485 o
= variable_buffer_output (o
, "automatic", 9);
493 func_flavor (char *o
, char **argv
, const char *funcname UNUSED
)
495 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
498 o
= variable_buffer_output (o
, "undefined", 9);
501 o
= variable_buffer_output (o
, "recursive", 9);
503 o
= variable_buffer_output (o
, "simple", 6);
509 # define IS_PATHSEP(c) ((c) == ']')
511 # ifdef HAVE_DOS_PATHS
512 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
514 # define IS_PATHSEP(c) ((c) == '/')
520 func_notdir_suffix (char *o
, char **argv
, const char *funcname
)
522 /* Expand the argument. */
523 const char *list_iterator
= argv
[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 const char *p
= p2
+ len
;
535 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
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] == ':')
555 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
559 o
= variable_buffer_output (o
, p2
, len
);
561 if (is_notdir
|| p
>= p2
)
563 o
= variable_buffer_output (o
, " ", 1);
569 /* Kill last space. */
577 func_basename_dir (char *o
, char **argv
, const char *funcname
)
579 /* Expand the argument. */
580 const char *p3
= argv
[0];
585 int is_basename
= streq (funcname
, "basename");
586 int is_dir
= !is_basename
;
588 while ((p2
= find_next_token (&p3
, &len
)) != 0)
590 const char *p
= p2
+ len
;
591 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
598 if (p
>= p2
&& (is_dir
))
599 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
600 else if (p
>= p2
&& (*p
== '.'))
601 o
= variable_buffer_output (o
, p2
, p
- p2
);
602 #ifdef HAVE_DOS_PATHS
603 /* Handle the "d:foobar" case */
604 else if (p2
[0] && p2
[1] == ':' && is_dir
)
605 o
= variable_buffer_output (o
, p2
, 2);
609 o
= variable_buffer_output (o
, "[]", 2);
612 o
= variable_buffer_output (o
, "./", 2);
614 ; /* Just a nop... */
618 /* The entire name is the basename. */
619 o
= variable_buffer_output (o
, p2
, len
);
621 o
= variable_buffer_output (o
, " ", 1);
626 /* Kill last space. */
633 func_addsuffix_addprefix (char *o
, char **argv
, const char *funcname
)
635 int fixlen
= strlen (argv
[0]);
636 const char *list_iterator
= argv
[1];
637 int is_addprefix
= streq (funcname
, "addprefix");
638 int is_addsuffix
= !is_addprefix
;
644 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
647 o
= variable_buffer_output (o
, argv
[0], fixlen
);
648 o
= variable_buffer_output (o
, p
, len
);
650 o
= variable_buffer_output (o
, argv
[0], fixlen
);
651 o
= variable_buffer_output (o
, " ", 1);
656 /* Kill last space. */
663 func_subst (char *o
, char **argv
, const char *funcname UNUSED
)
665 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
666 strlen (argv
[1]), 0);
673 func_firstword (char *o
, char **argv
, const char *funcname UNUSED
)
676 const char *words
= argv
[0]; /* Use a temp variable for find_next_token */
677 const char *p
= find_next_token (&words
, &i
);
680 o
= variable_buffer_output (o
, p
, i
);
686 func_lastword (char *o
, char **argv
, const char *funcname UNUSED
)
689 const char *words
= argv
[0]; /* Use a temp variable for find_next_token */
690 const char *p
= NULL
;
693 while ((t
= find_next_token (&words
, &i
)))
697 o
= variable_buffer_output (o
, p
, i
);
703 func_words (char *o
, char **argv
, const char *funcname UNUSED
)
706 const char *word_iterator
= argv
[0];
709 while (find_next_token (&word_iterator
, NULL
) != 0)
712 sprintf (buf
, "%d", i
);
713 o
= variable_buffer_output (o
, buf
, strlen (buf
));
718 /* Set begpp to point to the first non-whitespace character of the string,
719 * and endpp to point to the last non-whitespace character of the string.
720 * If the string is empty or contains nothing but whitespace, endpp will be
724 strip_whitespace (const char **begpp
, const char **endpp
)
726 while (*begpp
<= *endpp
&& isspace ((unsigned char)**begpp
))
728 while (*endpp
>= *begpp
&& isspace ((unsigned char)**endpp
))
730 return (char *)*begpp
;
734 check_numeric (const char *s
, const char *msg
)
736 const char *end
= s
+ strlen (s
) - 1;
738 strip_whitespace (&s
, &end
);
740 for (; s
<= end
; ++s
)
741 if (!ISDIGIT (*s
)) /* ISDIGIT only evals its arg once: see make.h. */
744 if (s
<= end
|| end
- beg
< 0)
745 fatal (*expanding_var
, "%s: '%s'", msg
, beg
);
751 func_word (char *o
, char **argv
, const char *funcname UNUSED
)
757 /* Check the first argument. */
758 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
762 fatal (*expanding_var
,
763 _("first argument to `word' function must be greater than 0"));
766 while ((p
= find_next_token (&end_p
, 0)) != 0)
771 o
= variable_buffer_output (o
, p
, end_p
- p
);
777 func_wordlist (char *o
, char **argv
, const char *funcname UNUSED
)
781 /* Check the arguments. */
782 check_numeric (argv
[0],
783 _("non-numeric first argument to `wordlist' function"));
784 check_numeric (argv
[1],
785 _("non-numeric second argument to `wordlist' function"));
787 start
= atoi (argv
[0]);
789 fatal (*expanding_var
,
790 "invalid first argument to `wordlist' function: `%d'", start
);
792 count
= atoi (argv
[1]) - start
+ 1;
797 const char *end_p
= argv
[2];
799 /* Find the beginning of the "start"th word. */
800 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
805 /* Find the end of the "count"th word from start. */
806 while (--count
&& (find_next_token (&end_p
, 0) != 0))
809 /* Return the stuff in the middle. */
810 o
= variable_buffer_output (o
, p
, end_p
- p
);
818 func_findstring (char *o
, char **argv
, const char *funcname UNUSED
)
820 /* Find the first occurrence of the first string in the second. */
821 if (strstr (argv
[1], argv
[0]) != 0)
822 o
= variable_buffer_output (o
, argv
[0], strlen (argv
[0]));
828 func_foreach (char *o
, char **argv
, const char *funcname UNUSED
)
830 /* expand only the first two. */
831 char *varname
= expand_argument (argv
[0], NULL
);
832 char *list
= expand_argument (argv
[1], NULL
);
833 const char *body
= argv
[2];
836 const char *list_iterator
= list
;
839 struct variable
*var
;
841 push_new_variable_scope ();
842 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
844 /* loop through LIST, put the value in VAR and expand BODY */
845 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
850 var
->value
= xstrndup (p
, len
);
852 result
= allocated_variable_expand (body
);
854 o
= variable_buffer_output (o
, result
, strlen (result
));
855 o
= variable_buffer_output (o
, " ", 1);
861 /* Kill the last space. */
864 pop_variable_scope ();
874 struct a_word
*chain
;
881 a_word_hash_1 (const void *key
)
883 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
887 a_word_hash_2 (const void *key
)
889 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
893 a_word_hash_cmp (const void *x
, const void *y
)
895 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
898 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
899 ((struct a_word
const *) y
)->str
);
904 struct a_pattern
*next
;
912 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
914 struct a_word
*wordhead
;
915 struct a_word
**wordtail
;
917 struct a_pattern
*pathead
;
918 struct a_pattern
**pattail
;
919 struct a_pattern
*pp
;
921 struct hash_table a_word_table
;
922 int is_filter
= streq (funcname
, "filter");
923 const char *pat_iterator
= argv
[0];
924 const char *word_iterator
= argv
[1];
931 /* Chop ARGV[0] up into patterns to match against the words. */
934 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
936 struct a_pattern
*pat
= alloca (sizeof (struct a_pattern
));
939 pattail
= &pat
->next
;
941 if (*pat_iterator
!= '\0')
946 pat
->save_c
= p
[len
];
948 pat
->percent
= find_percent (p
);
949 if (pat
->percent
== 0)
954 /* Chop ARGV[1] up into words to match against the patterns. */
956 wordtail
= &wordhead
;
957 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
959 struct a_word
*word
= alloca (sizeof (struct a_word
));
962 wordtail
= &word
->next
;
964 if (*word_iterator
!= '\0')
976 /* Only use a hash table if arg list lengths justifies the cost. */
977 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
980 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
,
982 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
984 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
994 /* Run each pattern through the words, killing words. */
995 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
998 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
999 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
1002 struct a_word a_word_key
;
1003 a_word_key
.str
= pp
->str
;
1004 a_word_key
.length
= pp
->length
;
1005 wp
= hash_find_item (&a_word_table
, &a_word_key
);
1013 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1014 wp
->matched
|= (wp
->length
== pp
->length
1015 && strneq (pp
->str
, wp
->str
, wp
->length
));
1018 /* Output the words that matched (or didn't, for filter-out). */
1019 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1020 if (is_filter
? wp
->matched
: !wp
->matched
)
1022 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
1023 o
= variable_buffer_output (o
, " ", 1);
1028 /* Kill the last space. */
1032 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1033 pp
->str
[pp
->length
] = pp
->save_c
;
1036 hash_free (&a_word_table
, 0);
1043 func_strip (char *o
, char **argv
, const char *funcname UNUSED
)
1045 const char *p
= argv
[0];
1051 const char *word_start
;
1053 while (isspace ((unsigned char)*p
))
1056 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1060 o
= variable_buffer_output (o
, word_start
, i
);
1061 o
= variable_buffer_output (o
, " ", 1);
1066 /* Kill the last space. */
1073 Print a warning or fatal message.
1076 func_error (char *o
, char **argv
, const char *funcname
)
1082 /* The arguments will be broken on commas. Rather than create yet
1083 another special case where function arguments aren't broken up,
1084 just create a format string that puts them back together. */
1085 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1086 len
+= strlen (*argvp
) + 2;
1088 p
= msg
= alloca (len
+ 1);
1090 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1093 p
+= strlen (*argvp
);
1099 switch (*funcname
) {
1101 fatal (reading_file
, "%s", msg
);
1104 error (reading_file
, "%s", msg
);
1108 printf ("%s\n", msg
);
1113 fatal (*expanding_var
, "Internal error: func_error: '%s'", funcname
);
1116 /* The warning function expands to the empty string. */
1122 chop argv[0] into words, and sort them.
1125 func_sort (char *o
, char **argv
, const char *funcname UNUSED
)
1134 /* Find the maximum number of words we'll have. */
1137 while ((p
= find_next_token (&t
, NULL
)) != 0)
1143 words
= xmalloc ((wordi
== 0 ? 1 : wordi
) * sizeof (char *));
1145 /* Now assign pointers to each string in the array. */
1148 while ((p
= find_next_token (&t
, &len
)) != 0)
1157 /* Now sort the list of words. */
1158 qsort (words
, wordi
, sizeof (char *), alpha_compare
);
1160 /* Now write the sorted list, uniquified. */
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);
1172 /* Kill the last space. */
1182 $(if condition,true-part[,false-part])
1184 CONDITION is false iff it evaluates to an empty string. White
1185 space before and after condition are stripped before evaluation.
1187 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1188 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1189 you can use $(if ...) to create side-effects (with $(shell ...), for
1194 func_if (char *o
, char **argv
, const char *funcname UNUSED
)
1196 const char *begp
= argv
[0];
1197 const char *endp
= begp
+ strlen (argv
[0]) - 1;
1200 /* Find the result of the condition: if we have a value, and it's not
1201 empty, the condition is true. If we don't have a value, or it's the
1202 empty string, then it's false. */
1204 strip_whitespace (&begp
, &endp
);
1208 char *expansion
= expand_argument (begp
, endp
+1);
1210 result
= strlen (expansion
);
1214 /* If the result is true (1) we want to eval the first argument, and if
1215 it's false (0) we want to eval the second. If the argument doesn't
1216 exist we do nothing, otherwise expand it and add to the buffer. */
1218 argv
+= 1 + !result
;
1222 char *expansion
= expand_argument (*argv
, NULL
);
1224 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1233 $(or condition1[,condition2[,condition3[...]]])
1235 A CONDITION is false iff it evaluates to an empty string. White
1236 space before and after CONDITION are stripped before evaluation.
1238 CONDITION1 is evaluated. If it's true, then this is the result of
1239 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1240 the conditions are true, the expansion is the empty string.
1242 Once a CONDITION is true no further conditions are evaluated
1247 func_or (char *o
, char **argv
, const char *funcname UNUSED
)
1249 for ( ; *argv
; ++argv
)
1251 const char *begp
= *argv
;
1252 const char *endp
= begp
+ strlen (*argv
) - 1;
1256 /* Find the result of the condition: if it's false keep going. */
1258 strip_whitespace (&begp
, &endp
);
1263 expansion
= expand_argument (begp
, endp
+1);
1264 result
= strlen (expansion
);
1266 /* If the result is false keep going. */
1273 /* It's true! Keep this result and return. */
1274 o
= variable_buffer_output (o
, expansion
, result
);
1283 $(and condition1[,condition2[,condition3[...]]])
1285 A CONDITION is false iff it evaluates to an empty string. White
1286 space before and after CONDITION are stripped before evaluation.
1288 CONDITION1 is evaluated. If it's false, then this is the result of
1289 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1290 the conditions are true, the expansion is the result of the last condition.
1292 Once a CONDITION is false no further conditions are evaluated
1297 func_and (char *o
, char **argv
, const char *funcname UNUSED
)
1304 const char *begp
= *argv
;
1305 const char *endp
= begp
+ strlen (*argv
) - 1;
1307 /* An empty condition is always false. */
1308 strip_whitespace (&begp
, &endp
);
1312 expansion
= expand_argument (begp
, endp
+1);
1313 result
= strlen (expansion
);
1315 /* If the result is false, stop here: we're done. */
1319 /* Otherwise the result is true. If this is the last one, keep this
1320 result and quit. Otherwise go on to the next one! */
1326 o
= variable_buffer_output (o
, expansion
, result
);
1337 func_wildcard (char *o
, char **argv
, const char *funcname UNUSED
)
1340 o
= wildcard_expansion (argv
[0], o
);
1342 char *p
= string_glob (argv
[0]);
1343 o
= variable_buffer_output (o
, p
, strlen (p
));
1349 $(eval <makefile string>)
1351 Always resolves to the empty string.
1353 Treat the arguments as a segment of makefile, and parse them.
1357 func_eval (char *o
, char **argv
, const char *funcname UNUSED
)
1362 /* Eval the buffer. Pop the current variable buffer setting so that the
1363 eval'd code can use its own without conflicting. */
1365 install_variable_buffer (&buf
, &len
);
1367 eval_buffer (argv
[0]);
1369 restore_variable_buffer (buf
, len
);
1376 func_value (char *o
, char **argv
, const char *funcname UNUSED
)
1378 /* Look up the variable. */
1379 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1381 /* Copy its value into the output buffer without expanding it. */
1383 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1389 \r is replaced on UNIX as well. Is this desirable?
1392 fold_newlines (char *buffer
, unsigned int *length
, int trim_newlines
)
1396 char *last_nonnl
= buffer
- 1;
1398 for (; *src
!= '\0'; ++src
)
1400 if (src
[0] == '\r' && src
[1] == '\n')
1413 if (!trim_newlines
&& (last_nonnl
< (dst
- 2)))
1414 last_nonnl
= dst
- 2;
1416 *(++last_nonnl
) = '\0';
1417 *length
= last_nonnl
- buffer
;
1422 int shell_function_pid
= 0, shell_function_completed
;
1428 #include <windows.h>
1430 #include "sub_proc.h"
1434 windows32_openpipe (int *pipedes
, pid_t
*pid_p
, char **command_argv
, char **envp
)
1436 SECURITY_ATTRIBUTES saAttr
;
1437 HANDLE hIn
= INVALID_HANDLE_VALUE
;
1438 HANDLE hErr
= INVALID_HANDLE_VALUE
;
1441 HANDLE hProcess
, tmpIn
, tmpErr
;
1444 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1445 saAttr
.bInheritHandle
= TRUE
;
1446 saAttr
.lpSecurityDescriptor
= NULL
;
1448 /* Standard handles returned by GetStdHandle can be NULL or
1449 INVALID_HANDLE_VALUE if the parent process closed them. If that
1450 happens, we open the null device and pass its handle to
1451 process_begin below as the corresponding handle to inherit. */
1452 tmpIn
= GetStdHandle(STD_INPUT_HANDLE
);
1453 if (DuplicateHandle (GetCurrentProcess(),
1455 GetCurrentProcess(),
1459 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1460 if ((e
= GetLastError()) == ERROR_INVALID_HANDLE
) {
1461 tmpIn
= CreateFile("NUL", GENERIC_READ
,
1462 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
1463 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1464 if (tmpIn
!= INVALID_HANDLE_VALUE
1465 && DuplicateHandle(GetCurrentProcess(),
1467 GetCurrentProcess(),
1471 DUPLICATE_SAME_ACCESS
) == FALSE
)
1474 if (hIn
== INVALID_HANDLE_VALUE
)
1475 fatal (NILF
, _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e
);
1477 tmpErr
= GetStdHandle(STD_ERROR_HANDLE
);
1478 if (DuplicateHandle(GetCurrentProcess(),
1480 GetCurrentProcess(),
1484 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1485 if ((e
= GetLastError()) == ERROR_INVALID_HANDLE
) {
1486 tmpErr
= CreateFile("NUL", GENERIC_WRITE
,
1487 FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
,
1488 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1489 if (tmpErr
!= INVALID_HANDLE_VALUE
1490 && DuplicateHandle(GetCurrentProcess(),
1492 GetCurrentProcess(),
1496 DUPLICATE_SAME_ACCESS
) == FALSE
)
1497 CloseHandle(tmpErr
);
1499 if (hErr
== INVALID_HANDLE_VALUE
)
1500 fatal (NILF
, _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e
);
1503 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1504 fatal (NILF
, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1506 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1509 fatal (NILF
, _("windows32_openpipe(): process_init_fd() failed\n"));
1511 /* make sure that CreateProcess() has Path it needs */
1512 sync_Path_environment();
1513 /* `sync_Path_environment' may realloc `environ', so take note of
1517 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1518 /* register process for wait */
1519 process_register(hProcess
);
1521 /* set the pid for returning to caller */
1522 *pid_p
= (pid_t
) hProcess
;
1524 /* set up to read data from child */
1525 pipedes
[0] = _open_osfhandle((intptr_t) hChildOutRd
, O_RDONLY
);
1527 /* this will be closed almost right away */
1528 pipedes
[1] = _open_osfhandle((intptr_t) hChildOutWr
, O_APPEND
);
1530 /* reap/cleanup the failed process */
1531 process_cleanup(hProcess
);
1533 /* close handles which were duplicated, they weren't used */
1534 if (hIn
!= INVALID_HANDLE_VALUE
)
1536 if (hErr
!= INVALID_HANDLE_VALUE
)
1539 /* close pipe handles, they won't be used */
1540 CloseHandle(hChildOutRd
);
1541 CloseHandle(hChildOutWr
);
1543 /* set status for return */
1544 pipedes
[0] = pipedes
[1] = -1;
1553 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1556 /* MSDOS can't fork, but it has `popen'. */
1557 struct variable
*sh
= lookup_variable ("SHELL", 5);
1559 extern int dos_command_running
, dos_status
;
1561 /* Make sure not to bother processing an empty line. */
1562 while (isblank ((unsigned char)*text
))
1569 char buf
[PATH_MAX
+ 7];
1570 /* This makes sure $SHELL value is used by $(shell), even
1571 though the target environment is not passed to it. */
1572 sprintf (buf
, "SHELL=%s", sh
->value
);
1578 dos_command_running
= 1;
1580 /* If dos_status becomes non-zero, it means the child process
1581 was interrupted by a signal, like SIGINT or SIGQUIT. See
1582 fatal_error_signal in commands.c. */
1583 fpipe
= popen (text
, "rt");
1584 dos_command_running
= 0;
1585 if (!fpipe
|| dos_status
)
1591 else if (errno
== 0)
1593 shell_function_completed
= -1;
1597 pipedes
[0] = fileno (fpipe
);
1598 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1600 shell_function_completed
= 1;
1607 Do shell spawning, with the naughty bits for different OSes.
1612 /* VMS can't do $(shell ...) */
1615 func_shell_base (char *o
, char **argv
, int trim_newlines
)
1617 fprintf (stderr
, "This platform does not support shell\n");
1621 #define func_shell 0
1626 func_shell_base (char *o
, char **argv
, int trim_newlines
)
1628 char *batch_filename
= NULL
;
1633 char **command_argv
;
1634 const char *error_prefix
;
1641 /* Reset just_print_flag. This is needed on Windows when batch files
1642 are used to run the commands, because we normally refrain from
1643 creating batch files under -n. */
1644 int j_p_f
= just_print_flag
;
1646 just_print_flag
= 0;
1648 /* Construct the argument list. */
1649 command_argv
= construct_command_argv (argv
[0], NULL
, NULL
, 0,
1651 if (command_argv
== 0)
1654 just_print_flag
= j_p_f
;
1660 /* Using a target environment for `shell' loses in cases like:
1661 export var = $(shell echo foobie)
1662 because target_environment hits a loop trying to expand $(var)
1663 to put it in the environment. This is even more confusing when
1664 var was not explicitly exported, but just appeared in the
1665 calling environment.
1667 See Savannah bug #10593.
1669 envp = target_environment (NILF);
1674 /* For error messages. */
1675 if (reading_file
&& reading_file
->filenm
)
1677 char *p
= alloca (strlen (reading_file
->filenm
)+11+4);
1678 sprintf (p
, "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1684 #if defined(__MSDOS__)
1685 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1688 perror_with_name (error_prefix
, "pipe");
1691 #elif defined(WINDOWS32)
1692 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1693 /* Restore the value of just_print_flag. */
1694 just_print_flag
= j_p_f
;
1698 /* Open of the pipe failed, mark as failed execution. */
1699 shell_function_completed
= -1;
1704 if (pipe (pipedes
) < 0)
1706 perror_with_name (error_prefix
, "pipe");
1711 /* close some handles that are unnecessary for the child process */
1712 CLOSE_ON_EXEC(pipedes
[1]);
1713 CLOSE_ON_EXEC(pipedes
[0]);
1714 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1715 pid
= child_execute_job (0, pipedes
[1], command_argv
, envp
);
1717 perror_with_name (error_prefix
, "spawn");
1718 # else /* ! __EMX__ */
1721 perror_with_name (error_prefix
, "fork");
1723 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1728 /* We are the parent. */
1730 unsigned int maxlen
, i
;
1733 /* Record the PID for reap_children. */
1734 shell_function_pid
= pid
;
1736 shell_function_completed
= 0;
1738 /* Free the storage only the child needed. */
1739 free (command_argv
[0]);
1740 free (command_argv
);
1742 /* Close the write side of the pipe. We test for -1, since
1743 pipedes[1] is -1 on MS-Windows, and some versions of MS
1744 libraries barf when `close' is called with -1. */
1745 if (pipedes
[1] >= 0)
1749 /* Set up and read from the pipe. */
1752 buffer
= xmalloc (maxlen
+ 1);
1754 /* Read from the pipe until it gets EOF. */
1755 for (i
= 0; ; i
+= cc
)
1760 buffer
= xrealloc (buffer
, maxlen
+ 1);
1763 EINTRLOOP (cc
, read (pipedes
[0], &buffer
[i
], maxlen
- i
));
1769 /* Close the read side of the pipe. */
1772 (void) pclose (fpipe
);
1774 (void) close (pipedes
[0]);
1777 /* Loop until child_handler or reap_children() sets
1778 shell_function_completed to the status of our child shell. */
1779 while (shell_function_completed
== 0)
1780 reap_children (1, 0);
1782 if (batch_filename
) {
1783 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1785 remove (batch_filename
);
1786 free (batch_filename
);
1788 shell_function_pid
= 0;
1790 /* The child_handler function will set shell_function_completed
1791 to 1 when the child dies normally, or to -1 if it
1792 dies with status 127, which is most likely an exec fail. */
1794 if (shell_function_completed
== -1)
1796 /* This likely means that the execvp failed, so we should just
1797 write the error message in the pipe from the child. */
1798 fputs (buffer
, stderr
);
1803 /* The child finished normally. Replace all newlines in its output
1804 with spaces, and put that in the variable output buffer. */
1805 fold_newlines (buffer
, &i
, trim_newlines
);
1806 o
= variable_buffer_output (o
, buffer
, i
);
1817 /* Do the Amiga version of func_shell. */
1820 func_shell_base (char *o
, char **argv
, int trim_newlines
)
1822 /* Amiga can't fork nor spawn, but I can start a program with
1823 redirection of my choice. However, this means that we
1824 don't have an opportunity to reopen stdout to trap it. Thus,
1825 we save our own stdout onto a new descriptor and dup a temp
1826 file's descriptor onto our stdout temporarily. After we
1827 spawn the shell program, we dup our own stdout back to the
1828 stdout descriptor. The buffer reading is the same as above,
1829 except that we're now reading from a file. */
1831 #include <dos/dos.h>
1832 #include <proto/dos.h>
1835 char tmp_output
[FILENAME_MAX
];
1836 unsigned int maxlen
= 200, i
;
1838 char * buffer
, * ptr
;
1841 char* batch_filename
= NULL
;
1843 /* Construct the argument list. */
1844 command_argv
= construct_command_argv (argv
[0], NULL
, NULL
, 0,
1846 if (command_argv
== 0)
1849 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1850 Ideally we would use main.c:open_tmpfile(), but this uses a special
1851 Open(), not fopen(), and I'm not familiar enough with the code to mess
1853 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1854 mktemp (tmp_output
);
1855 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1857 for (aptr
=command_argv
; *aptr
; aptr
++)
1858 len
+= strlen (*aptr
) + 1;
1860 buffer
= xmalloc (len
+ 1);
1863 for (aptr
=command_argv
; *aptr
; aptr
++)
1865 strcpy (ptr
, *aptr
);
1866 ptr
+= strlen (ptr
) + 1;
1873 Execute (buffer
, NULL
, child_stdout
);
1876 Close (child_stdout
);
1878 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1880 buffer
= xmalloc (maxlen
);
1887 buffer
= xrealloc (buffer
, maxlen
+ 1);
1890 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1895 Close (child_stdout
);
1897 fold_newlines (buffer
, &i
, trim_newlines
);
1898 o
= variable_buffer_output (o
, buffer
, i
);
1905 func_shell (char *o
, char **argv
, const char *funcname UNUSED
)
1907 return func_shell_base (o
, argv
, 1);
1914 equality. Return is string-boolean, ie, the empty string is false.
1917 func_eq (char *o
, char **argv
, char *funcname
)
1919 int result
= ! strcmp (argv
[0], argv
[1]);
1920 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1926 string-boolean not operator.
1929 func_not (char *o
, char **argv
, char *funcname
)
1931 const char *s
= argv
[0];
1933 while (isspace ((unsigned char)*s
))
1936 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1942 #ifdef HAVE_DOS_PATHS
1943 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1946 #define IS_ABSOLUTE(n) (n[0] == '/')
1950 /* Return the absolute name of file NAME which does not contain any `.',
1951 `..' components nor any repeated path separators ('/'). */
1954 abspath (const char *name
, char *apath
)
1957 const char *start
, *end
, *apath_limit
;
1958 unsigned long root_len
= ROOT_LEN
;
1960 if (name
[0] == '\0' || apath
== NULL
)
1963 apath_limit
= apath
+ GET_PATH_MAX
;
1965 if (!IS_ABSOLUTE(name
))
1967 /* It is unlikely we would make it until here but just to make sure. */
1968 if (!starting_directory
)
1971 strcpy (apath
, starting_directory
);
1973 #ifdef HAVE_DOS_PATHS
1974 if (IS_PATHSEP(name
[0]))
1976 if (IS_PATHSEP(name
[1]))
1978 /* A UNC. Don't prepend a drive letter. */
1983 /* We have /foo, an absolute file name except for the drive
1984 letter. Assume the missing drive letter is the current
1985 drive, which we can get if we remove from starting_directory
1986 everything past the root directory. */
1987 apath
[root_len
] = '\0';
1991 dest
= strchr (apath
, '\0');
1995 strncpy (apath
, name
, root_len
);
1996 apath
[root_len
] = '\0';
1997 dest
= apath
+ root_len
;
1998 /* Get past the root, since we already copied it. */
2000 #ifdef HAVE_DOS_PATHS
2001 if (!IS_PATHSEP(apath
[2]))
2003 /* Convert d:foo into d:./foo and increase root_len. */
2008 /* strncpy above copied one character too many. */
2012 apath
[2] = '/'; /* make sure it's a forward slash */
2016 for (start
= end
= name
; *start
!= '\0'; start
= end
)
2020 /* Skip sequence of multiple path-separators. */
2021 while (IS_PATHSEP(*start
))
2024 /* Find end of path component. */
2025 for (end
= start
; *end
!= '\0' && !IS_PATHSEP(*end
); ++end
)
2032 else if (len
== 1 && start
[0] == '.')
2034 else if (len
== 2 && start
[0] == '.' && start
[1] == '.')
2036 /* Back up to previous component, ignore if at root already. */
2037 if (dest
> apath
+ root_len
)
2038 for (--dest
; !IS_PATHSEP(dest
[-1]); --dest
);
2042 if (!IS_PATHSEP(dest
[-1]))
2045 if (dest
+ len
>= apath_limit
)
2048 dest
= memcpy (dest
, start
, len
);
2054 /* Unless it is root strip trailing separator. */
2055 if (dest
> apath
+ root_len
&& IS_PATHSEP(dest
[-1]))
2065 func_realpath (char *o
, char **argv
, const char *funcname UNUSED
)
2067 /* Expand the argument. */
2068 const char *p
= argv
[0];
2069 const char *path
= 0;
2071 unsigned int len
= 0;
2072 #ifndef HAVE_REALPATH
2078 while ((path
= find_next_token (&p
, &len
)) != 0)
2080 if (len
< GET_PATH_MAX
)
2082 strncpy (in
, path
, len
);
2086 #ifdef HAVE_REALPATH
2089 abspath (in
, out
) && stat (out
, &st
) == 0
2093 o
= variable_buffer_output (o
, out
, strlen (out
));
2094 o
= variable_buffer_output (o
, " ", 1);
2100 /* Kill last space. */
2108 func_file (char *o
, char **argv
, const char *funcname UNUSED
)
2115 const char *mode
= "w";
2117 /* We are writing a file. */
2124 fn
= next_token (fn
);
2126 fp
= fopen (fn
, mode
);
2128 fatal (reading_file
, _("open: %s: %s"), fn
, strerror (errno
));
2131 int l
= strlen (argv
[1]);
2132 int nl
= (l
== 0 || argv
[1][l
-1] != '\n');
2134 if (fputs (argv
[1], fp
) == EOF
|| (nl
&& fputc('\n', fp
) == EOF
))
2135 fatal (reading_file
, _("write: %s: %s"), fn
, strerror (errno
));
2141 fatal (reading_file
, _("Invalid file operation: %s"), fn
);
2147 func_abspath (char *o
, char **argv
, const char *funcname UNUSED
)
2149 /* Expand the argument. */
2150 const char *p
= argv
[0];
2151 const char *path
= 0;
2153 unsigned int len
= 0;
2157 while ((path
= find_next_token (&p
, &len
)) != 0)
2159 if (len
< GET_PATH_MAX
)
2161 strncpy (in
, path
, len
);
2164 if (abspath (in
, out
))
2166 o
= variable_buffer_output (o
, out
, strlen (out
));
2167 o
= variable_buffer_output (o
, " ", 1);
2173 /* Kill last space. */
2180 /* Lookup table for builtin functions.
2182 This doesn't have to be sorted; we use a straight lookup. We might gain
2183 some efficiency by moving most often used functions to the start of the
2186 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2187 comma-separated values are treated as arguments.
2189 EXPAND_ARGS means that all arguments should be expanded before invocation.
2190 Functions that do namespace tricks (foreach) don't automatically expand. */
2192 static char *func_call (char *o
, char **argv
, const char *funcname
);
2195 static struct function_table_entry function_table_init
[] =
2197 /* Name/size */ /* MIN MAX EXP? Function */
2198 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath
},
2199 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
2200 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
2201 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
2202 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
2203 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
2204 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
2205 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
2206 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
2207 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
2208 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
2209 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
2210 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor
},
2211 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
2212 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword
},
2213 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
2214 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath
},
2215 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
2216 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
2217 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
2218 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
2219 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
2220 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
2221 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
2222 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
2223 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
2224 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
2225 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error
},
2226 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
2227 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
2228 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
2229 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or
},
2230 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and
},
2231 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
2232 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
2233 { STRING_SIZE_TUPLE("file"), 1, 2, 1, func_file
},
2235 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
2236 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
2240 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2243 /* These must come after the definition of function_table. */
2246 expand_builtin_function (char *o
, int argc
, char **argv
,
2247 const struct function_table_entry
*entry_p
)
2249 if (argc
< (int)entry_p
->minimum_args
)
2250 fatal (*expanding_var
,
2251 _("insufficient number of arguments (%d) to function `%s'"),
2252 argc
, entry_p
->name
);
2254 /* I suppose technically some function could do something with no
2255 arguments, but so far none do, so just test it for all functions here
2256 rather than in each one. We can change it later if necessary. */
2261 if (!entry_p
->func_ptr
)
2262 fatal (*expanding_var
,
2263 _("unimplemented on this platform: function `%s'"), entry_p
->name
);
2265 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
2268 /* Check for a function invocation in *STRINGP. *STRINGP points at the
2269 opening ( or { and is not null-terminated. If a function invocation
2270 is found, expand it into the buffer at *OP, updating *OP, incrementing
2271 *STRINGP past the reference and returning nonzero. If not, return zero. */
2274 handle_function (char **op
, const char **stringp
)
2276 const struct function_table_entry
*entry_p
;
2277 char openparen
= (*stringp
)[0];
2278 char closeparen
= openparen
== '(' ? ')' : '}';
2283 char **argv
, **argvp
;
2288 entry_p
= lookup_function (beg
);
2293 /* We found a builtin function. Find the beginning of its arguments (skip
2294 whitespace after the name). */
2296 beg
= next_token (beg
+ entry_p
->len
);
2298 /* Find the end of the function invocation, counting nested use of
2299 whichever kind of parens we use. Since we're looking, count commas
2300 to get a rough estimate of how many arguments we might have. The
2301 count might be high, but it'll never be low. */
2303 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
2306 else if (*end
== openparen
)
2308 else if (*end
== closeparen
&& --count
< 0)
2312 fatal (*expanding_var
,
2313 _("unterminated call to function `%s': missing `%c'"),
2314 entry_p
->name
, closeparen
);
2318 /* Get some memory to store the arg pointers. */
2319 argvp
= argv
= alloca (sizeof (char *) * (nargs
+ 2));
2321 /* Chop the string into arguments, then a nul. As soon as we hit
2322 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2325 If we're expanding, store pointers to the expansion of each one. If
2326 not, make a duplicate of the string and point into that, nul-terminating
2329 if (entry_p
->expand_args
)
2332 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
2338 if (nargs
== entry_p
->maximum_args
2339 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
2342 *argvp
= expand_argument (p
, next
);
2348 int len
= end
- beg
;
2351 abeg
= xmalloc (len
+1);
2352 memcpy (abeg
, beg
, len
);
2356 for (p
=abeg
, nargs
=0; p
<= aend
; ++argvp
)
2362 if (nargs
== entry_p
->maximum_args
2363 || (! (next
= find_next_argument (openparen
, closeparen
, p
, aend
))))
2373 /* Finally! Run the function... */
2374 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
2377 if (entry_p
->expand_args
)
2378 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
2387 /* User-defined functions. Expand the first argument as either a builtin
2388 function or a make variable, in the context of the rest of the arguments
2389 assigned to $1, $2, ... $N. $0 is the name of the function. */
2392 func_call (char *o
, char **argv
, const char *funcname UNUSED
)
2394 static int max_args
= 0;
2401 const struct function_table_entry
*entry_p
;
2404 /* There is no way to define a variable with a space in the name, so strip
2405 leading and trailing whitespace as a favor to the user. */
2407 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
2410 cp
= fname
+ strlen (fname
) - 1;
2411 while (cp
> fname
&& isspace ((unsigned char)*cp
))
2415 /* Calling nothing is a no-op */
2419 /* Are we invoking a builtin function? */
2421 entry_p
= lookup_function (fname
);
2424 /* How many arguments do we have? */
2425 for (i
=0; argv
[i
+1]; ++i
)
2427 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
2430 /* Not a builtin, so the first argument is the name of a variable to be
2431 expanded and interpreted as a function. Find it. */
2432 flen
= strlen (fname
);
2434 v
= lookup_variable (fname
, flen
);
2437 warn_undefined (fname
, flen
);
2439 if (v
== 0 || *v
->value
== '\0')
2442 body
= alloca (flen
+ 4);
2445 memcpy (body
+ 2, fname
, flen
);
2447 body
[flen
+3] = '\0';
2449 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2451 push_new_variable_scope ();
2453 for (i
=0; *argv
; ++i
, ++argv
)
2457 sprintf (num
, "%d", i
);
2458 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
2461 /* If the number of arguments we have is < max_args, it means we're inside
2462 a recursive invocation of $(call ...). Fill in the remaining arguments
2463 in the new scope with the empty value, to hide them from this
2466 for (; i
< max_args
; ++i
)
2470 sprintf (num
, "%d", i
);
2471 define_variable (num
, strlen (num
), "", o_automatic
, 0);
2474 /* Expand the body in the context of the arguments, adding the result to
2475 the variable buffer. */
2477 v
->exp_count
= EXP_COUNT_MAX
;
2479 saved_args
= max_args
;
2481 o
= variable_expand_string (o
, body
, flen
+3);
2482 max_args
= saved_args
;
2486 pop_variable_scope ();
2488 return o
+ strlen (o
);
2492 define_new_function(const struct floc
*flocp
,
2493 const char *name
, int min
, int max
, int expand
,
2494 char *(*func
)(char *, char **, const char *))
2496 size_t len
= strlen (name
);
2497 struct function_table_entry
*ent
= xmalloc (sizeof (struct function_table_entry
));
2500 fatal (flocp
, _("Function name too long: %s\n"), name
);
2501 if (min
< 0 || min
> 255)
2502 fatal (flocp
, _("Invalid minimum argument count (%d) for function %s\n"),
2504 if (max
< 0 || max
> 255 || max
< min
)
2505 fatal (flocp
, _("Invalid maximum argument count (%d) for function %s\n"),
2510 ent
->minimum_args
= min
;
2511 ent
->maximum_args
= max
;
2512 ent
->expand_args
= expand
? 1 : 0;
2513 ent
->func_ptr
= func
;
2515 hash_insert (&function_table
, ent
);
2519 hash_init_function_table (void)
2521 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
2522 function_table_entry_hash_1
, function_table_entry_hash_2
,
2523 function_table_entry_hash_cmp
);
2524 hash_load (&function_table
, function_table_init
,
2525 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));