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 (const char **begpp
, const char **endpp
)
679 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
681 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
683 return (char *)*begpp
;
687 check_numeric (const char *s
, const char *message
)
689 const char *end
= s
+ strlen (s
) - 1;
691 strip_whitespace (&s
, &end
);
693 for (; s
<= end
; ++s
)
694 if (!ISDIGIT (*s
)) /* ISDIGIT only evals its arg once: see make.h. */
697 if (s
<= end
|| end
- beg
< 0)
698 fatal (reading_file
, "%s: '%s'", message
, beg
);
704 func_word (char *o
, char **argv
, const char *funcname
)
710 /* Check the first argument. */
711 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
715 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
719 while ((p
= find_next_token (&end_p
, 0)) != 0)
724 o
= variable_buffer_output (o
, p
, end_p
- p
);
730 func_wordlist (char *o
, char **argv
, const char *funcname
)
734 /* Check the arguments. */
735 check_numeric (argv
[0],
736 _("non-numeric first argument to `wordlist' function"));
737 check_numeric (argv
[1],
738 _("non-numeric second argument to `wordlist' function"));
740 start
= atoi (argv
[0]);
741 count
= atoi (argv
[1]) - start
+ 1;
746 char *end_p
= argv
[2];
748 /* Find the beginning of the "start"th word. */
749 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
754 /* Find the end of the "count"th word from start. */
755 while (--count
&& (find_next_token (&end_p
, 0) != 0))
758 /* Return the stuff in the middle. */
759 o
= variable_buffer_output (o
, p
, end_p
- p
);
767 func_findstring (char *o
, char **argv
, const char *funcname
)
769 /* Find the first occurrence of the first string in the second. */
770 int i
= strlen (argv
[0]);
771 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
772 o
= variable_buffer_output (o
, argv
[0], i
);
778 func_foreach (char *o
, char **argv
, const char *funcname
)
780 /* expand only the first two. */
781 char *varname
= expand_argument (argv
[0], NULL
);
782 char *list
= expand_argument (argv
[1], NULL
);
783 char *body
= argv
[2];
786 char *list_iterator
= list
;
789 register struct variable
*var
;
791 push_new_variable_scope ();
792 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
794 /* loop through LIST, put the value in VAR and expand BODY */
795 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
804 var
->value
= (char *) xstrdup ((char*) p
);
808 result
= allocated_variable_expand (body
);
810 o
= variable_buffer_output (o
, result
, strlen (result
));
811 o
= variable_buffer_output (o
, " ", 1);
817 /* Kill the last space. */
820 pop_variable_scope ();
830 struct a_word
*chain
;
837 a_word_hash_1 (const void *key
)
839 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
843 a_word_hash_2 (const void *key
)
845 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
849 a_word_hash_cmp (const void *x
, const void *y
)
851 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
854 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
855 ((struct a_word
const *) y
)->str
);
860 struct a_pattern
*next
;
868 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
870 struct a_word
*wordhead
;
871 struct a_word
**wordtail
;
873 struct a_pattern
*pathead
;
874 struct a_pattern
**pattail
;
875 struct a_pattern
*pp
;
877 struct hash_table a_word_table
;
878 int is_filter
= streq (funcname
, "filter");
879 char *pat_iterator
= argv
[0];
880 char *word_iterator
= argv
[1];
887 /* Chop ARGV[0] up into patterns to match against the words. */
890 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
892 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
895 pattail
= &pat
->next
;
897 if (*pat_iterator
!= '\0')
902 pat
->save_c
= p
[len
];
904 pat
->percent
= find_percent (p
);
905 if (pat
->percent
== 0)
910 /* Chop ARGV[1] up into words to match against the patterns. */
912 wordtail
= &wordhead
;
913 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
915 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
918 wordtail
= &word
->next
;
920 if (*word_iterator
!= '\0')
932 /* Only use a hash table if arg list lengths justifies the cost. */
933 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
936 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
937 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
939 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
949 /* Run each pattern through the words, killing words. */
950 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
953 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
954 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
957 struct a_word a_word_key
;
958 a_word_key
.str
= pp
->str
;
959 a_word_key
.length
= pp
->length
;
960 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
968 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
969 wp
->matched
|= (wp
->length
== pp
->length
970 && strneq (pp
->str
, wp
->str
, wp
->length
));
973 /* Output the words that matched (or didn't, for filter-out). */
974 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
975 if (is_filter
? wp
->matched
: !wp
->matched
)
977 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
978 o
= variable_buffer_output (o
, " ", 1);
983 /* Kill the last space. */
987 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
988 pp
->str
[pp
->length
] = pp
->save_c
;
991 hash_free (&a_word_table
, 0);
998 func_strip (char *o
, char **argv
, const char *funcname
)
1008 while (isspace ((unsigned char)*p
))
1011 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1015 o
= variable_buffer_output (o
, word_start
, i
);
1016 o
= variable_buffer_output (o
, " ", 1);
1021 /* Kill the last space. */
1027 Print a warning or fatal message.
1030 func_error (char *o
, char **argv
, const char *funcname
)
1036 /* The arguments will be broken on commas. Rather than create yet
1037 another special case where function arguments aren't broken up,
1038 just create a format string that puts them back together. */
1039 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1040 len
+= strlen (*argvp
) + 2;
1042 p
= msg
= (char *) alloca (len
+ 1);
1044 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1047 p
+= strlen (*argvp
);
1053 if (*funcname
== 'e')
1054 fatal (reading_file
, "%s", msg
);
1056 /* The warning function expands to the empty string. */
1057 error (reading_file
, "%s", msg
);
1064 chop argv[0] into words, and sort them.
1067 func_sort (char *o
, char **argv
, const char *funcname
)
1071 register int wordi
= 0;
1073 /* Chop ARGV[0] into words and put them in WORDS. */
1079 while ((p
= find_next_token (&t
, &len
)) != 0)
1081 if (wordi
>= nwords
- 1)
1083 nwords
= (2 * nwords
) + 5;
1084 words
= (char **) xrealloc ((char *) words
,
1085 nwords
* sizeof (char *));
1087 words
[wordi
++] = savestring (p
, len
);
1093 /* Now sort the list of words. */
1094 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1096 /* Now write the sorted list. */
1097 for (i
= 0; i
< wordi
; ++i
)
1099 len
= strlen (words
[i
]);
1100 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1101 || strcmp (words
[i
], words
[i
+ 1]))
1103 o
= variable_buffer_output (o
, words
[i
], len
);
1104 o
= variable_buffer_output (o
, " ", 1);
1108 /* Kill the last space. */
1117 $(if condition,true-part[,false-part])
1119 CONDITION is false iff it evaluates to an empty string. White
1120 space before and after condition are stripped before evaluation.
1122 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1123 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1124 you can use $(if ...) to create side-effects (with $(shell ...), for
1129 func_if (char *o
, char **argv
, const char *funcname
)
1131 const char *begp
= argv
[0];
1132 const char *endp
= begp
+ strlen (argv
[0]);
1135 /* Find the result of the condition: if we have a value, and it's not
1136 empty, the condition is true. If we don't have a value, or it's the
1137 empty string, then it's false. */
1139 strip_whitespace (&begp
, &endp
);
1143 char *expansion
= expand_argument (begp
, NULL
);
1145 result
= strlen (expansion
);
1149 /* If the result is true (1) we want to eval the first argument, and if
1150 it's false (0) we want to eval the second. If the argument doesn't
1151 exist we do nothing, otherwise expand it and add to the buffer. */
1153 argv
+= 1 + !result
;
1159 expansion
= expand_argument (argv
[0], NULL
);
1161 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1170 func_wildcard (char *o
, char **argv
, const char *funcname
)
1174 o
= wildcard_expansion (argv
[0], o
);
1176 char *p
= string_glob (argv
[0]);
1177 o
= variable_buffer_output (o
, p
, strlen (p
));
1183 $(eval <makefile string>)
1185 Always resolves to the empty string.
1187 Treat the arguments as a segment of makefile, and parse them.
1191 func_eval (char *o
, char **argv
, const char *funcname
)
1196 /* Eval the buffer. Pop the current variable buffer setting so that the
1197 eval'd code can use its own without conflicting. */
1199 install_variable_buffer (&buf
, &len
);
1201 eval_buffer (argv
[0]);
1203 restore_variable_buffer (buf
, len
);
1210 func_value (char *o
, char **argv
, const char *funcname
)
1212 /* Look up the variable. */
1213 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1215 /* Copy its value into the output buffer without expanding it. */
1217 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1223 \r is replaced on UNIX as well. Is this desirable?
1226 fold_newlines (char *buffer
, int *length
)
1230 char *last_nonnl
= buffer
-1;
1232 for (; *src
!= '\0'; ++src
)
1234 if (src
[0] == '\r' && src
[1] == '\n')
1246 *(++last_nonnl
) = '\0';
1247 *length
= last_nonnl
- buffer
;
1252 int shell_function_pid
= 0, shell_function_completed
;
1258 #include <windows.h>
1260 #include "sub_proc.h"
1264 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1266 SECURITY_ATTRIBUTES saAttr
;
1274 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1275 saAttr
.bInheritHandle
= TRUE
;
1276 saAttr
.lpSecurityDescriptor
= NULL
;
1278 if (DuplicateHandle (GetCurrentProcess(),
1279 GetStdHandle(STD_INPUT_HANDLE
),
1280 GetCurrentProcess(),
1284 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1285 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1289 if (DuplicateHandle(GetCurrentProcess(),
1290 GetStdHandle(STD_ERROR_HANDLE
),
1291 GetCurrentProcess(),
1295 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1296 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1300 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1301 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1303 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1306 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1308 /* make sure that CreateProcess() has Path it needs */
1309 sync_Path_environment();
1311 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1312 /* register process for wait */
1313 process_register(hProcess
);
1315 /* set the pid for returning to caller */
1316 *pid_p
= (int) hProcess
;
1318 /* set up to read data from child */
1319 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1321 /* this will be closed almost right away */
1322 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1324 /* reap/cleanup the failed process */
1325 process_cleanup(hProcess
);
1327 /* close handles which were duplicated, they weren't used */
1331 /* close pipe handles, they won't be used */
1332 CloseHandle(hChildOutRd
);
1333 CloseHandle(hChildOutWr
);
1335 /* set status for return */
1336 pipedes
[0] = pipedes
[1] = -1;
1345 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1348 /* MSDOS can't fork, but it has `popen'. */
1349 struct variable
*sh
= lookup_variable ("SHELL", 5);
1351 extern int dos_command_running
, dos_status
;
1353 /* Make sure not to bother processing an empty line. */
1354 while (isblank ((unsigned char)*text
))
1361 char buf
[PATH_MAX
+ 7];
1362 /* This makes sure $SHELL value is used by $(shell), even
1363 though the target environment is not passed to it. */
1364 sprintf (buf
, "SHELL=%s", sh
->value
);
1370 dos_command_running
= 1;
1372 /* If dos_status becomes non-zero, it means the child process
1373 was interrupted by a signal, like SIGINT or SIGQUIT. See
1374 fatal_error_signal in commands.c. */
1375 fpipe
= popen (text
, "rt");
1376 dos_command_running
= 0;
1377 if (!fpipe
|| dos_status
)
1383 else if (errno
== 0)
1385 shell_function_completed
= -1;
1389 pipedes
[0] = fileno (fpipe
);
1390 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1392 shell_function_completed
= 1;
1399 Do shell spawning, with the naughty bits for different OSes.
1404 /* VMS can't do $(shell ...) */
1405 #define func_shell 0
1410 func_shell (char *o
, char **argv
, const char *funcname
)
1412 char* batch_filename
= NULL
;
1418 char **command_argv
;
1425 /* Construct the argument list. */
1426 command_argv
= construct_command_argv (argv
[0],
1427 (char **) NULL
, (struct file
*) 0,
1429 if (command_argv
== 0)
1433 /* Using a target environment for `shell' loses in cases like:
1434 export var = $(shell echo foobie)
1435 because target_environment hits a loop trying to expand $(var)
1436 to put it in the environment. This is even more confusing when
1437 var was not explicitly exported, but just appeared in the
1438 calling environment. */
1442 /* For error messages. */
1443 if (reading_file
!= 0)
1445 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1446 sprintf (error_prefix
,
1447 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1453 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1455 if (pipedes
[0] < 0) {
1456 /* open of the pipe failed, mark as failed execution */
1457 shell_function_completed
= -1;
1461 #else /* WINDOWS32 */
1464 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1467 perror_with_name (error_prefix
, "pipe");
1471 if (pipe (pipedes
) < 0)
1473 perror_with_name (error_prefix
, "pipe");
1479 perror_with_name (error_prefix
, "fork");
1481 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1483 # endif /* ! __MSDOS__ */
1485 #endif /* WINDOWS32 */
1487 /* We are the parent. */
1490 unsigned int maxlen
;
1493 /* Record the PID for reap_children. */
1494 shell_function_pid
= pid
;
1496 shell_function_completed
= 0;
1498 /* Free the storage only the child needed. */
1499 free (command_argv
[0]);
1500 free ((char *) command_argv
);
1502 /* Close the write side of the pipe. */
1503 (void) close (pipedes
[1]);
1506 /* Set up and read from the pipe. */
1509 buffer
= (char *) xmalloc (maxlen
+ 1);
1511 /* Read from the pipe until it gets EOF. */
1512 for (i
= 0; ; i
+= cc
)
1517 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1520 cc
= read (pipedes
[0], &buffer
[i
], maxlen
- i
);
1526 /* Close the read side of the pipe. */
1529 (void) pclose (fpipe
);
1531 (void) close (pipedes
[0]);
1534 /* Loop until child_handler sets shell_function_completed
1535 to the status of our child shell. */
1536 while (shell_function_completed
== 0)
1537 reap_children (1, 0);
1539 if (batch_filename
) {
1540 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1542 remove (batch_filename
);
1543 free (batch_filename
);
1545 shell_function_pid
= 0;
1547 /* The child_handler function will set shell_function_completed
1548 to 1 when the child dies normally, or to -1 if it
1549 dies with status 127, which is most likely an exec fail. */
1551 if (shell_function_completed
== -1)
1553 /* This most likely means that the execvp failed,
1554 so we should just write out the error message
1555 that came in over the pipe from the child. */
1556 fputs (buffer
, stderr
);
1561 /* The child finished normally. Replace all
1562 newlines in its output with spaces, and put
1563 that in the variable output buffer. */
1564 fold_newlines (buffer
, &i
);
1565 o
= variable_buffer_output (o
, buffer
, i
);
1576 /* Do the Amiga version of func_shell. */
1579 func_shell (char *o
, char **argv
, const char *funcname
)
1581 /* Amiga can't fork nor spawn, but I can start a program with
1582 redirection of my choice. However, this means that we
1583 don't have an opportunity to reopen stdout to trap it. Thus,
1584 we save our own stdout onto a new descriptor and dup a temp
1585 file's descriptor onto our stdout temporarily. After we
1586 spawn the shell program, we dup our own stdout back to the
1587 stdout descriptor. The buffer reading is the same as above,
1588 except that we're now reading from a file. */
1590 #include <dos/dos.h>
1591 #include <proto/dos.h>
1594 char tmp_output
[FILENAME_MAX
];
1595 unsigned int maxlen
= 200;
1597 char * buffer
, * ptr
;
1600 char* batch_filename
= NULL
;
1602 /* Construct the argument list. */
1603 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1604 (struct file
*) 0, &batch_filename
);
1605 if (command_argv
== 0)
1608 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1609 Ideally we would use main.c:open_tmpfile(), but this uses a special
1610 Open(), not fopen(), and I'm not familiar enough with the code to mess
1612 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1613 mktemp (tmp_output
);
1614 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1616 for (aptr
=command_argv
; *aptr
; aptr
++)
1617 len
+= strlen (*aptr
) + 1;
1619 buffer
= xmalloc (len
+ 1);
1622 for (aptr
=command_argv
; *aptr
; aptr
++)
1624 strcpy (ptr
, *aptr
);
1625 ptr
+= strlen (ptr
) + 1;
1632 Execute (buffer
, NULL
, child_stdout
);
1635 Close (child_stdout
);
1637 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1639 buffer
= xmalloc (maxlen
);
1646 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1649 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1654 Close (child_stdout
);
1656 fold_newlines (buffer
, &i
);
1657 o
= variable_buffer_output (o
, buffer
, i
);
1667 equality. Return is string-boolean, ie, the empty string is false.
1670 func_eq (char* o
, char **argv
, char *funcname
)
1672 int result
= ! strcmp (argv
[0], argv
[1]);
1673 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1679 string-boolean not operator.
1682 func_not (char* o
, char **argv
, char *funcname
)
1686 while (isspace ((unsigned char)*s
))
1689 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1695 /* Lookup table for builtin functions.
1697 This doesn't have to be sorted; we use a straight lookup. We might gain
1698 some efficiency by moving most often used functions to the start of the
1701 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1702 comma-separated values are treated as arguments.
1704 EXPAND_ARGS means that all arguments should be expanded before invocation.
1705 Functions that do namespace tricks (foreach) don't automatically expand. */
1707 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1710 static struct function_table_entry function_table_init
[] =
1712 /* Name/size */ /* MIN MAX EXP? Function */
1713 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1714 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1715 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1716 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1717 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1718 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1719 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1720 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1721 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1722 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1723 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1724 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1725 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1726 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1727 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1728 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1729 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1730 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1731 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1732 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1733 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1734 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1735 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1736 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1737 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1738 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1739 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1740 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1742 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1743 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1747 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1750 /* These must come after the definition of function_table. */
1753 expand_builtin_function (char *o
, int argc
, char **argv
,
1754 const struct function_table_entry
*entry_p
)
1756 if (argc
< (int)entry_p
->minimum_args
)
1757 fatal (reading_file
,
1758 _("Insufficient number of arguments (%d) to function `%s'"),
1759 argc
, entry_p
->name
);
1761 /* I suppose technically some function could do something with no
1762 arguments, but so far none do, so just test it for all functions here
1763 rather than in each one. We can change it later if necessary. */
1768 if (!entry_p
->func_ptr
)
1769 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1772 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1775 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1776 opening ( or { and is not null-terminated. If a function invocation
1777 is found, expand it into the buffer at *OP, updating *OP, incrementing
1778 *STRINGP past the reference and returning nonzero. If not, return zero. */
1781 handle_function (char **op
, char **stringp
)
1783 const struct function_table_entry
*entry_p
;
1784 char openparen
= (*stringp
)[0];
1785 char closeparen
= openparen
== '(' ? ')' : '}';
1790 char **argv
, **argvp
;
1795 entry_p
= lookup_function (beg
);
1800 /* We found a builtin function. Find the beginning of its arguments (skip
1801 whitespace after the name). */
1803 beg
= next_token (beg
+ entry_p
->len
);
1805 /* Find the end of the function invocation, counting nested use of
1806 whichever kind of parens we use. Since we're looking, count commas
1807 to get a rough estimate of how many arguments we might have. The
1808 count might be high, but it'll never be low. */
1810 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1813 else if (*end
== openparen
)
1815 else if (*end
== closeparen
&& --count
< 0)
1819 fatal (reading_file
,
1820 _("unterminated call to function `%s': missing `%c'"),
1821 entry_p
->name
, closeparen
);
1825 /* Get some memory to store the arg pointers. */
1826 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1828 /* Chop the string into arguments, then a nul. As soon as we hit
1829 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1832 If we're expanding, store pointers to the expansion of each one. If
1833 not, make a duplicate of the string and point into that, nul-terminating
1836 if (!entry_p
->expand_args
)
1838 int len
= end
- beg
;
1840 p
= xmalloc (len
+1);
1841 memcpy (p
, beg
, len
);
1847 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1853 if (nargs
== entry_p
->maximum_args
1854 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1857 if (entry_p
->expand_args
)
1858 *argvp
= expand_argument (p
, next
);
1869 /* Finally! Run the function... */
1870 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1873 if (entry_p
->expand_args
)
1874 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1883 /* User-defined functions. Expand the first argument as either a builtin
1884 function or a make variable, in the context of the rest of the arguments
1885 assigned to $1, $2, ... $N. $0 is the name of the function. */
1888 func_call (char *o
, char **argv
, const char *funcname
)
1890 static int max_args
= 0;
1897 const struct function_table_entry
*entry_p
;
1900 /* There is no way to define a variable with a space in the name, so strip
1901 leading and trailing whitespace as a favor to the user. */
1903 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
1906 cp
= fname
+ strlen (fname
) - 1;
1907 while (cp
> fname
&& isspace ((unsigned char)*cp
))
1911 /* Calling nothing is a no-op */
1915 /* Are we invoking a builtin function? */
1917 entry_p
= lookup_function (fname
);
1921 /* How many arguments do we have? */
1922 for (i
=0; argv
[i
+1]; ++i
)
1925 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
1928 /* Not a builtin, so the first argument is the name of a variable to be
1929 expanded and interpreted as a function. Find it. */
1930 flen
= strlen (fname
);
1932 v
= lookup_variable (fname
, flen
);
1935 warn_undefined (fname
, flen
);
1937 if (v
== 0 || *v
->value
== '\0')
1940 body
= (char *) alloca (flen
+ 4);
1943 memcpy (body
+ 2, fname
, flen
);
1945 body
[flen
+3] = '\0';
1947 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1949 push_new_variable_scope ();
1951 for (i
=0; *argv
; ++i
, ++argv
)
1955 sprintf (num
, "%d", i
);
1956 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
1959 /* If the number of arguments we have is < max_args, it means we're inside
1960 a recursive invocation of $(call ...). Fill in the remaining arguments
1961 in the new scope with the empty value, to hide them from this
1964 for (; i
< max_args
; ++i
)
1968 sprintf (num
, "%d", i
);
1969 define_variable (num
, strlen (num
), "", o_automatic
, 0);
1972 /* Expand the body in the context of the arguments, adding the result to
1973 the variable buffer. */
1975 v
->exp_count
= EXP_COUNT_MAX
;
1977 saved_args
= max_args
;
1979 o
= variable_expand_string (o
, body
, flen
+3);
1980 max_args
= saved_args
;
1984 pop_variable_scope ();
1986 return o
+ strlen (o
);
1990 hash_init_function_table (void)
1992 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
1993 function_table_entry_hash_1
, function_table_entry_hash_2
,
1994 function_table_entry_hash_cmp
);
1995 hash_load (&function_table
, function_table_init
,
1996 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));