kmk: strlcpy build fix for windows.
[kbuild-mirror.git] / src / kmk / function.c
blob9d2075535e154e9714186baf798662898a6799f8
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
4 Foundation, Inc.
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
10 version.
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/>. */
19 #include "make.h"
20 #include "filedef.h"
21 #include "variable.h"
22 #include "dep.h"
23 #include "job.h"
24 #include "commands.h"
25 #include "debug.h"
27 #ifdef _AMIGA
28 #include "amiga.h"
29 #endif
31 #ifdef WINDOWS32 /* bird */
32 # include "pathstuff.h"
33 #endif
35 #ifdef KMK_HELPERS
36 # include "kbuild.h"
37 #endif
38 #ifdef CONFIG_WITH_PRINTF
39 # include "kmkbuiltin.h"
40 #endif
41 #ifdef CONFIG_WITH_XARGS /* bird */
42 # ifdef HAVE_LIMITS_H
43 # include <limits.h>
44 # endif
45 #endif
46 #include <assert.h> /* bird */
48 #if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE) /* bird */
49 # include <ctype.h>
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);
53 #endif
55 #ifdef CONFIG_WITH_NANOTS /* bird */
56 # ifdef WINDOWS32
57 # include <Windows.h>
58 # endif
59 #endif
61 #ifdef __OS2__
62 # define CONFIG_WITH_OS2_LIBPATH 1
63 #endif
64 #ifdef CONFIG_WITH_OS2_LIBPATH
65 # define INCL_BASE
66 # define INCL_ERRROS
67 # include <os2.h>
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
83 const char *name;
84 unsigned char len;
85 unsigned char minimum_args;
86 unsigned char maximum_args;
87 char expand_args;
88 char *(*func_ptr) (char *output, char **argv, const char *fname);
91 static unsigned long
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);
98 static unsigned long
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);
105 static int
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;
111 if (result)
112 return result;
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;
124 #endif
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. */
133 char *
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;
138 const char *p;
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));
144 if (rlen > 0)
145 o = variable_buffer_output (o, replace, rlen);
146 return o;
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));
155 else
157 p = strstr (t, subst);
158 if (p == 0)
160 /* No more matches. Output everything left on the end. */
161 o = variable_buffer_output (o, t, strlen (t));
162 return o;
166 /* Output everything before this occurrence of the string to replace. */
167 if (p > t)
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. */
172 if (by_word
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);
178 else if (rlen > 0)
179 /* Output the replacement string. */
180 o = variable_buffer_output (o, replace, rlen);
182 /* Advance T past the string to be replaced. */
183 t = p + slen;
184 } while (*t != '\0');
186 return o;
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.
200 char *
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;
207 const char *t;
208 unsigned int len;
209 int doneany = 0;
211 /* Record the length of REPLACE before and after the % so we don't have to
212 compute these lengths more than once. */
213 if (replace_percent)
215 replace_prepercent_len = replace_percent - replace - 1;
216 replace_postpercent_len = strlen (replace_percent);
218 else
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)
236 int fail = 0;
238 /* Is it big enough to match? */
239 if (len < pattern_prepercent_len + pattern_postpercent_len)
240 fail = 1;
242 /* Does the prefix match? */
243 if (!fail && pattern_prepercent_len > 0
244 && (*t != *pattern
245 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
246 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
247 fail = 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)))
255 fail = 1;
257 if (fail)
258 /* It didn't match. Output the string. */
259 o = variable_buffer_output (o, t, len);
260 else
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);
285 doneany = 1;
288 #ifndef CONFIG_WITH_VALUE_LENGTH
289 if (doneany)
290 /* Kill the last space. */
291 --o;
292 #else
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. */
296 if (doneany)
297 *--o = '\0';
298 else
299 o = variable_buffer_output (o, "\0", 1) - 1;
300 #endif
302 return o;
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.
315 char *
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. */
322 if (replace_percent)
323 ++replace_percent;
324 if (pattern_percent)
325 ++pattern_percent;
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)
353 unsigned char ch;
354 # if 0 /* insane loop unroll */
356 if (len > MAX_FUNCTION_LENGTH)
357 len = MAX_FUNCTION_LENGTH + 1;
359 # define X(idx) \
360 if (!func_char_map[ch = s[idx]]) \
362 if (isblank (ch)) \
363 return lookup_function_in_hash_tab (s, idx); \
364 return 0; \
366 # define Z(idx) \
367 return lookup_function_in_hash_tab (s, idx);
369 switch (len)
371 default:
372 assert (0);
373 case 0: return 0;
374 case 1: return 0;
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);
389 return 0;
391 # undef Z
392 # undef X
394 # else /* normal loop */
395 const char *e = s;
396 if (len > MAX_FUNCTION_LENGTH)
397 len = MAX_FUNCTION_LENGTH;
398 while (func_char_map[ch = *e])
400 if (!len--)
401 return 0;
402 e++;
404 if (ch == '\0' || isblank (ch))
405 return lookup_function_in_hash_tab (s, e - s);
406 return 0;
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)
416 const char *e = s;
417 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
418 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);
427 return 0;
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;
439 if (percent == 0)
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);
445 if (percent == 0)
446 return streq (new_chars, str);
447 pattern = new_chars;
450 sfxlen = strlen (percent + 1);
451 strlength = strlen (str);
453 if (strlength < (percent - pattern) + sfxlen
454 || !strneq (pattern, str, percent - pattern))
455 return 0;
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
463 next character.
465 If no next argument is found, return NULL.
468 static char *
469 find_next_argument (char startparen, char endparen,
470 const char *ptr, const char *end)
472 int count = 0;
474 for (; ptr < end; ++ptr)
475 if (*ptr == startparen)
476 ++count;
478 else if (*ptr == endparen)
480 --count;
481 if (count < 0)
482 return NULL;
485 else if (*ptr == ',' && !count)
486 return (char *)ptr;
488 /* We didn't find anything. */
489 return NULL;
493 /* Glob-expand LINE. The returned pointer is
494 only good until the next call to string_glob. */
496 static char *
497 string_glob (char *line)
499 static char *result = 0;
500 static unsigned int length;
501 struct nameseq *chain;
502 unsigned int idx;
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)). */
519 &nameseq_cache);
520 #endif /* CONFIG_WITH_ALLOC_CACHES */
522 if (result == 0)
524 length = 100;
525 result = xmalloc (100);
528 idx = 0;
529 while (chain != 0)
531 const char *name = chain->name;
532 unsigned int len = strlen (name);
534 struct nameseq *next = chain->next;
535 #ifndef CONFIG_WITH_ALLOC_CACHES
536 free (chain);
537 #else
538 alloccache_free (&nameseq_cache, chain);
539 #endif
540 chain = next;
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);
552 idx += len;
553 result[idx++] = ' ';
557 /* Kill the last space and terminate the string. */
558 if (idx == 0)
559 result[0] = '\0';
560 else
561 result[idx - 1] = '\0';
563 return result;
567 Builtin functions
570 static char *
571 func_patsubst (char *o, char **argv, const char *funcname UNUSED)
573 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
574 return o;
578 static char *
579 func_join (char *o, char **argv, const char *funcname UNUSED)
581 int doneany = 0;
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. */
587 const char *tp;
588 const char *pp;
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);
596 if (tp != 0)
597 o = variable_buffer_output (o, tp, len1);
599 pp = find_next_token (&list2_iterator, &len2);
600 if (pp != 0)
601 o = variable_buffer_output (o, pp, len2);
603 if (tp != 0 || pp != 0)
605 o = variable_buffer_output (o, " ", 1);
606 doneany = 1;
609 while (tp != 0 || pp != 0);
610 if (doneany)
611 /* Kill the last blank. */
612 --o;
614 return o;
618 static char *
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]));
623 if (v == 0)
624 o = variable_buffer_output (o, "undefined", 9);
625 else
626 switch (v->origin)
628 default:
629 case o_invalid:
630 abort ();
631 break;
632 case o_default:
633 o = variable_buffer_output (o, "default", 7);
634 break;
635 case o_env:
636 o = variable_buffer_output (o, "environment", 11);
637 break;
638 case o_file:
639 o = variable_buffer_output (o, "file", 4);
640 break;
641 case o_env_override:
642 o = variable_buffer_output (o, "environment override", 20);
643 break;
644 case o_command:
645 o = variable_buffer_output (o, "command line", 12);
646 break;
647 case o_override:
648 o = variable_buffer_output (o, "override", 8);
649 break;
650 case o_automatic:
651 o = variable_buffer_output (o, "automatic", 9);
652 break;
653 #ifdef CONFIG_WITH_LOCAL_VARIABLES
654 case o_local:
655 o = variable_buffer_output (o, "local", 5);
656 break;
657 #endif
660 return o;
663 static char *
664 func_flavor (char *o, char **argv, const char *funcname UNUSED)
666 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
668 if (v == 0)
669 o = variable_buffer_output (o, "undefined", 9);
670 else
671 if (v->recursive)
672 o = variable_buffer_output (o, "recursive", 9);
673 else
674 o = variable_buffer_output (o, "simple", 6);
676 return o;
679 #ifdef VMS
680 # define IS_PATHSEP(c) ((c) == ']')
681 #else
682 # ifdef HAVE_DOS_PATHS
683 # define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
684 # else
685 # define IS_PATHSEP(c) ((c) == '/')
686 # endif
687 #endif
690 static char *
691 func_notdir_suffix (char *o, char **argv, const char *funcname)
693 /* Expand the argument. */
694 const char *list_iterator = argv[0];
695 const char *p2;
696 int doneany =0;
697 unsigned int len=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 != '.'))
708 if (IS_PATHSEP (*p))
709 break;
710 --p;
713 if (p >= p2)
715 if (is_notdir)
716 ++p;
717 else if (*p != '.')
718 continue;
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] == ':')
725 p = p2 + 2;
726 o = variable_buffer_output (o, p, len - (p - p2));
728 #endif
729 else if (is_notdir)
730 o = variable_buffer_output (o, p2, len);
732 if (is_notdir || p >= p2)
734 o = variable_buffer_output (o, " ", 1);
735 doneany = 1;
739 if (doneany)
740 /* Kill last space. */
741 --o;
743 return o;
747 static char *
748 func_basename_dir (char *o, char **argv, const char *funcname)
750 /* Expand the argument. */
751 const char *p3 = argv[0];
752 const char *p2;
753 int doneany=0;
754 unsigned int len=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 != '.'))
764 if (IS_PATHSEP (*p))
765 break;
766 --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);
777 #endif
778 else if (is_dir)
779 #ifdef VMS
780 o = variable_buffer_output (o, "[]", 2);
781 #else
782 #ifndef _AMIGA
783 o = variable_buffer_output (o, "./", 2);
784 #else
785 ; /* Just a nop... */
786 #endif /* AMIGA */
787 #endif /* !VMS */
788 else
789 /* The entire name is the basename. */
790 o = variable_buffer_output (o, p2, len);
792 o = variable_buffer_output (o, " ", 1);
793 doneany = 1;
796 if (doneany)
797 /* Kill last space. */
798 --o;
800 return o;
803 #ifdef CONFIG_WITH_ROOT_FUNC
805 $(root path)
807 This is mainly for dealing with drive letters and UNC paths on Windows
808 and OS/2.
810 static char *
811 func_root (char *o, char **argv, const char *funcname UNUSED)
813 const char *paths = argv[0] ? argv[0] : "";
814 int doneany = 0;
815 const char *p;
816 unsigned int len;
818 while ((p = find_next_token (&paths, &len)) != 0)
820 const char *p2 = p;
822 #ifdef HAVE_DOS_PATHS
823 if ( len >= 2
824 && p2[1] == ':'
825 && ( (p2[0] >= 'A' && p2[0] <= 'Z')
826 || (p2[0] >= 'a' && p2[0] <= 'z')))
828 p2 += 2;
829 len -= 2;
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. */
838 p2 += 3;
839 len -= 3;
840 while (len > 0 && !IS_PATHSEP(*p2))
841 p2++, len--;
843 if (len && IS_PATHSEP(p2[0]) && (len == 1 || !IS_PATHSEP(p2[1])))
845 p2++;
846 len--;
848 if (len) /* optional share */
849 while (len > 0 && !IS_PATHSEP(*p2))
850 p2++, len--;
852 else
853 p2 = NULL;
855 else if (IS_PATHSEP(*p2))
857 p2++;
858 len--;
860 else
861 p2 = NULL;
863 #elif defined (VMS) || defined (AMGIA)
864 /* XXX: VMS and AMGIA */
865 fatal (NILF, _("$(root ) is not implemented on this platform"));
866 #else
867 if (IS_PATHSEP(*p2))
869 p2++;
870 len--;
872 else
873 p2 = NULL;
874 #endif
875 if (p2 != NULL)
877 /* Include all subsequent path seperators. */
879 while (len > 0 && IS_PATHSEP(*p2))
880 p2++, len--;
881 o = variable_buffer_output (o, p, p2 - p);
882 o = variable_buffer_output (o, " ", 1);
883 doneany = 1;
887 if (doneany)
888 /* Kill last space. */
889 --o;
891 return o;
893 #endif /* CONFIG_WITH_ROOT_FUNC */
895 static char *
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;
903 int doneany = 0;
904 const char *p;
905 unsigned int len;
907 while ((p = find_next_token (&list_iterator, &len)) != 0)
909 if (is_addprefix)
910 o = variable_buffer_output (o, argv[0], fixlen);
911 o = variable_buffer_output (o, p, len);
912 if (is_addsuffix)
913 o = variable_buffer_output (o, argv[0], fixlen);
914 o = variable_buffer_output (o, " ", 1);
915 doneany = 1;
918 if (doneany)
919 /* Kill last space. */
920 --o;
922 return o;
925 static char *
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);
931 return o;
935 static char *
936 func_firstword (char *o, char **argv, const char *funcname UNUSED)
938 unsigned int i;
939 const char *words = argv[0]; /* Use a temp variable for find_next_token */
940 const char *p = find_next_token (&words, &i);
942 if (p != 0)
943 o = variable_buffer_output (o, p, i);
945 return o;
948 static char *
949 func_lastword (char *o, char **argv, const char *funcname UNUSED)
951 unsigned int i;
952 const char *words = argv[0]; /* Use a temp variable for find_next_token */
953 const char *p = NULL;
954 const char *t;
956 while ((t = find_next_token (&words, &i)))
957 p = t;
959 if (p != 0)
960 o = variable_buffer_output (o, p, i);
962 return o;
965 static char *
966 func_words (char *o, char **argv, const char *funcname UNUSED)
968 int i = 0;
969 const char *word_iterator = argv[0];
970 char buf[20];
972 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
973 ++i;
975 sprintf (buf, "%d", i);
976 o = variable_buffer_output (o, buf, strlen (buf));
978 return o;
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
984 * begpp-1.
986 char *
987 strip_whitespace (const char **begpp, const char **endpp)
989 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
990 (*begpp) ++;
991 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
992 (*endpp) --;
993 return (char *)*begpp;
996 static void
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. */
1005 break;
1007 if (s <= end || end - beg < 0)
1008 fatal (*expanding_var, "%s: '%s'", msg, beg);
1013 static char *
1014 func_word (char *o, char **argv, const char *funcname UNUSED)
1016 const char *end_p;
1017 const char *p;
1018 int i;
1020 /* Check the first argument. */
1021 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
1022 i = atoi (argv[0]);
1024 if (i == 0)
1025 fatal (*expanding_var,
1026 _("first argument to `word' function must be greater than 0"));
1028 end_p = argv[1];
1029 while ((p = find_next_token (&end_p, 0)) != 0)
1030 if (--i == 0)
1031 break;
1033 if (i == 0)
1034 o = variable_buffer_output (o, p, end_p - p);
1036 return o;
1039 static char *
1040 func_wordlist (char *o, char **argv, const char *funcname UNUSED)
1042 int start, count;
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]);
1051 if (start < 1)
1052 fatal (*expanding_var,
1053 "invalid first argument to `wordlist' function: `%d'", start);
1055 count = atoi (argv[1]) - start + 1;
1057 if (count > 0)
1059 const char *p;
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)
1066 if (p)
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);
1077 return o;
1080 static char *
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]));
1087 return o;
1090 static char *
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);
1099 #endif
1101 int doneany = 0;
1102 const char *list_iterator = list;
1103 const char *p;
1104 unsigned int len;
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
1114 char *result = 0;
1116 free (var->value);
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);
1123 doneany = 1;
1124 free (result);
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;
1131 else
1132 # endif
1133 free (var->value);
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);
1143 doneany = 1;
1144 #endif /* CONFIG_WITH_VALUE_LENGTH */
1147 if (doneany)
1148 /* Kill the last space. */
1149 --o;
1151 pop_variable_scope ();
1152 free (varname);
1153 free (list);
1155 return o;
1158 #ifdef CONFIG_WITH_LOOP_FUNCTIONS
1160 /* Helper for func_for that evaluates the INIT and NEXT parts. */
1161 static void
1162 helper_eval (char *text, size_t text_len)
1164 unsigned int buf_len;
1165 char *buf;
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)
1175 static char *
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 */)
1197 /* Expand BODY. */
1199 if (!doneany)
1200 doneany = 1;
1201 else
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 ();
1212 free (next_buf);
1214 return o;
1218 $(while condition,body)
1220 static char *
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 */)
1232 if (!doneany)
1233 doneany = 1;
1234 else
1235 o = variable_buffer_output (o, " ", 1);
1236 variable_expand_string_2 (o, body, body_len, &o);
1239 pop_variable_scope ();
1241 return o;
1244 #endif /* CONFIG_WITH_LOOP_FUNCTIONS */
1246 struct a_word
1248 struct a_word *next;
1249 struct a_word *chain;
1250 char *str;
1251 int length;
1252 int matched;
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);
1267 static int
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;
1271 if (result)
1272 return result;
1273 return_STRING_COMPARE (((struct a_word const *) x)->str,
1274 ((struct a_word const *) y)->str);
1277 struct a_pattern
1279 struct a_pattern *next;
1280 char *str;
1281 char *percent;
1282 int length;
1283 int save_c;
1286 static char *
1287 func_filter_filterout (char *o, char **argv, const char *funcname)
1289 struct a_word *wordhead;
1290 struct a_word **wordtail;
1291 struct a_word *wp;
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];
1300 int literals = 0;
1301 int words = 0;
1302 int hashing = 0;
1303 char *p;
1304 unsigned int len;
1306 /* Chop ARGV[0] up into patterns to match against the words. */
1308 pattail = &pathead;
1309 while ((p = find_next_token (&pat_iterator, &len)) != 0)
1311 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
1313 *pattail = pat;
1314 pattail = &pat->next;
1316 if (*pat_iterator != '\0')
1317 ++pat_iterator;
1319 pat->str = p;
1320 pat->length = len;
1321 pat->save_c = p[len];
1322 p[len] = '\0';
1323 pat->percent = find_percent (p);
1324 if (pat->percent == 0)
1325 literals++;
1327 *pattail = 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));
1336 *wordtail = word;
1337 wordtail = &word->next;
1339 if (*word_iterator != '\0')
1340 ++word_iterator;
1342 p[len] = '\0';
1343 word->str = p;
1344 word->length = len;
1345 word->matched = 0;
1346 word->chain = 0;
1347 words++;
1349 *wordtail = 0;
1351 /* Only use a hash table if arg list lengths justifies the cost. */
1352 hashing = (literals >= 2 && (literals * words) >= 10);
1353 if (hashing)
1355 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
1356 a_word_hash_cmp);
1357 for (wp = wordhead; wp != 0; wp = wp->next)
1359 struct a_word *owp = hash_insert (&a_word_table, wp);
1360 if (owp)
1361 wp->chain = owp;
1365 if (words)
1367 int doneany = 0;
1369 /* Run each pattern through the words, killing words. */
1370 for (pp = pathead; pp != 0; pp = pp->next)
1372 if (pp->percent)
1373 for (wp = wordhead; wp != 0; wp = wp->next)
1374 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1375 else if (hashing)
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);
1381 while (wp)
1383 wp->matched |= 1;
1384 wp = wp->chain;
1387 else
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);
1399 doneany = 1;
1402 if (doneany)
1403 /* Kill the last space. */
1404 --o;
1407 for (pp = pathead; pp != 0; pp = pp->next)
1408 pp->str[pp->length] = pp->save_c;
1410 if (hashing)
1411 hash_free (&a_word_table, 0);
1413 return o;
1417 static char *
1418 func_strip (char *o, char **argv, const char *funcname UNUSED)
1420 const char *p = argv[0];
1421 int doneany = 0;
1423 while (*p != '\0')
1425 int i=0;
1426 const char *word_start;
1428 while (isspace ((unsigned char)*p))
1429 ++p;
1430 word_start = p;
1431 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1433 if (!i)
1434 break;
1435 o = variable_buffer_output (o, word_start, i);
1436 o = variable_buffer_output (o, " ", 1);
1437 doneany = 1;
1440 if (doneany)
1441 /* Kill the last space. */
1442 --o;
1444 return o;
1448 Print a warning or fatal message.
1450 static char *
1451 func_error (char *o, char **argv, const char *funcname)
1453 char **argvp;
1454 char *msg, *p;
1455 int len;
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)
1467 strcpy (p, *argvp);
1468 p += strlen (*argvp);
1469 *(p++) = ',';
1470 *(p++) = ' ';
1472 strcpy (p, *argvp);
1474 switch (*funcname) {
1475 case 'e':
1476 fatal (reading_file, "%s", msg);
1478 case 'w':
1479 error (reading_file, "%s", msg);
1480 break;
1482 case 'i':
1483 printf ("%s\n", msg);
1484 fflush(stdout);
1485 break;
1487 default:
1488 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1491 /* The warning function expands to the empty string. */
1492 return o;
1497 chop argv[0] into words, and sort them.
1499 static char *
1500 func_sort (char *o, char **argv, const char *funcname UNUSED)
1502 const char *t;
1503 char **words;
1504 int wordi;
1505 char *p;
1506 unsigned int len;
1507 int i;
1509 /* Find the maximum number of words we'll have. */
1510 t = argv[0];
1511 wordi = 1;
1512 while (*t != '\0')
1514 char c = *(t++);
1516 if (! isspace ((unsigned char)c))
1517 continue;
1519 ++wordi;
1521 while (isspace ((unsigned char)*t))
1522 ++t;
1525 words = xmalloc (wordi * sizeof (char *));
1527 /* Now assign pointers to each string in the array. */
1528 t = argv[0];
1529 wordi = 0;
1530 while ((p = find_next_token (&t, &len)) != 0)
1532 ++t;
1533 p[len] = '\0';
1534 words[wordi++] = p;
1537 if (wordi)
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"))
1546 /* sort */
1547 #endif
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
1560 else
1562 /* rsort - reverse the result */
1563 i = wordi;
1564 while (i-- > 0)
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);
1575 #endif
1577 /* Kill the last space. */
1578 --o;
1581 free (words);
1583 return o;
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
1595 example).
1598 static char *
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;
1603 int result = 0;
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);
1611 if (begp <= endp)
1613 char *expansion = expand_argument (begp, endp+1);
1615 result = strlen (expansion);
1616 free (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;
1625 if (*argv)
1627 char *expansion = expand_argument (*argv, NULL);
1629 o = variable_buffer_output (o, expansion, strlen (expansion));
1631 free (expansion);
1634 return o;
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
1648 (short-circuiting).
1651 static char *
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;
1658 char *expansion;
1659 int result = 0;
1661 /* Find the result of the condition: if it's false keep going. */
1663 strip_whitespace (&begp, &endp);
1665 if (begp > endp)
1666 continue;
1668 expansion = expand_argument (begp, endp+1);
1669 result = strlen (expansion);
1671 /* If the result is false keep going. */
1672 if (!result)
1674 free (expansion);
1675 continue;
1678 /* It's true! Keep this result and return. */
1679 o = variable_buffer_output (o, expansion, result);
1680 free (expansion);
1681 break;
1684 return o;
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
1698 (short-circuiting).
1701 static char *
1702 func_and (char *o, char **argv, const char *funcname UNUSED)
1704 char *expansion;
1705 int result;
1707 while (1)
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);
1714 if (begp > endp)
1715 return o;
1717 expansion = expand_argument (begp, endp+1);
1718 result = strlen (expansion);
1720 /* If the result is false, stop here: we're done. */
1721 if (!result)
1722 break;
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! */
1727 if (*(++argv))
1728 free (expansion);
1729 else
1731 o = variable_buffer_output (o, expansion, result);
1732 break;
1736 free (expansion);
1738 return o;
1741 static char *
1742 func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1744 #ifdef _AMIGA
1745 o = wildcard_expansion (argv[0], o);
1746 #else
1747 char *p = string_glob (argv[0]);
1748 o = variable_buffer_output (o, p, strlen (p));
1749 #endif
1750 return o;
1754 $(eval <makefile string>)
1756 Always resolves to the empty string.
1758 Treat the arguments as a segment of makefile, and parse them.
1761 static char *
1762 func_eval (char *o, char **argv, const char *funcname UNUSED)
1764 char *buf;
1765 unsigned int len;
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]);
1774 #else
1775 eval_buffer (argv[0], strchr (argv[0], '\0'));
1776 #endif
1778 restore_variable_buffer (buf, len);
1780 return o;
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. */
1787 static char *
1788 func_evalctx (char *o, char **argv, const char *funcname UNUSED)
1790 char *buf;
1791 unsigned int len;
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);
1806 return o;
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. */
1812 static char *
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]));
1817 if (v)
1819 char *buf;
1820 unsigned int len;
1821 int var_ctx;
1822 size_t off;
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");
1837 if (var_ctx)
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;
1846 if (var_ctx)
1847 pop_variable_scope ();
1848 restore_variable_buffer (buf, len);
1851 return o;
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. */
1857 static char *
1858 func_eval_optimize_variable (char *o, char **argv, const char *funcname)
1860 unsigned int i;
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)
1867 # else
1868 if (v && !v->origin != o_automatic)
1869 # endif
1871 char *eos, *src;
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);
1879 if (src)
1881 unsigned char ch = '\0';
1882 char *dst = src;
1885 /* drop blanks preceeding the comment */
1886 while (dst > v->value)
1888 ch = (unsigned char)dst[-1];
1889 if (!isblank (ch))
1890 break;
1891 dst--;
1894 /* advance SRC to eol / eos. */
1895 src = memchr (src, '\n', eos - src);
1896 if (!src)
1897 break;
1899 /* drop a preceeding newline if possible (full line comment) */
1900 if (dst > v->value && dst[-1] == '\n')
1901 dst--;
1903 /* copy till next comment or eol. */
1904 while (src < eos)
1906 ch = *src++;
1907 if (ch == '#')
1908 break;
1909 *dst++ = ch;
1912 while (ch == '#' && src < eos);
1914 *dst = '\0';
1915 v->value_length = dst - v->value;
1918 else if (v)
1919 error (NILF, _("$(%s ): variable `%s' is of the wrong type\n"), funcname, v->name);
1922 return o;
1925 #endif /* CONFIG_WITH_EVALPLUS */
1927 static char *
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. */
1934 if (v)
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);
1940 #else
1941 o = variable_buffer_output (o, v->value, strlen(v->value));
1942 #endif
1944 return o;
1948 \r is replaced on UNIX as well. Is this desirable?
1950 static void
1951 fold_newlines (char *buffer, unsigned int *length)
1953 char *dst = buffer;
1954 char *src = buffer;
1955 char *last_nonnl = buffer -1;
1956 src[*length] = 0;
1957 for (; *src != '\0'; ++src)
1959 if (src[0] == '\r' && src[1] == '\n')
1960 continue;
1961 if (*src == '\n')
1963 *dst++ = ' ';
1965 else
1967 last_nonnl = dst;
1968 *dst++ = *src;
1971 *(++last_nonnl) = '\0';
1972 *length = last_nonnl - buffer;
1977 int shell_function_pid = 0, shell_function_completed;
1980 #ifdef WINDOWS32
1981 /*untested*/
1983 #include <windows.h>
1984 #include <io.h>
1985 #include "sub_proc.h"
1988 void
1989 windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1991 SECURITY_ATTRIBUTES saAttr;
1992 HANDLE hIn;
1993 HANDLE hErr;
1994 HANDLE hChildOutRd;
1995 HANDLE hChildOutWr;
1996 HANDLE hProcess;
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(),
2006 &hIn,
2008 TRUE,
2009 DUPLICATE_SAME_ACCESS) == FALSE) {
2010 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
2011 GetLastError());
2014 if (DuplicateHandle(GetCurrentProcess(),
2015 GetStdHandle(STD_ERROR_HANDLE),
2016 GetCurrentProcess(),
2017 &hErr,
2019 TRUE,
2020 DUPLICATE_SAME_ACCESS) == FALSE) {
2021 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
2022 GetLastError());
2025 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
2026 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
2028 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
2030 if (!hProcess)
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);
2048 } else {
2049 /* reap/cleanup the failed process */
2050 process_cleanup(hProcess);
2052 /* close handles which were duplicated, they weren't used */
2053 CloseHandle(hIn);
2054 CloseHandle(hErr);
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;
2062 *pid_p = -1;
2065 #endif
2068 #ifdef __MSDOS__
2069 FILE *
2070 msdos_openpipe (int* pipedes, int *pidp, char *text)
2072 FILE *fpipe=0;
2073 /* MSDOS can't fork, but it has `popen'. */
2074 struct variable *sh = lookup_variable ("SHELL", 5);
2075 int e;
2076 extern int dos_command_running, dos_status;
2078 /* Make sure not to bother processing an empty line. */
2079 while (isblank ((unsigned char)*text))
2080 ++text;
2081 if (*text == '\0')
2082 return 0;
2084 if (sh)
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);
2090 putenv (buf);
2093 e = errno;
2094 errno = 0;
2095 dos_command_running = 1;
2096 dos_status = 0;
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)
2104 pipedes[0] = -1;
2105 *pidp = -1;
2106 if (dos_status)
2107 errno = EINTR;
2108 else if (errno == 0)
2109 errno = ENOMEM;
2110 shell_function_completed = -1;
2112 else
2114 pipedes[0] = fileno (fpipe);
2115 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
2116 errno = e;
2117 shell_function_completed = 1;
2119 return fpipe;
2121 #endif
2124 Do shell spawning, with the naughty bits for different OSes.
2127 #ifdef VMS
2129 /* VMS can't do $(shell ...) */
2130 #define func_shell 0
2132 #else
2133 #ifndef _AMIGA
2134 static char *
2135 func_shell (char *o, char **argv, const char *funcname UNUSED)
2137 char *batch_filename = NULL;
2139 #ifdef __MSDOS__
2140 FILE *fpipe;
2141 #endif
2142 char **command_argv;
2143 const char *error_prefix;
2144 char **envp;
2145 int pipedes[2];
2146 int pid;
2148 #ifndef __MSDOS__
2149 /* Construct the argument list. */
2150 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2151 &batch_filename);
2152 if (command_argv == 0)
2153 return o;
2154 #endif
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);
2168 envp = environ;
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);
2175 error_prefix = p;
2177 else
2178 error_prefix = "";
2180 #if defined(__MSDOS__)
2181 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
2182 if (pipedes[0] < 0)
2184 perror_with_name (error_prefix, "pipe");
2185 return o;
2187 #elif defined(WINDOWS32)
2188 windows32_openpipe (pipedes, &pid, command_argv, envp);
2189 if (pipedes[0] < 0)
2191 /* open of the pipe failed, mark as failed execution */
2192 shell_function_completed = -1;
2194 return o;
2196 else
2197 #else
2198 if (pipe (pipedes) < 0)
2200 perror_with_name (error_prefix, "pipe");
2201 return o;
2204 # ifdef __EMX__
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);
2210 if (pid < 0)
2211 perror_with_name (error_prefix, "spawn");
2212 # else /* ! __EMX__ */
2213 pid = vfork ();
2214 if (pid < 0)
2215 perror_with_name (error_prefix, "fork");
2216 else if (pid == 0)
2217 child_execute_job (0, pipedes[1], command_argv, envp);
2218 else
2219 # endif
2220 #endif
2222 /* We are the parent. */
2223 char *buffer;
2224 unsigned int maxlen, i;
2225 int cc;
2227 /* Record the PID for reap_children. */
2228 shell_function_pid = pid;
2229 #ifndef __MSDOS__
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)
2239 # endif
2240 close (pipedes[1]);
2241 #endif
2243 /* Set up and read from the pipe. */
2245 maxlen = 200;
2246 buffer = xmalloc (maxlen + 1);
2248 /* Read from the pipe until it gets EOF. */
2249 for (i = 0; ; i += cc)
2251 if (i == maxlen)
2253 maxlen += 512;
2254 buffer = xrealloc (buffer, maxlen + 1);
2257 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
2258 if (cc <= 0)
2259 break;
2261 buffer[i] = '\0';
2263 /* Close the read side of the pipe. */
2264 #ifdef __MSDOS__
2265 if (fpipe)
2266 (void) pclose (fpipe);
2267 #else
2268 # ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
2269 if (pipedes[0] != -1)
2270 # endif
2271 (void) close (pipedes[0]);
2272 #endif
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"),
2281 batch_filename));
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);
2296 fflush (stderr);
2298 else
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);
2306 free (buffer);
2309 return o;
2312 #else /* _AMIGA */
2314 /* Do the Amiga version of func_shell. */
2316 static char *
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>
2331 BPTR child_stdout;
2332 char tmp_output[FILENAME_MAX];
2333 unsigned int maxlen = 200, i;
2334 int cc;
2335 char * buffer, * ptr;
2336 char ** aptr;
2337 int len = 0;
2338 char* batch_filename = NULL;
2340 /* Construct the argument list. */
2341 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2342 &batch_filename);
2343 if (command_argv == 0)
2344 return o;
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
2349 with it. */
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);
2358 ptr = buffer;
2360 for (aptr=command_argv; *aptr; aptr++)
2362 strcpy (ptr, *aptr);
2363 ptr += strlen (ptr) + 1;
2364 *ptr ++ = ' ';
2365 *ptr = 0;
2368 ptr[-1] = '\n';
2370 Execute (buffer, NULL, child_stdout);
2371 free (buffer);
2373 Close (child_stdout);
2375 child_stdout = Open (tmp_output, MODE_OLDFILE);
2377 buffer = xmalloc (maxlen);
2378 i = 0;
2381 if (i == maxlen)
2383 maxlen += 512;
2384 buffer = xrealloc (buffer, maxlen + 1);
2387 cc = Read (child_stdout, &buffer[i], maxlen - i);
2388 if (cc > 0)
2389 i += cc;
2390 } while (cc > 0);
2392 Close (child_stdout);
2394 fold_newlines (buffer, &i);
2395 o = variable_buffer_output (o, buffer, i);
2396 free (buffer);
2397 return o;
2399 #endif /* _AMIGA */
2400 #endif /* !VMS */
2402 #ifdef EXPERIMENTAL
2405 equality. Return is string-boolean, ie, the empty string is false.
2407 static char *
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);
2412 return o;
2417 string-boolean not operator.
2419 static char *
2420 func_not (char *o, char **argv, const char *funcname UNUSED)
2422 const char *s = argv[0];
2423 int result = 0;
2424 while (isspace ((unsigned char)*s))
2425 s++;
2426 result = ! (*s);
2427 o = variable_buffer_output (o, result ? "1" : "", result);
2428 return o;
2430 #endif
2432 #ifdef CONFIG_WITH_STRING_FUNCTIONS
2434 $(length string)
2436 XXX: This doesn't take multibyte locales into account.
2438 static char *
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);
2446 $(length-var var)
2448 XXX: This doesn't take multibyte locales into account.
2450 static char *
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. */
2458 static char *
2459 helper_pad (char *o, size_t to_add, const char *pad, size_t pad_len)
2461 while (to_add > 0)
2463 size_t size = to_add > pad_len ? pad_len : to_add;
2464 o = variable_buffer_output (o, pad, size);
2465 to_add -= size;
2467 return o;
2471 $(insert in, str[, n[, length[, pad]]])
2473 XXX: This doesn't take multibyte locales into account.
2475 static char *
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);
2482 math_int n = 0;
2483 math_int length = str_len;
2484 const char *pad = " ";
2485 size_t pad_len = 16;
2486 size_t i;
2488 if (argv[2] != NULL)
2490 n = math_int_from_string (argv[2]);
2491 if (n > 0)
2492 n--; /* one-origin */
2493 else if (n == 0)
2494 n = str_len; /* append */
2495 else
2496 { /* n < 0: from the end */
2497 n = str_len + n;
2498 if (n < 0)
2499 n = 0;
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++)
2514 /* nothing */;
2515 if (tmp[i] != '\0')
2517 pad = argv[4];
2518 pad_len = strlen (pad);
2520 /* else: it was all default spaces. */
2525 /* the head of the original string */
2526 if (n > 0)
2528 if (n <= str_len)
2529 o = variable_buffer_output (o, str, n);
2530 else
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);
2540 else
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 */
2547 if (n < str_len)
2548 o = variable_buffer_output (o, str + n, str_len - n);
2550 return o;
2554 $(pos needle, haystack[, start])
2555 $(lastpos needle, haystack[, start])
2557 XXX: This doesn't take multibyte locales into account.
2559 static char *
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);
2566 math_int start = 0;
2567 const char *hit;
2569 if (argv[2] != NULL)
2571 start = math_int_from_string (argv[2]);
2572 if (start > 0)
2573 start--; /* one-origin */
2574 else if (start < 0)
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')
2584 { /* pos */
2585 if (needle_len == 1)
2586 hit = strchr (haystack + start, *needle);
2587 else
2588 hit = strstr (haystack + start, needle);
2590 else
2591 { /* last pos */
2592 int ch = *needle;
2593 size_t off = start + 1;
2595 hit = NULL;
2596 while (off-- > 0)
2598 if ( haystack[off] == ch
2599 && ( needle_len == 1
2600 || strncmp (&haystack[off], needle, needle_len) == 0))
2602 hit = haystack + off;
2603 break;
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.
2616 static char *
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;
2624 size_t pad_len = 0;
2626 if (argv[2] != NULL)
2628 if (argv[3] != NULL)
2630 pad = argv[3];
2631 for (pad_len = 0; pad[pad_len] == ' '; pad_len++)
2632 /* nothing */;
2633 if (pad[pad_len] != '\0')
2634 pad_len = strlen (pad);
2635 else
2637 pad = " ";
2638 pad_len = 16;
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]);
2644 if (length == 0)
2645 return o;
2648 /* adjust start and length. */
2649 if (pad == NULL)
2651 if (start > 0)
2653 start--; /* one-origin */
2654 if (start >= str_len)
2655 return o;
2656 if (length == 0 || start + length > str_len)
2657 length = str_len - start;
2659 else
2661 start = str_len + start;
2662 if (start <= 0)
2664 start += length;
2665 if (start <= 0)
2666 return o;
2667 length = start;
2668 start = 0;
2670 else if (length == 0 || start + length > str_len)
2671 length = str_len - start;
2674 o = variable_buffer_output (o, str + start, length);
2676 else
2678 if (start > 0)
2680 start--; /* one-origin */
2681 if (start >= str_len)
2682 return length ? helper_pad (o, length, pad, pad_len) : o;
2683 if (length == 0)
2684 length = str_len - start;
2686 else
2688 start = str_len + start;
2689 if (start <= 0)
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);
2696 if (length == 0)
2697 length = str_len - start;
2699 if (start + length <= str_len)
2700 o = variable_buffer_output (o, str + start, length);
2701 else
2703 o = variable_buffer_output (o, str + start, str_len - start);
2704 o = helper_pad (o, start + length - str_len, pad, pad_len);
2708 return o;
2712 $(translate string, from-set[, to-set[, pad-char]])
2714 XXX: This doesn't take multibyte locales into account.
2716 static char *
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];
2723 int i;
2724 char ch;
2726 /* init the array. */
2727 for (i = 0; i < (1 << CHAR_BIT); i++)
2728 trans_tab[i] = i;
2730 while ( (i = *from_set) != '\0'
2731 && (ch = *to_set) != '\0')
2733 trans_tab[i] = ch;
2734 from_set++;
2735 to_set++;
2738 if (i != '\0')
2740 ch = '\0'; /* no padding == remove char */
2741 if (argv[2] != NULL && argv[3] != NULL)
2743 ch = argv[3][0];
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 */
2747 ch = ' ';
2749 while ((i = *from_set++) != '\0')
2750 trans_tab[i] = ch;
2753 /* do the translation */
2754 while ((i = *str++) != '\0')
2756 ch = trans_tab[i];
2757 if (ch)
2758 o = variable_buffer_output (o, &ch, 1);
2761 return o;
2763 #endif /* CONFIG_WITH_STRING_FUNCTIONS */
2765 #ifdef CONFIG_WITH_LAZY_DEPS_VARS
2767 /* This is also in file.c (bad). */
2768 # if VMS
2769 # define FILE_LIST_SEPARATOR ','
2770 # else
2771 # define FILE_LIST_SEPARATOR ' '
2772 # endif
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. */
2782 static char *
2783 func_deps (char *o, char **argv, const char *funcname)
2785 unsigned int idx = 0;
2786 struct file *file;
2788 /* Handle the argument if present. */
2790 if (argv[1])
2792 char *p = argv[1];
2793 while (isspace ((unsigned int)*p))
2794 p++;
2795 if (*p != '\0')
2797 char *n;
2798 long l = strtol (p, &n, 0);
2799 while (isspace ((unsigned int)*n))
2800 n++;
2801 idx = l;
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]);
2810 if (file)
2812 struct dep *deps = funcname[4] != '\0' && file->org_deps
2813 ? file->org_deps : file->deps;
2814 struct dep *d;
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);
2833 #ifndef NO_ARCHIVES
2834 if (ar_name (c))
2836 c = strchr (c, '(') + 1;
2837 total_len += strlen (c);
2839 else
2840 #elif defined (CONFIG_WITH_STRCACHE2)
2841 total_len += strcache2_get_len (&file_strcache, c) + 1;
2842 #else
2843 total_len += strlen (c) + 1;
2844 #endif
2847 if (total_len)
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)
2857 unsigned int len;
2858 const char *c = dep_name (d);
2860 #ifndef NO_ARCHIVES
2861 if (ar_name (c))
2863 c = strchr (c, '(') + 1;
2864 len = strlen (c);
2866 else
2867 #elif defined (CONFIG_WITH_STRCACHE2)
2868 len = strcache2_get_len (&file_strcache, c) + 1;
2869 #else
2870 len = strlen (c) + 1;
2871 #endif
2872 o = variable_buffer_output (o, c, len);
2873 o[-1] = FILE_LIST_SEPARATOR;
2876 --o; /* nuke the last list separator */
2877 *o = '\0';
2880 else
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 */
2889 unsigned int len;
2890 const char *c = dep_name (d);
2892 #ifndef NO_ARCHIVES
2893 if (ar_name (c))
2895 c = strchr (c, '(') + 1;
2896 len = strlen (c) - 1;
2898 else
2899 #elif defined (CONFIG_WITH_STRCACHE2)
2900 len = strcache2_get_len (&file_strcache, c);
2901 #else
2902 len = strlen (c);
2903 #endif
2904 o = variable_buffer_output (o, c, len);
2905 break;
2911 return o;
2914 /* Implements $?.
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. */
2920 static char *
2921 func_deps_newer (char *o, char **argv, const char *funcname)
2923 unsigned int idx = 0;
2924 struct file *file;
2926 /* Handle the argument if present. */
2928 if (argv[1])
2930 char *p = argv[1];
2931 while (isspace ((unsigned int)*p))
2932 p++;
2933 if (*p != '\0')
2935 char *n;
2936 long l = strtol (p, &n, 0);
2937 while (isspace ((unsigned int)*n))
2938 n++;
2939 idx = l;
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]);
2948 if (file)
2950 struct dep *deps = file->deps;
2951 struct dep *d;
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);
2970 #ifndef NO_ARCHIVES
2971 if (ar_name (c))
2973 c = strchr (c, '(') + 1;
2974 total_len += strlen (c);
2976 else
2977 #elif defined (CONFIG_WITH_STRCACHE2)
2978 total_len += strcache2_get_len (&file_strcache, c) + 1;
2979 #else
2980 total_len += strlen (c) + 1;
2981 #endif
2984 if (total_len)
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)
2994 unsigned int len;
2995 const char *c = dep_name (d);
2997 #ifndef NO_ARCHIVES
2998 if (ar_name (c))
3000 c = strchr (c, '(') + 1;
3001 len = strlen (c);
3003 else
3004 #elif defined (CONFIG_WITH_STRCACHE2)
3005 len = strcache2_get_len (&file_strcache, c) + 1;
3006 #else
3007 len = strlen (c) + 1;
3008 #endif
3009 o = variable_buffer_output (o, c, len);
3010 o[-1] = FILE_LIST_SEPARATOR;
3013 --o; /* nuke the last list separator */
3014 *o = '\0';
3017 else
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 */
3026 unsigned int len;
3027 const char *c = dep_name (d);
3029 #ifndef NO_ARCHIVES
3030 if (ar_name (c))
3032 c = strchr (c, '(') + 1;
3033 len = strlen (c) - 1;
3035 else
3036 #elif defined (CONFIG_WITH_STRCACHE2)
3037 len = strcache2_get_len (&file_strcache, c);
3038 #else
3039 len = strlen (c);
3040 #endif
3041 o = variable_buffer_output (o, c, len);
3042 break;
3048 return o;
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. */
3057 static char *
3058 func_deps_order_only (char *o, char **argv, const char *funcname)
3060 unsigned int idx = 0;
3061 struct file *file;
3063 /* Handle the argument if present. */
3065 if (argv[1])
3067 char *p = argv[1];
3068 while (isspace ((unsigned int)*p))
3069 p++;
3070 if (*p != '\0')
3072 char *n;
3073 long l = strtol (p, &n, 0);
3074 while (isspace ((unsigned int)*n))
3075 n++;
3076 idx = l;
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]);
3085 if (file)
3087 struct dep *deps = file->deps;
3088 struct dep *d;
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);
3107 #ifndef NO_ARCHIVES
3108 if (ar_name (c))
3110 c = strchr (c, '(') + 1;
3111 total_len += strlen (c);
3113 else
3114 #elif defined (CONFIG_WITH_STRCACHE2)
3115 total_len += strcache2_get_len (&file_strcache, c) + 1;
3116 #else
3117 total_len += strlen (c) + 1;
3118 #endif
3121 if (total_len)
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)
3131 unsigned int len;
3132 const char *c = dep_name (d);
3134 #ifndef NO_ARCHIVES
3135 if (ar_name (c))
3137 c = strchr (c, '(') + 1;
3138 len = strlen (c);
3140 else
3141 #elif defined (CONFIG_WITH_STRCACHE2)
3142 len = strcache2_get_len (&file_strcache, c) + 1;
3143 #else
3144 len = strlen (c) + 1;
3145 #endif
3146 o = variable_buffer_output (o, c, len);
3147 o[-1] = FILE_LIST_SEPARATOR;
3150 --o; /* nuke the last list separator */
3151 *o = '\0';
3154 else
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 */
3163 unsigned int len;
3164 const char *c = dep_name (d);
3166 #ifndef NO_ARCHIVES
3167 if (ar_name (c))
3169 c = strchr (c, '(') + 1;
3170 len = strlen (c) - 1;
3172 else
3173 #elif defined (CONFIG_WITH_STRCACHE2)
3174 len = strcache2_get_len (&file_strcache, c);
3175 #else
3176 len = strlen (c);
3177 #endif
3178 o = variable_buffer_output (o, c, len);
3179 break;
3185 return o;
3187 #endif /* CONFIG_WITH_LAZY_DEPS_VARS */
3190 #ifdef CONFIG_WITH_DEFINED
3191 /* Similar to ifdef. */
3192 static char *
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);
3198 return o;
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 ('/'). */
3205 #ifdef KMK
3206 char *
3207 #else
3208 static char *
3209 #endif
3210 abspath (const char *name, char *apath)
3212 char *dest;
3213 const char *start, *end, *apath_limit;
3215 if (name[0] == '\0' || apath == NULL)
3216 return NULL;
3218 #ifdef WINDOWS32 /* bird */
3219 dest = w32ify((char *)name, 1);
3220 if (!dest)
3221 return NULL;
3223 size_t len = strlen(dest);
3224 memcpy(apath, dest, len);
3225 dest = apath + len;
3228 (void)end; (void)start; (void)apath_limit;
3230 #elif defined __OS2__ /* bird */
3231 if (_abspath(apath, name, GET_PATH_MAX))
3232 return NULL;
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] == ':')
3243 /* drive spec */
3244 apath[0] = toupper(name[0]);
3245 apath[1] = ':';
3246 apath[2] = '/';
3247 name += 2;
3249 else
3250 #endif /* HAVE_DOS_PATHS */
3251 if (name[0] != '/')
3253 /* It is unlikely we would make it until here but just to make sure. */
3254 if (!starting_directory)
3255 return NULL;
3257 strcpy (apath, starting_directory);
3259 dest = strchr (apath, '\0');
3261 else
3263 apath[0] = '/';
3264 dest = apath + 1;
3267 for (start = end = name; *start != '\0'; start = end)
3269 unsigned long len;
3271 /* Skip sequence of multiple path-separators. */
3272 while (*start == '/')
3273 ++start;
3275 /* Find end of path component. */
3276 for (end = start; *end != '\0' && *end != '/'; ++end)
3279 len = end - start;
3281 if (len == 0)
3282 break;
3283 else if (len == 1 && start[0] == '.')
3284 /* nothing */;
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] != '/');
3291 else
3293 if (dest[-1] != '/')
3294 *dest++ = '/';
3296 if (dest + len >= apath_limit)
3297 return NULL;
3299 dest = memcpy (dest, start, len);
3300 dest += len;
3301 *dest = '\0';
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] == '/')
3309 #else
3310 if (dest > apath + 1 && dest[-1] == '/')
3311 #endif
3312 --dest;
3314 *dest = '\0';
3316 return apath;
3320 static char *
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;
3326 int doneany = 0;
3327 unsigned int len = 0;
3328 PATH_VAR (in);
3329 PATH_VAR (out);
3331 while ((path = find_next_token (&p, &len)) != 0)
3333 if (len < GET_PATH_MAX)
3335 strncpy (in, path, len);
3336 in[len] = '\0';
3338 if (
3339 #ifdef HAVE_REALPATH
3340 realpath (in, out)
3341 #else
3342 abspath (in, out)
3343 #endif
3346 o = variable_buffer_output (o, out, strlen (out));
3347 o = variable_buffer_output (o, " ", 1);
3348 doneany = 1;
3353 /* Kill last space. */
3354 if (doneany)
3355 --o;
3357 return o;
3360 static char *
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;
3366 int doneany = 0;
3367 unsigned int len = 0;
3368 PATH_VAR (in);
3369 PATH_VAR (out);
3371 while ((path = find_next_token (&p, &len)) != 0)
3373 if (len < GET_PATH_MAX)
3375 strncpy (in, path, len);
3376 in[len] = '\0';
3378 if (abspath (in, out))
3380 o = variable_buffer_output (o, out, strlen (out));
3381 o = variable_buffer_output (o, " ", 1);
3382 doneany = 1;
3387 /* Kill last space. */
3388 if (doneany)
3389 --o;
3391 return o;
3394 #ifdef CONFIG_WITH_ABSPATHEX
3395 /* Same as abspath except that the current path may be given as the
3396 2nd argument. */
3397 static char *
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))
3405 cwd++;
3406 if (!*cwd)
3407 o = func_abspath (o, argv, funcname);
3408 else
3410 /* Expand the argument. */
3411 const char *p = argv[0];
3412 unsigned int cwd_len = ~0U;
3413 char *path = 0;
3414 int doneany = 0;
3415 unsigned int len = 0;
3416 PATH_VAR (in);
3417 PATH_VAR (out);
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)
3425 #else
3426 if (path[0] != '/' && cwd)
3427 #endif
3429 /* relative path, prefix with cwd. */
3430 if (cwd_len == ~0U)
3431 cwd_len = strlen (cwd);
3432 if (cwd_len + len + 1 >= GET_PATH_MAX)
3433 continue;
3434 memcpy (in, cwd, cwd_len);
3435 in[cwd_len] = '/';
3436 memcpy (in + cwd_len + 1, path, len);
3437 in[cwd_len + len + 1] = '\0';
3439 else
3441 /* absolute path pass it as-is. */
3442 memcpy (in, path, len);
3443 in[len] = '\0';
3446 if (abspath (in, out))
3448 o = variable_buffer_output (o, out, strlen (out));
3449 o = variable_buffer_output (o, " ", 1);
3450 doneany = 1;
3455 /* Kill last space. */
3456 if (doneany)
3457 --o;
3460 return o;
3462 #endif
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
3483 cause fatal errors.
3485 Typical usage is:
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
3492 writing rules. */
3493 static char *
3494 func_xargs (char *o, char **argv, const char *funcname UNUSED)
3496 int argc;
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;
3503 const char *args;
3504 size_t max_args;
3505 int i;
3507 #ifdef ARG_MAX
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
3512 #endif
3514 argc = 0;
3515 while (argv[argc])
3516 argc++;
3517 if (argc > 4)
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))
3523 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))
3529 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;
3536 else
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))
3545 final_cmd++;
3546 if (*final_cmd)
3548 final_cmd_len = strlen (final_cmd);
3549 if (final_cmd_len > max_args)
3550 max_args = final_cmd_len;
3552 else
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. */
3568 i = 0;
3569 for (i = 0; ; i++)
3571 unsigned int len;
3572 const char *iterator = args;
3573 const char *end = args;
3574 const char *cur;
3575 const char *tmp;
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)
3580 end = cur + len;
3581 if (cur && end == args)
3582 fatal (NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
3584 /* emit the command. */
3585 if (i == 0)
3587 o = variable_buffer_output (o, (char *)initial_cmd, initial_cmd_len);
3588 o = variable_buffer_output (o, " ", 1);
3590 else if (cur)
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);
3596 else
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);
3603 tmp = end;
3604 while (tmp > args && isspace ((unsigned char)tmp[-1])) /* drop trailing spaces. */
3605 tmp--;
3606 o = variable_buffer_output (o, (char *)args, tmp - args);
3609 /* next */
3610 if (!cur)
3611 break;
3612 args = end;
3613 while (isspace ((unsigned char)*args))
3614 args++;
3617 return o;
3619 #endif
3621 #ifdef CONFIG_WITH_TOUPPER_TOLOWER
3622 static char *
3623 func_toupper_tolower (char *o, char **argv, const char *funcname)
3625 /* Expand the argument. */
3626 const char *p = argv[0];
3627 while (*p)
3629 /* convert to temporary buffer */
3630 char tmp[256];
3631 unsigned int i;
3632 if (!strcmp(funcname, "toupper"))
3633 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
3634 tmp[i] = toupper(*p);
3635 else
3636 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
3637 tmp[i] = tolower(*p);
3638 o = variable_buffer_output (o, tmp, i);
3641 return o;
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. */
3648 static const char *
3649 comp_cmds_strip_leading (const char *s, const char *e)
3651 while (s < e)
3653 const char ch = *s;
3654 if (!isblank (ch)
3655 && ch != '@'
3656 #ifdef CONFIG_WITH_COMMANDS_FUNC
3657 && ch != '%'
3658 #endif
3659 && ch != '+'
3660 && ch != '-')
3661 break;
3662 s++;
3664 return s;
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. */
3670 static char *
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));
3678 else
3680 const char * const s1_start = s1;
3681 int new_cmd = 1;
3682 int diff;
3683 for (;;)
3685 /* if it's a new command, strip leading stuff. */
3686 if (new_cmd)
3688 s1 = comp_cmds_strip_leading (s1, e1);
3689 s2 = comp_cmds_strip_leading (s2, e2);
3690 new_cmd = 0;
3692 if (s1 >= e1 || s2 >= e2)
3693 break;
3696 * Inner compare loop which compares one line.
3697 * FIXME: parse quoting!
3699 for (;;)
3701 const char ch1 = *s1;
3702 const char ch2 = *s2;
3703 diff = ch1 - ch2;
3704 if (diff)
3705 break;
3706 if (ch1 == '\n')
3707 break;
3708 assert (ch1 != '\r');
3710 /* next */
3711 s1++;
3712 s2++;
3713 if (s1 >= e1 || s2 >= e2)
3714 break;
3718 * If we exited because of a difference try to end-of-command
3719 * comparision, e.g. ignore trailing spaces.
3721 if (diff)
3723 /* strip */
3724 while (s1 < e1 && isblank (*s1))
3725 s1++;
3726 while (s2 < e2 && isblank (*s2))
3727 s2++;
3728 if (s1 >= e1 || s2 >= e2)
3729 break;
3731 /* compare again and check that it's a newline. */
3732 if (*s2 != '\n' || *s1 != '\n')
3733 break;
3735 /* Break out if we exited because of EOS. */
3736 else if (s1 >= e1 || s2 >= e2)
3737 break;
3740 * Detect the end of command lines.
3742 if (*s1 == '\n')
3743 new_cmd = s1 == s1_start || s1[-1] != '\\';
3744 s1++;
3745 s2++;
3749 * Ignore trailing empty lines.
3751 if (s1 < e1 || s2 < e2)
3753 while (s1 < e1 && (isblank (*s1) || *s1 == '\n'))
3754 if (*s1++ == '\n')
3755 s1 = comp_cmds_strip_leading (s1, e1);
3756 while (s2 < e2 && (isblank (*s2) || *s2 == '\n'))
3757 if (*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... */
3764 else
3765 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
3767 return o;
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
3780 trailing spaces.
3782 comp-cmds will compare command by command, ignoring not only leading
3783 and trailing spaces on each line but also leading one leading '@',
3784 '-', '+' and '%'
3786 static char *
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;
3791 size_t l, l1, l2;
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 */
3796 if (var1 == var2)
3797 return variable_buffer_output (o, "", 0); /* eq */
3798 if (!var1 || !var2)
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 */
3809 s1 = var1->value;
3810 e1 = s1 + var1->value_length;
3811 while (isblank ((unsigned char) *s1))
3812 s1++;
3813 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
3814 e1--;
3816 s2 = var2->value;
3817 e2 = s2 + var2->value_length;
3818 while (isblank ((unsigned char) *s2))
3819 s2++;
3820 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
3821 e2--;
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 */
3831 s1 = var1->value;
3832 e1 = s1 + var1->value_length;
3833 while (isblank ((unsigned char) *s1))
3834 s1++;
3835 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
3836 e1--;
3838 s2 = var2->value;
3839 e2 = s2 + var2->value_length;
3840 while (isblank((unsigned char)*s2))
3841 s2++;
3842 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
3843 e2--;
3845 /* both empty after stripping? */
3846 if (s1 == e1 && s2 == e2)
3847 return variable_buffer_output (o, "", 0); /* eq */
3849 /* optimist. */
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;
3857 if (!x1 && !x2)
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. */
3867 if (!x1)
3868 s1 += l;
3869 else
3871 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
3872 if (!l)
3873 while (isblank ((unsigned char) *s1))
3874 s1++;
3875 e1 = strchr (s1, '\0');
3876 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
3877 e1--;
3880 if (!x2)
3881 s2 += l;
3882 else
3884 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
3885 if (!l)
3886 while (isblank ((unsigned char) *s2))
3887 s2++;
3888 e2 = strchr (s2, '\0');
3889 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
3890 e2--;
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);
3897 else
3898 o = variable_buffer_output (o, "", 1) - 1; /* eq */ /** @todo check why this was necessary back the... */
3899 if (a1)
3900 free (a1);
3901 if (a2)
3902 free (a2);
3903 return o;
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 '%'.
3916 static char *
3917 func_comp_cmds_ex (char *o, char **argv, const char *funcname)
3919 const char *s1, *e1, *s2, *e2;
3920 size_t l1, l2;
3922 /* the simple cases */
3923 s1 = argv[0];
3924 s2 = argv[1];
3925 if (s1 == s2)
3926 return variable_buffer_output (o, "", 0); /* eq */
3927 l1 = strlen (argv[0]);
3928 l2 = strlen (argv[1]);
3930 if ( l1 == l2
3931 && !memcmp (s1, s2, l1))
3932 return variable_buffer_output (o, "", 0); /* eq */
3934 /* ignore trailing and leading blanks */
3935 e1 = s1 + l1;
3936 s1 = comp_cmds_strip_leading (s1, e1);
3938 e2 = s2 + l2;
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);
3947 #endif
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";
3955 # endif
3956 /* Check if the string is all blanks or not. */
3957 static int
3958 all_blanks (const char *s)
3960 if (!s)
3961 return 1;
3962 while (isspace ((unsigned char)*s))
3963 s++;
3964 return *s == '\0';
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. */
3973 static char *
3974 func_date (char *o, char **argv, const char *funcname)
3976 char *p;
3977 char *buf;
3978 size_t buf_size;
3979 struct tm t;
3980 const char *format;
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]))
3987 format = argv[0];
3989 /* get the time. */
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);
4002 else
4004 time_t tval;
4005 time (&tval);
4006 if (!strcmp (funcname, "date-utc"))
4007 t = *gmtime (&tval);
4008 else
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. */
4014 buf_size = 64;
4015 buf = xmalloc (buf_size);
4016 while (strftime (buf, buf_size, format, &t) == 0)
4018 if (buf_size >= 4096)
4020 *buf = '\0';
4021 break;
4023 buf = xrealloc (buf, buf_size <<= 1);
4025 o = variable_buffer_output (o, buf, strlen (buf));
4026 free (buf);
4027 return o;
4029 #endif
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
4034 fails. */
4035 static char *
4036 func_file_size (char *o, char **argv, const char *funcname UNUSED)
4038 struct stat st;
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);
4043 #endif
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)
4051 struct stat st;
4052 # if defined(WINDOWS32) || defined(__OS2__)
4053 char *ext;
4054 char *slash;
4056 /* fix slashes first. */
4057 slash = file;
4058 while ((slash = strchr (slash, '\\')) != NULL)
4059 *slash++ = '/';
4061 /* straight */
4062 if (stat (file, &st) == 0
4063 && S_ISREG (st.st_mode))
4064 return 1;
4066 /* don't try add an extension if there already is one */
4067 ext = strchr (file, '\0');
4068 if (ext - file >= 4
4069 && ( !stricmp (ext - 4, ".exe")
4070 || !stricmp (ext - 4, ".cmd")
4071 || !stricmp (ext - 4, ".bat")
4072 || !stricmp (ext - 4, ".com")))
4073 return 0;
4075 /* try the extensions. */
4076 strcpy (ext, ".exe");
4077 if (stat (file, &st) == 0
4078 && S_ISREG (st.st_mode))
4079 return 1;
4081 strcpy (ext, ".cmd");
4082 if (stat (file, &st) == 0
4083 && S_ISREG (st.st_mode))
4084 return 1;
4086 strcpy (ext, ".bat");
4087 if (stat (file, &st) == 0
4088 && S_ISREG (st.st_mode))
4089 return 1;
4091 strcpy (ext, ".com");
4092 if (stat (file, &st) == 0
4093 && S_ISREG (st.st_mode))
4094 return 1;
4096 return 0;
4098 # else
4100 return access (file, X_OK) == 0
4101 && stat (file, &st) == 0
4102 && S_ISREG (st.st_mode);
4103 # endif
4106 /* Searches for the specified programs in the PATH and print
4107 their full location if found. Prints nothing if not found. */
4108 static char *
4109 func_which (char *o, char **argv, const char *funcname UNUSED)
4111 const char *path;
4112 struct variable *path_var;
4113 unsigned i;
4114 int first = 1;
4115 PATH_VAR (buf);
4117 path_var = lookup_variable ("PATH", 4);
4118 if (path_var)
4119 path = path_var->value;
4120 else
4121 path = ".";
4123 /* iterate input */
4124 for (i = 0; argv[i]; i++)
4126 unsigned int len;
4127 const char *iterator = argv[i];
4128 char *cur;
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)
4137 #endif
4140 if (len + 1 + 4 < GET_PATH_MAX) /* +4 for .exe */
4142 memcpy (buf, cur, len);
4143 buf[len] = '\0';
4144 if (func_which_test_x (buf))
4145 o = variable_buffer_output (o, buf, strlen (buf));
4148 else
4150 const char *comp = path;
4151 for (;;)
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);
4156 if (!comp_len)
4158 comp_len = 1;
4159 src = ".";
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))
4170 if (!first)
4171 o = variable_buffer_output (o, " ", 1);
4172 o = variable_buffer_output (o, buf, strlen (buf));
4173 first = 0;
4174 break;
4178 /* next */
4179 if (!end)
4180 break;
4181 comp = end + 1;
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
4196 '$(if-expr ,,)'. */
4197 static char *
4198 func_expr (char *o, char **argv, const char *funcname UNUSED)
4200 o = expr_eval_to_string (o, argv[0]);
4201 return o;
4204 /* Same as '$(if ,,)' except the first argument is evaluated
4205 using the same evaluator as for the new 'if' statements. */
4206 static char *
4207 func_if_expr (char *o, char **argv, const char *funcname UNUSED)
4209 int rc;
4210 char *to_expand;
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];
4216 if (*to_expand)
4217 variable_expand_string_2 (o, to_expand, -1, &o);
4219 return o;
4223 $(select when1-cond, when1-body[,whenN-cond, whenN-body]).
4225 static char *
4226 func_select (char *o, char **argv, const char *funcname UNUSED)
4228 int i;
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))
4242 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))
4248 end++;
4249 if (*end == ':')
4250 do end++;
4251 while (isspace ((unsigned char)*end));
4252 is_otherwise = *end == '\0';
4255 if ( is_otherwise
4256 || expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
4258 variable_expand_string_2 (o, argv[i + 1], -1, &o);
4259 break;
4263 return o;
4266 #endif /* CONFIG_WITH_IF_CONDITIONALS */
4268 #ifdef CONFIG_WITH_SET_CONDITIONALS
4269 static char *
4270 func_set_intersects (char *o, char **argv, const char *funcname UNUSED)
4272 const char *s1_cur;
4273 unsigned int s1_len;
4274 const char *s1_iterator = argv[0];
4276 while ((s1_cur = find_next_token (&s1_iterator, &s1_len)) != 0)
4278 const char *s2_cur;
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). */
4294 static char *
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 */);
4298 return o;
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.) */
4303 static char *
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) );
4310 if (stack_var)
4312 unsigned int len;
4313 const char *iterator = stack_var->value;
4314 char *lastitem = NULL;
4315 char *cur;
4317 while ((cur = find_next_token (&iterator, &len)))
4318 lastitem = cur;
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)
4326 *lastitem = '\0';
4327 while (lastitem > stack_var->value && isspace (lastitem[-1]))
4328 *--lastitem = '\0';
4329 #ifdef CONFIG_WITH_VALUE_LENGTH
4330 stack_var->value_length = lastitem - stack_var->value;
4331 #endif
4335 return o;
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. */
4341 static char *
4342 math_int_to_variable_buffer (char *o, math_int num)
4344 static const char xdigits[17] = "0123456789abcdef";
4345 int negative;
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];
4350 negative = num < 0;
4351 if (negative)
4352 num = -num;
4354 *str = '\0';
4358 #ifdef HEX_MATH_NUMBERS
4359 *--str = xdigits[num & 0xf];
4360 num >>= 4;
4361 #else
4362 *--str = xdigits[num % 10];
4363 num /= 10;
4364 #endif
4366 while (num);
4368 #ifdef HEX_MATH_NUMBERS
4369 *--str = 'x';
4370 *--str = '0';
4371 #endif
4373 if (negative)
4374 *--str = '-';
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. */
4383 static math_int
4384 math_int_from_string (const char *str)
4386 const char *start;
4387 unsigned base = 0;
4388 int negative = 0;
4389 math_int num = 0;
4391 /* strip spaces */
4392 while (isspace (*str))
4393 str++;
4394 if (!*str)
4396 error (NILF, _("bad number: empty\n"));
4397 return 0;
4399 start = str;
4401 /* check for +/- */
4402 while (*str == '+' || *str == '-' || isspace (*str))
4403 if (*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'))
4409 base = 16;
4410 str += 2;
4412 else
4414 /* look for a hex digit, if not found treat it as decimal */
4415 const char *p2 = str;
4416 for ( ; *p2; p2++)
4417 if (isxdigit (*p2) && !isdigit (*p2) && isascii (*p2) )
4419 base = 16;
4420 break;
4422 if (base == 0)
4423 base = 10;
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);
4431 return 0;
4434 /* convert it! */
4435 while (*str && !isspace (*str))
4437 int ch = *str++;
4438 if (ch >= '0' && ch <= '9')
4439 ch -= '0';
4440 else if (base == 16 && ch >= 'a' && ch <= 'f')
4441 ch -= 'a' - 10;
4442 else if (base == 16 && ch >= 'A' && ch <= 'F')
4443 ch -= 'A' - 10;
4444 else
4446 error (NILF, _("bad number: '%s' (base=%d, pos=%d)\n"), start, base, str - start);
4447 return 0;
4449 num *= base;
4450 num += ch;
4453 /* check trailing spaces. */
4454 while (isspace (*str))
4455 str++;
4456 if (*str)
4458 error (NILF, _("bad number: '%s'\n"), start);
4459 return 0;
4462 return negative ? -num : num;
4465 /* Add two or more integer numbers. */
4466 static char *
4467 func_int_add (char *o, char **argv, const char *funcname UNUSED)
4469 math_int num;
4470 int i;
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. */
4480 static char *
4481 func_int_sub (char *o, char **argv, const char *funcname UNUSED)
4483 math_int num;
4484 int i;
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. */
4494 static char *
4495 func_int_mul (char *o, char **argv, const char *funcname UNUSED)
4497 math_int num;
4498 int i;
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. */
4508 static char *
4509 func_int_div (char *o, char **argv, const char *funcname UNUSED)
4511 math_int num;
4512 math_int divisor;
4513 int i;
4515 num = math_int_from_string (argv[0]);
4516 for (i = 1; argv[i]; i++)
4518 divisor = math_int_from_string (argv[i]);
4519 if (!divisor)
4521 error (NILF, _("divide by zero ('%s')\n"), argv[i]);
4522 return math_int_to_variable_buffer (o, 0);
4524 num /= divisor;
4527 return math_int_to_variable_buffer (o, num);
4531 /* Divide and return the remainder. */
4532 static char *
4533 func_int_mod (char *o, char **argv, const char *funcname UNUSED)
4535 math_int num;
4536 math_int divisor;
4538 num = math_int_from_string (argv[0]);
4539 divisor = math_int_from_string (argv[1]);
4540 if (!divisor)
4542 error (NILF, _("divide by zero ('%s')\n"), argv[1]);
4543 return math_int_to_variable_buffer (o, 0);
4545 num %= divisor;
4547 return math_int_to_variable_buffer (o, num);
4550 /* 2-complement. */
4551 static char *
4552 func_int_not (char *o, char **argv, const char *funcname UNUSED)
4554 math_int num;
4556 num = math_int_from_string (argv[0]);
4557 num = ~num;
4559 return math_int_to_variable_buffer (o, num);
4562 /* Bitwise AND (two or more numbers). */
4563 static char *
4564 func_int_and (char *o, char **argv, const char *funcname UNUSED)
4566 math_int num;
4567 int i;
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). */
4577 static char *
4578 func_int_or (char *o, char **argv, const char *funcname UNUSED)
4580 math_int num;
4581 int i;
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). */
4591 static char *
4592 func_int_xor (char *o, char **argv, const char *funcname UNUSED)
4594 math_int num;
4595 int i;
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=""). */
4605 static char *
4606 func_int_cmp (char *o, char **argv, const char *funcname)
4608 math_int num1;
4609 math_int num2;
4610 int rc;
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"))
4617 rc = num1 == num2;
4618 else if (!strcmp (funcname, "ne"))
4619 rc = num1 != num2;
4620 else if (!strcmp (funcname, "gt"))
4621 rc = num1 > num2;
4622 else if (!strcmp (funcname, "ge"))
4623 rc = num1 >= num2;
4624 else if (!strcmp (funcname, "lt"))
4625 rc = num1 < num2;
4626 else /*if (!strcmp (funcname, "le"))*/
4627 rc = num1 <= num2;
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
4640 and similar. */
4641 static char *
4642 func_nanots (char *o, char **argv UNUSED, const char *funcname UNUSED)
4644 return math_int_to_variable_buffer (o, nano_timestamp ());
4646 #endif
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
4656 the variable. */
4657 static char *
4658 func_os2_libpath (char *o, char **argv, const char *funcname UNUSED)
4660 char buf[4096];
4661 ULONG fVar;
4662 APIRET rc;
4664 /* translate variable name (first arg) */
4665 if (!strcmp (argv[0], "BEGINLIBPATH"))
4666 fVar = BEGIN_LIBPATH;
4667 else if (!strcmp (argv[0], "ENDLIBPATH"))
4668 fVar = END_LIBPATH;
4669 else if (!strcmp (argv[0], "LIBPATHSTRICT"))
4670 fVar = LIBPATHSTRICT;
4671 else if (!strcmp (argv[0], "LIBPATH"))
4672 fVar = 0;
4673 else
4675 error (NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
4676 return variable_buffer_output (o, "", 0);
4679 if (!argv[1])
4681 /* get the variable value. */
4682 if (fVar != 0)
4684 buf[0] = buf[1] = buf[2] = buf[3] = '\0';
4685 rc = DosQueryExtLIBPATH (buf, fVar);
4687 else
4688 rc = DosQueryHeaderInfo (NULLHANDLE, 0, buf, sizeof(buf), QHINF_LIBPATH);
4689 if (rc != NO_ERROR)
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));
4696 else
4698 /* set the variable value. */
4699 size_t len;
4700 size_t len_max = sizeof (buf) < 2048 ? sizeof (buf) : 2048;
4701 const char *val;
4702 const char *end;
4704 if (fVar == 0)
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. */
4711 val = argv[1];
4712 while (isspace (*val))
4713 val++;
4714 end = strchr (val, '\0');
4715 while (end > val && isspace (end[-1]))
4716 end--;
4718 len = end - val;
4719 if (len >= len_max)
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);
4728 buf[len] = '\0';
4729 rc = DosSetExtLIBPATH (buf, fVar);
4730 if (rc != NO_ERROR)
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);
4738 return o;
4740 #endif /* CONFIG_WITH_OS2_LIBPATH */
4742 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
4743 /* Retrieve make statistics. */
4744 static char *
4745 func_make_stats (char *o, char **argv, const char *funcname UNUSED)
4747 char buf[512];
4748 int len;
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);
4760 #endif
4762 else
4764 /* selective */
4765 int i;
4766 for (i = 0; argv[i]; i++)
4768 unsigned long val;
4769 if (i != 0)
4770 o = variable_buffer_output (o, " ", 1);
4771 if (0)
4772 continue;
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;
4786 #endif
4787 else
4789 o = variable_buffer_output (o, argv[i], strlen (argv[i]));
4790 continue;
4793 len = sprintf (buf, "%ld", val);
4794 o = variable_buffer_output (o, buf, len);
4798 return o;
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. */
4819 char *
4820 func_commands (char *o, char **argv, const char *funcname)
4822 struct file *file;
4823 static int recursive = 0;
4825 if (recursive)
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);
4833 return o;
4835 recursive = 1;
4837 file = lookup_file (argv[0]);
4838 if (file && file->cmds)
4840 unsigned int i;
4841 int cmd_sep_len;
4842 struct commands *cmds = file->cmds;
4843 const char *cmd_sep;
4845 if (!strcmp (funcname, "commands"))
4847 cmd_sep = "\n";
4848 cmd_sep_len = 1;
4850 else if (!strcmp (funcname, "commands-sc"))
4852 cmd_sep = ";";
4853 cmd_sep_len = 1;
4855 else /*if (!strcmp (funcname, "commands-usr"))*/
4857 cmd_sep = argv[1];
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++)
4867 char *p;
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)
4872 continue;
4873 p = cmds->command_lines[i];
4874 while (isblank ((unsigned char)*p))
4875 p++;
4876 if (*p == '\0')
4877 continue;
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. */
4893 in = out = p;
4894 while ((ref = strchr (in, '$')) != 0)
4896 ++ref; /* Move past the $. */
4898 if (out != in)
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. */
4905 out += ref - in;
4906 in = ref;
4908 if (*ref == '(' || *ref == '{')
4910 char openparen = *ref;
4911 char closeparen = openparen == '(' ? ')' : '}';
4912 int count;
4913 char *p2;
4915 *out++ = *in++; /* Copy OPENPAREN. */
4916 /* IN now points past the opening paren or brace.
4917 Count parens or braces until it is matched. */
4918 count = 0;
4919 while (*in != '\0')
4921 if (*in == closeparen && --count < 0)
4922 break;
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. */
4929 int quoted = 0;
4930 for (p2 = in - 1; p2 > ref && *p2 == '\\'; --p2)
4931 quoted = !quoted;
4933 if (quoted)
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. */
4939 *out++ = *in++;
4940 else
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. */
4948 while (out > ref
4949 && isblank ((unsigned char)out[-1]))
4950 --out;
4952 /* Replace it all with a single space. */
4953 *out++ = ' ';
4956 else
4958 if (*in == openparen)
4959 ++count;
4961 *out++ = *in++;
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. */
4973 if (out != in)
4974 strcpy (out, in);
4976 /* --- copied from new_job() in job.c --- */
4978 /* Finally, expand the line. */
4979 if (i)
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. */
4984 p = o;
4985 while (isblank ((unsigned char)*o)
4986 || *o == '@'
4987 || *o == '-'
4988 || *o == '+')
4989 o++;
4990 if (*o != '\0' && *o != '%')
4991 o = strchr (o, '\0');
4992 else if (i)
4993 o = p - cmd_sep_len;
4994 else
4995 o = p;
4996 } /* for each command line */
4998 /* else FIXME: bitch about it? */
5000 recursive = 0;
5001 return o;
5003 #endif /* CONFIG_WITH_COMMANDS_FUNC */
5005 #ifdef KMK
5006 /* Useful when debugging kmk and/or makefiles. */
5007 char *
5008 func_breakpoint (char *o, char **argv UNUSED, const char *funcname UNUSED)
5010 #ifdef _MSC_VER
5011 __debugbreak();
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");
5015 #else
5016 char *p = (char *)0;
5017 *p = '\0';
5018 #endif
5019 return o;
5021 #endif /* KMK */
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
5028 table.
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},
5050 #endif
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},
5064 #endif
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},
5077 #endif
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},
5094 #endif
5095 #ifdef EXPERIMENTAL
5096 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
5097 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
5098 #endif
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},
5107 #endif
5108 #ifdef CONFIG_WITH_PRINTF
5109 { STRING_SIZE_TUPLE("printf"), 1, 0, 1, kmk_builtin_func_printf},
5110 #endif
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},
5116 #endif
5117 #ifdef CONFIG_WITH_DEFINED
5118 { STRING_SIZE_TUPLE("defined"), 1, 1, 1, func_defined},
5119 #endif
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},
5123 #endif
5124 #ifdef CONFIG_WITH_ABSPATHEX
5125 { STRING_SIZE_TUPLE("abspathex"), 0, 2, 1, func_abspathex},
5126 #endif
5127 #ifdef CONFIG_WITH_XARGS
5128 { STRING_SIZE_TUPLE("xargs"), 2, 0, 1, func_xargs},
5129 #endif
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},
5134 #endif
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},
5138 #endif
5139 #ifdef CONFIG_WITH_FILE_SIZE
5140 { STRING_SIZE_TUPLE("file-size"), 1, 1, 1, func_file_size},
5141 #endif
5142 #ifdef CONFIG_WITH_WHICH
5143 { STRING_SIZE_TUPLE("which"), 0, 0, 1, func_which},
5144 #endif
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},
5149 #endif
5150 #ifdef CONFIG_WITH_SET_CONDITIONALS
5151 { STRING_SIZE_TUPLE("intersects"), 2, 2, 1, func_set_intersects},
5152 #endif
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},
5158 #endif
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},
5175 #endif
5176 #ifdef CONFIG_WITH_NANOTS
5177 { STRING_SIZE_TUPLE("nanots"), 0, 0, 0, func_nanots},
5178 #endif
5179 #ifdef CONFIG_WITH_OS2_LIBPATH
5180 { STRING_SIZE_TUPLE("libpath"), 1, 2, 1, func_os2_libpath},
5181 #endif
5182 #if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5183 { STRING_SIZE_TUPLE("make-stats"), 0, 0, 0, func_make_stats},
5184 #endif
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},
5189 #endif
5190 #ifdef KMK_HELPERS
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},
5197 #endif
5198 #ifdef KMK
5199 { STRING_SIZE_TUPLE("breakpoint"), 0, 0, 0, func_breakpoint},
5200 #endif
5203 #define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
5206 /* These must come after the definition of function_table. */
5208 static char *
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. */
5221 if (!argc)
5222 return o;
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. */
5236 static int
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 == '(' ? ')' : '}';
5241 const char *beg;
5242 const char *end;
5243 int count = 0;
5244 char *abeg = NULL;
5245 char **argv, **argvp;
5246 int nargs;
5248 beg = *stringp + 1;
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)
5261 if (*end == ',')
5262 ++nargs;
5263 else if (*end == openparen)
5264 ++count;
5265 else if (*end == closeparen && --count < 0)
5266 break;
5268 if (count >= 0)
5269 fatal (*expanding_var,
5270 _("unterminated call to function `%s': missing `%c'"),
5271 entry_p->name, closeparen);
5273 *stringp = end;
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
5280 last argument.
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
5284 each argument. */
5286 if (entry_p->expand_args)
5288 const char *p;
5289 for (p=beg, nargs=0; p <= end; ++argvp)
5291 const char *next;
5293 ++nargs;
5295 if (nargs == entry_p->maximum_args
5296 || (! (next = find_next_argument (openparen, closeparen, p, end))))
5297 next = end;
5299 *argvp = expand_argument (p, next);
5300 p = next + 1;
5303 else
5305 int len = end - beg;
5306 char *p, *aend;
5308 abeg = xmalloc (len+1);
5309 memcpy (abeg, beg, len);
5310 abeg[len] = '\0';
5311 aend = abeg + len;
5313 for (p=abeg, nargs=0; p <= aend; ++argvp)
5315 char *next;
5317 ++nargs;
5319 if (nargs == entry_p->maximum_args
5320 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
5321 next = aend;
5323 *argvp = p;
5324 *next = '\0';
5325 p = next + 1;
5328 *argvp = NULL;
5330 /* Finally! Run the function... */
5331 *op = expand_builtin_function (*op, nargs, argv, entry_p);
5333 /* Free memory. */
5334 if (entry_p->expand_args)
5335 for (argvp=argv; *argvp != 0; ++argvp)
5336 free (*argvp);
5337 if (abeg)
5338 free (abeg);
5340 return 1;
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);
5349 if (!entry_p)
5350 return 0;
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);
5359 if (!entry_p)
5360 return 0;
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. */
5370 static char *
5371 func_call (char *o, char **argv, const char *funcname UNUSED)
5373 static int max_args = 0;
5374 char *fname;
5375 char *cp;
5376 char *body;
5377 int flen;
5378 int i;
5379 int saved_args;
5380 const struct function_table_entry *entry_p;
5381 struct variable *v;
5382 #ifdef CONFIG_WITH_EVALPLUS
5383 char *buf;
5384 unsigned int len;
5385 #endif
5386 #if defined (CONFIG_WITH_EVALPLUS) || defined (CONFIG_WITH_VALUE_LENGTH)
5387 char num[11];
5388 #endif
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. */
5392 fname = argv[0];
5393 while (*fname != '\0' && isspace ((unsigned char)*fname))
5394 ++fname;
5396 cp = fname + strlen (fname) - 1;
5397 while (cp > fname && isspace ((unsigned char)*cp))
5398 --cp;
5399 cp[1] = '\0';
5401 /* Calling nothing is a no-op */
5402 if (*fname == '\0')
5403 return o;
5405 /* Are we invoking a builtin function? */
5407 #ifndef CONFIG_WITH_VALUE_LENGTH
5408 entry_p = lookup_function (fname);
5409 #else
5410 entry_p = lookup_function (fname, cp - fname + 1);
5411 #endif
5412 if (entry_p)
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);
5426 if (v == 0)
5427 warn_undefined (fname, flen);
5429 if (v == 0 || *v->value == '\0')
5430 return o;
5432 body = alloca (flen + 4);
5433 body[0] = '$';
5434 body[1] = '(';
5435 memcpy (body + 2, fname, flen);
5436 body[flen+2] = ')';
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);
5446 #else
5448 char num[11];
5450 sprintf (num, "%d", i);
5451 define_variable (num, strlen (num), *argv, o_automatic, 0);
5453 #endif
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);
5461 #endif
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
5466 invocation. */
5468 for (; i < max_args; ++i)
5469 #ifdef CONFIG_WITH_VALUE_LENGTH
5470 define_variable (num, sprintf (num, "%d", i), "", o_automatic, 0);
5471 #else
5473 char num[11];
5475 sprintf (num, "%d", i);
5476 define_variable (num, strlen (num), "", o_automatic, 0);
5478 #endif
5480 saved_args = max_args;
5481 max_args = i;
5483 #ifdef CONFIG_WITH_EVALPLUS
5484 if (!strcmp (funcname, "call"))
5486 #endif
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);
5493 v->exp_count = 0;
5495 o += strlen (o);
5496 #else /* CONFIG_WITH_VALUE_LENGTH */
5497 variable_expand_string_2 (o, body, flen+3, &o);
5498 v->exp_count = 0;
5499 #endif /* CONFIG_WITH_VALUE_LENGTH */
5500 #ifdef CONFIG_WITH_EVALPLUS
5502 else
5504 const struct floc *reading_file_saved = reading_file;
5505 char *eos;
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;
5518 else
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);
5524 v->exp_count = 0;
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)
5538 if (v->recursive)
5540 v->exp_count = EXP_COUNT_MAX;
5541 variable_expand_string_2 (o, v->value, v->value_length, &o);
5542 v->exp_count = 0;
5544 else
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 ();
5554 return o;
5557 void
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)
5567 unsigned int i;
5568 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
5570 const char *fn = function_table_init[i].name;
5571 while (*fn)
5573 func_char_map[(int)*fn] = 1;
5574 fn++;
5576 assert (function_table_init[i].len <= MAX_FUNCTION_LENGTH);
5577 assert (function_table_init[i].len >= MIN_FUNCTION_LENGTH);
5580 #endif