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

Last change on this file since 2490 was 2489, checked in by bird, 14 years ago

kmk: added $(firstdefined ) and $(lastdefined ).

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