VirtualBox

source: kBuild/trunk/src/kmk/function.c@ 1922

Last change on this file since 1922 was 1915, checked in by bird, 16 years ago

kmk: CONFIG_WITH_MINIMAL_STATS vs. CONFIG_WITH_MAKE_STATS - require special builds for expensive statistics.

  • Property svn:eol-style set to native
File size: 119.0 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/* The maximum length of a function, once reached there is
337 it can't be function and we can skip the hash lookup drop out. */
338
339# define MAX_FUNCTION_LENGTH 12
340# define MIN_FUNCTION_LENGTH 2
341
342/* char map containing the valid function name characters. */
343static char func_char_map[256];
344
345/* Do the hash table lookup. */
346
347__inline static const struct function_table_entry *
348lookup_function_in_hash_tab (const char *s, unsigned char len)
349{
350 struct function_table_entry function_table_entry_key;
351 function_table_entry_key.name = s;
352 function_table_entry_key.len = len;
353
354 return hash_find_item (&function_table, &function_table_entry_key);
355}
356
357/* Look up a function by name. */
358
359__inline static const struct function_table_entry *
360lookup_function (const char *s, unsigned int len)
361{
362 unsigned char ch;
363# if 0 /* insane loop unroll */
364
365 if (len > MAX_FUNCTION_LENGTH)
366 len = MAX_FUNCTION_LENGTH + 1;
367
368# define X(idx) \
369 if (!func_char_map[ch = s[idx]]) \
370 { \
371 if (isblank (ch)) \
372 return lookup_function_in_hash_tab (s, idx); \
373 return 0; \
374 }
375# define Z(idx) \
376 return lookup_function_in_hash_tab (s, idx);
377
378 switch (len)
379 {
380 default:
381 assert (0);
382 case 0: return 0;
383 case 1: return 0;
384 case 2: X(0); X(1); Z(2);
385 case 3: X(0); X(1); X(2); Z(3);
386 case 4: X(0); X(1); X(2); X(3); Z(4);
387 case 5: X(0); X(1); X(2); X(3); X(4); Z(5);
388 case 6: X(0); X(1); X(2); X(3); X(4); X(5); Z(6);
389 case 7: X(0); X(1); X(2); X(3); X(4); X(5); X(6); Z(7);
390 case 8: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); Z(8);
391 case 9: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); Z(9);
392 case 10: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); Z(10);
393 case 11: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); Z(11);
394 case 12: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); Z(12);
395 case 13: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); X(12);
396 if ((ch = s[12]) == '\0' || isblank (ch))
397 return lookup_function_in_hash_tab (s, 12);
398 return 0;
399 }
400# undef Z
401# undef X
402
403# else /* normal loop */
404 const char *e = s;
405 if (len > MAX_FUNCTION_LENGTH)
406 len = MAX_FUNCTION_LENGTH;
407 while (func_char_map[ch = *e])
408 {
409 if (!len--)
410 return 0;
411 e++;
412 }
413 if (ch == '\0' || isblank ((unsigned char) ch))
414 return lookup_function_in_hash_tab (s, e - s);
415 return 0;
416# endif /* normal loop */
417}
418
419#else /* original code */
420/* Look up a function by name. */
421
422static const struct function_table_entry *
423lookup_function (const char *s)
424{
425 const char *e = s;
426 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
427 e++;
428 if (*e == '\0' || isblank ((unsigned char) *e))
429 {
430 struct function_table_entry function_table_entry_key;
431 function_table_entry_key.name = s;
432 function_table_entry_key.len = e - s;
433
434 return hash_find_item (&function_table, &function_table_entry_key);
435 }
436 return 0;
437}
438#endif /* original code */
439
440
441
442/* Return 1 if PATTERN matches STR, 0 if not. */
443
444int
445pattern_matches (const char *pattern, const char *percent, const char *str)
446{
447 unsigned int sfxlen, strlength;
448
449 if (percent == 0)
450 {
451 unsigned int len = strlen (pattern) + 1;
452 char *new_chars = alloca (len);
453 memcpy (new_chars, pattern, len);
454 percent = find_percent (new_chars);
455 if (percent == 0)
456 return streq (new_chars, str);
457 pattern = new_chars;
458 }
459
460 sfxlen = strlen (percent + 1);
461 strlength = strlen (str);
462
463 if (strlength < (percent - pattern) + sfxlen
464 || !strneq (pattern, str, percent - pattern))
465 return 0;
466
467 return !strcmp (percent + 1, str + (strlength - sfxlen));
468}
469
470
471
472/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
473 ENDPARENtheses), starting at PTR before END. Return a pointer to
474 next character.
475
476 If no next argument is found, return NULL.
477*/
478
479static char *
480find_next_argument (char startparen, char endparen,
481 const char *ptr, const char *end)
482{
483 int count = 0;
484
485 for (; ptr < end; ++ptr)
486 if (*ptr == startparen)
487 ++count;
488
489 else if (*ptr == endparen)
490 {
491 --count;
492 if (count < 0)
493 return NULL;
494 }
495
496 else if (*ptr == ',' && !count)
497 return (char *)ptr;
498
499 /* We didn't find anything. */
500 return NULL;
501}
502
503
504
505/* Glob-expand LINE. The returned pointer is
506 only good until the next call to string_glob. */
507
508static char *
509string_glob (char *line)
510{
511 static char *result = 0;
512 static unsigned int length;
513 struct nameseq *chain;
514 unsigned int idx;
515
516#ifndef CONFIG_WITH_ALLOC_CACHES
517 chain = multi_glob (parse_file_seq
518 (&line, '\0', sizeof (struct nameseq),
519 /* We do not want parse_file_seq to strip `./'s.
520 That would break examples like:
521 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
522 0),
523 sizeof (struct nameseq));
524#else
525 chain = multi_glob (parse_file_seq
526 (&line, '\0', &nameseq_cache,
527 /* We do not want parse_file_seq to strip `./'s.
528 That would break examples like:
529 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
530 0),
531 &nameseq_cache);
532#endif
533
534 if (result == 0)
535 {
536 length = 100;
537 result = xmalloc (100);
538 }
539
540 idx = 0;
541 while (chain != 0)
542 {
543 const char *name = chain->name;
544 unsigned int len = strlen (name);
545
546 struct nameseq *next = chain->next;
547#ifndef CONFIG_WITH_ALLOC_CACHES
548 free (chain);
549#else
550 alloccache_free (&nameseq_cache, chain);
551#endif
552 chain = next;
553
554 /* multi_glob will pass names without globbing metacharacters
555 through as is, but we want only files that actually exist. */
556 if (file_exists_p (name))
557 {
558 if (idx + len + 1 > length)
559 {
560 length += (len + 1) * 2;
561 result = xrealloc (result, length);
562 }
563 memcpy (&result[idx], name, len);
564 idx += len;
565 result[idx++] = ' ';
566 }
567 }
568
569 /* Kill the last space and terminate the string. */
570 if (idx == 0)
571 result[0] = '\0';
572 else
573 result[idx - 1] = '\0';
574
575 return result;
576}
577
578
579/*
580 Builtin functions
581 */
582
583static char *
584func_patsubst (char *o, char **argv, const char *funcname UNUSED)
585{
586 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
587 return o;
588}
589
590
591static char *
592func_join (char *o, char **argv, const char *funcname UNUSED)
593{
594 int doneany = 0;
595
596 /* Write each word of the first argument directly followed
597 by the corresponding word of the second argument.
598 If the two arguments have a different number of words,
599 the excess words are just output separated by blanks. */
600 const char *tp;
601 const char *pp;
602 const char *list1_iterator = argv[0];
603 const char *list2_iterator = argv[1];
604 do
605 {
606 unsigned int len1, len2;
607
608 tp = find_next_token (&list1_iterator, &len1);
609 if (tp != 0)
610 o = variable_buffer_output (o, tp, len1);
611
612 pp = find_next_token (&list2_iterator, &len2);
613 if (pp != 0)
614 o = variable_buffer_output (o, pp, len2);
615
616 if (tp != 0 || pp != 0)
617 {
618 o = variable_buffer_output (o, " ", 1);
619 doneany = 1;
620 }
621 }
622 while (tp != 0 || pp != 0);
623 if (doneany)
624 /* Kill the last blank. */
625 --o;
626
627 return o;
628}
629
630
631static char *
632func_origin (char *o, char **argv, const char *funcname UNUSED)
633{
634 /* Expand the argument. */
635 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
636 if (v == 0)
637 o = variable_buffer_output (o, "undefined", 9);
638 else
639 switch (v->origin)
640 {
641 default:
642 case o_invalid:
643 abort ();
644 break;
645 case o_default:
646 o = variable_buffer_output (o, "default", 7);
647 break;
648 case o_env:
649 o = variable_buffer_output (o, "environment", 11);
650 break;
651 case o_file:
652 o = variable_buffer_output (o, "file", 4);
653 break;
654 case o_env_override:
655 o = variable_buffer_output (o, "environment override", 20);
656 break;
657 case o_command:
658 o = variable_buffer_output (o, "command line", 12);
659 break;
660 case o_override:
661 o = variable_buffer_output (o, "override", 8);
662 break;
663 case o_automatic:
664 o = variable_buffer_output (o, "automatic", 9);
665 break;
666#ifdef CONFIG_WITH_LOCAL_VARIABLES
667 case o_local:
668 o = variable_buffer_output (o, "local", 5);
669 break;
670#endif
671 }
672
673 return o;
674}
675
676static char *
677func_flavor (char *o, char **argv, const char *funcname UNUSED)
678{
679 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
680
681 if (v == 0)
682 o = variable_buffer_output (o, "undefined", 9);
683 else
684 if (v->recursive)
685 o = variable_buffer_output (o, "recursive", 9);
686 else
687 o = variable_buffer_output (o, "simple", 6);
688
689 return o;
690}
691
692#ifdef VMS
693# define IS_PATHSEP(c) ((c) == ']')
694#else
695# ifdef HAVE_DOS_PATHS
696# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
697# else
698# define IS_PATHSEP(c) ((c) == '/')
699# endif
700#endif
701
702
703static char *
704func_notdir_suffix (char *o, char **argv, const char *funcname)
705{
706 /* Expand the argument. */
707 const char *list_iterator = argv[0];
708 const char *p2;
709 int doneany =0;
710 unsigned int len=0;
711
712 int is_suffix = streq (funcname, "suffix");
713 int is_notdir = !is_suffix;
714 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
715 {
716 const char *p = p2 + len;
717
718
719 while (p >= p2 && (!is_suffix || *p != '.'))
720 {
721 if (IS_PATHSEP (*p))
722 break;
723 --p;
724 }
725
726 if (p >= p2)
727 {
728 if (is_notdir)
729 ++p;
730 else if (*p != '.')
731 continue;
732 o = variable_buffer_output (o, p, len - (p - p2));
733 }
734#ifdef HAVE_DOS_PATHS
735 /* Handle the case of "d:foo/bar". */
736 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
737 {
738 p = p2 + 2;
739 o = variable_buffer_output (o, p, len - (p - p2));
740 }
741#endif
742 else if (is_notdir)
743 o = variable_buffer_output (o, p2, len);
744
745 if (is_notdir || p >= p2)
746 {
747 o = variable_buffer_output (o, " ", 1);
748 doneany = 1;
749 }
750 }
751
752 if (doneany)
753 /* Kill last space. */
754 --o;
755
756 return o;
757}
758
759
760static char *
761func_basename_dir (char *o, char **argv, const char *funcname)
762{
763 /* Expand the argument. */
764 const char *p3 = argv[0];
765 const char *p2;
766 int doneany=0;
767 unsigned int len=0;
768
769 int is_basename= streq (funcname, "basename");
770 int is_dir= !is_basename;
771
772 while ((p2 = find_next_token (&p3, &len)) != 0)
773 {
774 const char *p = p2 + len;
775 while (p >= p2 && (!is_basename || *p != '.'))
776 {
777 if (IS_PATHSEP (*p))
778 break;
779 --p;
780 }
781
782 if (p >= p2 && (is_dir))
783 o = variable_buffer_output (o, p2, ++p - p2);
784 else if (p >= p2 && (*p == '.'))
785 o = variable_buffer_output (o, p2, p - p2);
786#ifdef HAVE_DOS_PATHS
787 /* Handle the "d:foobar" case */
788 else if (p2[0] && p2[1] == ':' && is_dir)
789 o = variable_buffer_output (o, p2, 2);
790#endif
791 else if (is_dir)
792#ifdef VMS
793 o = variable_buffer_output (o, "[]", 2);
794#else
795#ifndef _AMIGA
796 o = variable_buffer_output (o, "./", 2);
797#else
798 ; /* Just a nop... */
799#endif /* AMIGA */
800#endif /* !VMS */
801 else
802 /* The entire name is the basename. */
803 o = variable_buffer_output (o, p2, len);
804
805 o = variable_buffer_output (o, " ", 1);
806 doneany = 1;
807 }
808
809 if (doneany)
810 /* Kill last space. */
811 --o;
812
813 return o;
814}
815
816static char *
817func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
818{
819 int fixlen = strlen (argv[0]);
820 const char *list_iterator = argv[1];
821 int is_addprefix = streq (funcname, "addprefix");
822 int is_addsuffix = !is_addprefix;
823
824 int doneany = 0;
825 const char *p;
826 unsigned int len;
827
828 while ((p = find_next_token (&list_iterator, &len)) != 0)
829 {
830 if (is_addprefix)
831 o = variable_buffer_output (o, argv[0], fixlen);
832 o = variable_buffer_output (o, p, len);
833 if (is_addsuffix)
834 o = variable_buffer_output (o, argv[0], fixlen);
835 o = variable_buffer_output (o, " ", 1);
836 doneany = 1;
837 }
838
839 if (doneany)
840 /* Kill last space. */
841 --o;
842
843 return o;
844}
845
846static char *
847func_subst (char *o, char **argv, const char *funcname UNUSED)
848{
849 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
850 strlen (argv[1]), 0);
851
852 return o;
853}
854
855
856static char *
857func_firstword (char *o, char **argv, const char *funcname UNUSED)
858{
859 unsigned int i;
860 const char *words = argv[0]; /* Use a temp variable for find_next_token */
861 const char *p = find_next_token (&words, &i);
862
863 if (p != 0)
864 o = variable_buffer_output (o, p, i);
865
866 return o;
867}
868
869static char *
870func_lastword (char *o, char **argv, const char *funcname UNUSED)
871{
872 unsigned int i;
873 const char *words = argv[0]; /* Use a temp variable for find_next_token */
874 const char *p = NULL;
875 const char *t;
876
877 while ((t = find_next_token (&words, &i)))
878 p = t;
879
880 if (p != 0)
881 o = variable_buffer_output (o, p, i);
882
883 return o;
884}
885
886static char *
887func_words (char *o, char **argv, const char *funcname UNUSED)
888{
889 int i = 0;
890 const char *word_iterator = argv[0];
891 char buf[20];
892
893 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
894 ++i;
895
896 sprintf (buf, "%d", i);
897 o = variable_buffer_output (o, buf, strlen (buf));
898
899 return o;
900}
901
902/* Set begpp to point to the first non-whitespace character of the string,
903 * and endpp to point to the last non-whitespace character of the string.
904 * If the string is empty or contains nothing but whitespace, endpp will be
905 * begpp-1.
906 */
907char *
908strip_whitespace (const char **begpp, const char **endpp)
909{
910 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
911 (*begpp) ++;
912 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
913 (*endpp) --;
914 return (char *)*begpp;
915}
916
917static void
918check_numeric (const char *s, const char *msg)
919{
920 const char *end = s + strlen (s) - 1;
921 const char *beg = s;
922 strip_whitespace (&s, &end);
923
924 for (; s <= end; ++s)
925 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
926 break;
927
928 if (s <= end || end - beg < 0)
929 fatal (*expanding_var, "%s: '%s'", msg, beg);
930}
931
932
933
934static char *
935func_word (char *o, char **argv, const char *funcname UNUSED)
936{
937 const char *end_p;
938 const char *p;
939 int i;
940
941 /* Check the first argument. */
942 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
943 i = atoi (argv[0]);
944
945 if (i == 0)
946 fatal (*expanding_var,
947 _("first argument to `word' function must be greater than 0"));
948
949 end_p = argv[1];
950 while ((p = find_next_token (&end_p, 0)) != 0)
951 if (--i == 0)
952 break;
953
954 if (i == 0)
955 o = variable_buffer_output (o, p, end_p - p);
956
957 return o;
958}
959
960static char *
961func_wordlist (char *o, char **argv, const char *funcname UNUSED)
962{
963 int start, count;
964
965 /* Check the arguments. */
966 check_numeric (argv[0],
967 _("non-numeric first argument to `wordlist' function"));
968 check_numeric (argv[1],
969 _("non-numeric second argument to `wordlist' function"));
970
971 start = atoi (argv[0]);
972 if (start < 1)
973 fatal (*expanding_var,
974 "invalid first argument to `wordlist' function: `%d'", start);
975
976 count = atoi (argv[1]) - start + 1;
977
978 if (count > 0)
979 {
980 const char *p;
981 const char *end_p = argv[2];
982
983 /* Find the beginning of the "start"th word. */
984 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
985 ;
986
987 if (p)
988 {
989 /* Find the end of the "count"th word from start. */
990 while (--count && (find_next_token (&end_p, 0) != 0))
991 ;
992
993 /* Return the stuff in the middle. */
994 o = variable_buffer_output (o, p, end_p - p);
995 }
996 }
997
998 return o;
999}
1000
1001static char *
1002func_findstring (char *o, char **argv, const char *funcname UNUSED)
1003{
1004 /* Find the first occurrence of the first string in the second. */
1005 if (strstr (argv[1], argv[0]) != 0)
1006 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
1007
1008 return o;
1009}
1010
1011static char *
1012func_foreach (char *o, char **argv, const char *funcname UNUSED)
1013{
1014 /* expand only the first two. */
1015 char *varname = expand_argument (argv[0], NULL);
1016 char *list = expand_argument (argv[1], NULL);
1017 const char *body = argv[2];
1018#ifdef CONFIG_WITH_VALUE_LENGTH
1019 long body_len = strlen (body);
1020#endif
1021
1022 int doneany = 0;
1023 const char *list_iterator = list;
1024 const char *p;
1025 unsigned int len;
1026 struct variable *var;
1027
1028 push_new_variable_scope ();
1029 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
1030
1031 /* loop through LIST, put the value in VAR and expand BODY */
1032 while ((p = find_next_token (&list_iterator, &len)) != 0)
1033 {
1034#ifndef CONFIG_WITH_VALUE_LENGTH
1035 char *result = 0;
1036
1037 free (var->value);
1038 var->value = savestring (p, len);
1039 result = allocated_variable_expand (body);
1040
1041 o = variable_buffer_output (o, result, strlen (result));
1042 o = variable_buffer_output (o, " ", 1);
1043 doneany = 1;
1044 free (result);
1045#else /* CONFIG_WITH_VALUE_LENGTH */
1046 if (len >= (unsigned int)var->value_alloc_len)
1047 {
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
2188#ifdef CONFIG_WITH_DEFINED
2189/* Similar to ifdef. */
2190static char *
2191func_defined (char *o, char **argv, const char *funcname)
2192{
2193 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
2194 int result = v != NULL && *v->value != '\0';
2195 o = variable_buffer_output (o, result ? "1" : "", result);
2196 return o;
2197}
2198#endif /* CONFIG_WITH_DEFINED*/
2199
2200
2201
2202/* Return the absolute name of file NAME which does not contain any `.',
2203 `..' components nor any repeated path separators ('/'). */
2204#ifdef KMK
2205char *
2206#else
2207static char *
2208#endif
2209abspath (const char *name, char *apath)
2210{
2211 char *dest;
2212 const char *start, *end, *apath_limit;
2213
2214 if (name[0] == '\0' || apath == NULL)
2215 return NULL;
2216
2217#ifdef WINDOWS32 /* bird */
2218 dest = w32ify((char *)name, 1);
2219 if (!dest)
2220 return NULL;
2221 {
2222 size_t len = strlen(dest);
2223 memcpy(apath, dest, len);
2224 dest = apath + len;
2225 }
2226
2227 (void)end; (void)start; (void)apath_limit;
2228
2229#elif defined __OS2__ /* bird */
2230 if (_abspath(apath, name, GET_PATH_MAX))
2231 return NULL;
2232 dest = strchr(apath, '\0');
2233
2234 (void)end; (void)start; (void)apath_limit; (void)dest;
2235
2236#else /* !WINDOWS32 && !__OS2__ */
2237 apath_limit = apath + GET_PATH_MAX;
2238
2239#ifdef HAVE_DOS_PATHS /* bird added this */
2240 if (isalpha(name[0]) && name[1] == ':')
2241 {
2242 /* drive spec */
2243 apath[0] = toupper(name[0]);
2244 apath[1] = ':';
2245 apath[2] = '/';
2246 name += 2;
2247 }
2248 else
2249#endif /* HAVE_DOS_PATHS */
2250 if (name[0] != '/')
2251 {
2252 /* It is unlikely we would make it until here but just to make sure. */
2253 if (!starting_directory)
2254 return NULL;
2255
2256 strcpy (apath, starting_directory);
2257
2258 dest = strchr (apath, '\0');
2259 }
2260 else
2261 {
2262 apath[0] = '/';
2263 dest = apath + 1;
2264 }
2265
2266 for (start = end = name; *start != '\0'; start = end)
2267 {
2268 unsigned long len;
2269
2270 /* Skip sequence of multiple path-separators. */
2271 while (*start == '/')
2272 ++start;
2273
2274 /* Find end of path component. */
2275 for (end = start; *end != '\0' && *end != '/'; ++end)
2276 ;
2277
2278 len = end - start;
2279
2280 if (len == 0)
2281 break;
2282 else if (len == 1 && start[0] == '.')
2283 /* nothing */;
2284 else if (len == 2 && start[0] == '.' && start[1] == '.')
2285 {
2286 /* Back up to previous component, ignore if at root already. */
2287 if (dest > apath + 1)
2288 while ((--dest)[-1] != '/');
2289 }
2290 else
2291 {
2292 if (dest[-1] != '/')
2293 *dest++ = '/';
2294
2295 if (dest + len >= apath_limit)
2296 return NULL;
2297
2298 dest = memcpy (dest, start, len);
2299 dest += len;
2300 *dest = '\0';
2301 }
2302 }
2303#endif /* !WINDOWS32 && !__OS2__ */
2304
2305 /* Unless it is root strip trailing separator. */
2306#ifdef HAVE_DOS_PATHS /* bird (is this correct? what about UNC?) */
2307 if (dest > apath + 1 + (apath[0] != '/') && dest[-1] == '/')
2308#else
2309 if (dest > apath + 1 && dest[-1] == '/')
2310#endif
2311 --dest;
2312
2313 *dest = '\0';
2314
2315 return apath;
2316}
2317
2318
2319static char *
2320func_realpath (char *o, char **argv, const char *funcname UNUSED)
2321{
2322 /* Expand the argument. */
2323 const char *p = argv[0];
2324 const char *path = 0;
2325 int doneany = 0;
2326 unsigned int len = 0;
2327 PATH_VAR (in);
2328 PATH_VAR (out);
2329
2330 while ((path = find_next_token (&p, &len)) != 0)
2331 {
2332 if (len < GET_PATH_MAX)
2333 {
2334 strncpy (in, path, len);
2335 in[len] = '\0';
2336
2337 if (
2338#ifdef HAVE_REALPATH
2339 realpath (in, out)
2340#else
2341 abspath (in, out)
2342#endif
2343 )
2344 {
2345 o = variable_buffer_output (o, out, strlen (out));
2346 o = variable_buffer_output (o, " ", 1);
2347 doneany = 1;
2348 }
2349 }
2350 }
2351
2352 /* Kill last space. */
2353 if (doneany)
2354 --o;
2355
2356 return o;
2357}
2358
2359static char *
2360func_abspath (char *o, char **argv, const char *funcname UNUSED)
2361{
2362 /* Expand the argument. */
2363 const char *p = argv[0];
2364 const char *path = 0;
2365 int doneany = 0;
2366 unsigned int len = 0;
2367 PATH_VAR (in);
2368 PATH_VAR (out);
2369
2370 while ((path = find_next_token (&p, &len)) != 0)
2371 {
2372 if (len < GET_PATH_MAX)
2373 {
2374 strncpy (in, path, len);
2375 in[len] = '\0';
2376
2377 if (abspath (in, out))
2378 {
2379 o = variable_buffer_output (o, out, strlen (out));
2380 o = variable_buffer_output (o, " ", 1);
2381 doneany = 1;
2382 }
2383 }
2384 }
2385
2386 /* Kill last space. */
2387 if (doneany)
2388 --o;
2389
2390 return o;
2391}
2392
2393#ifdef CONFIG_WITH_ABSPATHEX
2394/* Same as abspath except that the current path may be given as the
2395 2nd argument. */
2396static char *
2397func_abspathex (char *o, char **argv, const char *funcname UNUSED)
2398{
2399 char *cwd = argv[1];
2400
2401 /* cwd needs leading spaces chopped and may be optional,
2402 in which case we're exactly like $(abspath ). */
2403 while (isblank(*cwd))
2404 cwd++;
2405 if (!*cwd)
2406 o = func_abspath (o, argv, funcname);
2407 else
2408 {
2409 /* Expand the argument. */
2410 const char *p = argv[0];
2411 unsigned int cwd_len = ~0U;
2412 char *path = 0;
2413 int doneany = 0;
2414 unsigned int len = 0;
2415 PATH_VAR (in);
2416 PATH_VAR (out);
2417
2418 while ((path = find_next_token (&p, &len)) != 0)
2419 {
2420 if (len < GET_PATH_MAX)
2421 {
2422#ifdef HAVE_DOS_PATHS
2423 if (path[0] != '/' && path[0] != '\\' && (len < 2 || path[1] != ':') && cwd)
2424#else
2425 if (path[0] != '/' && cwd)
2426#endif
2427 {
2428 /* relative path, prefix with cwd. */
2429 if (cwd_len == ~0U)
2430 cwd_len = strlen (cwd);
2431 if (cwd_len + len + 1 >= GET_PATH_MAX)
2432 continue;
2433 memcpy (in, cwd, cwd_len);
2434 in[cwd_len] = '/';
2435 memcpy (in + cwd_len + 1, path, len);
2436 in[cwd_len + len + 1] = '\0';
2437 }
2438 else
2439 {
2440 /* absolute path pass it as-is. */
2441 memcpy (in, path, len);
2442 in[len] = '\0';
2443 }
2444
2445 if (abspath (in, out))
2446 {
2447 o = variable_buffer_output (o, out, strlen (out));
2448 o = variable_buffer_output (o, " ", 1);
2449 doneany = 1;
2450 }
2451 }
2452 }
2453
2454 /* Kill last space. */
2455 if (doneany)
2456 --o;
2457 }
2458
2459 return o;
2460}
2461#endif
2462
2463#ifdef CONFIG_WITH_XARGS
2464/* Create one or more command lines avoiding the max argument
2465 lenght restriction of the host OS.
2466
2467 The last argument is the list of arguments that the normal
2468 xargs command would be fed from stdin.
2469
2470 The first argument is initial command and it's arguments.
2471
2472 If there are three or more arguments, the 2nd argument is
2473 the command and arguments to be used on subsequent
2474 command lines. Defaults to the initial command.
2475
2476 If there are four or more arguments, the 3rd argument is
2477 the command to be used at the final command line. Defaults
2478 to the sub sequent or initial command .
2479
2480 A future version of this function may define more arguments
2481 and therefor anyone specifying six or more arguments will
2482 cause fatal errors.
2483
2484 Typical usage is:
2485 $(xargs ar cas mylib.a,$(objects))
2486 or
2487 $(xargs ar cas mylib.a,ar as mylib.a,$(objects))
2488
2489 It will then create one or more "ar mylib.a ..." command
2490 lines with proper \n\t separation so it can be used when
2491 writing rules. */
2492static char *
2493func_xargs (char *o, char **argv, const char *funcname UNUSED)
2494{
2495 int argc;
2496 const char *initial_cmd;
2497 size_t initial_cmd_len;
2498 const char *subsequent_cmd;
2499 size_t subsequent_cmd_len;
2500 const char *final_cmd;
2501 size_t final_cmd_len;
2502 const char *args;
2503 size_t max_args;
2504 int i;
2505
2506#ifdef ARG_MAX
2507 /* ARG_MAX is a bit unreliable (environment), so drop 25% of the max. */
2508# define XARGS_MAX (ARG_MAX - (ARG_MAX / 4))
2509#else /* FIXME: update configure with a command line length test. */
2510# define XARGS_MAX 10240
2511#endif
2512
2513 argc = 0;
2514 while (argv[argc])
2515 argc++;
2516 if (argc > 4)
2517 fatal (NILF, _("Too many arguments for $(xargs)!\n"));
2518
2519 /* first: the initial / default command.*/
2520 initial_cmd = argv[0];
2521 while (isspace ((unsigned char)*initial_cmd))
2522 initial_cmd++;
2523 max_args = initial_cmd_len = strlen (initial_cmd);
2524
2525 /* second: the command for the subsequent command lines. defaults to the initial cmd. */
2526 subsequent_cmd = argc > 2 && argv[1][0] != '\0' ? argv[1] : "";
2527 while (isspace ((unsigned char)*subsequent_cmd))
2528 subsequent_cmd++;
2529 if (*subsequent_cmd)
2530 {
2531 subsequent_cmd_len = strlen (subsequent_cmd);
2532 if (subsequent_cmd_len > max_args)
2533 max_args = subsequent_cmd_len;
2534 }
2535 else
2536 {
2537 subsequent_cmd = initial_cmd;
2538 subsequent_cmd_len = initial_cmd_len;
2539 }
2540
2541 /* third: the final command. defaults to the subseq cmd. */
2542 final_cmd = argc > 3 && argv[2][0] != '\0' ? argv[2] : "";
2543 while (isspace ((unsigned char)*final_cmd))
2544 final_cmd++;
2545 if (*final_cmd)
2546 {
2547 final_cmd_len = strlen (final_cmd);
2548 if (final_cmd_len > max_args)
2549 max_args = final_cmd_len;
2550 }
2551 else
2552 {
2553 final_cmd = subsequent_cmd;
2554 final_cmd_len = subsequent_cmd_len;
2555 }
2556
2557 /* last: the arguments to split up into sensible portions. */
2558 args = argv[argc - 1];
2559
2560 /* calc the max argument length. */
2561 if (XARGS_MAX <= max_args + 2)
2562 fatal (NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
2563 (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
2564 max_args = XARGS_MAX - max_args - 1;
2565
2566 /* generate the commands. */
2567 i = 0;
2568 for (i = 0; ; i++)
2569 {
2570 unsigned int len;
2571 const char *iterator = args;
2572 const char *end = args;
2573 const char *cur;
2574 const char *tmp;
2575
2576 /* scan the arguments till we reach the end or the max length. */
2577 while ((cur = find_next_token(&iterator, &len))
2578 && (size_t)((cur + len) - args) < max_args)
2579 end = cur + len;
2580 if (cur && end == args)
2581 fatal (NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
2582
2583 /* emit the command. */
2584 if (i == 0)
2585 {
2586 o = variable_buffer_output (o, (char *)initial_cmd, initial_cmd_len);
2587 o = variable_buffer_output (o, " ", 1);
2588 }
2589 else if (cur)
2590 {
2591 o = variable_buffer_output (o, "\n\t", 2);
2592 o = variable_buffer_output (o, (char *)subsequent_cmd, subsequent_cmd_len);
2593 o = variable_buffer_output (o, " ", 1);
2594 }
2595 else
2596 {
2597 o = variable_buffer_output (o, "\n\t", 2);
2598 o = variable_buffer_output (o, (char *)final_cmd, final_cmd_len);
2599 o = variable_buffer_output (o, " ", 1);
2600 }
2601
2602 tmp = end;
2603 while (tmp > args && isspace ((unsigned char)tmp[-1])) /* drop trailing spaces. */
2604 tmp--;
2605 o = variable_buffer_output (o, (char *)args, tmp - args);
2606
2607
2608 /* next */
2609 if (!cur)
2610 break;
2611 args = end;
2612 while (isspace ((unsigned char)*args))
2613 args++;
2614 }
2615
2616 return o;
2617}
2618#endif
2619
2620#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2621static char *
2622func_toupper_tolower (char *o, char **argv, const char *funcname)
2623{
2624 /* Expand the argument. */
2625 const char *p = argv[0];
2626 while (*p)
2627 {
2628 /* convert to temporary buffer */
2629 char tmp[256];
2630 unsigned int i;
2631 if (!strcmp(funcname, "toupper"))
2632 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2633 tmp[i] = toupper(*p);
2634 else
2635 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2636 tmp[i] = tolower(*p);
2637 o = variable_buffer_output (o, tmp, i);
2638 }
2639
2640 return o;
2641}
2642#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
2643
2644#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2645
2646/* Strip leading spaces and other things off a command. */
2647static const char *
2648comp_cmds_strip_leading (const char *s, const char *e)
2649{
2650 while (s < e)
2651 {
2652 const char ch = *s;
2653 if (!isblank (ch)
2654 && ch != '@'
2655#ifdef CONFIG_WITH_COMMANDS_FUNC
2656 && ch != '%'
2657#endif
2658 && ch != '+'
2659 && ch != '-')
2660 break;
2661 s++;
2662 }
2663 return s;
2664}
2665
2666/* Worker for func_comp_vars() which is called if the comparision failed.
2667 It will do the slow command by command comparision of the commands
2668 when there invoked as comp-cmds. */
2669static char *
2670comp_vars_ne (char *o, const char *s1, const char *e1, const char *s2, const char *e2,
2671 char *ne_retval, const char *funcname)
2672{
2673 /* give up at once if not comp-cmds or comp-cmds-ex. */
2674 if (strcmp (funcname, "comp-cmds") != 0
2675 && strcmp (funcname, "comp-cmds-ex") != 0)
2676 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
2677 else
2678 {
2679 const char * const s1_start = s1;
2680 int new_cmd = 1;
2681 int diff;
2682 for (;;)
2683 {
2684 /* if it's a new command, strip leading stuff. */
2685 if (new_cmd)
2686 {
2687 s1 = comp_cmds_strip_leading (s1, e1);
2688 s2 = comp_cmds_strip_leading (s2, e2);
2689 new_cmd = 0;
2690 }
2691 if (s1 >= e1 || s2 >= e2)
2692 break;
2693
2694 /*
2695 * Inner compare loop which compares one line.
2696 * FIXME: parse quoting!
2697 */
2698 for (;;)
2699 {
2700 const char ch1 = *s1;
2701 const char ch2 = *s2;
2702 diff = ch1 - ch2;
2703 if (diff)
2704 break;
2705 if (ch1 == '\n')
2706 break;
2707 assert (ch1 != '\r');
2708
2709 /* next */
2710 s1++;
2711 s2++;
2712 if (s1 >= e1 || s2 >= e2)
2713 break;
2714 }
2715
2716 /*
2717 * If we exited because of a difference try to end-of-command
2718 * comparision, e.g. ignore trailing spaces.
2719 */
2720 if (diff)
2721 {
2722 /* strip */
2723 while (s1 < e1 && isblank (*s1))
2724 s1++;
2725 while (s2 < e2 && isblank (*s2))
2726 s2++;
2727 if (s1 >= e1 || s2 >= e2)
2728 break;
2729
2730 /* compare again and check that it's a newline. */
2731 if (*s2 != '\n' || *s1 != '\n')
2732 break;
2733 }
2734 /* Break out if we exited because of EOS. */
2735 else if (s1 >= e1 || s2 >= e2)
2736 break;
2737
2738 /*
2739 * Detect the end of command lines.
2740 */
2741 if (*s1 == '\n')
2742 new_cmd = s1 == s1_start || s1[-1] != '\\';
2743 s1++;
2744 s2++;
2745 }
2746
2747 /*
2748 * Ignore trailing empty lines.
2749 */
2750 if (s1 < e1 || s2 < e2)
2751 {
2752 while (s1 < e1 && (isblank (*s1) || *s1 == '\n'))
2753 if (*s1++ == '\n')
2754 s1 = comp_cmds_strip_leading (s1, e1);
2755 while (s2 < e2 && (isblank (*s2) || *s2 == '\n'))
2756 if (*s2++ == '\n')
2757 s2 = comp_cmds_strip_leading (s2, e2);
2758 }
2759
2760 /* emit the result. */
2761 if (s1 == e1 && s2 == e2)
2762 o = variable_buffer_output (o, "", 1) - 1; /** @todo check why this was necessary back the... */
2763 else
2764 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
2765 }
2766 return o;
2767}
2768
2769/*
2770 $(comp-vars var1,var2,not-equal-return)
2771 or
2772 $(comp-cmds cmd-var1,cmd-var2,not-equal-return)
2773
2774 Compares the two variables (that's given by name to avoid unnecessary
2775 expanding) and return the string in the third argument if not equal.
2776 If equal, nothing is returned.
2777
2778 comp-vars will to an exact comparision only stripping leading and
2779 trailing spaces.
2780
2781 comp-cmds will compare command by command, ignoring not only leading
2782 and trailing spaces on each line but also leading one leading '@',
2783 '-', '+' and '%'
2784*/
2785static char *
2786func_comp_vars (char *o, char **argv, const char *funcname)
2787{
2788 const char *s1, *e1, *x1, *s2, *e2, *x2;
2789 char *a1 = NULL, *a2 = NULL;
2790 size_t l, l1, l2;
2791 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
2792 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
2793
2794 /* the simple cases */
2795 if (var1 == var2)
2796 return variable_buffer_output (o, "", 0); /* eq */
2797 if (!var1 || !var2)
2798 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2799 if (var1->value == var2->value)
2800 return variable_buffer_output (o, "", 0); /* eq */
2801 if (!var1->recursive && !var2->recursive)
2802 {
2803 if ( var1->value_length == var2->value_length
2804 && !memcmp (var1->value, var2->value, var1->value_length))
2805 return variable_buffer_output (o, "", 0); /* eq */
2806
2807 /* ignore trailing and leading blanks */
2808 s1 = var1->value;
2809 e1 = s1 + var1->value_length;
2810 while (isblank ((unsigned char) *s1))
2811 s1++;
2812 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2813 e1--;
2814
2815 s2 = var2->value;
2816 e2 = s2 + var2->value_length;
2817 while (isblank ((unsigned char) *s2))
2818 s2++;
2819 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2820 e2--;
2821
2822 if (e1 - s1 != e2 - s2)
2823 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2824 if (!memcmp (s1, s2, e1 - s1))
2825 return variable_buffer_output (o, "", 0); /* eq */
2826 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2827 }
2828
2829 /* ignore trailing and leading blanks */
2830 s1 = var1->value;
2831 e1 = s1 + var1->value_length;
2832 while (isblank ((unsigned char) *s1))
2833 s1++;
2834 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2835 e1--;
2836
2837 s2 = var2->value;
2838 e2 = s2 + var2->value_length;
2839 while (isblank((unsigned char)*s2))
2840 s2++;
2841 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2842 e2--;
2843
2844 /* both empty after stripping? */
2845 if (s1 == e1 && s2 == e2)
2846 return variable_buffer_output (o, "", 0); /* eq */
2847
2848 /* optimist. */
2849 if ( e1 - s1 == e2 - s2
2850 && !memcmp(s1, s2, e1 - s1))
2851 return variable_buffer_output (o, "", 0); /* eq */
2852
2853 /* compare up to the first '$' or the end. */
2854 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
2855 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
2856 if (!x1 && !x2)
2857 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2858
2859 l1 = x1 ? x1 - s1 : e1 - s1;
2860 l2 = x2 ? x2 - s2 : e2 - s2;
2861 l = l1 <= l2 ? l1 : l2;
2862 if (l && memcmp (s1, s2, l))
2863 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2864
2865 /* one or both buffers now require expanding. */
2866 if (!x1)
2867 s1 += l;
2868 else
2869 {
2870 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
2871 if (!l)
2872 while (isblank ((unsigned char) *s1))
2873 s1++;
2874 e1 = strchr (s1, '\0');
2875 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2876 e1--;
2877 }
2878
2879 if (!x2)
2880 s2 += l;
2881 else
2882 {
2883 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
2884 if (!l)
2885 while (isblank ((unsigned char) *s2))
2886 s2++;
2887 e2 = strchr (s2, '\0');
2888 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2889 e2--;
2890 }
2891
2892 /* the final compare */
2893 if ( e1 - s1 != e2 - s2
2894 || memcmp (s1, s2, e1 - s1))
2895 o = comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2896 else
2897 o = variable_buffer_output (o, "", 1) - 1; /* eq */ /** @todo check why this was necessary back the... */
2898 if (a1)
2899 free (a1);
2900 if (a2)
2901 free (a2);
2902 return o;
2903}
2904
2905/*
2906 $(comp-cmds-ex cmds1,cmds2,not-equal-return)
2907
2908 Compares the two strings and return the string in the third argument
2909 if not equal. If equal, nothing is returned.
2910
2911 The comparision will be performed command by command, ignoring not
2912 only leading and trailing spaces on each line but also leading one
2913 leading '@', '-', '+' and '%'.
2914*/
2915static char *
2916func_comp_cmds_ex (char *o, char **argv, const char *funcname)
2917{
2918 const char *s1, *e1, *s2, *e2;
2919 size_t l1, l2;
2920
2921 /* the simple cases */
2922 s1 = argv[0];
2923 s2 = argv[1];
2924 if (s1 == s2)
2925 return variable_buffer_output (o, "", 0); /* eq */
2926 l1 = strlen (argv[0]);
2927 l2 = strlen (argv[1]);
2928
2929 if ( l1 == l2
2930 && !memcmp (s1, s2, l1))
2931 return variable_buffer_output (o, "", 0); /* eq */
2932
2933 /* ignore trailing and leading blanks */
2934 e1 = s1 + l1;
2935 s1 = comp_cmds_strip_leading (s1, e1);
2936
2937 e2 = s2 + l2;
2938 s2 = comp_cmds_strip_leading (s2, e2);
2939
2940 if (e1 - s1 != e2 - s2)
2941 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2942 if (!memcmp (s1, s2, e1 - s1))
2943 return variable_buffer_output (o, "", 0); /* eq */
2944 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2945}
2946#endif
2947
2948#ifdef CONFIG_WITH_DATE
2949# if defined (_MSC_VER) /* FIXME: !defined (HAVE_STRPTIME) */
2950char *strptime(const char *s, const char *format, struct tm *tm)
2951{
2952 return (char *)"strptime is not implemented";
2953}
2954# endif
2955/* Check if the string is all blanks or not. */
2956static int
2957all_blanks (const char *s)
2958{
2959 if (!s)
2960 return 1;
2961 while (isspace ((unsigned char)*s))
2962 s++;
2963 return *s == '\0';
2964}
2965
2966/* The first argument is the strftime format string, a iso
2967 timestamp is the default if nothing is given.
2968
2969 The second argument is a time value if given. The format
2970 is either the format from the first argument or given as
2971 an additional third argument. */
2972static char *
2973func_date (char *o, char **argv, const char *funcname)
2974{
2975 char *p;
2976 char *buf;
2977 size_t buf_size;
2978 struct tm t;
2979 const char *format;
2980
2981 /* determin the format - use a single word as the default. */
2982 format = !strcmp (funcname, "date-utc")
2983 ? "%Y-%m-%dT%H:%M:%SZ"
2984 : "%Y-%m-%dT%H:%M:%S";
2985 if (!all_blanks (argv[0]))
2986 format = argv[0];
2987
2988 /* get the time. */
2989 memset (&t, 0, sizeof(t));
2990 if (argv[0] && !all_blanks (argv[1]))
2991 {
2992 const char *input_format = !all_blanks (argv[2]) ? argv[2] : format;
2993 p = strptime (argv[1], input_format, &t);
2994 if (!p || *p != '\0')
2995 {
2996 error (NILF, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname,
2997 argv[1], input_format, p ? p : "<null>");
2998 return variable_buffer_output (o, "", 0);
2999 }
3000 }
3001 else
3002 {
3003 time_t tval;
3004 time (&tval);
3005 if (!strcmp (funcname, "date-utc"))
3006 t = *gmtime (&tval);
3007 else
3008 t = *localtime (&tval);
3009 }
3010
3011 /* format it. note that zero isn't necessarily an error, so we'll
3012 have to keep shut about failures. */
3013 buf_size = 64;
3014 buf = xmalloc (buf_size);
3015 while (strftime (buf, buf_size, format, &t) == 0)
3016 {
3017 if (buf_size >= 4096)
3018 {
3019 *buf = '\0';
3020 break;
3021 }
3022 buf = xrealloc (buf, buf_size <<= 1);
3023 }
3024 o = variable_buffer_output (o, buf, strlen (buf));
3025 free (buf);
3026 return o;
3027}
3028#endif
3029
3030#ifdef CONFIG_WITH_FILE_SIZE
3031/* Prints the size of the specified file. Only one file is
3032 permitted, notthing is stripped. -1 is returned if stat
3033 fails. */
3034static char *
3035func_file_size (char *o, char **argv, const char *funcname UNUSED)
3036{
3037 struct stat st;
3038 if (stat (argv[0], &st))
3039 return variable_buffer_output (o, "-1", 2);
3040 return math_int_to_variable_buffer (o, st.st_size);
3041}
3042#endif
3043
3044#ifdef CONFIG_WITH_WHICH
3045/* Checks if the specified file exists an is executable.
3046 On systems employing executable extensions, the name may
3047 be modified to include the extension. */
3048static int func_which_test_x (char *file)
3049{
3050 struct stat st;
3051# if defined(WINDOWS32) || defined(__OS2__)
3052 char *ext;
3053 char *slash;
3054
3055 /* fix slashes first. */
3056 slash = file;
3057 while ((slash = strchr (slash, '\\')) != NULL)
3058 *slash++ = '/';
3059
3060 /* straight */
3061 if (stat (file, &st) == 0
3062 && S_ISREG (st.st_mode))
3063 return 1;
3064
3065 /* don't try add an extension if there already is one */
3066 ext = strchr (file, '\0');
3067 if (ext - file >= 4
3068 && ( !stricmp (ext - 4, ".exe")
3069 || !stricmp (ext - 4, ".cmd")
3070 || !stricmp (ext - 4, ".bat")
3071 || !stricmp (ext - 4, ".com")))
3072 return 0;
3073
3074 /* try the extensions. */
3075 strcpy (ext, ".exe");
3076 if (stat (file, &st) == 0
3077 && S_ISREG (st.st_mode))
3078 return 1;
3079
3080 strcpy (ext, ".cmd");
3081 if (stat (file, &st) == 0
3082 && S_ISREG (st.st_mode))
3083 return 1;
3084
3085 strcpy (ext, ".bat");
3086 if (stat (file, &st) == 0
3087 && S_ISREG (st.st_mode))
3088 return 1;
3089
3090 strcpy (ext, ".com");
3091 if (stat (file, &st) == 0
3092 && S_ISREG (st.st_mode))
3093 return 1;
3094
3095 return 0;
3096
3097# else
3098
3099 return access (file, X_OK) == 0
3100 && stat (file, &st) == 0
3101 && S_ISREG (st.st_mode);
3102# endif
3103}
3104
3105/* Searches for the specified programs in the PATH and print
3106 their full location if found. Prints nothing if not found. */
3107static char *
3108func_which (char *o, char **argv, const char *funcname UNUSED)
3109{
3110 const char *path;
3111 struct variable *path_var;
3112 unsigned i;
3113 int first = 1;
3114 PATH_VAR (buf);
3115
3116 path_var = lookup_variable ("PATH", 4);
3117 if (path_var)
3118 path = path_var->value;
3119 else
3120 path = ".";
3121
3122 /* iterate input */
3123 for (i = 0; argv[i]; i++)
3124 {
3125 unsigned int len;
3126 const char *iterator = argv[i];
3127 char *cur;
3128
3129 while ((cur = find_next_token (&iterator, &len)))
3130 {
3131 /* if there is a separator, don't walk the path. */
3132 if (memchr (cur, '/', len)
3133#ifdef HAVE_DOS_PATHS
3134 || memchr (cur, '\\', len)
3135 || memchr (cur, ':', len)
3136#endif
3137 )
3138 {
3139 if (len + 1 + 4 < GET_PATH_MAX) /* +4 for .exe */
3140 {
3141 memcpy (buf, cur, len);
3142 buf[len] = '\0';
3143 if (func_which_test_x (buf))
3144 o = variable_buffer_output (o, buf, strlen (buf));
3145 }
3146 }
3147 else
3148 {
3149 const char *comp = path;
3150 for (;;)
3151 {
3152 const char *src = comp;
3153 const char *end = strchr (comp, PATH_SEPARATOR_CHAR);
3154 size_t comp_len = end ? (size_t)(end - comp) : strlen (comp);
3155 if (!comp_len)
3156 {
3157 comp_len = 1;
3158 src = ".";
3159 }
3160 if (len + comp_len + 2 + 4 < GET_PATH_MAX) /* +4 for .exe */
3161 {
3162 memcpy (buf, comp, comp_len);
3163 buf [comp_len] = '/';
3164 memcpy (&buf[comp_len + 1], cur, len);
3165 buf[comp_len + 1 + len] = '\0';
3166
3167 if (func_which_test_x (buf))
3168 {
3169 if (!first)
3170 o = variable_buffer_output (o, " ", 1);
3171 o = variable_buffer_output (o, buf, strlen (buf));
3172 first = 0;
3173 break;
3174 }
3175 }
3176
3177 /* next */
3178 if (!end)
3179 break;
3180 comp = end + 1;
3181 }
3182 }
3183 }
3184 }
3185
3186 return variable_buffer_output (o, "", 0);
3187}
3188#endif /* CONFIG_WITH_WHICH */
3189
3190#ifdef CONFIG_WITH_IF_CONDITIONALS
3191
3192/* Evaluates the expression given in the argument using the
3193 same evaluator as for the new 'if' statements, except now
3194 we don't force the result into a boolean like for 'if' and
3195 '$(if-expr ,,)'. */
3196static char *
3197func_expr (char *o, char **argv, const char *funcname UNUSED)
3198{
3199 o = expr_eval_to_string (o, argv[0]);
3200 return o;
3201}
3202
3203/* Same as '$(if ,,)' except the first argument is evaluated
3204 using the same evaluator as for the new 'if' statements. */
3205static char *
3206func_if_expr (char *o, char **argv, const char *funcname UNUSED)
3207{
3208 int rc;
3209 char *to_expand;
3210
3211 /* Evaluate the condition in argv[0] and expand the 2nd or
3212 3rd argument according to the result. */
3213 rc = expr_eval_if_conditionals (argv[0], NULL);
3214 to_expand = rc == 0 ? argv[1] : argv[2];
3215 if (*to_expand)
3216 {
3217 char *expansion = expand_argument (to_expand, NULL);
3218
3219 o = variable_buffer_output (o, expansion, strlen (expansion));
3220
3221 free (expansion);
3222 }
3223
3224 return o;
3225}
3226
3227#endif /* CONFIG_WITH_IF_CONDITIONALS */
3228
3229#ifdef CONFIG_WITH_STACK
3230
3231/* Push an item (string without spaces). */
3232static char *
3233func_stack_push (char *o, char **argv, const char *funcname UNUSED)
3234{
3235 do_variable_definition(NILF, argv[0], argv[1], o_file, f_append, 0 /* !target_var */);
3236 return o;
3237}
3238
3239/* Pops an item off the stack / get the top stack element.
3240 (This is what's tricky to do in pure GNU make syntax.) */
3241static char *
3242func_stack_pop_top (char *o, char **argv, const char *funcname)
3243{
3244 struct variable *stack_var;
3245 const char *stack = argv[0];
3246
3247 stack_var = lookup_variable (stack, strlen (stack) );
3248 if (stack_var)
3249 {
3250 unsigned int len;
3251 const char *iterator = stack_var->value;
3252 char *lastitem = NULL;
3253 char *cur;
3254
3255 while ((cur = find_next_token (&iterator, &len)))
3256 lastitem = cur;
3257
3258 if (lastitem != NULL)
3259 {
3260 if (strcmp (funcname, "stack-popv") != 0)
3261 o = variable_buffer_output (o, lastitem, len);
3262 if (strcmp (funcname, "stack-top") != 0)
3263 {
3264 *lastitem = '\0';
3265 while (lastitem > stack_var->value && isspace (lastitem[-1]))
3266 *--lastitem = '\0';
3267#ifdef CONFIG_WITH_VALUE_LENGTH
3268 stack_var->value_length = lastitem - stack_var->value;
3269#endif
3270 }
3271 }
3272 }
3273 return o;
3274}
3275#endif /* CONFIG_WITH_STACK */
3276
3277#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE)
3278/* outputs the number (as a string) into the variable buffer. */
3279static char *
3280math_int_to_variable_buffer (char *o, math_int num)
3281{
3282 static const char xdigits[17] = "0123456789abcdef";
3283 int negative;
3284 char strbuf[24]; /* 16 hex + 2 prefix + sign + term => 20
3285 or 20 dec + sign + term => 22 */
3286 char *str = &strbuf[sizeof (strbuf) - 1];
3287
3288 negative = num < 0;
3289 if (negative)
3290 num = -num;
3291
3292 *str = '\0';
3293
3294 do
3295 {
3296#ifdef HEX_MATH_NUMBERS
3297 *--str = xdigits[num & 0xf];
3298 num >>= 4;
3299#else
3300 *--str = xdigits[num % 10];
3301 num /= 10;
3302#endif
3303 }
3304 while (num);
3305
3306#ifdef HEX_MATH_NUMBERS
3307 *--str = 'x';
3308 *--str = '0';
3309#endif
3310
3311 if (negative)
3312 *--str = '-';
3313
3314 return variable_buffer_output (o, str, &strbuf[sizeof (strbuf) - 1] - str);
3315}
3316#endif /* CONFIG_WITH_MATH || CONFIG_WITH_NANOTS */
3317
3318#ifdef CONFIG_WITH_MATH
3319
3320/* Converts a string to an integer, causes an error if the format is invalid. */
3321static math_int
3322math_int_from_string (const char *str)
3323{
3324 const char *start;
3325 unsigned base = 0;
3326 int negative = 0;
3327 math_int num = 0;
3328
3329 /* strip spaces */
3330 while (isspace (*str))
3331 str++;
3332 if (!*str)
3333 {
3334 error (NILF, _("bad number: empty\n"));
3335 return 0;
3336 }
3337 start = str;
3338
3339 /* check for +/- */
3340 while (*str == '+' || *str == '-' || isspace (*str))
3341 if (*str++ == '-')
3342 negative = !negative;
3343
3344 /* check for prefix - we do not accept octal numbers, sorry. */
3345 if (*str == '0' && (str[1] == 'x' || str[1] == 'X'))
3346 {
3347 base = 16;
3348 str += 2;
3349 }
3350 else
3351 {
3352 /* look for a hex digit, if not found treat it as decimal */
3353 const char *p2 = str;
3354 for ( ; *p2; p2++)
3355 if (isxdigit (*p2) && !isdigit (*p2) && isascii (*p2) )
3356 {
3357 base = 16;
3358 break;
3359 }
3360 if (base == 0)
3361 base = 10;
3362 }
3363
3364 /* must have at least one digit! */
3365 if ( !isascii (*str)
3366 || !(base == 16 ? isxdigit (*str) : isdigit (*str)) )
3367 {
3368 error (NILF, _("bad number: '%s'\n"), start);
3369 return 0;
3370 }
3371
3372 /* convert it! */
3373 while (*str && !isspace (*str))
3374 {
3375 int ch = *str++;
3376 if (ch >= '0' && ch <= '9')
3377 ch -= '0';
3378 else if (base == 16 && ch >= 'a' && ch <= 'f')
3379 ch -= 'a' - 10;
3380 else if (base == 16 && ch >= 'A' && ch <= 'F')
3381 ch -= 'A' - 10;
3382 else
3383 {
3384 error (NILF, _("bad number: '%s' (base=%d, pos=%d)\n"), start, base, str - start);
3385 return 0;
3386 }
3387 num *= base;
3388 num += ch;
3389 }
3390
3391 /* check trailing spaces. */
3392 while (isspace (*str))
3393 str++;
3394 if (*str)
3395 {
3396 error (NILF, _("bad number: '%s'\n"), start);
3397 return 0;
3398 }
3399
3400 return negative ? -num : num;
3401}
3402
3403/* Add two or more integer numbers. */
3404static char *
3405func_int_add (char *o, char **argv, const char *funcname UNUSED)
3406{
3407 math_int num;
3408 int i;
3409
3410 num = math_int_from_string (argv[0]);
3411 for (i = 1; argv[i]; i++)
3412 num += math_int_from_string (argv[i]);
3413
3414 return math_int_to_variable_buffer (o, num);
3415}
3416
3417/* Subtract two or more integer numbers. */
3418static char *
3419func_int_sub (char *o, char **argv, const char *funcname UNUSED)
3420{
3421 math_int num;
3422 int i;
3423
3424 num = math_int_from_string (argv[0]);
3425 for (i = 1; argv[i]; i++)
3426 num -= math_int_from_string (argv[i]);
3427
3428 return math_int_to_variable_buffer (o, num);
3429}
3430
3431/* Multiply two or more integer numbers. */
3432static char *
3433func_int_mul (char *o, char **argv, const char *funcname UNUSED)
3434{
3435 math_int num;
3436 int i;
3437
3438 num = math_int_from_string (argv[0]);
3439 for (i = 1; argv[i]; i++)
3440 num *= math_int_from_string (argv[i]);
3441
3442 return math_int_to_variable_buffer (o, num);
3443}
3444
3445/* Divide an integer number by one or more divisors. */
3446static char *
3447func_int_div (char *o, char **argv, const char *funcname UNUSED)
3448{
3449 math_int num;
3450 math_int divisor;
3451 int i;
3452
3453 num = math_int_from_string (argv[0]);
3454 for (i = 1; argv[i]; i++)
3455 {
3456 divisor = math_int_from_string (argv[i]);
3457 if (!divisor)
3458 {
3459 error (NILF, _("divide by zero ('%s')\n"), argv[i]);
3460 return math_int_to_variable_buffer (o, 0);
3461 }
3462 num /= divisor;
3463 }
3464
3465 return math_int_to_variable_buffer (o, num);
3466}
3467
3468
3469/* Divide and return the remainder. */
3470static char *
3471func_int_mod (char *o, char **argv, const char *funcname UNUSED)
3472{
3473 math_int num;
3474 math_int divisor;
3475
3476 num = math_int_from_string (argv[0]);
3477 divisor = math_int_from_string (argv[1]);
3478 if (!divisor)
3479 {
3480 error (NILF, _("divide by zero ('%s')\n"), argv[1]);
3481 return math_int_to_variable_buffer (o, 0);
3482 }
3483 num %= divisor;
3484
3485 return math_int_to_variable_buffer (o, num);
3486}
3487
3488/* 2-complement. */
3489static char *
3490func_int_not (char *o, char **argv, const char *funcname UNUSED)
3491{
3492 math_int num;
3493
3494 num = math_int_from_string (argv[0]);
3495 num = ~num;
3496
3497 return math_int_to_variable_buffer (o, num);
3498}
3499
3500/* Bitwise AND (two or more numbers). */
3501static char *
3502func_int_and (char *o, char **argv, const char *funcname UNUSED)
3503{
3504 math_int num;
3505 int i;
3506
3507 num = math_int_from_string (argv[0]);
3508 for (i = 1; argv[i]; i++)
3509 num &= math_int_from_string (argv[i]);
3510
3511 return math_int_to_variable_buffer (o, num);
3512}
3513
3514/* Bitwise OR (two or more numbers). */
3515static char *
3516func_int_or (char *o, char **argv, const char *funcname UNUSED)
3517{
3518 math_int num;
3519 int i;
3520
3521 num = math_int_from_string (argv[0]);
3522 for (i = 1; argv[i]; i++)
3523 num |= math_int_from_string (argv[i]);
3524
3525 return math_int_to_variable_buffer (o, num);
3526}
3527
3528/* Bitwise XOR (two or more numbers). */
3529static char *
3530func_int_xor (char *o, char **argv, const char *funcname UNUSED)
3531{
3532 math_int num;
3533 int i;
3534
3535 num = math_int_from_string (argv[0]);
3536 for (i = 1; argv[i]; i++)
3537 num ^= math_int_from_string (argv[i]);
3538
3539 return math_int_to_variable_buffer (o, num);
3540}
3541
3542/* Compare two integer numbers. Returns make boolean (true="1"; false=""). */
3543static char *
3544func_int_cmp (char *o, char **argv, const char *funcname)
3545{
3546 math_int num1;
3547 math_int num2;
3548 int rc;
3549
3550 num1 = math_int_from_string (argv[0]);
3551 num2 = math_int_from_string (argv[1]);
3552
3553 funcname += sizeof ("int-") - 1;
3554 if (!strcmp (funcname, "eq"))
3555 rc = num1 == num2;
3556 else if (!strcmp (funcname, "ne"))
3557 rc = num1 != num2;
3558 else if (!strcmp (funcname, "gt"))
3559 rc = num1 > num2;
3560 else if (!strcmp (funcname, "ge"))
3561 rc = num1 >= num2;
3562 else if (!strcmp (funcname, "lt"))
3563 rc = num1 < num2;
3564 else /*if (!strcmp (funcname, "le"))*/
3565 rc = num1 <= num2;
3566
3567 return variable_buffer_output (o, rc ? "1" : "", rc);
3568}
3569
3570#endif /* CONFIG_WITH_MATH */
3571
3572#ifdef CONFIG_WITH_NANOTS
3573/* Returns the current timestamp as nano seconds. The time
3574 source is a high res monotone one if the platform provides
3575 this (and we know about it).
3576
3577 Tip. Use this with int-sub to profile makefile reading
3578 and similar. */
3579static char *
3580func_nanots (char *o, char **argv, const char *funcname)
3581{
3582 math_int ts;
3583
3584#if defined (WINDOWS32)
3585 static int s_state = -1;
3586 static LARGE_INTEGER s_freq;
3587
3588 if (s_state == -1)
3589 s_state = QueryPerformanceFrequency (&s_freq);
3590 if (s_state)
3591 {
3592 LARGE_INTEGER pc;
3593 if (!QueryPerformanceCounter (&pc))
3594 {
3595 s_state = 0;
3596 return func_nanots (o, argv, funcname);
3597 }
3598 ts = (math_int)((long double)pc.QuadPart / (long double)s_freq.QuadPart * 1000000000);
3599 }
3600 else
3601 {
3602 /* fall back to low resolution system time. */
3603 LARGE_INTEGER bigint;
3604 FILETIME ft = {0,0};
3605 GetSystemTimeAsFileTime (&ft);
3606 bigint.u.LowPart = ft.dwLowDateTime;
3607 bigint.u.HighPart = ft.dwLowDateTime;
3608 ts = bigint.QuadPart * 100;
3609 }
3610
3611/* FIXME: Linux and others have the realtime clock_* api, detect and use it. */
3612
3613#elif HAVE_GETTIMEOFDAY
3614 struct timeval tv;
3615 if (!gettimeofday (&tv, NULL))
3616 ts = (math_int)tv.tv_sec * 1000000000
3617 + tv.tv_usec * 1000;
3618 else
3619 {
3620 error (NILF, _("$(nanots): gettimeofday failed"));
3621 ts = 0;
3622 }
3623
3624#else
3625# error "PORTME"
3626#endif
3627
3628 return math_int_to_variable_buffer (o, ts);
3629}
3630#endif
3631
3632#ifdef CONFIG_WITH_OS2_LIBPATH
3633/* Sets or gets the OS/2 libpath variables.
3634
3635 The first argument indicates which variable - BEGINLIBPATH,
3636 ENDLIBPATH, LIBPATHSTRICT or LIBPATH.
3637
3638 The second indicates whether this is a get (not present) or
3639 set (present) operation. When present it is the new value for
3640 the variable. */
3641static char *
3642func_os2_libpath (char *o, char **argv, const char *funcname UNUSED)
3643{
3644 char buf[4096];
3645 ULONG fVar;
3646 APIRET rc;
3647
3648 /* translate variable name (first arg) */
3649 if (!strcmp (argv[0], "BEGINLIBPATH"))
3650 fVar = BEGIN_LIBPATH;
3651 else if (!strcmp (argv[0], "ENDLIBPATH"))
3652 fVar = END_LIBPATH;
3653 else if (!strcmp (argv[0], "LIBPATHSTRICT"))
3654 fVar = LIBPATHSTRICT;
3655 else if (!strcmp (argv[0], "LIBPATH"))
3656 fVar = 0;
3657 else
3658 {
3659 error (NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
3660 return variable_buffer_output (o, "", 0);
3661 }
3662
3663 if (!argv[1])
3664 {
3665 /* get the variable value. */
3666 if (fVar != 0)
3667 {
3668 buf[0] = buf[1] = buf[2] = buf[3] = '\0';
3669 rc = DosQueryExtLIBPATH (buf, fVar);
3670 }
3671 else
3672 rc = DosQueryHeaderInfo (NULLHANDLE, 0, buf, sizeof(buf), QHINF_LIBPATH);
3673 if (rc != NO_ERROR)
3674 {
3675 error (NILF, _("$(libpath): failed to query `%s', rc=%d"), argv[0], rc);
3676 return variable_buffer_output (o, "", 0);
3677 }
3678 o = variable_buffer_output (o, buf, strlen (buf));
3679 }
3680 else
3681 {
3682 /* set the variable value. */
3683 size_t len;
3684 size_t len_max = sizeof (buf) < 2048 ? sizeof (buf) : 2048;
3685 const char *val;
3686 const char *end;
3687
3688 if (fVar == 0)
3689 {
3690 error (NILF, _("$(libpath): LIBPATH is read-only"));
3691 return variable_buffer_output (o, "", 0);
3692 }
3693
3694 /* strip leading and trailing spaces and check for max length. */
3695 val = argv[1];
3696 while (isspace (*val))
3697 val++;
3698 end = strchr (val, '\0');
3699 while (end > val && isspace (end[-1]))
3700 end--;
3701
3702 len = end - val;
3703 if (len >= len_max)
3704 {
3705 error (NILF, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
3706 argv[0], len, len_max);
3707 return variable_buffer_output (o, "", 0);
3708 }
3709
3710 /* make a stripped copy in low memory and try set it. */
3711 memcpy (buf, val, len);
3712 buf[len] = '\0';
3713 rc = DosSetExtLIBPATH (buf, fVar);
3714 if (rc != NO_ERROR)
3715 {
3716 error (NILF, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv[0], buf, rc);
3717 return variable_buffer_output (o, "", 0);
3718 }
3719
3720 o = variable_buffer_output (o, "", 0);
3721 }
3722 return o;
3723}
3724#endif /* CONFIG_WITH_OS2_LIBPATH */
3725
3726#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
3727/* Retrieve make statistics. */
3728static char *
3729func_make_stats (char *o, char **argv, const char *funcname UNUSED)
3730{
3731 char buf[512];
3732 int len;
3733
3734 if (!argv[0] || (!argv[0][0] && !argv[1]))
3735 {
3736# ifdef CONFIG_WITH_MAKE_STATS
3737 len = sprintf (buf, "alloc-cur: %5ld %6luKB (/%3luMB) hash: %5lu %2lu%%",
3738 make_stats_allocations,
3739 make_stats_allocated / 1024,
3740 make_stats_allocated_sum / (1024*1024),
3741 make_stats_ht_lookups,
3742 (make_stats_ht_collisions * 100) / make_stats_ht_lookups);
3743 o = variable_buffer_output (o, buf, len);
3744#endif
3745 }
3746 else
3747 {
3748 /* selective */
3749 int i;
3750 for (i = 0; argv[i]; i++)
3751 {
3752 unsigned long val;
3753 if (i != 0)
3754 o = variable_buffer_output (o, " ", 1);
3755 if (0)
3756 continue;
3757# ifdef CONFIG_WITH_MAKE_STATS
3758 else if (!strcmp(argv[i], "allocations"))
3759 val = make_stats_allocations;
3760 else if (!strcmp(argv[i], "allocated"))
3761 val = make_stats_allocated;
3762 else if (!strcmp(argv[i], "allocated_sum"))
3763 val = make_stats_allocated_sum;
3764 else if (!strcmp(argv[i], "ht_lookups"))
3765 val = make_stats_ht_lookups;
3766 else if (!strcmp(argv[i], "ht_collisions"))
3767 val = make_stats_ht_collisions;
3768 else if (!strcmp(argv[i], "ht_collisions_pct"))
3769 val = (make_stats_ht_collisions * 100) / make_stats_ht_lookups;
3770#endif
3771 else
3772 {
3773 o = variable_buffer_output (o, argv[i], strlen (argv[i]));
3774 continue;
3775 }
3776
3777 len = sprintf (buf, "%ld", val);
3778 o = variable_buffer_output (o, buf, len);
3779 }
3780 }
3781
3782 return o;
3783}
3784#endif /* CONFIG_WITH_MAKE_STATS */
3785
3786#ifdef CONFIG_WITH_COMMANDS_FUNC
3787/* Gets all the commands for a target, separated by newlines.
3788
3789 This is useful when creating and checking target dependencies since
3790 it reduces the amount of work and the memory consuption. A new prefix
3791 character '%' has been introduced for skipping certain lines, like
3792 for instance the one calling this function and pushing to a dep file.
3793 Blank lines are also skipped.
3794
3795 The commands function takes exactly one argument, which is the name of
3796 the target which commands should be returned.
3797
3798 The commands-sc is identical to commands except that it uses a ';' to
3799 separate the commands.
3800
3801 The commands-usr is similar to commands except that it takes a 2nd
3802 argument that is used to separate the commands. */
3803char *
3804func_commands (char *o, char **argv, const char *funcname)
3805{
3806 struct file *file;
3807 static int recursive = 0;
3808
3809 if (recursive)
3810 {
3811 error (reading_file, _("$(%s ) was invoked recursivly"), funcname);
3812 return variable_buffer_output (o, "recursive", sizeof ("recursive") - 1);
3813 }
3814 if (*argv[0] == '\0')
3815 {
3816 error (reading_file, _("$(%s ) was invoked with an empty target name"), funcname);
3817 return o;
3818 }
3819 recursive = 1;
3820
3821 file = lookup_file (argv[0]);
3822 if (file && file->cmds)
3823 {
3824 unsigned int i;
3825 int cmd_sep_len;
3826 struct commands *cmds = file->cmds;
3827 const char *cmd_sep;
3828
3829 if (!strcmp (funcname, "commands"))
3830 {
3831 cmd_sep = "\n";
3832 cmd_sep_len = 1;
3833 }
3834 else if (!strcmp (funcname, "commands-sc"))
3835 {
3836 cmd_sep = ";";
3837 cmd_sep_len = 1;
3838 }
3839 else /*if (!strcmp (funcname, "commands-usr"))*/
3840 {
3841 cmd_sep = argv[1];
3842 cmd_sep_len = strlen (cmd_sep);
3843 }
3844
3845 initialize_file_variables (file, 1 /* reading - FIXME: we don't know? */);
3846 set_file_variables (file);
3847 chop_commands (cmds);
3848
3849 for (i = 0; i < cmds->ncommand_lines; i++)
3850 {
3851 char *p;
3852 char *in, *out, *ref;
3853
3854 /* Skip it if it has a '%' prefix or is blank. */
3855 if (cmds->lines_flags[i] & COMMAND_GETTER_SKIP_IT)
3856 continue;
3857 p = cmds->command_lines[i];
3858 while (isblank ((unsigned char)*p))
3859 p++;
3860 if (*p == '\0')
3861 continue;
3862
3863 /* --- copied from new_job() in job.c --- */
3864
3865 /* Collapse backslash-newline combinations that are inside variable
3866 or function references. These are left alone by the parser so
3867 that they will appear in the echoing of commands (where they look
3868 nice); and collapsed by construct_command_argv when it tokenizes.
3869 But letting them survive inside function invocations loses because
3870 we don't want the functions to see them as part of the text. */
3871
3872 /* IN points to where in the line we are scanning.
3873 OUT points to where in the line we are writing.
3874 When we collapse a backslash-newline combination,
3875 IN gets ahead of OUT. */
3876
3877 in = out = p;
3878 while ((ref = strchr (in, '$')) != 0)
3879 {
3880 ++ref; /* Move past the $. */
3881
3882 if (out != in)
3883 /* Copy the text between the end of the last chunk
3884 we processed (where IN points) and the new chunk
3885 we are about to process (where REF points). */
3886 memmove (out, in, ref - in);
3887
3888 /* Move both pointers past the boring stuff. */
3889 out += ref - in;
3890 in = ref;
3891
3892 if (*ref == '(' || *ref == '{')
3893 {
3894 char openparen = *ref;
3895 char closeparen = openparen == '(' ? ')' : '}';
3896 int count;
3897 char *p;
3898
3899 *out++ = *in++; /* Copy OPENPAREN. */
3900 /* IN now points past the opening paren or brace.
3901 Count parens or braces until it is matched. */
3902 count = 0;
3903 while (*in != '\0')
3904 {
3905 if (*in == closeparen && --count < 0)
3906 break;
3907 else if (*in == '\\' && in[1] == '\n')
3908 {
3909 /* We have found a backslash-newline inside a
3910 variable or function reference. Eat it and
3911 any following whitespace. */
3912
3913 int quoted = 0;
3914 for (p = in - 1; p > ref && *p == '\\'; --p)
3915 quoted = !quoted;
3916
3917 if (quoted)
3918 /* There were two or more backslashes, so this is
3919 not really a continuation line. We don't collapse
3920 the quoting backslashes here as is done in
3921 collapse_continuations, because the line will
3922 be collapsed again after expansion. */
3923 *out++ = *in++;
3924 else
3925 {
3926 /* Skip the backslash, newline and
3927 any following whitespace. */
3928 in = next_token (in + 2);
3929
3930 /* Discard any preceding whitespace that has
3931 already been written to the output. */
3932 while (out > ref
3933 && isblank ((unsigned char)out[-1]))
3934 --out;
3935
3936 /* Replace it all with a single space. */
3937 *out++ = ' ';
3938 }
3939 }
3940 else
3941 {
3942 if (*in == openparen)
3943 ++count;
3944
3945 *out++ = *in++;
3946 }
3947 }
3948 }
3949 /* Some of these can be amended ($< perhaps), but we're likely to be called while the
3950 dep expansion happens, so it would have to be on a hackish basis. sad... */
3951 else if (*ref == '<' || *ref == '*' || *ref == '%' || *ref == '^' || *ref == '+')
3952 error (reading_file, _("$(%s ) does not work reliably with $%c in all cases"), funcname, *ref);
3953 }
3954
3955 /* There are no more references in this line to worry about.
3956 Copy the remaining uninteresting text to the output. */
3957 if (out != in)
3958 strcpy (out, in);
3959
3960 /* --- copied from new_job() in job.c --- */
3961
3962 /* Finally, expand the line. */
3963 if (i)
3964 o = variable_buffer_output (o, cmd_sep, cmd_sep_len);
3965 o = variable_expand_for_file_2 (o, cmds->command_lines[i], ~0U, file, NULL);
3966
3967 /* Skip it if it has a '%' prefix or is blank. */
3968 p = o;
3969 while (isblank ((unsigned char)*o)
3970 || *o == '@'
3971 || *o == '-'
3972 || *o == '+')
3973 o++;
3974 if (*o != '\0' && *o != '%')
3975 o = strchr (o, '\0');
3976 else if (i)
3977 o = p - cmd_sep_len;
3978 else
3979 o = p;
3980 } /* for each command line */
3981 }
3982 /* else FIXME: bitch about it? */
3983
3984 recursive = 0;
3985 return o;
3986}
3987#endif /* CONFIG_WITH_COMMANDS_FUNC */
3988
3989#ifdef KMK
3990/* Useful when debugging kmk and/or makefiles. */
3991char *
3992func_breakpoint (char *o, char **argv, const char *funcname)
3993{
3994#ifdef _MSC_VER
3995 __debugbreak();
3996#elif defined(__i386__) || defined(__x86__) || defined(__X86__) || defined(_M_IX86) || defined(__i386) \
3997 || defined(__amd64__) || defined(__x86_64__) || defined(__AMD64__) || defined(_M_X64) || defined(__amd64)
3998 __asm__ __volatile__ ("int3\n\t");
3999#else
4000 char *p = (char *)0;
4001 *p = '\0';
4002#endif
4003 return o;
4004}
4005#endif /* KMK */
4006
4007
4008/* Lookup table for builtin functions.
4009
4010 This doesn't have to be sorted; we use a straight lookup. We might gain
4011 some efficiency by moving most often used functions to the start of the
4012 table.
4013
4014 If MAXIMUM_ARGS is 0, that means there is no maximum and all
4015 comma-separated values are treated as arguments.
4016
4017 EXPAND_ARGS means that all arguments should be expanded before invocation.
4018 Functions that do namespace tricks (foreach) don't automatically expand. */
4019
4020static char *func_call (char *o, char **argv, const char *funcname);
4021
4022
4023static struct function_table_entry function_table_init[] =
4024{
4025 /* Name/size */ /* MIN MAX EXP? Function */
4026 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
4027 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
4028 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
4029 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
4030 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
4031 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
4032 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
4033 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
4034 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
4035 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
4036 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
4037 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
4038 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
4039 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
4040 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
4041 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
4042 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
4043#ifdef CONFIG_WITH_RSORT
4044 { STRING_SIZE_TUPLE("rsort"), 0, 1, 1, func_sort},
4045#endif
4046 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
4047 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
4048 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
4049 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
4050 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
4051 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
4052 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
4053 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
4054 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
4055 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
4056 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
4057 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
4058 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
4059 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
4060 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
4061 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
4062 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
4063 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
4064#ifdef CONFIG_WITH_EVALPLUS
4065 { STRING_SIZE_TUPLE("evalctx"), 0, 1, 1, func_evalctx},
4066 { STRING_SIZE_TUPLE("evalval"), 1, 1, 1, func_evalval},
4067 { STRING_SIZE_TUPLE("evalvalctx"), 1, 1, 1, func_evalval},
4068 { STRING_SIZE_TUPLE("evalcall"), 1, 0, 1, func_call},
4069 { STRING_SIZE_TUPLE("evalcall2"), 1, 0, 1, func_call},
4070#endif
4071#ifdef EXPERIMENTAL
4072 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
4073 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
4074#endif
4075#ifdef CONFIG_WITH_DEFINED
4076 { STRING_SIZE_TUPLE("defined"), 1, 1, 1, func_defined},
4077#endif
4078#ifdef CONFIG_WITH_TOUPPER_TOLOWER
4079 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower},
4080 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower},
4081#endif
4082#ifdef CONFIG_WITH_ABSPATHEX
4083 { STRING_SIZE_TUPLE("abspathex"), 0, 2, 1, func_abspathex},
4084#endif
4085#ifdef CONFIG_WITH_XARGS
4086 { STRING_SIZE_TUPLE("xargs"), 2, 0, 1, func_xargs},
4087#endif
4088#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
4089 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars},
4090 { STRING_SIZE_TUPLE("comp-cmds"), 3, 3, 1, func_comp_vars},
4091 { STRING_SIZE_TUPLE("comp-cmds-ex"), 3, 3, 1, func_comp_cmds_ex},
4092#endif
4093#ifdef CONFIG_WITH_DATE
4094 { STRING_SIZE_TUPLE("date"), 0, 1, 1, func_date},
4095 { STRING_SIZE_TUPLE("date-utc"), 0, 3, 1, func_date},
4096#endif
4097#ifdef CONFIG_WITH_FILE_SIZE
4098 { STRING_SIZE_TUPLE("file-size"), 1, 1, 1, func_file_size},
4099#endif
4100#ifdef CONFIG_WITH_WHICH
4101 { STRING_SIZE_TUPLE("which"), 0, 0, 1, func_which},
4102#endif
4103#ifdef CONFIG_WITH_IF_CONDITIONALS
4104 { STRING_SIZE_TUPLE("expr"), 1, 1, 0, func_expr},
4105 { STRING_SIZE_TUPLE("if-expr"), 2, 3, 0, func_if_expr},
4106#endif
4107#ifdef CONFIG_WITH_STACK
4108 { STRING_SIZE_TUPLE("stack-push"), 2, 2, 1, func_stack_push},
4109 { STRING_SIZE_TUPLE("stack-pop"), 1, 1, 1, func_stack_pop_top},
4110 { STRING_SIZE_TUPLE("stack-popv"), 1, 1, 1, func_stack_pop_top},
4111 { STRING_SIZE_TUPLE("stack-top"), 1, 1, 1, func_stack_pop_top},
4112#endif
4113#ifdef CONFIG_WITH_MATH
4114 { STRING_SIZE_TUPLE("int-add"), 2, 0, 1, func_int_add},
4115 { STRING_SIZE_TUPLE("int-sub"), 2, 0, 1, func_int_sub},
4116 { STRING_SIZE_TUPLE("int-mul"), 2, 0, 1, func_int_mul},
4117 { STRING_SIZE_TUPLE("int-div"), 2, 0, 1, func_int_div},
4118 { STRING_SIZE_TUPLE("int-mod"), 2, 2, 1, func_int_mod},
4119 { STRING_SIZE_TUPLE("int-not"), 1, 1, 1, func_int_not},
4120 { STRING_SIZE_TUPLE("int-and"), 2, 0, 1, func_int_and},
4121 { STRING_SIZE_TUPLE("int-or"), 2, 0, 1, func_int_or},
4122 { STRING_SIZE_TUPLE("int-xor"), 2, 0, 1, func_int_xor},
4123 { STRING_SIZE_TUPLE("int-eq"), 2, 2, 1, func_int_cmp},
4124 { STRING_SIZE_TUPLE("int-ne"), 2, 2, 1, func_int_cmp},
4125 { STRING_SIZE_TUPLE("int-gt"), 2, 2, 1, func_int_cmp},
4126 { STRING_SIZE_TUPLE("int-ge"), 2, 2, 1, func_int_cmp},
4127 { STRING_SIZE_TUPLE("int-lt"), 2, 2, 1, func_int_cmp},
4128 { STRING_SIZE_TUPLE("int-le"), 2, 2, 1, func_int_cmp},
4129#endif
4130#ifdef CONFIG_WITH_NANOTS
4131 { STRING_SIZE_TUPLE("nanots"), 0, 0, 0, func_nanots},
4132#endif
4133#ifdef CONFIG_WITH_OS2_LIBPATH
4134 { STRING_SIZE_TUPLE("libpath"), 1, 2, 1, func_os2_libpath},
4135#endif
4136#ifdef CONFIG_WITH_MAKE_STATS
4137 { STRING_SIZE_TUPLE("make-stats"), 0, 0, 0, func_make_stats},
4138#endif
4139#ifdef CONFIG_WITH_COMMANDS_FUNC
4140 { STRING_SIZE_TUPLE("commands"), 1, 1, 1, func_commands},
4141 { STRING_SIZE_TUPLE("commands-sc"), 1, 1, 1, func_commands},
4142 { STRING_SIZE_TUPLE("commands-usr"), 2, 2, 1, func_commands},
4143#endif
4144#ifdef KMK_HELPERS
4145 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool},
4146 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base},
4147 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix},
4148 { STRING_SIZE_TUPLE("kb-src-prop"), 3, 4, 0, func_kbuild_source_prop},
4149 { STRING_SIZE_TUPLE("kb-src-one"), 0, 1, 0, func_kbuild_source_one},
4150#endif
4151#ifdef KMK
4152 { STRING_SIZE_TUPLE("breakpoint"), 0, 0, 0, func_breakpoint},
4153#endif
4154};
4155
4156#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
4157
4158
4159
4160/* These must come after the definition of function_table. */
4161
4162static char *
4163expand_builtin_function (char *o, int argc, char **argv,
4164 const struct function_table_entry *entry_p)
4165{
4166 if (argc < (int)entry_p->minimum_args)
4167 fatal (*expanding_var,
4168 _("insufficient number of arguments (%d) to function `%s'"),
4169 argc, entry_p->name);
4170
4171 /* I suppose technically some function could do something with no
4172 arguments, but so far none do, so just test it for all functions here
4173 rather than in each one. We can change it later if necessary. */
4174
4175 if (!argc)
4176 return o;
4177
4178 if (!entry_p->func_ptr)
4179 fatal (*expanding_var,
4180 _("unimplemented on this platform: function `%s'"), entry_p->name);
4181
4182 return entry_p->func_ptr (o, argv, entry_p->name);
4183}
4184
4185/* Check for a function invocation in *STRINGP. *STRINGP points at the
4186 opening ( or { and is not null-terminated. If a function invocation
4187 is found, expand it into the buffer at *OP, updating *OP, incrementing
4188 *STRINGP past the reference and returning nonzero. If not, return zero. */
4189
4190static int
4191handle_function2 (const struct function_table_entry *entry_p, char **op, const char **stringp) /* bird split it up. */
4192{
4193 char openparen = (*stringp)[0];
4194 char closeparen = openparen == '(' ? ')' : '}';
4195 const char *beg;
4196 const char *end;
4197 int count = 0;
4198 char *abeg = NULL;
4199 char **argv, **argvp;
4200 int nargs;
4201
4202 beg = *stringp + 1;
4203
4204 /* We found a builtin function. Find the beginning of its arguments (skip
4205 whitespace after the name). */
4206
4207 beg = next_token (beg + entry_p->len);
4208
4209 /* Find the end of the function invocation, counting nested use of
4210 whichever kind of parens we use. Since we're looking, count commas
4211 to get a rough estimate of how many arguments we might have. The
4212 count might be high, but it'll never be low. */
4213
4214 for (nargs=1, end=beg; *end != '\0'; ++end)
4215 if (*end == ',')
4216 ++nargs;
4217 else if (*end == openparen)
4218 ++count;
4219 else if (*end == closeparen && --count < 0)
4220 break;
4221
4222 if (count >= 0)
4223 fatal (*expanding_var,
4224 _("unterminated call to function `%s': missing `%c'"),
4225 entry_p->name, closeparen);
4226
4227 *stringp = end;
4228
4229 /* Get some memory to store the arg pointers. */
4230 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
4231
4232 /* Chop the string into arguments, then a nul. As soon as we hit
4233 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
4234 last argument.
4235
4236 If we're expanding, store pointers to the expansion of each one. If
4237 not, make a duplicate of the string and point into that, nul-terminating
4238 each argument. */
4239
4240 if (entry_p->expand_args)
4241 {
4242 const char *p;
4243 for (p=beg, nargs=0; p <= end; ++argvp)
4244 {
4245 const char *next;
4246
4247 ++nargs;
4248
4249 if (nargs == entry_p->maximum_args
4250 || (! (next = find_next_argument (openparen, closeparen, p, end))))
4251 next = end;
4252
4253 *argvp = expand_argument (p, next);
4254 p = next + 1;
4255 }
4256 }
4257 else
4258 {
4259 int len = end - beg;
4260 char *p, *aend;
4261
4262 abeg = xmalloc (len+1);
4263 memcpy (abeg, beg, len);
4264 abeg[len] = '\0';
4265 aend = abeg + len;
4266
4267 for (p=abeg, nargs=0; p <= aend; ++argvp)
4268 {
4269 char *next;
4270
4271 ++nargs;
4272
4273 if (nargs == entry_p->maximum_args
4274 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
4275 next = aend;
4276
4277 *argvp = p;
4278 *next = '\0';
4279 p = next + 1;
4280 }
4281 }
4282 *argvp = NULL;
4283
4284 /* Finally! Run the function... */
4285 *op = expand_builtin_function (*op, nargs, argv, entry_p);
4286
4287 /* Free memory. */
4288 if (entry_p->expand_args)
4289 for (argvp=argv; *argvp != 0; ++argvp)
4290 free (*argvp);
4291 if (abeg)
4292 free (abeg);
4293
4294 return 1;
4295}
4296
4297
4298int /* bird split it up */
4299#ifndef CONFIG_WITH_VALUE_LENGTH
4300handle_function (char **op, const char **stringp)
4301{
4302 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
4303 if (!entry_p)
4304 return 0;
4305 return handle_function2 (entry_p, op, stringp);
4306}
4307#else /* CONFIG_WITH_VALUE_LENGTH */
4308handle_function (char **op, const char **stringp, const char *eol)
4309{
4310 const char *fname = *stringp + 1;
4311 const struct function_table_entry *entry_p = lookup_function (fname, eol - fname);
4312 if (!entry_p)
4313 return 0;
4314 return handle_function2 (entry_p, op, stringp);
4315}
4316#endif /* CONFIG_WITH_VALUE_LENGTH */
4317
4318
4319
4320/* User-defined functions. Expand the first argument as either a builtin
4321 function or a make variable, in the context of the rest of the arguments
4322 assigned to $1, $2, ... $N. $0 is the name of the function. */
4323
4324static char *
4325func_call (char *o, char **argv, const char *funcname UNUSED)
4326{
4327 static int max_args = 0;
4328 char *fname;
4329 char *cp;
4330 char *body;
4331 int flen;
4332 int i;
4333 int saved_args;
4334 const struct function_table_entry *entry_p;
4335 struct variable *v;
4336#ifdef CONFIG_WITH_EVALPLUS
4337 char *buf;
4338 unsigned int len;
4339#endif
4340
4341 /* There is no way to define a variable with a space in the name, so strip
4342 leading and trailing whitespace as a favor to the user. */
4343 fname = argv[0];
4344 while (*fname != '\0' && isspace ((unsigned char)*fname))
4345 ++fname;
4346
4347 cp = fname + strlen (fname) - 1;
4348 while (cp > fname && isspace ((unsigned char)*cp))
4349 --cp;
4350 cp[1] = '\0';
4351
4352 /* Calling nothing is a no-op */
4353 if (*fname == '\0')
4354 return o;
4355
4356 /* Are we invoking a builtin function? */
4357
4358#ifndef CONFIG_WITH_VALUE_LENGTH
4359 entry_p = lookup_function (fname);
4360#else
4361 entry_p = lookup_function (fname, cp - fname + 1);
4362#endif
4363 if (entry_p)
4364 {
4365 /* How many arguments do we have? */
4366 for (i=0; argv[i+1]; ++i)
4367 ;
4368 return expand_builtin_function (o, i, argv+1, entry_p);
4369 }
4370
4371 /* Not a builtin, so the first argument is the name of a variable to be
4372 expanded and interpreted as a function. Find it. */
4373 flen = strlen (fname);
4374
4375 v = lookup_variable (fname, flen);
4376
4377 if (v == 0)
4378 warn_undefined (fname, flen);
4379
4380 if (v == 0 || *v->value == '\0')
4381 return o;
4382
4383 body = alloca (flen + 4);
4384 body[0] = '$';
4385 body[1] = '(';
4386 memcpy (body + 2, fname, flen);
4387 body[flen+2] = ')';
4388 body[flen+3] = '\0';
4389
4390 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
4391
4392 push_new_variable_scope ();
4393
4394 for (i=0; *argv; ++i, ++argv)
4395 {
4396 char num[11];
4397
4398 sprintf (num, "%d", i);
4399 define_variable (num, strlen (num), *argv, o_automatic, 0);
4400 }
4401
4402 /* If the number of arguments we have is < max_args, it means we're inside
4403 a recursive invocation of $(call ...). Fill in the remaining arguments
4404 in the new scope with the empty value, to hide them from this
4405 invocation. */
4406
4407 for (; i < max_args; ++i)
4408 {
4409 char num[11];
4410
4411#ifndef CONFIG_WITH_VALUE_LENGTH
4412 sprintf (num, "%d", i);
4413 define_variable (num, strlen (num), "", o_automatic, 0);
4414#else
4415 define_variable (num, sprintf (num, "%d", i), "", o_automatic, 0);
4416#endif
4417 }
4418
4419 saved_args = max_args;
4420 max_args = i;
4421
4422#ifdef CONFIG_WITH_EVALPLUS
4423 if (!strcmp (funcname, "call"))
4424 {
4425#endif
4426 /* Expand the body in the context of the arguments, adding the result to
4427 the variable buffer. */
4428
4429 v->exp_count = EXP_COUNT_MAX;
4430#ifndef CONFIG_WITH_VALUE_LENGTH
4431 o = variable_expand_string (o, body, flen+3);
4432 v->exp_count = 0;
4433
4434 o += strlen (o);
4435#else /* CONFIG_WITH_VALUE_LENGTH */
4436 variable_expand_string_2 (o, body, flen+3, &o);
4437 v->exp_count = 0;
4438#endif /* CONFIG_WITH_VALUE_LENGTH */
4439#ifdef CONFIG_WITH_EVALPLUS
4440 }
4441 else
4442 {
4443 const struct floc *reading_file_saved = reading_file;
4444 char *eos;
4445
4446 if (!strcmp (funcname, "evalcall"))
4447 {
4448 /* Evaluate the variable value without expanding it. We
4449 need a copy since eval_buffer is destructive. */
4450
4451 size_t off = o - variable_buffer;
4452 eos = variable_buffer_output (o, v->value, v->value_length + 1) - 1;
4453 o = variable_buffer + off;
4454 if (v->fileinfo.filenm)
4455 reading_file = &v->fileinfo;
4456 }
4457 else
4458 {
4459 /* Expand the body first and then evaluate the output. */
4460
4461 v->exp_count = EXP_COUNT_MAX;
4462 o = variable_expand_string_2 (o, body, flen+3, &eos);
4463 v->exp_count = 0;
4464 }
4465
4466 install_variable_buffer (&buf, &len);
4467 eval_buffer (o, eos);
4468 restore_variable_buffer (buf, len);
4469 reading_file = reading_file_saved;
4470 }
4471#endif /* CONFIG_WITH_EVALPLUS */
4472
4473 max_args = saved_args;
4474
4475 pop_variable_scope ();
4476
4477 return o;
4478}
4479
4480void
4481hash_init_function_table (void)
4482{
4483 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
4484 function_table_entry_hash_1, function_table_entry_hash_2,
4485 function_table_entry_hash_cmp);
4486 hash_load (&function_table, function_table_init,
4487 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
4488#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
4489 {
4490 unsigned int i;
4491 for (i = 'a'; i <= 'z'; i++)
4492 func_char_map[i] = 1;
4493 func_char_map[(unsigned int)'-'] = 1;
4494
4495 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
4496 {
4497 assert (function_table_init[i].len <= MAX_FUNCTION_LENGTH);
4498 assert (function_table_init[i].len >= MIN_FUNCTION_LENGTH);
4499 }
4500 }
4501#endif
4502}
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette