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

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

kmk: Extended evalcall and evalcall2 with a return value, local .RETURN.

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