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

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

kmk: Inlined much of handle_function/lookup_function so variable_expand_string_2 can avoid having to make the call for every variable it encounters. Also fixed the func_char_map generation.

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