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

Last change on this file since 2150 was 2149, checked in by bird, 17 years ago

function.c: comment typo.

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