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 (const void *keyv
)
46 struct function_table_entry
const *key
= (struct function_table_entry
const *) keyv
;
47 return_STRING_N_HASH_1 (key
->name
, key
->len
);
51 function_table_entry_hash_2 (const void *keyv
)
53 struct function_table_entry
const *key
= (struct function_table_entry
const *) keyv
;
54 return_STRING_N_HASH_2 (key
->name
, key
->len
);
58 function_table_entry_hash_cmp (const void *xv
, const void *yv
)
60 struct function_table_entry
const *x
= (struct function_table_entry
const *) xv
;
61 struct function_table_entry
const *y
= (struct function_table_entry
const *) yv
;
62 int result
= x
->len
- y
->len
;
65 return_STRING_N_COMPARE (x
->name
, y
->name
, x
->len
);
68 static struct hash_table function_table
;
71 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
72 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
73 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
74 nonzero, substitutions are done only on matches which are complete
75 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
76 done only at the ends of whitespace-delimited words. */
79 subst_expand (char *o
, char *text
, char *subst
, char *replace
,
80 unsigned int slen
, unsigned int rlen
,
81 int by_word
, int suffix_only
)
83 register char *t
= text
;
86 if (slen
== 0 && !by_word
&& !suffix_only
)
88 /* The first occurrence of "" in any string is its end. */
89 o
= variable_buffer_output (o
, t
, strlen (t
));
91 o
= variable_buffer_output (o
, replace
, rlen
);
97 if ((by_word
| suffix_only
) && slen
== 0)
98 /* When matching by words, the empty string should match
99 the end of each word, rather than the end of the whole text. */
100 p
= end_of_token (next_token (t
));
103 p
= sindex (t
, 0, subst
, slen
);
106 /* No more matches. Output everything left on the end. */
107 o
= variable_buffer_output (o
, t
, strlen (t
));
112 /* Output everything before this occurrence of the string to replace. */
114 o
= variable_buffer_output (o
, t
, p
- t
);
116 /* If we're substituting only by fully matched words,
117 or only at the ends of words, check that this case qualifies. */
119 && ((p
> t
&& !isblank ((unsigned char)p
[-1]))
120 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
122 && (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
123 /* Struck out. Output the rest of the string that is
124 no longer to be replaced. */
125 o
= variable_buffer_output (o
, subst
, slen
);
127 /* Output the replacement string. */
128 o
= variable_buffer_output (o
, replace
, rlen
);
130 /* Advance T past the string to be replaced. */
132 } while (*t
!= '\0');
138 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
139 and replacing strings matching PATTERN with REPLACE.
140 If PATTERN_PERCENT is not nil, PATTERN has already been
141 run through find_percent, and PATTERN_PERCENT is the result.
142 If REPLACE_PERCENT is not nil, REPLACE has already been
143 run through find_percent, and REPLACE_PERCENT is the result. */
146 patsubst_expand (char *o
, char *text
, char *pattern
, char *replace
,
147 char *pattern_percent
, char *replace_percent
)
149 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
150 unsigned int replace_prepercent_len
, replace_postpercent_len
= 0;
155 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
156 will be collapsed before we call subst_expand if PATTERN has no %. */
157 if (replace_percent
== 0)
158 replace_percent
= find_percent (replace
);
159 if (replace_percent
!= 0)
161 /* Record the length of REPLACE before and after the % so
162 we don't have to compute these lengths more than once. */
163 replace_prepercent_len
= replace_percent
- replace
;
164 replace_postpercent_len
= strlen (replace_percent
+ 1);
167 /* We store the length of the replacement
168 so we only need to compute it once. */
169 replace_prepercent_len
= strlen (replace
);
171 if (pattern_percent
== 0)
172 pattern_percent
= find_percent (pattern
);
173 if (pattern_percent
== 0)
174 /* With no % in the pattern, this is just a simple substitution. */
175 return subst_expand (o
, text
, pattern
, replace
,
176 strlen (pattern
), strlen (replace
), 1, 0);
178 /* Record the length of PATTERN before and after the %
179 so we don't have to compute it more than once. */
180 pattern_prepercent_len
= pattern_percent
- pattern
;
181 pattern_postpercent_len
= strlen (pattern_percent
+ 1);
183 while ((t
= find_next_token (&text
, &len
)) != 0)
187 /* Is it big enough to match? */
188 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
191 /* Does the prefix match? */
192 if (!fail
&& pattern_prepercent_len
> 0
194 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-1]
195 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
198 /* Does the suffix match? */
199 if (!fail
&& pattern_postpercent_len
> 0
200 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
]
201 || t
[len
- pattern_postpercent_len
] != pattern_percent
[1]
202 || !strneq (&t
[len
- pattern_postpercent_len
],
203 &pattern_percent
[1], pattern_postpercent_len
- 1)))
207 /* It didn't match. Output the string. */
208 o
= variable_buffer_output (o
, t
, len
);
211 /* It matched. Output the replacement. */
213 /* Output the part of the replacement before the %. */
214 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
216 if (replace_percent
!= 0)
218 /* Output the part of the matched string that
219 matched the % in the pattern. */
220 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
221 len
- (pattern_prepercent_len
222 + pattern_postpercent_len
));
223 /* Output the part of the replacement after the %. */
224 o
= variable_buffer_output (o
, replace_percent
+ 1,
225 replace_postpercent_len
);
229 /* Output a space, but not if the replacement is "". */
230 if (fail
|| replace_prepercent_len
> 0
231 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
233 o
= variable_buffer_output (o
, " ", 1);
238 /* Kill the last space. */
245 /* Look up a function by name. */
247 static const struct function_table_entry
*
248 lookup_function (const char *s
)
252 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
254 if (*e
== '\0' || isblank ((unsigned char) *e
))
256 struct function_table_entry function_table_entry_key
;
257 function_table_entry_key
.name
= s
;
258 function_table_entry_key
.len
= e
- s
;
260 return hash_find_item (&function_table
, &function_table_entry_key
);
266 /* Return 1 if PATTERN matches STR, 0 if not. */
269 pattern_matches (char *pattern
, char *percent
, char *str
)
271 unsigned int sfxlen
, strlength
;
275 unsigned int len
= strlen (pattern
) + 1;
276 char *new_chars
= (char *) alloca (len
);
277 bcopy (pattern
, new_chars
, len
);
279 percent
= find_percent (pattern
);
281 return streq (pattern
, str
);
284 sfxlen
= strlen (percent
+ 1);
285 strlength
= strlen (str
);
287 if (strlength
< (percent
- pattern
) + sfxlen
288 || !strneq (pattern
, str
, percent
- pattern
))
291 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
295 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
296 ENDPARENtheses), starting at PTR before END. Return a pointer to
299 If no next argument is found, return NULL.
303 find_next_argument (char startparen
, char endparen
,
304 const char *ptr
, const char *end
)
308 for (; ptr
< end
; ++ptr
)
309 if (*ptr
== startparen
)
312 else if (*ptr
== endparen
)
319 else if (*ptr
== ',' && !count
)
322 /* We didn't find anything. */
327 /* Glob-expand LINE. The returned pointer is
328 only good until the next call to string_glob. */
331 string_glob (char *line
)
333 static char *result
= 0;
334 static unsigned int length
;
335 register struct nameseq
*chain
;
336 register unsigned int idx
;
338 chain
= multi_glob (parse_file_seq
339 (&line
, '\0', sizeof (struct nameseq
),
340 /* We do not want parse_file_seq to strip `./'s.
341 That would break examples like:
342 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
344 sizeof (struct nameseq
));
349 result
= (char *) xmalloc (100);
355 register char *name
= chain
->name
;
356 unsigned int len
= strlen (name
);
358 struct nameseq
*next
= chain
->next
;
359 free ((char *) chain
);
362 /* multi_glob will pass names without globbing metacharacters
363 through as is, but we want only files that actually exist. */
364 if (file_exists_p (name
))
366 if (idx
+ len
+ 1 > length
)
368 length
+= (len
+ 1) * 2;
369 result
= (char *) xrealloc (result
, length
);
371 bcopy (name
, &result
[idx
], len
);
379 /* Kill the last space and terminate the string. */
383 result
[idx
- 1] = '\0';
393 func_patsubst (char *o
, char **argv
, const char *funcname
)
395 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
401 func_join (char *o
, char **argv
, const char *funcname
)
405 /* Write each word of the first argument directly followed
406 by the corresponding word of the second argument.
407 If the two arguments have a different number of words,
408 the excess words are just output separated by blanks. */
411 char *list1_iterator
= argv
[0];
412 char *list2_iterator
= argv
[1];
415 unsigned int len1
, len2
;
417 tp
= find_next_token (&list1_iterator
, &len1
);
419 o
= variable_buffer_output (o
, tp
, len1
);
421 pp
= find_next_token (&list2_iterator
, &len2
);
423 o
= variable_buffer_output (o
, pp
, len2
);
425 if (tp
!= 0 || pp
!= 0)
427 o
= variable_buffer_output (o
, " ", 1);
431 while (tp
!= 0 || pp
!= 0);
433 /* Kill the last blank. */
441 func_origin (char *o
, char **argv
, const char *funcname
)
443 /* Expand the argument. */
444 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
446 o
= variable_buffer_output (o
, "undefined", 9);
455 o
= variable_buffer_output (o
, "default", 7);
458 o
= variable_buffer_output (o
, "environment", 11);
461 o
= variable_buffer_output (o
, "file", 4);
464 o
= variable_buffer_output (o
, "environment override", 20);
467 o
= variable_buffer_output (o
, "command line", 12);
470 o
= variable_buffer_output (o
, "override", 8);
473 o
= variable_buffer_output (o
, "automatic", 9);
481 # define IS_PATHSEP(c) ((c) == ']')
483 # ifdef HAVE_DOS_PATHS
484 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
486 # define IS_PATHSEP(c) ((c) == '/')
492 func_notdir_suffix (char *o
, char **argv
, const char *funcname
)
494 /* Expand the argument. */
495 char *list_iterator
= argv
[0];
500 int is_suffix
= streq (funcname
, "suffix");
501 int is_notdir
= !is_suffix
;
502 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
507 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
520 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
522 #ifdef HAVE_DOS_PATHS
523 /* Handle the case of "d:foo/bar". */
524 else if (streq (funcname
, "notdir") && p2
[0] && p2
[1] == ':')
527 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
531 o
= variable_buffer_output (o
, p2
, len
);
533 if (is_notdir
|| p
>= p2
)
535 o
= variable_buffer_output (o
, " ", 1);
540 /* Kill last space. */
550 func_basename_dir (char *o
, char **argv
, const char *funcname
)
552 /* Expand the argument. */
558 int is_basename
= streq (funcname
, "basename");
559 int is_dir
= !is_basename
;
561 while ((p2
= find_next_token (&p3
, &len
)) != 0)
564 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
571 if (p
>= p2
&& (is_dir
))
572 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
573 else if (p
>= p2
&& (*p
== '.'))
574 o
= variable_buffer_output (o
, p2
, p
- p2
);
575 #ifdef HAVE_DOS_PATHS
576 /* Handle the "d:foobar" case */
577 else if (p2
[0] && p2
[1] == ':' && is_dir
)
578 o
= variable_buffer_output (o
, p2
, 2);
582 o
= variable_buffer_output (o
, "[]", 2);
585 o
= variable_buffer_output (o
, "./", 2);
587 ; /* Just a nop... */
591 /* The entire name is the basename. */
592 o
= variable_buffer_output (o
, p2
, len
);
594 o
= variable_buffer_output (o
, " ", 1);
598 /* Kill last space. */
606 func_addsuffix_addprefix (char *o
, char **argv
, const char *funcname
)
608 int fixlen
= strlen (argv
[0]);
609 char *list_iterator
= argv
[1];
610 int is_addprefix
= streq (funcname
, "addprefix");
611 int is_addsuffix
= !is_addprefix
;
617 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
620 o
= variable_buffer_output (o
, argv
[0], fixlen
);
621 o
= variable_buffer_output (o
, p
, len
);
623 o
= variable_buffer_output (o
, argv
[0], fixlen
);
624 o
= variable_buffer_output (o
, " ", 1);
629 /* Kill last space. */
636 func_subst (char *o
, char **argv
, const char *funcname
)
638 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
639 strlen (argv
[1]), 0, 0);
646 func_firstword (char *o
, char **argv
, const char *funcname
)
649 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
650 char *p
= find_next_token (&words
, &i
);
653 o
= variable_buffer_output (o
, p
, i
);
660 func_words (char *o
, char **argv
, const char *funcname
)
663 char *word_iterator
= argv
[0];
666 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
669 sprintf (buf
, "%d", i
);
670 o
= variable_buffer_output (o
, buf
, strlen (buf
));
677 strip_whitespace (char **begpp
, char **endpp
)
679 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
681 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
689 char *end
= p
+ strlen (p
) - 1;
691 strip_whitespace (&p
, &end
);
694 if (!ISDIGIT (*(p
++))) /* ISDIGIT only evals its arg once: see make.h. */
697 return (end
- beg
>= 0);
701 check_numeric (char *s
, char *message
)
704 fatal (reading_file
, message
);
710 func_word (char *o
, char **argv
, const char *funcname
)
716 /* Check the first argument. */
717 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
721 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
725 while ((p
= find_next_token (&end_p
, 0)) != 0)
730 o
= variable_buffer_output (o
, p
, end_p
- p
);
736 func_wordlist (char *o
, char **argv
, const char *funcname
)
740 /* Check the arguments. */
741 check_numeric (argv
[0],
742 _("non-numeric first argument to `wordlist' function"));
743 check_numeric (argv
[1],
744 _("non-numeric second argument to `wordlist' function"));
746 start
= atoi (argv
[0]);
747 count
= atoi (argv
[1]) - start
+ 1;
752 char *end_p
= argv
[2];
754 /* Find the beginning of the "start"th word. */
755 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
760 /* Find the end of the "count"th word from start. */
761 while (--count
&& (find_next_token (&end_p
, 0) != 0))
764 /* Return the stuff in the middle. */
765 o
= variable_buffer_output (o
, p
, end_p
- p
);
773 func_findstring (char *o
, char **argv
, const char *funcname
)
775 /* Find the first occurrence of the first string in the second. */
776 int i
= strlen (argv
[0]);
777 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
778 o
= variable_buffer_output (o
, argv
[0], i
);
784 func_foreach (char *o
, char **argv
, const char *funcname
)
786 /* expand only the first two. */
787 char *varname
= expand_argument (argv
[0], NULL
);
788 char *list
= expand_argument (argv
[1], NULL
);
789 char *body
= argv
[2];
792 char *list_iterator
= list
;
795 register struct variable
*var
;
797 push_new_variable_scope ();
798 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
800 /* loop through LIST, put the value in VAR and expand BODY */
801 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
810 var
->value
= (char *) xstrdup ((char*) p
);
814 result
= allocated_variable_expand (body
);
816 o
= variable_buffer_output (o
, result
, strlen (result
));
817 o
= variable_buffer_output (o
, " ", 1);
823 /* Kill the last space. */
826 pop_variable_scope ();
836 struct a_word
*chain
;
843 a_word_hash_1 (const void *key
)
845 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
849 a_word_hash_2 (const void *key
)
851 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
855 a_word_hash_cmp (const void *x
, const void *y
)
857 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
860 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
861 ((struct a_word
const *) y
)->str
);
866 struct a_pattern
*next
;
874 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
876 struct a_word
*wordhead
;
877 struct a_word
**wordtail
;
879 struct a_pattern
*pathead
;
880 struct a_pattern
**pattail
;
881 struct a_pattern
*pp
;
883 struct hash_table a_word_table
;
884 int is_filter
= streq (funcname
, "filter");
885 char *pat_iterator
= argv
[0];
886 char *word_iterator
= argv
[1];
893 /* Chop ARGV[0] up into patterns to match against the words. */
896 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
898 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
901 pattail
= &pat
->next
;
903 if (*pat_iterator
!= '\0')
908 pat
->save_c
= p
[len
];
910 pat
->percent
= find_percent (p
);
911 if (pat
->percent
== 0)
916 /* Chop ARGV[1] up into words to match against the patterns. */
918 wordtail
= &wordhead
;
919 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
921 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
924 wordtail
= &word
->next
;
926 if (*word_iterator
!= '\0')
938 /* Only use a hash table if arg list lengths justifies the cost. */
939 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
942 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
943 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
945 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
955 /* Run each pattern through the words, killing words. */
956 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
959 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
960 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
963 struct a_word a_word_key
;
964 a_word_key
.str
= pp
->str
;
965 a_word_key
.length
= pp
->length
;
966 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
974 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
975 wp
->matched
|= (wp
->length
== pp
->length
976 && strneq (pp
->str
, wp
->str
, wp
->length
));
979 /* Output the words that matched (or didn't, for filter-out). */
980 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
981 if (is_filter
? wp
->matched
: !wp
->matched
)
983 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
984 o
= variable_buffer_output (o
, " ", 1);
989 /* Kill the last space. */
993 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
994 pp
->str
[pp
->length
] = pp
->save_c
;
997 hash_free (&a_word_table
, 0);
1004 func_strip (char *o
, char **argv
, const char *funcname
)
1014 while (isspace ((unsigned char)*p
))
1017 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1021 o
= variable_buffer_output (o
, word_start
, i
);
1022 o
= variable_buffer_output (o
, " ", 1);
1027 /* Kill the last space. */
1033 Print a warning or fatal message.
1036 func_error (char *o
, char **argv
, const char *funcname
)
1042 /* The arguments will be broken on commas. Rather than create yet
1043 another special case where function arguments aren't broken up,
1044 just create a format string that puts them back together. */
1045 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1046 len
+= strlen (*argvp
) + 2;
1048 p
= msg
= (char *) alloca (len
+ 1);
1050 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1053 p
+= strlen (*argvp
);
1059 if (*funcname
== 'e')
1060 fatal (reading_file
, "%s", msg
);
1062 /* The warning function expands to the empty string. */
1063 error (reading_file
, "%s", msg
);
1070 chop argv[0] into words, and sort them.
1073 func_sort (char *o
, char **argv
, const char *funcname
)
1077 register int wordi
= 0;
1079 /* Chop ARGV[0] into words and put them in WORDS. */
1085 while ((p
= find_next_token (&t
, &len
)) != 0)
1087 if (wordi
>= nwords
- 1)
1089 nwords
= (2 * nwords
) + 5;
1090 words
= (char **) xrealloc ((char *) words
,
1091 nwords
* sizeof (char *));
1093 words
[wordi
++] = savestring (p
, len
);
1099 /* Now sort the list of words. */
1100 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1102 /* Now write the sorted list. */
1103 for (i
= 0; i
< wordi
; ++i
)
1105 len
= strlen (words
[i
]);
1106 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1107 || strcmp (words
[i
], words
[i
+ 1]))
1109 o
= variable_buffer_output (o
, words
[i
], len
);
1110 o
= variable_buffer_output (o
, " ", 1);
1114 /* Kill the last space. */
1123 $(if condition,true-part[,false-part])
1125 CONDITION is false iff it evaluates to an empty string. White
1126 space before and after condition are stripped before evaluation.
1128 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1129 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1130 you can use $(if ...) to create side-effects (with $(shell ...), for
1135 func_if (char *o
, char **argv
, const char *funcname
)
1137 char *begp
= argv
[0];
1138 char *endp
= begp
+ strlen (argv
[0]);
1141 /* Find the result of the condition: if we have a value, and it's not
1142 empty, the condition is true. If we don't have a value, or it's the
1143 empty string, then it's false. */
1145 strip_whitespace (&begp
, &endp
);
1149 char *expansion
= expand_argument (begp
, NULL
);
1151 result
= strlen (expansion
);
1155 /* If the result is true (1) we want to eval the first argument, and if
1156 it's false (0) we want to eval the second. If the argument doesn't
1157 exist we do nothing, otherwise expand it and add to the buffer. */
1159 argv
+= 1 + !result
;
1165 expansion
= expand_argument (argv
[0], NULL
);
1167 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1176 func_wildcard (char *o
, char **argv
, const char *funcname
)
1180 o
= wildcard_expansion (argv
[0], o
);
1182 char *p
= string_glob (argv
[0]);
1183 o
= variable_buffer_output (o
, p
, strlen (p
));
1189 $(eval <makefile string>)
1191 Always resolves to the empty string.
1193 Treat the arguments as a segment of makefile, and parse them.
1197 func_eval (char *o
, char **argv
, const char *funcname
)
1202 /* Eval the buffer. Pop the current variable buffer setting so that the
1203 eval'd code can use its own without conflicting. */
1205 install_variable_buffer (&buf
, &len
);
1207 eval_buffer (argv
[0]);
1209 restore_variable_buffer (buf
, len
);
1216 func_value (char *o
, char **argv
, const char *funcname
)
1218 /* Look up the variable. */
1219 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1221 /* Copy its value into the output buffer without expanding it. */
1223 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1229 \r is replaced on UNIX as well. Is this desirable?
1232 fold_newlines (char *buffer
, int *length
)
1236 char *last_nonnl
= buffer
-1;
1238 for (; *src
!= '\0'; ++src
)
1240 if (src
[0] == '\r' && src
[1] == '\n')
1252 *(++last_nonnl
) = '\0';
1253 *length
= last_nonnl
- buffer
;
1258 int shell_function_pid
= 0, shell_function_completed
;
1264 #include <windows.h>
1266 #include "sub_proc.h"
1270 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1272 SECURITY_ATTRIBUTES saAttr
;
1280 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1281 saAttr
.bInheritHandle
= TRUE
;
1282 saAttr
.lpSecurityDescriptor
= NULL
;
1284 if (DuplicateHandle (GetCurrentProcess(),
1285 GetStdHandle(STD_INPUT_HANDLE
),
1286 GetCurrentProcess(),
1290 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1291 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1295 if (DuplicateHandle(GetCurrentProcess(),
1296 GetStdHandle(STD_ERROR_HANDLE
),
1297 GetCurrentProcess(),
1301 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1302 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1306 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1307 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1309 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1312 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1314 /* make sure that CreateProcess() has Path it needs */
1315 sync_Path_environment();
1317 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1318 /* register process for wait */
1319 process_register(hProcess
);
1321 /* set the pid for returning to caller */
1322 *pid_p
= (int) hProcess
;
1324 /* set up to read data from child */
1325 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1327 /* this will be closed almost right away */
1328 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1330 /* reap/cleanup the failed process */
1331 process_cleanup(hProcess
);
1333 /* close handles which were duplicated, they weren't used */
1337 /* close pipe handles, they won't be used */
1338 CloseHandle(hChildOutRd
);
1339 CloseHandle(hChildOutWr
);
1341 /* set status for return */
1342 pipedes
[0] = pipedes
[1] = -1;
1351 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1354 /* MSDOS can't fork, but it has `popen'. */
1355 struct variable
*sh
= lookup_variable ("SHELL", 5);
1357 extern int dos_command_running
, dos_status
;
1359 /* Make sure not to bother processing an empty line. */
1360 while (isblank ((unsigned char)*text
))
1367 char buf
[PATH_MAX
+ 7];
1368 /* This makes sure $SHELL value is used by $(shell), even
1369 though the target environment is not passed to it. */
1370 sprintf (buf
, "SHELL=%s", sh
->value
);
1376 dos_command_running
= 1;
1378 /* If dos_status becomes non-zero, it means the child process
1379 was interrupted by a signal, like SIGINT or SIGQUIT. See
1380 fatal_error_signal in commands.c. */
1381 fpipe
= popen (text
, "rt");
1382 dos_command_running
= 0;
1383 if (!fpipe
|| dos_status
)
1389 else if (errno
== 0)
1391 shell_function_completed
= -1;
1395 pipedes
[0] = fileno (fpipe
);
1396 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1398 shell_function_completed
= 1;
1405 Do shell spawning, with the naughty bits for different OSes.
1410 /* VMS can't do $(shell ...) */
1411 #define func_shell 0
1416 func_shell (char *o
, char **argv
, const char *funcname
)
1418 char* batch_filename
= NULL
;
1424 char **command_argv
;
1431 /* Construct the argument list. */
1432 command_argv
= construct_command_argv (argv
[0],
1433 (char **) NULL
, (struct file
*) 0,
1435 if (command_argv
== 0)
1439 /* Using a target environment for `shell' loses in cases like:
1440 export var = $(shell echo foobie)
1441 because target_environment hits a loop trying to expand $(var)
1442 to put it in the environment. This is even more confusing when
1443 var was not explicitly exported, but just appeared in the
1444 calling environment. */
1448 /* For error messages. */
1449 if (reading_file
!= 0)
1451 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1452 sprintf (error_prefix
,
1453 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1459 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1461 if (pipedes
[0] < 0) {
1462 /* open of the pipe failed, mark as failed execution */
1463 shell_function_completed
= -1;
1467 #else /* WINDOWS32 */
1470 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1473 perror_with_name (error_prefix
, "pipe");
1477 if (pipe (pipedes
) < 0)
1479 perror_with_name (error_prefix
, "pipe");
1485 perror_with_name (error_prefix
, "fork");
1487 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1489 # endif /* ! __MSDOS__ */
1491 #endif /* WINDOWS32 */
1493 /* We are the parent. */
1496 unsigned int maxlen
;
1499 /* Record the PID for reap_children. */
1500 shell_function_pid
= pid
;
1502 shell_function_completed
= 0;
1504 /* Free the storage only the child needed. */
1505 free (command_argv
[0]);
1506 free ((char *) command_argv
);
1508 /* Close the write side of the pipe. */
1509 (void) close (pipedes
[1]);
1512 /* Set up and read from the pipe. */
1515 buffer
= (char *) xmalloc (maxlen
+ 1);
1517 /* Read from the pipe until it gets EOF. */
1518 for (i
= 0; ; i
+= cc
)
1523 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1526 cc
= read (pipedes
[0], &buffer
[i
], maxlen
- i
);
1532 /* Close the read side of the pipe. */
1535 (void) pclose (fpipe
);
1537 (void) close (pipedes
[0]);
1540 /* Loop until child_handler sets shell_function_completed
1541 to the status of our child shell. */
1542 while (shell_function_completed
== 0)
1543 reap_children (1, 0);
1545 if (batch_filename
) {
1546 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1548 remove (batch_filename
);
1549 free (batch_filename
);
1551 shell_function_pid
= 0;
1553 /* The child_handler function will set shell_function_completed
1554 to 1 when the child dies normally, or to -1 if it
1555 dies with status 127, which is most likely an exec fail. */
1557 if (shell_function_completed
== -1)
1559 /* This most likely means that the execvp failed,
1560 so we should just write out the error message
1561 that came in over the pipe from the child. */
1562 fputs (buffer
, stderr
);
1567 /* The child finished normally. Replace all
1568 newlines in its output with spaces, and put
1569 that in the variable output buffer. */
1570 fold_newlines (buffer
, &i
);
1571 o
= variable_buffer_output (o
, buffer
, i
);
1582 /* Do the Amiga version of func_shell. */
1585 func_shell (char *o
, char **argv
, const char *funcname
)
1587 /* Amiga can't fork nor spawn, but I can start a program with
1588 redirection of my choice. However, this means that we
1589 don't have an opportunity to reopen stdout to trap it. Thus,
1590 we save our own stdout onto a new descriptor and dup a temp
1591 file's descriptor onto our stdout temporarily. After we
1592 spawn the shell program, we dup our own stdout back to the
1593 stdout descriptor. The buffer reading is the same as above,
1594 except that we're now reading from a file. */
1596 #include <dos/dos.h>
1597 #include <proto/dos.h>
1600 char tmp_output
[FILENAME_MAX
];
1601 unsigned int maxlen
= 200;
1603 char * buffer
, * ptr
;
1606 char* batch_filename
= NULL
;
1608 /* Construct the argument list. */
1609 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1610 (struct file
*) 0, &batch_filename
);
1611 if (command_argv
== 0)
1614 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1615 Ideally we would use main.c:open_tmpfile(), but this uses a special
1616 Open(), not fopen(), and I'm not familiar enough with the code to mess
1618 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1619 mktemp (tmp_output
);
1620 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1622 for (aptr
=command_argv
; *aptr
; aptr
++)
1623 len
+= strlen (*aptr
) + 1;
1625 buffer
= xmalloc (len
+ 1);
1628 for (aptr
=command_argv
; *aptr
; aptr
++)
1630 strcpy (ptr
, *aptr
);
1631 ptr
+= strlen (ptr
) + 1;
1638 Execute (buffer
, NULL
, child_stdout
);
1641 Close (child_stdout
);
1643 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1645 buffer
= xmalloc (maxlen
);
1652 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1655 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1660 Close (child_stdout
);
1662 fold_newlines (buffer
, &i
);
1663 o
= variable_buffer_output (o
, buffer
, i
);
1673 equality. Return is string-boolean, ie, the empty string is false.
1676 func_eq (char* o
, char **argv
, char *funcname
)
1678 int result
= ! strcmp (argv
[0], argv
[1]);
1679 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1685 string-boolean not operator.
1688 func_not (char* o
, char **argv
, char *funcname
)
1692 while (isspace ((unsigned char)*s
))
1695 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1701 /* Lookup table for builtin functions.
1703 This doesn't have to be sorted; we use a straight lookup. We might gain
1704 some efficiency by moving most often used functions to the start of the
1707 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1708 comma-separated values are treated as arguments.
1710 EXPAND_ARGS means that all arguments should be expanded before invocation.
1711 Functions that do namespace tricks (foreach) don't automatically expand. */
1713 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1716 static struct function_table_entry function_table_init
[] =
1718 /* Name/size */ /* MIN MAX EXP? Function */
1719 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1720 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1721 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1722 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1723 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1724 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1725 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1726 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1727 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1728 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1729 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1730 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1731 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1732 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1733 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1734 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1735 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1736 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1737 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1738 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1739 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1740 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1741 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1742 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1743 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1744 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1745 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1746 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1748 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1749 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1753 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1756 /* These must come after the definition of function_table. */
1759 expand_builtin_function (char *o
, int argc
, char **argv
,
1760 const struct function_table_entry
*entry_p
)
1762 if (argc
< (int)entry_p
->minimum_args
)
1763 fatal (reading_file
,
1764 _("Insufficient number of arguments (%d) to function `%s'"),
1765 argc
, entry_p
->name
);
1767 /* I suppose technically some function could do something with no
1768 arguments, but so far none do, so just test it for all functions here
1769 rather than in each one. We can change it later if necessary. */
1774 if (!entry_p
->func_ptr
)
1775 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1778 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1781 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1782 opening ( or { and is not null-terminated. If a function invocation
1783 is found, expand it into the buffer at *OP, updating *OP, incrementing
1784 *STRINGP past the reference and returning nonzero. If not, return zero. */
1787 handle_function (char **op
, char **stringp
)
1789 const struct function_table_entry
*entry_p
;
1790 char openparen
= (*stringp
)[0];
1791 char closeparen
= openparen
== '(' ? ')' : '}';
1796 char **argv
, **argvp
;
1801 entry_p
= lookup_function (beg
);
1806 /* We found a builtin function. Find the beginning of its arguments (skip
1807 whitespace after the name). */
1809 beg
= next_token (beg
+ entry_p
->len
);
1811 /* Find the end of the function invocation, counting nested use of
1812 whichever kind of parens we use. Since we're looking, count commas
1813 to get a rough estimate of how many arguments we might have. The
1814 count might be high, but it'll never be low. */
1816 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1819 else if (*end
== openparen
)
1821 else if (*end
== closeparen
&& --count
< 0)
1825 fatal (reading_file
,
1826 _("unterminated call to function `%s': missing `%c'"),
1827 entry_p
->name
, closeparen
);
1831 /* Get some memory to store the arg pointers. */
1832 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1834 /* Chop the string into arguments, then a nul. As soon as we hit
1835 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1838 If we're expanding, store pointers to the expansion of each one. If
1839 not, make a duplicate of the string and point into that, nul-terminating
1842 if (!entry_p
->expand_args
)
1844 int len
= end
- beg
;
1846 p
= xmalloc (len
+1);
1847 memcpy (p
, beg
, len
);
1853 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1859 if (nargs
== entry_p
->maximum_args
1860 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1863 if (entry_p
->expand_args
)
1864 *argvp
= expand_argument (p
, next
);
1875 /* Finally! Run the function... */
1876 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1879 if (entry_p
->expand_args
)
1880 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1889 /* User-defined functions. Expand the first argument as either a builtin
1890 function or a make variable, in the context of the rest of the arguments
1891 assigned to $1, $2, ... $N. $0 is the name of the function. */
1894 func_call (char *o
, char **argv
, const char *funcname
)
1896 static int max_args
= 0;
1903 const struct function_table_entry
*entry_p
;
1906 /* There is no way to define a variable with a space in the name, so strip
1907 leading and trailing whitespace as a favor to the user. */
1909 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
1912 cp
= fname
+ strlen (fname
) - 1;
1913 while (cp
> fname
&& isspace ((unsigned char)*cp
))
1917 /* Calling nothing is a no-op */
1921 /* Are we invoking a builtin function? */
1923 entry_p
= lookup_function (fname
);
1927 /* How many arguments do we have? */
1928 for (i
=0; argv
[i
+1]; ++i
)
1931 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
1934 /* Not a builtin, so the first argument is the name of a variable to be
1935 expanded and interpreted as a function. Find it. */
1936 flen
= strlen (fname
);
1938 v
= lookup_variable (fname
, flen
);
1941 warn_undefined (fname
, flen
);
1943 if (v
== 0 || *v
->value
== '\0')
1946 body
= (char *) alloca (flen
+ 4);
1949 memcpy (body
+ 2, fname
, flen
);
1951 body
[flen
+3] = '\0';
1953 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1955 push_new_variable_scope ();
1957 for (i
=0; *argv
; ++i
, ++argv
)
1961 sprintf (num
, "%d", i
);
1962 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
1965 /* If the number of arguments we have is < max_args, it means we're inside
1966 a recursive invocation of $(call ...). Fill in the remaining arguments
1967 in the new scope with the empty value, to hide them from this
1970 for (; i
< max_args
; ++i
)
1974 sprintf (num
, "%d", i
);
1975 define_variable (num
, strlen (num
), "", o_automatic
, 0);
1978 /* Expand the body in the context of the arguments, adding the result to
1979 the variable buffer. */
1981 v
->exp_count
= EXP_COUNT_MAX
;
1983 saved_args
= max_args
;
1985 o
= variable_expand_string (o
, body
, flen
+3);
1986 max_args
= saved_args
;
1990 pop_variable_scope ();
1992 return o
+ strlen (o
);
1996 hash_init_function_table (void)
1998 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
1999 function_table_entry_hash_1
, function_table_entry_hash_2
,
2000 function_table_entry_hash_cmp
);
2001 hash_load (&function_table
, function_table_init
,
2002 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));