source: trunk/src/kmk/function.c@ 2591

Last change on this file since 2591 was 2591, checked in by bird, 13 years ago

kmk: Merged in changes from GNU make 3.82. Previous GNU make base version was gnumake-2008-10-28-CVS.

  • Property svn:eol-style set to native
File size: 158.2 KB
Line 
1/* Builtin function expansion for GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
42010 Free Software Foundation, Inc.
5This file is part of GNU Make.
6
7GNU Make is free software; you can redistribute it and/or modify it under the
8terms of the GNU General Public License as published by the Free Software
9Foundation; either version 3 of the License, or (at your option) any later
10version.
11
12GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License along with
17this program. If not, see <http://www.gnu.org/licenses/>. */
18
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"
26
27#ifdef _AMIGA
28#include "amiga.h"
29#endif
30
31#ifdef WINDOWS32 /* bird */
32# include "pathstuff.h"
33#endif
34
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 */
47
48#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE) /* bird */
49# include <ctype.h>
50typedef big_int math_int;
51static char *math_int_to_variable_buffer (char *, math_int);
52static math_int math_int_from_string (const char *str);
53#endif
54
55#ifdef CONFIG_WITH_NANOTS /* bird */
56# ifdef WINDOWS32
57# include <Windows.h>
58# endif
59#endif
60
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>
68
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 */
79
80#ifdef KMK
81/** Checks if the @a_cch characters (bytes) in @a a_psz equals @a a_szConst. */
82# define STR_N_EQUALS(a_psz, a_cch, a_szConst) \
83 ( (a_cch) == sizeof (a_szConst) - 1 && !strncmp ((a_psz), (a_szConst), sizeof (a_szConst) - 1) )
84#endif
85
86
87struct function_table_entry
88 {
89 const char *name;
90 unsigned char len;
91 unsigned char minimum_args;
92 unsigned char maximum_args;
93 char expand_args;
94 char *(*func_ptr) (char *output, char **argv, const char *fname);
95 };
96
97static unsigned long
98function_table_entry_hash_1 (const void *keyv)
99{
100 const struct function_table_entry *key = keyv;
101 return_STRING_N_HASH_1 (key->name, key->len);
102}
103
104static unsigned long
105function_table_entry_hash_2 (const void *keyv)
106{
107 const struct function_table_entry *key = keyv;
108 return_STRING_N_HASH_2 (key->name, key->len);
109}
110
111static int
112function_table_entry_hash_cmp (const void *xv, const void *yv)
113{
114 const struct function_table_entry *x = xv;
115 const struct function_table_entry *y = yv;
116 int result = x->len - y->len;
117 if (result)
118 return result;
119 return_STRING_N_COMPARE (x->name, y->name, x->len);
120}
121
122static struct hash_table function_table;
123
124#ifdef CONFIG_WITH_MAKE_STATS
125long make_stats_allocations = 0;
126long make_stats_reallocations = 0;
127unsigned long make_stats_allocated = 0;
128unsigned long make_stats_ht_lookups = 0;
129unsigned long make_stats_ht_collisions = 0;
130#endif
131
132
133
134/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
135 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
136 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
137 nonzero, substitutions are done only on matches which are complete
138 whitespace-delimited words. */
139
140char *
141subst_expand (char *o, const char *text, const char *subst, const char *replace,
142 unsigned int slen, unsigned int rlen, int by_word)
143{
144 const char *t = text;
145 const char *p;
146
147 if (slen == 0 && !by_word)
148 {
149 /* The first occurrence of "" in any string is its end. */
150 o = variable_buffer_output (o, t, strlen (t));
151 if (rlen > 0)
152 o = variable_buffer_output (o, replace, rlen);
153 return o;
154 }
155
156 do
157 {
158 if (by_word && slen == 0)
159 /* When matching by words, the empty string should match
160 the end of each word, rather than the end of the whole text. */
161 p = end_of_token (next_token (t));
162 else
163 {
164 p = strstr (t, subst);
165 if (p == 0)
166 {
167 /* No more matches. Output everything left on the end. */
168 o = variable_buffer_output (o, t, strlen (t));
169 return o;
170 }
171 }
172
173 /* Output everything before this occurrence of the string to replace. */
174 if (p > t)
175 o = variable_buffer_output (o, t, p - t);
176
177 /* If we're substituting only by fully matched words,
178 or only at the ends of words, check that this case qualifies. */
179 if (by_word
180 && ((p > text && !isblank ((unsigned char)p[-1]))
181 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
182 /* Struck out. Output the rest of the string that is
183 no longer to be replaced. */
184 o = variable_buffer_output (o, subst, slen);
185 else if (rlen > 0)
186 /* Output the replacement string. */
187 o = variable_buffer_output (o, replace, rlen);
188
189 /* Advance T past the string to be replaced. */
190 t = p + slen;
191 } while (*t != '\0');
192
193 return o;
194}
195
196
197
198/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
199 and replacing strings matching PATTERN with REPLACE.
200 If PATTERN_PERCENT is not nil, PATTERN has already been
201 run through find_percent, and PATTERN_PERCENT is the result.
202 If REPLACE_PERCENT is not nil, REPLACE has already been
203 run through find_percent, and REPLACE_PERCENT is the result.
204 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
205 character _AFTER_ the %, not to the % itself.
206*/
207
208char *
209patsubst_expand_pat (char *o, const char *text,
210 const char *pattern, const char *replace,
211 const char *pattern_percent, const char *replace_percent)
212{
213 unsigned int pattern_prepercent_len, pattern_postpercent_len;
214 unsigned int replace_prepercent_len, replace_postpercent_len;
215 const char *t;
216 unsigned int len;
217 int doneany = 0;
218
219 /* Record the length of REPLACE before and after the % so we don't have to
220 compute these lengths more than once. */
221 if (replace_percent)
222 {
223 replace_prepercent_len = replace_percent - replace - 1;
224 replace_postpercent_len = strlen (replace_percent);
225 }
226 else
227 {
228 replace_prepercent_len = strlen (replace);
229 replace_postpercent_len = 0;
230 }
231
232 if (!pattern_percent)
233 /* With no % in the pattern, this is just a simple substitution. */
234 return subst_expand (o, text, pattern, replace,
235 strlen (pattern), strlen (replace), 1);
236
237 /* Record the length of PATTERN before and after the %
238 so we don't have to compute it more than once. */
239 pattern_prepercent_len = pattern_percent - pattern - 1;
240 pattern_postpercent_len = strlen (pattern_percent);
241
242 while ((t = find_next_token (&text, &len)) != 0)
243 {
244 int fail = 0;
245
246 /* Is it big enough to match? */
247 if (len < pattern_prepercent_len + pattern_postpercent_len)
248 fail = 1;
249
250 /* Does the prefix match? */
251 if (!fail && pattern_prepercent_len > 0
252 && (*t != *pattern
253 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
254 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
255 fail = 1;
256
257 /* Does the suffix match? */
258 if (!fail && pattern_postpercent_len > 0
259 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
260 || t[len - pattern_postpercent_len] != *pattern_percent
261 || !strneq (&t[len - pattern_postpercent_len],
262 pattern_percent, pattern_postpercent_len - 1)))
263 fail = 1;
264
265 if (fail)
266 /* It didn't match. Output the string. */
267 o = variable_buffer_output (o, t, len);
268 else
269 {
270 /* It matched. Output the replacement. */
271
272 /* Output the part of the replacement before the %. */
273 o = variable_buffer_output (o, replace, replace_prepercent_len);
274
275 if (replace_percent != 0)
276 {
277 /* Output the part of the matched string that
278 matched the % in the pattern. */
279 o = variable_buffer_output (o, t + pattern_prepercent_len,
280 len - (pattern_prepercent_len
281 + pattern_postpercent_len));
282 /* Output the part of the replacement after the %. */
283 o = variable_buffer_output (o, replace_percent,
284 replace_postpercent_len);
285 }
286 }
287
288 /* Output a space, but not if the replacement is "". */
289 if (fail || replace_prepercent_len > 0
290 || (replace_percent != 0 && len + replace_postpercent_len > 0))
291 {
292 o = variable_buffer_output (o, " ", 1);
293 doneany = 1;
294 }
295 }
296#ifndef CONFIG_WITH_VALUE_LENGTH
297 if (doneany)
298 /* Kill the last space. */
299 --o;
300#else
301 /* Kill the last space and make sure there is a terminator there
302 so that strcache_add_len doesn't have to do a lot of exacty work
303 when expand_deps sends the output its way. */
304 if (doneany)
305 *--o = '\0';
306 else
307 o = variable_buffer_output (o, "\0", 1) - 1;
308#endif
309
310 return o;
311}
312
313/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
314 and replacing strings matching PATTERN with REPLACE.
315 If PATTERN_PERCENT is not nil, PATTERN has already been
316 run through find_percent, and PATTERN_PERCENT is the result.
317 If REPLACE_PERCENT is not nil, REPLACE has already been
318 run through find_percent, and REPLACE_PERCENT is the result.
319 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
320 character _AFTER_ the %, not to the % itself.
321*/
322
323char *
324patsubst_expand (char *o, const char *text, char *pattern, char *replace)
325{
326 const char *pattern_percent = find_percent (pattern);
327 const char *replace_percent = find_percent (replace);
328
329 /* If there's a percent in the pattern or replacement skip it. */
330 if (replace_percent)
331 ++replace_percent;
332 if (pattern_percent)
333 ++pattern_percent;
334
335 return patsubst_expand_pat (o, text, pattern, replace,
336 pattern_percent, replace_percent);
337}
338
339
340#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
341
342/* Char map containing the valid function name characters. */
343char func_char_map[256];
344
345/* Do the hash table lookup. */
346
347MY_INLINE const struct function_table_entry *
348lookup_function_in_hash_tab (const char *s, unsigned char len)
349{
350 struct function_table_entry function_table_entry_key;
351 function_table_entry_key.name = s;
352 function_table_entry_key.len = len;
353
354 return hash_find_item (&function_table, &function_table_entry_key);
355}
356
357/* Look up a function by name. */
358
359MY_INLINE const struct function_table_entry *
360lookup_function (const char *s, unsigned int len)
361{
362 unsigned char ch;
363# if 0 /* insane loop unroll */
364
365 if (len > MAX_FUNCTION_LENGTH)
366 len = MAX_FUNCTION_LENGTH + 1;
367
368# define X(idx) \
369 if (!func_char_map[ch = s[idx]]) \
370 { \
371 if (isblank (ch)) \
372 return lookup_function_in_hash_tab (s, idx); \
373 return 0; \
374 }
375# define Z(idx) \
376 return lookup_function_in_hash_tab (s, idx);
377
378 switch (len)
379 {
380 default:
381 assert (0);
382 case 0: return 0;
383 case 1: return 0;
384 case 2: X(0); X(1); Z(2);
385 case 3: X(0); X(1); X(2); Z(3);
386 case 4: X(0); X(1); X(2); X(3); Z(4);
387 case 5: X(0); X(1); X(2); X(3); X(4); Z(5);
388 case 6: X(0); X(1); X(2); X(3); X(4); X(5); Z(6);
389 case 7: X(0); X(1); X(2); X(3); X(4); X(5); X(6); Z(7);
390 case 8: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); Z(8);
391 case 9: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); Z(9);
392 case 10: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); Z(10);
393 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);
394 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);
395 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);
396 if ((ch = s[12]) == '\0' || isblank (ch))
397 return lookup_function_in_hash_tab (s, 12);
398 return 0;
399 }
400# undef Z
401# undef X
402
403# else /* normal loop */
404 const char *e = s;
405 if (len > MAX_FUNCTION_LENGTH)
406 len = MAX_FUNCTION_LENGTH;
407 while (func_char_map[ch = *e])
408 {
409 if (!len--)
410 return 0;
411 e++;
412 }
413 if (ch == '\0' || isblank (ch))
414 return lookup_function_in_hash_tab (s, e - s);
415 return 0;
416# endif /* normal loop */
417}
418
419#else /* original code */
420/* Look up a function by name. */
421
422static const struct function_table_entry *
423lookup_function (const char *s)
424{
425 const char *e = s;
426 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
427 e++;
428 if (*e == '\0' || isblank ((unsigned char) *e))
429 {
430 struct function_table_entry function_table_entry_key;
431 function_table_entry_key.name = s;
432 function_table_entry_key.len = e - s;
433
434 return hash_find_item (&function_table, &function_table_entry_key);
435 }
436 return 0;
437}
438#endif /* original code */
439
440
441
442/* Return 1 if PATTERN matches STR, 0 if not. */
443
444int
445pattern_matches (const char *pattern, const char *percent, const char *str)
446{
447 unsigned int sfxlen, strlength;
448
449 if (percent == 0)
450 {
451 unsigned int len = strlen (pattern) + 1;
452 char *new_chars = alloca (len);
453 memcpy (new_chars, pattern, len);
454 percent = find_percent (new_chars);
455 if (percent == 0)
456 return streq (new_chars, str);
457 pattern = new_chars;
458 }
459
460 sfxlen = strlen (percent + 1);
461 strlength = strlen (str);
462
463 if (strlength < (percent - pattern) + sfxlen
464 || !strneq (pattern, str, percent - pattern))
465 return 0;
466
467 return !strcmp (percent + 1, str + (strlength - sfxlen));
468}
469
470
471
472/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
473 ENDPARENtheses), starting at PTR before END. Return a pointer to
474 next character.
475
476 If no next argument is found, return NULL.
477*/
478
479static char *
480find_next_argument (char startparen, char endparen,
481 const char *ptr, const char *end)
482{
483 int count = 0;
484
485 for (; ptr < end; ++ptr)
486 if (*ptr == startparen)
487 ++count;
488
489 else if (*ptr == endparen)
490 {
491 --count;
492 if (count < 0)
493 return NULL;
494 }
495
496 else if (*ptr == ',' && !count)
497 return (char *)ptr;
498
499 /* We didn't find anything. */
500 return NULL;
501}
502
503
504
505/* Glob-expand LINE. The returned pointer is
506 only good until the next call to string_glob. */
507
508static char *
509string_glob (char *line)
510{
511 static char *result = 0;
512 static unsigned int length;
513 struct nameseq *chain;
514 unsigned int idx;
515
516 chain = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
517 /* We do not want parse_file_seq to strip `./'s.
518 That would break examples like:
519 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
520 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
521
522 if (result == 0)
523 {
524 length = 100;
525 result = xmalloc (100);
526 }
527
528 idx = 0;
529 while (chain != 0)
530 {
531 struct nameseq *next = chain->next;
532 unsigned int len = strlen (chain->name);
533
534 if (idx + len + 1 > length)
535 {
536 length += (len + 1) * 2;
537 result = xrealloc (result, length);
538 }
539 memcpy (&result[idx], chain->name, len);
540 idx += len;
541 result[idx++] = ' ';
542
543 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
544 free ((char *)chain->name);
545#ifndef CONFIG_WITH_ALLOC_CACHES
546 free (chain);
547#else
548 alloccache_free (&nameseq_cache, chain);
549#endif
550 chain = next;
551 }
552
553 /* Kill the last space and terminate the string. */
554 if (idx == 0)
555 result[0] = '\0';
556 else
557 result[idx - 1] = '\0';
558
559 return result;
560}
561
562
563/*
564 Builtin functions
565 */
566
567static char *
568func_patsubst (char *o, char **argv, const char *funcname UNUSED)
569{
570 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
571 return o;
572}
573
574
575static char *
576func_join (char *o, char **argv, const char *funcname UNUSED)
577{
578 int doneany = 0;
579
580 /* Write each word of the first argument directly followed
581 by the corresponding word of the second argument.
582 If the two arguments have a different number of words,
583 the excess words are just output separated by blanks. */
584 const char *tp;
585 const char *pp;
586 const char *list1_iterator = argv[0];
587 const char *list2_iterator = argv[1];
588 do
589 {
590 unsigned int len1, len2;
591
592 tp = find_next_token (&list1_iterator, &len1);
593 if (tp != 0)
594 o = variable_buffer_output (o, tp, len1);
595
596 pp = find_next_token (&list2_iterator, &len2);
597 if (pp != 0)
598 o = variable_buffer_output (o, pp, len2);
599
600 if (tp != 0 || pp != 0)
601 {
602 o = variable_buffer_output (o, " ", 1);
603 doneany = 1;
604 }
605 }
606 while (tp != 0 || pp != 0);
607 if (doneany)
608 /* Kill the last blank. */
609 --o;
610
611 return o;
612}
613
614
615static char *
616func_origin (char *o, char **argv, const char *funcname UNUSED)
617{
618 /* Expand the argument. */
619 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
620 if (v == 0)
621 o = variable_buffer_output (o, "undefined", 9);
622 else
623 switch (v->origin)
624 {
625 default:
626 case o_invalid:
627 abort ();
628 break;
629 case o_default:
630 o = variable_buffer_output (o, "default", 7);
631 break;
632 case o_env:
633 o = variable_buffer_output (o, "environment", 11);
634 break;
635 case o_file:
636 o = variable_buffer_output (o, "file", 4);
637 break;
638 case o_env_override:
639 o = variable_buffer_output (o, "environment override", 20);
640 break;
641 case o_command:
642 o = variable_buffer_output (o, "command line", 12);
643 break;
644 case o_override:
645 o = variable_buffer_output (o, "override", 8);
646 break;
647 case o_automatic:
648 o = variable_buffer_output (o, "automatic", 9);
649 break;
650#ifdef CONFIG_WITH_LOCAL_VARIABLES
651 case o_local:
652 o = variable_buffer_output (o, "local", 5);
653 break;
654#endif
655 }
656
657 return o;
658}
659
660static char *
661func_flavor (char *o, char **argv, const char *funcname UNUSED)
662{
663 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
664
665 if (v == 0)
666 o = variable_buffer_output (o, "undefined", 9);
667 else
668 if (v->recursive)
669 o = variable_buffer_output (o, "recursive", 9);
670 else
671 o = variable_buffer_output (o, "simple", 6);
672
673 return o;
674}
675
676#ifdef CONFIG_WITH_WHERE_FUNCTION
677static char *
678func_where (char *o, char **argv, const char *funcname UNUSED)
679{
680 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
681 char buf[64];
682
683 if (v == 0)
684 o = variable_buffer_output (o, "undefined", 9);
685 else
686 if (v->fileinfo.filenm)
687 {
688 o = variable_buffer_output (o, v->fileinfo.filenm, strlen(v->fileinfo.filenm));
689 sprintf (buf, ":%lu", v->fileinfo.lineno);
690 o = variable_buffer_output (o, buf, strlen(buf));
691 }
692 else
693 o = variable_buffer_output (o, "no-location", 11);
694
695 return o;
696}
697#endif /* CONFIG_WITH_WHERE_FUNCTION */
698
699#ifdef VMS
700# define IS_PATHSEP(c) ((c) == ']')
701#else
702# ifdef HAVE_DOS_PATHS
703# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
704# else
705# define IS_PATHSEP(c) ((c) == '/')
706# endif
707#endif
708
709
710static char *
711func_notdir_suffix (char *o, char **argv, const char *funcname)
712{
713 /* Expand the argument. */
714 const char *list_iterator = argv[0];
715 const char *p2;
716 int doneany =0;
717 unsigned int len=0;
718
719 int is_suffix = streq (funcname, "suffix");
720 int is_notdir = !is_suffix;
721 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
722 {
723 const char *p = p2 + len;
724
725
726 while (p >= p2 && (!is_suffix || *p != '.'))
727 {
728 if (IS_PATHSEP (*p))
729 break;
730 --p;
731 }
732
733 if (p >= p2)
734 {
735 if (is_notdir)
736 ++p;
737 else if (*p != '.')
738 continue;
739 o = variable_buffer_output (o, p, len - (p - p2));
740 }
741#ifdef HAVE_DOS_PATHS
742 /* Handle the case of "d:foo/bar". */
743 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
744 {
745 p = p2 + 2;
746 o = variable_buffer_output (o, p, len - (p - p2));
747 }
748#endif
749 else if (is_notdir)
750 o = variable_buffer_output (o, p2, len);
751
752 if (is_notdir || p >= p2)
753 {
754 o = variable_buffer_output (o, " ", 1);
755 doneany = 1;
756 }
757 }
758
759 if (doneany)
760 /* Kill last space. */
761 --o;
762
763 return o;
764}
765
766
767static char *
768func_basename_dir (char *o, char **argv, const char *funcname)
769{
770 /* Expand the argument. */
771 const char *p3 = argv[0];
772 const char *p2;
773 int doneany=0;
774 unsigned int len=0;
775
776 int is_basename= streq (funcname, "basename");
777 int is_dir= !is_basename;
778
779 while ((p2 = find_next_token (&p3, &len)) != 0)
780 {
781 const char *p = p2 + len;
782 while (p >= p2 && (!is_basename || *p != '.'))
783 {
784 if (IS_PATHSEP (*p))
785 break;
786 --p;
787 }
788
789 if (p >= p2 && (is_dir))
790 o = variable_buffer_output (o, p2, ++p - p2);
791 else if (p >= p2 && (*p == '.'))
792 o = variable_buffer_output (o, p2, p - p2);
793#ifdef HAVE_DOS_PATHS
794 /* Handle the "d:foobar" case */
795 else if (p2[0] && p2[1] == ':' && is_dir)
796 o = variable_buffer_output (o, p2, 2);
797#endif
798 else if (is_dir)
799#ifdef VMS
800 o = variable_buffer_output (o, "[]", 2);
801#else
802#ifndef _AMIGA
803 o = variable_buffer_output (o, "./", 2);
804#else
805 ; /* Just a nop... */
806#endif /* AMIGA */
807#endif /* !VMS */
808 else
809 /* The entire name is the basename. */
810 o = variable_buffer_output (o, p2, len);
811
812 o = variable_buffer_output (o, " ", 1);
813 doneany = 1;
814 }
815
816 if (doneany)
817 /* Kill last space. */
818 --o;
819
820 return o;
821}
822
823#ifdef CONFIG_WITH_ROOT_FUNC
824
825/*
826 $(root path)
827
828 This is mainly for dealing with drive letters and UNC paths on Windows
829 and OS/2.
830 */
831static char *
832func_root (char *o, char **argv, const char *funcname UNUSED)
833{
834 const char *paths = argv[0] ? argv[0] : "";
835 int doneany = 0;
836 const char *p;
837 unsigned int len;
838
839 while ((p = find_next_token (&paths, &len)) != 0)
840 {
841 const char *p2 = p;
842
843#ifdef HAVE_DOS_PATHS
844 if ( len >= 2
845 && p2[1] == ':'
846 && ( (p2[0] >= 'A' && p2[0] <= 'Z')
847 || (p2[0] >= 'a' && p2[0] <= 'z')))
848 {
849 p2 += 2;
850 len -= 2;
851 }
852 else if (len >= 4 && IS_PATHSEP(p2[0]) && IS_PATHSEP(p2[1])
853 && !IS_PATHSEP(p2[2]))
854 {
855 /* Min recognized UNC: "//./" - find the next slash
856 Typical root: "//srv/shr/" */
857 /* XXX: Check if //./ needs special handling. */
858
859 p2 += 3;
860 len -= 3;
861 while (len > 0 && !IS_PATHSEP(*p2))
862 p2++, len--;
863
864 if (len && IS_PATHSEP(p2[0]) && (len == 1 || !IS_PATHSEP(p2[1])))
865 {
866 p2++;
867 len--;
868
869 if (len) /* optional share */
870 while (len > 0 && !IS_PATHSEP(*p2))
871 p2++, len--;
872 }
873 else
874 p2 = NULL;
875 }
876 else if (IS_PATHSEP(*p2))
877 {
878 p2++;
879 len--;
880 }
881 else
882 p2 = NULL;
883
884#elif defined (VMS) || defined (AMGIA)
885 /* XXX: VMS and AMGIA */
886 fatal (NILF, _("$(root ) is not implemented on this platform"));
887#else
888 if (IS_PATHSEP(*p2))
889 {
890 p2++;
891 len--;
892 }
893 else
894 p2 = NULL;
895#endif
896 if (p2 != NULL)
897 {
898 /* Include all subsequent path separators. */
899
900 while (len > 0 && IS_PATHSEP(*p2))
901 p2++, len--;
902 o = variable_buffer_output (o, p, p2 - p);
903 o = variable_buffer_output (o, " ", 1);
904 doneany = 1;
905 }
906 }
907
908 if (doneany)
909 /* Kill last space. */
910 --o;
911
912 return o;
913}
914
915/*
916 $(notroot path)
917
918 This is mainly for dealing with drive letters and UNC paths on Windows
919 and OS/2.
920 */
921static char *
922func_notroot (char *o, char **argv, const char *funcname UNUSED)
923{
924 const char *paths = argv[0] ? argv[0] : "";
925 int doneany = 0;
926 const char *p;
927 unsigned int len;
928
929 while ((p = find_next_token (&paths, &len)) != 0)
930 {
931 const char *p2 = p;
932
933#ifdef HAVE_DOS_PATHS
934 if ( len >= 2
935 && p2[1] == ':'
936 && ( (p2[0] >= 'A' && p2[0] <= 'Z')
937 || (p2[0] >= 'a' && p2[0] <= 'z')))
938 {
939 p2 += 2;
940 len -= 2;
941 }
942 else if (len >= 4 && IS_PATHSEP(p2[0]) && IS_PATHSEP(p2[1])
943 && !IS_PATHSEP(p2[2]))
944 {
945 /* Min recognized UNC: "//./" - find the next slash
946 Typical root: "//srv/shr/" */
947 /* XXX: Check if //./ needs special handling. */
948 unsigned int saved_len = len;
949
950 p2 += 3;
951 len -= 3;
952 while (len > 0 && !IS_PATHSEP(*p2))
953 p2++, len--;
954
955 if (len && IS_PATHSEP(p2[0]) && (len == 1 || !IS_PATHSEP(p2[1])))
956 {
957 p2++;
958 len--;
959
960 if (len) /* optional share */
961 while (len > 0 && !IS_PATHSEP(*p2))
962 p2++, len--;
963 }
964 else
965 {
966 p2 = p;
967 len = saved_len;
968 }
969 }
970
971#elif defined (VMS) || defined (AMGIA)
972 /* XXX: VMS and AMGIA */
973 fatal (NILF, _("$(root ) is not implemented on this platform"));
974#endif
975
976 /* Exclude all subsequent / leading path separators. */
977
978 while (len > 0 && IS_PATHSEP(*p2))
979 p2++, len--;
980 if (len > 0)
981 o = variable_buffer_output (o, p2, len);
982 else
983 o = variable_buffer_output (o, ".", 1);
984 o = variable_buffer_output (o, " ", 1);
985 doneany = 1;
986 }
987
988 if (doneany)
989 /* Kill last space. */
990 --o;
991
992 return o;
993}
994
995#endif /* CONFIG_WITH_ROOT_FUNC */
996
997static char *
998func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
999{
1000 int fixlen = strlen (argv[0]);
1001 const char *list_iterator = argv[1];
1002 int is_addprefix = streq (funcname, "addprefix");
1003 int is_addsuffix = !is_addprefix;
1004
1005 int doneany = 0;
1006 const char *p;
1007 unsigned int len;
1008
1009 while ((p = find_next_token (&list_iterator, &len)) != 0)
1010 {
1011 if (is_addprefix)
1012 o = variable_buffer_output (o, argv[0], fixlen);
1013 o = variable_buffer_output (o, p, len);
1014 if (is_addsuffix)
1015 o = variable_buffer_output (o, argv[0], fixlen);
1016 o = variable_buffer_output (o, " ", 1);
1017 doneany = 1;
1018 }
1019
1020 if (doneany)
1021 /* Kill last space. */
1022 --o;
1023
1024 return o;
1025}
1026
1027static char *
1028func_subst (char *o, char **argv, const char *funcname UNUSED)
1029{
1030 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
1031 strlen (argv[1]), 0);
1032
1033 return o;
1034}
1035
1036#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
1037
1038/* Used by func_firstdefined and func_lastdefined to parse the optional last
1039 argument. Returns 0 if the variable name is to be returned and 1 if it's
1040 the variable value value. */
1041static int
1042parse_value_name_argument (const char *arg1, const char *funcname)
1043{
1044 const char *end;
1045 int rc;
1046
1047 if (arg1 == NULL)
1048 return 0;
1049
1050 end = strchr (arg1, '\0');
1051 strip_whitespace (&arg1, &end);
1052
1053 if (!strncmp (arg1, "name", end - arg1))
1054 rc = 0;
1055 else if (!strncmp (arg1, "value", end - arg1))
1056 rc = 1;
1057 else
1058#if 1 /* FIXME: later */
1059 fatal (*expanding_var,
1060 _("second argument to `%s' function must be `name' or `value', not `%s'"),
1061 funcname, arg1);
1062#else
1063 {
1064 /* check the expanded form */
1065 char *exp = expand_argument (arg1, strchr (arg1, '\0'));
1066 arg1 = exp;
1067 end = strchr (arg1, '\0');
1068 strip_whitespace (&arg1, &end);
1069
1070 if (!strncmp (arg1, "name", end - arg1))
1071 rc = 0;
1072 else if (!strncmp (arg1, "value", end - arg1))
1073 rc = 1;
1074 else
1075 fatal (*expanding_var,
1076 _("second argument to `%s' function must be `name' or `value', not `%s'"),
1077 funcname, exp);
1078 free (exp);
1079 }
1080#endif
1081
1082 return rc;
1083}
1084
1085/* Given a list of variable names (ARGV[0]), returned the first variable which
1086 is defined (i.e. value is not empty). ARGV[1] indicates whether to return
1087 the variable name or its value. */
1088static char *
1089func_firstdefined (char *o, char **argv, const char *funcname)
1090{
1091 unsigned int i;
1092 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1093 const char *p;
1094 int ret_value = parse_value_name_argument (argv[1], funcname);
1095
1096 /* FIXME: Optimize by not expanding the arguments, but instead expand them
1097 one by one here. This will require a find_next_token variant which
1098 takes `$(' and `)' into account. */
1099 while ((p = find_next_token (&words, &i)) != NULL)
1100 {
1101 struct variable *v = lookup_variable (p, i);
1102 if (v && v->value_length)
1103 {
1104 if (ret_value)
1105 variable_expand_string_2 (o, v->value, v->value_length, &o);
1106 else
1107 o = variable_buffer_output (o, p, i);
1108 break;
1109 }
1110 }
1111
1112 return o;
1113}
1114
1115/* Given a list of variable names (ARGV[0]), returned the last variable which
1116 is defined (i.e. value is not empty). ARGV[1] indicates whether to return
1117 the variable name or its value. */
1118static char *
1119func_lastdefined (char *o, char **argv, const char *funcname)
1120{
1121 struct variable *last_v = NULL;
1122 unsigned int i;
1123 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1124 const char *p;
1125 int ret_value = parse_value_name_argument (argv[1], funcname);
1126
1127 /* FIXME: Optimize this. Walk from the end on unexpanded arguments. */
1128 while ((p = find_next_token (&words, &i)) != NULL)
1129 {
1130 struct variable *v = lookup_variable (p, i);
1131 if (v && v->value_length)
1132 {
1133 last_v = v;
1134 break;
1135 }
1136 }
1137
1138 if (last_v != NULL)
1139 {
1140 if (ret_value)
1141 variable_expand_string_2 (o, last_v->value, last_v->value_length, &o);
1142 else
1143 o = variable_buffer_output (o, last_v->name, last_v->length);
1144 }
1145 return o;
1146}
1147
1148#endif /* CONFIG_WITH_DEFINED_FUNCTIONS */
1149
1150static char *
1151func_firstword (char *o, char **argv, const char *funcname UNUSED)
1152{
1153 unsigned int i;
1154 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1155 const char *p = find_next_token (&words, &i);
1156
1157 if (p != 0)
1158 o = variable_buffer_output (o, p, i);
1159
1160 return o;
1161}
1162
1163static char *
1164func_lastword (char *o, char **argv, const char *funcname UNUSED)
1165{
1166 unsigned int i;
1167 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1168 const char *p = NULL;
1169 const char *t;
1170
1171 while ((t = find_next_token (&words, &i)))
1172 p = t;
1173
1174 if (p != 0)
1175 o = variable_buffer_output (o, p, i);
1176
1177 return o;
1178}
1179
1180static char *
1181func_words (char *o, char **argv, const char *funcname UNUSED)
1182{
1183 int i = 0;
1184 const char *word_iterator = argv[0];
1185 char buf[20];
1186
1187 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
1188 ++i;
1189
1190 sprintf (buf, "%d", i);
1191 o = variable_buffer_output (o, buf, strlen (buf));
1192
1193 return o;
1194}
1195
1196/* Set begpp to point to the first non-whitespace character of the string,
1197 * and endpp to point to the last non-whitespace character of the string.
1198 * If the string is empty or contains nothing but whitespace, endpp will be
1199 * begpp-1.
1200 */
1201char *
1202strip_whitespace (const char **begpp, const char **endpp)
1203{
1204 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
1205 (*begpp) ++;
1206 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
1207 (*endpp) --;
1208 return (char *)*begpp;
1209}
1210
1211static void
1212check_numeric (const char *s, const char *msg)
1213{
1214 const char *end = s + strlen (s) - 1;
1215 const char *beg = s;
1216 strip_whitespace (&s, &end);
1217
1218 for (; s <= end; ++s)
1219 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
1220 break;
1221
1222 if (s <= end || end - beg < 0)
1223 fatal (*expanding_var, "%s: '%s'", msg, beg);
1224}
1225
1226
1227
1228static char *
1229func_word (char *o, char **argv, const char *funcname UNUSED)
1230{
1231 const char *end_p;
1232 const char *p;
1233 int i;
1234
1235 /* Check the first argument. */
1236 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
1237 i = atoi (argv[0]);
1238
1239 if (i == 0)
1240 fatal (*expanding_var,
1241 _("first argument to `word' function must be greater than 0"));
1242
1243 end_p = argv[1];
1244 while ((p = find_next_token (&end_p, 0)) != 0)
1245 if (--i == 0)
1246 break;
1247
1248 if (i == 0)
1249 o = variable_buffer_output (o, p, end_p - p);
1250
1251 return o;
1252}
1253
1254static char *
1255func_wordlist (char *o, char **argv, const char *funcname UNUSED)
1256{
1257 int start, count;
1258
1259 /* Check the arguments. */
1260 check_numeric (argv[0],
1261 _("non-numeric first argument to `wordlist' function"));
1262 check_numeric (argv[1],
1263 _("non-numeric second argument to `wordlist' function"));
1264
1265 start = atoi (argv[0]);
1266 if (start < 1)
1267 fatal (*expanding_var,
1268 "invalid first argument to `wordlist' function: `%d'", start);
1269
1270 count = atoi (argv[1]) - start + 1;
1271
1272 if (count > 0)
1273 {
1274 const char *p;
1275 const char *end_p = argv[2];
1276
1277 /* Find the beginning of the "start"th word. */
1278 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
1279 ;
1280
1281 if (p)
1282 {
1283 /* Find the end of the "count"th word from start. */
1284 while (--count && (find_next_token (&end_p, 0) != 0))
1285 ;
1286
1287 /* Return the stuff in the middle. */
1288 o = variable_buffer_output (o, p, end_p - p);
1289 }
1290 }
1291
1292 return o;
1293}
1294
1295static char *
1296func_findstring (char *o, char **argv, const char *funcname UNUSED)
1297{
1298 /* Find the first occurrence of the first string in the second. */
1299 if (strstr (argv[1], argv[0]) != 0)
1300 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
1301
1302 return o;
1303}
1304
1305static char *
1306func_foreach (char *o, char **argv, const char *funcname UNUSED)
1307{
1308 /* expand only the first two. */
1309 char *varname = expand_argument (argv[0], NULL);
1310 char *list = expand_argument (argv[1], NULL);
1311 const char *body = argv[2];
1312#ifdef CONFIG_WITH_VALUE_LENGTH
1313 long body_len = strlen (body);
1314#endif
1315
1316 int doneany = 0;
1317 const char *list_iterator = list;
1318 const char *p;
1319 unsigned int len;
1320 struct variable *var;
1321
1322 push_new_variable_scope ();
1323 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
1324
1325 /* loop through LIST, put the value in VAR and expand BODY */
1326 while ((p = find_next_token (&list_iterator, &len)) != 0)
1327 {
1328#ifndef CONFIG_WITH_VALUE_LENGTH
1329 char *result = 0;
1330
1331 free (var->value);
1332 var->value = xstrndup (p, len);
1333
1334 result = allocated_variable_expand (body);
1335
1336 o = variable_buffer_output (o, result, strlen (result));
1337 o = variable_buffer_output (o, " ", 1);
1338 doneany = 1;
1339 free (result);
1340#else /* CONFIG_WITH_VALUE_LENGTH */
1341 if (len >= var->value_alloc_len)
1342 {
1343# ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
1344 if (var->rdonly_val)
1345 var->rdonly_val = 0;
1346 else
1347# endif
1348 free (var->value);
1349 var->value_alloc_len = VAR_ALIGN_VALUE_ALLOC (len + 1);
1350 var->value = xmalloc (var->value_alloc_len);
1351 }
1352 memcpy (var->value, p, len);
1353 var->value[len] = '\0';
1354 var->value_length = len;
1355
1356 variable_expand_string_2 (o, body, body_len, &o);
1357 o = variable_buffer_output (o, " ", 1);
1358 doneany = 1;
1359#endif /* CONFIG_WITH_VALUE_LENGTH */
1360 }
1361
1362 if (doneany)
1363 /* Kill the last space. */
1364 --o;
1365
1366 pop_variable_scope ();
1367 free (varname);
1368 free (list);
1369
1370 return o;
1371}
1372
1373#ifdef CONFIG_WITH_LOOP_FUNCTIONS
1374
1375
1376/* Helper for func_for that evaluates the INIT and NEXT parts. */
1377static void
1378helper_eval (char *text, size_t text_len)
1379{
1380 unsigned int buf_len;
1381 char *buf;
1382
1383 install_variable_buffer (&buf, &buf_len);
1384 eval_buffer (text, text + text_len);
1385 restore_variable_buffer (buf, buf_len);
1386}
1387
1388/*
1389 $(for init,condition,next,body)
1390 */
1391static char *
1392func_for (char *o, char **argv, const char *funcname UNUSED)
1393{
1394 char *init = argv[0];
1395 const char *cond = argv[1];
1396 const char *next = argv[2];
1397 size_t next_len = strlen (next);
1398 char *next_buf = xmalloc (next_len + 1);
1399 const char *body = argv[3];
1400 size_t body_len = strlen (body);
1401 unsigned int doneany = 0;
1402
1403 push_new_variable_scope ();
1404
1405 /* Evaluate INIT. */
1406
1407 helper_eval (init, strlen (init));
1408
1409 /* Loop till COND is false. */
1410
1411 while (expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
1412 {
1413 /* Expand BODY. */
1414
1415 if (!doneany)
1416 doneany = 1;
1417 else
1418 o = variable_buffer_output (o, " ", 1);
1419 variable_expand_string_2 (o, body, body_len, &o);
1420
1421 /* Evaluate NEXT. */
1422
1423 memcpy (next_buf, next, next_len + 1);
1424 helper_eval (next_buf, next_len);
1425 }
1426
1427 pop_variable_scope ();
1428 free (next_buf);
1429
1430 return o;
1431}
1432
1433/*
1434 $(while condition,body)
1435 */
1436static char *
1437func_while (char *o, char **argv, const char *funcname UNUSED)
1438{
1439 const char *cond = argv[0];
1440 const char *body = argv[1];
1441 size_t body_len = strlen (body);
1442 unsigned int doneany = 0;
1443
1444 push_new_variable_scope ();
1445
1446 while (expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
1447 {
1448 if (!doneany)
1449 doneany = 1;
1450 else
1451 o = variable_buffer_output (o, " ", 1);
1452 variable_expand_string_2 (o, body, body_len, &o);
1453 }
1454
1455 pop_variable_scope ();
1456
1457 return o;
1458}
1459
1460
1461#endif /* CONFIG_WITH_LOOP_FUNCTIONS */
1462
1463struct a_word
1464{
1465 struct a_word *next;
1466 struct a_word *chain;
1467 char *str;
1468 int length;
1469 int matched;
1470};
1471
1472static unsigned long
1473a_word_hash_1 (const void *key)
1474{
1475 return_STRING_HASH_1 (((struct a_word const *) key)->str);
1476}
1477
1478static unsigned long
1479a_word_hash_2 (const void *key)
1480{
1481 return_STRING_HASH_2 (((struct a_word const *) key)->str);
1482}
1483
1484static int
1485a_word_hash_cmp (const void *x, const void *y)
1486{
1487 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
1488 if (result)
1489 return result;
1490 return_STRING_COMPARE (((struct a_word const *) x)->str,
1491 ((struct a_word const *) y)->str);
1492}
1493
1494struct a_pattern
1495{
1496 struct a_pattern *next;
1497 char *str;
1498 char *percent;
1499 int length;
1500 int save_c;
1501};
1502
1503static char *
1504func_filter_filterout (char *o, char **argv, const char *funcname)
1505{
1506 struct a_word *wordhead;
1507 struct a_word **wordtail;
1508 struct a_word *wp;
1509 struct a_pattern *pathead;
1510 struct a_pattern **pattail;
1511 struct a_pattern *pp;
1512
1513 struct hash_table a_word_table;
1514 int is_filter = streq (funcname, "filter");
1515 const char *pat_iterator = argv[0];
1516 const char *word_iterator = argv[1];
1517 int literals = 0;
1518 int words = 0;
1519 int hashing = 0;
1520 char *p;
1521 unsigned int len;
1522
1523 /* Chop ARGV[0] up into patterns to match against the words. */
1524
1525 pattail = &pathead;
1526 while ((p = find_next_token (&pat_iterator, &len)) != 0)
1527 {
1528 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
1529
1530 *pattail = pat;
1531 pattail = &pat->next;
1532
1533 if (*pat_iterator != '\0')
1534 ++pat_iterator;
1535
1536 pat->str = p;
1537 pat->length = len;
1538 pat->save_c = p[len];
1539 p[len] = '\0';
1540 pat->percent = find_percent (p);
1541 if (pat->percent == 0)
1542 literals++;
1543 }
1544 *pattail = 0;
1545
1546 /* Chop ARGV[1] up into words to match against the patterns. */
1547
1548 wordtail = &wordhead;
1549 while ((p = find_next_token (&word_iterator, &len)) != 0)
1550 {
1551 struct a_word *word = alloca (sizeof (struct a_word));
1552
1553 *wordtail = word;
1554 wordtail = &word->next;
1555
1556 if (*word_iterator != '\0')
1557 ++word_iterator;
1558
1559 p[len] = '\0';
1560 word->str = p;
1561 word->length = len;
1562 word->matched = 0;
1563 word->chain = 0;
1564 words++;
1565 }
1566 *wordtail = 0;
1567
1568 /* Only use a hash table if arg list lengths justifies the cost. */
1569 hashing = (literals >= 2 && (literals * words) >= 10);
1570 if (hashing)
1571 {
1572 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
1573 a_word_hash_cmp);
1574 for (wp = wordhead; wp != 0; wp = wp->next)
1575 {
1576 struct a_word *owp = hash_insert (&a_word_table, wp);
1577 if (owp)
1578 wp->chain = owp;
1579 }
1580 }
1581
1582 if (words)
1583 {
1584 int doneany = 0;
1585
1586 /* Run each pattern through the words, killing words. */
1587 for (pp = pathead; pp != 0; pp = pp->next)
1588 {
1589 if (pp->percent)
1590 for (wp = wordhead; wp != 0; wp = wp->next)
1591 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1592 else if (hashing)
1593 {
1594 struct a_word a_word_key;
1595 a_word_key.str = pp->str;
1596 a_word_key.length = pp->length;
1597 wp = hash_find_item (&a_word_table, &a_word_key);
1598 while (wp)
1599 {
1600 wp->matched |= 1;
1601 wp = wp->chain;
1602 }
1603 }
1604 else
1605 for (wp = wordhead; wp != 0; wp = wp->next)
1606 wp->matched |= (wp->length == pp->length
1607 && strneq (pp->str, wp->str, wp->length));
1608 }
1609
1610 /* Output the words that matched (or didn't, for filter-out). */
1611 for (wp = wordhead; wp != 0; wp = wp->next)
1612 if (is_filter ? wp->matched : !wp->matched)
1613 {
1614 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1615 o = variable_buffer_output (o, " ", 1);
1616 doneany = 1;
1617 }
1618
1619 if (doneany)
1620 /* Kill the last space. */
1621 --o;
1622 }
1623
1624 for (pp = pathead; pp != 0; pp = pp->next)
1625 pp->str[pp->length] = pp->save_c;
1626
1627 if (hashing)
1628 hash_free (&a_word_table, 0);
1629
1630 return o;
1631}
1632
1633
1634static char *
1635func_strip (char *o, char **argv, const char *funcname UNUSED)
1636{
1637 const char *p = argv[0];
1638 int doneany = 0;
1639
1640 while (*p != '\0')
1641 {
1642 int i=0;
1643 const char *word_start;
1644
1645 while (isspace ((unsigned char)*p))
1646 ++p;
1647 word_start = p;
1648 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1649 {}
1650 if (!i)
1651 break;
1652 o = variable_buffer_output (o, word_start, i);
1653 o = variable_buffer_output (o, " ", 1);
1654 doneany = 1;
1655 }
1656
1657 if (doneany)
1658 /* Kill the last space. */
1659 --o;
1660
1661 return o;
1662}
1663
1664/*
1665 Print a warning or fatal message.
1666*/
1667static char *
1668func_error (char *o, char **argv, const char *funcname)
1669{
1670 char **argvp;
1671 char *msg, *p;
1672 int len;
1673
1674 /* The arguments will be broken on commas. Rather than create yet
1675 another special case where function arguments aren't broken up,
1676 just create a format string that puts them back together. */
1677 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1678 len += strlen (*argvp) + 2;
1679
1680 p = msg = alloca (len + 1);
1681
1682 for (argvp=argv; argvp[1] != 0; ++argvp)
1683 {
1684 strcpy (p, *argvp);
1685 p += strlen (*argvp);
1686 *(p++) = ',';
1687 *(p++) = ' ';
1688 }
1689 strcpy (p, *argvp);
1690
1691 switch (*funcname) {
1692 case 'e':
1693 fatal (reading_file, "%s", msg);
1694
1695 case 'w':
1696 error (reading_file, "%s", msg);
1697 break;
1698
1699 case 'i':
1700 printf ("%s\n", msg);
1701 fflush(stdout);
1702 break;
1703
1704 default:
1705 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1706 }
1707
1708 /* The warning function expands to the empty string. */
1709 return o;
1710}
1711
1712
1713/*
1714 chop argv[0] into words, and sort them.
1715 */
1716static char *
1717func_sort (char *o, char **argv, const char *funcname UNUSED)
1718{
1719 const char *t;
1720 char **words;
1721 int wordi;
1722 char *p;
1723 unsigned int len;
1724 int i;
1725
1726 /* Find the maximum number of words we'll have. */
1727 t = argv[0];
1728 wordi = 1;
1729 while (*t != '\0')
1730 {
1731 char c = *(t++);
1732
1733 if (! isspace ((unsigned char)c))
1734 continue;
1735
1736 ++wordi;
1737
1738 while (isspace ((unsigned char)*t))
1739 ++t;
1740 }
1741
1742 words = xmalloc (wordi * sizeof (char *));
1743
1744 /* Now assign pointers to each string in the array. */
1745 t = argv[0];
1746 wordi = 0;
1747 while ((p = find_next_token (&t, &len)) != 0)
1748 {
1749 ++t;
1750 p[len] = '\0';
1751 words[wordi++] = p;
1752 }
1753
1754 if (wordi)
1755 {
1756 /* Now sort the list of words. */
1757 qsort (words, wordi, sizeof (char *), alpha_compare);
1758
1759 /* Now write the sorted list, uniquified. */
1760#ifdef CONFIG_WITH_RSORT
1761 if (strcmp (funcname, "rsort"))
1762 {
1763 /* sort */
1764#endif
1765 for (i = 0; i < wordi; ++i)
1766 {
1767 len = strlen (words[i]);
1768 if (i == wordi - 1 || strlen (words[i + 1]) != len
1769 || strcmp (words[i], words[i + 1]))
1770 {
1771 o = variable_buffer_output (o, words[i], len);
1772 o = variable_buffer_output (o, " ", 1);
1773 }
1774 }
1775#ifdef CONFIG_WITH_RSORT
1776 }
1777 else
1778 {
1779 /* rsort - reverse the result */
1780 i = wordi;
1781 while (i-- > 0)
1782 {
1783 len = strlen (words[i]);
1784 if (i == 0 || strlen (words[i - 1]) != len
1785 || strcmp (words[i], words[i - 1]))
1786 {
1787 o = variable_buffer_output (o, words[i], len);
1788 o = variable_buffer_output (o, " ", 1);
1789 }
1790 }
1791 }
1792#endif
1793
1794 /* Kill the last space. */
1795 --o;
1796 }
1797
1798 free (words);
1799
1800 return o;
1801}
1802
1803/*
1804 $(if condition,true-part[,false-part])
1805
1806 CONDITION is false iff it evaluates to an empty string. White
1807 space before and after condition are stripped before evaluation.
1808
1809 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1810 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1811 you can use $(if ...) to create side-effects (with $(shell ...), for
1812 example).
1813*/
1814
1815static char *
1816func_if (char *o, char **argv, const char *funcname UNUSED)
1817{
1818 const char *begp = argv[0];
1819 const char *endp = begp + strlen (argv[0]) - 1;
1820 int result = 0;
1821
1822 /* Find the result of the condition: if we have a value, and it's not
1823 empty, the condition is true. If we don't have a value, or it's the
1824 empty string, then it's false. */
1825
1826 strip_whitespace (&begp, &endp);
1827
1828 if (begp <= endp)
1829 {
1830 char *expansion = expand_argument (begp, endp+1);
1831
1832 result = strlen (expansion);
1833 free (expansion);
1834 }
1835
1836 /* If the result is true (1) we want to eval the first argument, and if
1837 it's false (0) we want to eval the second. If the argument doesn't
1838 exist we do nothing, otherwise expand it and add to the buffer. */
1839
1840 argv += 1 + !result;
1841
1842 if (*argv)
1843 {
1844 char *expansion = expand_argument (*argv, NULL);
1845
1846 o = variable_buffer_output (o, expansion, strlen (expansion));
1847
1848 free (expansion);
1849 }
1850
1851 return o;
1852}
1853
1854/*
1855 $(or condition1[,condition2[,condition3[...]]])
1856
1857 A CONDITION is false iff it evaluates to an empty string. White
1858 space before and after CONDITION are stripped before evaluation.
1859
1860 CONDITION1 is evaluated. If it's true, then this is the result of
1861 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1862 the conditions are true, the expansion is the empty string.
1863
1864 Once a CONDITION is true no further conditions are evaluated
1865 (short-circuiting).
1866*/
1867
1868static char *
1869func_or (char *o, char **argv, const char *funcname UNUSED)
1870{
1871 for ( ; *argv ; ++argv)
1872 {
1873 const char *begp = *argv;
1874 const char *endp = begp + strlen (*argv) - 1;
1875 char *expansion;
1876 int result = 0;
1877
1878 /* Find the result of the condition: if it's false keep going. */
1879
1880 strip_whitespace (&begp, &endp);
1881
1882 if (begp > endp)
1883 continue;
1884
1885 expansion = expand_argument (begp, endp+1);
1886 result = strlen (expansion);
1887
1888 /* If the result is false keep going. */
1889 if (!result)
1890 {
1891 free (expansion);
1892 continue;
1893 }
1894
1895 /* It's true! Keep this result and return. */
1896 o = variable_buffer_output (o, expansion, result);
1897 free (expansion);
1898 break;
1899 }
1900
1901 return o;
1902}
1903
1904/*
1905 $(and condition1[,condition2[,condition3[...]]])
1906
1907 A CONDITION is false iff it evaluates to an empty string. White
1908 space before and after CONDITION are stripped before evaluation.
1909
1910 CONDITION1 is evaluated. If it's false, then this is the result of
1911 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1912 the conditions are true, the expansion is the result of the last condition.
1913
1914 Once a CONDITION is false no further conditions are evaluated
1915 (short-circuiting).
1916*/
1917
1918static char *
1919func_and (char *o, char **argv, const char *funcname UNUSED)
1920{
1921 char *expansion;
1922 int result;
1923
1924 while (1)
1925 {
1926 const char *begp = *argv;
1927 const char *endp = begp + strlen (*argv) - 1;
1928
1929 /* An empty condition is always false. */
1930 strip_whitespace (&begp, &endp);
1931 if (begp > endp)
1932 return o;
1933
1934 expansion = expand_argument (begp, endp+1);
1935 result = strlen (expansion);
1936
1937 /* If the result is false, stop here: we're done. */
1938 if (!result)
1939 break;
1940
1941 /* Otherwise the result is true. If this is the last one, keep this
1942 result and quit. Otherwise go on to the next one! */
1943
1944 if (*(++argv))
1945 free (expansion);
1946 else
1947 {
1948 o = variable_buffer_output (o, expansion, result);
1949 break;
1950 }
1951 }
1952
1953 free (expansion);
1954
1955 return o;
1956}
1957
1958static char *
1959func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1960{
1961#ifdef _AMIGA
1962 o = wildcard_expansion (argv[0], o);
1963#else
1964 char *p = string_glob (argv[0]);
1965 o = variable_buffer_output (o, p, strlen (p));
1966#endif
1967 return o;
1968}
1969
1970/*
1971 $(eval <makefile string>)
1972
1973 Always resolves to the empty string.
1974
1975 Treat the arguments as a segment of makefile, and parse them.
1976*/
1977
1978static char *
1979func_eval (char *o, char **argv, const char *funcname UNUSED)
1980{
1981 char *buf;
1982 unsigned int len;
1983
1984 /* Eval the buffer. Pop the current variable buffer setting so that the
1985 eval'd code can use its own without conflicting. */
1986
1987 install_variable_buffer (&buf, &len);
1988
1989#ifndef CONFIG_WITH_VALUE_LENGTH
1990 eval_buffer (argv[0]);
1991#else
1992 eval_buffer (argv[0], strchr (argv[0], '\0'));
1993#endif
1994
1995 restore_variable_buffer (buf, len);
1996
1997 return o;
1998}
1999
2000
2001#ifdef CONFIG_WITH_EVALPLUS
2002/* Same as func_eval except that we push and pop the local variable
2003 context before evaluating the buffer. */
2004static char *
2005func_evalctx (char *o, char **argv, const char *funcname UNUSED)
2006{
2007 char *buf;
2008 unsigned int len;
2009
2010 /* Eval the buffer. Pop the current variable buffer setting so that the
2011 eval'd code can use its own without conflicting. */
2012
2013 install_variable_buffer (&buf, &len);
2014
2015 push_new_variable_scope ();
2016
2017 eval_buffer (argv[0], strchr (argv[0], '\0'));
2018
2019 pop_variable_scope ();
2020
2021 restore_variable_buffer (buf, len);
2022
2023 return o;
2024}
2025
2026/* A mix of func_eval and func_value, saves memory for the expansion.
2027 This implements both evalval and evalvalctx, the latter has its own
2028 variable context just like evalctx. */
2029static char *
2030func_evalval (char *o, char **argv, const char *funcname)
2031{
2032 /* Look up the variable. */
2033 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
2034 if (v)
2035 {
2036 char *buf;
2037 unsigned int len;
2038 int var_ctx;
2039 size_t off;
2040 const struct floc *reading_file_saved = reading_file;
2041
2042 /* Make a copy of the value to the variable buffer since
2043 eval_buffer will make changes to its input. */
2044
2045 off = o - variable_buffer;
2046 variable_buffer_output (o, v->value, v->value_length + 1);
2047 o = variable_buffer + off;
2048
2049 /* Eval the value. Pop the current variable buffer setting so that the
2050 eval'd code can use its own without conflicting. (really necessary?) */
2051
2052 install_variable_buffer (&buf, &len);
2053 var_ctx = !strcmp (funcname, "evalvalctx");
2054 if (var_ctx)
2055 push_new_variable_scope ();
2056 if (v->fileinfo.filenm)
2057 reading_file = &v->fileinfo;
2058
2059 assert (!o[v->value_length]);
2060 eval_buffer (o, o + v->value_length);
2061
2062 reading_file = reading_file_saved;
2063 if (var_ctx)
2064 pop_variable_scope ();
2065 restore_variable_buffer (buf, len);
2066 }
2067
2068 return o;
2069}
2070
2071/* Optimizes the content of one or more variables to save time in
2072 the eval functions. This function will collapse line continuations
2073 and remove comments. */
2074static char *
2075func_eval_optimize_variable (char *o, char **argv, const char *funcname)
2076{
2077 unsigned int i;
2078
2079 for (i = 0; argv[i]; i++)
2080 {
2081 struct variable *v = lookup_variable (argv[i], strlen (argv[i]));
2082# ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
2083 if (v && !v->origin != o_automatic && !v->rdonly_val)
2084# else
2085 if (v && !v->origin != o_automatic)
2086# endif
2087 {
2088 char *eos, *src;
2089
2090 eos = collapse_continuations (v->value, v->value_length);
2091 v->value_length = eos - v->value;
2092
2093 /* remove comments */
2094
2095 src = memchr (v->value, '#', v->value_length);
2096 if (src)
2097 {
2098 unsigned char ch = '\0';
2099 char *dst = src;
2100 do
2101 {
2102 /* drop blanks preceeding the comment */
2103 while (dst > v->value)
2104 {
2105 ch = (unsigned char)dst[-1];
2106 if (!isblank (ch))
2107 break;
2108 dst--;
2109 }
2110
2111 /* advance SRC to eol / eos. */
2112 src = memchr (src, '\n', eos - src);
2113 if (!src)
2114 break;
2115
2116 /* drop a preceeding newline if possible (full line comment) */
2117 if (dst > v->value && dst[-1] == '\n')
2118 dst--;
2119
2120 /* copy till next comment or eol. */
2121 while (src < eos)
2122 {
2123 ch = *src++;
2124 if (ch == '#')
2125 break;
2126 *dst++ = ch;
2127 }
2128 }
2129 while (ch == '#' && src < eos);
2130
2131 *dst = '\0';
2132 v->value_length = dst - v->value;
2133 }
2134 }
2135 else if (v)
2136 error (NILF, _("$(%s ): variable `%s' is of the wrong type\n"), funcname, v->name);
2137 }
2138
2139 return o;
2140}
2141
2142#endif /* CONFIG_WITH_EVALPLUS */
2143
2144static char *
2145func_value (char *o, char **argv, const char *funcname UNUSED)
2146{
2147 /* Look up the variable. */
2148 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
2149
2150 /* Copy its value into the output buffer without expanding it. */
2151 if (v)
2152#ifdef CONFIG_WITH_VALUE_LENGTH
2153 {
2154 assert (v->value_length == strlen (v->value));
2155 o = variable_buffer_output (o, v->value, v->value_length);
2156 }
2157#else
2158 o = variable_buffer_output (o, v->value, strlen(v->value));
2159#endif
2160
2161 return o;
2162}
2163
2164/*
2165 \r is replaced on UNIX as well. Is this desirable?
2166 */
2167static void
2168fold_newlines (char *buffer, unsigned int *length)
2169{
2170 char *dst = buffer;
2171 char *src = buffer;
2172 char *last_nonnl = buffer -1;
2173 src[*length] = 0;
2174 for (; *src != '\0'; ++src)
2175 {
2176 if (src[0] == '\r' && src[1] == '\n')
2177 continue;
2178 if (*src == '\n')
2179 {
2180 *dst++ = ' ';
2181 }
2182 else
2183 {
2184 last_nonnl = dst;
2185 *dst++ = *src;
2186 }
2187 }
2188 *(++last_nonnl) = '\0';
2189 *length = last_nonnl - buffer;
2190}
2191
2192
2193
2194int shell_function_pid = 0, shell_function_completed;
2195
2196
2197#ifdef WINDOWS32
2198/*untested*/
2199
2200#include <windows.h>
2201#include <io.h>
2202#include "sub_proc.h"
2203
2204
2205void
2206windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
2207{
2208 SECURITY_ATTRIBUTES saAttr;
2209 HANDLE hIn;
2210 HANDLE hErr;
2211 HANDLE hChildOutRd;
2212 HANDLE hChildOutWr;
2213 HANDLE hProcess;
2214
2215
2216 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
2217 saAttr.bInheritHandle = TRUE;
2218 saAttr.lpSecurityDescriptor = NULL;
2219
2220 if (DuplicateHandle (GetCurrentProcess(),
2221 GetStdHandle(STD_INPUT_HANDLE),
2222 GetCurrentProcess(),
2223 &hIn,
2224 0,
2225 TRUE,
2226 DUPLICATE_SAME_ACCESS) == FALSE) {
2227 fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
2228 GetLastError());
2229
2230 }
2231 if (DuplicateHandle(GetCurrentProcess(),
2232 GetStdHandle(STD_ERROR_HANDLE),
2233 GetCurrentProcess(),
2234 &hErr,
2235 0,
2236 TRUE,
2237 DUPLICATE_SAME_ACCESS) == FALSE) {
2238 fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
2239 GetLastError());
2240 }
2241
2242 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
2243 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
2244
2245 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
2246
2247 if (!hProcess)
2248 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
2249
2250 /* make sure that CreateProcess() has Path it needs */
2251 sync_Path_environment();
2252 /* `sync_Path_environment' may realloc `environ', so take note of
2253 the new value. */
2254 envp = environ;
2255
2256 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
2257 /* register process for wait */
2258 process_register(hProcess);
2259
2260 /* set the pid for returning to caller */
2261 *pid_p = (pid_t) hProcess;
2262
2263 /* set up to read data from child */
2264 pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
2265
2266 /* this will be closed almost right away */
2267 pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
2268 } else {
2269 /* reap/cleanup the failed process */
2270 process_cleanup(hProcess);
2271
2272 /* close handles which were duplicated, they weren't used */
2273 CloseHandle(hIn);
2274 CloseHandle(hErr);
2275
2276 /* close pipe handles, they won't be used */
2277 CloseHandle(hChildOutRd);
2278 CloseHandle(hChildOutWr);
2279
2280 /* set status for return */
2281 pipedes[0] = pipedes[1] = -1;
2282 *pid_p = (pid_t)-1;
2283 }
2284}
2285#endif
2286
2287
2288#ifdef __MSDOS__
2289FILE *
2290msdos_openpipe (int* pipedes, int *pidp, char *text)
2291{
2292 FILE *fpipe=0;
2293 /* MSDOS can't fork, but it has `popen'. */
2294 struct variable *sh = lookup_variable ("SHELL", 5);
2295 int e;
2296 extern int dos_command_running, dos_status;
2297
2298 /* Make sure not to bother processing an empty line. */
2299 while (isblank ((unsigned char)*text))
2300 ++text;
2301 if (*text == '\0')
2302 return 0;
2303
2304 if (sh)
2305 {
2306 char buf[PATH_MAX + 7];
2307 /* This makes sure $SHELL value is used by $(shell), even
2308 though the target environment is not passed to it. */
2309 sprintf (buf, "SHELL=%s", sh->value);
2310 putenv (buf);
2311 }
2312
2313 e = errno;
2314 errno = 0;
2315 dos_command_running = 1;
2316 dos_status = 0;
2317 /* If dos_status becomes non-zero, it means the child process
2318 was interrupted by a signal, like SIGINT or SIGQUIT. See
2319 fatal_error_signal in commands.c. */
2320 fpipe = popen (text, "rt");
2321 dos_command_running = 0;
2322 if (!fpipe || dos_status)
2323 {
2324 pipedes[0] = -1;
2325 *pidp = -1;
2326 if (dos_status)
2327 errno = EINTR;
2328 else if (errno == 0)
2329 errno = ENOMEM;
2330 shell_function_completed = -1;
2331 }
2332 else
2333 {
2334 pipedes[0] = fileno (fpipe);
2335 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
2336 errno = e;
2337 shell_function_completed = 1;
2338 }
2339 return fpipe;
2340}
2341#endif
2342
2343/*
2344 Do shell spawning, with the naughty bits for different OSes.
2345 */
2346
2347#ifdef VMS
2348
2349/* VMS can't do $(shell ...) */
2350#define func_shell 0
2351
2352#else
2353#ifndef _AMIGA
2354static char *
2355func_shell (char * volatile o, char **argv, const char *funcname UNUSED)
2356{
2357 char *batch_filename = NULL;
2358
2359#ifdef __MSDOS__
2360 FILE *fpipe;
2361#endif
2362 char **command_argv;
2363 const char * volatile error_prefix; /* bird: this volatile and the 'o' one, is for shutting up gcc warnings */
2364 char **envp;
2365 int pipedes[2];
2366 pid_t pid;
2367
2368#ifndef __MSDOS__
2369 /* Construct the argument list. */
2370 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2371 &batch_filename);
2372 if (command_argv == 0)
2373 return o;
2374#endif
2375
2376 /* Using a target environment for `shell' loses in cases like:
2377 export var = $(shell echo foobie)
2378 because target_environment hits a loop trying to expand $(var)
2379 to put it in the environment. This is even more confusing when
2380 var was not explicitly exported, but just appeared in the
2381 calling environment.
2382
2383 See Savannah bug #10593.
2384
2385 envp = target_environment (NILF);
2386 */
2387
2388 envp = environ;
2389
2390 /* For error messages. */
2391 if (reading_file && reading_file->filenm)
2392 {
2393 char *p = alloca (strlen (reading_file->filenm)+11+4);
2394 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
2395 error_prefix = p;
2396 }
2397 else
2398 error_prefix = "";
2399
2400#if defined(__MSDOS__)
2401 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
2402 if (pipedes[0] < 0)
2403 {
2404 perror_with_name (error_prefix, "pipe");
2405 return o;
2406 }
2407#elif defined(WINDOWS32)
2408 windows32_openpipe (pipedes, &pid, command_argv, envp);
2409 if (pipedes[0] < 0)
2410 {
2411 /* open of the pipe failed, mark as failed execution */
2412 shell_function_completed = -1;
2413
2414 return o;
2415 }
2416 else
2417#else
2418 if (pipe (pipedes) < 0)
2419 {
2420 perror_with_name (error_prefix, "pipe");
2421 return o;
2422 }
2423
2424# ifdef __EMX__
2425 /* close some handles that are unnecessary for the child process */
2426 CLOSE_ON_EXEC(pipedes[1]);
2427 CLOSE_ON_EXEC(pipedes[0]);
2428 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
2429 pid = child_execute_job (0, pipedes[1], command_argv, envp);
2430 if (pid < 0)
2431 perror_with_name (error_prefix, "spawn");
2432# else /* ! __EMX__ */
2433 pid = vfork ();
2434 if (pid < 0)
2435 perror_with_name (error_prefix, "fork");
2436 else if (pid == 0)
2437 child_execute_job (0, pipedes[1], command_argv, envp);
2438 else
2439# endif
2440#endif
2441 {
2442 /* We are the parent. */
2443 char *buffer;
2444 unsigned int maxlen, i;
2445 int cc;
2446
2447 /* Record the PID for reap_children. */
2448 shell_function_pid = pid;
2449#ifndef __MSDOS__
2450 shell_function_completed = 0;
2451
2452 /* Free the storage only the child needed. */
2453 free (command_argv[0]);
2454 free (command_argv);
2455
2456 /* Close the write side of the pipe. We test for -1, since
2457 pipedes[1] is -1 on MS-Windows, and some versions of MS
2458 libraries barf when `close' is called with -1. */
2459 if (pipedes[1] >= 0)
2460 close (pipedes[1]);
2461#endif
2462
2463 /* Set up and read from the pipe. */
2464
2465 maxlen = 200;
2466 buffer = xmalloc (maxlen + 1);
2467
2468 /* Read from the pipe until it gets EOF. */
2469 for (i = 0; ; i += cc)
2470 {
2471 if (i == maxlen)
2472 {
2473 maxlen += 512;
2474 buffer = xrealloc (buffer, maxlen + 1);
2475 }
2476
2477 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
2478 if (cc <= 0)
2479 break;
2480 }
2481 buffer[i] = '\0';
2482
2483 /* Close the read side of the pipe. */
2484#ifdef __MSDOS__
2485 if (fpipe)
2486 (void) pclose (fpipe);
2487#else
2488# ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
2489 if (pipedes[0] != -1)
2490# endif
2491 (void) close (pipedes[0]);
2492#endif
2493
2494 /* Loop until child_handler or reap_children() sets
2495 shell_function_completed to the status of our child shell. */
2496 while (shell_function_completed == 0)
2497 reap_children (1, 0);
2498
2499 if (batch_filename) {
2500 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
2501 batch_filename));
2502 remove (batch_filename);
2503 free (batch_filename);
2504 }
2505 shell_function_pid = 0;
2506
2507 /* The child_handler function will set shell_function_completed
2508 to 1 when the child dies normally, or to -1 if it
2509 dies with status 127, which is most likely an exec fail. */
2510
2511 if (shell_function_completed == -1)
2512 {
2513 /* This likely means that the execvp failed, so we should just
2514 write the error message in the pipe from the child. */
2515 fputs (buffer, stderr);
2516 fflush (stderr);
2517 }
2518 else
2519 {
2520 /* The child finished normally. Replace all newlines in its output
2521 with spaces, and put that in the variable output buffer. */
2522 fold_newlines (buffer, &i);
2523 o = variable_buffer_output (o, buffer, i);
2524 }
2525
2526 free (buffer);
2527 }
2528
2529 return o;
2530}
2531
2532#else /* _AMIGA */
2533
2534/* Do the Amiga version of func_shell. */
2535
2536static char *
2537func_shell (char *o, char **argv, const char *funcname)
2538{
2539 /* Amiga can't fork nor spawn, but I can start a program with
2540 redirection of my choice. However, this means that we
2541 don't have an opportunity to reopen stdout to trap it. Thus,
2542 we save our own stdout onto a new descriptor and dup a temp
2543 file's descriptor onto our stdout temporarily. After we
2544 spawn the shell program, we dup our own stdout back to the
2545 stdout descriptor. The buffer reading is the same as above,
2546 except that we're now reading from a file. */
2547
2548#include <dos/dos.h>
2549#include <proto/dos.h>
2550
2551 BPTR child_stdout;
2552 char tmp_output[FILENAME_MAX];
2553 unsigned int maxlen = 200, i;
2554 int cc;
2555 char * buffer, * ptr;
2556 char ** aptr;
2557 int len = 0;
2558 char* batch_filename = NULL;
2559
2560 /* Construct the argument list. */
2561 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2562 &batch_filename);
2563 if (command_argv == 0)
2564 return o;
2565
2566 /* Note the mktemp() is a security hole, but this only runs on Amiga.
2567 Ideally we would use main.c:open_tmpfile(), but this uses a special
2568 Open(), not fopen(), and I'm not familiar enough with the code to mess
2569 with it. */
2570 strcpy (tmp_output, "t:MakeshXXXXXXXX");
2571 mktemp (tmp_output);
2572 child_stdout = Open (tmp_output, MODE_NEWFILE);
2573
2574 for (aptr=command_argv; *aptr; aptr++)
2575 len += strlen (*aptr) + 1;
2576
2577 buffer = xmalloc (len + 1);
2578 ptr = buffer;
2579
2580 for (aptr=command_argv; *aptr; aptr++)
2581 {
2582 strcpy (ptr, *aptr);
2583 ptr += strlen (ptr) + 1;
2584 *ptr ++ = ' ';
2585 *ptr = 0;
2586 }
2587
2588 ptr[-1] = '\n';
2589
2590 Execute (buffer, NULL, child_stdout);
2591 free (buffer);
2592
2593 Close (child_stdout);
2594
2595 child_stdout = Open (tmp_output, MODE_OLDFILE);
2596
2597 buffer = xmalloc (maxlen);
2598 i = 0;
2599 do
2600 {
2601 if (i == maxlen)
2602 {
2603 maxlen += 512;
2604 buffer = xrealloc (buffer, maxlen + 1);
2605 }
2606
2607 cc = Read (child_stdout, &buffer[i], maxlen - i);
2608 if (cc > 0)
2609 i += cc;
2610 } while (cc > 0);
2611
2612 Close (child_stdout);
2613
2614 fold_newlines (buffer, &i);
2615 o = variable_buffer_output (o, buffer, i);
2616 free (buffer);
2617 return o;
2618}
2619#endif /* _AMIGA */
2620#endif /* !VMS */
2621
2622#ifdef EXPERIMENTAL
2623
2624/*
2625 equality. Return is string-boolean, ie, the empty string is false.
2626 */
2627static char *
2628func_eq (char *o, char **argv, const char *funcname UNUSED)
2629{
2630 int result = ! strcmp (argv[0], argv[1]);
2631 o = variable_buffer_output (o, result ? "1" : "", result);
2632 return o;
2633}
2634
2635
2636/*
2637 string-boolean not operator.
2638 */
2639static char *
2640func_not (char *o, char **argv, const char *funcname UNUSED)
2641{
2642 const char *s = argv[0];
2643 int result = 0;
2644 while (isspace ((unsigned char)*s))
2645 s++;
2646 result = ! (*s);
2647 o = variable_buffer_output (o, result ? "1" : "", result);
2648 return o;
2649}
2650#endif
2651
2652
2653#ifdef CONFIG_WITH_STRING_FUNCTIONS
2654/*
2655 $(length string)
2656
2657 XXX: This doesn't take multibyte locales into account.
2658 */
2659static char *
2660func_length (char *o, char **argv, const char *funcname UNUSED)
2661{
2662 size_t len = strlen (argv[0]);
2663 return math_int_to_variable_buffer (o, len);
2664}
2665
2666/*
2667 $(length-var var)
2668
2669 XXX: This doesn't take multibyte locales into account.
2670 */
2671static char *
2672func_length_var (char *o, char **argv, const char *funcname UNUSED)
2673{
2674 struct variable *var = lookup_variable (argv[0], strlen (argv[0]));
2675 return math_int_to_variable_buffer (o, var ? var->value_length : 0);
2676}
2677
2678
2679/* func_insert and func_substr helper. */
2680static char *
2681helper_pad (char *o, size_t to_add, const char *pad, size_t pad_len)
2682{
2683 while (to_add > 0)
2684 {
2685 size_t size = to_add > pad_len ? pad_len : to_add;
2686 o = variable_buffer_output (o, pad, size);
2687 to_add -= size;
2688 }
2689 return o;
2690}
2691
2692/*
2693 $(insert in, str[, n[, length[, pad]]])
2694
2695 XXX: This doesn't take multibyte locales into account.
2696 */
2697static char *
2698func_insert (char *o, char **argv, const char *funcname UNUSED)
2699{
2700 const char *in = argv[0];
2701 math_int in_len = (math_int)strlen (in);
2702 const char *str = argv[1];
2703 math_int str_len = (math_int)strlen (str);
2704 math_int n = 0;
2705 math_int length = str_len;
2706 const char *pad = " ";
2707 size_t pad_len = 16;
2708 size_t i;
2709
2710 if (argv[2] != NULL)
2711 {
2712 n = math_int_from_string (argv[2]);
2713 if (n > 0)
2714 n--; /* one-origin */
2715 else if (n == 0)
2716 n = str_len; /* append */
2717 else
2718 { /* n < 0: from the end */
2719 n = str_len + n;
2720 if (n < 0)
2721 n = 0;
2722 }
2723 if (n > 16*1024*1024) /* 16MB */
2724 fatal (NILF, _("$(insert ): n=%s is out of bounds\n"), argv[2]);
2725
2726 if (argv[3] != NULL)
2727 {
2728 length = math_int_from_string (argv[3]);
2729 if (length < 0 || length > 16*1024*1024 /* 16MB */)
2730 fatal (NILF, _("$(insert ): length=%s is out of bounds\n"), argv[3]);
2731
2732 if (argv[4] != NULL)
2733 {
2734 const char *tmp = argv[4];
2735 for (i = 0; tmp[i] == ' '; i++)
2736 /* nothing */;
2737 if (tmp[i] != '\0')
2738 {
2739 pad = argv[4];
2740 pad_len = strlen (pad);
2741 }
2742 /* else: it was all default spaces. */
2743 }
2744 }
2745 }
2746
2747 /* the head of the original string */
2748 if (n > 0)
2749 {
2750 if (n <= str_len)
2751 o = variable_buffer_output (o, str, n);
2752 else
2753 {
2754 o = variable_buffer_output (o, str, str_len);
2755 o = helper_pad (o, n - str_len, pad, pad_len);
2756 }
2757 }
2758
2759 /* insert the string */
2760 if (length <= in_len)
2761 o = variable_buffer_output (o, in, length);
2762 else
2763 {
2764 o = variable_buffer_output (o, in, in_len);
2765 o = helper_pad (o, length - in_len, pad, pad_len);
2766 }
2767
2768 /* the tail of the original string */
2769 if (n < str_len)
2770 o = variable_buffer_output (o, str + n, str_len - n);
2771
2772 return o;
2773}
2774
2775
2776/*
2777 $(pos needle, haystack[, start])
2778 $(lastpos needle, haystack[, start])
2779
2780 XXX: This doesn't take multibyte locales into account.
2781 */
2782static char *
2783func_pos (char *o, char **argv, const char *funcname UNUSED)
2784{
2785 const char *needle = *argv[0] ? argv[0] : " ";
2786 size_t needle_len = strlen (needle);
2787 const char *haystack = argv[1];
2788 size_t haystack_len = strlen (haystack);
2789 math_int start = 0;
2790 const char *hit;
2791
2792 if (argv[2] != NULL)
2793 {
2794 start = math_int_from_string (argv[2]);
2795 if (start > 0)
2796 start--; /* one-origin */
2797 else if (start < 0)
2798 start = haystack_len + start; /* from the end */
2799 if (start < 0 || start + needle_len > haystack_len)
2800 return math_int_to_variable_buffer (o, 0);
2801 }
2802 else if (funcname[0] == 'l')
2803 start = haystack_len - 1;
2804
2805 /* do the searching */
2806 if (funcname[0] != 'l')
2807 { /* pos */
2808 if (needle_len == 1)
2809 hit = strchr (haystack + start, *needle);
2810 else
2811 hit = strstr (haystack + start, needle);
2812 }
2813 else
2814 { /* last pos */
2815 int ch = *needle;
2816 size_t off = start + 1;
2817
2818 hit = NULL;
2819 while (off-- > 0)
2820 {
2821 if ( haystack[off] == ch
2822 && ( needle_len == 1
2823 || strncmp (&haystack[off], needle, needle_len) == 0))
2824 {
2825 hit = haystack + off;
2826 break;
2827 }
2828 }
2829 }
2830
2831 return math_int_to_variable_buffer (o, hit ? hit - haystack + 1 : 0);
2832}
2833
2834
2835/*
2836 $(substr str, start[, length[, pad]])
2837
2838 XXX: This doesn't take multibyte locales into account.
2839 */
2840static char *
2841func_substr (char *o, char **argv, const char *funcname UNUSED)
2842{
2843 const char *str = argv[0];
2844 math_int str_len = (math_int)strlen (str);
2845 math_int start = math_int_from_string (argv[1]);
2846 math_int length = 0;
2847 const char *pad = NULL;
2848 size_t pad_len = 0;
2849
2850 if (argv[2] != NULL)
2851 {
2852 if (argv[3] != NULL)
2853 {
2854 pad = argv[3];
2855 for (pad_len = 0; pad[pad_len] == ' '; pad_len++)
2856 /* nothing */;
2857 if (pad[pad_len] != '\0')
2858 pad_len = strlen (pad);
2859 else
2860 {
2861 pad = " ";
2862 pad_len = 16;
2863 }
2864 }
2865 length = math_int_from_string (argv[2]);
2866 if (length < 0 || (pad != NULL && length > 16*1024*1024 /* 16MB */))
2867 fatal (NILF, _("$(substr ): length=%s is out of bounds\n"), argv[3]);
2868 if (length == 0)
2869 return o;
2870 }
2871
2872 /* adjust start and length. */
2873 if (pad == NULL)
2874 {
2875 if (start > 0)
2876 {
2877 start--; /* one-origin */
2878 if (start >= str_len)
2879 return o;
2880 if (length == 0 || start + length > str_len)
2881 length = str_len - start;
2882 }
2883 else
2884 {
2885 start = str_len + start;
2886 if (start <= 0)
2887 {
2888 start += length;
2889 if (start <= 0)
2890 return o;
2891 length = start;
2892 start = 0;
2893 }
2894 else if (length == 0 || start + length > str_len)
2895 length = str_len - start;
2896 }
2897
2898 o = variable_buffer_output (o, str + start, length);
2899 }
2900 else
2901 {
2902 if (start > 0)
2903 {
2904 start--; /* one-origin */
2905 if (start >= str_len)
2906 return length ? helper_pad (o, length, pad, pad_len) : o;
2907 if (length == 0)
2908 length = str_len - start;
2909 }
2910 else
2911 {
2912 start = str_len + start;
2913 if (start <= 0)
2914 {
2915 if (start + length <= 0)
2916 return length ? helper_pad (o, length, pad, pad_len) : o;
2917 o = helper_pad (o, -start, pad, pad_len);
2918 return variable_buffer_output (o, str, length + start);
2919 }
2920 if (length == 0)
2921 length = str_len - start;
2922 }
2923 if (start + length <= str_len)
2924 o = variable_buffer_output (o, str + start, length);
2925 else
2926 {
2927 o = variable_buffer_output (o, str + start, str_len - start);
2928 o = helper_pad (o, start + length - str_len, pad, pad_len);
2929 }
2930 }
2931
2932 return o;
2933}
2934
2935
2936/*
2937 $(translate string, from-set[, to-set[, pad-char]])
2938
2939 XXX: This doesn't take multibyte locales into account.
2940 */
2941static char *
2942func_translate (char *o, char **argv, const char *funcname UNUSED)
2943{
2944 const unsigned char *str = (const unsigned char *)argv[0];
2945 const unsigned char *from_set = (const unsigned char *)argv[1];
2946 const char *to_set = argv[2] != NULL ? argv[2] : "";
2947 char trans_tab[1 << CHAR_BIT];
2948 int i;
2949 char ch;
2950
2951 /* init the array. */
2952 for (i = 0; i < (1 << CHAR_BIT); i++)
2953 trans_tab[i] = i;
2954
2955 while ( (i = *from_set) != '\0'
2956 && (ch = *to_set) != '\0')
2957 {
2958 trans_tab[i] = ch;
2959 from_set++;
2960 to_set++;
2961 }
2962
2963 if (i != '\0')
2964 {
2965 ch = '\0'; /* no padding == remove char */
2966 if (argv[2] != NULL && argv[3] != NULL)
2967 {
2968 ch = argv[3][0];
2969 if (ch && argv[3][1])
2970 fatal (NILF, _("$(translate ): pad=`%s' expected a single char\n"), argv[3]);
2971 if (ch == '\0') /* no char == space */
2972 ch = ' ';
2973 }
2974 while ((i = *from_set++) != '\0')
2975 trans_tab[i] = ch;
2976 }
2977
2978 /* do the translation */
2979 while ((i = *str++) != '\0')
2980 {
2981 ch = trans_tab[i];
2982 if (ch)
2983 o = variable_buffer_output (o, &ch, 1);
2984 }
2985
2986 return o;
2987}
2988#endif /* CONFIG_WITH_STRING_FUNCTIONS */
2989
2990
2991#ifdef CONFIG_WITH_LAZY_DEPS_VARS
2992
2993/* This is also in file.c (bad). */
2994# if VMS
2995# define FILE_LIST_SEPARATOR ','
2996# else
2997# define FILE_LIST_SEPARATOR ' '
2998# endif
2999
3000/* Implements $^ and $+.
3001
3002 The first is somes with with FUNCNAME 'deps', the second as 'deps-all'.
3003
3004 If no second argument is given, or if it's empty, or if it's zero,
3005 all dependencies will be returned. If the second argument is non-zero
3006 the dependency at that position will be returned. If the argument is
3007 negative a fatal error is thrown. */
3008static char *
3009func_deps (char *o, char **argv, const char *funcname)
3010{
3011 unsigned int idx = 0;
3012 struct file *file;
3013
3014 /* Handle the argument if present. */
3015
3016 if (argv[1])
3017 {
3018 char *p = argv[1];
3019 while (isspace ((unsigned int)*p))
3020 p++;
3021 if (*p != '\0')
3022 {
3023 char *n;
3024 long l = strtol (p, &n, 0);
3025 while (isspace ((unsigned int)*n))
3026 n++;
3027 idx = l;
3028 if (*n != '\0' || l < 0 || (long)idx != l)
3029 fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
3030 }
3031 }
3032
3033 /* Find the file and select the list corresponding to FUNCNAME. */
3034
3035 file = lookup_file (argv[0]);
3036 if (file)
3037 {
3038 struct dep *deps = funcname[4] != '\0' && file->org_deps
3039 ? file->org_deps : file->deps;
3040 struct dep *d;
3041
3042 if ( file->double_colon
3043 && ( file->double_colon != file
3044 || file->last != file))
3045 error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3046 funcname, file->name);
3047
3048 if (idx == 0 /* all */)
3049 {
3050 unsigned int total_len = 0;
3051
3052 /* calc the result length. */
3053
3054 for (d = deps; d; d = d->next)
3055 if (!d->ignore_mtime)
3056 {
3057 const char *c = dep_name (d);
3058
3059#ifndef NO_ARCHIVES
3060 if (ar_name (c))
3061 {
3062 c = strchr (c, '(') + 1;
3063 total_len += strlen (c);
3064 }
3065 else
3066#elif defined (CONFIG_WITH_STRCACHE2)
3067 total_len += strcache2_get_len (&file_strcache, c) + 1;
3068#else
3069 total_len += strlen (c) + 1;
3070#endif
3071 }
3072
3073 if (total_len)
3074 {
3075 /* prepare the variable buffer dude wrt to the output size and
3076 pass along the strings. */
3077
3078 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
3079
3080 for (d = deps; d; d = d->next)
3081 if (!d->ignore_mtime)
3082 {
3083 unsigned int len;
3084 const char *c = dep_name (d);
3085
3086#ifndef NO_ARCHIVES
3087 if (ar_name (c))
3088 {
3089 c = strchr (c, '(') + 1;
3090 len = strlen (c);
3091 }
3092 else
3093#elif defined (CONFIG_WITH_STRCACHE2)
3094 len = strcache2_get_len (&file_strcache, c) + 1;
3095#else
3096 len = strlen (c) + 1;
3097#endif
3098 o = variable_buffer_output (o, c, len);
3099 o[-1] = FILE_LIST_SEPARATOR;
3100 }
3101
3102 --o; /* nuke the last list separator */
3103 *o = '\0';
3104 }
3105 }
3106 else
3107 {
3108 /* Dependency given by index. */
3109
3110 for (d = deps; d; d = d->next)
3111 if (!d->ignore_mtime)
3112 {
3113 if (--idx == 0) /* 1 based indexing */
3114 {
3115 unsigned int len;
3116 const char *c = dep_name (d);
3117
3118#ifndef NO_ARCHIVES
3119 if (ar_name (c))
3120 {
3121 c = strchr (c, '(') + 1;
3122 len = strlen (c) - 1;
3123 }
3124 else
3125#elif defined (CONFIG_WITH_STRCACHE2)
3126 len = strcache2_get_len (&file_strcache, c);
3127#else
3128 len = strlen (c);
3129#endif
3130 o = variable_buffer_output (o, c, len);
3131 break;
3132 }
3133 }
3134 }
3135 }
3136
3137 return o;
3138}
3139
3140/* Implements $?.
3141
3142 If no second argument is given, or if it's empty, or if it's zero,
3143 all dependencies will be returned. If the second argument is non-zero
3144 the dependency at that position will be returned. If the argument is
3145 negative a fatal error is thrown. */
3146static char *
3147func_deps_newer (char *o, char **argv, const char *funcname)
3148{
3149 unsigned int idx = 0;
3150 struct file *file;
3151
3152 /* Handle the argument if present. */
3153
3154 if (argv[1])
3155 {
3156 char *p = argv[1];
3157 while (isspace ((unsigned int)*p))
3158 p++;
3159 if (*p != '\0')
3160 {
3161 char *n;
3162 long l = strtol (p, &n, 0);
3163 while (isspace ((unsigned int)*n))
3164 n++;
3165 idx = l;
3166 if (*n != '\0' || l < 0 || (long)idx != l)
3167 fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
3168 }
3169 }
3170
3171 /* Find the file. */
3172
3173 file = lookup_file (argv[0]);
3174 if (file)
3175 {
3176 struct dep *deps = file->deps;
3177 struct dep *d;
3178
3179 if ( file->double_colon
3180 && ( file->double_colon != file
3181 || file->last != file))
3182 error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3183 funcname, file->name);
3184
3185 if (idx == 0 /* all */)
3186 {
3187 unsigned int total_len = 0;
3188
3189 /* calc the result length. */
3190
3191 for (d = deps; d; d = d->next)
3192 if (!d->ignore_mtime && d->changed)
3193 {
3194 const char *c = dep_name (d);
3195
3196#ifndef NO_ARCHIVES
3197 if (ar_name (c))
3198 {
3199 c = strchr (c, '(') + 1;
3200 total_len += strlen (c);
3201 }
3202 else
3203#elif defined (CONFIG_WITH_STRCACHE2)
3204 total_len += strcache2_get_len (&file_strcache, c) + 1;
3205#else
3206 total_len += strlen (c) + 1;
3207#endif
3208 }
3209
3210 if (total_len)
3211 {
3212 /* prepare the variable buffer dude wrt to the output size and
3213 pass along the strings. */
3214
3215 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
3216
3217 for (d = deps; d; d = d->next)
3218 if (!d->ignore_mtime && d->changed)
3219 {
3220 unsigned int len;
3221 const char *c = dep_name (d);
3222
3223#ifndef NO_ARCHIVES
3224 if (ar_name (c))
3225 {
3226 c = strchr (c, '(') + 1;
3227 len = strlen (c);
3228 }
3229 else
3230#elif defined (CONFIG_WITH_STRCACHE2)
3231 len = strcache2_get_len (&file_strcache, c) + 1;
3232#else
3233 len = strlen (c) + 1;
3234#endif
3235 o = variable_buffer_output (o, c, len);
3236 o[-1] = FILE_LIST_SEPARATOR;
3237 }
3238
3239 --o; /* nuke the last list separator */
3240 *o = '\0';
3241 }
3242 }
3243 else
3244 {
3245 /* Dependency given by index. */
3246
3247 for (d = deps; d; d = d->next)
3248 if (!d->ignore_mtime && d->changed)
3249 {
3250 if (--idx == 0) /* 1 based indexing */
3251 {
3252 unsigned int len;
3253 const char *c = dep_name (d);
3254
3255#ifndef NO_ARCHIVES
3256 if (ar_name (c))
3257 {
3258 c = strchr (c, '(') + 1;
3259 len = strlen (c) - 1;
3260 }
3261 else
3262#elif defined (CONFIG_WITH_STRCACHE2)
3263 len = strcache2_get_len (&file_strcache, c);
3264#else
3265 len = strlen (c);
3266#endif
3267 o = variable_buffer_output (o, c, len);
3268 break;
3269 }
3270 }
3271 }
3272 }
3273
3274 return o;
3275}
3276
3277/* Implements $|, the order only dependency list.
3278
3279 If no second argument is given, or if it's empty, or if it's zero,
3280 all dependencies will be returned. If the second argument is non-zero
3281 the dependency at that position will be returned. If the argument is
3282 negative a fatal error is thrown. */
3283static char *
3284func_deps_order_only (char *o, char **argv, const char *funcname)
3285{
3286 unsigned int idx = 0;
3287 struct file *file;
3288
3289 /* Handle the argument if present. */
3290
3291 if (argv[1])
3292 {
3293 char *p = argv[1];
3294 while (isspace ((unsigned int)*p))
3295 p++;
3296 if (*p != '\0')
3297 {
3298 char *n;
3299 long l = strtol (p, &n, 0);
3300 while (isspace ((unsigned int)*n))
3301 n++;
3302 idx = l;
3303 if (*n != '\0' || l < 0 || (long)idx != l)
3304 fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
3305 }
3306 }
3307
3308 /* Find the file. */
3309
3310 file = lookup_file (argv[0]);
3311 if (file)
3312 {
3313 struct dep *deps = file->deps;
3314 struct dep *d;
3315
3316 if ( file->double_colon
3317 && ( file->double_colon != file
3318 || file->last != file))
3319 error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3320 funcname, file->name);
3321
3322 if (idx == 0 /* all */)
3323 {
3324 unsigned int total_len = 0;
3325
3326 /* calc the result length. */
3327
3328 for (d = deps; d; d = d->next)
3329 if (d->ignore_mtime)
3330 {
3331 const char *c = dep_name (d);
3332
3333#ifndef NO_ARCHIVES
3334 if (ar_name (c))
3335 {
3336 c = strchr (c, '(') + 1;
3337 total_len += strlen (c);
3338 }
3339 else
3340#elif defined (CONFIG_WITH_STRCACHE2)
3341 total_len += strcache2_get_len (&file_strcache, c) + 1;
3342#else
3343 total_len += strlen (c) + 1;
3344#endif
3345 }
3346
3347 if (total_len)
3348 {
3349 /* prepare the variable buffer dude wrt to the output size and
3350 pass along the strings. */
3351
3352 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
3353
3354 for (d = deps; d; d = d->next)
3355 if (d->ignore_mtime)
3356 {
3357 unsigned int len;
3358 const char *c = dep_name (d);
3359
3360#ifndef NO_ARCHIVES
3361 if (ar_name (c))
3362 {
3363 c = strchr (c, '(') + 1;
3364 len = strlen (c);
3365 }
3366 else
3367#elif defined (CONFIG_WITH_STRCACHE2)
3368 len = strcache2_get_len (&file_strcache, c) + 1;
3369#else
3370 len = strlen (c) + 1;
3371#endif
3372 o = variable_buffer_output (o, c, len);
3373 o[-1] = FILE_LIST_SEPARATOR;
3374 }
3375
3376 --o; /* nuke the last list separator */
3377 *o = '\0';
3378 }
3379 }
3380 else
3381 {
3382 /* Dependency given by index. */
3383
3384 for (d = deps; d; d = d->next)
3385 if (d->ignore_mtime)
3386 {
3387 if (--idx == 0) /* 1 based indexing */
3388 {
3389 unsigned int len;
3390 const char *c = dep_name (d);
3391
3392#ifndef NO_ARCHIVES
3393 if (ar_name (c))
3394 {
3395 c = strchr (c, '(') + 1;
3396 len = strlen (c) - 1;
3397 }
3398 else
3399#elif defined (CONFIG_WITH_STRCACHE2)
3400 len = strcache2_get_len (&file_strcache, c);
3401#else
3402 len = strlen (c);
3403#endif
3404 o = variable_buffer_output (o, c, len);
3405 break;
3406 }
3407 }
3408 }
3409 }
3410
3411 return o;
3412}
3413#endif /* CONFIG_WITH_LAZY_DEPS_VARS */
3414
3415
3416
3417#ifdef CONFIG_WITH_DEFINED
3418/* Similar to ifdef. */
3419static char *
3420func_defined (char *o, char **argv, const char *funcname UNUSED)
3421{
3422 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
3423 int result = v != NULL && *v->value != '\0';
3424 o = variable_buffer_output (o, result ? "1" : "", result);
3425 return o;
3426}
3427#endif /* CONFIG_WITH_DEFINED*/
3428
3429
3430
3431#ifdef HAVE_DOS_PATHS
3432#define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
3433#define ROOT_LEN 3
3434#else
3435#define IS_ABSOLUTE(n) (n[0] == '/')
3436#define ROOT_LEN 1
3437#endif
3438
3439/* Return the absolute name of file NAME which does not contain any `.',
3440 `..' components nor any repeated path separators ('/'). */
3441#ifdef KMK
3442char *
3443#else
3444static char *
3445#endif
3446abspath (const char *name, char *apath)
3447{
3448 char *dest;
3449 const char *start, *end, *apath_limit;
3450 unsigned long root_len = ROOT_LEN;
3451
3452 if (name[0] == '\0' || apath == NULL)
3453 return NULL;
3454
3455#ifdef WINDOWS32 /* bird */
3456 dest = w32ify((char *)name, 1);
3457 if (!dest)
3458 return NULL;
3459 {
3460 size_t len = strlen(dest);
3461 memcpy(apath, dest, len);
3462 dest = apath + len;
3463 }
3464
3465 (void)end; (void)start; (void)apath_limit;
3466
3467#elif defined __OS2__ /* bird */
3468 if (_abspath(apath, name, GET_PATH_MAX))
3469 return NULL;
3470 dest = strchr(apath, '\0');
3471
3472 (void)end; (void)start; (void)apath_limit; (void)dest;
3473
3474#else /* !WINDOWS32 && !__OS2__ */
3475 apath_limit = apath + GET_PATH_MAX;
3476
3477 if (!IS_ABSOLUTE(name))
3478 {
3479 /* It is unlikely we would make it until here but just to make sure. */
3480 if (!starting_directory)
3481 return NULL;
3482
3483 strcpy (apath, starting_directory);
3484
3485#ifdef HAVE_DOS_PATHS
3486 if (IS_PATHSEP(name[0]))
3487 {
3488 if (IS_PATHSEP(name[1]))
3489 {
3490 /* A UNC. Don't prepend a drive letter. */
3491 apath[0] = name[0];
3492 apath[1] = name[1];
3493 root_len = 2;
3494 }
3495 /* We have /foo, an absolute file name except for the drive
3496 letter. Assume the missing drive letter is the current
3497 drive, which we can get if we remove from starting_directory
3498 everything past the root directory. */
3499 apath[root_len] = '\0';
3500 }
3501#endif
3502
3503 dest = strchr (apath, '\0');
3504 }
3505 else
3506 {
3507 strncpy (apath, name, root_len);
3508 apath[root_len] = '\0';
3509 dest = apath + root_len;
3510 /* Get past the root, since we already copied it. */
3511 name += root_len;
3512#ifdef HAVE_DOS_PATHS
3513 if (!IS_PATHSEP(apath[2]))
3514 {
3515 /* Convert d:foo into d:./foo and increase root_len. */
3516 apath[2] = '.';
3517 apath[3] = '/';
3518 dest++;
3519 root_len++;
3520 /* strncpy above copied one character too many. */
3521 name--;
3522 }
3523 else
3524 apath[2] = '/'; /* make sure it's a forward slash */
3525#endif
3526 }
3527
3528 for (start = end = name; *start != '\0'; start = end)
3529 {
3530 unsigned long len;
3531
3532 /* Skip sequence of multiple path-separators. */
3533 while (IS_PATHSEP(*start))
3534 ++start;
3535
3536 /* Find end of path component. */
3537 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
3538 ;
3539
3540 len = end - start;
3541
3542 if (len == 0)
3543 break;
3544 else if (len == 1 && start[0] == '.')
3545 /* nothing */;
3546 else if (len == 2 && start[0] == '.' && start[1] == '.')
3547 {
3548 /* Back up to previous component, ignore if at root already. */
3549 if (dest > apath + root_len)
3550 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
3551 }
3552 else
3553 {
3554 if (!IS_PATHSEP(dest[-1]))
3555 *dest++ = '/';
3556
3557 if (dest + len >= apath_limit)
3558 return NULL;
3559
3560 dest = memcpy (dest, start, len);
3561 dest += len;
3562 *dest = '\0';
3563 }
3564 }
3565#endif /* !WINDOWS32 && !__OS2__ */
3566
3567 /* Unless it is root strip trailing separator. */
3568 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
3569 --dest;
3570
3571 *dest = '\0';
3572
3573 return apath;
3574}
3575
3576
3577static char *
3578func_realpath (char *o, char **argv, const char *funcname UNUSED)
3579{
3580 /* Expand the argument. */
3581 const char *p = argv[0];
3582 const char *path = 0;
3583 int doneany = 0;
3584 unsigned int len = 0;
3585#ifndef HAVE_REALPATH
3586 struct stat st;
3587#endif
3588 PATH_VAR (in);
3589 PATH_VAR (out);
3590
3591 while ((path = find_next_token (&p, &len)) != 0)
3592 {
3593 if (len < GET_PATH_MAX)
3594 {
3595 strncpy (in, path, len);
3596 in[len] = '\0';
3597
3598 if (
3599#ifdef HAVE_REALPATH
3600 realpath (in, out)
3601#else
3602 abspath (in, out) && stat (out, &st) == 0
3603#endif
3604 )
3605 {
3606 o = variable_buffer_output (o, out, strlen (out));
3607 o = variable_buffer_output (o, " ", 1);
3608 doneany = 1;
3609 }
3610 }
3611 }
3612
3613 /* Kill last space. */
3614 if (doneany)
3615 --o;
3616
3617 return o;
3618}
3619
3620static char *
3621func_abspath (char *o, char **argv, const char *funcname UNUSED)
3622{
3623 /* Expand the argument. */
3624 const char *p = argv[0];
3625 const char *path = 0;
3626 int doneany = 0;
3627 unsigned int len = 0;
3628 PATH_VAR (in);
3629 PATH_VAR (out);
3630
3631 while ((path = find_next_token (&p, &len)) != 0)
3632 {
3633 if (len < GET_PATH_MAX)
3634 {
3635 strncpy (in, path, len);
3636 in[len] = '\0';
3637
3638 if (abspath (in, out))
3639 {
3640 o = variable_buffer_output (o, out, strlen (out));
3641 o = variable_buffer_output (o, " ", 1);
3642 doneany = 1;
3643 }
3644 }
3645 }
3646
3647 /* Kill last space. */
3648 if (doneany)
3649 --o;
3650
3651 return o;
3652}
3653
3654#ifdef CONFIG_WITH_ABSPATHEX
3655/* Same as abspath except that the current path may be given as the
3656 2nd argument. */
3657static char *
3658func_abspathex (char *o, char **argv, const char *funcname UNUSED)
3659{
3660 char *cwd = argv[1];
3661
3662 /* cwd needs leading spaces chopped and may be optional,
3663 in which case we're exactly like $(abspath ). */
3664 if (cwd)
3665 while (isblank (*cwd))
3666 cwd++;
3667 if (!cwd || !*cwd)
3668 o = func_abspath (o, argv, funcname);
3669 else
3670 {
3671 /* Expand the argument. */
3672 const char *p = argv[0];
3673 unsigned int cwd_len = ~0U;
3674 char *path = 0;
3675 int doneany = 0;
3676 unsigned int len = 0;
3677 PATH_VAR (in);
3678 PATH_VAR (out);
3679
3680 while ((path = find_next_token (&p, &len)) != 0)
3681 {
3682 if (len < GET_PATH_MAX)
3683 {
3684#ifdef HAVE_DOS_PATHS
3685 if (path[0] != '/' && path[0] != '\\' && (len < 2 || path[1] != ':') && cwd)
3686#else
3687 if (path[0] != '/' && cwd)
3688#endif
3689 {
3690 /* relative path, prefix with cwd. */
3691 if (cwd_len == ~0U)
3692 cwd_len = strlen (cwd);
3693 if (cwd_len + len + 1 >= GET_PATH_MAX)
3694 continue;
3695 memcpy (in, cwd, cwd_len);
3696 in[cwd_len] = '/';
3697 memcpy (in + cwd_len + 1, path, len);
3698 in[cwd_len + len + 1] = '\0';
3699 }
3700 else
3701 {
3702 /* absolute path pass it as-is. */
3703 memcpy (in, path, len);
3704 in[len] = '\0';
3705 }
3706
3707 if (abspath (in, out))
3708 {
3709 o = variable_buffer_output (o, out, strlen (out));
3710 o = variable_buffer_output (o, " ", 1);
3711 doneany = 1;
3712 }
3713 }
3714 }
3715
3716 /* Kill last space. */
3717 if (doneany)
3718 --o;
3719 }
3720
3721 return o;
3722}
3723#endif
3724
3725#ifdef CONFIG_WITH_XARGS
3726/* Create one or more command lines avoiding the max argument
3727 length restriction of the host OS.
3728
3729 The last argument is the list of arguments that the normal
3730 xargs command would be fed from stdin.
3731
3732 The first argument is initial command and it's arguments.
3733
3734 If there are three or more arguments, the 2nd argument is
3735 the command and arguments to be used on subsequent
3736 command lines. Defaults to the initial command.
3737
3738 If there are four or more arguments, the 3rd argument is
3739 the command to be used at the final command line. Defaults
3740 to the sub sequent or initial command .
3741
3742 A future version of this function may define more arguments
3743 and therefor anyone specifying six or more arguments will
3744 cause fatal errors.
3745
3746 Typical usage is:
3747 $(xargs ar cas mylib.a,$(objects))
3748 or
3749 $(xargs ar cas mylib.a,ar as mylib.a,$(objects))
3750
3751 It will then create one or more "ar mylib.a ..." command
3752 lines with proper \n\t separation so it can be used when
3753 writing rules. */
3754static char *
3755func_xargs (char *o, char **argv, const char *funcname UNUSED)
3756{
3757 int argc;
3758 const char *initial_cmd;
3759 size_t initial_cmd_len;
3760 const char *subsequent_cmd;
3761 size_t subsequent_cmd_len;
3762 const char *final_cmd;
3763 size_t final_cmd_len;
3764 const char *args;
3765 size_t max_args;
3766 int i;
3767
3768#ifdef ARG_MAX
3769 /* ARG_MAX is a bit unreliable (environment), so drop 25% of the max. */
3770# define XARGS_MAX (ARG_MAX - (ARG_MAX / 4))
3771#else /* FIXME: update configure with a command line length test. */
3772# define XARGS_MAX 10240
3773#endif
3774
3775 argc = 0;
3776 while (argv[argc])
3777 argc++;
3778 if (argc > 4)
3779 fatal (NILF, _("Too many arguments for $(xargs)!\n"));
3780
3781 /* first: the initial / default command.*/
3782 initial_cmd = argv[0];
3783 while (isspace ((unsigned char)*initial_cmd))
3784 initial_cmd++;
3785 max_args = initial_cmd_len = strlen (initial_cmd);
3786
3787 /* second: the command for the subsequent command lines. defaults to the initial cmd. */
3788 subsequent_cmd = argc > 2 && argv[1][0] != '\0' ? argv[1] : "";
3789 while (isspace ((unsigned char)*subsequent_cmd))
3790 subsequent_cmd++;
3791 if (*subsequent_cmd)
3792 {
3793 subsequent_cmd_len = strlen (subsequent_cmd);
3794 if (subsequent_cmd_len > max_args)
3795 max_args = subsequent_cmd_len;
3796 }
3797 else
3798 {
3799 subsequent_cmd = initial_cmd;
3800 subsequent_cmd_len = initial_cmd_len;
3801 }
3802
3803 /* third: the final command. defaults to the subseq cmd. */
3804 final_cmd = argc > 3 && argv[2][0] != '\0' ? argv[2] : "";
3805 while (isspace ((unsigned char)*final_cmd))
3806 final_cmd++;
3807 if (*final_cmd)
3808 {
3809 final_cmd_len = strlen (final_cmd);
3810 if (final_cmd_len > max_args)
3811 max_args = final_cmd_len;
3812 }
3813 else
3814 {
3815 final_cmd = subsequent_cmd;
3816 final_cmd_len = subsequent_cmd_len;
3817 }
3818
3819 /* last: the arguments to split up into sensible portions. */
3820 args = argv[argc - 1];
3821
3822 /* calc the max argument length. */
3823 if (XARGS_MAX <= max_args + 2)
3824 fatal (NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
3825 (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
3826 max_args = XARGS_MAX - max_args - 1;
3827
3828 /* generate the commands. */
3829 i = 0;
3830 for (i = 0; ; i++)
3831 {
3832 unsigned int len;
3833 const char *iterator = args;
3834 const char *end = args;
3835 const char *cur;
3836 const char *tmp;
3837
3838 /* scan the arguments till we reach the end or the max length. */
3839 while ((cur = find_next_token(&iterator, &len))
3840 && (size_t)((cur + len) - args) < max_args)
3841 end = cur + len;
3842 if (cur && end == args)
3843 fatal (NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
3844
3845 /* emit the command. */
3846 if (i == 0)
3847 {
3848 o = variable_buffer_output (o, (char *)initial_cmd, initial_cmd_len);
3849 o = variable_buffer_output (o, " ", 1);
3850 }
3851 else if (cur)
3852 {
3853 o = variable_buffer_output (o, "\n\t", 2);
3854 o = variable_buffer_output (o, (char *)subsequent_cmd, subsequent_cmd_len);
3855 o = variable_buffer_output (o, " ", 1);
3856 }
3857 else
3858 {
3859 o = variable_buffer_output (o, "\n\t", 2);
3860 o = variable_buffer_output (o, (char *)final_cmd, final_cmd_len);
3861 o = variable_buffer_output (o, " ", 1);
3862 }
3863
3864 tmp = end;
3865 while (tmp > args && isspace ((unsigned char)tmp[-1])) /* drop trailing spaces. */
3866 tmp--;
3867 o = variable_buffer_output (o, (char *)args, tmp - args);
3868
3869
3870 /* next */
3871 if (!cur)
3872 break;
3873 args = end;
3874 while (isspace ((unsigned char)*args))
3875 args++;
3876 }
3877
3878 return o;
3879}
3880#endif
3881
3882#ifdef CONFIG_WITH_TOUPPER_TOLOWER
3883static char *
3884func_toupper_tolower (char *o, char **argv, const char *funcname)
3885{
3886 /* Expand the argument. */
3887 const char *p = argv[0];
3888 while (*p)
3889 {
3890 /* convert to temporary buffer */
3891 char tmp[256];
3892 unsigned int i;
3893 if (!strcmp(funcname, "toupper"))
3894 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
3895 tmp[i] = toupper(*p);
3896 else
3897 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
3898 tmp[i] = tolower(*p);
3899 o = variable_buffer_output (o, tmp, i);
3900 }
3901
3902 return o;
3903}
3904#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
3905
3906#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
3907
3908/* Strip leading spaces and other things off a command. */
3909static const char *
3910comp_cmds_strip_leading (const char *s, const char *e)
3911{
3912 while (s < e)
3913 {
3914 const char ch = *s;
3915 if (!isblank (ch)
3916 && ch != '@'
3917#ifdef CONFIG_WITH_COMMANDS_FUNC
3918 && ch != '%'
3919#endif
3920 && ch != '+'
3921 && ch != '-')
3922 break;
3923 s++;
3924 }
3925 return s;
3926}
3927
3928/* Worker for func_comp_vars() which is called if the comparision failed.
3929 It will do the slow command by command comparision of the commands
3930 when there invoked as comp-cmds. */
3931static char *
3932comp_vars_ne (char *o, const char *s1, const char *e1, const char *s2, const char *e2,
3933 char *ne_retval, const char *funcname)
3934{
3935 /* give up at once if not comp-cmds or comp-cmds-ex. */
3936 if (strcmp (funcname, "comp-cmds") != 0
3937 && strcmp (funcname, "comp-cmds-ex") != 0)
3938 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
3939 else
3940 {
3941 const char * const s1_start = s1;
3942 int new_cmd = 1;
3943 int diff;
3944 for (;;)
3945 {
3946 /* if it's a new command, strip leading stuff. */
3947 if (new_cmd)
3948 {
3949 s1 = comp_cmds_strip_leading (s1, e1);
3950 s2 = comp_cmds_strip_leading (s2, e2);
3951 new_cmd = 0;
3952 }
3953 if (s1 >= e1 || s2 >= e2)
3954 break;
3955
3956 /*
3957 * Inner compare loop which compares one line.
3958 * FIXME: parse quoting!
3959 */
3960 for (;;)
3961 {
3962 const char ch1 = *s1;
3963 const char ch2 = *s2;
3964 diff = ch1 - ch2;
3965 if (diff)
3966 break;
3967 if (ch1 == '\n')
3968 break;
3969 assert (ch1 != '\r');
3970
3971 /* next */
3972 s1++;
3973 s2++;
3974 if (s1 >= e1 || s2 >= e2)
3975 break;
3976 }
3977
3978 /*
3979 * If we exited because of a difference try to end-of-command
3980 * comparision, e.g. ignore trailing spaces.
3981 */
3982 if (diff)
3983 {
3984 /* strip */
3985 while (s1 < e1 && isblank (*s1))
3986 s1++;
3987 while (s2 < e2 && isblank (*s2))
3988 s2++;
3989 if (s1 >= e1 || s2 >= e2)
3990 break;
3991
3992 /* compare again and check that it's a newline. */
3993 if (*s2 != '\n' || *s1 != '\n')
3994 break;
3995 }
3996 /* Break out if we exited because of EOS. */
3997 else if (s1 >= e1 || s2 >= e2)
3998 break;
3999
4000 /*
4001 * Detect the end of command lines.
4002 */
4003 if (*s1 == '\n')
4004 new_cmd = s1 == s1_start || s1[-1] != '\\';
4005 s1++;
4006 s2++;
4007 }
4008
4009 /*
4010 * Ignore trailing empty lines.
4011 */
4012 if (s1 < e1 || s2 < e2)
4013 {
4014 while (s1 < e1 && (isblank (*s1) || *s1 == '\n'))
4015 if (*s1++ == '\n')
4016 s1 = comp_cmds_strip_leading (s1, e1);
4017 while (s2 < e2 && (isblank (*s2) || *s2 == '\n'))
4018 if (*s2++ == '\n')
4019 s2 = comp_cmds_strip_leading (s2, e2);
4020 }
4021
4022 /* emit the result. */
4023 if (s1 == e1 && s2 == e2)
4024 o = variable_buffer_output (o, "", 1) - 1; /** @todo check why this was necessary back the... */
4025 else
4026 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
4027 }
4028 return o;
4029}
4030
4031/*
4032 $(comp-vars var1,var2,not-equal-return)
4033 or
4034 $(comp-cmds cmd-var1,cmd-var2,not-equal-return)
4035
4036 Compares the two variables (that's given by name to avoid unnecessary
4037 expanding) and return the string in the third argument if not equal.
4038 If equal, nothing is returned.
4039
4040 comp-vars will to an exact comparision only stripping leading and
4041 trailing spaces.
4042
4043 comp-cmds will compare command by command, ignoring not only leading
4044 and trailing spaces on each line but also leading one leading '@',
4045 '-', '+' and '%'
4046*/
4047static char *
4048func_comp_vars (char *o, char **argv, const char *funcname)
4049{
4050 const char *s1, *e1, *x1, *s2, *e2, *x2;
4051 char *a1 = NULL, *a2 = NULL;
4052 size_t l, l1, l2;
4053 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
4054 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
4055
4056 /* the simple cases */
4057 if (var1 == var2)
4058 return variable_buffer_output (o, "", 0); /* eq */
4059 if (!var1 || !var2)
4060 return variable_buffer_output (o, argv[2], strlen(argv[2]));
4061 if (var1->value == var2->value)
4062 return variable_buffer_output (o, "", 0); /* eq */
4063 if (!var1->recursive && !var2->recursive)
4064 {
4065 if ( var1->value_length == var2->value_length
4066 && !memcmp (var1->value, var2->value, var1->value_length))
4067 return variable_buffer_output (o, "", 0); /* eq */
4068
4069 /* ignore trailing and leading blanks */
4070 s1 = var1->value;
4071 e1 = s1 + var1->value_length;
4072 while (isblank ((unsigned char) *s1))
4073 s1++;
4074 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
4075 e1--;
4076
4077 s2 = var2->value;
4078 e2 = s2 + var2->value_length;
4079 while (isblank ((unsigned char) *s2))
4080 s2++;
4081 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
4082 e2--;
4083
4084 if (e1 - s1 != e2 - s2)
4085 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4086 if (!memcmp (s1, s2, e1 - s1))
4087 return variable_buffer_output (o, "", 0); /* eq */
4088 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4089 }
4090
4091 /* ignore trailing and leading blanks */
4092 s1 = var1->value;
4093 e1 = s1 + var1->value_length;
4094 while (isblank ((unsigned char) *s1))
4095 s1++;
4096 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
4097 e1--;
4098
4099 s2 = var2->value;
4100 e2 = s2 + var2->value_length;
4101 while (isblank((unsigned char)*s2))
4102 s2++;
4103 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
4104 e2--;
4105
4106 /* both empty after stripping? */
4107 if (s1 == e1 && s2 == e2)
4108 return variable_buffer_output (o, "", 0); /* eq */
4109
4110 /* optimist. */
4111 if ( e1 - s1 == e2 - s2
4112 && !memcmp(s1, s2, e1 - s1))
4113 return variable_buffer_output (o, "", 0); /* eq */
4114
4115 /* compare up to the first '$' or the end. */
4116 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
4117 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
4118 if (!x1 && !x2)
4119 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4120
4121 l1 = x1 ? x1 - s1 : e1 - s1;
4122 l2 = x2 ? x2 - s2 : e2 - s2;
4123 l = l1 <= l2 ? l1 : l2;
4124 if (l && memcmp (s1, s2, l))
4125 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4126
4127 /* one or both buffers now require expanding. */
4128 if (!x1)
4129 s1 += l;
4130 else
4131 {
4132 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
4133 if (!l)
4134 while (isblank ((unsigned char) *s1))
4135 s1++;
4136 e1 = strchr (s1, '\0');
4137 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
4138 e1--;
4139 }
4140
4141 if (!x2)
4142 s2 += l;
4143 else
4144 {
4145 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
4146 if (!l)
4147 while (isblank ((unsigned char) *s2))
4148 s2++;
4149 e2 = strchr (s2, '\0');
4150 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
4151 e2--;
4152 }
4153
4154 /* the final compare */
4155 if ( e1 - s1 != e2 - s2
4156 || memcmp (s1, s2, e1 - s1))
4157 o = comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4158 else
4159 o = variable_buffer_output (o, "", 1) - 1; /* eq */ /** @todo check why this was necessary back the... */
4160 if (a1)
4161 free (a1);
4162 if (a2)
4163 free (a2);
4164 return o;
4165}
4166
4167/*
4168 $(comp-cmds-ex cmds1,cmds2,not-equal-return)
4169
4170 Compares the two strings and return the string in the third argument
4171 if not equal. If equal, nothing is returned.
4172
4173 The comparision will be performed command by command, ignoring not
4174 only leading and trailing spaces on each line but also leading one
4175 leading '@', '-', '+' and '%'.
4176*/
4177static char *
4178func_comp_cmds_ex (char *o, char **argv, const char *funcname)
4179{
4180 const char *s1, *e1, *s2, *e2;
4181 size_t l1, l2;
4182
4183 /* the simple cases */
4184 s1 = argv[0];
4185 s2 = argv[1];
4186 if (s1 == s2)
4187 return variable_buffer_output (o, "", 0); /* eq */
4188 l1 = strlen (argv[0]);
4189 l2 = strlen (argv[1]);
4190
4191 if ( l1 == l2
4192 && !memcmp (s1, s2, l1))
4193 return variable_buffer_output (o, "", 0); /* eq */
4194
4195 /* ignore trailing and leading blanks */
4196 e1 = s1 + l1;
4197 s1 = comp_cmds_strip_leading (s1, e1);
4198
4199 e2 = s2 + l2;
4200 s2 = comp_cmds_strip_leading (s2, e2);
4201
4202 if (e1 - s1 != e2 - s2)
4203 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4204 if (!memcmp (s1, s2, e1 - s1))
4205 return variable_buffer_output (o, "", 0); /* eq */
4206 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4207}
4208#endif
4209
4210#ifdef CONFIG_WITH_DATE
4211# if defined (_MSC_VER) /* FIXME: !defined (HAVE_STRPTIME) */
4212char *strptime(const char *s, const char *format, struct tm *tm)
4213{
4214 return (char *)"strptime is not implemented";
4215}
4216# endif
4217/* Check if the string is all blanks or not. */
4218static int
4219all_blanks (const char *s)
4220{
4221 if (!s)
4222 return 1;
4223 while (isspace ((unsigned char)*s))
4224 s++;
4225 return *s == '\0';
4226}
4227
4228/* The first argument is the strftime format string, a iso
4229 timestamp is the default if nothing is given.
4230
4231 The second argument is a time value if given. The format
4232 is either the format from the first argument or given as
4233 an additional third argument. */
4234static char *
4235func_date (char *o, char **argv, const char *funcname)
4236{
4237 char *p;
4238 char *buf;
4239 size_t buf_size;
4240 struct tm t;
4241 const char *format;
4242
4243 /* determin the format - use a single word as the default. */
4244 format = !strcmp (funcname, "date-utc")
4245 ? "%Y-%m-%dT%H:%M:%SZ"
4246 : "%Y-%m-%dT%H:%M:%S";
4247 if (!all_blanks (argv[0]))
4248 format = argv[0];
4249
4250 /* get the time. */
4251 memset (&t, 0, sizeof(t));
4252 if (argv[0] && !all_blanks (argv[1]))
4253 {
4254 const char *input_format = !all_blanks (argv[2]) ? argv[2] : format;
4255 p = strptime (argv[1], input_format, &t);
4256 if (!p || *p != '\0')
4257 {
4258 error (NILF, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname,
4259 argv[1], input_format, p ? p : "<null>");
4260 return variable_buffer_output (o, "", 0);
4261 }
4262 }
4263 else
4264 {
4265 time_t tval;
4266 time (&tval);
4267 if (!strcmp (funcname, "date-utc"))
4268 t = *gmtime (&tval);
4269 else
4270 t = *localtime (&tval);
4271 }
4272
4273 /* format it. note that zero isn't necessarily an error, so we'll
4274 have to keep shut about failures. */
4275 buf_size = 64;
4276 buf = xmalloc (buf_size);
4277 while (strftime (buf, buf_size, format, &t) == 0)
4278 {
4279 if (buf_size >= 4096)
4280 {
4281 *buf = '\0';
4282 break;
4283 }
4284 buf = xrealloc (buf, buf_size <<= 1);
4285 }
4286 o = variable_buffer_output (o, buf, strlen (buf));
4287 free (buf);
4288 return o;
4289}
4290#endif
4291
4292#ifdef CONFIG_WITH_FILE_SIZE
4293/* Prints the size of the specified file. Only one file is
4294 permitted, notthing is stripped. -1 is returned if stat
4295 fails. */
4296static char *
4297func_file_size (char *o, char **argv, const char *funcname UNUSED)
4298{
4299 struct stat st;
4300 if (stat (argv[0], &st))
4301 return variable_buffer_output (o, "-1", 2);
4302 return math_int_to_variable_buffer (o, st.st_size);
4303}
4304#endif
4305
4306#ifdef CONFIG_WITH_WHICH
4307/* Checks if the specified file exists an is executable.
4308 On systems employing executable extensions, the name may
4309 be modified to include the extension. */
4310static int func_which_test_x (char *file)
4311{
4312 struct stat st;
4313# if defined(WINDOWS32) || defined(__OS2__)
4314 char *ext;
4315 char *slash;
4316
4317 /* fix slashes first. */
4318 slash = file;
4319 while ((slash = strchr (slash, '\\')) != NULL)
4320 *slash++ = '/';
4321
4322 /* straight */
4323 if (stat (file, &st) == 0
4324 && S_ISREG (st.st_mode))
4325 return 1;
4326
4327 /* don't try add an extension if there already is one */
4328 ext = strchr (file, '\0');
4329 if (ext - file >= 4
4330 && ( !stricmp (ext - 4, ".exe")
4331 || !stricmp (ext - 4, ".cmd")
4332 || !stricmp (ext - 4, ".bat")
4333 || !stricmp (ext - 4, ".com")))
4334 return 0;
4335
4336 /* try the extensions. */
4337 strcpy (ext, ".exe");
4338 if (stat (file, &st) == 0
4339 && S_ISREG (st.st_mode))
4340 return 1;
4341
4342 strcpy (ext, ".cmd");
4343 if (stat (file, &st) == 0
4344 && S_ISREG (st.st_mode))
4345 return 1;
4346
4347 strcpy (ext, ".bat");
4348 if (stat (file, &st) == 0
4349 && S_ISREG (st.st_mode))
4350 return 1;
4351
4352 strcpy (ext, ".com");
4353 if (stat (file, &st) == 0
4354 && S_ISREG (st.st_mode))
4355 return 1;
4356
4357 return 0;
4358
4359# else
4360
4361 return access (file, X_OK) == 0
4362 && stat (file, &st) == 0
4363 && S_ISREG (st.st_mode);
4364# endif
4365}
4366
4367/* Searches for the specified programs in the PATH and print
4368 their full location if found. Prints nothing if not found. */
4369static char *
4370func_which (char *o, char **argv, const char *funcname UNUSED)
4371{
4372 const char *path;
4373 struct variable *path_var;
4374 unsigned i;
4375 int first = 1;
4376 PATH_VAR (buf);
4377
4378 path_var = lookup_variable ("PATH", 4);
4379 if (path_var)
4380 path = path_var->value;
4381 else
4382 path = ".";
4383
4384 /* iterate input */
4385 for (i = 0; argv[i]; i++)
4386 {
4387 unsigned int len;
4388 const char *iterator = argv[i];
4389 char *cur;
4390
4391 while ((cur = find_next_token (&iterator, &len)))
4392 {
4393 /* if there is a separator, don't walk the path. */
4394 if (memchr (cur, '/', len)
4395#ifdef HAVE_DOS_PATHS
4396 || memchr (cur, '\\', len)
4397 || memchr (cur, ':', len)
4398#endif
4399 )
4400 {
4401 if (len + 1 + 4 < GET_PATH_MAX) /* +4 for .exe */
4402 {
4403 memcpy (buf, cur, len);
4404 buf[len] = '\0';
4405 if (func_which_test_x (buf))
4406 o = variable_buffer_output (o, buf, strlen (buf));
4407 }
4408 }
4409 else
4410 {
4411 const char *comp = path;
4412 for (;;)
4413 {
4414 const char *src = comp;
4415 const char *end = strchr (comp, PATH_SEPARATOR_CHAR);
4416 size_t comp_len = end ? (size_t)(end - comp) : strlen (comp);
4417 if (!comp_len)
4418 {
4419 comp_len = 1;
4420 src = ".";
4421 }
4422 if (len + comp_len + 2 + 4 < GET_PATH_MAX) /* +4 for .exe */
4423 {
4424 memcpy (buf, comp, comp_len);
4425 buf [comp_len] = '/';
4426 memcpy (&buf[comp_len + 1], cur, len);
4427 buf[comp_len + 1 + len] = '\0';
4428
4429 if (func_which_test_x (buf))
4430 {
4431 if (!first)
4432 o = variable_buffer_output (o, " ", 1);
4433 o = variable_buffer_output (o, buf, strlen (buf));
4434 first = 0;
4435 break;
4436 }
4437 }
4438
4439 /* next */
4440 if (!end)
4441 break;
4442 comp = end + 1;
4443 }
4444 }
4445 }
4446 }
4447
4448 return variable_buffer_output (o, "", 0);
4449}
4450#endif /* CONFIG_WITH_WHICH */
4451
4452#ifdef CONFIG_WITH_IF_CONDITIONALS
4453
4454/* Evaluates the expression given in the argument using the
4455 same evaluator as for the new 'if' statements, except now
4456 we don't force the result into a boolean like for 'if' and
4457 '$(if-expr ,,)'. */
4458static char *
4459func_expr (char *o, char **argv, const char *funcname UNUSED)
4460{
4461 o = expr_eval_to_string (o, argv[0]);
4462 return o;
4463}
4464
4465/* Same as '$(if ,,)' except the first argument is evaluated
4466 using the same evaluator as for the new 'if' statements. */
4467static char *
4468func_if_expr (char *o, char **argv, const char *funcname UNUSED)
4469{
4470 int rc;
4471 char *to_expand;
4472
4473 /* Evaluate the condition in argv[0] and expand the 2nd or
4474 3rd (optional) argument according to the result. */
4475 rc = expr_eval_if_conditionals (argv[0], NULL);
4476 to_expand = rc == 0 ? argv[1] : argv[2];
4477 if (to_expand && *to_expand)
4478 variable_expand_string_2 (o, to_expand, -1, &o);
4479
4480 return o;
4481}
4482
4483/*
4484 $(select when1-cond, when1-body[,whenN-cond, whenN-body]).
4485 */
4486static char *
4487func_select (char *o, char **argv, const char *funcname UNUSED)
4488{
4489 int i;
4490
4491 /* Test WHEN-CONDs until one matches. The check for 'otherwise[:]'
4492 and 'default[:]' make this a bit more fun... */
4493
4494 for (i = 0; argv[i] != NULL; i += 2)
4495 {
4496 const char *cond = argv[i];
4497 int is_otherwise = 0;
4498
4499 if (argv[i + 1] == NULL)
4500 fatal (NILF, _("$(select ): not an even argument count\n"));
4501
4502 while (isspace ((unsigned char)*cond))
4503 cond++;
4504 if ( (*cond == 'o' && strncmp (cond, "otherwise", 9) == 0)
4505 || (*cond == 'd' && strncmp (cond, "default", 7) == 0))
4506 {
4507 const char *end = cond + (*cond == 'o' ? 9 : 7);
4508 while (isspace ((unsigned char)*end))
4509 end++;
4510 if (*end == ':')
4511 do end++;
4512 while (isspace ((unsigned char)*end));
4513 is_otherwise = *end == '\0';
4514 }
4515
4516 if ( is_otherwise
4517 || expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
4518 {
4519 variable_expand_string_2 (o, argv[i + 1], -1, &o);
4520 break;
4521 }
4522 }
4523
4524 return o;
4525}
4526
4527#endif /* CONFIG_WITH_IF_CONDITIONALS */
4528
4529#ifdef CONFIG_WITH_SET_CONDITIONALS
4530static char *
4531func_set_intersects (char *o, char **argv, const char *funcname UNUSED)
4532{
4533 const char *s1_cur;
4534 unsigned int s1_len;
4535 const char *s1_iterator = argv[0];
4536
4537 while ((s1_cur = find_next_token (&s1_iterator, &s1_len)) != 0)
4538 {
4539 const char *s2_cur;
4540 unsigned int s2_len;
4541 const char *s2_iterator = argv[1];
4542 while ((s2_cur = find_next_token (&s2_iterator, &s2_len)) != 0)
4543 if (s2_len == s1_len
4544 && strneq (s2_cur, s1_cur, s1_len) )
4545 return variable_buffer_output (o, "1", 1); /* found intersection */
4546 }
4547
4548 return o; /* no intersection */
4549}
4550#endif /* CONFIG_WITH_SET_CONDITIONALS */
4551
4552#ifdef CONFIG_WITH_STACK
4553
4554/* Push an item (string without spaces). */
4555static char *
4556func_stack_push (char *o, char **argv, const char *funcname UNUSED)
4557{
4558 do_variable_definition(NILF, argv[0], argv[1], o_file, f_append, 0 /* !target_var */);
4559 return o;
4560}
4561
4562/* Pops an item off the stack / get the top stack element.
4563 (This is what's tricky to do in pure GNU make syntax.) */
4564static char *
4565func_stack_pop_top (char *o, char **argv, const char *funcname)
4566{
4567 struct variable *stack_var;
4568 const char *stack = argv[0];
4569
4570 stack_var = lookup_variable (stack, strlen (stack) );
4571 if (stack_var)
4572 {
4573 unsigned int len;
4574 const char *iterator = stack_var->value;
4575 char *lastitem = NULL;
4576 char *cur;
4577
4578 while ((cur = find_next_token (&iterator, &len)))
4579 lastitem = cur;
4580
4581 if (lastitem != NULL)
4582 {
4583 if (strcmp (funcname, "stack-popv") != 0)
4584 o = variable_buffer_output (o, lastitem, len);
4585 if (strcmp (funcname, "stack-top") != 0)
4586 {
4587 *lastitem = '\0';
4588 while (lastitem > stack_var->value && isspace (lastitem[-1]))
4589 *--lastitem = '\0';
4590#ifdef CONFIG_WITH_VALUE_LENGTH
4591 stack_var->value_length = lastitem - stack_var->value;
4592#endif
4593 }
4594 }
4595 }
4596 return o;
4597}
4598#endif /* CONFIG_WITH_STACK */
4599
4600#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE)
4601/* outputs the number (as a string) into the variable buffer. */
4602static char *
4603math_int_to_variable_buffer (char *o, math_int num)
4604{
4605 static const char xdigits[17] = "0123456789abcdef";
4606 int negative;
4607 char strbuf[24]; /* 16 hex + 2 prefix + sign + term => 20
4608 or 20 dec + sign + term => 22 */
4609 char *str = &strbuf[sizeof (strbuf) - 1];
4610
4611 negative = num < 0;
4612 if (negative)
4613 num = -num;
4614
4615 *str = '\0';
4616
4617 do
4618 {
4619#ifdef HEX_MATH_NUMBERS
4620 *--str = xdigits[num & 0xf];
4621 num >>= 4;
4622#else
4623 *--str = xdigits[num % 10];
4624 num /= 10;
4625#endif
4626 }
4627 while (num);
4628
4629#ifdef HEX_MATH_NUMBERS
4630 *--str = 'x';
4631 *--str = '0';
4632#endif
4633
4634 if (negative)
4635 *--str = '-';
4636
4637 return variable_buffer_output (o, str, &strbuf[sizeof (strbuf) - 1] - str);
4638}
4639#endif /* CONFIG_WITH_MATH || CONFIG_WITH_NANOTS */
4640
4641#ifdef CONFIG_WITH_MATH
4642
4643/* Converts a string to an integer, causes an error if the format is invalid. */
4644static math_int
4645math_int_from_string (const char *str)
4646{
4647 const char *start;
4648 unsigned base = 0;
4649 int negative = 0;
4650 math_int num = 0;
4651
4652 /* strip spaces */
4653 while (isspace (*str))
4654 str++;
4655 if (!*str)
4656 {
4657 error (NILF, _("bad number: empty\n"));
4658 return 0;
4659 }
4660 start = str;
4661
4662 /* check for +/- */
4663 while (*str == '+' || *str == '-' || isspace (*str))
4664 if (*str++ == '-')
4665 negative = !negative;
4666
4667 /* check for prefix - we do not accept octal numbers, sorry. */
4668 if (*str == '0' && (str[1] == 'x' || str[1] == 'X'))
4669 {
4670 base = 16;
4671 str += 2;
4672 }
4673 else
4674 {
4675 /* look for a hex digit, if not found treat it as decimal */
4676 const char *p2 = str;
4677 for ( ; *p2; p2++)
4678 if (isxdigit (*p2) && !isdigit (*p2) && isascii (*p2) )
4679 {
4680 base = 16;
4681 break;
4682 }
4683 if (base == 0)
4684 base = 10;
4685 }
4686
4687 /* must have at least one digit! */
4688 if ( !isascii (*str)
4689 || !(base == 16 ? isxdigit (*str) : isdigit (*str)) )
4690 {
4691 error (NILF, _("bad number: '%s'\n"), start);
4692 return 0;
4693 }
4694
4695 /* convert it! */
4696 while (*str && !isspace (*str))
4697 {
4698 int ch = *str++;
4699 if (ch >= '0' && ch <= '9')
4700 ch -= '0';
4701 else if (base == 16 && ch >= 'a' && ch <= 'f')
4702 ch -= 'a' - 10;
4703 else if (base == 16 && ch >= 'A' && ch <= 'F')
4704 ch -= 'A' - 10;
4705 else
4706 {
4707 error (NILF, _("bad number: '%s' (base=%u, pos=%lu)\n"), start, base, (unsigned long)(str - start));
4708 return 0;
4709 }
4710 num *= base;
4711 num += ch;
4712 }
4713
4714 /* check trailing spaces. */
4715 while (isspace (*str))
4716 str++;
4717 if (*str)
4718 {
4719 error (NILF, _("bad number: '%s'\n"), start);
4720 return 0;
4721 }
4722
4723 return negative ? -num : num;
4724}
4725
4726/* Add two or more integer numbers. */
4727static char *
4728func_int_add (char *o, char **argv, const char *funcname UNUSED)
4729{
4730 math_int num;
4731 int i;
4732
4733 num = math_int_from_string (argv[0]);
4734 for (i = 1; argv[i]; i++)
4735 num += math_int_from_string (argv[i]);
4736
4737 return math_int_to_variable_buffer (o, num);
4738}
4739
4740/* Subtract two or more integer numbers. */
4741static char *
4742func_int_sub (char *o, char **argv, const char *funcname UNUSED)
4743{
4744 math_int num;
4745 int i;
4746
4747 num = math_int_from_string (argv[0]);
4748 for (i = 1; argv[i]; i++)
4749 num -= math_int_from_string (argv[i]);
4750
4751 return math_int_to_variable_buffer (o, num);
4752}
4753
4754/* Multiply two or more integer numbers. */
4755static char *
4756func_int_mul (char *o, char **argv, const char *funcname UNUSED)
4757{
4758 math_int num;
4759 int i;
4760
4761 num = math_int_from_string (argv[0]);
4762 for (i = 1; argv[i]; i++)
4763 num *= math_int_from_string (argv[i]);
4764
4765 return math_int_to_variable_buffer (o, num);
4766}
4767
4768/* Divide an integer number by one or more divisors. */
4769static char *
4770func_int_div (char *o, char **argv, const char *funcname UNUSED)
4771{
4772 math_int num;
4773 math_int divisor;
4774 int i;
4775
4776 num = math_int_from_string (argv[0]);
4777 for (i = 1; argv[i]; i++)
4778 {
4779 divisor = math_int_from_string (argv[i]);
4780 if (!divisor)
4781 {
4782 error (NILF, _("divide by zero ('%s')\n"), argv[i]);
4783 return math_int_to_variable_buffer (o, 0);
4784 }
4785 num /= divisor;
4786 }
4787
4788 return math_int_to_variable_buffer (o, num);
4789}
4790
4791
4792/* Divide and return the remainder. */
4793static char *
4794func_int_mod (char *o, char **argv, const char *funcname UNUSED)
4795{
4796 math_int num;
4797 math_int divisor;
4798
4799 num = math_int_from_string (argv[0]);
4800 divisor = math_int_from_string (argv[1]);
4801 if (!divisor)
4802 {
4803 error (NILF, _("divide by zero ('%s')\n"), argv[1]);
4804 return math_int_to_variable_buffer (o, 0);
4805 }
4806 num %= divisor;
4807
4808 return math_int_to_variable_buffer (o, num);
4809}
4810
4811/* 2-complement. */
4812static char *
4813func_int_not (char *o, char **argv, const char *funcname UNUSED)
4814{
4815 math_int num;
4816
4817 num = math_int_from_string (argv[0]);
4818 num = ~num;
4819
4820 return math_int_to_variable_buffer (o, num);
4821}
4822
4823/* Bitwise AND (two or more numbers). */
4824static char *
4825func_int_and (char *o, char **argv, const char *funcname UNUSED)
4826{
4827 math_int num;
4828 int i;
4829
4830 num = math_int_from_string (argv[0]);
4831 for (i = 1; argv[i]; i++)
4832 num &= math_int_from_string (argv[i]);
4833
4834 return math_int_to_variable_buffer (o, num);
4835}
4836
4837/* Bitwise OR (two or more numbers). */
4838static char *
4839func_int_or (char *o, char **argv, const char *funcname UNUSED)
4840{
4841 math_int num;
4842 int i;
4843
4844 num = math_int_from_string (argv[0]);
4845 for (i = 1; argv[i]; i++)
4846 num |= math_int_from_string (argv[i]);
4847
4848 return math_int_to_variable_buffer (o, num);
4849}
4850
4851/* Bitwise XOR (two or more numbers). */
4852static char *
4853func_int_xor (char *o, char **argv, const char *funcname UNUSED)
4854{
4855 math_int num;
4856 int i;
4857
4858 num = math_int_from_string (argv[0]);
4859 for (i = 1; argv[i]; i++)
4860 num ^= math_int_from_string (argv[i]);
4861
4862 return math_int_to_variable_buffer (o, num);
4863}
4864
4865/* Compare two integer numbers. Returns make boolean (true="1"; false=""). */
4866static char *
4867func_int_cmp (char *o, char **argv, const char *funcname)
4868{
4869 math_int num1;
4870 math_int num2;
4871 int rc;
4872
4873 num1 = math_int_from_string (argv[0]);
4874 num2 = math_int_from_string (argv[1]);
4875
4876 funcname += sizeof ("int-") - 1;
4877 if (!strcmp (funcname, "eq"))
4878 rc = num1 == num2;
4879 else if (!strcmp (funcname, "ne"))
4880 rc = num1 != num2;
4881 else if (!strcmp (funcname, "gt"))
4882 rc = num1 > num2;
4883 else if (!strcmp (funcname, "ge"))
4884 rc = num1 >= num2;
4885 else if (!strcmp (funcname, "lt"))
4886 rc = num1 < num2;
4887 else /*if (!strcmp (funcname, "le"))*/
4888 rc = num1 <= num2;
4889
4890 return variable_buffer_output (o, rc ? "1" : "", rc);
4891}
4892
4893#endif /* CONFIG_WITH_MATH */
4894
4895#ifdef CONFIG_WITH_NANOTS
4896/* Returns the current timestamp as nano seconds. The time
4897 source is a high res monotone one if the platform provides
4898 this (and we know about it).
4899
4900 Tip. Use this with int-sub to profile makefile reading
4901 and similar. */
4902static char *
4903func_nanots (char *o, char **argv UNUSED, const char *funcname UNUSED)
4904{
4905 return math_int_to_variable_buffer (o, nano_timestamp ());
4906}
4907#endif
4908
4909#ifdef CONFIG_WITH_OS2_LIBPATH
4910/* Sets or gets the OS/2 libpath variables.
4911
4912 The first argument indicates which variable - BEGINLIBPATH,
4913 ENDLIBPATH, LIBPATHSTRICT or LIBPATH.
4914
4915 The second indicates whether this is a get (not present) or
4916 set (present) operation. When present it is the new value for
4917 the variable. */
4918static char *
4919func_os2_libpath (char *o, char **argv, const char *funcname UNUSED)
4920{
4921 char buf[4096];
4922 ULONG fVar;
4923 APIRET rc;
4924
4925 /* translate variable name (first arg) */
4926 if (!strcmp (argv[0], "BEGINLIBPATH"))
4927 fVar = BEGIN_LIBPATH;
4928 else if (!strcmp (argv[0], "ENDLIBPATH"))
4929 fVar = END_LIBPATH;
4930 else if (!strcmp (argv[0], "LIBPATHSTRICT"))
4931 fVar = LIBPATHSTRICT;
4932 else if (!strcmp (argv[0], "LIBPATH"))
4933 fVar = 0;
4934 else
4935 {
4936 error (NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
4937 return variable_buffer_output (o, "", 0);
4938 }
4939
4940 if (!argv[1])
4941 {
4942 /* get the variable value. */
4943 if (fVar != 0)
4944 {
4945 buf[0] = buf[1] = buf[2] = buf[3] = '\0';
4946 rc = DosQueryExtLIBPATH (buf, fVar);
4947 }
4948 else
4949 rc = DosQueryHeaderInfo (NULLHANDLE, 0, buf, sizeof(buf), QHINF_LIBPATH);
4950 if (rc != NO_ERROR)
4951 {
4952 error (NILF, _("$(libpath): failed to query `%s', rc=%d"), argv[0], rc);
4953 return variable_buffer_output (o, "", 0);
4954 }
4955 o = variable_buffer_output (o, buf, strlen (buf));
4956 }
4957 else
4958 {
4959 /* set the variable value. */
4960 size_t len;
4961 size_t len_max = sizeof (buf) < 2048 ? sizeof (buf) : 2048;
4962 const char *val;
4963 const char *end;
4964
4965 if (fVar == 0)
4966 {
4967 error (NILF, _("$(libpath): LIBPATH is read-only"));
4968 return variable_buffer_output (o, "", 0);
4969 }
4970
4971 /* strip leading and trailing spaces and check for max length. */
4972 val = argv[1];
4973 while (isspace (*val))
4974 val++;
4975 end = strchr (val, '\0');
4976 while (end > val && isspace (end[-1]))
4977 end--;
4978
4979 len = end - val;
4980 if (len >= len_max)
4981 {
4982 error (NILF, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
4983 argv[0], len, len_max);
4984 return variable_buffer_output (o, "", 0);
4985 }
4986
4987 /* make a stripped copy in low memory and try set it. */
4988 memcpy (buf, val, len);
4989 buf[len] = '\0';
4990 rc = DosSetExtLIBPATH (buf, fVar);
4991 if (rc != NO_ERROR)
4992 {
4993 error (NILF, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv[0], buf, rc);
4994 return variable_buffer_output (o, "", 0);
4995 }
4996
4997 o = variable_buffer_output (o, "", 0);
4998 }
4999 return o;
5000}
5001#endif /* CONFIG_WITH_OS2_LIBPATH */
5002
5003#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5004/* Retrieve make statistics. */
5005static char *
5006func_make_stats (char *o, char **argv, const char *funcname UNUSED)
5007{
5008 char buf[512];
5009 int len;
5010
5011 if (!argv[0] || (!argv[0][0] && !argv[1]))
5012 {
5013# ifdef CONFIG_WITH_MAKE_STATS
5014 len = sprintf (buf, "alloc-cur: %5ld/%3ld %3luMB hash: %5lu %2lu%%",
5015 make_stats_allocations,
5016 make_stats_reallocations,
5017 make_stats_allocated / (1024*1024),
5018 make_stats_ht_lookups,
5019 (make_stats_ht_collisions * 100) / make_stats_ht_lookups);
5020 o = variable_buffer_output (o, buf, len);
5021#endif
5022 }
5023 else
5024 {
5025 /* selective */
5026 int i;
5027 for (i = 0; argv[i]; i++)
5028 {
5029 unsigned long val;
5030 if (i != 0)
5031 o = variable_buffer_output (o, " ", 1);
5032 if (0)
5033 continue;
5034# ifdef CONFIG_WITH_MAKE_STATS
5035 else if (!strcmp(argv[i], "allocations"))
5036 val = make_stats_allocations;
5037 else if (!strcmp(argv[i], "reallocations"))
5038 val = make_stats_reallocations;
5039 else if (!strcmp(argv[i], "allocated"))
5040 val = make_stats_allocated;
5041 else if (!strcmp(argv[i], "ht_lookups"))
5042 val = make_stats_ht_lookups;
5043 else if (!strcmp(argv[i], "ht_collisions"))
5044 val = make_stats_ht_collisions;
5045 else if (!strcmp(argv[i], "ht_collisions_pct"))
5046 val = (make_stats_ht_collisions * 100) / make_stats_ht_lookups;
5047#endif
5048 else
5049 {
5050 o = variable_buffer_output (o, argv[i], strlen (argv[i]));
5051 continue;
5052 }
5053
5054 len = sprintf (buf, "%ld", val);
5055 o = variable_buffer_output (o, buf, len);
5056 }
5057 }
5058
5059 return o;
5060}
5061#endif /* CONFIG_WITH_MAKE_STATS */
5062
5063#ifdef CONFIG_WITH_COMMANDS_FUNC
5064/* Gets all the commands for a target, separated by newlines.
5065
5066 This is useful when creating and checking target dependencies since
5067 it reduces the amount of work and the memory consuption. A new prefix
5068 character '%' has been introduced for skipping certain lines, like
5069 for instance the one calling this function and pushing to a dep file.
5070 Blank lines are also skipped.
5071
5072 The commands function takes exactly one argument, which is the name of
5073 the target which commands should be returned.
5074
5075 The commands-sc is identical to commands except that it uses a ';' to
5076 separate the commands.
5077
5078 The commands-usr is similar to commands except that it takes a 2nd
5079 argument that is used to separate the commands. */
5080char *
5081func_commands (char *o, char **argv, const char *funcname)
5082{
5083 struct file *file;
5084 static int recursive = 0;
5085
5086 if (recursive)
5087 {
5088 error (reading_file, _("$(%s ) was invoked recursivly"), funcname);
5089 return variable_buffer_output (o, "recursive", sizeof ("recursive") - 1);
5090 }
5091 if (*argv[0] == '\0')
5092 {
5093 error (reading_file, _("$(%s ) was invoked with an empty target name"), funcname);
5094 return o;
5095 }
5096 recursive = 1;
5097
5098 file = lookup_file (argv[0]);
5099 if (file && file->cmds)
5100 {
5101 unsigned int i;
5102 int cmd_sep_len;
5103 struct commands *cmds = file->cmds;
5104 const char *cmd_sep;
5105
5106 if (!strcmp (funcname, "commands"))
5107 {
5108 cmd_sep = "\n";
5109 cmd_sep_len = 1;
5110 }
5111 else if (!strcmp (funcname, "commands-sc"))
5112 {
5113 cmd_sep = ";";
5114 cmd_sep_len = 1;
5115 }
5116 else /*if (!strcmp (funcname, "commands-usr"))*/
5117 {
5118 cmd_sep = argv[1];
5119 cmd_sep_len = strlen (cmd_sep);
5120 }
5121
5122 initialize_file_variables (file, 1 /* don't search for pattern vars */);
5123 set_file_variables (file, 1 /* early call */);
5124 chop_commands (cmds);
5125
5126 for (i = 0; i < cmds->ncommand_lines; i++)
5127 {
5128 char *p;
5129 char *in, *out, *ref;
5130
5131 /* Skip it if it has a '%' prefix or is blank. */
5132 if (cmds->lines_flags[i] & COMMAND_GETTER_SKIP_IT)
5133 continue;
5134 p = cmds->command_lines[i];
5135 while (isblank ((unsigned char)*p))
5136 p++;
5137 if (*p == '\0')
5138 continue;
5139
5140 /* --- copied from new_job() in job.c --- */
5141
5142 /* Collapse backslash-newline combinations that are inside variable
5143 or function references. These are left alone by the parser so
5144 that they will appear in the echoing of commands (where they look
5145 nice); and collapsed by construct_command_argv when it tokenizes.
5146 But letting them survive inside function invocations loses because
5147 we don't want the functions to see them as part of the text. */
5148
5149 /* IN points to where in the line we are scanning.
5150 OUT points to where in the line we are writing.
5151 When we collapse a backslash-newline combination,
5152 IN gets ahead of OUT. */
5153
5154 in = out = p;
5155 while ((ref = strchr (in, '$')) != 0)
5156 {
5157 ++ref; /* Move past the $. */
5158
5159 if (out != in)
5160 /* Copy the text between the end of the last chunk
5161 we processed (where IN points) and the new chunk
5162 we are about to process (where REF points). */
5163 memmove (out, in, ref - in);
5164
5165 /* Move both pointers past the boring stuff. */
5166 out += ref - in;
5167 in = ref;
5168
5169 if (*ref == '(' || *ref == '{')
5170 {
5171 char openparen = *ref;
5172 char closeparen = openparen == '(' ? ')' : '}';
5173 int count;
5174 char *p2;
5175
5176 *out++ = *in++; /* Copy OPENPAREN. */
5177 /* IN now points past the opening paren or brace.
5178 Count parens or braces until it is matched. */
5179 count = 0;
5180 while (*in != '\0')
5181 {
5182 if (*in == closeparen && --count < 0)
5183 break;
5184 else if (*in == '\\' && in[1] == '\n')
5185 {
5186 /* We have found a backslash-newline inside a
5187 variable or function reference. Eat it and
5188 any following whitespace. */
5189
5190 int quoted = 0;
5191 for (p2 = in - 1; p2 > ref && *p2 == '\\'; --p2)
5192 quoted = !quoted;
5193
5194 if (quoted)
5195 /* There were two or more backslashes, so this is
5196 not really a continuation line. We don't collapse
5197 the quoting backslashes here as is done in
5198 collapse_continuations, because the line will
5199 be collapsed again after expansion. */
5200 *out++ = *in++;
5201 else
5202 {
5203 /* Skip the backslash, newline and
5204 any following whitespace. */
5205 in = next_token (in + 2);
5206
5207 /* Discard any preceding whitespace that has
5208 already been written to the output. */
5209 while (out > ref
5210 && isblank ((unsigned char)out[-1]))
5211 --out;
5212
5213 /* Replace it all with a single space. */
5214 *out++ = ' ';
5215 }
5216 }
5217 else
5218 {
5219 if (*in == openparen)
5220 ++count;
5221
5222 *out++ = *in++;
5223 }
5224 }
5225 }
5226 /* Some of these can be amended ($< perhaps), but we're likely to be called while the
5227 dep expansion happens, so it would have to be on a hackish basis. sad... */
5228 else if (*ref == '<' || *ref == '*' || *ref == '%' || *ref == '^' || *ref == '+')
5229 error (reading_file, _("$(%s ) does not work reliably with $%c in all cases"), funcname, *ref);
5230 }
5231
5232 /* There are no more references in this line to worry about.
5233 Copy the remaining uninteresting text to the output. */
5234 if (out != in)
5235 strcpy (out, in);
5236
5237 /* --- copied from new_job() in job.c --- */
5238
5239 /* Finally, expand the line. */
5240 if (i)
5241 o = variable_buffer_output (o, cmd_sep, cmd_sep_len);
5242 o = variable_expand_for_file_2 (o, cmds->command_lines[i], ~0U, file, NULL);
5243
5244 /* Skip it if it has a '%' prefix or is blank. */
5245 p = o;
5246 while (isblank ((unsigned char)*o)
5247 || *o == '@'
5248 || *o == '-'
5249 || *o == '+')
5250 o++;
5251 if (*o != '\0' && *o != '%')
5252 o = strchr (o, '\0');
5253 else if (i)
5254 o = p - cmd_sep_len;
5255 else
5256 o = p;
5257 } /* for each command line */
5258 }
5259 /* else FIXME: bitch about it? */
5260
5261 recursive = 0;
5262 return o;
5263}
5264#endif /* CONFIG_WITH_COMMANDS_FUNC */
5265#ifdef KMK
5266
5267/* Useful when debugging kmk and/or makefiles. */
5268char *
5269func_breakpoint (char *o, char **argv UNUSED, const char *funcname UNUSED)
5270{
5271#ifdef _MSC_VER
5272 __debugbreak();
5273#elif defined(__i386__) || defined(__x86__) || defined(__X86__) || defined(_M_IX86) || defined(__i386) \
5274 || defined(__amd64__) || defined(__x86_64__) || defined(__AMD64__) || defined(_M_X64) || defined(__amd64)
5275# ifdef __sun__
5276 __asm__ __volatile__ ("int $3\n\t");
5277# else
5278 __asm__ __volatile__ ("int3\n\t");
5279# endif
5280#else
5281 char *p = (char *)0;
5282 *p = '\0';
5283#endif
5284 return o;
5285}
5286
5287/* umask | umask -S. */
5288char *
5289func_get_umask (char *o, char **argv UNUSED, const char *funcname UNUSED)
5290{
5291 char sz[80];
5292 int off;
5293 mode_t u;
5294 int symbolic = 0;
5295 const char *psz = argv[0];
5296
5297 if (psz)
5298 {
5299 const char *pszEnd = strchr (psz, '\0');
5300 strip_whitespace (&psz, &pszEnd);
5301
5302 if (pszEnd != psz)
5303 {
5304 if ( STR_N_EQUALS (psz, pszEnd - pszEnd, "S")
5305 || STR_N_EQUALS (psz, pszEnd - pszEnd, "-S")
5306 || STR_N_EQUALS (psz, pszEnd - pszEnd, "symbolic") )
5307 symbolic = 1;
5308 else
5309 error (reading_file, _("$(%s ) invalid argument `%s'"),
5310 funcname, argv[0]);
5311 }
5312 }
5313
5314 u = umask (002);
5315 umask (u);
5316
5317 if (symbolic)
5318 {
5319 off = 0;
5320 sz[off++] = 'u';
5321 sz[off++] = '=';
5322 if ((u & S_IRUSR) == 0)
5323 sz[off++] = 'r';
5324 if ((u & S_IWUSR) == 0)
5325 sz[off++] = 'w';
5326 if ((u & S_IXUSR) == 0)
5327 sz[off++] = 'x';
5328 sz[off++] = ',';
5329 sz[off++] = 'g';
5330 sz[off++] = '=';
5331 if ((u & S_IRGRP) == 0)
5332 sz[off++] = 'r';
5333 if ((u & S_IWGRP) == 0)
5334 sz[off++] = 'w';
5335 if ((u & S_IXGRP) == 0)
5336 sz[off++] = 'x';
5337 sz[off++] = ',';
5338 sz[off++] = 'o';
5339 sz[off++] = '=';
5340 if ((u & S_IROTH) == 0)
5341 sz[off++] = 'r';
5342 if ((u & S_IWOTH) == 0)
5343 sz[off++] = 'w';
5344 if ((u & S_IXOTH) == 0)
5345 sz[off++] = 'x';
5346 }
5347 else
5348 off = sprintf (sz, "%.4o", u);
5349
5350 return variable_buffer_output (o, sz, off);
5351}
5352
5353
5354/* umask 0002 | umask u=rwx,g=rwx,o=rx. */
5355char *
5356func_set_umask (char *o, char **argv UNUSED, const char *funcname UNUSED)
5357{
5358 mode_t u;
5359 const char *psz;
5360
5361 /* Figure what kind of input this is. */
5362 psz = argv[0];
5363 while (isblank ((unsigned char)*psz))
5364 psz++;
5365
5366 if (isdigit ((unsigned char)*psz))
5367 {
5368 u = 0;
5369 while (*psz)
5370 {
5371 u <<= 3;
5372 if (*psz < '0' || *psz >= '8')
5373 {
5374 error (reading_file, _("$(%s ) illegal number `%s'"), funcname, argv[0]);
5375 break;
5376 }
5377 u += *psz - '0';
5378 psz++;
5379 }
5380
5381 if (argv[1] != NULL)
5382 error (reading_file, _("$(%s ) too many arguments for octal mode"), funcname);
5383 }
5384 else
5385 {
5386 u = umask(0);
5387 umask(u);
5388 error (reading_file, _("$(%s ) symbol mode is not implemented"), funcname);
5389 }
5390
5391 umask(u);
5392
5393 return o;
5394}
5395
5396#endif /* KMK */
5397
5398
5399/* Lookup table for builtin functions.
5400
5401 This doesn't have to be sorted; we use a straight lookup. We might gain
5402 some efficiency by moving most often used functions to the start of the
5403 table.
5404
5405 If MAXIMUM_ARGS is 0, that means there is no maximum and all
5406 comma-separated values are treated as arguments.
5407
5408 EXPAND_ARGS means that all arguments should be expanded before invocation.
5409 Functions that do namespace tricks (foreach) don't automatically expand. */
5410
5411static char *func_call (char *o, char **argv, const char *funcname);
5412
5413
5414static struct function_table_entry function_table_init[] =
5415{
5416 /* Name/size */ /* MIN MAX EXP? Function */
5417 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
5418 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
5419 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
5420 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
5421 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
5422 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
5423#ifdef CONFIG_WITH_ROOT_FUNC
5424 { STRING_SIZE_TUPLE("root"), 0, 1, 1, func_root},
5425 { STRING_SIZE_TUPLE("notroot"), 0, 1, 1, func_notroot},
5426#endif
5427 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
5428 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
5429 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
5430 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
5431 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
5432#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
5433 { STRING_SIZE_TUPLE("firstdefined"), 0, 2, 1, func_firstdefined},
5434#endif
5435 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
5436 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
5437 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
5438#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
5439 { STRING_SIZE_TUPLE("lastdefined"), 0, 2, 1, func_lastdefined},
5440#endif
5441 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
5442 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
5443 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
5444#ifdef CONFIG_WITH_RSORT
5445 { STRING_SIZE_TUPLE("rsort"), 0, 1, 1, func_sort},
5446#endif
5447 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
5448 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
5449 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
5450#ifdef CONFIG_WITH_WHERE_FUNCTION
5451 { STRING_SIZE_TUPLE("where"), 0, 1, 1, func_where},
5452#endif
5453 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
5454 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
5455 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
5456 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
5457 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
5458 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
5459#ifdef CONFIG_WITH_LOOP_FUNCTIONS
5460 { STRING_SIZE_TUPLE("for"), 4, 4, 0, func_for},
5461 { STRING_SIZE_TUPLE("while"), 2, 2, 0, func_while},
5462#endif
5463 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
5464 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
5465 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
5466 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
5467 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
5468 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
5469 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
5470 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
5471 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
5472#ifdef CONFIG_WITH_EVALPLUS
5473 { STRING_SIZE_TUPLE("evalctx"), 0, 1, 1, func_evalctx},
5474 { STRING_SIZE_TUPLE("evalval"), 1, 1, 1, func_evalval},
5475 { STRING_SIZE_TUPLE("evalvalctx"), 1, 1, 1, func_evalval},
5476 { STRING_SIZE_TUPLE("evalcall"), 1, 0, 1, func_call},
5477 { STRING_SIZE_TUPLE("evalcall2"), 1, 0, 1, func_call},
5478 { STRING_SIZE_TUPLE("eval-opt-var"), 1, 0, 1, func_eval_optimize_variable},
5479#endif
5480#ifdef EXPERIMENTAL
5481 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
5482 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
5483#endif
5484#ifdef CONFIG_WITH_STRING_FUNCTIONS
5485 { STRING_SIZE_TUPLE("length"), 1, 1, 1, func_length},
5486 { STRING_SIZE_TUPLE("length-var"), 1, 1, 1, func_length_var},
5487 { STRING_SIZE_TUPLE("insert"), 2, 5, 1, func_insert},
5488 { STRING_SIZE_TUPLE("pos"), 2, 3, 1, func_pos},
5489 { STRING_SIZE_TUPLE("lastpos"), 2, 3, 1, func_pos},
5490 { STRING_SIZE_TUPLE("substr"), 2, 4, 1, func_substr},
5491 { STRING_SIZE_TUPLE("translate"), 2, 4, 1, func_translate},
5492#endif
5493#ifdef CONFIG_WITH_PRINTF
5494 { STRING_SIZE_TUPLE("printf"), 1, 0, 1, kmk_builtin_func_printf},
5495#endif
5496#ifdef CONFIG_WITH_LAZY_DEPS_VARS
5497 { STRING_SIZE_TUPLE("deps"), 1, 2, 1, func_deps},
5498 { STRING_SIZE_TUPLE("deps-all"), 1, 2, 1, func_deps},
5499 { STRING_SIZE_TUPLE("deps-newer"), 1, 2, 1, func_deps_newer},
5500 { STRING_SIZE_TUPLE("deps-oo"), 1, 2, 1, func_deps_order_only},
5501#endif
5502#ifdef CONFIG_WITH_DEFINED
5503 { STRING_SIZE_TUPLE("defined"), 1, 1, 1, func_defined},
5504#endif
5505#ifdef CONFIG_WITH_TOUPPER_TOLOWER
5506 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower},
5507 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower},
5508#endif
5509#ifdef CONFIG_WITH_ABSPATHEX
5510 { STRING_SIZE_TUPLE("abspathex"), 0, 2, 1, func_abspathex},
5511#endif
5512#ifdef CONFIG_WITH_XARGS
5513 { STRING_SIZE_TUPLE("xargs"), 2, 0, 1, func_xargs},
5514#endif
5515#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
5516 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars},
5517 { STRING_SIZE_TUPLE("comp-cmds"), 3, 3, 1, func_comp_vars},
5518 { STRING_SIZE_TUPLE("comp-cmds-ex"), 3, 3, 1, func_comp_cmds_ex},
5519#endif
5520#ifdef CONFIG_WITH_DATE
5521 { STRING_SIZE_TUPLE("date"), 0, 1, 1, func_date},
5522 { STRING_SIZE_TUPLE("date-utc"), 0, 3, 1, func_date},
5523#endif
5524#ifdef CONFIG_WITH_FILE_SIZE
5525 { STRING_SIZE_TUPLE("file-size"), 1, 1, 1, func_file_size},
5526#endif
5527#ifdef CONFIG_WITH_WHICH
5528 { STRING_SIZE_TUPLE("which"), 0, 0, 1, func_which},
5529#endif
5530#ifdef CONFIG_WITH_IF_CONDITIONALS
5531 { STRING_SIZE_TUPLE("expr"), 1, 1, 0, func_expr},
5532 { STRING_SIZE_TUPLE("if-expr"), 2, 3, 0, func_if_expr},
5533 { STRING_SIZE_TUPLE("select"), 2, 0, 0, func_select},
5534#endif
5535#ifdef CONFIG_WITH_SET_CONDITIONALS
5536 { STRING_SIZE_TUPLE("intersects"), 2, 2, 1, func_set_intersects},
5537#endif
5538#ifdef CONFIG_WITH_STACK
5539 { STRING_SIZE_TUPLE("stack-push"), 2, 2, 1, func_stack_push},
5540 { STRING_SIZE_TUPLE("stack-pop"), 1, 1, 1, func_stack_pop_top},
5541 { STRING_SIZE_TUPLE("stack-popv"), 1, 1, 1, func_stack_pop_top},
5542 { STRING_SIZE_TUPLE("stack-top"), 1, 1, 1, func_stack_pop_top},
5543#endif
5544#ifdef CONFIG_WITH_MATH
5545 { STRING_SIZE_TUPLE("int-add"), 2, 0, 1, func_int_add},
5546 { STRING_SIZE_TUPLE("int-sub"), 2, 0, 1, func_int_sub},
5547 { STRING_SIZE_TUPLE("int-mul"), 2, 0, 1, func_int_mul},
5548 { STRING_SIZE_TUPLE("int-div"), 2, 0, 1, func_int_div},
5549 { STRING_SIZE_TUPLE("int-mod"), 2, 2, 1, func_int_mod},
5550 { STRING_SIZE_TUPLE("int-not"), 1, 1, 1, func_int_not},
5551 { STRING_SIZE_TUPLE("int-and"), 2, 0, 1, func_int_and},
5552 { STRING_SIZE_TUPLE("int-or"), 2, 0, 1, func_int_or},
5553 { STRING_SIZE_TUPLE("int-xor"), 2, 0, 1, func_int_xor},
5554 { STRING_SIZE_TUPLE("int-eq"), 2, 2, 1, func_int_cmp},
5555 { STRING_SIZE_TUPLE("int-ne"), 2, 2, 1, func_int_cmp},
5556 { STRING_SIZE_TUPLE("int-gt"), 2, 2, 1, func_int_cmp},
5557 { STRING_SIZE_TUPLE("int-ge"), 2, 2, 1, func_int_cmp},
5558 { STRING_SIZE_TUPLE("int-lt"), 2, 2, 1, func_int_cmp},
5559 { STRING_SIZE_TUPLE("int-le"), 2, 2, 1, func_int_cmp},
5560#endif
5561#ifdef CONFIG_WITH_NANOTS
5562 { STRING_SIZE_TUPLE("nanots"), 0, 0, 0, func_nanots},
5563#endif
5564#ifdef CONFIG_WITH_OS2_LIBPATH
5565 { STRING_SIZE_TUPLE("libpath"), 1, 2, 1, func_os2_libpath},
5566#endif
5567#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5568 { STRING_SIZE_TUPLE("make-stats"), 0, 0, 0, func_make_stats},
5569#endif
5570#ifdef CONFIG_WITH_COMMANDS_FUNC
5571 { STRING_SIZE_TUPLE("commands"), 1, 1, 1, func_commands},
5572 { STRING_SIZE_TUPLE("commands-sc"), 1, 1, 1, func_commands},
5573 { STRING_SIZE_TUPLE("commands-usr"), 2, 2, 1, func_commands},
5574#endif
5575#ifdef KMK_HELPERS
5576 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool},
5577 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base},
5578 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix},
5579 { STRING_SIZE_TUPLE("kb-src-prop"), 3, 4, 0, func_kbuild_source_prop},
5580 { STRING_SIZE_TUPLE("kb-src-one"), 0, 1, 0, func_kbuild_source_one},
5581 { STRING_SIZE_TUPLE("kb-exp-tmpl"), 6, 6, 1, func_kbuild_expand_template},
5582#endif
5583#ifdef KMK
5584 { STRING_SIZE_TUPLE("breakpoint"), 0, 0, 0, func_breakpoint},
5585 { STRING_SIZE_TUPLE("set-umask"), 1, 3, 1, func_set_umask},
5586 { STRING_SIZE_TUPLE("get-umask"), 0, 0, 0, func_get_umask},
5587#endif
5588};
5589
5590#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
5591
5592
5593
5594/* These must come after the definition of function_table. */
5595
5596static char *
5597expand_builtin_function (char *o, int argc, char **argv,
5598 const struct function_table_entry *entry_p)
5599{
5600 if (argc < (int)entry_p->minimum_args)
5601 fatal (*expanding_var,
5602 _("insufficient number of arguments (%d) to function `%s'"),
5603 argc, entry_p->name);
5604
5605 /* I suppose technically some function could do something with no
5606 arguments, but so far none do, so just test it for all functions here
5607 rather than in each one. We can change it later if necessary. */
5608
5609 if (!argc)
5610 return o;
5611
5612 if (!entry_p->func_ptr)
5613 fatal (*expanding_var,
5614 _("unimplemented on this platform: function `%s'"), entry_p->name);
5615
5616 return entry_p->func_ptr (o, argv, entry_p->name);
5617}
5618
5619/* Check for a function invocation in *STRINGP. *STRINGP points at the
5620 opening ( or { and is not null-terminated. If a function invocation
5621 is found, expand it into the buffer at *OP, updating *OP, incrementing
5622 *STRINGP past the reference and returning nonzero. If not, return zero. */
5623
5624static int
5625handle_function2 (const struct function_table_entry *entry_p, char **op, const char **stringp) /* bird split it up. */
5626{
5627 char openparen = (*stringp)[0];
5628 char closeparen = openparen == '(' ? ')' : '}';
5629 const char *beg;
5630 const char *end;
5631 int count = 0;
5632 char *abeg = NULL;
5633 char **argv, **argvp;
5634 int nargs;
5635
5636 beg = *stringp + 1;
5637
5638 /* We found a builtin function. Find the beginning of its arguments (skip
5639 whitespace after the name). */
5640
5641 beg = next_token (beg + entry_p->len);
5642
5643 /* Find the end of the function invocation, counting nested use of
5644 whichever kind of parens we use. Since we're looking, count commas
5645 to get a rough estimate of how many arguments we might have. The
5646 count might be high, but it'll never be low. */
5647
5648 for (nargs=1, end=beg; *end != '\0'; ++end)
5649 if (*end == ',')
5650 ++nargs;
5651 else if (*end == openparen)
5652 ++count;
5653 else if (*end == closeparen && --count < 0)
5654 break;
5655
5656 if (count >= 0)
5657 fatal (*expanding_var,
5658 _("unterminated call to function `%s': missing `%c'"),
5659 entry_p->name, closeparen);
5660
5661 *stringp = end;
5662
5663 /* Get some memory to store the arg pointers. */
5664 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
5665
5666 /* Chop the string into arguments, then a nul. As soon as we hit
5667 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
5668 last argument.
5669
5670 If we're expanding, store pointers to the expansion of each one. If
5671 not, make a duplicate of the string and point into that, nul-terminating
5672 each argument. */
5673
5674 if (entry_p->expand_args)
5675 {
5676 const char *p;
5677 for (p=beg, nargs=0; p <= end; ++argvp)
5678 {
5679 const char *next;
5680
5681 ++nargs;
5682
5683 if (nargs == entry_p->maximum_args
5684 || (! (next = find_next_argument (openparen, closeparen, p, end))))
5685 next = end;
5686
5687 *argvp = expand_argument (p, next);
5688 p = next + 1;
5689 }
5690 }
5691 else
5692 {
5693 int len = end - beg;
5694 char *p, *aend;
5695
5696 abeg = xmalloc (len+1);
5697 memcpy (abeg, beg, len);
5698 abeg[len] = '\0';
5699 aend = abeg + len;
5700
5701 for (p=abeg, nargs=0; p <= aend; ++argvp)
5702 {
5703 char *next;
5704
5705 ++nargs;
5706
5707 if (nargs == entry_p->maximum_args
5708 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
5709 next = aend;
5710
5711 *argvp = p;
5712 *next = '\0';
5713 p = next + 1;
5714 }
5715 }
5716 *argvp = NULL;
5717
5718 /* Finally! Run the function... */
5719 *op = expand_builtin_function (*op, nargs, argv, entry_p);
5720
5721 /* Free memory. */
5722 if (entry_p->expand_args)
5723 for (argvp=argv; *argvp != 0; ++argvp)
5724 free (*argvp);
5725 if (abeg)
5726 free (abeg);
5727
5728 return 1;
5729}
5730
5731
5732int /* bird split it up and hacked it. */
5733#ifndef CONFIG_WITH_VALUE_LENGTH
5734handle_function (char **op, const char **stringp)
5735{
5736 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
5737 if (!entry_p)
5738 return 0;
5739 return handle_function2 (entry_p, op, stringp);
5740}
5741#else /* CONFIG_WITH_VALUE_LENGTH */
5742handle_function (char **op, const char **stringp, const char *nameend, const char *eol UNUSED)
5743{
5744 const char *fname = *stringp + 1;
5745 const struct function_table_entry *entry_p =
5746 lookup_function_in_hash_tab (fname, nameend - fname);
5747 if (!entry_p)
5748 return 0;
5749 return handle_function2 (entry_p, op, stringp);
5750}
5751#endif /* CONFIG_WITH_VALUE_LENGTH */
5752
5753
5754
5755/* User-defined functions. Expand the first argument as either a builtin
5756 function or a make variable, in the context of the rest of the arguments
5757 assigned to $1, $2, ... $N. $0 is the name of the function. */
5758
5759static char *
5760func_call (char *o, char **argv, const char *funcname UNUSED)
5761{
5762 static int max_args = 0;
5763 char *fname;
5764 char *cp;
5765 char *body;
5766 int flen;
5767 int i;
5768 int saved_args;
5769 const struct function_table_entry *entry_p;
5770 struct variable *v;
5771#ifdef CONFIG_WITH_EVALPLUS
5772 char *buf;
5773 unsigned int len;
5774#endif
5775#if defined (CONFIG_WITH_EVALPLUS) || defined (CONFIG_WITH_VALUE_LENGTH)
5776 char num[11];
5777#endif
5778
5779 /* There is no way to define a variable with a space in the name, so strip
5780 leading and trailing whitespace as a favor to the user. */
5781 fname = argv[0];
5782 while (*fname != '\0' && isspace ((unsigned char)*fname))
5783 ++fname;
5784
5785 cp = fname + strlen (fname) - 1;
5786 while (cp > fname && isspace ((unsigned char)*cp))
5787 --cp;
5788 cp[1] = '\0';
5789
5790 /* Calling nothing is a no-op */
5791 if (*fname == '\0')
5792 return o;
5793
5794 /* Are we invoking a builtin function? */
5795
5796#ifndef CONFIG_WITH_VALUE_LENGTH
5797 entry_p = lookup_function (fname);
5798#else
5799 entry_p = lookup_function (fname, cp - fname + 1);
5800#endif
5801 if (entry_p)
5802 {
5803 /* How many arguments do we have? */
5804 for (i=0; argv[i+1]; ++i)
5805 ;
5806 return expand_builtin_function (o, i, argv+1, entry_p);
5807 }
5808
5809 /* Not a builtin, so the first argument is the name of a variable to be
5810 expanded and interpreted as a function. Find it. */
5811 flen = strlen (fname);
5812
5813 v = lookup_variable (fname, flen);
5814
5815 if (v == 0)
5816 warn_undefined (fname, flen);
5817
5818 if (v == 0 || *v->value == '\0')
5819 return o;
5820
5821 body = alloca (flen + 4);
5822 body[0] = '$';
5823 body[1] = '(';
5824 memcpy (body + 2, fname, flen);
5825 body[flen+2] = ')';
5826 body[flen+3] = '\0';
5827
5828 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
5829
5830 push_new_variable_scope ();
5831
5832 for (i=0; *argv; ++i, ++argv)
5833#ifdef CONFIG_WITH_VALUE_LENGTH
5834 define_variable (num, sprintf (num, "%d", i), *argv, o_automatic, 0);
5835#else
5836 {
5837 char num[11];
5838
5839 sprintf (num, "%d", i);
5840 define_variable (num, strlen (num), *argv, o_automatic, 0);
5841 }
5842#endif
5843
5844#ifdef CONFIG_WITH_EVALPLUS
5845 /* $(.ARGC) is the argument count. */
5846
5847 len = sprintf (num, "%d", i - 1);
5848 define_variable_vl (".ARGC", sizeof (".ARGC") - 1, num, len,
5849 1 /* dup val */, o_automatic, 0);
5850#endif
5851
5852 /* If the number of arguments we have is < max_args, it means we're inside
5853 a recursive invocation of $(call ...). Fill in the remaining arguments
5854 in the new scope with the empty value, to hide them from this
5855 invocation. */
5856
5857 for (; i < max_args; ++i)
5858#ifdef CONFIG_WITH_VALUE_LENGTH
5859 define_variable (num, sprintf (num, "%d", i), "", o_automatic, 0);
5860#else
5861 {
5862 char num[11];
5863
5864 sprintf (num, "%d", i);
5865 define_variable (num, strlen (num), "", o_automatic, 0);
5866 }
5867#endif
5868
5869 saved_args = max_args;
5870 max_args = i;
5871
5872#ifdef CONFIG_WITH_EVALPLUS
5873 if (!strcmp (funcname, "call"))
5874 {
5875#endif
5876 /* Expand the body in the context of the arguments, adding the result to
5877 the variable buffer. */
5878
5879 v->exp_count = EXP_COUNT_MAX;
5880#ifndef CONFIG_WITH_VALUE_LENGTH
5881 o = variable_expand_string (o, body, flen+3);
5882 v->exp_count = 0;
5883
5884 o += strlen (o);
5885#else /* CONFIG_WITH_VALUE_LENGTH */
5886 variable_expand_string_2 (o, body, flen+3, &o);
5887 v->exp_count = 0;
5888#endif /* CONFIG_WITH_VALUE_LENGTH */
5889#ifdef CONFIG_WITH_EVALPLUS
5890 }
5891 else
5892 {
5893 const struct floc *reading_file_saved = reading_file;
5894 char *eos;
5895
5896 if (!strcmp (funcname, "evalcall"))
5897 {
5898 /* Evaluate the variable value without expanding it. We
5899 need a copy since eval_buffer is destructive. */
5900
5901 size_t off = o - variable_buffer;
5902 eos = variable_buffer_output (o, v->value, v->value_length + 1) - 1;
5903 o = variable_buffer + off;
5904 if (v->fileinfo.filenm)
5905 reading_file = &v->fileinfo;
5906 }
5907 else
5908 {
5909 /* Expand the body first and then evaluate the output. */
5910
5911 v->exp_count = EXP_COUNT_MAX;
5912 o = variable_expand_string_2 (o, body, flen+3, &eos);
5913 v->exp_count = 0;
5914 }
5915
5916 install_variable_buffer (&buf, &len);
5917 eval_buffer (o, eos);
5918 restore_variable_buffer (buf, len);
5919 reading_file = reading_file_saved;
5920
5921 /* Deal with the .RETURN value if present. */
5922
5923 v = lookup_variable_in_set (".RETURN", sizeof (".RETURN") - 1,
5924 current_variable_set_list->set);
5925 if (v && v->value_length)
5926 {
5927 if (v->recursive)
5928 {
5929 v->exp_count = EXP_COUNT_MAX;
5930 variable_expand_string_2 (o, v->value, v->value_length, &o);
5931 v->exp_count = 0;
5932 }
5933 else
5934 o = variable_buffer_output (o, v->value, v->value_length);
5935 }
5936 }
5937#endif /* CONFIG_WITH_EVALPLUS */
5938
5939 max_args = saved_args;
5940
5941 pop_variable_scope ();
5942
5943 return o;
5944}
5945
5946void
5947hash_init_function_table (void)
5948{
5949 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
5950 function_table_entry_hash_1, function_table_entry_hash_2,
5951 function_table_entry_hash_cmp);
5952 hash_load (&function_table, function_table_init,
5953 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
5954#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
5955 {
5956 unsigned int i;
5957 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
5958 {
5959 const char *fn = function_table_init[i].name;
5960 while (*fn)
5961 {
5962 func_char_map[(int)*fn] = 1;
5963 fn++;
5964 }
5965 assert (function_table_init[i].len <= MAX_FUNCTION_LENGTH);
5966 assert (function_table_init[i].len >= MIN_FUNCTION_LENGTH);
5967 }
5968 }
5969#endif
5970}
Note: See TracBrowser for help on using the repository browser.