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
)
84 unsigned int tlen
= strlen (text
);
87 if (slen
== 0 && !by_word
&& !suffix_only
)
89 /* The first occurrence of "" in any string is its end. */
90 o
= variable_buffer_output (o
, t
, tlen
);
92 o
= variable_buffer_output (o
, replace
, rlen
);
98 if ((by_word
| suffix_only
) && slen
== 0)
99 /* When matching by words, the empty string should match
100 the end of each word, rather than the end of the whole text. */
101 p
= end_of_token (next_token (t
));
104 p
= sindex (t
, tlen
, subst
, slen
);
107 /* No more matches. Output everything left on the end. */
108 o
= variable_buffer_output (o
, t
, tlen
);
113 /* Output everything before this occurrence of the string to replace. */
115 o
= variable_buffer_output (o
, t
, p
- t
);
117 /* If we're substituting only by fully matched words,
118 or only at the ends of words, check that this case qualifies. */
120 && ((p
> t
&& !isblank ((unsigned char)p
[-1]))
121 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
123 && (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
124 /* Struck out. Output the rest of the string that is
125 no longer to be replaced. */
126 o
= variable_buffer_output (o
, subst
, slen
);
128 /* Output the replacement string. */
129 o
= variable_buffer_output (o
, replace
, rlen
);
131 /* Advance T past the string to be replaced; adjust tlen. */
137 } while (*t
!= '\0');
143 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
144 and replacing strings matching PATTERN with REPLACE.
145 If PATTERN_PERCENT is not nil, PATTERN has already been
146 run through find_percent, and PATTERN_PERCENT is the result.
147 If REPLACE_PERCENT is not nil, REPLACE has already been
148 run through find_percent, and REPLACE_PERCENT is the result. */
151 patsubst_expand (char *o
, char *text
, char *pattern
, char *replace
,
152 char *pattern_percent
, char *replace_percent
)
154 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
155 unsigned int replace_prepercent_len
, replace_postpercent_len
= 0;
160 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
161 will be collapsed before we call subst_expand if PATTERN has no %. */
162 if (replace_percent
== 0)
163 replace_percent
= find_percent (replace
);
164 if (replace_percent
!= 0)
166 /* Record the length of REPLACE before and after the % so
167 we don't have to compute these lengths more than once. */
168 replace_prepercent_len
= replace_percent
- replace
;
169 replace_postpercent_len
= strlen (replace_percent
+ 1);
172 /* We store the length of the replacement
173 so we only need to compute it once. */
174 replace_prepercent_len
= strlen (replace
);
176 if (pattern_percent
== 0)
177 pattern_percent
= find_percent (pattern
);
178 if (pattern_percent
== 0)
179 /* With no % in the pattern, this is just a simple substitution. */
180 return subst_expand (o
, text
, pattern
, replace
,
181 strlen (pattern
), strlen (replace
), 1, 0);
183 /* Record the length of PATTERN before and after the %
184 so we don't have to compute it more than once. */
185 pattern_prepercent_len
= pattern_percent
- pattern
;
186 pattern_postpercent_len
= strlen (pattern_percent
+ 1);
188 while ((t
= find_next_token (&text
, &len
)) != 0)
192 /* Is it big enough to match? */
193 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
196 /* Does the prefix match? */
197 if (!fail
&& pattern_prepercent_len
> 0
199 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-1]
200 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
203 /* Does the suffix match? */
204 if (!fail
&& pattern_postpercent_len
> 0
205 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
]
206 || t
[len
- pattern_postpercent_len
] != pattern_percent
[1]
207 || !strneq (&t
[len
- pattern_postpercent_len
],
208 &pattern_percent
[1], pattern_postpercent_len
- 1)))
212 /* It didn't match. Output the string. */
213 o
= variable_buffer_output (o
, t
, len
);
216 /* It matched. Output the replacement. */
218 /* Output the part of the replacement before the %. */
219 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
221 if (replace_percent
!= 0)
223 /* Output the part of the matched string that
224 matched the % in the pattern. */
225 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
226 len
- (pattern_prepercent_len
227 + pattern_postpercent_len
));
228 /* Output the part of the replacement after the %. */
229 o
= variable_buffer_output (o
, replace_percent
+ 1,
230 replace_postpercent_len
);
234 /* Output a space, but not if the replacement is "". */
235 if (fail
|| replace_prepercent_len
> 0
236 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
238 o
= variable_buffer_output (o
, " ", 1);
243 /* Kill the last space. */
250 /* Look up a function by name. */
252 static const struct function_table_entry
*
253 lookup_function (const char *s
)
257 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
259 if (*e
== '\0' || isblank ((unsigned char) *e
))
261 struct function_table_entry function_table_entry_key
;
262 function_table_entry_key
.name
= s
;
263 function_table_entry_key
.len
= e
- s
;
265 return hash_find_item (&function_table
, &function_table_entry_key
);
271 /* Return 1 if PATTERN matches STR, 0 if not. */
274 pattern_matches (char *pattern
, char *percent
, char *str
)
276 unsigned int sfxlen
, strlength
;
280 unsigned int len
= strlen (pattern
) + 1;
281 char *new_chars
= (char *) alloca (len
);
282 bcopy (pattern
, new_chars
, len
);
284 percent
= find_percent (pattern
);
286 return streq (pattern
, str
);
289 sfxlen
= strlen (percent
+ 1);
290 strlength
= strlen (str
);
292 if (strlength
< (percent
- pattern
) + sfxlen
293 || !strneq (pattern
, str
, percent
- pattern
))
296 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
300 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
301 ENDPARENtheses), starting at PTR before END. Return a pointer to
304 If no next argument is found, return NULL.
308 find_next_argument (char startparen
, char endparen
,
309 const char *ptr
, const char *end
)
313 for (; ptr
< end
; ++ptr
)
314 if (*ptr
== startparen
)
317 else if (*ptr
== endparen
)
324 else if (*ptr
== ',' && !count
)
327 /* We didn't find anything. */
332 /* Glob-expand LINE. The returned pointer is
333 only good until the next call to string_glob. */
336 string_glob (char *line
)
338 static char *result
= 0;
339 static unsigned int length
;
340 register struct nameseq
*chain
;
341 register unsigned int idx
;
343 chain
= multi_glob (parse_file_seq
344 (&line
, '\0', sizeof (struct nameseq
),
345 /* We do not want parse_file_seq to strip `./'s.
346 That would break examples like:
347 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
349 sizeof (struct nameseq
));
354 result
= (char *) xmalloc (100);
360 register char *name
= chain
->name
;
361 unsigned int len
= strlen (name
);
363 struct nameseq
*next
= chain
->next
;
364 free ((char *) chain
);
367 /* multi_glob will pass names without globbing metacharacters
368 through as is, but we want only files that actually exist. */
369 if (file_exists_p (name
))
371 if (idx
+ len
+ 1 > length
)
373 length
+= (len
+ 1) * 2;
374 result
= (char *) xrealloc (result
, length
);
376 bcopy (name
, &result
[idx
], len
);
384 /* Kill the last space and terminate the string. */
388 result
[idx
- 1] = '\0';
398 func_patsubst (char *o
, char **argv
, const char *funcname
)
400 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
406 func_join (char *o
, char **argv
, const char *funcname
)
410 /* Write each word of the first argument directly followed
411 by the corresponding word of the second argument.
412 If the two arguments have a different number of words,
413 the excess words are just output separated by blanks. */
416 char *list1_iterator
= argv
[0];
417 char *list2_iterator
= argv
[1];
420 unsigned int len1
, len2
;
422 tp
= find_next_token (&list1_iterator
, &len1
);
424 o
= variable_buffer_output (o
, tp
, len1
);
426 pp
= find_next_token (&list2_iterator
, &len2
);
428 o
= variable_buffer_output (o
, pp
, len2
);
430 if (tp
!= 0 || pp
!= 0)
432 o
= variable_buffer_output (o
, " ", 1);
436 while (tp
!= 0 || pp
!= 0);
438 /* Kill the last blank. */
446 func_origin (char *o
, char **argv
, const char *funcname
)
448 /* Expand the argument. */
449 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
451 o
= variable_buffer_output (o
, "undefined", 9);
460 o
= variable_buffer_output (o
, "default", 7);
463 o
= variable_buffer_output (o
, "environment", 11);
466 o
= variable_buffer_output (o
, "file", 4);
469 o
= variable_buffer_output (o
, "environment override", 20);
472 o
= variable_buffer_output (o
, "command line", 12);
475 o
= variable_buffer_output (o
, "override", 8);
478 o
= variable_buffer_output (o
, "automatic", 9);
486 # define IS_PATHSEP(c) ((c) == ']')
488 # ifdef HAVE_DOS_PATHS
489 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
491 # define IS_PATHSEP(c) ((c) == '/')
497 func_notdir_suffix (char *o
, char **argv
, const char *funcname
)
499 /* Expand the argument. */
500 char *list_iterator
= argv
[0];
505 int is_suffix
= streq (funcname
, "suffix");
506 int is_notdir
= !is_suffix
;
507 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
512 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
525 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
527 #ifdef HAVE_DOS_PATHS
528 /* Handle the case of "d:foo/bar". */
529 else if (streq (funcname
, "notdir") && p2
[0] && p2
[1] == ':')
532 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
536 o
= variable_buffer_output (o
, p2
, len
);
538 if (is_notdir
|| p
>= p2
)
540 o
= variable_buffer_output (o
, " ", 1);
545 /* Kill last space. */
555 func_basename_dir (char *o
, char **argv
, const char *funcname
)
557 /* Expand the argument. */
563 int is_basename
= streq (funcname
, "basename");
564 int is_dir
= !is_basename
;
566 while ((p2
= find_next_token (&p3
, &len
)) != 0)
569 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
576 if (p
>= p2
&& (is_dir
))
577 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
578 else if (p
>= p2
&& (*p
== '.'))
579 o
= variable_buffer_output (o
, p2
, p
- p2
);
580 #ifdef HAVE_DOS_PATHS
581 /* Handle the "d:foobar" case */
582 else if (p2
[0] && p2
[1] == ':' && is_dir
)
583 o
= variable_buffer_output (o
, p2
, 2);
587 o
= variable_buffer_output (o
, "[]", 2);
590 o
= variable_buffer_output (o
, "./", 2);
592 ; /* Just a nop... */
596 /* The entire name is the basename. */
597 o
= variable_buffer_output (o
, p2
, len
);
599 o
= variable_buffer_output (o
, " ", 1);
603 /* Kill last space. */
611 func_addsuffix_addprefix (char *o
, char **argv
, const char *funcname
)
613 int fixlen
= strlen (argv
[0]);
614 char *list_iterator
= argv
[1];
615 int is_addprefix
= streq (funcname
, "addprefix");
616 int is_addsuffix
= !is_addprefix
;
622 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
625 o
= variable_buffer_output (o
, argv
[0], fixlen
);
626 o
= variable_buffer_output (o
, p
, len
);
628 o
= variable_buffer_output (o
, argv
[0], fixlen
);
629 o
= variable_buffer_output (o
, " ", 1);
634 /* Kill last space. */
641 func_subst (char *o
, char **argv
, const char *funcname
)
643 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
644 strlen (argv
[1]), 0, 0);
651 func_firstword (char *o
, char **argv
, const char *funcname
)
654 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
655 char *p
= find_next_token (&words
, &i
);
658 o
= variable_buffer_output (o
, p
, i
);
665 func_words (char *o
, char **argv
, const char *funcname
)
668 char *word_iterator
= argv
[0];
671 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
674 sprintf (buf
, "%d", i
);
675 o
= variable_buffer_output (o
, buf
, strlen (buf
));
682 strip_whitespace (const char **begpp
, const char **endpp
)
684 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
686 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
688 return (char *)*begpp
;
692 check_numeric (const char *s
, const char *message
)
694 const char *end
= s
+ strlen (s
) - 1;
696 strip_whitespace (&s
, &end
);
698 for (; s
<= end
; ++s
)
699 if (!ISDIGIT (*s
)) /* ISDIGIT only evals its arg once: see make.h. */
702 if (s
<= end
|| end
- beg
< 0)
703 fatal (reading_file
, "%s: '%s'", message
, beg
);
709 func_word (char *o
, char **argv
, const char *funcname
)
715 /* Check the first argument. */
716 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
720 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
724 while ((p
= find_next_token (&end_p
, 0)) != 0)
729 o
= variable_buffer_output (o
, p
, end_p
- p
);
735 func_wordlist (char *o
, char **argv
, const char *funcname
)
739 /* Check the arguments. */
740 check_numeric (argv
[0],
741 _("non-numeric first argument to `wordlist' function"));
742 check_numeric (argv
[1],
743 _("non-numeric second argument to `wordlist' function"));
745 start
= atoi (argv
[0]);
746 count
= atoi (argv
[1]) - start
+ 1;
751 char *end_p
= argv
[2];
753 /* Find the beginning of the "start"th word. */
754 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
759 /* Find the end of the "count"th word from start. */
760 while (--count
&& (find_next_token (&end_p
, 0) != 0))
763 /* Return the stuff in the middle. */
764 o
= variable_buffer_output (o
, p
, end_p
- p
);
772 func_findstring (char *o
, char **argv
, const char *funcname
)
774 /* Find the first occurrence of the first string in the second. */
775 int i
= strlen (argv
[0]);
776 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
777 o
= variable_buffer_output (o
, argv
[0], i
);
783 func_foreach (char *o
, char **argv
, const char *funcname
)
785 /* expand only the first two. */
786 char *varname
= expand_argument (argv
[0], NULL
);
787 char *list
= expand_argument (argv
[1], NULL
);
788 char *body
= argv
[2];
791 char *list_iterator
= list
;
794 register struct variable
*var
;
796 push_new_variable_scope ();
797 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
799 /* loop through LIST, put the value in VAR and expand BODY */
800 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
809 var
->value
= (char *) xstrdup ((char*) p
);
813 result
= allocated_variable_expand (body
);
815 o
= variable_buffer_output (o
, result
, strlen (result
));
816 o
= variable_buffer_output (o
, " ", 1);
822 /* Kill the last space. */
825 pop_variable_scope ();
835 struct a_word
*chain
;
842 a_word_hash_1 (const void *key
)
844 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
848 a_word_hash_2 (const void *key
)
850 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
854 a_word_hash_cmp (const void *x
, const void *y
)
856 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
859 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
860 ((struct a_word
const *) y
)->str
);
865 struct a_pattern
*next
;
873 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
875 struct a_word
*wordhead
;
876 struct a_word
**wordtail
;
878 struct a_pattern
*pathead
;
879 struct a_pattern
**pattail
;
880 struct a_pattern
*pp
;
882 struct hash_table a_word_table
;
883 int is_filter
= streq (funcname
, "filter");
884 char *pat_iterator
= argv
[0];
885 char *word_iterator
= argv
[1];
892 /* Chop ARGV[0] up into patterns to match against the words. */
895 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
897 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
900 pattail
= &pat
->next
;
902 if (*pat_iterator
!= '\0')
907 pat
->save_c
= p
[len
];
909 pat
->percent
= find_percent (p
);
910 if (pat
->percent
== 0)
915 /* Chop ARGV[1] up into words to match against the patterns. */
917 wordtail
= &wordhead
;
918 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
920 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
923 wordtail
= &word
->next
;
925 if (*word_iterator
!= '\0')
937 /* Only use a hash table if arg list lengths justifies the cost. */
938 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
941 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
942 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
944 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
954 /* Run each pattern through the words, killing words. */
955 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
958 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
959 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
962 struct a_word a_word_key
;
963 a_word_key
.str
= pp
->str
;
964 a_word_key
.length
= pp
->length
;
965 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
973 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
974 wp
->matched
|= (wp
->length
== pp
->length
975 && strneq (pp
->str
, wp
->str
, wp
->length
));
978 /* Output the words that matched (or didn't, for filter-out). */
979 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
980 if (is_filter
? wp
->matched
: !wp
->matched
)
982 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
983 o
= variable_buffer_output (o
, " ", 1);
988 /* Kill the last space. */
992 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
993 pp
->str
[pp
->length
] = pp
->save_c
;
996 hash_free (&a_word_table
, 0);
1003 func_strip (char *o
, char **argv
, const char *funcname
)
1013 while (isspace ((unsigned char)*p
))
1016 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1020 o
= variable_buffer_output (o
, word_start
, i
);
1021 o
= variable_buffer_output (o
, " ", 1);
1026 /* Kill the last space. */
1032 Print a warning or fatal message.
1035 func_error (char *o
, char **argv
, const char *funcname
)
1041 /* The arguments will be broken on commas. Rather than create yet
1042 another special case where function arguments aren't broken up,
1043 just create a format string that puts them back together. */
1044 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1045 len
+= strlen (*argvp
) + 2;
1047 p
= msg
= (char *) alloca (len
+ 1);
1049 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1052 p
+= strlen (*argvp
);
1058 if (*funcname
== 'e')
1059 fatal (reading_file
, "%s", msg
);
1061 /* The warning function expands to the empty string. */
1062 error (reading_file
, "%s", msg
);
1069 chop argv[0] into words, and sort them.
1072 func_sort (char *o
, char **argv
, const char *funcname
)
1076 register int wordi
= 0;
1078 /* Chop ARGV[0] into words and put them in WORDS. */
1084 while ((p
= find_next_token (&t
, &len
)) != 0)
1086 if (wordi
>= nwords
- 1)
1088 nwords
= (2 * nwords
) + 5;
1089 words
= (char **) xrealloc ((char *) words
,
1090 nwords
* sizeof (char *));
1092 words
[wordi
++] = savestring (p
, len
);
1098 /* Now sort the list of words. */
1099 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1101 /* Now write the sorted list. */
1102 for (i
= 0; i
< wordi
; ++i
)
1104 len
= strlen (words
[i
]);
1105 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1106 || strcmp (words
[i
], words
[i
+ 1]))
1108 o
= variable_buffer_output (o
, words
[i
], len
);
1109 o
= variable_buffer_output (o
, " ", 1);
1113 /* Kill the last space. */
1122 $(if condition,true-part[,false-part])
1124 CONDITION is false iff it evaluates to an empty string. White
1125 space before and after condition are stripped before evaluation.
1127 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1128 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1129 you can use $(if ...) to create side-effects (with $(shell ...), for
1134 func_if (char *o
, char **argv
, const char *funcname
)
1136 const char *begp
= argv
[0];
1137 const char *endp
= begp
+ strlen (argv
[0]);
1140 /* Find the result of the condition: if we have a value, and it's not
1141 empty, the condition is true. If we don't have a value, or it's the
1142 empty string, then it's false. */
1144 strip_whitespace (&begp
, &endp
);
1148 char *expansion
= expand_argument (begp
, NULL
);
1150 result
= strlen (expansion
);
1154 /* If the result is true (1) we want to eval the first argument, and if
1155 it's false (0) we want to eval the second. If the argument doesn't
1156 exist we do nothing, otherwise expand it and add to the buffer. */
1158 argv
+= 1 + !result
;
1164 expansion
= expand_argument (argv
[0], NULL
);
1166 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1175 func_wildcard (char *o
, char **argv
, const char *funcname
)
1179 o
= wildcard_expansion (argv
[0], o
);
1181 char *p
= string_glob (argv
[0]);
1182 o
= variable_buffer_output (o
, p
, strlen (p
));
1188 $(eval <makefile string>)
1190 Always resolves to the empty string.
1192 Treat the arguments as a segment of makefile, and parse them.
1196 func_eval (char *o
, char **argv
, const char *funcname
)
1201 /* Eval the buffer. Pop the current variable buffer setting so that the
1202 eval'd code can use its own without conflicting. */
1204 install_variable_buffer (&buf
, &len
);
1206 eval_buffer (argv
[0]);
1208 restore_variable_buffer (buf
, len
);
1215 func_value (char *o
, char **argv
, const char *funcname
)
1217 /* Look up the variable. */
1218 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1220 /* Copy its value into the output buffer without expanding it. */
1222 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1228 \r is replaced on UNIX as well. Is this desirable?
1231 fold_newlines (char *buffer
, int *length
)
1235 char *last_nonnl
= buffer
-1;
1237 for (; *src
!= '\0'; ++src
)
1239 if (src
[0] == '\r' && src
[1] == '\n')
1251 *(++last_nonnl
) = '\0';
1252 *length
= last_nonnl
- buffer
;
1257 int shell_function_pid
= 0, shell_function_completed
;
1263 #include <windows.h>
1265 #include "sub_proc.h"
1269 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1271 SECURITY_ATTRIBUTES saAttr
;
1279 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1280 saAttr
.bInheritHandle
= TRUE
;
1281 saAttr
.lpSecurityDescriptor
= NULL
;
1283 if (DuplicateHandle (GetCurrentProcess(),
1284 GetStdHandle(STD_INPUT_HANDLE
),
1285 GetCurrentProcess(),
1289 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1290 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1294 if (DuplicateHandle(GetCurrentProcess(),
1295 GetStdHandle(STD_ERROR_HANDLE
),
1296 GetCurrentProcess(),
1300 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1301 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1305 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1306 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1308 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1311 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1313 /* make sure that CreateProcess() has Path it needs */
1314 sync_Path_environment();
1316 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1317 /* register process for wait */
1318 process_register(hProcess
);
1320 /* set the pid for returning to caller */
1321 *pid_p
= (int) hProcess
;
1323 /* set up to read data from child */
1324 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1326 /* this will be closed almost right away */
1327 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1329 /* reap/cleanup the failed process */
1330 process_cleanup(hProcess
);
1332 /* close handles which were duplicated, they weren't used */
1336 /* close pipe handles, they won't be used */
1337 CloseHandle(hChildOutRd
);
1338 CloseHandle(hChildOutWr
);
1340 /* set status for return */
1341 pipedes
[0] = pipedes
[1] = -1;
1350 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1353 /* MSDOS can't fork, but it has `popen'. */
1354 struct variable
*sh
= lookup_variable ("SHELL", 5);
1356 extern int dos_command_running
, dos_status
;
1358 /* Make sure not to bother processing an empty line. */
1359 while (isblank ((unsigned char)*text
))
1366 char buf
[PATH_MAX
+ 7];
1367 /* This makes sure $SHELL value is used by $(shell), even
1368 though the target environment is not passed to it. */
1369 sprintf (buf
, "SHELL=%s", sh
->value
);
1375 dos_command_running
= 1;
1377 /* If dos_status becomes non-zero, it means the child process
1378 was interrupted by a signal, like SIGINT or SIGQUIT. See
1379 fatal_error_signal in commands.c. */
1380 fpipe
= popen (text
, "rt");
1381 dos_command_running
= 0;
1382 if (!fpipe
|| dos_status
)
1388 else if (errno
== 0)
1390 shell_function_completed
= -1;
1394 pipedes
[0] = fileno (fpipe
);
1395 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1397 shell_function_completed
= 1;
1404 Do shell spawning, with the naughty bits for different OSes.
1409 /* VMS can't do $(shell ...) */
1410 #define func_shell 0
1415 func_shell (char *o
, char **argv
, const char *funcname
)
1417 char* batch_filename
= NULL
;
1423 char **command_argv
;
1430 /* Construct the argument list. */
1431 command_argv
= construct_command_argv (argv
[0],
1432 (char **) NULL
, (struct file
*) 0,
1434 if (command_argv
== 0)
1438 /* Using a target environment for `shell' loses in cases like:
1439 export var = $(shell echo foobie)
1440 because target_environment hits a loop trying to expand $(var)
1441 to put it in the environment. This is even more confusing when
1442 var was not explicitly exported, but just appeared in the
1443 calling environment. */
1447 /* For error messages. */
1448 if (reading_file
!= 0)
1450 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1451 sprintf (error_prefix
,
1452 "%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;
1468 #elif defined(__MSDOS__)
1470 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1473 perror_with_name (error_prefix
, "pipe");
1479 if (pipe (pipedes
) < 0)
1481 perror_with_name (error_prefix
, "pipe");
1487 /* close some handles that are unnecessary for the child process */
1488 CLOSE_ON_EXEC(pipedes
[1]);
1489 CLOSE_ON_EXEC(pipedes
[0]);
1490 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1491 pid
= child_execute_job (0, pipedes
[1], command_argv
, envp
);
1493 perror_with_name (error_prefix
, "spawn");
1495 # else /* ! __EMX__ */
1499 perror_with_name (error_prefix
, "fork");
1501 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1508 /* We are the parent. */
1511 unsigned int maxlen
;
1514 /* Record the PID for reap_children. */
1515 shell_function_pid
= pid
;
1517 shell_function_completed
= 0;
1519 /* Free the storage only the child needed. */
1520 free (command_argv
[0]);
1521 free ((char *) command_argv
);
1523 /* Close the write side of the pipe. */
1524 (void) close (pipedes
[1]);
1527 /* Set up and read from the pipe. */
1530 buffer
= (char *) xmalloc (maxlen
+ 1);
1532 /* Read from the pipe until it gets EOF. */
1533 for (i
= 0; ; i
+= cc
)
1538 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1541 EINTRLOOP (cc
, read (pipedes
[0], &buffer
[i
], maxlen
- i
));
1547 /* Close the read side of the pipe. */
1550 (void) pclose (fpipe
);
1552 (void) close (pipedes
[0]);
1555 /* Loop until child_handler or reap_children() sets
1556 shell_function_completed to the status of our child shell. */
1557 while (shell_function_completed
== 0)
1558 reap_children (1, 0);
1560 if (batch_filename
) {
1561 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1563 remove (batch_filename
);
1564 free (batch_filename
);
1566 shell_function_pid
= 0;
1568 /* The child_handler function will set shell_function_completed
1569 to 1 when the child dies normally, or to -1 if it
1570 dies with status 127, which is most likely an exec fail. */
1572 if (shell_function_completed
== -1)
1574 /* This most likely means that the execvp failed,
1575 so we should just write out the error message
1576 that came in over the pipe from the child. */
1577 fputs (buffer
, stderr
);
1582 /* The child finished normally. Replace all
1583 newlines in its output with spaces, and put
1584 that in the variable output buffer. */
1585 fold_newlines (buffer
, &i
);
1586 o
= variable_buffer_output (o
, buffer
, i
);
1597 /* Do the Amiga version of func_shell. */
1600 func_shell (char *o
, char **argv
, const char *funcname
)
1602 /* Amiga can't fork nor spawn, but I can start a program with
1603 redirection of my choice. However, this means that we
1604 don't have an opportunity to reopen stdout to trap it. Thus,
1605 we save our own stdout onto a new descriptor and dup a temp
1606 file's descriptor onto our stdout temporarily. After we
1607 spawn the shell program, we dup our own stdout back to the
1608 stdout descriptor. The buffer reading is the same as above,
1609 except that we're now reading from a file. */
1611 #include <dos/dos.h>
1612 #include <proto/dos.h>
1615 char tmp_output
[FILENAME_MAX
];
1616 unsigned int maxlen
= 200;
1618 char * buffer
, * ptr
;
1621 char* batch_filename
= NULL
;
1623 /* Construct the argument list. */
1624 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1625 (struct file
*) 0, &batch_filename
);
1626 if (command_argv
== 0)
1629 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1630 Ideally we would use main.c:open_tmpfile(), but this uses a special
1631 Open(), not fopen(), and I'm not familiar enough with the code to mess
1633 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1634 mktemp (tmp_output
);
1635 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1637 for (aptr
=command_argv
; *aptr
; aptr
++)
1638 len
+= strlen (*aptr
) + 1;
1640 buffer
= xmalloc (len
+ 1);
1643 for (aptr
=command_argv
; *aptr
; aptr
++)
1645 strcpy (ptr
, *aptr
);
1646 ptr
+= strlen (ptr
) + 1;
1653 Execute (buffer
, NULL
, child_stdout
);
1656 Close (child_stdout
);
1658 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1660 buffer
= xmalloc (maxlen
);
1667 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1670 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1675 Close (child_stdout
);
1677 fold_newlines (buffer
, &i
);
1678 o
= variable_buffer_output (o
, buffer
, i
);
1688 equality. Return is string-boolean, ie, the empty string is false.
1691 func_eq (char* o
, char **argv
, char *funcname
)
1693 int result
= ! strcmp (argv
[0], argv
[1]);
1694 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1700 string-boolean not operator.
1703 func_not (char* o
, char **argv
, char *funcname
)
1707 while (isspace ((unsigned char)*s
))
1710 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1716 /* Lookup table for builtin functions.
1718 This doesn't have to be sorted; we use a straight lookup. We might gain
1719 some efficiency by moving most often used functions to the start of the
1722 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1723 comma-separated values are treated as arguments.
1725 EXPAND_ARGS means that all arguments should be expanded before invocation.
1726 Functions that do namespace tricks (foreach) don't automatically expand. */
1728 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1731 static struct function_table_entry function_table_init
[] =
1733 /* Name/size */ /* MIN MAX EXP? Function */
1734 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1735 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1736 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1737 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1738 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1739 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1740 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1741 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1742 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1743 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1744 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1745 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1746 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1747 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1748 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1749 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1750 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1751 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1752 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1753 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1754 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1755 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1756 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1757 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1758 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1759 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1760 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1761 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1763 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1764 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1768 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1771 /* These must come after the definition of function_table. */
1774 expand_builtin_function (char *o
, int argc
, char **argv
,
1775 const struct function_table_entry
*entry_p
)
1777 if (argc
< (int)entry_p
->minimum_args
)
1778 fatal (reading_file
,
1779 _("Insufficient number of arguments (%d) to function `%s'"),
1780 argc
, entry_p
->name
);
1782 /* I suppose technically some function could do something with no
1783 arguments, but so far none do, so just test it for all functions here
1784 rather than in each one. We can change it later if necessary. */
1789 if (!entry_p
->func_ptr
)
1790 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1793 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1796 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1797 opening ( or { and is not null-terminated. If a function invocation
1798 is found, expand it into the buffer at *OP, updating *OP, incrementing
1799 *STRINGP past the reference and returning nonzero. If not, return zero. */
1802 handle_function (char **op
, char **stringp
)
1804 const struct function_table_entry
*entry_p
;
1805 char openparen
= (*stringp
)[0];
1806 char closeparen
= openparen
== '(' ? ')' : '}';
1811 char **argv
, **argvp
;
1816 entry_p
= lookup_function (beg
);
1821 /* We found a builtin function. Find the beginning of its arguments (skip
1822 whitespace after the name). */
1824 beg
= next_token (beg
+ entry_p
->len
);
1826 /* Find the end of the function invocation, counting nested use of
1827 whichever kind of parens we use. Since we're looking, count commas
1828 to get a rough estimate of how many arguments we might have. The
1829 count might be high, but it'll never be low. */
1831 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1834 else if (*end
== openparen
)
1836 else if (*end
== closeparen
&& --count
< 0)
1840 fatal (reading_file
,
1841 _("unterminated call to function `%s': missing `%c'"),
1842 entry_p
->name
, closeparen
);
1846 /* Get some memory to store the arg pointers. */
1847 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1849 /* Chop the string into arguments, then a nul. As soon as we hit
1850 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1853 If we're expanding, store pointers to the expansion of each one. If
1854 not, make a duplicate of the string and point into that, nul-terminating
1857 if (!entry_p
->expand_args
)
1859 int len
= end
- beg
;
1861 p
= xmalloc (len
+1);
1862 memcpy (p
, beg
, len
);
1868 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1874 if (nargs
== entry_p
->maximum_args
1875 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1878 if (entry_p
->expand_args
)
1879 *argvp
= expand_argument (p
, next
);
1890 /* Finally! Run the function... */
1891 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1894 if (entry_p
->expand_args
)
1895 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1904 /* User-defined functions. Expand the first argument as either a builtin
1905 function or a make variable, in the context of the rest of the arguments
1906 assigned to $1, $2, ... $N. $0 is the name of the function. */
1909 func_call (char *o
, char **argv
, const char *funcname
)
1911 static int max_args
= 0;
1918 const struct function_table_entry
*entry_p
;
1921 /* There is no way to define a variable with a space in the name, so strip
1922 leading and trailing whitespace as a favor to the user. */
1924 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
1927 cp
= fname
+ strlen (fname
) - 1;
1928 while (cp
> fname
&& isspace ((unsigned char)*cp
))
1932 /* Calling nothing is a no-op */
1936 /* Are we invoking a builtin function? */
1938 entry_p
= lookup_function (fname
);
1942 /* How many arguments do we have? */
1943 for (i
=0; argv
[i
+1]; ++i
)
1946 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
1949 /* Not a builtin, so the first argument is the name of a variable to be
1950 expanded and interpreted as a function. Find it. */
1951 flen
= strlen (fname
);
1953 v
= lookup_variable (fname
, flen
);
1956 warn_undefined (fname
, flen
);
1958 if (v
== 0 || *v
->value
== '\0')
1961 body
= (char *) alloca (flen
+ 4);
1964 memcpy (body
+ 2, fname
, flen
);
1966 body
[flen
+3] = '\0';
1968 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1970 push_new_variable_scope ();
1972 for (i
=0; *argv
; ++i
, ++argv
)
1976 sprintf (num
, "%d", i
);
1977 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
1980 /* If the number of arguments we have is < max_args, it means we're inside
1981 a recursive invocation of $(call ...). Fill in the remaining arguments
1982 in the new scope with the empty value, to hide them from this
1985 for (; i
< max_args
; ++i
)
1989 sprintf (num
, "%d", i
);
1990 define_variable (num
, strlen (num
), "", o_automatic
, 0);
1993 /* Expand the body in the context of the arguments, adding the result to
1994 the variable buffer. */
1996 v
->exp_count
= EXP_COUNT_MAX
;
1998 saved_args
= max_args
;
2000 o
= variable_expand_string (o
, body
, flen
+3);
2001 max_args
= saved_args
;
2005 pop_variable_scope ();
2007 return o
+ strlen (o
);
2011 hash_init_function_table (void)
2013 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
2014 function_table_entry_hash_1
, function_table_entry_hash_2
,
2015 function_table_entry_hash_cmp
);
2016 hash_load (&function_table
, function_table_init
,
2017 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));