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)
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. */
33 struct function_table_entry
37 unsigned char minimum_args
;
38 unsigned char maximum_args
;
40 char *(*func_ptr
) PARAMS ((char *output
, char **argv
, const char *fname
));
44 function_table_entry_hash_1 (keyv
)
47 struct function_table_entry
const *key
= (struct function_table_entry
const *) keyv
;
48 return_STRING_N_HASH_1 (key
->name
, key
->len
);
52 function_table_entry_hash_2 (keyv
)
55 struct function_table_entry
const *key
= (struct function_table_entry
const *) keyv
;
56 return_STRING_N_HASH_2 (key
->name
, key
->len
);
60 function_table_entry_hash_cmp (xv
, yv
)
64 struct function_table_entry
const *x
= (struct function_table_entry
const *) xv
;
65 struct function_table_entry
const *y
= (struct function_table_entry
const *) yv
;
66 int result
= x
->len
- y
->len
;
69 return_STRING_N_COMPARE (x
->name
, y
->name
, x
->len
);
72 static struct hash_table function_table
;
75 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
76 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
77 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
78 nonzero, substitutions are done only on matches which are complete
79 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
80 done only at the ends of whitespace-delimited words. */
83 subst_expand (o
, text
, subst
, replace
, slen
, rlen
, by_word
, suffix_only
)
86 char *subst
, *replace
;
87 unsigned int slen
, rlen
;
88 int by_word
, suffix_only
;
90 register char *t
= text
;
93 if (slen
== 0 && !by_word
&& !suffix_only
)
95 /* The first occurrence of "" in any string is its end. */
96 o
= variable_buffer_output (o
, t
, strlen (t
));
98 o
= variable_buffer_output (o
, replace
, rlen
);
104 if ((by_word
| suffix_only
) && slen
== 0)
105 /* When matching by words, the empty string should match
106 the end of each word, rather than the end of the whole text. */
107 p
= end_of_token (next_token (t
));
110 p
= sindex (t
, 0, subst
, slen
);
113 /* No more matches. Output everything left on the end. */
114 o
= variable_buffer_output (o
, t
, strlen (t
));
119 /* Output everything before this occurrence of the string to replace. */
121 o
= variable_buffer_output (o
, t
, p
- t
);
123 /* If we're substituting only by fully matched words,
124 or only at the ends of words, check that this case qualifies. */
126 && ((p
> t
&& !isblank ((unsigned char)p
[-1]))
127 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
129 && (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
130 /* Struck out. Output the rest of the string that is
131 no longer to be replaced. */
132 o
= variable_buffer_output (o
, subst
, slen
);
134 /* Output the replacement string. */
135 o
= variable_buffer_output (o
, replace
, rlen
);
137 /* Advance T past the string to be replaced. */
139 } while (*t
!= '\0');
145 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
146 and replacing strings matching PATTERN with REPLACE.
147 If PATTERN_PERCENT is not nil, PATTERN has already been
148 run through find_percent, and PATTERN_PERCENT is the result.
149 If REPLACE_PERCENT is not nil, REPLACE has already been
150 run through find_percent, and REPLACE_PERCENT is the result. */
153 patsubst_expand (o
, text
, pattern
, replace
, pattern_percent
, replace_percent
)
156 register char *pattern
, *replace
;
157 register char *pattern_percent
, *replace_percent
;
159 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
160 unsigned int replace_prepercent_len
, replace_postpercent_len
= 0;
165 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
166 will be collapsed before we call subst_expand if PATTERN has no %. */
167 if (replace_percent
== 0)
168 replace_percent
= find_percent (replace
);
169 if (replace_percent
!= 0)
171 /* Record the length of REPLACE before and after the % so
172 we don't have to compute these lengths more than once. */
173 replace_prepercent_len
= replace_percent
- replace
;
174 replace_postpercent_len
= strlen (replace_percent
+ 1);
177 /* We store the length of the replacement
178 so we only need to compute it once. */
179 replace_prepercent_len
= strlen (replace
);
181 if (pattern_percent
== 0)
182 pattern_percent
= find_percent (pattern
);
183 if (pattern_percent
== 0)
184 /* With no % in the pattern, this is just a simple substitution. */
185 return subst_expand (o
, text
, pattern
, replace
,
186 strlen (pattern
), strlen (replace
), 1, 0);
188 /* Record the length of PATTERN before and after the %
189 so we don't have to compute it more than once. */
190 pattern_prepercent_len
= pattern_percent
- pattern
;
191 pattern_postpercent_len
= strlen (pattern_percent
+ 1);
193 while ((t
= find_next_token (&text
, &len
)) != 0)
197 /* Is it big enough to match? */
198 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
201 /* Does the prefix match? */
202 if (!fail
&& pattern_prepercent_len
> 0
204 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-1]
205 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
208 /* Does the suffix match? */
209 if (!fail
&& pattern_postpercent_len
> 0
210 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
]
211 || t
[len
- pattern_postpercent_len
] != pattern_percent
[1]
212 || !strneq (&t
[len
- pattern_postpercent_len
],
213 &pattern_percent
[1], pattern_postpercent_len
- 1)))
217 /* It didn't match. Output the string. */
218 o
= variable_buffer_output (o
, t
, len
);
221 /* It matched. Output the replacement. */
223 /* Output the part of the replacement before the %. */
224 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
226 if (replace_percent
!= 0)
228 /* Output the part of the matched string that
229 matched the % in the pattern. */
230 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
231 len
- (pattern_prepercent_len
232 + pattern_postpercent_len
));
233 /* Output the part of the replacement after the %. */
234 o
= variable_buffer_output (o
, replace_percent
+ 1,
235 replace_postpercent_len
);
239 /* Output a space, but not if the replacement is "". */
240 if (fail
|| replace_prepercent_len
> 0
241 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
243 o
= variable_buffer_output (o
, " ", 1);
248 /* Kill the last space. */
255 /* Look up a function by name. */
257 static const struct function_table_entry
*
263 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
265 if (*e
== '\0' || isblank ((unsigned char) *e
))
267 struct function_table_entry function_table_entry_key
;
268 function_table_entry_key
.name
= s
;
269 function_table_entry_key
.len
= e
- s
;
271 return hash_find_item (&function_table
, &function_table_entry_key
);
277 /* Return 1 if PATTERN matches STR, 0 if not. */
280 pattern_matches (pattern
, percent
, str
)
281 register char *pattern
, *percent
, *str
;
283 unsigned int sfxlen
, strlength
;
287 unsigned int len
= strlen (pattern
) + 1;
288 char *new_chars
= (char *) alloca (len
);
289 bcopy (pattern
, new_chars
, len
);
291 percent
= find_percent (pattern
);
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
))
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
311 If no next argument is found, return NULL.
315 find_next_argument (startparen
, endparen
, ptr
, end
)
323 for (; ptr
< end
; ++ptr
)
324 if (*ptr
== startparen
)
327 else if (*ptr
== endparen
)
334 else if (*ptr
== ',' && !count
)
337 /* We didn't find anything. */
342 /* Glob-expand LINE. The returned pointer is
343 only good until the next call to string_glob. */
349 static char *result
= 0;
350 static unsigned int length
;
351 register struct nameseq
*chain
;
352 register unsigned int idx
;
354 chain
= multi_glob (parse_file_seq
355 (&line
, '\0', sizeof (struct nameseq
),
356 /* We do not want parse_file_seq to strip `./'s.
357 That would break examples like:
358 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
360 sizeof (struct nameseq
));
365 result
= (char *) xmalloc (100);
371 register char *name
= chain
->name
;
372 unsigned int len
= strlen (name
);
374 struct nameseq
*next
= chain
->next
;
375 free ((char *) chain
);
378 /* multi_glob will pass names without globbing metacharacters
379 through as is, but we want only files that actually exist. */
380 if (file_exists_p (name
))
382 if (idx
+ len
+ 1 > length
)
384 length
+= (len
+ 1) * 2;
385 result
= (char *) xrealloc (result
, length
);
387 bcopy (name
, &result
[idx
], len
);
395 /* Kill the last space and terminate the string. */
399 result
[idx
- 1] = '\0';
409 func_patsubst (o
, argv
, funcname
)
412 const char *funcname
;
414 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
420 func_join (o
, argv
, funcname
)
423 const char *funcname
;
427 /* Write each word of the first argument directly followed
428 by the corresponding word of the second argument.
429 If the two arguments have a different number of words,
430 the excess words are just output separated by blanks. */
433 char *list1_iterator
= argv
[0];
434 char *list2_iterator
= argv
[1];
437 unsigned int len1
, len2
;
439 tp
= find_next_token (&list1_iterator
, &len1
);
441 o
= variable_buffer_output (o
, tp
, len1
);
443 pp
= find_next_token (&list2_iterator
, &len2
);
445 o
= variable_buffer_output (o
, pp
, len2
);
447 if (tp
!= 0 || pp
!= 0)
449 o
= variable_buffer_output (o
, " ", 1);
453 while (tp
!= 0 || pp
!= 0);
455 /* Kill the last blank. */
463 func_origin (o
, argv
, funcname
)
466 const char *funcname
;
468 /* Expand the argument. */
469 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
471 o
= variable_buffer_output (o
, "undefined", 9);
480 o
= variable_buffer_output (o
, "default", 7);
483 o
= variable_buffer_output (o
, "environment", 11);
486 o
= variable_buffer_output (o
, "file", 4);
489 o
= variable_buffer_output (o
, "environment override", 20);
492 o
= variable_buffer_output (o
, "command line", 12);
495 o
= variable_buffer_output (o
, "override", 8);
498 o
= variable_buffer_output (o
, "automatic", 9);
506 # define IS_PATHSEP(c) ((c) == ']')
508 # ifdef HAVE_DOS_PATHS
509 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
511 # define IS_PATHSEP(c) ((c) == '/')
517 func_notdir_suffix (o
, argv
, funcname
)
520 const char *funcname
;
522 /* Expand the argument. */
523 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)
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);
568 /* Kill last space. */
578 func_basename_dir (o
, argv
, funcname
)
581 const char *funcname
;
583 /* Expand the argument. */
589 int is_basename
= streq (funcname
, "basename");
590 int is_dir
= !is_basename
;
592 while ((p2
= find_next_token (&p3
, &len
)) != 0)
595 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
602 if (p
>= p2
&& (is_dir
))
603 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
604 else if (p
>= p2
&& (*p
== '.'))
605 o
= variable_buffer_output (o
, p2
, p
- p2
);
606 #ifdef HAVE_DOS_PATHS
607 /* Handle the "d:foobar" case */
608 else if (p2
[0] && p2
[1] == ':' && is_dir
)
609 o
= variable_buffer_output (o
, p2
, 2);
613 o
= variable_buffer_output (o
, "[]", 2);
616 o
= variable_buffer_output (o
, "./", 2);
618 ; /* Just a nop... */
622 /* The entire name is the basename. */
623 o
= variable_buffer_output (o
, p2
, len
);
625 o
= variable_buffer_output (o
, " ", 1);
629 /* Kill last space. */
637 func_addsuffix_addprefix (o
, argv
, funcname
)
640 const char *funcname
;
642 int fixlen
= strlen (argv
[0]);
643 char *list_iterator
= argv
[1];
644 int is_addprefix
= streq (funcname
, "addprefix");
645 int is_addsuffix
= !is_addprefix
;
651 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
654 o
= variable_buffer_output (o
, argv
[0], fixlen
);
655 o
= variable_buffer_output (o
, p
, len
);
657 o
= variable_buffer_output (o
, argv
[0], fixlen
);
658 o
= variable_buffer_output (o
, " ", 1);
663 /* Kill last space. */
670 func_subst (o
, argv
, funcname
)
673 const char *funcname
;
675 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
676 strlen (argv
[1]), 0, 0);
683 func_firstword (o
, argv
, funcname
)
686 const char *funcname
;
689 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
690 char *p
= find_next_token (&words
, &i
);
693 o
= variable_buffer_output (o
, p
, i
);
700 func_words (o
, argv
, funcname
)
703 const char *funcname
;
706 char *word_iterator
= argv
[0];
709 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
712 sprintf (buf
, "%d", i
);
713 o
= variable_buffer_output (o
, buf
, strlen (buf
));
720 strip_whitespace (begpp
, endpp
)
724 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
726 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
735 char *end
= p
+ strlen (p
) - 1;
737 strip_whitespace (&p
, &end
);
740 if (!ISDIGIT (*(p
++))) /* ISDIGIT only evals its arg once: see make.h. */
743 return (end
- beg
>= 0);
747 check_numeric (s
, message
)
752 fatal (reading_file
, message
);
758 func_word (o
, argv
, funcname
)
761 const char *funcname
;
767 /* Check the first argument. */
768 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
772 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
776 while ((p
= find_next_token (&end_p
, 0)) != 0)
781 o
= variable_buffer_output (o
, p
, end_p
- p
);
787 func_wordlist (o
, argv
, funcname
)
790 const char *funcname
;
794 /* Check the arguments. */
795 check_numeric (argv
[0],
796 _("non-numeric first argument to `wordlist' function"));
797 check_numeric (argv
[1],
798 _("non-numeric second argument to `wordlist' function"));
800 start
= atoi (argv
[0]);
801 count
= atoi (argv
[1]) - start
+ 1;
806 char *end_p
= argv
[2];
808 /* Find the beginning of the "start"th word. */
809 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
814 /* Find the end of the "count"th word from start. */
815 while (--count
&& (find_next_token (&end_p
, 0) != 0))
818 /* Return the stuff in the middle. */
819 o
= variable_buffer_output (o
, p
, end_p
- p
);
827 func_findstring (o
, argv
, funcname
)
830 const char *funcname
;
832 /* Find the first occurrence of the first string in the second. */
833 int i
= strlen (argv
[0]);
834 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
835 o
= variable_buffer_output (o
, argv
[0], i
);
841 func_foreach (o
, argv
, funcname
)
844 const char *funcname
;
846 /* expand only the first two. */
847 char *varname
= expand_argument (argv
[0], NULL
);
848 char *list
= expand_argument (argv
[1], NULL
);
849 char *body
= argv
[2];
852 char *list_iterator
= list
;
855 register struct variable
*var
;
857 push_new_variable_scope ();
858 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
860 /* loop through LIST, put the value in VAR and expand BODY */
861 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
870 var
->value
= (char *) xstrdup ((char*) p
);
874 result
= allocated_variable_expand (body
);
876 o
= variable_buffer_output (o
, result
, strlen (result
));
877 o
= variable_buffer_output (o
, " ", 1);
883 /* Kill the last space. */
886 pop_variable_scope ();
896 struct a_word
*chain
;
906 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
913 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
917 a_word_hash_cmp (x
, y
)
921 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
924 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
925 ((struct a_word
const *) y
)->str
);
930 struct a_pattern
*next
;
938 func_filter_filterout (o
, argv
, funcname
)
941 const char *funcname
;
943 struct a_word
*wordhead
;
944 struct a_word
**wordtail
;
946 struct a_pattern
*pathead
;
947 struct a_pattern
**pattail
;
948 struct a_pattern
*pp
;
950 struct hash_table a_word_table
;
951 int is_filter
= streq (funcname
, "filter");
952 char *pat_iterator
= argv
[0];
953 char *word_iterator
= argv
[1];
960 /* Chop ARGV[0] up into patterns to match against the words. */
963 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
965 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
968 pattail
= &pat
->next
;
970 if (*pat_iterator
!= '\0')
975 pat
->save_c
= p
[len
];
977 pat
->percent
= find_percent (p
);
978 if (pat
->percent
== 0)
983 /* Chop ARGV[1] up into words to match against the patterns. */
985 wordtail
= &wordhead
;
986 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
988 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
991 wordtail
= &word
->next
;
993 if (*word_iterator
!= '\0')
1005 /* Only use a hash table if arg list lengths justifies the cost. */
1006 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
1009 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
1010 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1012 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
1022 /* Run each pattern through the words, killing words. */
1023 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1026 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1027 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
1030 struct a_word a_word_key
;
1031 a_word_key
.str
= pp
->str
;
1032 a_word_key
.length
= pp
->length
;
1033 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
1041 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1042 wp
->matched
|= (wp
->length
== pp
->length
1043 && strneq (pp
->str
, wp
->str
, wp
->length
));
1046 /* Output the words that matched (or didn't, for filter-out). */
1047 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1048 if (is_filter
? wp
->matched
: !wp
->matched
)
1050 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
1051 o
= variable_buffer_output (o
, " ", 1);
1056 /* Kill the last space. */
1060 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1061 pp
->str
[pp
->length
] = pp
->save_c
;
1064 hash_free (&a_word_table
, 0);
1071 func_strip (o
, argv
, funcname
)
1074 const char *funcname
;
1084 while (isspace ((unsigned char)*p
))
1087 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1091 o
= variable_buffer_output (o
, word_start
, i
);
1092 o
= variable_buffer_output (o
, " ", 1);
1097 /* Kill the last space. */
1103 Print a warning or fatal message.
1106 func_error (o
, argv
, funcname
)
1109 const char *funcname
;
1115 /* The arguments will be broken on commas. Rather than create yet
1116 another special case where function arguments aren't broken up,
1117 just create a format string that puts them back together. */
1118 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1119 len
+= strlen (*argvp
) + 2;
1121 p
= msg
= (char *) alloca (len
+ 1);
1123 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1126 p
+= strlen (*argvp
);
1132 if (*funcname
== 'e')
1133 fatal (reading_file
, "%s", msg
);
1135 /* The warning function expands to the empty string. */
1136 error (reading_file
, "%s", msg
);
1143 chop argv[0] into words, and sort them.
1146 func_sort (o
, argv
, funcname
)
1149 const char *funcname
;
1153 register int wordi
= 0;
1155 /* Chop ARGV[0] into words and put them in WORDS. */
1161 while ((p
= find_next_token (&t
, &len
)) != 0)
1163 if (wordi
>= nwords
- 1)
1165 nwords
= (2 * nwords
) + 5;
1166 words
= (char **) xrealloc ((char *) words
,
1167 nwords
* sizeof (char *));
1169 words
[wordi
++] = savestring (p
, len
);
1175 /* Now sort the list of words. */
1176 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1178 /* Now write the sorted list. */
1179 for (i
= 0; i
< wordi
; ++i
)
1181 len
= strlen (words
[i
]);
1182 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1183 || strcmp (words
[i
], words
[i
+ 1]))
1185 o
= variable_buffer_output (o
, words
[i
], len
);
1186 o
= variable_buffer_output (o
, " ", 1);
1190 /* Kill the last space. */
1199 $(if condition,true-part[,false-part])
1201 CONDITION is false iff it evaluates to an empty string. White
1202 space before and after condition are stripped before evaluation.
1204 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1205 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1206 you can use $(if ...) to create side-effects (with $(shell ...), for
1211 func_if (o
, argv
, funcname
)
1214 const char *funcname
;
1216 char *begp
= argv
[0];
1217 char *endp
= begp
+ strlen (argv
[0]);
1220 /* Find the result of the condition: if we have a value, and it's not
1221 empty, the condition is true. If we don't have a value, or it's the
1222 empty string, then it's false. */
1224 strip_whitespace (&begp
, &endp
);
1228 char *expansion
= expand_argument (begp
, NULL
);
1230 result
= strlen (expansion
);
1234 /* If the result is true (1) we want to eval the first argument, and if
1235 it's false (0) we want to eval the second. If the argument doesn't
1236 exist we do nothing, otherwise expand it and add to the buffer. */
1238 argv
+= 1 + !result
;
1244 expansion
= expand_argument (argv
[0], NULL
);
1246 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1255 func_wildcard (o
, argv
, funcname
)
1258 const char *funcname
;
1262 o
= wildcard_expansion (argv
[0], o
);
1264 char *p
= string_glob (argv
[0]);
1265 o
= variable_buffer_output (o
, p
, strlen (p
));
1271 $(eval <makefile string>)
1273 Always resolves to the empty string.
1275 Treat the arguments as a segment of makefile, and parse them.
1279 func_eval (o
, argv
, funcname
)
1282 const char *funcname
;
1284 eval_buffer (argv
[0]);
1291 func_value (o
, argv
, funcname
)
1294 const char *funcname
;
1296 /* Look up the variable. */
1297 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1299 /* Copy its value into the output buffer without expanding it. */
1301 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1307 \r is replaced on UNIX as well. Is this desirable?
1310 fold_newlines (buffer
, length
)
1316 char *last_nonnl
= buffer
-1;
1318 for (; *src
!= '\0'; ++src
)
1320 if (src
[0] == '\r' && src
[1] == '\n')
1332 *(++last_nonnl
) = '\0';
1333 *length
= last_nonnl
- buffer
;
1338 int shell_function_pid
= 0, shell_function_completed
;
1344 #include <windows.h>
1346 #include "sub_proc.h"
1350 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1352 SECURITY_ATTRIBUTES saAttr
;
1360 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1361 saAttr
.bInheritHandle
= TRUE
;
1362 saAttr
.lpSecurityDescriptor
= NULL
;
1364 if (DuplicateHandle (GetCurrentProcess(),
1365 GetStdHandle(STD_INPUT_HANDLE
),
1366 GetCurrentProcess(),
1370 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1371 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1375 if (DuplicateHandle(GetCurrentProcess(),
1376 GetStdHandle(STD_ERROR_HANDLE
),
1377 GetCurrentProcess(),
1381 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1382 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1386 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1387 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1389 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1392 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1394 /* make sure that CreateProcess() has Path it needs */
1395 sync_Path_environment();
1397 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1398 /* register process for wait */
1399 process_register(hProcess
);
1401 /* set the pid for returning to caller */
1402 *pid_p
= (int) hProcess
;
1404 /* set up to read data from child */
1405 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1407 /* this will be closed almost right away */
1408 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1410 /* reap/cleanup the failed process */
1411 process_cleanup(hProcess
);
1413 /* close handles which were duplicated, they weren't used */
1417 /* close pipe handles, they won't be used */
1418 CloseHandle(hChildOutRd
);
1419 CloseHandle(hChildOutWr
);
1421 /* set status for return */
1422 pipedes
[0] = pipedes
[1] = -1;
1431 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1434 /* MSDOS can't fork, but it has `popen'. */
1435 struct variable
*sh
= lookup_variable ("SHELL", 5);
1437 extern int dos_command_running
, dos_status
;
1439 /* Make sure not to bother processing an empty line. */
1440 while (isblank ((unsigned char)*text
))
1447 char buf
[PATH_MAX
+ 7];
1448 /* This makes sure $SHELL value is used by $(shell), even
1449 though the target environment is not passed to it. */
1450 sprintf (buf
, "SHELL=%s", sh
->value
);
1456 dos_command_running
= 1;
1458 /* If dos_status becomes non-zero, it means the child process
1459 was interrupted by a signal, like SIGINT or SIGQUIT. See
1460 fatal_error_signal in commands.c. */
1461 fpipe
= popen (text
, "rt");
1462 dos_command_running
= 0;
1463 if (!fpipe
|| dos_status
)
1469 else if (errno
== 0)
1471 shell_function_completed
= -1;
1475 pipedes
[0] = fileno (fpipe
);
1476 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1478 shell_function_completed
= 1;
1485 Do shell spawning, with the naughty bits for different OSes.
1490 /* VMS can't do $(shell ...) */
1491 #define func_shell 0
1496 func_shell (o
, argv
, funcname
)
1499 const char *funcname
;
1501 char* batch_filename
= NULL
;
1507 char **command_argv
;
1514 /* Construct the argument list. */
1515 command_argv
= construct_command_argv (argv
[0],
1516 (char **) NULL
, (struct file
*) 0,
1518 if (command_argv
== 0)
1522 /* Using a target environment for `shell' loses in cases like:
1523 export var = $(shell echo foobie)
1524 because target_environment hits a loop trying to expand $(var)
1525 to put it in the environment. This is even more confusing when
1526 var was not explicitly exported, but just appeared in the
1527 calling environment. */
1531 /* For error messages. */
1532 if (reading_file
!= 0)
1534 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1535 sprintf (error_prefix
,
1536 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1542 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1544 if (pipedes
[0] < 0) {
1545 /* open of the pipe failed, mark as failed execution */
1546 shell_function_completed
= -1;
1550 #else /* WINDOWS32 */
1553 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1556 perror_with_name (error_prefix
, "pipe");
1560 if (pipe (pipedes
) < 0)
1562 perror_with_name (error_prefix
, "pipe");
1568 perror_with_name (error_prefix
, "fork");
1570 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1572 # endif /* ! __MSDOS__ */
1574 #endif /* WINDOWS32 */
1576 /* We are the parent. */
1579 unsigned int maxlen
;
1582 /* Record the PID for reap_children. */
1583 shell_function_pid
= pid
;
1585 shell_function_completed
= 0;
1587 /* Free the storage only the child needed. */
1588 free (command_argv
[0]);
1589 free ((char *) command_argv
);
1591 /* Close the write side of the pipe. */
1592 (void) close (pipedes
[1]);
1595 /* Set up and read from the pipe. */
1598 buffer
= (char *) xmalloc (maxlen
+ 1);
1600 /* Read from the pipe until it gets EOF. */
1601 for (i
= 0; ; i
+= cc
)
1606 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1609 cc
= read (pipedes
[0], &buffer
[i
], maxlen
- i
);
1615 /* Close the read side of the pipe. */
1618 (void) pclose (fpipe
);
1620 (void) close (pipedes
[0]);
1623 /* Loop until child_handler sets shell_function_completed
1624 to the status of our child shell. */
1625 while (shell_function_completed
== 0)
1626 reap_children (1, 0);
1628 if (batch_filename
) {
1629 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1631 remove (batch_filename
);
1632 free (batch_filename
);
1634 shell_function_pid
= 0;
1636 /* The child_handler function will set shell_function_completed
1637 to 1 when the child dies normally, or to -1 if it
1638 dies with status 127, which is most likely an exec fail. */
1640 if (shell_function_completed
== -1)
1642 /* This most likely means that the execvp failed,
1643 so we should just write out the error message
1644 that came in over the pipe from the child. */
1645 fputs (buffer
, stderr
);
1650 /* The child finished normally. Replace all
1651 newlines in its output with spaces, and put
1652 that in the variable output buffer. */
1653 fold_newlines (buffer
, &i
);
1654 o
= variable_buffer_output (o
, buffer
, i
);
1665 /* Do the Amiga version of func_shell. */
1668 func_shell (char *o
, char **argv
, const char *funcname
)
1670 /* Amiga can't fork nor spawn, but I can start a program with
1671 redirection of my choice. However, this means that we
1672 don't have an opportunity to reopen stdout to trap it. Thus,
1673 we save our own stdout onto a new descriptor and dup a temp
1674 file's descriptor onto our stdout temporarily. After we
1675 spawn the shell program, we dup our own stdout back to the
1676 stdout descriptor. The buffer reading is the same as above,
1677 except that we're now reading from a file. */
1679 #include <dos/dos.h>
1680 #include <proto/dos.h>
1683 char tmp_output
[FILENAME_MAX
];
1684 unsigned int maxlen
= 200;
1686 char * buffer
, * ptr
;
1689 char* batch_filename
= NULL
;
1691 /* Construct the argument list. */
1692 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1693 (struct file
*) 0, &batch_filename
);
1694 if (command_argv
== 0)
1697 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1698 Ideally we would use main.c:open_tmpfile(), but this uses a special
1699 Open(), not fopen(), and I'm not familiar enough with the code to mess
1701 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1702 mktemp (tmp_output
);
1703 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1705 for (aptr
=command_argv
; *aptr
; aptr
++)
1706 len
+= strlen (*aptr
) + 1;
1708 buffer
= xmalloc (len
+ 1);
1711 for (aptr
=command_argv
; *aptr
; aptr
++)
1713 strcpy (ptr
, *aptr
);
1714 ptr
+= strlen (ptr
) + 1;
1721 Execute (buffer
, NULL
, child_stdout
);
1724 Close (child_stdout
);
1726 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1728 buffer
= xmalloc (maxlen
);
1735 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1738 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1743 Close (child_stdout
);
1745 fold_newlines (buffer
, &i
);
1746 o
= variable_buffer_output (o
, buffer
, i
);
1756 equality. Return is string-boolean, ie, the empty string is false.
1759 func_eq (char* o
, char **argv
, char *funcname
)
1761 int result
= ! strcmp (argv
[0], argv
[1]);
1762 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1768 string-boolean not operator.
1771 func_not (char* o
, char **argv
, char *funcname
)
1775 while (isspace ((unsigned char)*s
))
1778 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1784 /* Lookup table for builtin functions.
1786 This doesn't have to be sorted; we use a straight lookup. We might gain
1787 some efficiency by moving most often used functions to the start of the
1790 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1791 comma-separated values are treated as arguments.
1793 EXPAND_ARGS means that all arguments should be expanded before invocation.
1794 Functions that do namespace tricks (foreach) don't automatically expand. */
1796 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1799 static struct function_table_entry function_table_init
[] =
1801 /* Name/size */ /* MIN MAX EXP? Function */
1802 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1803 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1804 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1805 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1806 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1807 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1808 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1809 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1810 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1811 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1812 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1813 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1814 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1815 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1816 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1817 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1818 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1819 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1820 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1821 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1822 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1823 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1824 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1825 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1826 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1827 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1828 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1829 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1831 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1832 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1836 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1839 /* These must come after the definition of function_table. */
1842 expand_builtin_function (o
, argc
, argv
, entry_p
)
1846 struct function_table_entry
*entry_p
;
1848 if (argc
< (int)entry_p
->minimum_args
)
1849 fatal (reading_file
,
1850 _("Insufficient number of arguments (%d) to function `%s'"),
1851 argc
, entry_p
->name
);
1853 /* I suppose technically some function could do something with no
1854 arguments, but so far none do, so just test it for all functions here
1855 rather than in each one. We can change it later if necessary. */
1860 if (!entry_p
->func_ptr
)
1861 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1864 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1867 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1868 opening ( or { and is not null-terminated. If a function invocation
1869 is found, expand it into the buffer at *OP, updating *OP, incrementing
1870 *STRINGP past the reference and returning nonzero. If not, return zero. */
1873 handle_function (op
, stringp
)
1877 const struct function_table_entry
*entry_p
;
1878 char openparen
= (*stringp
)[0];
1879 char closeparen
= openparen
== '(' ? ')' : '}';
1884 char **argv
, **argvp
;
1889 entry_p
= lookup_function (beg
);
1894 /* We found a builtin function. Find the beginning of its arguments (skip
1895 whitespace after the name). */
1897 beg
= next_token (beg
+ entry_p
->len
);
1899 /* Find the end of the function invocation, counting nested use of
1900 whichever kind of parens we use. Since we're looking, count commas
1901 to get a rough estimate of how many arguments we might have. The
1902 count might be high, but it'll never be low. */
1904 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1907 else if (*end
== openparen
)
1909 else if (*end
== closeparen
&& --count
< 0)
1913 fatal (reading_file
,
1914 _("unterminated call to function `%s': missing `%c'"),
1915 entry_p
->name
, closeparen
);
1919 /* Get some memory to store the arg pointers. */
1920 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1922 /* Chop the string into arguments, then a nul. As soon as we hit
1923 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1926 If we're expanding, store pointers to the expansion of each one. If
1927 not, make a duplicate of the string and point into that, nul-terminating
1930 if (!entry_p
->expand_args
)
1932 int len
= end
- beg
;
1934 p
= xmalloc (len
+1);
1935 memcpy (p
, beg
, len
);
1941 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1947 if (nargs
== entry_p
->maximum_args
1948 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1951 if (entry_p
->expand_args
)
1952 *argvp
= expand_argument (p
, next
);
1963 /* Finally! Run the function... */
1964 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1967 if (entry_p
->expand_args
)
1968 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1977 /* User-defined functions. Expand the first argument as either a builtin
1978 function or a make variable, in the context of the rest of the arguments
1979 assigned to $1, $2, ... $N. $0 is the name of the function. */
1982 func_call (o
, argv
, funcname
)
1985 const char *funcname
;
1992 const struct function_table_entry
*entry_p
;
1995 /* There is no way to define a variable with a space in the name, so strip
1996 leading and trailing whitespace as a favor to the user. */
1998 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
2001 cp
= fname
+ strlen (fname
) - 1;
2002 while (cp
> fname
&& isspace ((unsigned char)*cp
))
2006 /* Calling nothing is a no-op */
2010 /* Are we invoking a builtin function? */
2012 entry_p
= lookup_function (fname
);
2016 /* How many arguments do we have? */
2017 for (i
=0; argv
[i
+1]; ++i
)
2020 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
2023 /* Not a builtin, so the first argument is the name of a variable to be
2024 expanded and interpreted as a function. Find it. */
2025 flen
= strlen (fname
);
2027 v
= lookup_variable (fname
, flen
);
2030 warn_undefined (fname
, flen
);
2032 if (v
== 0 || *v
->value
== '\0')
2035 body
= (char *) alloca (flen
+ 4);
2038 memcpy (body
+ 2, fname
, flen
);
2040 body
[flen
+3] = '\0';
2042 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2044 push_new_variable_scope ();
2046 for (i
=0; *argv
; ++i
, ++argv
)
2050 sprintf (num
, "%d", i
);
2051 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
2054 /* Expand the body in the context of the arguments, adding the result to
2055 the variable buffer. */
2057 v
->exp_count
= EXP_COUNT_MAX
;
2059 o
= variable_expand_string (o
, body
, flen
+3);
2063 pop_variable_scope ();
2065 return o
+ strlen (o
);
2069 hash_init_function_table ()
2071 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
2072 function_table_entry_hash_1
, function_table_entry_hash_2
,
2073 function_table_entry_hash_cmp
);
2074 hash_load (&function_table
, function_table_init
,
2075 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));