1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
5 This file is part of GNU Make.
7 GNU Make is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 3 of the License, or (at your option) any later
12 GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along with
17 this program. If not, see <http://www.gnu.org/licenses/>. */
31 #ifdef WINDOWS32 /* bird */
32 # include "pathstuff.h"
38 #ifdef CONFIG_WITH_PRINTF
39 # include "kmkbuiltin.h"
41 #ifdef CONFIG_WITH_XARGS /* bird */
46 #include <assert.h> /* bird */
48 #if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE) /* bird */
50 typedef big_int math_int
;
51 static char *math_int_to_variable_buffer (char *, math_int
);
52 static math_int
math_int_from_string (const char *str
);
55 #ifdef CONFIG_WITH_NANOTS /* bird */
62 # define CONFIG_WITH_OS2_LIBPATH 1
64 #ifdef CONFIG_WITH_OS2_LIBPATH
69 # define QHINF_EXEINFO 1 /* NE exeinfo. */
70 # define QHINF_READRSRCTBL 2 /* Reads from the resource table. */
71 # define QHINF_READFILE 3 /* Reads from the executable file. */
72 # define QHINF_LIBPATHLENGTH 4 /* Gets the libpath length. */
73 # define QHINF_LIBPATH 5 /* Gets the entire libpath. */
74 # define QHINF_FIXENTRY 6 /* NE only */
75 # define QHINF_STE 7 /* NE only */
76 # define QHINF_MAPSEL 8 /* NE only */
77 extern APIRET APIENTRY
DosQueryHeaderInfo(HMODULE hmod
, ULONG ulIndex
, PVOID pvBuffer
, ULONG cbBuffer
, ULONG ulSubFunction
);
78 #endif /* CONFIG_WITH_OS2_LIBPATH */
81 struct function_table_entry
85 unsigned char minimum_args
;
86 unsigned char maximum_args
;
88 char *(*func_ptr
) (char *output
, char **argv
, const char *fname
);
92 function_table_entry_hash_1 (const void *keyv
)
94 const struct function_table_entry
*key
= keyv
;
95 return_STRING_N_HASH_1 (key
->name
, key
->len
);
99 function_table_entry_hash_2 (const void *keyv
)
101 const struct function_table_entry
*key
= keyv
;
102 return_STRING_N_HASH_2 (key
->name
, key
->len
);
106 function_table_entry_hash_cmp (const void *xv
, const void *yv
)
108 const struct function_table_entry
*x
= xv
;
109 const struct function_table_entry
*y
= yv
;
110 int result
= x
->len
- y
->len
;
113 return_STRING_N_COMPARE (x
->name
, y
->name
, x
->len
);
116 static struct hash_table function_table
;
118 #ifdef CONFIG_WITH_MAKE_STATS
119 long make_stats_allocations
= 0;
120 long make_stats_reallocations
= 0;
121 unsigned long make_stats_allocated
= 0;
122 unsigned long make_stats_ht_lookups
= 0;
123 unsigned long make_stats_ht_collisions
= 0;
127 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
128 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
129 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
130 nonzero, substitutions are done only on matches which are complete
131 whitespace-delimited words. */
134 subst_expand (char *o
, const char *text
, const char *subst
, const char *replace
,
135 unsigned int slen
, unsigned int rlen
, int by_word
)
137 const char *t
= text
;
140 if (slen
== 0 && !by_word
)
142 /* The first occurrence of "" in any string is its end. */
143 o
= variable_buffer_output (o
, t
, strlen (t
));
145 o
= variable_buffer_output (o
, replace
, rlen
);
151 if (by_word
&& slen
== 0)
152 /* When matching by words, the empty string should match
153 the end of each word, rather than the end of the whole text. */
154 p
= end_of_token (next_token (t
));
157 p
= strstr (t
, subst
);
160 /* No more matches. Output everything left on the end. */
161 o
= variable_buffer_output (o
, t
, strlen (t
));
166 /* Output everything before this occurrence of the string to replace. */
168 o
= variable_buffer_output (o
, t
, p
- t
);
170 /* If we're substituting only by fully matched words,
171 or only at the ends of words, check that this case qualifies. */
173 && ((p
> text
&& !isblank ((unsigned char)p
[-1]))
174 || (p
[slen
] != '\0' && !isblank ((unsigned char)p
[slen
]))))
175 /* Struck out. Output the rest of the string that is
176 no longer to be replaced. */
177 o
= variable_buffer_output (o
, subst
, slen
);
179 /* Output the replacement string. */
180 o
= variable_buffer_output (o
, replace
, rlen
);
182 /* Advance T past the string to be replaced. */
184 } while (*t
!= '\0');
190 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
191 and replacing strings matching PATTERN with REPLACE.
192 If PATTERN_PERCENT is not nil, PATTERN has already been
193 run through find_percent, and PATTERN_PERCENT is the result.
194 If REPLACE_PERCENT is not nil, REPLACE has already been
195 run through find_percent, and REPLACE_PERCENT is the result.
196 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
197 character _AFTER_ the %, not to the % itself.
201 patsubst_expand_pat (char *o
, const char *text
,
202 const char *pattern
, const char *replace
,
203 const char *pattern_percent
, const char *replace_percent
)
205 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
206 unsigned int replace_prepercent_len
, replace_postpercent_len
;
211 /* Record the length of REPLACE before and after the % so we don't have to
212 compute these lengths more than once. */
215 replace_prepercent_len
= replace_percent
- replace
- 1;
216 replace_postpercent_len
= strlen (replace_percent
);
220 replace_prepercent_len
= strlen (replace
);
221 replace_postpercent_len
= 0;
224 if (!pattern_percent
)
225 /* With no % in the pattern, this is just a simple substitution. */
226 return subst_expand (o
, text
, pattern
, replace
,
227 strlen (pattern
), strlen (replace
), 1);
229 /* Record the length of PATTERN before and after the %
230 so we don't have to compute it more than once. */
231 pattern_prepercent_len
= pattern_percent
- pattern
- 1;
232 pattern_postpercent_len
= strlen (pattern_percent
);
234 while ((t
= find_next_token (&text
, &len
)) != 0)
238 /* Is it big enough to match? */
239 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
242 /* Does the prefix match? */
243 if (!fail
&& pattern_prepercent_len
> 0
245 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-2]
246 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
249 /* Does the suffix match? */
250 if (!fail
&& pattern_postpercent_len
> 0
251 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
- 1]
252 || t
[len
- pattern_postpercent_len
] != *pattern_percent
253 || !strneq (&t
[len
- pattern_postpercent_len
],
254 pattern_percent
, pattern_postpercent_len
- 1)))
258 /* It didn't match. Output the string. */
259 o
= variable_buffer_output (o
, t
, len
);
262 /* It matched. Output the replacement. */
264 /* Output the part of the replacement before the %. */
265 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
267 if (replace_percent
!= 0)
269 /* Output the part of the matched string that
270 matched the % in the pattern. */
271 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
272 len
- (pattern_prepercent_len
273 + pattern_postpercent_len
));
274 /* Output the part of the replacement after the %. */
275 o
= variable_buffer_output (o
, replace_percent
,
276 replace_postpercent_len
);
280 /* Output a space, but not if the replacement is "". */
281 if (fail
|| replace_prepercent_len
> 0
282 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
284 o
= variable_buffer_output (o
, " ", 1);
288 #ifndef CONFIG_WITH_VALUE_LENGTH
290 /* Kill the last space. */
293 /* Kill the last space and make sure there is a terminator there
294 so that strcache_add_len doesn't have to do a lot of exacty work
295 when expand_deps sends the output its way. */
299 o
= variable_buffer_output (o
, "\0", 1) - 1;
305 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
306 and replacing strings matching PATTERN with REPLACE.
307 If PATTERN_PERCENT is not nil, PATTERN has already been
308 run through find_percent, and PATTERN_PERCENT is the result.
309 If REPLACE_PERCENT is not nil, REPLACE has already been
310 run through find_percent, and REPLACE_PERCENT is the result.
311 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
312 character _AFTER_ the %, not to the % itself.
316 patsubst_expand (char *o
, const char *text
, char *pattern
, char *replace
)
318 const char *pattern_percent
= find_percent (pattern
);
319 const char *replace_percent
= find_percent (replace
);
321 /* If there's a percent in the pattern or replacement skip it. */
327 return patsubst_expand_pat (o
, text
, pattern
, replace
,
328 pattern_percent
, replace_percent
);
331 #if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
333 /* Char map containing the valid function name characters. */
334 char func_char_map
[256];
336 /* Do the hash table lookup. */
338 MY_INLINE
const struct function_table_entry
*
339 lookup_function_in_hash_tab (const char *s
, unsigned char len
)
341 struct function_table_entry function_table_entry_key
;
342 function_table_entry_key
.name
= s
;
343 function_table_entry_key
.len
= len
;
345 return hash_find_item (&function_table
, &function_table_entry_key
);
348 /* Look up a function by name. */
350 MY_INLINE
const struct function_table_entry
*
351 lookup_function (const char *s
, unsigned int len
)
354 # if 0 /* insane loop unroll */
356 if (len
> MAX_FUNCTION_LENGTH
)
357 len
= MAX_FUNCTION_LENGTH
+ 1;
360 if (!func_char_map[ch = s[idx]]) \
363 return lookup_function_in_hash_tab (s, idx); \
367 return lookup_function_in_hash_tab (s, idx);
375 case 2: X(0); X(1); Z(2);
376 case 3: X(0); X(1); X(2); Z(3);
377 case 4: X(0); X(1); X(2); X(3); Z(4);
378 case 5: X(0); X(1); X(2); X(3); X(4); Z(5);
379 case 6: X(0); X(1); X(2); X(3); X(4); X(5); Z(6);
380 case 7: X(0); X(1); X(2); X(3); X(4); X(5); X(6); Z(7);
381 case 8: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); Z(8);
382 case 9: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); Z(9);
383 case 10: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); Z(10);
384 case 11: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); Z(11);
385 case 12: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); Z(12);
386 case 13: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); X(12);
387 if ((ch
= s
[12]) == '\0' || isblank (ch
))
388 return lookup_function_in_hash_tab (s
, 12);
394 # else /* normal loop */
396 if (len
> MAX_FUNCTION_LENGTH
)
397 len
= MAX_FUNCTION_LENGTH
;
398 while (func_char_map
[ch
= *e
])
404 if (ch
== '\0' || isblank (ch
))
405 return lookup_function_in_hash_tab (s
, e
- s
);
407 # endif /* normal loop */
410 #else /* original code */
411 /* Look up a function by name. */
413 static const struct function_table_entry
*
414 lookup_function (const char *s
)
417 while (*e
&& ( (*e
>= 'a' && *e
<= 'z') || *e
== '-'))
419 if (*e
== '\0' || isblank ((unsigned char) *e
))
421 struct function_table_entry function_table_entry_key
;
422 function_table_entry_key
.name
= s
;
423 function_table_entry_key
.len
= e
- s
;
425 return hash_find_item (&function_table
, &function_table_entry_key
);
429 #endif /* original code */
432 /* Return 1 if PATTERN matches STR, 0 if not. */
435 pattern_matches (const char *pattern
, const char *percent
, const char *str
)
437 unsigned int sfxlen
, strlength
;
441 unsigned int len
= strlen (pattern
) + 1;
442 char *new_chars
= alloca (len
);
443 memcpy (new_chars
, pattern
, len
);
444 percent
= find_percent (new_chars
);
446 return streq (new_chars
, str
);
450 sfxlen
= strlen (percent
+ 1);
451 strlength
= strlen (str
);
453 if (strlength
< (percent
- pattern
) + sfxlen
454 || !strneq (pattern
, str
, percent
- pattern
))
457 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
461 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
462 ENDPARENtheses), starting at PTR before END. Return a pointer to
465 If no next argument is found, return NULL.
469 find_next_argument (char startparen
, char endparen
,
470 const char *ptr
, const char *end
)
474 for (; ptr
< end
; ++ptr
)
475 if (*ptr
== startparen
)
478 else if (*ptr
== endparen
)
485 else if (*ptr
== ',' && !count
)
488 /* We didn't find anything. */
493 /* Glob-expand LINE. The returned pointer is
494 only good until the next call to string_glob. */
497 string_glob (char *line
)
499 static char *result
= 0;
500 static unsigned int length
;
501 struct nameseq
*chain
;
504 #ifndef CONFIG_WITH_ALLOC_CACHES
505 chain
= multi_glob (parse_file_seq
506 (&line
, '\0', sizeof (struct nameseq
),
507 /* We do not want parse_file_seq to strip `./'s.
508 That would break examples like:
509 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
511 sizeof (struct nameseq
));
512 #else /* CONFIG_WITH_ALLOC_CACHES */
513 chain
= multi_glob (parse_file_seq
514 (&line
, '\0', &nameseq_cache
,
515 /* We do not want parse_file_seq to strip `./'s.
516 That would break examples like:
517 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
520 #endif /* CONFIG_WITH_ALLOC_CACHES */
525 result
= xmalloc (100);
531 const char *name
= chain
->name
;
532 unsigned int len
= strlen (name
);
534 struct nameseq
*next
= chain
->next
;
535 #ifndef CONFIG_WITH_ALLOC_CACHES
538 alloccache_free (&nameseq_cache
, chain
);
542 /* multi_glob will pass names without globbing metacharacters
543 through as is, but we want only files that actually exist. */
544 if (file_exists_p (name
))
546 if (idx
+ len
+ 1 > length
)
548 length
+= (len
+ 1) * 2;
549 result
= xrealloc (result
, length
);
551 memcpy (&result
[idx
], name
, len
);
557 /* Kill the last space and terminate the string. */
561 result
[idx
- 1] = '\0';
571 func_patsubst (char *o
, char **argv
, const char *funcname UNUSED
)
573 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1]);
579 func_join (char *o
, char **argv
, const char *funcname UNUSED
)
583 /* Write each word of the first argument directly followed
584 by the corresponding word of the second argument.
585 If the two arguments have a different number of words,
586 the excess words are just output separated by blanks. */
589 const char *list1_iterator
= argv
[0];
590 const char *list2_iterator
= argv
[1];
593 unsigned int len1
, len2
;
595 tp
= find_next_token (&list1_iterator
, &len1
);
597 o
= variable_buffer_output (o
, tp
, len1
);
599 pp
= find_next_token (&list2_iterator
, &len2
);
601 o
= variable_buffer_output (o
, pp
, len2
);
603 if (tp
!= 0 || pp
!= 0)
605 o
= variable_buffer_output (o
, " ", 1);
609 while (tp
!= 0 || pp
!= 0);
611 /* Kill the last blank. */
619 func_origin (char *o
, char **argv
, const char *funcname UNUSED
)
621 /* Expand the argument. */
622 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
624 o
= variable_buffer_output (o
, "undefined", 9);
633 o
= variable_buffer_output (o
, "default", 7);
636 o
= variable_buffer_output (o
, "environment", 11);
639 o
= variable_buffer_output (o
, "file", 4);
642 o
= variable_buffer_output (o
, "environment override", 20);
645 o
= variable_buffer_output (o
, "command line", 12);
648 o
= variable_buffer_output (o
, "override", 8);
651 o
= variable_buffer_output (o
, "automatic", 9);
653 #ifdef CONFIG_WITH_LOCAL_VARIABLES
655 o
= variable_buffer_output (o
, "local", 5);
664 func_flavor (char *o
, char **argv
, const char *funcname UNUSED
)
666 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
669 o
= variable_buffer_output (o
, "undefined", 9);
672 o
= variable_buffer_output (o
, "recursive", 9);
674 o
= variable_buffer_output (o
, "simple", 6);
680 # define IS_PATHSEP(c) ((c) == ']')
682 # ifdef HAVE_DOS_PATHS
683 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
685 # define IS_PATHSEP(c) ((c) == '/')
691 func_notdir_suffix (char *o
, char **argv
, const char *funcname
)
693 /* Expand the argument. */
694 const char *list_iterator
= argv
[0];
699 int is_suffix
= streq (funcname
, "suffix");
700 int is_notdir
= !is_suffix
;
701 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
703 const char *p
= p2
+ len
;
706 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
719 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
721 #ifdef HAVE_DOS_PATHS
722 /* Handle the case of "d:foo/bar". */
723 else if (streq (funcname
, "notdir") && p2
[0] && p2
[1] == ':')
726 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
730 o
= variable_buffer_output (o
, p2
, len
);
732 if (is_notdir
|| p
>= p2
)
734 o
= variable_buffer_output (o
, " ", 1);
740 /* Kill last space. */
748 func_basename_dir (char *o
, char **argv
, const char *funcname
)
750 /* Expand the argument. */
751 const char *p3
= argv
[0];
756 int is_basename
= streq (funcname
, "basename");
757 int is_dir
= !is_basename
;
759 while ((p2
= find_next_token (&p3
, &len
)) != 0)
761 const char *p
= p2
+ len
;
762 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
769 if (p
>= p2
&& (is_dir
))
770 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
771 else if (p
>= p2
&& (*p
== '.'))
772 o
= variable_buffer_output (o
, p2
, p
- p2
);
773 #ifdef HAVE_DOS_PATHS
774 /* Handle the "d:foobar" case */
775 else if (p2
[0] && p2
[1] == ':' && is_dir
)
776 o
= variable_buffer_output (o
, p2
, 2);
780 o
= variable_buffer_output (o
, "[]", 2);
783 o
= variable_buffer_output (o
, "./", 2);
785 ; /* Just a nop... */
789 /* The entire name is the basename. */
790 o
= variable_buffer_output (o
, p2
, len
);
792 o
= variable_buffer_output (o
, " ", 1);
797 /* Kill last space. */
803 #ifdef CONFIG_WITH_ROOT_FUNC
807 This is mainly for dealing with drive letters and UNC paths on Windows
811 func_root (char *o
, char **argv
, const char *funcname UNUSED
)
813 const char *paths
= argv
[0] ? argv
[0] : "";
818 while ((p
= find_next_token (&paths
, &len
)) != 0)
822 #ifdef HAVE_DOS_PATHS
825 && ( (p2
[0] >= 'A' && p2
[0] <= 'Z')
826 || (p2
[0] >= 'a' && p2
[0] <= 'z')))
831 else if (len
>= 4 && IS_PATHSEP(p2
[0]) && IS_PATHSEP(p2
[1])
832 && !IS_PATHSEP(p2
[2]))
834 /* Min recognized UNC: "//./" - find the next slash
835 Typical root: "//srv/shr/" */
836 /* XXX: Check if //./ needs special handling. */
840 while (len
> 0 && !IS_PATHSEP(*p2
))
843 if (len
&& IS_PATHSEP(p2
[0]) && (len
== 1 || !IS_PATHSEP(p2
[1])))
848 if (len
) /* optional share */
849 while (len
> 0 && !IS_PATHSEP(*p2
))
855 else if (IS_PATHSEP(*p2
))
863 #elif defined (VMS) || defined (AMGIA)
864 /* XXX: VMS and AMGIA */
865 fatal (NILF
, _("$(root ) is not implemented on this platform"));
877 /* Include all subsequent path seperators. */
879 while (len
> 0 && IS_PATHSEP(*p2
))
881 o
= variable_buffer_output (o
, p
, p2
- p
);
882 o
= variable_buffer_output (o
, " ", 1);
888 /* Kill last space. */
893 #endif /* CONFIG_WITH_ROOT_FUNC */
896 func_addsuffix_addprefix (char *o
, char **argv
, const char *funcname
)
898 int fixlen
= strlen (argv
[0]);
899 const char *list_iterator
= argv
[1];
900 int is_addprefix
= streq (funcname
, "addprefix");
901 int is_addsuffix
= !is_addprefix
;
907 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
910 o
= variable_buffer_output (o
, argv
[0], fixlen
);
911 o
= variable_buffer_output (o
, p
, len
);
913 o
= variable_buffer_output (o
, argv
[0], fixlen
);
914 o
= variable_buffer_output (o
, " ", 1);
919 /* Kill last space. */
926 func_subst (char *o
, char **argv
, const char *funcname UNUSED
)
928 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
929 strlen (argv
[1]), 0);
936 func_firstword (char *o
, char **argv
, const char *funcname UNUSED
)
939 const char *words
= argv
[0]; /* Use a temp variable for find_next_token */
940 const char *p
= find_next_token (&words
, &i
);
943 o
= variable_buffer_output (o
, p
, i
);
949 func_lastword (char *o
, char **argv
, const char *funcname UNUSED
)
952 const char *words
= argv
[0]; /* Use a temp variable for find_next_token */
953 const char *p
= NULL
;
956 while ((t
= find_next_token (&words
, &i
)))
960 o
= variable_buffer_output (o
, p
, i
);
966 func_words (char *o
, char **argv
, const char *funcname UNUSED
)
969 const char *word_iterator
= argv
[0];
972 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
975 sprintf (buf
, "%d", i
);
976 o
= variable_buffer_output (o
, buf
, strlen (buf
));
981 /* Set begpp to point to the first non-whitespace character of the string,
982 * and endpp to point to the last non-whitespace character of the string.
983 * If the string is empty or contains nothing but whitespace, endpp will be
987 strip_whitespace (const char **begpp
, const char **endpp
)
989 while (*begpp
<= *endpp
&& isspace ((unsigned char)**begpp
))
991 while (*endpp
>= *begpp
&& isspace ((unsigned char)**endpp
))
993 return (char *)*begpp
;
997 check_numeric (const char *s
, const char *msg
)
999 const char *end
= s
+ strlen (s
) - 1;
1000 const char *beg
= s
;
1001 strip_whitespace (&s
, &end
);
1003 for (; s
<= end
; ++s
)
1004 if (!ISDIGIT (*s
)) /* ISDIGIT only evals its arg once: see make.h. */
1007 if (s
<= end
|| end
- beg
< 0)
1008 fatal (*expanding_var
, "%s: '%s'", msg
, beg
);
1014 func_word (char *o
, char **argv
, const char *funcname UNUSED
)
1020 /* Check the first argument. */
1021 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
1025 fatal (*expanding_var
,
1026 _("first argument to `word' function must be greater than 0"));
1029 while ((p
= find_next_token (&end_p
, 0)) != 0)
1034 o
= variable_buffer_output (o
, p
, end_p
- p
);
1040 func_wordlist (char *o
, char **argv
, const char *funcname UNUSED
)
1044 /* Check the arguments. */
1045 check_numeric (argv
[0],
1046 _("non-numeric first argument to `wordlist' function"));
1047 check_numeric (argv
[1],
1048 _("non-numeric second argument to `wordlist' function"));
1050 start
= atoi (argv
[0]);
1052 fatal (*expanding_var
,
1053 "invalid first argument to `wordlist' function: `%d'", start
);
1055 count
= atoi (argv
[1]) - start
+ 1;
1060 const char *end_p
= argv
[2];
1062 /* Find the beginning of the "start"th word. */
1063 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
1068 /* Find the end of the "count"th word from start. */
1069 while (--count
&& (find_next_token (&end_p
, 0) != 0))
1072 /* Return the stuff in the middle. */
1073 o
= variable_buffer_output (o
, p
, end_p
- p
);
1081 func_findstring (char *o
, char **argv
, const char *funcname UNUSED
)
1083 /* Find the first occurrence of the first string in the second. */
1084 if (strstr (argv
[1], argv
[0]) != 0)
1085 o
= variable_buffer_output (o
, argv
[0], strlen (argv
[0]));
1091 func_foreach (char *o
, char **argv
, const char *funcname UNUSED
)
1093 /* expand only the first two. */
1094 char *varname
= expand_argument (argv
[0], NULL
);
1095 char *list
= expand_argument (argv
[1], NULL
);
1096 const char *body
= argv
[2];
1097 #ifdef CONFIG_WITH_VALUE_LENGTH
1098 long body_len
= strlen (body
);
1102 const char *list_iterator
= list
;
1105 struct variable
*var
;
1107 push_new_variable_scope ();
1108 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
1110 /* loop through LIST, put the value in VAR and expand BODY */
1111 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
1113 #ifndef CONFIG_WITH_VALUE_LENGTH
1117 var
->value
= savestring (p
, len
);
1119 result
= allocated_variable_expand (body
);
1121 o
= variable_buffer_output (o
, result
, strlen (result
));
1122 o
= variable_buffer_output (o
, " ", 1);
1125 #else /* CONFIG_WITH_VALUE_LENGTH */
1126 if (len
>= var
->value_alloc_len
)
1128 # ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
1129 if (var
->rdonly_val
)
1130 var
->rdonly_val
= 0;
1134 var
->value_alloc_len
= VAR_ALIGN_VALUE_ALLOC (len
+ 1);
1135 var
->value
= xmalloc (var
->value_alloc_len
);
1137 memcpy (var
->value
, p
, len
);
1138 var
->value
[len
] = '\0';
1139 var
->value_length
= len
;
1141 variable_expand_string_2 (o
, body
, body_len
, &o
);
1142 o
= variable_buffer_output (o
, " ", 1);
1144 #endif /* CONFIG_WITH_VALUE_LENGTH */
1148 /* Kill the last space. */
1151 pop_variable_scope ();
1158 #ifdef CONFIG_WITH_LOOP_FUNCTIONS
1160 /* Helper for func_for that evaluates the INIT and NEXT parts. */
1162 helper_eval (char *text
, size_t text_len
)
1164 unsigned int buf_len
;
1167 install_variable_buffer (&buf
, &buf_len
);
1168 eval_buffer (text
, text
+ text_len
);
1169 restore_variable_buffer (buf
, buf_len
);
1173 $(for init,condition,next,body)
1176 func_for (char *o
, char **argv
, const char *funcname UNUSED
)
1178 char *init
= argv
[0];
1179 const char *cond
= argv
[1];
1180 const char *next
= argv
[2];
1181 size_t next_len
= strlen (next
);
1182 char *next_buf
= xmalloc (next_len
+ 1);
1183 const char *body
= argv
[3];
1184 size_t body_len
= strlen (body
);
1185 unsigned int doneany
= 0;
1187 push_new_variable_scope ();
1189 /* Evaluate INIT. */
1191 helper_eval (init
, strlen (init
));
1193 /* Loop till COND is false. */
1195 while (expr_eval_if_conditionals (cond
, NULL
) == 0 /* true */)
1202 o
= variable_buffer_output (o
, " ", 1);
1203 variable_expand_string_2 (o
, body
, body_len
, &o
);
1205 /* Evaluate NEXT. */
1207 memcpy (next_buf
, next
, next_len
+ 1);
1208 helper_eval (next_buf
, next_len
);
1211 pop_variable_scope ();
1218 $(while condition,body)
1221 func_while (char *o
, char **argv
, const char *funcname UNUSED
)
1223 const char *cond
= argv
[0];
1224 const char *body
= argv
[1];
1225 size_t body_len
= strlen (body
);
1226 unsigned int doneany
= 0;
1228 push_new_variable_scope ();
1230 while (expr_eval_if_conditionals (cond
, NULL
) == 0 /* true */)
1235 o
= variable_buffer_output (o
, " ", 1);
1236 variable_expand_string_2 (o
, body
, body_len
, &o
);
1239 pop_variable_scope ();
1244 #endif /* CONFIG_WITH_LOOP_FUNCTIONS */
1248 struct a_word
*next
;
1249 struct a_word
*chain
;
1255 static unsigned long
1256 a_word_hash_1 (const void *key
)
1258 return_STRING_HASH_1 (((struct a_word
const *) key
)->str
);
1261 static unsigned long
1262 a_word_hash_2 (const void *key
)
1264 return_STRING_HASH_2 (((struct a_word
const *) key
)->str
);
1268 a_word_hash_cmp (const void *x
, const void *y
)
1270 int result
= ((struct a_word
const *) x
)->length
- ((struct a_word
const *) y
)->length
;
1273 return_STRING_COMPARE (((struct a_word
const *) x
)->str
,
1274 ((struct a_word
const *) y
)->str
);
1279 struct a_pattern
*next
;
1287 func_filter_filterout (char *o
, char **argv
, const char *funcname
)
1289 struct a_word
*wordhead
;
1290 struct a_word
**wordtail
;
1292 struct a_pattern
*pathead
;
1293 struct a_pattern
**pattail
;
1294 struct a_pattern
*pp
;
1296 struct hash_table a_word_table
;
1297 int is_filter
= streq (funcname
, "filter");
1298 const char *pat_iterator
= argv
[0];
1299 const char *word_iterator
= argv
[1];
1306 /* Chop ARGV[0] up into patterns to match against the words. */
1309 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
1311 struct a_pattern
*pat
= alloca (sizeof (struct a_pattern
));
1314 pattail
= &pat
->next
;
1316 if (*pat_iterator
!= '\0')
1321 pat
->save_c
= p
[len
];
1323 pat
->percent
= find_percent (p
);
1324 if (pat
->percent
== 0)
1329 /* Chop ARGV[1] up into words to match against the patterns. */
1331 wordtail
= &wordhead
;
1332 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
1334 struct a_word
*word
= alloca (sizeof (struct a_word
));
1337 wordtail
= &word
->next
;
1339 if (*word_iterator
!= '\0')
1351 /* Only use a hash table if arg list lengths justifies the cost. */
1352 hashing
= (literals
>= 2 && (literals
* words
) >= 10);
1355 hash_init (&a_word_table
, words
, a_word_hash_1
, a_word_hash_2
,
1357 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1359 struct a_word
*owp
= hash_insert (&a_word_table
, wp
);
1369 /* Run each pattern through the words, killing words. */
1370 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1373 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1374 wp
->matched
|= pattern_matches (pp
->str
, pp
->percent
, wp
->str
);
1377 struct a_word a_word_key
;
1378 a_word_key
.str
= pp
->str
;
1379 a_word_key
.length
= pp
->length
;
1380 wp
= hash_find_item (&a_word_table
, &a_word_key
);
1388 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1389 wp
->matched
|= (wp
->length
== pp
->length
1390 && strneq (pp
->str
, wp
->str
, wp
->length
));
1393 /* Output the words that matched (or didn't, for filter-out). */
1394 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
1395 if (is_filter
? wp
->matched
: !wp
->matched
)
1397 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
1398 o
= variable_buffer_output (o
, " ", 1);
1403 /* Kill the last space. */
1407 for (pp
= pathead
; pp
!= 0; pp
= pp
->next
)
1408 pp
->str
[pp
->length
] = pp
->save_c
;
1411 hash_free (&a_word_table
, 0);
1418 func_strip (char *o
, char **argv
, const char *funcname UNUSED
)
1420 const char *p
= argv
[0];
1426 const char *word_start
;
1428 while (isspace ((unsigned char)*p
))
1431 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
1435 o
= variable_buffer_output (o
, word_start
, i
);
1436 o
= variable_buffer_output (o
, " ", 1);
1441 /* Kill the last space. */
1448 Print a warning or fatal message.
1451 func_error (char *o
, char **argv
, const char *funcname
)
1457 /* The arguments will be broken on commas. Rather than create yet
1458 another special case where function arguments aren't broken up,
1459 just create a format string that puts them back together. */
1460 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
1461 len
+= strlen (*argvp
) + 2;
1463 p
= msg
= alloca (len
+ 1);
1465 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1468 p
+= strlen (*argvp
);
1474 switch (*funcname
) {
1476 fatal (reading_file
, "%s", msg
);
1479 error (reading_file
, "%s", msg
);
1483 printf ("%s\n", msg
);
1488 fatal (*expanding_var
, "Internal error: func_error: '%s'", funcname
);
1491 /* The warning function expands to the empty string. */
1497 chop argv[0] into words, and sort them.
1500 func_sort (char *o
, char **argv
, const char *funcname UNUSED
)
1509 /* Find the maximum number of words we'll have. */
1516 if (! isspace ((unsigned char)c
))
1521 while (isspace ((unsigned char)*t
))
1525 words
= xmalloc (wordi
* sizeof (char *));
1527 /* Now assign pointers to each string in the array. */
1530 while ((p
= find_next_token (&t
, &len
)) != 0)
1539 /* Now sort the list of words. */
1540 qsort (words
, wordi
, sizeof (char *), alpha_compare
);
1542 /* Now write the sorted list, uniquified. */
1543 #ifdef CONFIG_WITH_RSORT
1544 if (strcmp (funcname
, "rsort"))
1548 for (i
= 0; i
< wordi
; ++i
)
1550 len
= strlen (words
[i
]);
1551 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1552 || strcmp (words
[i
], words
[i
+ 1]))
1554 o
= variable_buffer_output (o
, words
[i
], len
);
1555 o
= variable_buffer_output (o
, " ", 1);
1558 #ifdef CONFIG_WITH_RSORT
1562 /* rsort - reverse the result */
1566 len
= strlen (words
[i
]);
1567 if (i
== 0 || strlen (words
[i
- 1]) != len
1568 || strcmp (words
[i
], words
[i
- 1]))
1570 o
= variable_buffer_output (o
, words
[i
], len
);
1571 o
= variable_buffer_output (o
, " ", 1);
1577 /* Kill the last space. */
1587 $(if condition,true-part[,false-part])
1589 CONDITION is false iff it evaluates to an empty string. White
1590 space before and after condition are stripped before evaluation.
1592 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1593 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1594 you can use $(if ...) to create side-effects (with $(shell ...), for
1599 func_if (char *o
, char **argv
, const char *funcname UNUSED
)
1601 const char *begp
= argv
[0];
1602 const char *endp
= begp
+ strlen (argv
[0]) - 1;
1605 /* Find the result of the condition: if we have a value, and it's not
1606 empty, the condition is true. If we don't have a value, or it's the
1607 empty string, then it's false. */
1609 strip_whitespace (&begp
, &endp
);
1613 char *expansion
= expand_argument (begp
, endp
+1);
1615 result
= strlen (expansion
);
1619 /* If the result is true (1) we want to eval the first argument, and if
1620 it's false (0) we want to eval the second. If the argument doesn't
1621 exist we do nothing, otherwise expand it and add to the buffer. */
1623 argv
+= 1 + !result
;
1627 char *expansion
= expand_argument (*argv
, NULL
);
1629 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1638 $(or condition1[,condition2[,condition3[...]]])
1640 A CONDITION is false iff it evaluates to an empty string. White
1641 space before and after CONDITION are stripped before evaluation.
1643 CONDITION1 is evaluated. If it's true, then this is the result of
1644 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1645 the conditions are true, the expansion is the empty string.
1647 Once a CONDITION is true no further conditions are evaluated
1652 func_or (char *o
, char **argv
, const char *funcname UNUSED
)
1654 for ( ; *argv
; ++argv
)
1656 const char *begp
= *argv
;
1657 const char *endp
= begp
+ strlen (*argv
) - 1;
1661 /* Find the result of the condition: if it's false keep going. */
1663 strip_whitespace (&begp
, &endp
);
1668 expansion
= expand_argument (begp
, endp
+1);
1669 result
= strlen (expansion
);
1671 /* If the result is false keep going. */
1678 /* It's true! Keep this result and return. */
1679 o
= variable_buffer_output (o
, expansion
, result
);
1688 $(and condition1[,condition2[,condition3[...]]])
1690 A CONDITION is false iff it evaluates to an empty string. White
1691 space before and after CONDITION are stripped before evaluation.
1693 CONDITION1 is evaluated. If it's false, then this is the result of
1694 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1695 the conditions are true, the expansion is the result of the last condition.
1697 Once a CONDITION is false no further conditions are evaluated
1702 func_and (char *o
, char **argv
, const char *funcname UNUSED
)
1709 const char *begp
= *argv
;
1710 const char *endp
= begp
+ strlen (*argv
) - 1;
1712 /* An empty condition is always false. */
1713 strip_whitespace (&begp
, &endp
);
1717 expansion
= expand_argument (begp
, endp
+1);
1718 result
= strlen (expansion
);
1720 /* If the result is false, stop here: we're done. */
1724 /* Otherwise the result is true. If this is the last one, keep this
1725 result and quit. Otherwise go on to the next one! */
1731 o
= variable_buffer_output (o
, expansion
, result
);
1742 func_wildcard (char *o
, char **argv
, const char *funcname UNUSED
)
1745 o
= wildcard_expansion (argv
[0], o
);
1747 char *p
= string_glob (argv
[0]);
1748 o
= variable_buffer_output (o
, p
, strlen (p
));
1754 $(eval <makefile string>)
1756 Always resolves to the empty string.
1758 Treat the arguments as a segment of makefile, and parse them.
1762 func_eval (char *o
, char **argv
, const char *funcname UNUSED
)
1767 /* Eval the buffer. Pop the current variable buffer setting so that the
1768 eval'd code can use its own without conflicting. */
1770 install_variable_buffer (&buf
, &len
);
1772 #ifndef CONFIG_WITH_VALUE_LENGTH
1773 eval_buffer (argv
[0]);
1775 eval_buffer (argv
[0], strchr (argv
[0], '\0'));
1778 restore_variable_buffer (buf
, len
);
1784 #ifdef CONFIG_WITH_EVALPLUS
1785 /* Same as func_eval except that we push and pop the local variable
1786 context before evaluating the buffer. */
1788 func_evalctx (char *o
, char **argv
, const char *funcname UNUSED
)
1793 /* Eval the buffer. Pop the current variable buffer setting so that the
1794 eval'd code can use its own without conflicting. */
1796 install_variable_buffer (&buf
, &len
);
1798 push_new_variable_scope ();
1800 eval_buffer (argv
[0], strchr (argv
[0], '\0'));
1802 pop_variable_scope ();
1804 restore_variable_buffer (buf
, len
);
1809 /* A mix of func_eval and func_value, saves memory for the expansion.
1810 This implements both evalval and evalvalctx, the latter has its own
1811 variable context just like evalctx. */
1813 func_evalval (char *o
, char **argv
, const char *funcname
)
1815 /* Look up the variable. */
1816 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1823 const struct floc
*reading_file_saved
= reading_file
;
1825 /* Make a copy of the value to the variable buffer since
1826 eval_buffer will make changes to its input. */
1828 off
= o
- variable_buffer
;
1829 variable_buffer_output (o
, v
->value
, v
->value_length
+ 1);
1830 o
= variable_buffer
+ off
;
1832 /* Eval the value. Pop the current variable buffer setting so that the
1833 eval'd code can use its own without conflicting. (really necessary?) */
1835 install_variable_buffer (&buf
, &len
);
1836 var_ctx
= !strcmp (funcname
, "evalvalctx");
1838 push_new_variable_scope ();
1839 if (v
->fileinfo
.filenm
)
1840 reading_file
= &v
->fileinfo
;
1842 assert (!o
[v
->value_length
]);
1843 eval_buffer (o
, o
+ v
->value_length
);
1845 reading_file
= reading_file_saved
;
1847 pop_variable_scope ();
1848 restore_variable_buffer (buf
, len
);
1854 /* Optimizes the content of one or more variables to save time in
1855 the eval functions. This function will collapse line continuations
1856 and remove comments. */
1858 func_eval_optimize_variable (char *o
, char **argv
, const char *funcname
)
1862 for (i
= 0; argv
[i
]; i
++)
1864 struct variable
*v
= lookup_variable (argv
[i
], strlen (argv
[i
]));
1865 # ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
1866 if (v
&& !v
->origin
!= o_automatic
&& !v
->rdonly_val
)
1868 if (v
&& !v
->origin
!= o_automatic
)
1873 eos
= collapse_continuations (v
->value
, v
->value_length
);
1874 v
->value_length
= eos
- v
->value
;
1876 /* remove comments */
1878 src
= memchr (v
->value
, '#', v
->value_length
);
1881 unsigned char ch
= '\0';
1885 /* drop blanks preceeding the comment */
1886 while (dst
> v
->value
)
1888 ch
= (unsigned char)dst
[-1];
1894 /* advance SRC to eol / eos. */
1895 src
= memchr (src
, '\n', eos
- src
);
1899 /* drop a preceeding newline if possible (full line comment) */
1900 if (dst
> v
->value
&& dst
[-1] == '\n')
1903 /* copy till next comment or eol. */
1912 while (ch
== '#' && src
< eos
);
1915 v
->value_length
= dst
- v
->value
;
1919 error (NILF
, _("$(%s ): variable `%s' is of the wrong type\n"), funcname
, v
->name
);
1925 #endif /* CONFIG_WITH_EVALPLUS */
1928 func_value (char *o
, char **argv
, const char *funcname UNUSED
)
1930 /* Look up the variable. */
1931 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
1933 /* Copy its value into the output buffer without expanding it. */
1935 #ifdef CONFIG_WITH_VALUE_LENGTH
1937 assert (v
->value_length
== strlen (v
->value
));
1938 o
= variable_buffer_output (o
, v
->value
, v
->value_length
);
1941 o
= variable_buffer_output (o
, v
->value
, strlen(v
->value
));
1948 \r is replaced on UNIX as well. Is this desirable?
1951 fold_newlines (char *buffer
, unsigned int *length
)
1955 char *last_nonnl
= buffer
-1;
1957 for (; *src
!= '\0'; ++src
)
1959 if (src
[0] == '\r' && src
[1] == '\n')
1971 *(++last_nonnl
) = '\0';
1972 *length
= last_nonnl
- buffer
;
1977 int shell_function_pid
= 0, shell_function_completed
;
1983 #include <windows.h>
1985 #include "sub_proc.h"
1989 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1991 SECURITY_ATTRIBUTES saAttr
;
1999 saAttr
.nLength
= sizeof (SECURITY_ATTRIBUTES
);
2000 saAttr
.bInheritHandle
= TRUE
;
2001 saAttr
.lpSecurityDescriptor
= NULL
;
2003 if (DuplicateHandle (GetCurrentProcess(),
2004 GetStdHandle(STD_INPUT_HANDLE
),
2005 GetCurrentProcess(),
2009 DUPLICATE_SAME_ACCESS
) == FALSE
) {
2010 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
2014 if (DuplicateHandle(GetCurrentProcess(),
2015 GetStdHandle(STD_ERROR_HANDLE
),
2016 GetCurrentProcess(),
2020 DUPLICATE_SAME_ACCESS
) == FALSE
) {
2021 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
2025 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
2026 fatal (NILF
, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
2028 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
2031 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
2033 /* make sure that CreateProcess() has Path it needs */
2034 sync_Path_environment();
2036 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
)) {
2037 /* register process for wait */
2038 process_register(hProcess
);
2040 /* set the pid for returning to caller */
2041 *pid_p
= (int) hProcess
;
2043 /* set up to read data from child */
2044 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
2046 /* this will be closed almost right away */
2047 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
2049 /* reap/cleanup the failed process */
2050 process_cleanup(hProcess
);
2052 /* close handles which were duplicated, they weren't used */
2056 /* close pipe handles, they won't be used */
2057 CloseHandle(hChildOutRd
);
2058 CloseHandle(hChildOutWr
);
2060 /* set status for return */
2061 pipedes
[0] = pipedes
[1] = -1;
2070 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
2073 /* MSDOS can't fork, but it has `popen'. */
2074 struct variable
*sh
= lookup_variable ("SHELL", 5);
2076 extern int dos_command_running
, dos_status
;
2078 /* Make sure not to bother processing an empty line. */
2079 while (isblank ((unsigned char)*text
))
2086 char buf
[PATH_MAX
+ 7];
2087 /* This makes sure $SHELL value is used by $(shell), even
2088 though the target environment is not passed to it. */
2089 sprintf (buf
, "SHELL=%s", sh
->value
);
2095 dos_command_running
= 1;
2097 /* If dos_status becomes non-zero, it means the child process
2098 was interrupted by a signal, like SIGINT or SIGQUIT. See
2099 fatal_error_signal in commands.c. */
2100 fpipe
= popen (text
, "rt");
2101 dos_command_running
= 0;
2102 if (!fpipe
|| dos_status
)
2108 else if (errno
== 0)
2110 shell_function_completed
= -1;
2114 pipedes
[0] = fileno (fpipe
);
2115 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
2117 shell_function_completed
= 1;
2124 Do shell spawning, with the naughty bits for different OSes.
2129 /* VMS can't do $(shell ...) */
2130 #define func_shell 0
2135 func_shell (char *o
, char **argv
, const char *funcname UNUSED
)
2137 char *batch_filename
= NULL
;
2142 char **command_argv
;
2143 const char *error_prefix
;
2149 /* Construct the argument list. */
2150 command_argv
= construct_command_argv (argv
[0], NULL
, NULL
, 0,
2152 if (command_argv
== 0)
2156 /* Using a target environment for `shell' loses in cases like:
2157 export var = $(shell echo foobie)
2158 because target_environment hits a loop trying to expand $(var)
2159 to put it in the environment. This is even more confusing when
2160 var was not explicitly exported, but just appeared in the
2161 calling environment.
2163 See Savannah bug #10593.
2165 envp = target_environment (NILF);
2170 /* For error messages. */
2171 if (reading_file
&& reading_file
->filenm
)
2173 char *p
= alloca (strlen (reading_file
->filenm
)+11+4);
2174 sprintf (p
, "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
2180 #if defined(__MSDOS__)
2181 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
2184 perror_with_name (error_prefix
, "pipe");
2187 #elif defined(WINDOWS32)
2188 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
2191 /* open of the pipe failed, mark as failed execution */
2192 shell_function_completed
= -1;
2198 if (pipe (pipedes
) < 0)
2200 perror_with_name (error_prefix
, "pipe");
2205 /* close some handles that are unnecessary for the child process */
2206 CLOSE_ON_EXEC(pipedes
[1]);
2207 CLOSE_ON_EXEC(pipedes
[0]);
2208 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
2209 pid
= child_execute_job (0, pipedes
[1], command_argv
, envp
);
2211 perror_with_name (error_prefix
, "spawn");
2212 # else /* ! __EMX__ */
2215 perror_with_name (error_prefix
, "fork");
2217 child_execute_job (0, pipedes
[1], command_argv
, envp
);
2222 /* We are the parent. */
2224 unsigned int maxlen
, i
;
2227 /* Record the PID for reap_children. */
2228 shell_function_pid
= pid
;
2230 shell_function_completed
= 0;
2232 /* Free the storage only the child needed. */
2233 free (command_argv
[0]);
2234 free (command_argv
);
2236 /* Close the write side of the pipe. */
2237 # ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
2238 if (pipedes
[1] != -1)
2243 /* Set up and read from the pipe. */
2246 buffer
= xmalloc (maxlen
+ 1);
2248 /* Read from the pipe until it gets EOF. */
2249 for (i
= 0; ; i
+= cc
)
2254 buffer
= xrealloc (buffer
, maxlen
+ 1);
2257 EINTRLOOP (cc
, read (pipedes
[0], &buffer
[i
], maxlen
- i
));
2263 /* Close the read side of the pipe. */
2266 (void) pclose (fpipe
);
2268 # ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
2269 if (pipedes
[0] != -1)
2271 (void) close (pipedes
[0]);
2274 /* Loop until child_handler or reap_children() sets
2275 shell_function_completed to the status of our child shell. */
2276 while (shell_function_completed
== 0)
2277 reap_children (1, 0);
2279 if (batch_filename
) {
2280 DB (DB_VERBOSE
, (_("Cleaning up temporary batch file %s\n"),
2282 remove (batch_filename
);
2283 free (batch_filename
);
2285 shell_function_pid
= 0;
2287 /* The child_handler function will set shell_function_completed
2288 to 1 when the child dies normally, or to -1 if it
2289 dies with status 127, which is most likely an exec fail. */
2291 if (shell_function_completed
== -1)
2293 /* This likely means that the execvp failed, so we should just
2294 write the error message in the pipe from the child. */
2295 fputs (buffer
, stderr
);
2300 /* The child finished normally. Replace all newlines in its output
2301 with spaces, and put that in the variable output buffer. */
2302 fold_newlines (buffer
, &i
);
2303 o
= variable_buffer_output (o
, buffer
, i
);
2314 /* Do the Amiga version of func_shell. */
2317 func_shell (char *o
, char **argv
, const char *funcname
)
2319 /* Amiga can't fork nor spawn, but I can start a program with
2320 redirection of my choice. However, this means that we
2321 don't have an opportunity to reopen stdout to trap it. Thus,
2322 we save our own stdout onto a new descriptor and dup a temp
2323 file's descriptor onto our stdout temporarily. After we
2324 spawn the shell program, we dup our own stdout back to the
2325 stdout descriptor. The buffer reading is the same as above,
2326 except that we're now reading from a file. */
2328 #include <dos/dos.h>
2329 #include <proto/dos.h>
2332 char tmp_output
[FILENAME_MAX
];
2333 unsigned int maxlen
= 200, i
;
2335 char * buffer
, * ptr
;
2338 char* batch_filename
= NULL
;
2340 /* Construct the argument list. */
2341 command_argv
= construct_command_argv (argv
[0], NULL
, NULL
, 0,
2343 if (command_argv
== 0)
2346 /* Note the mktemp() is a security hole, but this only runs on Amiga.
2347 Ideally we would use main.c:open_tmpfile(), but this uses a special
2348 Open(), not fopen(), and I'm not familiar enough with the code to mess
2350 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
2351 mktemp (tmp_output
);
2352 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
2354 for (aptr
=command_argv
; *aptr
; aptr
++)
2355 len
+= strlen (*aptr
) + 1;
2357 buffer
= xmalloc (len
+ 1);
2360 for (aptr
=command_argv
; *aptr
; aptr
++)
2362 strcpy (ptr
, *aptr
);
2363 ptr
+= strlen (ptr
) + 1;
2370 Execute (buffer
, NULL
, child_stdout
);
2373 Close (child_stdout
);
2375 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
2377 buffer
= xmalloc (maxlen
);
2384 buffer
= xrealloc (buffer
, maxlen
+ 1);
2387 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
2392 Close (child_stdout
);
2394 fold_newlines (buffer
, &i
);
2395 o
= variable_buffer_output (o
, buffer
, i
);
2405 equality. Return is string-boolean, ie, the empty string is false.
2408 func_eq (char *o
, char **argv
, const char *funcname UNUSED
)
2410 int result
= ! strcmp (argv
[0], argv
[1]);
2411 o
= variable_buffer_output (o
, result
? "1" : "", result
);
2417 string-boolean not operator.
2420 func_not (char *o
, char **argv
, const char *funcname UNUSED
)
2422 const char *s
= argv
[0];
2424 while (isspace ((unsigned char)*s
))
2427 o
= variable_buffer_output (o
, result
? "1" : "", result
);
2432 #ifdef CONFIG_WITH_STRING_FUNCTIONS
2436 XXX: This doesn't take multibyte locales into account.
2439 func_length (char *o
, char **argv
, const char *funcname UNUSED
)
2441 size_t len
= strlen (argv
[0]);
2442 return math_int_to_variable_buffer (o
, len
);
2448 XXX: This doesn't take multibyte locales into account.
2451 func_length_var (char *o
, char **argv
, const char *funcname UNUSED
)
2453 struct variable
*var
= lookup_variable (argv
[0], strlen (argv
[0]));
2454 return math_int_to_variable_buffer (o
, var
? var
->value_length
: 0);
2457 /* func_insert and func_substr helper. */
2459 helper_pad (char *o
, size_t to_add
, const char *pad
, size_t pad_len
)
2463 size_t size
= to_add
> pad_len
? pad_len
: to_add
;
2464 o
= variable_buffer_output (o
, pad
, size
);
2471 $(insert in, str[, n[, length[, pad]]])
2473 XXX: This doesn't take multibyte locales into account.
2476 func_insert (char *o
, char **argv
, const char *funcname UNUSED
)
2478 const char *in
= argv
[0];
2479 size_t in_len
= strlen (in
);
2480 const char *str
= argv
[1];
2481 size_t str_len
= strlen (str
);
2483 math_int length
= str_len
;
2484 const char *pad
= " ";
2485 size_t pad_len
= 16;
2488 if (argv
[2] != NULL
)
2490 n
= math_int_from_string (argv
[2]);
2492 n
--; /* one-origin */
2494 n
= str_len
; /* append */
2496 { /* n < 0: from the end */
2501 if (n
> 16*1024*1024) /* 16MB */
2502 fatal (NILF
, _("$(insert ): n=%s is out of bounds\n"), argv
[2]);
2504 if (argv
[3] != NULL
)
2506 length
= math_int_from_string (argv
[3]);
2507 if (length
< 0 || length
> 16*1024*1024 /* 16MB */)
2508 fatal (NILF
, _("$(insert ): length=%s is out of bounds\n"), argv
[3]);
2510 if (argv
[4] != NULL
)
2512 const char *tmp
= argv
[4];
2513 for (i
= 0; tmp
[i
] == ' '; i
++)
2518 pad_len
= strlen (pad
);
2520 /* else: it was all default spaces. */
2525 /* the head of the original string */
2529 o
= variable_buffer_output (o
, str
, n
);
2532 o
= variable_buffer_output (o
, str
, str_len
);
2533 o
= helper_pad (o
, n
- str_len
, pad
, pad_len
);
2537 /* insert the string */
2538 if (length
<= in_len
)
2539 o
= variable_buffer_output (o
, in
, length
);
2542 o
= variable_buffer_output (o
, in
, in_len
);
2543 o
= helper_pad (o
, length
- in_len
, pad
, pad_len
);
2546 /* the tail of the original string */
2548 o
= variable_buffer_output (o
, str
+ n
, str_len
- n
);
2554 $(pos needle, haystack[, start])
2555 $(lastpos needle, haystack[, start])
2557 XXX: This doesn't take multibyte locales into account.
2560 func_pos (char *o
, char **argv
, const char *funcname UNUSED
)
2562 const char *needle
= *argv
[0] ? argv
[0] : " ";
2563 size_t needle_len
= strlen (needle
);
2564 const char *haystack
= argv
[1];
2565 size_t haystack_len
= strlen (haystack
);
2569 if (argv
[2] != NULL
)
2571 start
= math_int_from_string (argv
[2]);
2573 start
--; /* one-origin */
2575 start
= haystack_len
+ start
; /* from the end */
2576 if (start
< 0 || start
+ needle_len
> haystack_len
)
2577 return math_int_to_variable_buffer (o
, 0);
2579 else if (funcname
[0] == 'l')
2580 start
= haystack_len
- 1;
2582 /* do the searching */
2583 if (funcname
[0] != 'l')
2585 if (needle_len
== 1)
2586 hit
= strchr (haystack
+ start
, *needle
);
2588 hit
= strstr (haystack
+ start
, needle
);
2593 size_t off
= start
+ 1;
2598 if ( haystack
[off
] == ch
2599 && ( needle_len
== 1
2600 || strncmp (&haystack
[off
], needle
, needle_len
) == 0))
2602 hit
= haystack
+ off
;
2608 return math_int_to_variable_buffer (o
, hit
? hit
- haystack
+ 1 : 0);
2612 $(substr str, start[, length[, pad]])
2614 XXX: This doesn't take multibyte locales into account.
2617 func_substr (char *o
, char **argv
, const char *funcname UNUSED
)
2619 const char *str
= argv
[0];
2620 size_t str_len
= strlen (str
);
2621 math_int start
= math_int_from_string (argv
[1]);
2622 math_int length
= 0;
2623 const char *pad
= NULL
;
2626 if (argv
[2] != NULL
)
2628 if (argv
[3] != NULL
)
2631 for (pad_len
= 0; pad
[pad_len
] == ' '; pad_len
++)
2633 if (pad
[pad_len
] != '\0')
2634 pad_len
= strlen (pad
);
2641 length
= math_int_from_string (argv
[2]);
2642 if (length
< 0 || (pad
!= NULL
&& length
> 16*1024*1024 /* 16MB */))
2643 fatal (NILF
, _("$(substr ): length=%s is out of bounds\n"), argv
[3]);
2648 /* adjust start and length. */
2653 start
--; /* one-origin */
2654 if (start
>= str_len
)
2656 if (length
== 0 || start
+ length
> str_len
)
2657 length
= str_len
- start
;
2661 start
= str_len
+ start
;
2670 else if (length
== 0 || start
+ length
> str_len
)
2671 length
= str_len
- start
;
2674 o
= variable_buffer_output (o
, str
+ start
, length
);
2680 start
--; /* one-origin */
2681 if (start
>= str_len
)
2682 return length
? helper_pad (o
, length
, pad
, pad_len
) : o
;
2684 length
= str_len
- start
;
2688 start
= str_len
+ start
;
2691 if (start
+ length
<= 0)
2692 return length
? helper_pad (o
, length
, pad
, pad_len
) : o
;
2693 o
= helper_pad (o
, -start
, pad
, pad_len
);
2694 return variable_buffer_output (o
, str
, length
+ start
);
2697 length
= str_len
- start
;
2699 if (start
+ length
<= str_len
)
2700 o
= variable_buffer_output (o
, str
+ start
, length
);
2703 o
= variable_buffer_output (o
, str
+ start
, str_len
- start
);
2704 o
= helper_pad (o
, start
+ length
- str_len
, pad
, pad_len
);
2712 $(translate string, from-set[, to-set[, pad-char]])
2714 XXX: This doesn't take multibyte locales into account.
2717 func_translate (char *o
, char **argv
, const char *funcname UNUSED
)
2719 const unsigned char *str
= (const unsigned char *)argv
[0];
2720 const unsigned char *from_set
= (const unsigned char *)argv
[1];
2721 const char *to_set
= argv
[2] != NULL
? argv
[2] : "";
2722 char trans_tab
[1 << CHAR_BIT
];
2726 /* init the array. */
2727 for (i
= 0; i
< (1 << CHAR_BIT
); i
++)
2730 while ( (i
= *from_set
) != '\0'
2731 && (ch
= *to_set
) != '\0')
2740 ch
= '\0'; /* no padding == remove char */
2741 if (argv
[2] != NULL
&& argv
[3] != NULL
)
2744 if (ch
&& argv
[3][1])
2745 fatal (NILF
, _("$(translate ): pad=`%s' expected a single char\n"), argv
[3]);
2746 if (ch
== '\0') /* no char == space */
2749 while ((i
= *from_set
++) != '\0')
2753 /* do the translation */
2754 while ((i
= *str
++) != '\0')
2758 o
= variable_buffer_output (o
, &ch
, 1);
2763 #endif /* CONFIG_WITH_STRING_FUNCTIONS */
2765 #ifdef CONFIG_WITH_LAZY_DEPS_VARS
2767 /* This is also in file.c (bad). */
2769 # define FILE_LIST_SEPARATOR ','
2771 # define FILE_LIST_SEPARATOR ' '
2774 /* Implements $^ and $+.
2776 The first is somes with with FUNCNAME 'deps', the second as 'deps-all'.
2778 If no second argument is given, or if it's empty, or if it's zero,
2779 all dependencies will be returned. If the second argument is non-zero
2780 the dependency at that position will be returned. If the argument is
2781 negative a fatal error is thrown. */
2783 func_deps (char *o
, char **argv
, const char *funcname
)
2785 unsigned int idx
= 0;
2788 /* Handle the argument if present. */
2793 while (isspace ((unsigned int)*p
))
2798 long l
= strtol (p
, &n
, 0);
2799 while (isspace ((unsigned int)*n
))
2802 if (*n
!= '\0' || l
< 0 || (long)idx
!= l
)
2803 fatal (NILF
, _("%s: invalid index value: `%s'\n"), funcname
, p
);
2807 /* Find the file and select the list corresponding to FUNCNAME. */
2809 file
= lookup_file (argv
[0]);
2812 struct dep
*deps
= funcname
[4] != '\0' && file
->org_deps
2813 ? file
->org_deps
: file
->deps
;
2816 if ( file
->double_colon
2817 && ( file
->double_colon
!= file
2818 || file
->last
!= file
))
2819 error (NILF
, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
2820 funcname
, file
->name
);
2822 if (idx
== 0 /* all */)
2824 unsigned int total_len
= 0;
2826 /* calc the result length. */
2828 for (d
= deps
; d
; d
= d
->next
)
2829 if (!d
->ignore_mtime
)
2831 const char *c
= dep_name (d
);
2836 c
= strchr (c
, '(') + 1;
2837 total_len
+= strlen (c
);
2840 #elif defined (CONFIG_WITH_STRCACHE2)
2841 total_len
+= strcache2_get_len (&file_strcache
, c
) + 1;
2843 total_len
+= strlen (c
) + 1;
2849 /* prepare the variable buffer dude wrt to the output size and
2850 pass along the strings. */
2852 o
= variable_buffer_output (o
+ total_len
, "", 0) - total_len
; /* a hack */
2854 for (d
= deps
; d
; d
= d
->next
)
2855 if (!d
->ignore_mtime
)
2858 const char *c
= dep_name (d
);
2863 c
= strchr (c
, '(') + 1;
2867 #elif defined (CONFIG_WITH_STRCACHE2)
2868 len
= strcache2_get_len (&file_strcache
, c
) + 1;
2870 len
= strlen (c
) + 1;
2872 o
= variable_buffer_output (o
, c
, len
);
2873 o
[-1] = FILE_LIST_SEPARATOR
;
2876 --o
; /* nuke the last list separator */
2882 /* Dependency given by index. */
2884 for (d
= deps
; d
; d
= d
->next
)
2885 if (!d
->ignore_mtime
)
2887 if (--idx
== 0) /* 1 based indexing */
2890 const char *c
= dep_name (d
);
2895 c
= strchr (c
, '(') + 1;
2896 len
= strlen (c
) - 1;
2899 #elif defined (CONFIG_WITH_STRCACHE2)
2900 len
= strcache2_get_len (&file_strcache
, c
);
2904 o
= variable_buffer_output (o
, c
, len
);
2916 If no second argument is given, or if it's empty, or if it's zero,
2917 all dependencies will be returned. If the second argument is non-zero
2918 the dependency at that position will be returned. If the argument is
2919 negative a fatal error is thrown. */
2921 func_deps_newer (char *o
, char **argv
, const char *funcname
)
2923 unsigned int idx
= 0;
2926 /* Handle the argument if present. */
2931 while (isspace ((unsigned int)*p
))
2936 long l
= strtol (p
, &n
, 0);
2937 while (isspace ((unsigned int)*n
))
2940 if (*n
!= '\0' || l
< 0 || (long)idx
!= l
)
2941 fatal (NILF
, _("%s: invalid index value: `%s'\n"), funcname
, p
);
2945 /* Find the file. */
2947 file
= lookup_file (argv
[0]);
2950 struct dep
*deps
= file
->deps
;
2953 if ( file
->double_colon
2954 && ( file
->double_colon
!= file
2955 || file
->last
!= file
))
2956 error (NILF
, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
2957 funcname
, file
->name
);
2959 if (idx
== 0 /* all */)
2961 unsigned int total_len
= 0;
2963 /* calc the result length. */
2965 for (d
= deps
; d
; d
= d
->next
)
2966 if (!d
->ignore_mtime
&& d
->changed
)
2968 const char *c
= dep_name (d
);
2973 c
= strchr (c
, '(') + 1;
2974 total_len
+= strlen (c
);
2977 #elif defined (CONFIG_WITH_STRCACHE2)
2978 total_len
+= strcache2_get_len (&file_strcache
, c
) + 1;
2980 total_len
+= strlen (c
) + 1;
2986 /* prepare the variable buffer dude wrt to the output size and
2987 pass along the strings. */
2989 o
= variable_buffer_output (o
+ total_len
, "", 0) - total_len
; /* a hack */
2991 for (d
= deps
; d
; d
= d
->next
)
2992 if (!d
->ignore_mtime
&& d
->changed
)
2995 const char *c
= dep_name (d
);
3000 c
= strchr (c
, '(') + 1;
3004 #elif defined (CONFIG_WITH_STRCACHE2)
3005 len
= strcache2_get_len (&file_strcache
, c
) + 1;
3007 len
= strlen (c
) + 1;
3009 o
= variable_buffer_output (o
, c
, len
);
3010 o
[-1] = FILE_LIST_SEPARATOR
;
3013 --o
; /* nuke the last list separator */
3019 /* Dependency given by index. */
3021 for (d
= deps
; d
; d
= d
->next
)
3022 if (!d
->ignore_mtime
&& d
->changed
)
3024 if (--idx
== 0) /* 1 based indexing */
3027 const char *c
= dep_name (d
);
3032 c
= strchr (c
, '(') + 1;
3033 len
= strlen (c
) - 1;
3036 #elif defined (CONFIG_WITH_STRCACHE2)
3037 len
= strcache2_get_len (&file_strcache
, c
);
3041 o
= variable_buffer_output (o
, c
, len
);
3051 /* Implements $|, the order only dependency list.
3053 If no second argument is given, or if it's empty, or if it's zero,
3054 all dependencies will be returned. If the second argument is non-zero
3055 the dependency at that position will be returned. If the argument is
3056 negative a fatal error is thrown. */
3058 func_deps_order_only (char *o
, char **argv
, const char *funcname
)
3060 unsigned int idx
= 0;
3063 /* Handle the argument if present. */
3068 while (isspace ((unsigned int)*p
))
3073 long l
= strtol (p
, &n
, 0);
3074 while (isspace ((unsigned int)*n
))
3077 if (*n
!= '\0' || l
< 0 || (long)idx
!= l
)
3078 fatal (NILF
, _("%s: invalid index value: `%s'\n"), funcname
, p
);
3082 /* Find the file. */
3084 file
= lookup_file (argv
[0]);
3087 struct dep
*deps
= file
->deps
;
3090 if ( file
->double_colon
3091 && ( file
->double_colon
!= file
3092 || file
->last
!= file
))
3093 error (NILF
, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3094 funcname
, file
->name
);
3096 if (idx
== 0 /* all */)
3098 unsigned int total_len
= 0;
3100 /* calc the result length. */
3102 for (d
= deps
; d
; d
= d
->next
)
3103 if (d
->ignore_mtime
)
3105 const char *c
= dep_name (d
);
3110 c
= strchr (c
, '(') + 1;
3111 total_len
+= strlen (c
);
3114 #elif defined (CONFIG_WITH_STRCACHE2)
3115 total_len
+= strcache2_get_len (&file_strcache
, c
) + 1;
3117 total_len
+= strlen (c
) + 1;
3123 /* prepare the variable buffer dude wrt to the output size and
3124 pass along the strings. */
3126 o
= variable_buffer_output (o
+ total_len
, "", 0) - total_len
; /* a hack */
3128 for (d
= deps
; d
; d
= d
->next
)
3129 if (d
->ignore_mtime
)
3132 const char *c
= dep_name (d
);
3137 c
= strchr (c
, '(') + 1;
3141 #elif defined (CONFIG_WITH_STRCACHE2)
3142 len
= strcache2_get_len (&file_strcache
, c
) + 1;
3144 len
= strlen (c
) + 1;
3146 o
= variable_buffer_output (o
, c
, len
);
3147 o
[-1] = FILE_LIST_SEPARATOR
;
3150 --o
; /* nuke the last list separator */
3156 /* Dependency given by index. */
3158 for (d
= deps
; d
; d
= d
->next
)
3159 if (d
->ignore_mtime
)
3161 if (--idx
== 0) /* 1 based indexing */
3164 const char *c
= dep_name (d
);
3169 c
= strchr (c
, '(') + 1;
3170 len
= strlen (c
) - 1;
3173 #elif defined (CONFIG_WITH_STRCACHE2)
3174 len
= strcache2_get_len (&file_strcache
, c
);
3178 o
= variable_buffer_output (o
, c
, len
);
3187 #endif /* CONFIG_WITH_LAZY_DEPS_VARS */
3190 #ifdef CONFIG_WITH_DEFINED
3191 /* Similar to ifdef. */
3193 func_defined (char *o
, char **argv
, const char *funcname UNUSED
)
3195 struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
3196 int result
= v
!= NULL
&& *v
->value
!= '\0';
3197 o
= variable_buffer_output (o
, result
? "1" : "", result
);
3200 #endif /* CONFIG_WITH_DEFINED*/
3203 /* Return the absolute name of file NAME which does not contain any `.',
3204 `..' components nor any repeated path separators ('/'). */
3210 abspath (const char *name
, char *apath
)
3213 const char *start
, *end
, *apath_limit
;
3215 if (name
[0] == '\0' || apath
== NULL
)
3218 #ifdef WINDOWS32 /* bird */
3219 dest
= w32ify((char *)name
, 1);
3223 size_t len
= strlen(dest
);
3224 memcpy(apath
, dest
, len
);
3228 (void)end
; (void)start
; (void)apath_limit
;
3230 #elif defined __OS2__ /* bird */
3231 if (_abspath(apath
, name
, GET_PATH_MAX
))
3233 dest
= strchr(apath
, '\0');
3235 (void)end
; (void)start
; (void)apath_limit
; (void)dest
;
3237 #else /* !WINDOWS32 && !__OS2__ */
3238 apath_limit
= apath
+ GET_PATH_MAX
;
3240 #ifdef HAVE_DOS_PATHS /* bird added this */
3241 if (isalpha(name
[0]) && name
[1] == ':')
3244 apath
[0] = toupper(name
[0]);
3250 #endif /* HAVE_DOS_PATHS */
3253 /* It is unlikely we would make it until here but just to make sure. */
3254 if (!starting_directory
)
3257 strcpy (apath
, starting_directory
);
3259 dest
= strchr (apath
, '\0');
3267 for (start
= end
= name
; *start
!= '\0'; start
= end
)
3271 /* Skip sequence of multiple path-separators. */
3272 while (*start
== '/')
3275 /* Find end of path component. */
3276 for (end
= start
; *end
!= '\0' && *end
!= '/'; ++end
)
3283 else if (len
== 1 && start
[0] == '.')
3285 else if (len
== 2 && start
[0] == '.' && start
[1] == '.')
3287 /* Back up to previous component, ignore if at root already. */
3288 if (dest
> apath
+ 1)
3289 while ((--dest
)[-1] != '/');
3293 if (dest
[-1] != '/')
3296 if (dest
+ len
>= apath_limit
)
3299 dest
= memcpy (dest
, start
, len
);
3304 #endif /* !WINDOWS32 && !__OS2__ */
3306 /* Unless it is root strip trailing separator. */
3307 #ifdef HAVE_DOS_PATHS /* bird (is this correct? what about UNC?) */
3308 if (dest
> apath
+ 1 + (apath
[0] != '/') && dest
[-1] == '/')
3310 if (dest
> apath
+ 1 && dest
[-1] == '/')
3321 func_realpath (char *o
, char **argv
, const char *funcname UNUSED
)
3323 /* Expand the argument. */
3324 const char *p
= argv
[0];
3325 const char *path
= 0;
3327 unsigned int len
= 0;
3331 while ((path
= find_next_token (&p
, &len
)) != 0)
3333 if (len
< GET_PATH_MAX
)
3335 strncpy (in
, path
, len
);
3339 #ifdef HAVE_REALPATH
3346 o
= variable_buffer_output (o
, out
, strlen (out
));
3347 o
= variable_buffer_output (o
, " ", 1);
3353 /* Kill last space. */
3361 func_abspath (char *o
, char **argv
, const char *funcname UNUSED
)
3363 /* Expand the argument. */
3364 const char *p
= argv
[0];
3365 const char *path
= 0;
3367 unsigned int len
= 0;
3371 while ((path
= find_next_token (&p
, &len
)) != 0)
3373 if (len
< GET_PATH_MAX
)
3375 strncpy (in
, path
, len
);
3378 if (abspath (in
, out
))
3380 o
= variable_buffer_output (o
, out
, strlen (out
));
3381 o
= variable_buffer_output (o
, " ", 1);
3387 /* Kill last space. */
3394 #ifdef CONFIG_WITH_ABSPATHEX
3395 /* Same as abspath except that the current path may be given as the
3398 func_abspathex (char *o
, char **argv
, const char *funcname UNUSED
)
3400 char *cwd
= argv
[1];
3402 /* cwd needs leading spaces chopped and may be optional,
3403 in which case we're exactly like $(abspath ). */
3404 while (isblank(*cwd
))
3407 o
= func_abspath (o
, argv
, funcname
);
3410 /* Expand the argument. */
3411 const char *p
= argv
[0];
3412 unsigned int cwd_len
= ~0U;
3415 unsigned int len
= 0;
3419 while ((path
= find_next_token (&p
, &len
)) != 0)
3421 if (len
< GET_PATH_MAX
)
3423 #ifdef HAVE_DOS_PATHS
3424 if (path
[0] != '/' && path
[0] != '\\' && (len
< 2 || path
[1] != ':') && cwd
)
3426 if (path
[0] != '/' && cwd
)
3429 /* relative path, prefix with cwd. */
3431 cwd_len
= strlen (cwd
);
3432 if (cwd_len
+ len
+ 1 >= GET_PATH_MAX
)
3434 memcpy (in
, cwd
, cwd_len
);
3436 memcpy (in
+ cwd_len
+ 1, path
, len
);
3437 in
[cwd_len
+ len
+ 1] = '\0';
3441 /* absolute path pass it as-is. */
3442 memcpy (in
, path
, len
);
3446 if (abspath (in
, out
))
3448 o
= variable_buffer_output (o
, out
, strlen (out
));
3449 o
= variable_buffer_output (o
, " ", 1);
3455 /* Kill last space. */
3464 #ifdef CONFIG_WITH_XARGS
3465 /* Create one or more command lines avoiding the max argument
3466 length restriction of the host OS.
3468 The last argument is the list of arguments that the normal
3469 xargs command would be fed from stdin.
3471 The first argument is initial command and it's arguments.
3473 If there are three or more arguments, the 2nd argument is
3474 the command and arguments to be used on subsequent
3475 command lines. Defaults to the initial command.
3477 If there are four or more arguments, the 3rd argument is
3478 the command to be used at the final command line. Defaults
3479 to the sub sequent or initial command .
3481 A future version of this function may define more arguments
3482 and therefor anyone specifying six or more arguments will
3486 $(xargs ar cas mylib.a,$(objects))
3488 $(xargs ar cas mylib.a,ar as mylib.a,$(objects))
3490 It will then create one or more "ar mylib.a ..." command
3491 lines with proper \n\t separation so it can be used when
3494 func_xargs (char *o
, char **argv
, const char *funcname UNUSED
)
3497 const char *initial_cmd
;
3498 size_t initial_cmd_len
;
3499 const char *subsequent_cmd
;
3500 size_t subsequent_cmd_len
;
3501 const char *final_cmd
;
3502 size_t final_cmd_len
;
3508 /* ARG_MAX is a bit unreliable (environment), so drop 25% of the max. */
3509 # define XARGS_MAX (ARG_MAX - (ARG_MAX / 4))
3510 #else /* FIXME: update configure with a command line length test. */
3511 # define XARGS_MAX 10240
3518 fatal (NILF
, _("Too many arguments for $(xargs)!\n"));
3520 /* first: the initial / default command.*/
3521 initial_cmd
= argv
[0];
3522 while (isspace ((unsigned char)*initial_cmd
))
3524 max_args
= initial_cmd_len
= strlen (initial_cmd
);
3526 /* second: the command for the subsequent command lines. defaults to the initial cmd. */
3527 subsequent_cmd
= argc
> 2 && argv
[1][0] != '\0' ? argv
[1] : "";
3528 while (isspace ((unsigned char)*subsequent_cmd
))
3530 if (*subsequent_cmd
)
3532 subsequent_cmd_len
= strlen (subsequent_cmd
);
3533 if (subsequent_cmd_len
> max_args
)
3534 max_args
= subsequent_cmd_len
;
3538 subsequent_cmd
= initial_cmd
;
3539 subsequent_cmd_len
= initial_cmd_len
;
3542 /* third: the final command. defaults to the subseq cmd. */
3543 final_cmd
= argc
> 3 && argv
[2][0] != '\0' ? argv
[2] : "";
3544 while (isspace ((unsigned char)*final_cmd
))
3548 final_cmd_len
= strlen (final_cmd
);
3549 if (final_cmd_len
> max_args
)
3550 max_args
= final_cmd_len
;
3554 final_cmd
= subsequent_cmd
;
3555 final_cmd_len
= subsequent_cmd_len
;
3558 /* last: the arguments to split up into sensible portions. */
3559 args
= argv
[argc
- 1];
3561 /* calc the max argument length. */
3562 if (XARGS_MAX
<= max_args
+ 2)
3563 fatal (NILF
, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
3564 (unsigned long)XARGS_MAX
, (unsigned long)max_args
+ 2);
3565 max_args
= XARGS_MAX
- max_args
- 1;
3567 /* generate the commands. */
3572 const char *iterator
= args
;
3573 const char *end
= args
;
3577 /* scan the arguments till we reach the end or the max length. */
3578 while ((cur
= find_next_token(&iterator
, &len
))
3579 && (size_t)((cur
+ len
) - args
) < max_args
)
3581 if (cur
&& end
== args
)
3582 fatal (NILF
, _("$(xargs): command + one single arg is too much. giving up.\n"));
3584 /* emit the command. */
3587 o
= variable_buffer_output (o
, (char *)initial_cmd
, initial_cmd_len
);
3588 o
= variable_buffer_output (o
, " ", 1);
3592 o
= variable_buffer_output (o
, "\n\t", 2);
3593 o
= variable_buffer_output (o
, (char *)subsequent_cmd
, subsequent_cmd_len
);
3594 o
= variable_buffer_output (o
, " ", 1);
3598 o
= variable_buffer_output (o
, "\n\t", 2);
3599 o
= variable_buffer_output (o
, (char *)final_cmd
, final_cmd_len
);
3600 o
= variable_buffer_output (o
, " ", 1);
3604 while (tmp
> args
&& isspace ((unsigned char)tmp
[-1])) /* drop trailing spaces. */
3606 o
= variable_buffer_output (o
, (char *)args
, tmp
- args
);
3613 while (isspace ((unsigned char)*args
))
3621 #ifdef CONFIG_WITH_TOUPPER_TOLOWER
3623 func_toupper_tolower (char *o
, char **argv
, const char *funcname
)
3625 /* Expand the argument. */
3626 const char *p
= argv
[0];
3629 /* convert to temporary buffer */
3632 if (!strcmp(funcname
, "toupper"))
3633 for (i
= 0; i
< sizeof(tmp
) && *p
; i
++, p
++)
3634 tmp
[i
] = toupper(*p
);
3636 for (i
= 0; i
< sizeof(tmp
) && *p
; i
++, p
++)
3637 tmp
[i
] = tolower(*p
);
3638 o
= variable_buffer_output (o
, tmp
, i
);
3643 #endif /* CONFIG_WITH_TOUPPER_TOLOWER */
3645 #if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
3647 /* Strip leading spaces and other things off a command. */
3649 comp_cmds_strip_leading (const char *s
, const char *e
)
3656 #ifdef CONFIG_WITH_COMMANDS_FUNC
3667 /* Worker for func_comp_vars() which is called if the comparision failed.
3668 It will do the slow command by command comparision of the commands
3669 when there invoked as comp-cmds. */
3671 comp_vars_ne (char *o
, const char *s1
, const char *e1
, const char *s2
, const char *e2
,
3672 char *ne_retval
, const char *funcname
)
3674 /* give up at once if not comp-cmds or comp-cmds-ex. */
3675 if (strcmp (funcname
, "comp-cmds") != 0
3676 && strcmp (funcname
, "comp-cmds-ex") != 0)
3677 o
= variable_buffer_output (o
, ne_retval
, strlen (ne_retval
));
3680 const char * const s1_start
= s1
;
3685 /* if it's a new command, strip leading stuff. */
3688 s1
= comp_cmds_strip_leading (s1
, e1
);
3689 s2
= comp_cmds_strip_leading (s2
, e2
);
3692 if (s1
>= e1
|| s2
>= e2
)
3696 * Inner compare loop which compares one line.
3697 * FIXME: parse quoting!
3701 const char ch1
= *s1
;
3702 const char ch2
= *s2
;
3708 assert (ch1
!= '\r');
3713 if (s1
>= e1
|| s2
>= e2
)
3718 * If we exited because of a difference try to end-of-command
3719 * comparision, e.g. ignore trailing spaces.
3724 while (s1
< e1
&& isblank (*s1
))
3726 while (s2
< e2
&& isblank (*s2
))
3728 if (s1
>= e1
|| s2
>= e2
)
3731 /* compare again and check that it's a newline. */
3732 if (*s2
!= '\n' || *s1
!= '\n')
3735 /* Break out if we exited because of EOS. */
3736 else if (s1
>= e1
|| s2
>= e2
)
3740 * Detect the end of command lines.
3743 new_cmd
= s1
== s1_start
|| s1
[-1] != '\\';
3749 * Ignore trailing empty lines.
3751 if (s1
< e1
|| s2
< e2
)
3753 while (s1
< e1
&& (isblank (*s1
) || *s1
== '\n'))
3755 s1
= comp_cmds_strip_leading (s1
, e1
);
3756 while (s2
< e2
&& (isblank (*s2
) || *s2
== '\n'))
3758 s2
= comp_cmds_strip_leading (s2
, e2
);
3761 /* emit the result. */
3762 if (s1
== e1
&& s2
== e2
)
3763 o
= variable_buffer_output (o
, "", 1) - 1; /** @todo check why this was necessary back the... */
3765 o
= variable_buffer_output (o
, ne_retval
, strlen (ne_retval
));
3771 $(comp-vars var1,var2,not-equal-return)
3773 $(comp-cmds cmd-var1,cmd-var2,not-equal-return)
3775 Compares the two variables (that's given by name to avoid unnecessary
3776 expanding) and return the string in the third argument if not equal.
3777 If equal, nothing is returned.
3779 comp-vars will to an exact comparision only stripping leading and
3782 comp-cmds will compare command by command, ignoring not only leading
3783 and trailing spaces on each line but also leading one leading '@',
3787 func_comp_vars (char *o
, char **argv
, const char *funcname
)
3789 const char *s1
, *e1
, *x1
, *s2
, *e2
, *x2
;
3790 char *a1
= NULL
, *a2
= NULL
;
3792 struct variable
*var1
= lookup_variable (argv
[0], strlen (argv
[0]));
3793 struct variable
*var2
= lookup_variable (argv
[1], strlen (argv
[1]));
3795 /* the simple cases */
3797 return variable_buffer_output (o
, "", 0); /* eq */
3799 return variable_buffer_output (o
, argv
[2], strlen(argv
[2]));
3800 if (var1
->value
== var2
->value
)
3801 return variable_buffer_output (o
, "", 0); /* eq */
3802 if (!var1
->recursive
&& !var2
->recursive
)
3804 if ( var1
->value_length
== var2
->value_length
3805 && !memcmp (var1
->value
, var2
->value
, var1
->value_length
))
3806 return variable_buffer_output (o
, "", 0); /* eq */
3808 /* ignore trailing and leading blanks */
3810 e1
= s1
+ var1
->value_length
;
3811 while (isblank ((unsigned char) *s1
))
3813 while (e1
> s1
&& isblank ((unsigned char) e1
[-1]))
3817 e2
= s2
+ var2
->value_length
;
3818 while (isblank ((unsigned char) *s2
))
3820 while (e2
> s2
&& isblank ((unsigned char) e2
[-1]))
3823 if (e1
- s1
!= e2
- s2
)
3824 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3825 if (!memcmp (s1
, s2
, e1
- s1
))
3826 return variable_buffer_output (o
, "", 0); /* eq */
3827 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3830 /* ignore trailing and leading blanks */
3832 e1
= s1
+ var1
->value_length
;
3833 while (isblank ((unsigned char) *s1
))
3835 while (e1
> s1
&& isblank ((unsigned char) e1
[-1]))
3839 e2
= s2
+ var2
->value_length
;
3840 while (isblank((unsigned char)*s2
))
3842 while (e2
> s2
&& isblank ((unsigned char) e2
[-1]))
3845 /* both empty after stripping? */
3846 if (s1
== e1
&& s2
== e2
)
3847 return variable_buffer_output (o
, "", 0); /* eq */
3850 if ( e1
- s1
== e2
- s2
3851 && !memcmp(s1
, s2
, e1
- s1
))
3852 return variable_buffer_output (o
, "", 0); /* eq */
3854 /* compare up to the first '$' or the end. */
3855 x1
= var1
->recursive
? memchr (s1
, '$', e1
- s1
) : NULL
;
3856 x2
= var2
->recursive
? memchr (s2
, '$', e2
- s2
) : NULL
;
3858 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3860 l1
= x1
? x1
- s1
: e1
- s1
;
3861 l2
= x2
? x2
- s2
: e2
- s2
;
3862 l
= l1
<= l2
? l1
: l2
;
3863 if (l
&& memcmp (s1
, s2
, l
))
3864 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3866 /* one or both buffers now require expanding. */
3871 s1
= a1
= allocated_variable_expand ((char *)s1
+ l
);
3873 while (isblank ((unsigned char) *s1
))
3875 e1
= strchr (s1
, '\0');
3876 while (e1
> s1
&& isblank ((unsigned char) e1
[-1]))
3884 s2
= a2
= allocated_variable_expand ((char *)s2
+ l
);
3886 while (isblank ((unsigned char) *s2
))
3888 e2
= strchr (s2
, '\0');
3889 while (e2
> s2
&& isblank ((unsigned char) e2
[-1]))
3893 /* the final compare */
3894 if ( e1
- s1
!= e2
- s2
3895 || memcmp (s1
, s2
, e1
- s1
))
3896 o
= comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3898 o
= variable_buffer_output (o
, "", 1) - 1; /* eq */ /** @todo check why this was necessary back the... */
3907 $(comp-cmds-ex cmds1,cmds2,not-equal-return)
3909 Compares the two strings and return the string in the third argument
3910 if not equal. If equal, nothing is returned.
3912 The comparision will be performed command by command, ignoring not
3913 only leading and trailing spaces on each line but also leading one
3914 leading '@', '-', '+' and '%'.
3917 func_comp_cmds_ex (char *o
, char **argv
, const char *funcname
)
3919 const char *s1
, *e1
, *s2
, *e2
;
3922 /* the simple cases */
3926 return variable_buffer_output (o
, "", 0); /* eq */
3927 l1
= strlen (argv
[0]);
3928 l2
= strlen (argv
[1]);
3931 && !memcmp (s1
, s2
, l1
))
3932 return variable_buffer_output (o
, "", 0); /* eq */
3934 /* ignore trailing and leading blanks */
3936 s1
= comp_cmds_strip_leading (s1
, e1
);
3939 s2
= comp_cmds_strip_leading (s2
, e2
);
3941 if (e1
- s1
!= e2
- s2
)
3942 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3943 if (!memcmp (s1
, s2
, e1
- s1
))
3944 return variable_buffer_output (o
, "", 0); /* eq */
3945 return comp_vars_ne (o
, s1
, e1
, s2
, e2
, argv
[2], funcname
);
3949 #ifdef CONFIG_WITH_DATE
3950 # if defined (_MSC_VER) /* FIXME: !defined (HAVE_STRPTIME) */
3951 char *strptime(const char *s
, const char *format
, struct tm
*tm
)
3953 return (char *)"strptime is not implemented";
3956 /* Check if the string is all blanks or not. */
3958 all_blanks (const char *s
)
3962 while (isspace ((unsigned char)*s
))
3967 /* The first argument is the strftime format string, a iso
3968 timestamp is the default if nothing is given.
3970 The second argument is a time value if given. The format
3971 is either the format from the first argument or given as
3972 an additional third argument. */
3974 func_date (char *o
, char **argv
, const char *funcname
)
3982 /* determin the format - use a single word as the default. */
3983 format
= !strcmp (funcname
, "date-utc")
3984 ? "%Y-%m-%dT%H:%M:%SZ"
3985 : "%Y-%m-%dT%H:%M:%S";
3986 if (!all_blanks (argv
[0]))
3990 memset (&t
, 0, sizeof(t
));
3991 if (argv
[0] && !all_blanks (argv
[1]))
3993 const char *input_format
= !all_blanks (argv
[2]) ? argv
[2] : format
;
3994 p
= strptime (argv
[1], input_format
, &t
);
3995 if (!p
|| *p
!= '\0')
3997 error (NILF
, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname
,
3998 argv
[1], input_format
, p
? p
: "<null>");
3999 return variable_buffer_output (o
, "", 0);
4006 if (!strcmp (funcname
, "date-utc"))
4007 t
= *gmtime (&tval
);
4009 t
= *localtime (&tval
);
4012 /* format it. note that zero isn't necessarily an error, so we'll
4013 have to keep shut about failures. */
4015 buf
= xmalloc (buf_size
);
4016 while (strftime (buf
, buf_size
, format
, &t
) == 0)
4018 if (buf_size
>= 4096)
4023 buf
= xrealloc (buf
, buf_size
<<= 1);
4025 o
= variable_buffer_output (o
, buf
, strlen (buf
));
4031 #ifdef CONFIG_WITH_FILE_SIZE
4032 /* Prints the size of the specified file. Only one file is
4033 permitted, notthing is stripped. -1 is returned if stat
4036 func_file_size (char *o
, char **argv
, const char *funcname UNUSED
)
4039 if (stat (argv
[0], &st
))
4040 return variable_buffer_output (o
, "-1", 2);
4041 return math_int_to_variable_buffer (o
, st
.st_size
);
4045 #ifdef CONFIG_WITH_WHICH
4046 /* Checks if the specified file exists an is executable.
4047 On systems employing executable extensions, the name may
4048 be modified to include the extension. */
4049 static int func_which_test_x (char *file
)
4052 # if defined(WINDOWS32) || defined(__OS2__)
4056 /* fix slashes first. */
4058 while ((slash
= strchr (slash
, '\\')) != NULL
)
4062 if (stat (file
, &st
) == 0
4063 && S_ISREG (st
.st_mode
))
4066 /* don't try add an extension if there already is one */
4067 ext
= strchr (file
, '\0');
4069 && ( !stricmp (ext
- 4, ".exe")
4070 || !stricmp (ext
- 4, ".cmd")
4071 || !stricmp (ext
- 4, ".bat")
4072 || !stricmp (ext
- 4, ".com")))
4075 /* try the extensions. */
4076 strcpy (ext
, ".exe");
4077 if (stat (file
, &st
) == 0
4078 && S_ISREG (st
.st_mode
))
4081 strcpy (ext
, ".cmd");
4082 if (stat (file
, &st
) == 0
4083 && S_ISREG (st
.st_mode
))
4086 strcpy (ext
, ".bat");
4087 if (stat (file
, &st
) == 0
4088 && S_ISREG (st
.st_mode
))
4091 strcpy (ext
, ".com");
4092 if (stat (file
, &st
) == 0
4093 && S_ISREG (st
.st_mode
))
4100 return access (file
, X_OK
) == 0
4101 && stat (file
, &st
) == 0
4102 && S_ISREG (st
.st_mode
);
4106 /* Searches for the specified programs in the PATH and print
4107 their full location if found. Prints nothing if not found. */
4109 func_which (char *o
, char **argv
, const char *funcname UNUSED
)
4112 struct variable
*path_var
;
4117 path_var
= lookup_variable ("PATH", 4);
4119 path
= path_var
->value
;
4124 for (i
= 0; argv
[i
]; i
++)
4127 const char *iterator
= argv
[i
];
4130 while ((cur
= find_next_token (&iterator
, &len
)))
4132 /* if there is a separator, don't walk the path. */
4133 if (memchr (cur
, '/', len
)
4134 #ifdef HAVE_DOS_PATHS
4135 || memchr (cur
, '\\', len
)
4136 || memchr (cur
, ':', len
)
4140 if (len
+ 1 + 4 < GET_PATH_MAX
) /* +4 for .exe */
4142 memcpy (buf
, cur
, len
);
4144 if (func_which_test_x (buf
))
4145 o
= variable_buffer_output (o
, buf
, strlen (buf
));
4150 const char *comp
= path
;
4153 const char *src
= comp
;
4154 const char *end
= strchr (comp
, PATH_SEPARATOR_CHAR
);
4155 size_t comp_len
= end
? (size_t)(end
- comp
) : strlen (comp
);
4161 if (len
+ comp_len
+ 2 + 4 < GET_PATH_MAX
) /* +4 for .exe */
4163 memcpy (buf
, comp
, comp_len
);
4164 buf
[comp_len
] = '/';
4165 memcpy (&buf
[comp_len
+ 1], cur
, len
);
4166 buf
[comp_len
+ 1 + len
] = '\0';
4168 if (func_which_test_x (buf
))
4171 o
= variable_buffer_output (o
, " ", 1);
4172 o
= variable_buffer_output (o
, buf
, strlen (buf
));
4187 return variable_buffer_output (o
, "", 0);
4189 #endif /* CONFIG_WITH_WHICH */
4191 #ifdef CONFIG_WITH_IF_CONDITIONALS
4193 /* Evaluates the expression given in the argument using the
4194 same evaluator as for the new 'if' statements, except now
4195 we don't force the result into a boolean like for 'if' and
4198 func_expr (char *o
, char **argv
, const char *funcname UNUSED
)
4200 o
= expr_eval_to_string (o
, argv
[0]);
4204 /* Same as '$(if ,,)' except the first argument is evaluated
4205 using the same evaluator as for the new 'if' statements. */
4207 func_if_expr (char *o
, char **argv
, const char *funcname UNUSED
)
4212 /* Evaluate the condition in argv[0] and expand the 2nd or
4213 3rd argument according to the result. */
4214 rc
= expr_eval_if_conditionals (argv
[0], NULL
);
4215 to_expand
= rc
== 0 ? argv
[1] : argv
[2];
4217 variable_expand_string_2 (o
, to_expand
, -1, &o
);
4223 $(select when1-cond, when1-body[,whenN-cond, whenN-body]).
4226 func_select (char *o
, char **argv
, const char *funcname UNUSED
)
4230 /* Test WHEN-CONDs until one matches. The check for 'otherwise[:]'
4231 and 'default[:]' make this a bit more fun... */
4233 for (i
= 0; argv
[i
] != NULL
; i
+= 2)
4235 const char *cond
= argv
[i
];
4236 int is_otherwise
= 0;
4238 if (argv
[i
+ 1] == NULL
)
4239 fatal (NILF
, _("$(select ): not an even argument count\n"));
4241 while (isspace ((unsigned char)*cond
))
4243 if ( (*cond
== 'o' && strncmp (cond
, "otherwise", 9) == 0)
4244 || (*cond
== 'd' && strncmp (cond
, "default", 7) == 0))
4246 const char *end
= cond
+ (*cond
== 'o' ? 9 : 7);
4247 while (isspace ((unsigned char)*end
))
4251 while (isspace ((unsigned char)*end
));
4252 is_otherwise
= *end
== '\0';
4256 || expr_eval_if_conditionals (cond
, NULL
) == 0 /* true */)
4258 variable_expand_string_2 (o
, argv
[i
+ 1], -1, &o
);
4266 #endif /* CONFIG_WITH_IF_CONDITIONALS */
4268 #ifdef CONFIG_WITH_SET_CONDITIONALS
4270 func_set_intersects (char *o
, char **argv
, const char *funcname UNUSED
)
4273 unsigned int s1_len
;
4274 const char *s1_iterator
= argv
[0];
4276 while ((s1_cur
= find_next_token (&s1_iterator
, &s1_len
)) != 0)
4279 unsigned int s2_len
;
4280 const char *s2_iterator
= argv
[1];
4281 while ((s2_cur
= find_next_token (&s2_iterator
, &s2_len
)) != 0)
4282 if (s2_len
== s1_len
4283 && strneq (s2_cur
, s1_cur
, s1_len
) )
4284 return variable_buffer_output (o
, "1", 1); /* found intersection */
4287 return o
; /* no intersection */
4289 #endif /* CONFIG_WITH_SET_CONDITIONALS */
4291 #ifdef CONFIG_WITH_STACK
4293 /* Push an item (string without spaces). */
4295 func_stack_push (char *o
, char **argv
, const char *funcname UNUSED
)
4297 do_variable_definition(NILF
, argv
[0], argv
[1], o_file
, f_append
, 0 /* !target_var */);
4301 /* Pops an item off the stack / get the top stack element.
4302 (This is what's tricky to do in pure GNU make syntax.) */
4304 func_stack_pop_top (char *o
, char **argv
, const char *funcname
)
4306 struct variable
*stack_var
;
4307 const char *stack
= argv
[0];
4309 stack_var
= lookup_variable (stack
, strlen (stack
) );
4313 const char *iterator
= stack_var
->value
;
4314 char *lastitem
= NULL
;
4317 while ((cur
= find_next_token (&iterator
, &len
)))
4320 if (lastitem
!= NULL
)
4322 if (strcmp (funcname
, "stack-popv") != 0)
4323 o
= variable_buffer_output (o
, lastitem
, len
);
4324 if (strcmp (funcname
, "stack-top") != 0)
4327 while (lastitem
> stack_var
->value
&& isspace (lastitem
[-1]))
4329 #ifdef CONFIG_WITH_VALUE_LENGTH
4330 stack_var
->value_length
= lastitem
- stack_var
->value
;
4337 #endif /* CONFIG_WITH_STACK */
4339 #if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE)
4340 /* outputs the number (as a string) into the variable buffer. */
4342 math_int_to_variable_buffer (char *o
, math_int num
)
4344 static const char xdigits
[17] = "0123456789abcdef";
4346 char strbuf
[24]; /* 16 hex + 2 prefix + sign + term => 20
4347 or 20 dec + sign + term => 22 */
4348 char *str
= &strbuf
[sizeof (strbuf
) - 1];
4358 #ifdef HEX_MATH_NUMBERS
4359 *--str
= xdigits
[num
& 0xf];
4362 *--str
= xdigits
[num
% 10];
4368 #ifdef HEX_MATH_NUMBERS
4376 return variable_buffer_output (o
, str
, &strbuf
[sizeof (strbuf
) - 1] - str
);
4378 #endif /* CONFIG_WITH_MATH || CONFIG_WITH_NANOTS */
4380 #ifdef CONFIG_WITH_MATH
4382 /* Converts a string to an integer, causes an error if the format is invalid. */
4384 math_int_from_string (const char *str
)
4392 while (isspace (*str
))
4396 error (NILF
, _("bad number: empty\n"));
4402 while (*str
== '+' || *str
== '-' || isspace (*str
))
4404 negative
= !negative
;
4406 /* check for prefix - we do not accept octal numbers, sorry. */
4407 if (*str
== '0' && (str
[1] == 'x' || str
[1] == 'X'))
4414 /* look for a hex digit, if not found treat it as decimal */
4415 const char *p2
= str
;
4417 if (isxdigit (*p2
) && !isdigit (*p2
) && isascii (*p2
) )
4426 /* must have at least one digit! */
4427 if ( !isascii (*str
)
4428 || !(base
== 16 ? isxdigit (*str
) : isdigit (*str
)) )
4430 error (NILF
, _("bad number: '%s'\n"), start
);
4435 while (*str
&& !isspace (*str
))
4438 if (ch
>= '0' && ch
<= '9')
4440 else if (base
== 16 && ch
>= 'a' && ch
<= 'f')
4442 else if (base
== 16 && ch
>= 'A' && ch
<= 'F')
4446 error (NILF
, _("bad number: '%s' (base=%d, pos=%d)\n"), start
, base
, str
- start
);
4453 /* check trailing spaces. */
4454 while (isspace (*str
))
4458 error (NILF
, _("bad number: '%s'\n"), start
);
4462 return negative
? -num
: num
;
4465 /* Add two or more integer numbers. */
4467 func_int_add (char *o
, char **argv
, const char *funcname UNUSED
)
4472 num
= math_int_from_string (argv
[0]);
4473 for (i
= 1; argv
[i
]; i
++)
4474 num
+= math_int_from_string (argv
[i
]);
4476 return math_int_to_variable_buffer (o
, num
);
4479 /* Subtract two or more integer numbers. */
4481 func_int_sub (char *o
, char **argv
, const char *funcname UNUSED
)
4486 num
= math_int_from_string (argv
[0]);
4487 for (i
= 1; argv
[i
]; i
++)
4488 num
-= math_int_from_string (argv
[i
]);
4490 return math_int_to_variable_buffer (o
, num
);
4493 /* Multiply two or more integer numbers. */
4495 func_int_mul (char *o
, char **argv
, const char *funcname UNUSED
)
4500 num
= math_int_from_string (argv
[0]);
4501 for (i
= 1; argv
[i
]; i
++)
4502 num
*= math_int_from_string (argv
[i
]);
4504 return math_int_to_variable_buffer (o
, num
);
4507 /* Divide an integer number by one or more divisors. */
4509 func_int_div (char *o
, char **argv
, const char *funcname UNUSED
)
4515 num
= math_int_from_string (argv
[0]);
4516 for (i
= 1; argv
[i
]; i
++)
4518 divisor
= math_int_from_string (argv
[i
]);
4521 error (NILF
, _("divide by zero ('%s')\n"), argv
[i
]);
4522 return math_int_to_variable_buffer (o
, 0);
4527 return math_int_to_variable_buffer (o
, num
);
4531 /* Divide and return the remainder. */
4533 func_int_mod (char *o
, char **argv
, const char *funcname UNUSED
)
4538 num
= math_int_from_string (argv
[0]);
4539 divisor
= math_int_from_string (argv
[1]);
4542 error (NILF
, _("divide by zero ('%s')\n"), argv
[1]);
4543 return math_int_to_variable_buffer (o
, 0);
4547 return math_int_to_variable_buffer (o
, num
);
4552 func_int_not (char *o
, char **argv
, const char *funcname UNUSED
)
4556 num
= math_int_from_string (argv
[0]);
4559 return math_int_to_variable_buffer (o
, num
);
4562 /* Bitwise AND (two or more numbers). */
4564 func_int_and (char *o
, char **argv
, const char *funcname UNUSED
)
4569 num
= math_int_from_string (argv
[0]);
4570 for (i
= 1; argv
[i
]; i
++)
4571 num
&= math_int_from_string (argv
[i
]);
4573 return math_int_to_variable_buffer (o
, num
);
4576 /* Bitwise OR (two or more numbers). */
4578 func_int_or (char *o
, char **argv
, const char *funcname UNUSED
)
4583 num
= math_int_from_string (argv
[0]);
4584 for (i
= 1; argv
[i
]; i
++)
4585 num
|= math_int_from_string (argv
[i
]);
4587 return math_int_to_variable_buffer (o
, num
);
4590 /* Bitwise XOR (two or more numbers). */
4592 func_int_xor (char *o
, char **argv
, const char *funcname UNUSED
)
4597 num
= math_int_from_string (argv
[0]);
4598 for (i
= 1; argv
[i
]; i
++)
4599 num
^= math_int_from_string (argv
[i
]);
4601 return math_int_to_variable_buffer (o
, num
);
4604 /* Compare two integer numbers. Returns make boolean (true="1"; false=""). */
4606 func_int_cmp (char *o
, char **argv
, const char *funcname
)
4612 num1
= math_int_from_string (argv
[0]);
4613 num2
= math_int_from_string (argv
[1]);
4615 funcname
+= sizeof ("int-") - 1;
4616 if (!strcmp (funcname
, "eq"))
4618 else if (!strcmp (funcname
, "ne"))
4620 else if (!strcmp (funcname
, "gt"))
4622 else if (!strcmp (funcname
, "ge"))
4624 else if (!strcmp (funcname
, "lt"))
4626 else /*if (!strcmp (funcname, "le"))*/
4629 return variable_buffer_output (o
, rc
? "1" : "", rc
);
4632 #endif /* CONFIG_WITH_MATH */
4634 #ifdef CONFIG_WITH_NANOTS
4635 /* Returns the current timestamp as nano seconds. The time
4636 source is a high res monotone one if the platform provides
4637 this (and we know about it).
4639 Tip. Use this with int-sub to profile makefile reading
4642 func_nanots (char *o
, char **argv UNUSED
, const char *funcname UNUSED
)
4644 return math_int_to_variable_buffer (o
, nano_timestamp ());
4648 #ifdef CONFIG_WITH_OS2_LIBPATH
4649 /* Sets or gets the OS/2 libpath variables.
4651 The first argument indicates which variable - BEGINLIBPATH,
4652 ENDLIBPATH, LIBPATHSTRICT or LIBPATH.
4654 The second indicates whether this is a get (not present) or
4655 set (present) operation. When present it is the new value for
4658 func_os2_libpath (char *o
, char **argv
, const char *funcname UNUSED
)
4664 /* translate variable name (first arg) */
4665 if (!strcmp (argv
[0], "BEGINLIBPATH"))
4666 fVar
= BEGIN_LIBPATH
;
4667 else if (!strcmp (argv
[0], "ENDLIBPATH"))
4669 else if (!strcmp (argv
[0], "LIBPATHSTRICT"))
4670 fVar
= LIBPATHSTRICT
;
4671 else if (!strcmp (argv
[0], "LIBPATH"))
4675 error (NILF
, _("$(libpath): unknown variable `%s'"), argv
[0]);
4676 return variable_buffer_output (o
, "", 0);
4681 /* get the variable value. */
4684 buf
[0] = buf
[1] = buf
[2] = buf
[3] = '\0';
4685 rc
= DosQueryExtLIBPATH (buf
, fVar
);
4688 rc
= DosQueryHeaderInfo (NULLHANDLE
, 0, buf
, sizeof(buf
), QHINF_LIBPATH
);
4691 error (NILF
, _("$(libpath): failed to query `%s', rc=%d"), argv
[0], rc
);
4692 return variable_buffer_output (o
, "", 0);
4694 o
= variable_buffer_output (o
, buf
, strlen (buf
));
4698 /* set the variable value. */
4700 size_t len_max
= sizeof (buf
) < 2048 ? sizeof (buf
) : 2048;
4706 error (NILF
, _("$(libpath): LIBPATH is read-only"));
4707 return variable_buffer_output (o
, "", 0);
4710 /* strip leading and trailing spaces and check for max length. */
4712 while (isspace (*val
))
4714 end
= strchr (val
, '\0');
4715 while (end
> val
&& isspace (end
[-1]))
4721 error (NILF
, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
4722 argv
[0], len
, len_max
);
4723 return variable_buffer_output (o
, "", 0);
4726 /* make a stripped copy in low memory and try set it. */
4727 memcpy (buf
, val
, len
);
4729 rc
= DosSetExtLIBPATH (buf
, fVar
);
4732 error (NILF
, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv
[0], buf
, rc
);
4733 return variable_buffer_output (o
, "", 0);
4736 o
= variable_buffer_output (o
, "", 0);
4740 #endif /* CONFIG_WITH_OS2_LIBPATH */
4742 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
4743 /* Retrieve make statistics. */
4745 func_make_stats (char *o
, char **argv
, const char *funcname UNUSED
)
4750 if (!argv
[0] || (!argv
[0][0] && !argv
[1]))
4752 # ifdef CONFIG_WITH_MAKE_STATS
4753 len
= sprintf (buf
, "alloc-cur: %5ld/%3ld %3luMB hash: %5lu %2lu%%",
4754 make_stats_allocations
,
4755 make_stats_reallocations
,
4756 make_stats_allocated
/ (1024*1024),
4757 make_stats_ht_lookups
,
4758 (make_stats_ht_collisions
* 100) / make_stats_ht_lookups
);
4759 o
= variable_buffer_output (o
, buf
, len
);
4766 for (i
= 0; argv
[i
]; i
++)
4770 o
= variable_buffer_output (o
, " ", 1);
4773 # ifdef CONFIG_WITH_MAKE_STATS
4774 else if (!strcmp(argv
[i
], "allocations"))
4775 val
= make_stats_allocations
;
4776 else if (!strcmp(argv
[i
], "reallocations"))
4777 val
= make_stats_reallocations
;
4778 else if (!strcmp(argv
[i
], "allocated"))
4779 val
= make_stats_allocated
;
4780 else if (!strcmp(argv
[i
], "ht_lookups"))
4781 val
= make_stats_ht_lookups
;
4782 else if (!strcmp(argv
[i
], "ht_collisions"))
4783 val
= make_stats_ht_collisions
;
4784 else if (!strcmp(argv
[i
], "ht_collisions_pct"))
4785 val
= (make_stats_ht_collisions
* 100) / make_stats_ht_lookups
;
4789 o
= variable_buffer_output (o
, argv
[i
], strlen (argv
[i
]));
4793 len
= sprintf (buf
, "%ld", val
);
4794 o
= variable_buffer_output (o
, buf
, len
);
4800 #endif /* CONFIG_WITH_MAKE_STATS */
4802 #ifdef CONFIG_WITH_COMMANDS_FUNC
4803 /* Gets all the commands for a target, separated by newlines.
4805 This is useful when creating and checking target dependencies since
4806 it reduces the amount of work and the memory consuption. A new prefix
4807 character '%' has been introduced for skipping certain lines, like
4808 for instance the one calling this function and pushing to a dep file.
4809 Blank lines are also skipped.
4811 The commands function takes exactly one argument, which is the name of
4812 the target which commands should be returned.
4814 The commands-sc is identical to commands except that it uses a ';' to
4815 separate the commands.
4817 The commands-usr is similar to commands except that it takes a 2nd
4818 argument that is used to separate the commands. */
4820 func_commands (char *o
, char **argv
, const char *funcname
)
4823 static int recursive
= 0;
4827 error (reading_file
, _("$(%s ) was invoked recursivly"), funcname
);
4828 return variable_buffer_output (o
, "recursive", sizeof ("recursive") - 1);
4830 if (*argv
[0] == '\0')
4832 error (reading_file
, _("$(%s ) was invoked with an empty target name"), funcname
);
4837 file
= lookup_file (argv
[0]);
4838 if (file
&& file
->cmds
)
4842 struct commands
*cmds
= file
->cmds
;
4843 const char *cmd_sep
;
4845 if (!strcmp (funcname
, "commands"))
4850 else if (!strcmp (funcname
, "commands-sc"))
4855 else /*if (!strcmp (funcname, "commands-usr"))*/
4858 cmd_sep_len
= strlen (cmd_sep
);
4861 initialize_file_variables (file
, 1 /* don't search for pattern vars */);
4862 set_file_variables (file
, 1 /* early call */);
4863 chop_commands (cmds
);
4865 for (i
= 0; i
< cmds
->ncommand_lines
; i
++)
4868 char *in
, *out
, *ref
;
4870 /* Skip it if it has a '%' prefix or is blank. */
4871 if (cmds
->lines_flags
[i
] & COMMAND_GETTER_SKIP_IT
)
4873 p
= cmds
->command_lines
[i
];
4874 while (isblank ((unsigned char)*p
))
4879 /* --- copied from new_job() in job.c --- */
4881 /* Collapse backslash-newline combinations that are inside variable
4882 or function references. These are left alone by the parser so
4883 that they will appear in the echoing of commands (where they look
4884 nice); and collapsed by construct_command_argv when it tokenizes.
4885 But letting them survive inside function invocations loses because
4886 we don't want the functions to see them as part of the text. */
4888 /* IN points to where in the line we are scanning.
4889 OUT points to where in the line we are writing.
4890 When we collapse a backslash-newline combination,
4891 IN gets ahead of OUT. */
4894 while ((ref
= strchr (in
, '$')) != 0)
4896 ++ref
; /* Move past the $. */
4899 /* Copy the text between the end of the last chunk
4900 we processed (where IN points) and the new chunk
4901 we are about to process (where REF points). */
4902 memmove (out
, in
, ref
- in
);
4904 /* Move both pointers past the boring stuff. */
4908 if (*ref
== '(' || *ref
== '{')
4910 char openparen
= *ref
;
4911 char closeparen
= openparen
== '(' ? ')' : '}';
4915 *out
++ = *in
++; /* Copy OPENPAREN. */
4916 /* IN now points past the opening paren or brace.
4917 Count parens or braces until it is matched. */
4921 if (*in
== closeparen
&& --count
< 0)
4923 else if (*in
== '\\' && in
[1] == '\n')
4925 /* We have found a backslash-newline inside a
4926 variable or function reference. Eat it and
4927 any following whitespace. */
4930 for (p2
= in
- 1; p2
> ref
&& *p2
== '\\'; --p2
)
4934 /* There were two or more backslashes, so this is
4935 not really a continuation line. We don't collapse
4936 the quoting backslashes here as is done in
4937 collapse_continuations, because the line will
4938 be collapsed again after expansion. */
4942 /* Skip the backslash, newline and
4943 any following whitespace. */
4944 in
= next_token (in
+ 2);
4946 /* Discard any preceding whitespace that has
4947 already been written to the output. */
4949 && isblank ((unsigned char)out
[-1]))
4952 /* Replace it all with a single space. */
4958 if (*in
== openparen
)
4965 /* Some of these can be amended ($< perhaps), but we're likely to be called while the
4966 dep expansion happens, so it would have to be on a hackish basis. sad... */
4967 else if (*ref
== '<' || *ref
== '*' || *ref
== '%' || *ref
== '^' || *ref
== '+')
4968 error (reading_file
, _("$(%s ) does not work reliably with $%c in all cases"), funcname
, *ref
);
4971 /* There are no more references in this line to worry about.
4972 Copy the remaining uninteresting text to the output. */
4976 /* --- copied from new_job() in job.c --- */
4978 /* Finally, expand the line. */
4980 o
= variable_buffer_output (o
, cmd_sep
, cmd_sep_len
);
4981 o
= variable_expand_for_file_2 (o
, cmds
->command_lines
[i
], ~0U, file
, NULL
);
4983 /* Skip it if it has a '%' prefix or is blank. */
4985 while (isblank ((unsigned char)*o
)
4990 if (*o
!= '\0' && *o
!= '%')
4991 o
= strchr (o
, '\0');
4993 o
= p
- cmd_sep_len
;
4996 } /* for each command line */
4998 /* else FIXME: bitch about it? */
5003 #endif /* CONFIG_WITH_COMMANDS_FUNC */
5006 /* Useful when debugging kmk and/or makefiles. */
5008 func_breakpoint (char *o
, char **argv UNUSED
, const char *funcname UNUSED
)
5012 #elif defined(__i386__) || defined(__x86__) || defined(__X86__) || defined(_M_IX86) || defined(__i386) \
5013 || defined(__amd64__) || defined(__x86_64__) || defined(__AMD64__) || defined(_M_X64) || defined(__amd64)
5014 __asm__
__volatile__ ("int3\n\t");
5016 char *p
= (char *)0;
5024 /* Lookup table for builtin functions.
5026 This doesn't have to be sorted; we use a straight lookup. We might gain
5027 some efficiency by moving most often used functions to the start of the
5030 If MAXIMUM_ARGS is 0, that means there is no maximum and all
5031 comma-separated values are treated as arguments.
5033 EXPAND_ARGS means that all arguments should be expanded before invocation.
5034 Functions that do namespace tricks (foreach) don't automatically expand. */
5036 static char *func_call (char *o
, char **argv
, const char *funcname
);
5039 static struct function_table_entry function_table_init
[] =
5041 /* Name/size */ /* MIN MAX EXP? Function */
5042 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath
},
5043 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix
},
5044 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix
},
5045 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir
},
5046 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir
},
5047 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix
},
5048 #ifdef CONFIG_WITH_ROOT_FUNC
5049 { STRING_SIZE_TUPLE("root"), 0, 1, 1, func_root
},
5051 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst
},
5052 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix
},
5053 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout
},
5054 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout
},
5055 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring
},
5056 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword
},
5057 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor
},
5058 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join
},
5059 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword
},
5060 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst
},
5061 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath
},
5062 #ifdef CONFIG_WITH_RSORT
5063 { STRING_SIZE_TUPLE("rsort"), 0, 1, 1, func_sort
},
5065 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell
},
5066 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort
},
5067 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip
},
5068 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard
},
5069 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word
},
5070 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist
},
5071 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words
},
5072 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin
},
5073 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach
},
5074 #ifdef CONFIG_WITH_LOOP_FUNCTIONS
5075 { STRING_SIZE_TUPLE("for"), 4, 4, 0, func_for
},
5076 { STRING_SIZE_TUPLE("while"), 2, 2, 0, func_while
},
5078 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call
},
5079 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error
},
5080 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error
},
5081 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error
},
5082 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if
},
5083 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or
},
5084 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and
},
5085 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value
},
5086 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval
},
5087 #ifdef CONFIG_WITH_EVALPLUS
5088 { STRING_SIZE_TUPLE("evalctx"), 0, 1, 1, func_evalctx
},
5089 { STRING_SIZE_TUPLE("evalval"), 1, 1, 1, func_evalval
},
5090 { STRING_SIZE_TUPLE("evalvalctx"), 1, 1, 1, func_evalval
},
5091 { STRING_SIZE_TUPLE("evalcall"), 1, 0, 1, func_call
},
5092 { STRING_SIZE_TUPLE("evalcall2"), 1, 0, 1, func_call
},
5093 { STRING_SIZE_TUPLE("eval-opt-var"), 1, 0, 1, func_eval_optimize_variable
},
5096 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq
},
5097 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not
},
5099 #ifdef CONFIG_WITH_STRING_FUNCTIONS
5100 { STRING_SIZE_TUPLE("length"), 1, 1, 1, func_length
},
5101 { STRING_SIZE_TUPLE("length-var"), 1, 1, 1, func_length_var
},
5102 { STRING_SIZE_TUPLE("insert"), 2, 5, 1, func_insert
},
5103 { STRING_SIZE_TUPLE("pos"), 2, 3, 1, func_pos
},
5104 { STRING_SIZE_TUPLE("lastpos"), 2, 3, 1, func_pos
},
5105 { STRING_SIZE_TUPLE("substr"), 2, 4, 1, func_substr
},
5106 { STRING_SIZE_TUPLE("translate"), 2, 4, 1, func_translate
},
5108 #ifdef CONFIG_WITH_PRINTF
5109 { STRING_SIZE_TUPLE("printf"), 1, 0, 1, kmk_builtin_func_printf
},
5111 #ifdef CONFIG_WITH_LAZY_DEPS_VARS
5112 { STRING_SIZE_TUPLE("deps"), 1, 2, 1, func_deps
},
5113 { STRING_SIZE_TUPLE("deps-all"), 1, 2, 1, func_deps
},
5114 { STRING_SIZE_TUPLE("deps-newer"), 1, 2, 1, func_deps_newer
},
5115 { STRING_SIZE_TUPLE("deps-oo"), 1, 2, 1, func_deps_order_only
},
5117 #ifdef CONFIG_WITH_DEFINED
5118 { STRING_SIZE_TUPLE("defined"), 1, 1, 1, func_defined
},
5120 #ifdef CONFIG_WITH_TOUPPER_TOLOWER
5121 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower
},
5122 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower
},
5124 #ifdef CONFIG_WITH_ABSPATHEX
5125 { STRING_SIZE_TUPLE("abspathex"), 0, 2, 1, func_abspathex
},
5127 #ifdef CONFIG_WITH_XARGS
5128 { STRING_SIZE_TUPLE("xargs"), 2, 0, 1, func_xargs
},
5130 #if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
5131 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars
},
5132 { STRING_SIZE_TUPLE("comp-cmds"), 3, 3, 1, func_comp_vars
},
5133 { STRING_SIZE_TUPLE("comp-cmds-ex"), 3, 3, 1, func_comp_cmds_ex
},
5135 #ifdef CONFIG_WITH_DATE
5136 { STRING_SIZE_TUPLE("date"), 0, 1, 1, func_date
},
5137 { STRING_SIZE_TUPLE("date-utc"), 0, 3, 1, func_date
},
5139 #ifdef CONFIG_WITH_FILE_SIZE
5140 { STRING_SIZE_TUPLE("file-size"), 1, 1, 1, func_file_size
},
5142 #ifdef CONFIG_WITH_WHICH
5143 { STRING_SIZE_TUPLE("which"), 0, 0, 1, func_which
},
5145 #ifdef CONFIG_WITH_IF_CONDITIONALS
5146 { STRING_SIZE_TUPLE("expr"), 1, 1, 0, func_expr
},
5147 { STRING_SIZE_TUPLE("if-expr"), 2, 3, 0, func_if_expr
},
5148 { STRING_SIZE_TUPLE("select"), 2, 0, 0, func_select
},
5150 #ifdef CONFIG_WITH_SET_CONDITIONALS
5151 { STRING_SIZE_TUPLE("intersects"), 2, 2, 1, func_set_intersects
},
5153 #ifdef CONFIG_WITH_STACK
5154 { STRING_SIZE_TUPLE("stack-push"), 2, 2, 1, func_stack_push
},
5155 { STRING_SIZE_TUPLE("stack-pop"), 1, 1, 1, func_stack_pop_top
},
5156 { STRING_SIZE_TUPLE("stack-popv"), 1, 1, 1, func_stack_pop_top
},
5157 { STRING_SIZE_TUPLE("stack-top"), 1, 1, 1, func_stack_pop_top
},
5159 #ifdef CONFIG_WITH_MATH
5160 { STRING_SIZE_TUPLE("int-add"), 2, 0, 1, func_int_add
},
5161 { STRING_SIZE_TUPLE("int-sub"), 2, 0, 1, func_int_sub
},
5162 { STRING_SIZE_TUPLE("int-mul"), 2, 0, 1, func_int_mul
},
5163 { STRING_SIZE_TUPLE("int-div"), 2, 0, 1, func_int_div
},
5164 { STRING_SIZE_TUPLE("int-mod"), 2, 2, 1, func_int_mod
},
5165 { STRING_SIZE_TUPLE("int-not"), 1, 1, 1, func_int_not
},
5166 { STRING_SIZE_TUPLE("int-and"), 2, 0, 1, func_int_and
},
5167 { STRING_SIZE_TUPLE("int-or"), 2, 0, 1, func_int_or
},
5168 { STRING_SIZE_TUPLE("int-xor"), 2, 0, 1, func_int_xor
},
5169 { STRING_SIZE_TUPLE("int-eq"), 2, 2, 1, func_int_cmp
},
5170 { STRING_SIZE_TUPLE("int-ne"), 2, 2, 1, func_int_cmp
},
5171 { STRING_SIZE_TUPLE("int-gt"), 2, 2, 1, func_int_cmp
},
5172 { STRING_SIZE_TUPLE("int-ge"), 2, 2, 1, func_int_cmp
},
5173 { STRING_SIZE_TUPLE("int-lt"), 2, 2, 1, func_int_cmp
},
5174 { STRING_SIZE_TUPLE("int-le"), 2, 2, 1, func_int_cmp
},
5176 #ifdef CONFIG_WITH_NANOTS
5177 { STRING_SIZE_TUPLE("nanots"), 0, 0, 0, func_nanots
},
5179 #ifdef CONFIG_WITH_OS2_LIBPATH
5180 { STRING_SIZE_TUPLE("libpath"), 1, 2, 1, func_os2_libpath
},
5182 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5183 { STRING_SIZE_TUPLE("make-stats"), 0, 0, 0, func_make_stats
},
5185 #ifdef CONFIG_WITH_COMMANDS_FUNC
5186 { STRING_SIZE_TUPLE("commands"), 1, 1, 1, func_commands
},
5187 { STRING_SIZE_TUPLE("commands-sc"), 1, 1, 1, func_commands
},
5188 { STRING_SIZE_TUPLE("commands-usr"), 2, 2, 1, func_commands
},
5191 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool
},
5192 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base
},
5193 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix
},
5194 { STRING_SIZE_TUPLE("kb-src-prop"), 3, 4, 0, func_kbuild_source_prop
},
5195 { STRING_SIZE_TUPLE("kb-src-one"), 0, 1, 0, func_kbuild_source_one
},
5196 { STRING_SIZE_TUPLE("kb-exp-tmpl"), 6, 6, 1, func_kbuild_expand_template
},
5199 { STRING_SIZE_TUPLE("breakpoint"), 0, 0, 0, func_breakpoint
},
5203 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
5206 /* These must come after the definition of function_table. */
5209 expand_builtin_function (char *o
, int argc
, char **argv
,
5210 const struct function_table_entry
*entry_p
)
5212 if (argc
< (int)entry_p
->minimum_args
)
5213 fatal (*expanding_var
,
5214 _("insufficient number of arguments (%d) to function `%s'"),
5215 argc
, entry_p
->name
);
5217 /* I suppose technically some function could do something with no
5218 arguments, but so far none do, so just test it for all functions here
5219 rather than in each one. We can change it later if necessary. */
5224 if (!entry_p
->func_ptr
)
5225 fatal (*expanding_var
,
5226 _("unimplemented on this platform: function `%s'"), entry_p
->name
);
5228 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
5231 /* Check for a function invocation in *STRINGP. *STRINGP points at the
5232 opening ( or { and is not null-terminated. If a function invocation
5233 is found, expand it into the buffer at *OP, updating *OP, incrementing
5234 *STRINGP past the reference and returning nonzero. If not, return zero. */
5237 handle_function2 (const struct function_table_entry
*entry_p
, char **op
, const char **stringp
) /* bird split it up. */
5239 char openparen
= (*stringp
)[0];
5240 char closeparen
= openparen
== '(' ? ')' : '}';
5245 char **argv
, **argvp
;
5250 /* We found a builtin function. Find the beginning of its arguments (skip
5251 whitespace after the name). */
5253 beg
= next_token (beg
+ entry_p
->len
);
5255 /* Find the end of the function invocation, counting nested use of
5256 whichever kind of parens we use. Since we're looking, count commas
5257 to get a rough estimate of how many arguments we might have. The
5258 count might be high, but it'll never be low. */
5260 for (nargs
=1, end
=beg
; *end
!= '\0'; ++end
)
5263 else if (*end
== openparen
)
5265 else if (*end
== closeparen
&& --count
< 0)
5269 fatal (*expanding_var
,
5270 _("unterminated call to function `%s': missing `%c'"),
5271 entry_p
->name
, closeparen
);
5275 /* Get some memory to store the arg pointers. */
5276 argvp
= argv
= alloca (sizeof (char *) * (nargs
+ 2));
5278 /* Chop the string into arguments, then a nul. As soon as we hit
5279 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
5282 If we're expanding, store pointers to the expansion of each one. If
5283 not, make a duplicate of the string and point into that, nul-terminating
5286 if (entry_p
->expand_args
)
5289 for (p
=beg
, nargs
=0; p
<= end
; ++argvp
)
5295 if (nargs
== entry_p
->maximum_args
5296 || (! (next
= find_next_argument (openparen
, closeparen
, p
, end
))))
5299 *argvp
= expand_argument (p
, next
);
5305 int len
= end
- beg
;
5308 abeg
= xmalloc (len
+1);
5309 memcpy (abeg
, beg
, len
);
5313 for (p
=abeg
, nargs
=0; p
<= aend
; ++argvp
)
5319 if (nargs
== entry_p
->maximum_args
5320 || (! (next
= find_next_argument (openparen
, closeparen
, p
, aend
))))
5330 /* Finally! Run the function... */
5331 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
5334 if (entry_p
->expand_args
)
5335 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
5344 int /* bird split it up and hacked it. */
5345 #ifndef CONFIG_WITH_VALUE_LENGTH
5346 handle_function (char **op
, const char **stringp
)
5348 const struct function_table_entry
*entry_p
= lookup_function (*stringp
+ 1);
5351 return handle_function2 (entry_p
, op
, stringp
);
5353 #else /* CONFIG_WITH_VALUE_LENGTH */
5354 handle_function (char **op
, const char **stringp
, const char *nameend
, const char *eol UNUSED
)
5356 const char *fname
= *stringp
+ 1;
5357 const struct function_table_entry
*entry_p
=
5358 lookup_function_in_hash_tab (fname
, nameend
- fname
);
5361 return handle_function2 (entry_p
, op
, stringp
);
5363 #endif /* CONFIG_WITH_VALUE_LENGTH */
5366 /* User-defined functions. Expand the first argument as either a builtin
5367 function or a make variable, in the context of the rest of the arguments
5368 assigned to $1, $2, ... $N. $0 is the name of the function. */
5371 func_call (char *o
, char **argv
, const char *funcname UNUSED
)
5373 static int max_args
= 0;
5380 const struct function_table_entry
*entry_p
;
5382 #ifdef CONFIG_WITH_EVALPLUS
5386 #if defined (CONFIG_WITH_EVALPLUS) || defined (CONFIG_WITH_VALUE_LENGTH)
5390 /* There is no way to define a variable with a space in the name, so strip
5391 leading and trailing whitespace as a favor to the user. */
5393 while (*fname
!= '\0' && isspace ((unsigned char)*fname
))
5396 cp
= fname
+ strlen (fname
) - 1;
5397 while (cp
> fname
&& isspace ((unsigned char)*cp
))
5401 /* Calling nothing is a no-op */
5405 /* Are we invoking a builtin function? */
5407 #ifndef CONFIG_WITH_VALUE_LENGTH
5408 entry_p
= lookup_function (fname
);
5410 entry_p
= lookup_function (fname
, cp
- fname
+ 1);
5414 /* How many arguments do we have? */
5415 for (i
=0; argv
[i
+1]; ++i
)
5417 return expand_builtin_function (o
, i
, argv
+1, entry_p
);
5420 /* Not a builtin, so the first argument is the name of a variable to be
5421 expanded and interpreted as a function. Find it. */
5422 flen
= strlen (fname
);
5424 v
= lookup_variable (fname
, flen
);
5427 warn_undefined (fname
, flen
);
5429 if (v
== 0 || *v
->value
== '\0')
5432 body
= alloca (flen
+ 4);
5435 memcpy (body
+ 2, fname
, flen
);
5437 body
[flen
+3] = '\0';
5439 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
5441 push_new_variable_scope ();
5443 for (i
=0; *argv
; ++i
, ++argv
)
5444 #ifdef CONFIG_WITH_VALUE_LENGTH
5445 define_variable (num
, sprintf (num
, "%d", i
), *argv
, o_automatic
, 0);
5450 sprintf (num
, "%d", i
);
5451 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
5455 #ifdef CONFIG_WITH_EVALPLUS
5456 /* $(.ARGC) is the argument count. */
5458 len
= sprintf (num
, "%d", i
- 1);
5459 define_variable_vl (".ARGC", sizeof (".ARGC") - 1, num
, len
,
5460 1 /* dup val */, o_automatic
, 0);
5463 /* If the number of arguments we have is < max_args, it means we're inside
5464 a recursive invocation of $(call ...). Fill in the remaining arguments
5465 in the new scope with the empty value, to hide them from this
5468 for (; i
< max_args
; ++i
)
5469 #ifdef CONFIG_WITH_VALUE_LENGTH
5470 define_variable (num
, sprintf (num
, "%d", i
), "", o_automatic
, 0);
5475 sprintf (num
, "%d", i
);
5476 define_variable (num
, strlen (num
), "", o_automatic
, 0);
5480 saved_args
= max_args
;
5483 #ifdef CONFIG_WITH_EVALPLUS
5484 if (!strcmp (funcname
, "call"))
5487 /* Expand the body in the context of the arguments, adding the result to
5488 the variable buffer. */
5490 v
->exp_count
= EXP_COUNT_MAX
;
5491 #ifndef CONFIG_WITH_VALUE_LENGTH
5492 o
= variable_expand_string (o
, body
, flen
+3);
5496 #else /* CONFIG_WITH_VALUE_LENGTH */
5497 variable_expand_string_2 (o
, body
, flen
+3, &o
);
5499 #endif /* CONFIG_WITH_VALUE_LENGTH */
5500 #ifdef CONFIG_WITH_EVALPLUS
5504 const struct floc
*reading_file_saved
= reading_file
;
5507 if (!strcmp (funcname
, "evalcall"))
5509 /* Evaluate the variable value without expanding it. We
5510 need a copy since eval_buffer is destructive. */
5512 size_t off
= o
- variable_buffer
;
5513 eos
= variable_buffer_output (o
, v
->value
, v
->value_length
+ 1) - 1;
5514 o
= variable_buffer
+ off
;
5515 if (v
->fileinfo
.filenm
)
5516 reading_file
= &v
->fileinfo
;
5520 /* Expand the body first and then evaluate the output. */
5522 v
->exp_count
= EXP_COUNT_MAX
;
5523 o
= variable_expand_string_2 (o
, body
, flen
+3, &eos
);
5527 install_variable_buffer (&buf
, &len
);
5528 eval_buffer (o
, eos
);
5529 restore_variable_buffer (buf
, len
);
5530 reading_file
= reading_file_saved
;
5532 /* Deal with the .RETURN value if present. */
5534 v
= lookup_variable_in_set (".RETURN", sizeof (".RETURN") - 1,
5535 current_variable_set_list
->set
);
5536 if (v
&& v
->value_length
)
5540 v
->exp_count
= EXP_COUNT_MAX
;
5541 variable_expand_string_2 (o
, v
->value
, v
->value_length
, &o
);
5545 o
= variable_buffer_output (o
, v
->value
, v
->value_length
);
5548 #endif /* CONFIG_WITH_EVALPLUS */
5550 max_args
= saved_args
;
5552 pop_variable_scope ();
5558 hash_init_function_table (void)
5560 hash_init (&function_table
, FUNCTION_TABLE_ENTRIES
* 2,
5561 function_table_entry_hash_1
, function_table_entry_hash_2
,
5562 function_table_entry_hash_cmp
);
5563 hash_load (&function_table
, function_table_init
,
5564 FUNCTION_TABLE_ENTRIES
, sizeof (struct function_table_entry
));
5565 #if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
5568 for (i
= 0; i
< FUNCTION_TABLE_ENTRIES
; i
++)
5570 const char *fn
= function_table_init
[i
].name
;
5573 func_char_map
[(int)*fn
] = 1;
5576 assert (function_table_init
[i
].len
<= MAX_FUNCTION_LENGTH
);
5577 assert (function_table_init
[i
].len
>= MIN_FUNCTION_LENGTH
);