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 (void const *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 (void const *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 (void const *xv
, void const *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 (o
, text
, subst
, replace
, slen
, rlen
, by_word
, suffix_only
)
82 char *subst
, *replace
;
83 unsigned int slen
, rlen
;
84 int by_word
, suffix_only
;
86 register char *t
= text
;
89 if (slen
== 0 && !by_word
&& !suffix_only
)
91 /* The first occurrence of "" in any string is its end. */
92 o
= variable_buffer_output (o
, t
, strlen (t
));
94 o
= variable_buffer_output (o
, replace
, rlen
);
100 if ((by_word
| suffix_only
) && slen
== 0)
101 /* When matching by words, the empty string should match
102 the end of each word, rather than the end of the whole text. */
103 p
= end_of_token (next_token (t
));
106 p
= sindex (t
, 0, subst
, slen
);
109 /* No more matches. Output everything left on the end. */
110 o
= variable_buffer_output (o
, t
, strlen (t
));
115 /* Output everything before this occurrence of the string to replace. */
117 o
= variable_buffer_output (o
, t
, p
- t
);
119 /* If we're substituting only by fully matched words,
120 or only at the ends of words, check that this case qualifies. */
122 && ((p
> t
&& !isblank ((unsigned char)p
[-1]))
123 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
125 && (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
126 /* Struck out. Output the rest of the string that is
127 no longer to be replaced. */
128 o
= variable_buffer_output (o
, subst
, slen
);
130 /* Output the replacement string. */
131 o
= variable_buffer_output (o
, replace
, rlen
);
133 /* Advance T past the string to be replaced. */
135 } while (*t
!= '\0');
141 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
142 and replacing strings matching PATTERN with REPLACE.
143 If PATTERN_PERCENT is not nil, PATTERN has already been
144 run through find_percent, and PATTERN_PERCENT is the result.
145 If REPLACE_PERCENT is not nil, REPLACE has already been
146 run through find_percent, and REPLACE_PERCENT is the result. */
149 patsubst_expand (o
, text
, pattern
, replace
, pattern_percent
, replace_percent
)
152 register char *pattern
, *replace
;
153 register char *pattern_percent
, *replace_percent
;
155 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
156 unsigned int replace_prepercent_len
, replace_postpercent_len
= 0;
161 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
162 will be collapsed before we call subst_expand if PATTERN has no %. */
163 if (replace_percent
== 0)
164 replace_percent
= find_percent (replace
);
165 if (replace_percent
!= 0)
167 /* Record the length of REPLACE before and after the % so
168 we don't have to compute these lengths more than once. */
169 replace_prepercent_len
= replace_percent
- replace
;
170 replace_postpercent_len
= strlen (replace_percent
+ 1);
173 /* We store the length of the replacement
174 so we only need to compute it once. */
175 replace_prepercent_len
= strlen (replace
);
177 if (pattern_percent
== 0)
178 pattern_percent
= find_percent (pattern
);
179 if (pattern_percent
== 0)
180 /* With no % in the pattern, this is just a simple substitution. */
181 return subst_expand (o
, text
, pattern
, replace
,
182 strlen (pattern
), strlen (replace
), 1, 0);
184 /* Record the length of PATTERN before and after the %
185 so we don't have to compute it more than once. */
186 pattern_prepercent_len
= pattern_percent
- pattern
;
187 pattern_postpercent_len
= strlen (pattern_percent
+ 1);
189 while ((t
= find_next_token (&text
, &len
)) != 0)
193 /* Is it big enough to match? */
194 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
197 /* Does the prefix match? */
198 if (!fail
&& pattern_prepercent_len
> 0
200 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-1]
201 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
204 /* Does the suffix match? */
205 if (!fail
&& pattern_postpercent_len
> 0
206 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
]
207 || t
[len
- pattern_postpercent_len
] != pattern_percent
[1]
208 || !strneq (&t
[len
- pattern_postpercent_len
],
209 &pattern_percent
[1], pattern_postpercent_len
- 1)))
213 /* It didn't match. Output the string. */
214 o
= variable_buffer_output (o
, t
, len
);
217 /* It matched. Output the replacement. */
219 /* Output the part of the replacement before the %. */
220 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
222 if (replace_percent
!= 0)
224 /* Output the part of the matched string that
225 matched the % in the pattern. */
226 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
227 len
- (pattern_prepercent_len
228 + pattern_postpercent_len
));
229 /* Output the part of the replacement after the %. */
230 o
= variable_buffer_output (o
, replace_percent
+ 1,
231 replace_postpercent_len
);
235 /* Output a space, but not if the replacement is "". */
236 if (fail
|| replace_prepercent_len
> 0
237 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
239 o
= variable_buffer_output (o
, " ", 1);
244 /* Kill the last space. */
251 /* Look up a function by name. */
253 static const struct function_table_entry
*
259 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
261 if (*e
== '\0' || isblank ((unsigned char) *e
))
263 struct function_table_entry function_table_entry_key
;
264 function_table_entry_key
.name
= s
;
265 function_table_entry_key
.len
= e
- s
;
267 return hash_find_item (&function_table
, &function_table_entry_key
);
273 /* Return 1 if PATTERN matches STR, 0 if not. */
276 pattern_matches (pattern
, percent
, str
)
277 register char *pattern
, *percent
, *str
;
279 unsigned int sfxlen
, strlength
;
283 unsigned int len
= strlen (pattern
) + 1;
284 char *new_chars
= (char *) alloca (len
);
285 bcopy (pattern
, new_chars
, len
);
287 percent
= find_percent (pattern
);
289 return streq (pattern
, str
);
292 sfxlen
= strlen (percent
+ 1);
293 strlength
= strlen (str
);
295 if (strlength
< (percent
- pattern
) + sfxlen
296 || !strneq (pattern
, str
, percent
- pattern
))
299 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
303 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
304 ENDPARENtheses), starting at PTR before END. Return a pointer to
307 If no next argument is found, return NULL.
311 find_next_argument (startparen
, endparen
, ptr
, end
)
319 for (; ptr
< end
; ++ptr
)
320 if (*ptr
== startparen
)
323 else if (*ptr
== endparen
)
330 else if (*ptr
== ',' && !count
)
333 /* We didn't find anything. */
338 /* Glob-expand LINE. The returned pointer is
339 only good until the next call to string_glob. */
345 static char *result
= 0;
346 static unsigned int length
;
347 register struct nameseq
*chain
;
348 register unsigned int idx
;
350 chain
= multi_glob (parse_file_seq
351 (&line
, '\0', sizeof (struct nameseq
),
352 /* We do not want parse_file_seq to strip `./'s.
353 That would break examples like:
354 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
356 sizeof (struct nameseq
));
361 result
= (char *) xmalloc (100);
367 register char *name
= chain
->name
;
368 unsigned int len
= strlen (name
);
370 struct nameseq
*next
= chain
->next
;
371 free ((char *) chain
);
374 /* multi_glob will pass names without globbing metacharacters
375 through as is, but we want only files that actually exist. */
376 if (file_exists_p (name
))
378 if (idx
+ len
+ 1 > length
)
380 length
+= (len
+ 1) * 2;
381 result
= (char *) xrealloc (result
, length
);
383 bcopy (name
, &result
[idx
], len
);
391 /* Kill the last space and terminate the string. */
395 result
[idx
- 1] = '\0';
405 func_patsubst (o
, argv
, funcname
)
408 const char *funcname
;
410 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
416 func_join (o
, argv
, funcname
)
419 const char *funcname
;
423 /* Write each word of the first argument directly followed
424 by the corresponding word of the second argument.
425 If the two arguments have a different number of words,
426 the excess words are just output separated by blanks. */
429 char *list1_iterator
= argv
[0];
430 char *list2_iterator
= argv
[1];
433 unsigned int len1
, len2
;
435 tp
= find_next_token (&list1_iterator
, &len1
);
437 o
= variable_buffer_output (o
, tp
, len1
);
439 pp
= find_next_token (&list2_iterator
, &len2
);
441 o
= variable_buffer_output (o
, pp
, len2
);
443 if (tp
!= 0 || pp
!= 0)
445 o
= variable_buffer_output (o
, " ", 1);
449 while (tp
!= 0 || pp
!= 0);
451 /* Kill the last blank. */
459 func_origin (o
, argv
, funcname
)
462 const char *funcname
;
464 /* Expand the argument. */
465 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
467 o
= variable_buffer_output (o
, "undefined", 9);
476 o
= variable_buffer_output (o
, "default", 7);
479 o
= variable_buffer_output (o
, "environment", 11);
482 o
= variable_buffer_output (o
, "file", 4);
485 o
= variable_buffer_output (o
, "environment override", 20);
488 o
= variable_buffer_output (o
, "command line", 12);
491 o
= variable_buffer_output (o
, "override", 8);
494 o
= variable_buffer_output (o
, "automatic", 9);
502 # define IS_PATHSEP(c) ((c) == ']')
504 # ifdef HAVE_DOS_PATHS
505 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
507 # define IS_PATHSEP(c) ((c) == '/')
513 func_notdir_suffix (o
, argv
, funcname
)
516 const char *funcname
;
518 /* Expand the argument. */
519 char *list_iterator
= argv
[0];
524 int is_suffix
= streq (funcname
, "suffix");
525 int is_notdir
= !is_suffix
;
526 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
531 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
544 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
546 #ifdef HAVE_DOS_PATHS
547 /* Handle the case of "d:foo/bar". */
548 else if (streq (funcname
, "notdir") && p2
[0] && p2
[1] == ':')
551 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
555 o
= variable_buffer_output (o
, p2
, len
);
557 if (is_notdir
|| p
>= p2
)
559 o
= variable_buffer_output (o
, " ", 1);
564 /* Kill last space. */
574 func_basename_dir (o
, argv
, funcname
)
577 const char *funcname
;
579 /* Expand the argument. */
585 int is_basename
= streq (funcname
, "basename");
586 int is_dir
= !is_basename
;
588 while ((p2
= find_next_token (&p3
, &len
)) != 0)
591 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
598 if (p
>= p2
&& (is_dir
))
599 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
600 else if (p
>= p2
&& (*p
== '.'))
601 o
= variable_buffer_output (o
, p2
, p
- p2
);
602 #ifdef HAVE_DOS_PATHS
603 /* Handle the "d:foobar" case */
604 else if (p2
[0] && p2
[1] == ':' && is_dir
)
605 o
= variable_buffer_output (o
, p2
, 2);
609 o
= variable_buffer_output (o
, "[]", 2);
612 o
= variable_buffer_output (o
, "./", 2);
614 ; /* Just a nop... */
618 /* The entire name is the basename. */
619 o
= variable_buffer_output (o
, p2
, len
);
621 o
= variable_buffer_output (o
, " ", 1);
625 /* Kill last space. */
633 func_addsuffix_addprefix (o
, argv
, funcname
)
636 const char *funcname
;
638 int fixlen
= strlen (argv
[0]);
639 char *list_iterator
= argv
[1];
640 int is_addprefix
= streq (funcname
, "addprefix");
641 int is_addsuffix
= !is_addprefix
;
647 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
650 o
= variable_buffer_output (o
, argv
[0], fixlen
);
651 o
= variable_buffer_output (o
, p
, len
);
653 o
= variable_buffer_output (o
, argv
[0], fixlen
);
654 o
= variable_buffer_output (o
, " ", 1);
659 /* Kill last space. */
666 func_subst (o
, argv
, funcname
)
669 const char *funcname
;
671 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
672 strlen (argv
[1]), 0, 0);
679 func_firstword (o
, argv
, funcname
)
682 const char *funcname
;
685 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
686 char *p
= find_next_token (&words
, &i
);
689 o
= variable_buffer_output (o
, p
, i
);
696 func_words (o
, argv
, funcname
)
699 const char *funcname
;
702 char *word_iterator
= argv
[0];
705 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
708 sprintf (buf
, "%d", i
);
709 o
= variable_buffer_output (o
, buf
, strlen (buf
));
716 strip_whitespace (begpp
, endpp
)
720 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
722 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
731 char *end
= p
+ strlen (p
) - 1;
733 strip_whitespace (&p
, &end
);
736 if (!ISDIGIT (*(p
++))) /* ISDIGIT only evals its arg once: see make.h. */
739 return (end
- beg
>= 0);
743 check_numeric (s
, message
)
748 fatal (reading_file
, message
);
754 func_word (o
, argv
, funcname
)
757 const char *funcname
;
763 /* Check the first argument. */
764 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
768 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
772 while ((p
= find_next_token (&end_p
, 0)) != 0)
777 o
= variable_buffer_output (o
, p
, end_p
- p
);
783 func_wordlist (o
, argv
, funcname
)
786 const char *funcname
;
790 /* Check the arguments. */
791 check_numeric (argv
[0],
792 _("non-numeric first argument to `wordlist' function"));
793 check_numeric (argv
[1],
794 _("non-numeric second argument to `wordlist' function"));
796 start
= atoi (argv
[0]);
797 count
= atoi (argv
[1]) - start
+ 1;
802 char *end_p
= argv
[2];
804 /* Find the beginning of the "start"th word. */
805 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
810 /* Find the end of the "count"th word from start. */
811 while (--count
&& (find_next_token (&end_p
, 0) != 0))
814 /* Return the stuff in the middle. */
815 o
= variable_buffer_output (o
, p
, end_p
- p
);
823 func_findstring (o
, argv
, funcname
)
826 const char *funcname
;
828 /* Find the first occurrence of the first string in the second. */
829 int i
= strlen (argv
[0]);
830 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
831 o
= variable_buffer_output (o
, argv
[0], i
);
837 func_foreach (o
, argv
, funcname
)
840 const char *funcname
;
842 /* expand only the first two. */
843 char *varname
= expand_argument (argv
[0], NULL
);
844 char *list
= expand_argument (argv
[1], NULL
);
845 char *body
= argv
[2];
848 char *list_iterator
= list
;
851 register struct variable
*var
;
853 push_new_variable_scope ();
854 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
856 /* loop through LIST, put the value in VAR and expand BODY */
857 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
866 var
->value
= (char *) xstrdup ((char*) p
);
870 result
= allocated_variable_expand (body
);
872 o
= variable_buffer_output (o
, result
, strlen (result
));
873 o
= variable_buffer_output (o
, " ", 1);
879 /* Kill the last space. */
882 pop_variable_scope ();
892 struct a_word
*chain
;
899 a_word_hash_1 (void const *key
)
901 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
905 a_word_hash_2 (void const *key
)
907 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
911 a_word_hash_cmp (void const *x
, void const *y
)
913 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
916 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
917 ((struct a_word
const *) y
)->str
);
922 struct a_pattern
*next
;
930 func_filter_filterout (o
, argv
, funcname
)
933 const char *funcname
;
935 struct a_word
*wordhead
;
936 struct a_word
**wordtail
;
938 struct a_pattern
*pathead
;
939 struct a_pattern
**pattail
;
940 struct a_pattern
*pp
;
942 struct hash_table a_word_table
;
943 int is_filter
= streq (funcname
, "filter");
944 char *pat_iterator
= argv
[0];
945 char *word_iterator
= argv
[1];
952 /* Chop ARGV[0] up into patterns to match against the words. */
955 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
957 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
960 pattail
= &pat
->next
;
962 if (*pat_iterator
!= '\0')
967 pat
->save_c
= p
[len
];
969 pat
->percent
= find_percent (p
);
970 if (pat
->percent
== 0)
975 /* Chop ARGV[1] up into words to match against the patterns. */
977 wordtail
= &wordhead
;
978 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
980 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
983 wordtail
= &word
->next
;
985 if (*word_iterator
!= '\0')
997 /* Only use a hash table if arg list lengths justifies the cost. */
998 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
1001 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
1002 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1004 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
1014 /* Run each pattern through the words, killing words. */
1015 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1018 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1019 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
1022 struct a_word a_word_key
;
1023 a_word_key
.str
= pp
->str
;
1024 a_word_key
.length
= pp
->length
;
1025 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
1033 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1034 wp
->matched
|= (wp
->length
== pp
->length
1035 && strneq (pp
->str
, wp
->str
, wp
->length
));
1038 /* Output the words that matched (or didn't, for filter-out). */
1039 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1040 if (is_filter
? wp
->matched
: !wp
->matched
)
1042 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
1043 o
= variable_buffer_output (o
, " ", 1);
1048 /* Kill the last space. */
1052 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1053 pp
->str
[pp
->length
] = pp
->save_c
;
1056 hash_free (&a_word_table
, 0);
1063 func_strip (o
, argv
, funcname
)
1066 const char *funcname
;
1076 while (isspace ((unsigned char)*p
))
1079 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1083 o
= variable_buffer_output (o
, word_start
, i
);
1084 o
= variable_buffer_output (o
, " ", 1);
1089 /* Kill the last space. */
1095 Print a warning or fatal message.
1098 func_error (o
, argv
, funcname
)
1101 const char *funcname
;
1107 /* The arguments will be broken on commas. Rather than create yet
1108 another special case where function arguments aren't broken up,
1109 just create a format string that puts them back together. */
1110 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1111 len
+= strlen (*argvp
) + 2;
1113 p
= msg
= (char *) alloca (len
+ 1);
1115 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1118 p
+= strlen (*argvp
);
1124 if (*funcname
== 'e')
1125 fatal (reading_file
, "%s", msg
);
1127 /* The warning function expands to the empty string. */
1128 error (reading_file
, "%s", msg
);
1135 chop argv[0] into words, and sort them.
1138 func_sort (o
, argv
, funcname
)
1141 const char *funcname
;
1145 register int wordi
= 0;
1147 /* Chop ARGV[0] into words and put them in WORDS. */
1153 while ((p
= find_next_token (&t
, &len
)) != 0)
1155 if (wordi
>= nwords
- 1)
1157 nwords
= (2 * nwords
) + 5;
1158 words
= (char **) xrealloc ((char *) words
,
1159 nwords
* sizeof (char *));
1161 words
[wordi
++] = savestring (p
, len
);
1167 /* Now sort the list of words. */
1168 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1170 /* Now write the sorted list. */
1171 for (i
= 0; i
< wordi
; ++i
)
1173 len
= strlen (words
[i
]);
1174 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1175 || strcmp (words
[i
], words
[i
+ 1]))
1177 o
= variable_buffer_output (o
, words
[i
], len
);
1178 o
= variable_buffer_output (o
, " ", 1);
1182 /* Kill the last space. */
1191 $(if condition,true-part[,false-part])
1193 CONDITION is false iff it evaluates to an empty string. White
1194 space before and after condition are stripped before evaluation.
1196 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1197 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1198 you can use $(if ...) to create side-effects (with $(shell ...), for
1203 func_if (o
, argv
, funcname
)
1206 const char *funcname
;
1208 char *begp
= argv
[0];
1209 char *endp
= begp
+ strlen (argv
[0]);
1212 /* Find the result of the condition: if we have a value, and it's not
1213 empty, the condition is true. If we don't have a value, or it's the
1214 empty string, then it's false. */
1216 strip_whitespace (&begp
, &endp
);
1220 char *expansion
= expand_argument (begp
, NULL
);
1222 result
= strlen (expansion
);
1226 /* If the result is true (1) we want to eval the first argument, and if
1227 it's false (0) we want to eval the second. If the argument doesn't
1228 exist we do nothing, otherwise expand it and add to the buffer. */
1230 argv
+= 1 + !result
;
1236 expansion
= expand_argument (argv
[0], NULL
);
1238 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1247 func_wildcard (o
, argv
, funcname
)
1250 const char *funcname
;
1254 o
= wildcard_expansion (argv
[0], o
);
1256 char *p
= string_glob (argv
[0]);
1257 o
= variable_buffer_output (o
, p
, strlen (p
));
1263 $(eval <makefile string>)
1265 Always resolves to the empty string.
1267 Treat the arguments as a segment of makefile, and parse them.
1271 func_eval (o
, argv
, funcname
)
1274 const char *funcname
;
1276 eval_buffer (argv
[0]);
1283 func_value (o
, argv
, funcname
)
1286 const char *funcname
;
1288 /* Look up the variable. */
1289 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1291 /* Copy its value into the output buffer without expanding it. */
1293 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1299 \r is replaced on UNIX as well. Is this desirable?
1302 fold_newlines (buffer
, length
)
1308 char *last_nonnl
= buffer
-1;
1310 for (; *src
!= '\0'; ++src
)
1312 if (src
[0] == '\r' && src
[1] == '\n')
1324 *(++last_nonnl
) = '\0';
1325 *length
= last_nonnl
- buffer
;
1330 int shell_function_pid
= 0, shell_function_completed
;
1336 #include <windows.h>
1338 #include "sub_proc.h"
1342 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1344 SECURITY_ATTRIBUTES saAttr
;
1352 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1353 saAttr
.bInheritHandle
= TRUE
;
1354 saAttr
.lpSecurityDescriptor
= NULL
;
1356 if (DuplicateHandle (GetCurrentProcess(),
1357 GetStdHandle(STD_INPUT_HANDLE
),
1358 GetCurrentProcess(),
1362 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1363 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1367 if (DuplicateHandle(GetCurrentProcess(),
1368 GetStdHandle(STD_ERROR_HANDLE
),
1369 GetCurrentProcess(),
1373 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1374 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1378 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1379 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1381 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1384 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1386 /* make sure that CreateProcess() has Path it needs */
1387 sync_Path_environment();
1389 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1390 /* register process for wait */
1391 process_register(hProcess
);
1393 /* set the pid for returning to caller */
1394 *pid_p
= (int) hProcess
;
1396 /* set up to read data from child */
1397 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1399 /* this will be closed almost right away */
1400 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1402 /* reap/cleanup the failed process */
1403 process_cleanup(hProcess
);
1405 /* close handles which were duplicated, they weren't used */
1409 /* close pipe handles, they won't be used */
1410 CloseHandle(hChildOutRd
);
1411 CloseHandle(hChildOutWr
);
1413 /* set status for return */
1414 pipedes
[0] = pipedes
[1] = -1;
1423 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1426 /* MSDOS can't fork, but it has `popen'. */
1427 struct variable
*sh
= lookup_variable ("SHELL", 5);
1429 extern int dos_command_running
, dos_status
;
1431 /* Make sure not to bother processing an empty line. */
1432 while (isblank ((unsigned char)*text
))
1439 char buf
[PATH_MAX
+ 7];
1440 /* This makes sure $SHELL value is used by $(shell), even
1441 though the target environment is not passed to it. */
1442 sprintf (buf
, "SHELL=%s", sh
->value
);
1448 dos_command_running
= 1;
1450 /* If dos_status becomes non-zero, it means the child process
1451 was interrupted by a signal, like SIGINT or SIGQUIT. See
1452 fatal_error_signal in commands.c. */
1453 fpipe
= popen (text
, "rt");
1454 dos_command_running
= 0;
1455 if (!fpipe
|| dos_status
)
1461 else if (errno
== 0)
1463 shell_function_completed
= -1;
1467 pipedes
[0] = fileno (fpipe
);
1468 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1470 shell_function_completed
= 1;
1477 Do shell spawning, with the naughty bits for different OSes.
1482 /* VMS can't do $(shell ...) */
1483 #define func_shell 0
1488 func_shell (o
, argv
, funcname
)
1491 const char *funcname
;
1493 char* batch_filename
= NULL
;
1499 char **command_argv
;
1506 /* Construct the argument list. */
1507 command_argv
= construct_command_argv (argv
[0],
1508 (char **) NULL
, (struct file
*) 0,
1510 if (command_argv
== 0)
1514 /* Using a target environment for `shell' loses in cases like:
1515 export var = $(shell echo foobie)
1516 because target_environment hits a loop trying to expand $(var)
1517 to put it in the environment. This is even more confusing when
1518 var was not explicitly exported, but just appeared in the
1519 calling environment. */
1523 /* For error messages. */
1524 if (reading_file
!= 0)
1526 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1527 sprintf (error_prefix
,
1528 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1534 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1536 if (pipedes
[0] < 0) {
1537 /* open of the pipe failed, mark as failed execution */
1538 shell_function_completed
= -1;
1542 #else /* WINDOWS32 */
1545 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1548 perror_with_name (error_prefix
, "pipe");
1552 if (pipe (pipedes
) < 0)
1554 perror_with_name (error_prefix
, "pipe");
1560 perror_with_name (error_prefix
, "fork");
1562 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1564 # endif /* ! __MSDOS__ */
1566 #endif /* WINDOWS32 */
1568 /* We are the parent. */
1571 unsigned int maxlen
;
1574 /* Record the PID for reap_children. */
1575 shell_function_pid
= pid
;
1577 shell_function_completed
= 0;
1579 /* Free the storage only the child needed. */
1580 free (command_argv
[0]);
1581 free ((char *) command_argv
);
1583 /* Close the write side of the pipe. */
1584 (void) close (pipedes
[1]);
1587 /* Set up and read from the pipe. */
1590 buffer
= (char *) xmalloc (maxlen
+ 1);
1592 /* Read from the pipe until it gets EOF. */
1593 for (i
= 0; ; i
+= cc
)
1598 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1601 cc
= read (pipedes
[0], &buffer
[i
], maxlen
- i
);
1607 /* Close the read side of the pipe. */
1610 (void) pclose (fpipe
);
1612 (void) close (pipedes
[0]);
1615 /* Loop until child_handler sets shell_function_completed
1616 to the status of our child shell. */
1617 while (shell_function_completed
== 0)
1618 reap_children (1, 0);
1620 if (batch_filename
) {
1621 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1623 remove (batch_filename
);
1624 free (batch_filename
);
1626 shell_function_pid
= 0;
1628 /* The child_handler function will set shell_function_completed
1629 to 1 when the child dies normally, or to -1 if it
1630 dies with status 127, which is most likely an exec fail. */
1632 if (shell_function_completed
== -1)
1634 /* This most likely means that the execvp failed,
1635 so we should just write out the error message
1636 that came in over the pipe from the child. */
1637 fputs (buffer
, stderr
);
1642 /* The child finished normally. Replace all
1643 newlines in its output with spaces, and put
1644 that in the variable output buffer. */
1645 fold_newlines (buffer
, &i
);
1646 o
= variable_buffer_output (o
, buffer
, i
);
1657 /* Do the Amiga version of func_shell. */
1660 func_shell (char *o
, char **argv
, const char *funcname
)
1662 /* Amiga can't fork nor spawn, but I can start a program with
1663 redirection of my choice. However, this means that we
1664 don't have an opportunity to reopen stdout to trap it. Thus,
1665 we save our own stdout onto a new descriptor and dup a temp
1666 file's descriptor onto our stdout temporarily. After we
1667 spawn the shell program, we dup our own stdout back to the
1668 stdout descriptor. The buffer reading is the same as above,
1669 except that we're now reading from a file. */
1671 #include <dos/dos.h>
1672 #include <proto/dos.h>
1675 char tmp_output
[FILENAME_MAX
];
1676 unsigned int maxlen
= 200;
1678 char * buffer
, * ptr
;
1681 char* batch_filename
= NULL
;
1683 /* Construct the argument list. */
1684 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1685 (struct file
*) 0, &batch_filename
);
1686 if (command_argv
== 0)
1689 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1690 Ideally we would use main.c:open_tmpfile(), but this uses a special
1691 Open(), not fopen(), and I'm not familiar enough with the code to mess
1693 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1694 mktemp (tmp_output
);
1695 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1697 for (aptr
=command_argv
; *aptr
; aptr
++)
1698 len
+= strlen (*aptr
) + 1;
1700 buffer
= xmalloc (len
+ 1);
1703 for (aptr
=command_argv
; *aptr
; aptr
++)
1705 strcpy (ptr
, *aptr
);
1706 ptr
+= strlen (ptr
) + 1;
1713 Execute (buffer
, NULL
, child_stdout
);
1716 Close (child_stdout
);
1718 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1720 buffer
= xmalloc (maxlen
);
1727 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1730 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1735 Close (child_stdout
);
1737 fold_newlines (buffer
, &i
);
1738 o
= variable_buffer_output (o
, buffer
, i
);
1748 equality. Return is string-boolean, ie, the empty string is false.
1751 func_eq (char* o
, char **argv
, char *funcname
)
1753 int result
= ! strcmp (argv
[0], argv
[1]);
1754 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1760 string-boolean not operator.
1763 func_not (char* o
, char **argv
, char *funcname
)
1767 while (isspace ((unsigned char)*s
))
1770 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1776 /* Lookup table for builtin functions.
1778 This doesn't have to be sorted; we use a straight lookup. We might gain
1779 some efficiency by moving most often used functions to the start of the
1782 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1783 comma-separated values are treated as arguments.
1785 EXPAND_ARGS means that all arguments should be expanded before invocation.
1786 Functions that do namespace tricks (foreach) don't automatically expand. */
1788 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1791 static struct function_table_entry function_table_init
[] =
1793 /* Name/size */ /* MIN MAX EXP? Function */
1794 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1795 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1796 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1797 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1798 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1799 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1800 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1801 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1802 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1803 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1804 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1805 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1806 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1807 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1808 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1809 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1810 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1811 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1812 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1813 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1814 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1815 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1816 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1817 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1818 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1819 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1820 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1821 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1823 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1824 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1828 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1831 /* These must come after the definition of function_table. */
1834 expand_builtin_function (o
, argc
, argv
, entry_p
)
1838 struct function_table_entry
*entry_p
;
1840 if (argc
< entry_p
->minimum_args
)
1841 fatal (reading_file
,
1842 _("Insufficient number of arguments (%d) to function `%s'"),
1843 argc
, entry_p
->name
);
1845 /* I suppose technically some function could do something with no
1846 arguments, but so far none do, so just test it for all functions here
1847 rather than in each one. We can change it later if necessary. */
1852 if (!entry_p
->func_ptr
)
1853 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1856 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1859 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1860 opening ( or { and is not null-terminated. If a function invocation
1861 is found, expand it into the buffer at *OP, updating *OP, incrementing
1862 *STRINGP past the reference and returning nonzero. If not, return zero. */
1865 handle_function (op
, stringp
)
1869 const struct function_table_entry
*entry_p
;
1870 char openparen
= (*stringp
)[0];
1871 char closeparen
= openparen
== '(' ? ')' : '}';
1876 char **argv
, **argvp
;
1881 entry_p
= lookup_function (beg
);
1886 /* We found a builtin function. Find the beginning of its arguments (skip
1887 whitespace after the name). */
1889 beg
= next_token (beg
+ entry_p
->len
);
1891 /* Find the end of the function invocation, counting nested use of
1892 whichever kind of parens we use. Since we're looking, count commas
1893 to get a rough estimate of how many arguments we might have. The
1894 count might be high, but it'll never be low. */
1896 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1899 else if (*end
== openparen
)
1901 else if (*end
== closeparen
&& --count
< 0)
1905 fatal (reading_file
,
1906 _("unterminated call to function `%s': missing `%c'"),
1907 entry_p
->name
, closeparen
);
1911 /* Get some memory to store the arg pointers. */
1912 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1914 /* Chop the string into arguments, then a nul. As soon as we hit
1915 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1918 If we're expanding, store pointers to the expansion of each one. If
1919 not, make a duplicate of the string and point into that, nul-terminating
1922 if (!entry_p
->expand_args
)
1924 int len
= end
- beg
;
1926 p
= xmalloc (len
+1);
1927 memcpy (p
, beg
, len
);
1933 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1939 if (nargs
== entry_p
->maximum_args
1940 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1943 if (entry_p
->expand_args
)
1944 *argvp
= expand_argument (p
, next
);
1955 /* Finally! Run the function... */
1956 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1959 if (entry_p
->expand_args
)
1960 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1969 /* User-defined functions. Expand the first argument as either a builtin
1970 function or a make variable, in the context of the rest of the arguments
1971 assigned to $1, $2, ... $N. $0 is the name of the function. */
1974 func_call (o
, argv
, funcname
)
1977 const char *funcname
;
1984 const struct function_table_entry
*entry_p
;
1987 /* There is no way to define a variable with a space in the name, so strip
1988 leading and trailing whitespace as a favor to the user. */
1990 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
1993 cp
= fname
+ strlen (fname
) - 1;
1994 while (cp
> fname
&& isspace ((unsigned char)*cp
))
1998 /* Calling nothing is a no-op */
2002 /* Are we invoking a builtin function? */
2004 entry_p
= lookup_function (fname
);
2008 /* How many arguments do we have? */
2009 for (i
=0; argv
[i
+1]; ++i
)
2012 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
2015 /* Not a builtin, so the first argument is the name of a variable to be
2016 expanded and interpreted as a function. Find it. */
2017 flen
= strlen (fname
);
2019 v
= lookup_variable (fname
, flen
);
2022 warn_undefined (fname
, flen
);
2024 if (v
== 0 || *v
->value
== '\0')
2027 body
= (char *) alloca (flen
+ 4);
2030 memcpy (body
+ 2, fname
, flen
);
2032 body
[flen
+3] = '\0';
2034 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2036 push_new_variable_scope ();
2038 for (i
=0; *argv
; ++i
, ++argv
)
2042 sprintf (num
, "%d", i
);
2043 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
2046 /* Expand the body in the context of the arguments, adding the result to
2047 the variable buffer. */
2049 v
->exp_count
= EXP_COUNT_MAX
;
2051 o
= variable_expand_string (o
, body
, flen
+3);
2055 pop_variable_scope ();
2057 return o
+ strlen (o
);
2061 hash_init_function_table ()
2063 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
2064 function_table_entry_hash_1
, function_table_entry_hash_2
,
2065 function_table_entry_hash_cmp
);
2066 hash_load (&function_table
, function_table_init
,
2067 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));