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. */
78 subst_expand (char *o
, char *text
, char *subst
, char *replace
,
79 unsigned int slen
, unsigned int rlen
, int by_word
)
84 if (slen
== 0 && !by_word
)
86 /* The first occurrence of "" in any string is its end. */
87 o
= variable_buffer_output (o
, t
, strlen (t
));
89 o
= variable_buffer_output (o
, replace
, rlen
);
95 if (by_word
&& slen
== 0)
96 /* When matching by words, the empty string should match
97 the end of each word, rather than the end of the whole text. */
98 p
= end_of_token (next_token (t
));
101 p
= strstr (t
, subst
);
104 /* No more matches. Output everything left on the end. */
105 o
= variable_buffer_output (o
, t
, strlen (t
));
110 /* Output everything before this occurrence of the string to replace. */
112 o
= variable_buffer_output (o
, t
, p
- t
);
114 /* If we're substituting only by fully matched words,
115 or only at the ends of words, check that this case qualifies. */
117 && ((p
> text
&& !isblank ((unsigned char)p
[-1]))
118 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
119 /* Struck out. Output the rest of the string that is
120 no longer to be replaced. */
121 o
= variable_buffer_output (o
, subst
, slen
);
123 /* Output the replacement string. */
124 o
= variable_buffer_output (o
, replace
, rlen
);
126 /* Advance T past the string to be replaced. */
131 } while (*t
!= '\0');
137 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
138 and replacing strings matching PATTERN with REPLACE.
139 If PATTERN_PERCENT is not nil, PATTERN has already been
140 run through find_percent, and PATTERN_PERCENT is the result.
141 If REPLACE_PERCENT is not nil, REPLACE has already been
142 run through find_percent, and REPLACE_PERCENT is the result.
143 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
144 character _AFTER_ the %, not to the % itself.
148 patsubst_expand (char *o
, char *text
, char *pattern
, char *replace
,
149 char *pattern_percent
, char *replace_percent
)
151 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
152 unsigned int replace_prepercent_len
, replace_postpercent_len
;
157 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
158 will be collapsed before we call subst_expand if PATTERN has no %. */
159 if (!replace_percent
)
161 replace_percent
= find_percent (replace
);
166 /* Record the length of REPLACE before and after the % so we don't have to
167 compute these lengths more than once. */
170 replace_prepercent_len
= replace_percent
- replace
- 1;
171 replace_postpercent_len
= strlen (replace_percent
);
175 replace_prepercent_len
= strlen (replace
);
176 replace_postpercent_len
= 0;
179 if (!pattern_percent
)
181 pattern_percent
= find_percent (pattern
);
185 if (!pattern_percent
)
186 /* With no % in the pattern, this is just a simple substitution. */
187 return subst_expand (o
, text
, pattern
, replace
,
188 strlen (pattern
), strlen (replace
), 1);
190 /* Record the length of PATTERN before and after the %
191 so we don't have to compute it more than once. */
192 pattern_prepercent_len
= pattern_percent
- pattern
- 1;
193 pattern_postpercent_len
= strlen (pattern_percent
);
195 while ((t
= find_next_token (&text
, &len
)) != 0)
199 /* Is it big enough to match? */
200 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
203 /* Does the prefix match? */
204 if (!fail
&& pattern_prepercent_len
> 0
206 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-2]
207 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
210 /* Does the suffix match? */
211 if (!fail
&& pattern_postpercent_len
> 0
212 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
- 1]
213 || t
[len
- pattern_postpercent_len
] != *pattern_percent
214 || !strneq (&t
[len
- pattern_postpercent_len
],
215 pattern_percent
, pattern_postpercent_len
- 1)))
219 /* It didn't match. Output the string. */
220 o
= variable_buffer_output (o
, t
, len
);
223 /* It matched. Output the replacement. */
225 /* Output the part of the replacement before the %. */
226 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
228 if (replace_percent
!= 0)
230 /* Output the part of the matched string that
231 matched the % in the pattern. */
232 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
233 len
- (pattern_prepercent_len
234 + pattern_postpercent_len
));
235 /* Output the part of the replacement after the %. */
236 o
= variable_buffer_output (o
, replace_percent
,
237 replace_postpercent_len
);
241 /* Output a space, but not if the replacement is "". */
242 if (fail
|| replace_prepercent_len
> 0
243 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
245 o
= variable_buffer_output (o
, " ", 1);
250 /* Kill the last space. */
257 /* Look up a function by name. */
259 static const struct function_table_entry
*
260 lookup_function (const char *s
)
264 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
266 if (*e
== '\0' || isblank ((unsigned char) *e
))
268 struct function_table_entry function_table_entry_key
;
269 function_table_entry_key
.name
= s
;
270 function_table_entry_key
.len
= e
- s
;
272 return hash_find_item (&function_table
, &function_table_entry_key
);
278 /* Return 1 if PATTERN matches STR, 0 if not. */
281 pattern_matches (char *pattern
, char *percent
, char *str
)
283 unsigned int sfxlen
, strlength
;
287 unsigned int len
= strlen (pattern
) + 1;
288 char *new_chars
= (char *) alloca (len
);
289 bcopy (pattern
, new_chars
, len
);
291 percent
= find_percent (pattern
);
293 return streq (pattern
, str
);
296 sfxlen
= strlen (percent
+ 1);
297 strlength
= strlen (str
);
299 if (strlength
< (percent
- pattern
) + sfxlen
300 || !strneq (pattern
, str
, percent
- pattern
))
303 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
307 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
308 ENDPARENtheses), starting at PTR before END. Return a pointer to
311 If no next argument is found, return NULL.
315 find_next_argument (char startparen
, char endparen
,
316 const char *ptr
, const char *end
)
320 for (; ptr
< end
; ++ptr
)
321 if (*ptr
== startparen
)
324 else if (*ptr
== endparen
)
331 else if (*ptr
== ',' && !count
)
334 /* We didn't find anything. */
339 /* Glob-expand LINE. The returned pointer is
340 only good until the next call to string_glob. */
343 string_glob (char *line
)
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 (char *o
, char **argv
, const char *funcname UNUSED
)
407 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
413 func_join (char *o
, char **argv
, const char *funcname UNUSED
)
417 /* Write each word of the first argument directly followed
418 by the corresponding word of the second argument.
419 If the two arguments have a different number of words,
420 the excess words are just output separated by blanks. */
423 char *list1_iterator
= argv
[0];
424 char *list2_iterator
= argv
[1];
427 unsigned int len1
, len2
;
429 tp
= find_next_token (&list1_iterator
, &len1
);
431 o
= variable_buffer_output (o
, tp
, len1
);
433 pp
= find_next_token (&list2_iterator
, &len2
);
435 o
= variable_buffer_output (o
, pp
, len2
);
437 if (tp
!= 0 || pp
!= 0)
439 o
= variable_buffer_output (o
, " ", 1);
443 while (tp
!= 0 || pp
!= 0);
445 /* Kill the last blank. */
453 func_origin (char *o
, char **argv
, const char *funcname UNUSED
)
455 /* Expand the argument. */
456 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
458 o
= variable_buffer_output (o
, "undefined", 9);
467 o
= variable_buffer_output (o
, "default", 7);
470 o
= variable_buffer_output (o
, "environment", 11);
473 o
= variable_buffer_output (o
, "file", 4);
476 o
= variable_buffer_output (o
, "environment override", 20);
479 o
= variable_buffer_output (o
, "command line", 12);
482 o
= variable_buffer_output (o
, "override", 8);
485 o
= variable_buffer_output (o
, "automatic", 9);
493 # define IS_PATHSEP(c) ((c) == ']')
495 # ifdef HAVE_DOS_PATHS
496 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
498 # define IS_PATHSEP(c) ((c) == '/')
504 func_notdir_suffix (char *o
, char **argv
, const char *funcname
)
506 /* Expand the argument. */
507 char *list_iterator
= argv
[0];
512 int is_suffix
= streq (funcname
, "suffix");
513 int is_notdir
= !is_suffix
;
514 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
519 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
532 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
534 #ifdef HAVE_DOS_PATHS
535 /* Handle the case of "d:foo/bar". */
536 else if (streq (funcname
, "notdir") && p2
[0] && p2
[1] == ':')
539 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
543 o
= variable_buffer_output (o
, p2
, len
);
545 if (is_notdir
|| p
>= p2
)
547 o
= variable_buffer_output (o
, " ", 1);
552 /* Kill last space. */
562 func_basename_dir (char *o
, char **argv
, const char *funcname
)
564 /* Expand the argument. */
570 int is_basename
= streq (funcname
, "basename");
571 int is_dir
= !is_basename
;
573 while ((p2
= find_next_token (&p3
, &len
)) != 0)
576 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
583 if (p
>= p2
&& (is_dir
))
584 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
585 else if (p
>= p2
&& (*p
== '.'))
586 o
= variable_buffer_output (o
, p2
, p
- p2
);
587 #ifdef HAVE_DOS_PATHS
588 /* Handle the "d:foobar" case */
589 else if (p2
[0] && p2
[1] == ':' && is_dir
)
590 o
= variable_buffer_output (o
, p2
, 2);
594 o
= variable_buffer_output (o
, "[]", 2);
597 o
= variable_buffer_output (o
, "./", 2);
599 ; /* Just a nop... */
603 /* The entire name is the basename. */
604 o
= variable_buffer_output (o
, p2
, len
);
606 o
= variable_buffer_output (o
, " ", 1);
610 /* Kill last space. */
618 func_addsuffix_addprefix (char *o
, char **argv
, const char *funcname
)
620 int fixlen
= strlen (argv
[0]);
621 char *list_iterator
= argv
[1];
622 int is_addprefix
= streq (funcname
, "addprefix");
623 int is_addsuffix
= !is_addprefix
;
629 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
632 o
= variable_buffer_output (o
, argv
[0], fixlen
);
633 o
= variable_buffer_output (o
, p
, len
);
635 o
= variable_buffer_output (o
, argv
[0], fixlen
);
636 o
= variable_buffer_output (o
, " ", 1);
641 /* Kill last space. */
648 func_subst (char *o
, char **argv
, const char *funcname UNUSED
)
650 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
651 strlen (argv
[1]), 0);
658 func_firstword (char *o
, char **argv
, const char *funcname UNUSED
)
661 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
662 char *p
= find_next_token (&words
, &i
);
665 o
= variable_buffer_output (o
, p
, i
);
671 func_lastword (char *o
, char **argv
, const char *funcname UNUSED
)
674 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
678 while ((t
= find_next_token (&words
, &i
)))
682 o
= variable_buffer_output (o
, p
, i
);
688 func_words (char *o
, char **argv
, const char *funcname UNUSED
)
691 char *word_iterator
= argv
[0];
694 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
697 sprintf (buf
, "%d", i
);
698 o
= variable_buffer_output (o
, buf
, strlen (buf
));
704 /* Set begpp to point to the first non-whitespace character of the string,
705 * and endpp to point to the last non-whitespace character of the string.
706 * If the string is empty or contains nothing but whitespace, endpp will be
710 strip_whitespace (const char **begpp
, const char **endpp
)
712 while (*begpp
<= *endpp
&& isspace ((unsigned char)**begpp
))
714 while (*endpp
>= *begpp
&& isspace ((unsigned char)**endpp
))
716 return (char *)*begpp
;
720 check_numeric (const char *s
, const char *message
)
722 const char *end
= s
+ strlen (s
) - 1;
724 strip_whitespace (&s
, &end
);
726 for (; s
<= end
; ++s
)
727 if (!ISDIGIT (*s
)) /* ISDIGIT only evals its arg once: see make.h. */
730 if (s
<= end
|| end
- beg
< 0)
731 fatal (reading_file
, "%s: '%s'", message
, beg
);
737 func_word (char *o
, char **argv
, const char *funcname UNUSED
)
743 /* Check the first argument. */
744 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
748 fatal (reading_file
, _("first argument to `word' function must be greater than 0"));
752 while ((p
= find_next_token (&end_p
, 0)) != 0)
757 o
= variable_buffer_output (o
, p
, end_p
- p
);
763 func_wordlist (char *o
, char **argv
, const char *funcname UNUSED
)
767 /* Check the arguments. */
768 check_numeric (argv
[0],
769 _("non-numeric first argument to `wordlist' function"));
770 check_numeric (argv
[1],
771 _("non-numeric second argument to `wordlist' function"));
773 start
= atoi (argv
[0]);
774 count
= atoi (argv
[1]) - start
+ 1;
779 char *end_p
= argv
[2];
781 /* Find the beginning of the "start"th word. */
782 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
787 /* Find the end of the "count"th word from start. */
788 while (--count
&& (find_next_token (&end_p
, 0) != 0))
791 /* Return the stuff in the middle. */
792 o
= variable_buffer_output (o
, p
, end_p
- p
);
800 func_findstring (char *o
, char **argv
, const char *funcname UNUSED
)
802 /* Find the first occurrence of the first string in the second. */
803 if (strstr (argv
[1], argv
[0]) != 0)
804 o
= variable_buffer_output (o
, argv
[0], strlen (argv
[0]));
810 func_foreach (char *o
, char **argv
, const char *funcname UNUSED
)
812 /* expand only the first two. */
813 char *varname
= expand_argument (argv
[0], NULL
);
814 char *list
= expand_argument (argv
[1], NULL
);
815 char *body
= argv
[2];
818 char *list_iterator
= list
;
821 register struct variable
*var
;
823 push_new_variable_scope ();
824 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
826 /* loop through LIST, put the value in VAR and expand BODY */
827 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
836 var
->value
= (char *) xstrdup ((char*) p
);
840 result
= allocated_variable_expand (body
);
842 o
= variable_buffer_output (o
, result
, strlen (result
));
843 o
= variable_buffer_output (o
, " ", 1);
849 /* Kill the last space. */
852 pop_variable_scope ();
862 struct a_word
*chain
;
869 a_word_hash_1 (const void *key
)
871 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
875 a_word_hash_2 (const void *key
)
877 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
881 a_word_hash_cmp (const void *x
, const void *y
)
883 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
886 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
887 ((struct a_word
const *) y
)->str
);
892 struct a_pattern
*next
;
900 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
902 struct a_word
*wordhead
;
903 struct a_word
**wordtail
;
905 struct a_pattern
*pathead
;
906 struct a_pattern
**pattail
;
907 struct a_pattern
*pp
;
909 struct hash_table a_word_table
;
910 int is_filter
= streq (funcname
, "filter");
911 char *pat_iterator
= argv
[0];
912 char *word_iterator
= argv
[1];
919 /* Chop ARGV[0] up into patterns to match against the words. */
922 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
924 struct a_pattern
*pat
= (struct a_pattern
*) alloca (sizeof (struct a_pattern
));
927 pattail
= &pat
->next
;
929 if (*pat_iterator
!= '\0')
934 pat
->save_c
= p
[len
];
936 pat
->percent
= find_percent (p
);
937 if (pat
->percent
== 0)
942 /* Chop ARGV[1] up into words to match against the patterns. */
944 wordtail
= &wordhead
;
945 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
947 struct a_word
*word
= (struct a_word
*) alloca (sizeof (struct a_word
));
950 wordtail
= &word
->next
;
952 if (*word_iterator
!= '\0')
964 /* Only use a hash table if arg list lengths justifies the cost. */
965 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
968 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
, a_word_hash_cmp
);
969 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
971 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
981 /* Run each pattern through the words, killing words. */
982 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
985 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
986 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
989 struct a_word a_word_key
;
990 a_word_key
.str
= pp
->str
;
991 a_word_key
.length
= pp
->length
;
992 wp
= (struct a_word
*) hash_find_item (&a_word_table
, &a_word_key
);
1000 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1001 wp
->matched
|= (wp
->length
== pp
->length
1002 && strneq (pp
->str
, wp
->str
, wp
->length
));
1005 /* Output the words that matched (or didn't, for filter-out). */
1006 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1007 if (is_filter
? wp
->matched
: !wp
->matched
)
1009 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
1010 o
= variable_buffer_output (o
, " ", 1);
1015 /* Kill the last space. */
1019 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1020 pp
->str
[pp
->length
] = pp
->save_c
;
1023 hash_free (&a_word_table
, 0);
1030 func_strip (char *o
, char **argv
, const char *funcname UNUSED
)
1040 while (isspace ((unsigned char)*p
))
1043 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1047 o
= variable_buffer_output (o
, word_start
, i
);
1048 o
= variable_buffer_output (o
, " ", 1);
1053 /* Kill the last space. */
1059 Print a warning or fatal message.
1062 func_error (char *o
, char **argv
, const char *funcname
)
1068 /* The arguments will be broken on commas. Rather than create yet
1069 another special case where function arguments aren't broken up,
1070 just create a format string that puts them back together. */
1071 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1072 len
+= strlen (*argvp
) + 2;
1074 p
= msg
= (char *) alloca (len
+ 1);
1076 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1079 p
+= strlen (*argvp
);
1085 if (*funcname
== 'e')
1086 fatal (reading_file
, "%s", msg
);
1088 /* The warning function expands to the empty string. */
1089 error (reading_file
, "%s", msg
);
1096 chop argv[0] into words, and sort them.
1099 func_sort (char *o
, char **argv
, const char *funcname UNUSED
)
1103 register int wordi
= 0;
1105 /* Chop ARGV[0] into words and put them in WORDS. */
1111 while ((p
= find_next_token (&t
, &len
)) != 0)
1113 if (wordi
>= nwords
- 1)
1115 nwords
= (2 * nwords
) + 5;
1116 words
= (char **) xrealloc ((char *) words
,
1117 nwords
* sizeof (char *));
1119 words
[wordi
++] = savestring (p
, len
);
1125 /* Now sort the list of words. */
1126 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1128 /* Now write the sorted list. */
1129 for (i
= 0; i
< wordi
; ++i
)
1131 len
= strlen (words
[i
]);
1132 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1133 || strcmp (words
[i
], words
[i
+ 1]))
1135 o
= variable_buffer_output (o
, words
[i
], len
);
1136 o
= variable_buffer_output (o
, " ", 1);
1140 /* Kill the last space. */
1149 $(if condition,true-part[,false-part])
1151 CONDITION is false iff it evaluates to an empty string. White
1152 space before and after condition are stripped before evaluation.
1154 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1155 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1156 you can use $(if ...) to create side-effects (with $(shell ...), for
1161 func_if (char *o
, char **argv
, const char *funcname UNUSED
)
1163 const char *begp
= argv
[0];
1164 const char *endp
= begp
+ strlen (argv
[0]) - 1;
1167 /* Find the result of the condition: if we have a value, and it's not
1168 empty, the condition is true. If we don't have a value, or it's the
1169 empty string, then it's false. */
1171 strip_whitespace (&begp
, &endp
);
1175 char *expansion
= expand_argument (begp
, endp
+1);
1177 result
= strlen (expansion
);
1181 /* If the result is true (1) we want to eval the first argument, and if
1182 it's false (0) we want to eval the second. If the argument doesn't
1183 exist we do nothing, otherwise expand it and add to the buffer. */
1185 argv
+= 1 + !result
;
1191 expansion
= expand_argument (argv
[0], NULL
);
1193 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1202 func_wildcard (char *o
, char **argv
, const char *funcname UNUSED
)
1206 o
= wildcard_expansion (argv
[0], o
);
1208 char *p
= string_glob (argv
[0]);
1209 o
= variable_buffer_output (o
, p
, strlen (p
));
1215 $(eval <makefile string>)
1217 Always resolves to the empty string.
1219 Treat the arguments as a segment of makefile, and parse them.
1223 func_eval (char *o
, char **argv
, const char *funcname UNUSED
)
1228 /* Eval the buffer. Pop the current variable buffer setting so that the
1229 eval'd code can use its own without conflicting. */
1231 install_variable_buffer (&buf
, &len
);
1233 eval_buffer (argv
[0]);
1235 restore_variable_buffer (buf
, len
);
1242 func_value (char *o
, char **argv
, const char *funcname UNUSED
)
1244 /* Look up the variable. */
1245 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1247 /* Copy its value into the output buffer without expanding it. */
1249 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1255 \r is replaced on UNIX as well. Is this desirable?
1258 fold_newlines (char *buffer
, int *length
)
1262 char *last_nonnl
= buffer
-1;
1264 for (; *src
!= '\0'; ++src
)
1266 if (src
[0] == '\r' && src
[1] == '\n')
1278 *(++last_nonnl
) = '\0';
1279 *length
= last_nonnl
- buffer
;
1284 int shell_function_pid
= 0, shell_function_completed
;
1290 #include <windows.h>
1292 #include "sub_proc.h"
1296 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1298 SECURITY_ATTRIBUTES saAttr
;
1306 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
1307 saAttr
.bInheritHandle
= TRUE
;
1308 saAttr
.lpSecurityDescriptor
= NULL
;
1310 if (DuplicateHandle (GetCurrentProcess(),
1311 GetStdHandle(STD_INPUT_HANDLE
),
1312 GetCurrentProcess(),
1316 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1317 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1321 if (DuplicateHandle(GetCurrentProcess(),
1322 GetStdHandle(STD_ERROR_HANDLE
),
1323 GetCurrentProcess(),
1327 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1328 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1332 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1333 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1335 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1338 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1340 /* make sure that CreateProcess() has Path it needs */
1341 sync_Path_environment();
1343 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
1344 /* register process for wait */
1345 process_register(hProcess
);
1347 /* set the pid for returning to caller */
1348 *pid_p
= (int) hProcess
;
1350 /* set up to read data from child */
1351 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1353 /* this will be closed almost right away */
1354 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1356 /* reap/cleanup the failed process */
1357 process_cleanup(hProcess
);
1359 /* close handles which were duplicated, they weren't used */
1363 /* close pipe handles, they won't be used */
1364 CloseHandle(hChildOutRd
);
1365 CloseHandle(hChildOutWr
);
1367 /* set status for return */
1368 pipedes
[0] = pipedes
[1] = -1;
1377 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1380 /* MSDOS can't fork, but it has `popen'. */
1381 struct variable
*sh
= lookup_variable ("SHELL", 5);
1383 extern int dos_command_running
, dos_status
;
1385 /* Make sure not to bother processing an empty line. */
1386 while (isblank ((unsigned char)*text
))
1393 char buf
[PATH_MAX
+ 7];
1394 /* This makes sure $SHELL value is used by $(shell), even
1395 though the target environment is not passed to it. */
1396 sprintf (buf
, "SHELL=%s", sh
->value
);
1402 dos_command_running
= 1;
1404 /* If dos_status becomes non-zero, it means the child process
1405 was interrupted by a signal, like SIGINT or SIGQUIT. See
1406 fatal_error_signal in commands.c. */
1407 fpipe
= popen (text
, "rt");
1408 dos_command_running
= 0;
1409 if (!fpipe
|| dos_status
)
1415 else if (errno
== 0)
1417 shell_function_completed
= -1;
1421 pipedes
[0] = fileno (fpipe
);
1422 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1424 shell_function_completed
= 1;
1431 Do shell spawning, with the naughty bits for different OSes.
1436 /* VMS can't do $(shell ...) */
1437 #define func_shell 0
1442 func_shell (char *o
, char **argv
, const char *funcname UNUSED
)
1444 char* batch_filename
= NULL
;
1450 char **command_argv
;
1457 /* Construct the argument list. */
1458 command_argv
= construct_command_argv (argv
[0],
1459 (char **) NULL
, (struct file
*) 0,
1461 if (command_argv
== 0)
1465 /* Using a target environment for `shell' loses in cases like:
1466 export var = $(shell echo foobie)
1467 because target_environment hits a loop trying to expand $(var)
1468 to put it in the environment. This is even more confusing when
1469 var was not explicitly exported, but just appeared in the
1470 calling environment. */
1474 /* For error messages. */
1475 if (reading_file
!= 0)
1477 error_prefix
= (char *) alloca (strlen (reading_file
->filenm
)+11+4);
1478 sprintf (error_prefix
,
1479 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1486 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1488 if (pipedes
[0] < 0) {
1489 /* open of the pipe failed, mark as failed execution */
1490 shell_function_completed
= -1;
1495 #elif defined(__MSDOS__)
1497 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1500 perror_with_name (error_prefix
, "pipe");
1506 if (pipe (pipedes
) < 0)
1508 perror_with_name (error_prefix
, "pipe");
1514 /* close some handles that are unnecessary for the child process */
1515 CLOSE_ON_EXEC(pipedes
[1]);
1516 CLOSE_ON_EXEC(pipedes
[0]);
1517 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1518 pid
= child_execute_job (0, pipedes
[1], command_argv
, envp
);
1520 perror_with_name (error_prefix
, "spawn");
1522 # else /* ! __EMX__ */
1526 perror_with_name (error_prefix
, "fork");
1528 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1535 /* We are the parent. */
1538 unsigned int maxlen
;
1541 /* Record the PID for reap_children. */
1542 shell_function_pid
= pid
;
1544 shell_function_completed
= 0;
1546 /* Free the storage only the child needed. */
1547 free (command_argv
[0]);
1548 free ((char *) command_argv
);
1550 /* Close the write side of the pipe. */
1551 (void) close (pipedes
[1]);
1554 /* Set up and read from the pipe. */
1557 buffer
= (char *) xmalloc (maxlen
+ 1);
1559 /* Read from the pipe until it gets EOF. */
1560 for (i
= 0; ; i
+= cc
)
1565 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1568 EINTRLOOP (cc
, read (pipedes
[0], &buffer
[i
], maxlen
- i
));
1574 /* Close the read side of the pipe. */
1577 (void) pclose (fpipe
);
1579 (void) close (pipedes
[0]);
1582 /* Loop until child_handler or reap_children() sets
1583 shell_function_completed to the status of our child shell. */
1584 while (shell_function_completed
== 0)
1585 reap_children (1, 0);
1587 if (batch_filename
) {
1588 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
1590 remove (batch_filename
);
1591 free (batch_filename
);
1593 shell_function_pid
= 0;
1595 /* The child_handler function will set shell_function_completed
1596 to 1 when the child dies normally, or to -1 if it
1597 dies with status 127, which is most likely an exec fail. */
1599 if (shell_function_completed
== -1)
1601 /* This most likely means that the execvp failed,
1602 so we should just write out the error message
1603 that came in over the pipe from the child. */
1604 fputs (buffer
, stderr
);
1609 /* The child finished normally. Replace all
1610 newlines in its output with spaces, and put
1611 that in the variable output buffer. */
1612 fold_newlines (buffer
, &i
);
1613 o
= variable_buffer_output (o
, buffer
, i
);
1624 /* Do the Amiga version of func_shell. */
1627 func_shell (char *o
, char **argv
, const char *funcname
)
1629 /* Amiga can't fork nor spawn, but I can start a program with
1630 redirection of my choice. However, this means that we
1631 don't have an opportunity to reopen stdout to trap it. Thus,
1632 we save our own stdout onto a new descriptor and dup a temp
1633 file's descriptor onto our stdout temporarily. After we
1634 spawn the shell program, we dup our own stdout back to the
1635 stdout descriptor. The buffer reading is the same as above,
1636 except that we're now reading from a file. */
1638 #include <dos/dos.h>
1639 #include <proto/dos.h>
1642 char tmp_output
[FILENAME_MAX
];
1643 unsigned int maxlen
= 200;
1645 char * buffer
, * ptr
;
1648 char* batch_filename
= NULL
;
1650 /* Construct the argument list. */
1651 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1652 (struct file
*) 0, &batch_filename
);
1653 if (command_argv
== 0)
1656 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1657 Ideally we would use main.c:open_tmpfile(), but this uses a special
1658 Open(), not fopen(), and I'm not familiar enough with the code to mess
1660 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1661 mktemp (tmp_output
);
1662 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1664 for (aptr
=command_argv
; *aptr
; aptr
++)
1665 len
+= strlen (*aptr
) + 1;
1667 buffer
= xmalloc (len
+ 1);
1670 for (aptr
=command_argv
; *aptr
; aptr
++)
1672 strcpy (ptr
, *aptr
);
1673 ptr
+= strlen (ptr
) + 1;
1680 Execute (buffer
, NULL
, child_stdout
);
1683 Close (child_stdout
);
1685 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1687 buffer
= xmalloc (maxlen
);
1694 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1697 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1702 Close (child_stdout
);
1704 fold_newlines (buffer
, &i
);
1705 o
= variable_buffer_output (o
, buffer
, i
);
1715 equality. Return is string-boolean, ie, the empty string is false.
1718 func_eq (char* o
, char **argv
, char *funcname
)
1720 int result
= ! strcmp (argv
[0], argv
[1]);
1721 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1727 string-boolean not operator.
1730 func_not (char* o
, char **argv
, char *funcname
)
1734 while (isspace ((unsigned char)*s
))
1737 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1743 /* Lookup table for builtin functions.
1745 This doesn't have to be sorted; we use a straight lookup. We might gain
1746 some efficiency by moving most often used functions to the start of the
1749 If MAXIMUM_ARGS is 0, that means there is no maximum and all
1750 comma-separated values are treated as arguments.
1752 EXPAND_ARGS means that all arguments should be expanded before invocation.
1753 Functions that do namespace tricks (foreach) don't automatically expand. */
1755 static char *func_call
PARAMS ((char *o
, char **argv
, const char *funcname
));
1758 static struct function_table_entry function_table_init
[] =
1760 /* Name/size */ /* MIN MAX EXP? Function */
1761 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
1762 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
1763 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
1764 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
1765 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
1766 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
1767 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
1768 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
1769 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
1770 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
1771 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
1772 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
1773 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword
},
1774 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
1775 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
1776 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
1777 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
1778 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
1779 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
1780 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
1781 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
1782 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
1783 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
1784 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
1785 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
1786 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
1787 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
1788 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
1789 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
1791 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
1792 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
1796 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
1799 /* These must come after the definition of function_table. */
1802 expand_builtin_function (char *o
, int argc
, char **argv
,
1803 const struct function_table_entry
*entry_p
)
1805 if (argc
< (int)entry_p
->minimum_args
)
1806 fatal (reading_file
,
1807 _("Insufficient number of arguments (%d) to function `%s'"),
1808 argc
, entry_p
->name
);
1810 /* I suppose technically some function could do something with no
1811 arguments, but so far none do, so just test it for all functions here
1812 rather than in each one. We can change it later if necessary. */
1817 if (!entry_p
->func_ptr
)
1818 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1821 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1824 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1825 opening ( or { and is not null-terminated. If a function invocation
1826 is found, expand it into the buffer at *OP, updating *OP, incrementing
1827 *STRINGP past the reference and returning nonzero. If not, return zero. */
1830 handle_function (char **op
, char **stringp
)
1832 const struct function_table_entry
*entry_p
;
1833 char openparen
= (*stringp
)[0];
1834 char closeparen
= openparen
== '(' ? ')' : '}';
1839 char **argv
, **argvp
;
1844 entry_p
= lookup_function (beg
);
1849 /* We found a builtin function. Find the beginning of its arguments (skip
1850 whitespace after the name). */
1852 beg
= next_token (beg
+ entry_p
->len
);
1854 /* Find the end of the function invocation, counting nested use of
1855 whichever kind of parens we use. Since we're looking, count commas
1856 to get a rough estimate of how many arguments we might have. The
1857 count might be high, but it'll never be low. */
1859 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
1862 else if (*end
== openparen
)
1864 else if (*end
== closeparen
&& --count
< 0)
1868 fatal (reading_file
,
1869 _("unterminated call to function `%s': missing `%c'"),
1870 entry_p
->name
, closeparen
);
1874 /* Get some memory to store the arg pointers. */
1875 argvp
= argv
= (char **) alloca (sizeof (char *) * (nargs
+ 2));
1877 /* Chop the string into arguments, then a nul. As soon as we hit
1878 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
1881 If we're expanding, store pointers to the expansion of each one. If
1882 not, make a duplicate of the string and point into that, nul-terminating
1885 if (!entry_p
->expand_args
)
1887 int len
= end
- beg
;
1889 p
= xmalloc (len
+1);
1890 memcpy (p
, beg
, len
);
1896 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
1902 if (nargs
== entry_p
->maximum_args
1903 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
1906 if (entry_p
->expand_args
)
1907 *argvp
= expand_argument (p
, next
);
1918 /* Finally! Run the function... */
1919 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1922 if (entry_p
->expand_args
)
1923 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1932 /* User-defined functions. Expand the first argument as either a builtin
1933 function or a make variable, in the context of the rest of the arguments
1934 assigned to $1, $2, ... $N. $0 is the name of the function. */
1937 func_call (char *o
, char **argv
, const char *funcname UNUSED
)
1939 static int max_args
= 0;
1946 const struct function_table_entry
*entry_p
;
1949 /* There is no way to define a variable with a space in the name, so strip
1950 leading and trailing whitespace as a favor to the user. */
1952 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
1955 cp
= fname
+ strlen (fname
) - 1;
1956 while (cp
> fname
&& isspace ((unsigned char)*cp
))
1960 /* Calling nothing is a no-op */
1964 /* Are we invoking a builtin function? */
1966 entry_p
= lookup_function (fname
);
1970 /* How many arguments do we have? */
1971 for (i
=0; argv
[i
+1]; ++i
)
1974 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
1977 /* Not a builtin, so the first argument is the name of a variable to be
1978 expanded and interpreted as a function. Find it. */
1979 flen
= strlen (fname
);
1981 v
= lookup_variable (fname
, flen
);
1984 warn_undefined (fname
, flen
);
1986 if (v
== 0 || *v
->value
== '\0')
1989 body
= (char *) alloca (flen
+ 4);
1992 memcpy (body
+ 2, fname
, flen
);
1994 body
[flen
+3] = '\0';
1996 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1998 push_new_variable_scope ();
2000 for (i
=0; *argv
; ++i
, ++argv
)
2004 sprintf (num
, "%d", i
);
2005 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
2008 /* If the number of arguments we have is < max_args, it means we're inside
2009 a recursive invocation of $(call ...). Fill in the remaining arguments
2010 in the new scope with the empty value, to hide them from this
2013 for (; i
< max_args
; ++i
)
2017 sprintf (num
, "%d", i
);
2018 define_variable (num
, strlen (num
), "", o_automatic
, 0);
2021 /* Expand the body in the context of the arguments, adding the result to
2022 the variable buffer. */
2024 v
->exp_count
= EXP_COUNT_MAX
;
2026 saved_args
= max_args
;
2028 o
= variable_expand_string (o
, body
, flen
+3);
2029 max_args
= saved_args
;
2033 pop_variable_scope ();
2035 return o
+ strlen (o
);
2039 hash_init_function_table (void)
2041 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
2042 function_table_entry_hash_1
, function_table_entry_hash_2
,
2043 function_table_entry_hash_cmp
);
2044 hash_load (&function_table
, function_table_init
,
2045 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));