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

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

kmk: Implemented lazy resolving of $+, $, $? and $|. This saves > 30% memory and also a bit of time.

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