VirtualBox

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

Last change on this file since 990 was 990, checked in by bird, 18 years ago

it's 100ns units, not 10000.

  • Property svn:eol-style set to native
File size: 87.0 KB
Line 
1/* Builtin function expansion for GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software
4Foundation, Inc.
5This file is part of GNU Make.
6
7GNU Make is free software; you can redistribute it and/or modify it under the
8terms of the GNU General Public License as published by the Free Software
9Foundation; either version 2, or (at your option) any later version.
10
11GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
12WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License along with
16GNU Make; see the file COPYING. If not, write to the Free Software
17Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */
18
19#include "make.h"
20#include "filedef.h"
21#include "variable.h"
22#include "dep.h"
23#include "job.h"
24#include "commands.h"
25#include "debug.h"
26
27#ifdef _AMIGA
28#include "amiga.h"
29#endif
30
31#ifdef WINDOWS32 /* bird */
32# include "pathstuff.h"
33#endif
34
35#ifdef KMK_HELPERS
36# include "kbuild.h"
37#endif
38#ifdef CONFIG_WITH_XARGS /* bird */
39# ifdef HAVE_LIMITS_H
40# include <limits.h>
41# endif
42#endif
43#include <assert.h> /* bird */
44
45#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) /* bird */
46# include <ctype.h>
47# ifdef _MSC_VER
48typedef __int64 math_int;
49# else
50# include <stdint.h>
51typedef int64_t math_int;
52# endif
53#endif
54
55#ifdef CONFIG_WITH_NANOTS /* bird */
56# ifdef WINDOWS32
57# include <Windows.h>
58# endif
59#endif
60
61
62struct function_table_entry
63 {
64 const char *name;
65 unsigned char len;
66 unsigned char minimum_args;
67 unsigned char maximum_args;
68 char expand_args;
69 char *(*func_ptr) (char *output, char **argv, const char *fname);
70 };
71
72static unsigned long
73function_table_entry_hash_1 (const void *keyv)
74{
75 const struct function_table_entry *key = keyv;
76 return_STRING_N_HASH_1 (key->name, key->len);
77}
78
79static unsigned long
80function_table_entry_hash_2 (const void *keyv)
81{
82 const struct function_table_entry *key = keyv;
83 return_STRING_N_HASH_2 (key->name, key->len);
84}
85
86static int
87function_table_entry_hash_cmp (const void *xv, const void *yv)
88{
89 const struct function_table_entry *x = xv;
90 const struct function_table_entry *y = yv;
91 int result = x->len - y->len;
92 if (result)
93 return result;
94 return_STRING_N_COMPARE (x->name, y->name, x->len);
95}
96
97static struct hash_table function_table;
98
99
100
101/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
102 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
103 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
104 nonzero, substitutions are done only on matches which are complete
105 whitespace-delimited words. */
106
107char *
108subst_expand (char *o, const char *text, const char *subst, const char *replace,
109 unsigned int slen, unsigned int rlen, int by_word)
110{
111 const char *t = text;
112 const char *p;
113
114 if (slen == 0 && !by_word)
115 {
116 /* The first occurrence of "" in any string is its end. */
117 o = variable_buffer_output (o, t, strlen (t));
118 if (rlen > 0)
119 o = variable_buffer_output (o, replace, rlen);
120 return o;
121 }
122
123 do
124 {
125 if (by_word && slen == 0)
126 /* When matching by words, the empty string should match
127 the end of each word, rather than the end of the whole text. */
128 p = end_of_token (next_token (t));
129 else
130 {
131 p = strstr (t, subst);
132 if (p == 0)
133 {
134 /* No more matches. Output everything left on the end. */
135 o = variable_buffer_output (o, t, strlen (t));
136 return o;
137 }
138 }
139
140 /* Output everything before this occurrence of the string to replace. */
141 if (p > t)
142 o = variable_buffer_output (o, t, p - t);
143
144 /* If we're substituting only by fully matched words,
145 or only at the ends of words, check that this case qualifies. */
146 if (by_word
147 && ((p > text && !isblank ((unsigned char)p[-1]))
148 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
149 /* Struck out. Output the rest of the string that is
150 no longer to be replaced. */
151 o = variable_buffer_output (o, subst, slen);
152 else if (rlen > 0)
153 /* Output the replacement string. */
154 o = variable_buffer_output (o, replace, rlen);
155
156 /* Advance T past the string to be replaced. */
157 t = p + slen;
158 } while (*t != '\0');
159
160 return o;
161}
162
163
164
165/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
166 and replacing strings matching PATTERN with REPLACE.
167 If PATTERN_PERCENT is not nil, PATTERN has already been
168 run through find_percent, and PATTERN_PERCENT is the result.
169 If REPLACE_PERCENT is not nil, REPLACE has already been
170 run through find_percent, and REPLACE_PERCENT is the result.
171 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
172 character _AFTER_ the %, not to the % itself.
173*/
174
175char *
176patsubst_expand_pat (char *o, const char *text,
177 const char *pattern, const char *replace,
178 const char *pattern_percent, const char *replace_percent)
179{
180 unsigned int pattern_prepercent_len, pattern_postpercent_len;
181 unsigned int replace_prepercent_len, replace_postpercent_len;
182 const char *t;
183 unsigned int len;
184 int doneany = 0;
185
186 /* Record the length of REPLACE before and after the % so we don't have to
187 compute these lengths more than once. */
188 if (replace_percent)
189 {
190 replace_prepercent_len = replace_percent - replace - 1;
191 replace_postpercent_len = strlen (replace_percent);
192 }
193 else
194 {
195 replace_prepercent_len = strlen (replace);
196 replace_postpercent_len = 0;
197 }
198
199 if (!pattern_percent)
200 /* With no % in the pattern, this is just a simple substitution. */
201 return subst_expand (o, text, pattern, replace,
202 strlen (pattern), strlen (replace), 1);
203
204 /* Record the length of PATTERN before and after the %
205 so we don't have to compute it more than once. */
206 pattern_prepercent_len = pattern_percent - pattern - 1;
207 pattern_postpercent_len = strlen (pattern_percent);
208
209 while ((t = find_next_token (&text, &len)) != 0)
210 {
211 int fail = 0;
212
213 /* Is it big enough to match? */
214 if (len < pattern_prepercent_len + pattern_postpercent_len)
215 fail = 1;
216
217 /* Does the prefix match? */
218 if (!fail && pattern_prepercent_len > 0
219 && (*t != *pattern
220 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
221 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
222 fail = 1;
223
224 /* Does the suffix match? */
225 if (!fail && pattern_postpercent_len > 0
226 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
227 || t[len - pattern_postpercent_len] != *pattern_percent
228 || !strneq (&t[len - pattern_postpercent_len],
229 pattern_percent, pattern_postpercent_len - 1)))
230 fail = 1;
231
232 if (fail)
233 /* It didn't match. Output the string. */
234 o = variable_buffer_output (o, t, len);
235 else
236 {
237 /* It matched. Output the replacement. */
238
239 /* Output the part of the replacement before the %. */
240 o = variable_buffer_output (o, replace, replace_prepercent_len);
241
242 if (replace_percent != 0)
243 {
244 /* Output the part of the matched string that
245 matched the % in the pattern. */
246 o = variable_buffer_output (o, t + pattern_prepercent_len,
247 len - (pattern_prepercent_len
248 + pattern_postpercent_len));
249 /* Output the part of the replacement after the %. */
250 o = variable_buffer_output (o, replace_percent,
251 replace_postpercent_len);
252 }
253 }
254
255 /* Output a space, but not if the replacement is "". */
256 if (fail || replace_prepercent_len > 0
257 || (replace_percent != 0 && len + replace_postpercent_len > 0))
258 {
259 o = variable_buffer_output (o, " ", 1);
260 doneany = 1;
261 }
262 }
263 if (doneany)
264 /* Kill the last space. */
265 --o;
266
267 return o;
268}
269
270/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
271 and replacing strings matching PATTERN with REPLACE.
272 If PATTERN_PERCENT is not nil, PATTERN has already been
273 run through find_percent, and PATTERN_PERCENT is the result.
274 If REPLACE_PERCENT is not nil, REPLACE has already been
275 run through find_percent, and REPLACE_PERCENT is the result.
276 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
277 character _AFTER_ the %, not to the % itself.
278*/
279
280char *
281patsubst_expand (char *o, const char *text, char *pattern, char *replace)
282{
283 const char *pattern_percent = find_percent (pattern);
284 const char *replace_percent = find_percent (replace);
285
286 /* If there's a percent in the pattern or replacement skip it. */
287 if (replace_percent)
288 ++replace_percent;
289 if (pattern_percent)
290 ++pattern_percent;
291
292 return patsubst_expand_pat (o, text, pattern, replace,
293 pattern_percent, replace_percent);
294}
295
296
297#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
298/* The maximum length of a function, once reached there is
299 it can't be function and we can skip the hash lookup drop out. */
300
301# ifdef KMK
302# define MAX_FUNCTION_LENGTH 12
303# else
304# define MAX_FUNCTION_LENGTH 10
305# endif
306#endif /* CONFIG_WITH_OPTIMIZATION_HACKS */
307
308/* Look up a function by name. */
309
310#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
311__inline
312#endif /* CONFIG_WITH_OPTIMIZATION_HACKS */
313static const struct function_table_entry *
314lookup_function (const char *s)
315{
316 const char *e = s;
317#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
318 int left = MAX_FUNCTION_LENGTH;
319 int ch;
320 while (((ch = *e) >= 'a' && ch <='z') || ch == '-')
321 {
322 if (!left--)
323 return 0;
324 e++;
325 }
326#else
327 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
328 e++;
329#endif
330 if (*e == '\0' || isblank ((unsigned char) *e))
331 {
332 struct function_table_entry function_table_entry_key;
333 function_table_entry_key.name = s;
334 function_table_entry_key.len = e - s;
335
336 return hash_find_item (&function_table, &function_table_entry_key);
337 }
338 return 0;
339}
340
341
342
343/* Return 1 if PATTERN matches STR, 0 if not. */
344
345int
346pattern_matches (const char *pattern, const char *percent, const char *str)
347{
348 unsigned int sfxlen, strlength;
349
350 if (percent == 0)
351 {
352 unsigned int len = strlen (pattern) + 1;
353 char *new_chars = alloca (len);
354 memcpy (new_chars, pattern, len);
355 percent = find_percent (new_chars);
356 if (percent == 0)
357 return streq (new_chars, str);
358 pattern = new_chars;
359 }
360
361 sfxlen = strlen (percent + 1);
362 strlength = strlen (str);
363
364 if (strlength < (percent - pattern) + sfxlen
365 || !strneq (pattern, str, percent - pattern))
366 return 0;
367
368 return !strcmp (percent + 1, str + (strlength - sfxlen));
369}
370
371
372
373/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
374 ENDPARENtheses), starting at PTR before END. Return a pointer to
375 next character.
376
377 If no next argument is found, return NULL.
378*/
379
380static char *
381find_next_argument (char startparen, char endparen,
382 const char *ptr, const char *end)
383{
384 int count = 0;
385
386 for (; ptr < end; ++ptr)
387 if (*ptr == startparen)
388 ++count;
389
390 else if (*ptr == endparen)
391 {
392 --count;
393 if (count < 0)
394 return NULL;
395 }
396
397 else if (*ptr == ',' && !count)
398 return (char *)ptr;
399
400 /* We didn't find anything. */
401 return NULL;
402}
403
404
405
406/* Glob-expand LINE. The returned pointer is
407 only good until the next call to string_glob. */
408
409static char *
410string_glob (char *line)
411{
412 static char *result = 0;
413 static unsigned int length;
414 struct nameseq *chain;
415 unsigned int idx;
416
417 chain = multi_glob (parse_file_seq
418 (&line, '\0', sizeof (struct nameseq),
419 /* We do not want parse_file_seq to strip `./'s.
420 That would break examples like:
421 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
422 0),
423 sizeof (struct nameseq));
424
425 if (result == 0)
426 {
427 length = 100;
428 result = xmalloc (100);
429 }
430
431 idx = 0;
432 while (chain != 0)
433 {
434 const char *name = chain->name;
435 unsigned int len = strlen (name);
436
437 struct nameseq *next = chain->next;
438 free (chain);
439 chain = next;
440
441 /* multi_glob will pass names without globbing metacharacters
442 through as is, but we want only files that actually exist. */
443 if (file_exists_p (name))
444 {
445 if (idx + len + 1 > length)
446 {
447 length += (len + 1) * 2;
448 result = xrealloc (result, length);
449 }
450 memcpy (&result[idx], name, len);
451 idx += len;
452 result[idx++] = ' ';
453 }
454 }
455
456 /* Kill the last space and terminate the string. */
457 if (idx == 0)
458 result[0] = '\0';
459 else
460 result[idx - 1] = '\0';
461
462 return result;
463}
464
465
466/*
467 Builtin functions
468 */
469
470static char *
471func_patsubst (char *o, char **argv, const char *funcname UNUSED)
472{
473 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
474 return o;
475}
476
477
478static char *
479func_join (char *o, char **argv, const char *funcname UNUSED)
480{
481 int doneany = 0;
482
483 /* Write each word of the first argument directly followed
484 by the corresponding word of the second argument.
485 If the two arguments have a different number of words,
486 the excess words are just output separated by blanks. */
487 const char *tp;
488 const char *pp;
489 const char *list1_iterator = argv[0];
490 const char *list2_iterator = argv[1];
491 do
492 {
493 unsigned int len1, len2;
494
495 tp = find_next_token (&list1_iterator, &len1);
496 if (tp != 0)
497 o = variable_buffer_output (o, tp, len1);
498
499 pp = find_next_token (&list2_iterator, &len2);
500 if (pp != 0)
501 o = variable_buffer_output (o, pp, len2);
502
503 if (tp != 0 || pp != 0)
504 {
505 o = variable_buffer_output (o, " ", 1);
506 doneany = 1;
507 }
508 }
509 while (tp != 0 || pp != 0);
510 if (doneany)
511 /* Kill the last blank. */
512 --o;
513
514 return o;
515}
516
517
518static char *
519func_origin (char *o, char **argv, const char *funcname UNUSED)
520{
521 /* Expand the argument. */
522 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
523 if (v == 0)
524 o = variable_buffer_output (o, "undefined", 9);
525 else
526 switch (v->origin)
527 {
528 default:
529 case o_invalid:
530 abort ();
531 break;
532 case o_default:
533 o = variable_buffer_output (o, "default", 7);
534 break;
535 case o_env:
536 o = variable_buffer_output (o, "environment", 11);
537 break;
538 case o_file:
539 o = variable_buffer_output (o, "file", 4);
540 break;
541 case o_env_override:
542 o = variable_buffer_output (o, "environment override", 20);
543 break;
544 case o_command:
545 o = variable_buffer_output (o, "command line", 12);
546 break;
547 case o_override:
548 o = variable_buffer_output (o, "override", 8);
549 break;
550 case o_automatic:
551 o = variable_buffer_output (o, "automatic", 9);
552 break;
553 }
554
555 return o;
556}
557
558static char *
559func_flavor (char *o, char **argv, const char *funcname UNUSED)
560{
561 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
562
563 if (v == 0)
564 o = variable_buffer_output (o, "undefined", 9);
565 else
566 if (v->recursive)
567 o = variable_buffer_output (o, "recursive", 9);
568 else
569 o = variable_buffer_output (o, "simple", 6);
570
571 return o;
572}
573
574#ifdef VMS
575# define IS_PATHSEP(c) ((c) == ']')
576#else
577# ifdef HAVE_DOS_PATHS
578# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
579# else
580# define IS_PATHSEP(c) ((c) == '/')
581# endif
582#endif
583
584
585static char *
586func_notdir_suffix (char *o, char **argv, const char *funcname)
587{
588 /* Expand the argument. */
589 const char *list_iterator = argv[0];
590 const char *p2;
591 int doneany =0;
592 unsigned int len=0;
593
594 int is_suffix = streq (funcname, "suffix");
595 int is_notdir = !is_suffix;
596 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
597 {
598 const char *p = p2 + len;
599
600
601 while (p >= p2 && (!is_suffix || *p != '.'))
602 {
603 if (IS_PATHSEP (*p))
604 break;
605 --p;
606 }
607
608 if (p >= p2)
609 {
610 if (is_notdir)
611 ++p;
612 else if (*p != '.')
613 continue;
614 o = variable_buffer_output (o, p, len - (p - p2));
615 }
616#ifdef HAVE_DOS_PATHS
617 /* Handle the case of "d:foo/bar". */
618 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
619 {
620 p = p2 + 2;
621 o = variable_buffer_output (o, p, len - (p - p2));
622 }
623#endif
624 else if (is_notdir)
625 o = variable_buffer_output (o, p2, len);
626
627 if (is_notdir || p >= p2)
628 {
629 o = variable_buffer_output (o, " ", 1);
630 doneany = 1;
631 }
632 }
633
634 if (doneany)
635 /* Kill last space. */
636 --o;
637
638 return o;
639}
640
641
642static char *
643func_basename_dir (char *o, char **argv, const char *funcname)
644{
645 /* Expand the argument. */
646 const char *p3 = argv[0];
647 const char *p2;
648 int doneany=0;
649 unsigned int len=0;
650
651 int is_basename= streq (funcname, "basename");
652 int is_dir= !is_basename;
653
654 while ((p2 = find_next_token (&p3, &len)) != 0)
655 {
656 const char *p = p2 + len;
657 while (p >= p2 && (!is_basename || *p != '.'))
658 {
659 if (IS_PATHSEP (*p))
660 break;
661 --p;
662 }
663
664 if (p >= p2 && (is_dir))
665 o = variable_buffer_output (o, p2, ++p - p2);
666 else if (p >= p2 && (*p == '.'))
667 o = variable_buffer_output (o, p2, p - p2);
668#ifdef HAVE_DOS_PATHS
669 /* Handle the "d:foobar" case */
670 else if (p2[0] && p2[1] == ':' && is_dir)
671 o = variable_buffer_output (o, p2, 2);
672#endif
673 else if (is_dir)
674#ifdef VMS
675 o = variable_buffer_output (o, "[]", 2);
676#else
677#ifndef _AMIGA
678 o = variable_buffer_output (o, "./", 2);
679#else
680 ; /* Just a nop... */
681#endif /* AMIGA */
682#endif /* !VMS */
683 else
684 /* The entire name is the basename. */
685 o = variable_buffer_output (o, p2, len);
686
687 o = variable_buffer_output (o, " ", 1);
688 doneany = 1;
689 }
690
691 if (doneany)
692 /* Kill last space. */
693 --o;
694
695 return o;
696}
697
698static char *
699func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
700{
701 int fixlen = strlen (argv[0]);
702 const char *list_iterator = argv[1];
703 int is_addprefix = streq (funcname, "addprefix");
704 int is_addsuffix = !is_addprefix;
705
706 int doneany = 0;
707 const char *p;
708 unsigned int len;
709
710 while ((p = find_next_token (&list_iterator, &len)) != 0)
711 {
712 if (is_addprefix)
713 o = variable_buffer_output (o, argv[0], fixlen);
714 o = variable_buffer_output (o, p, len);
715 if (is_addsuffix)
716 o = variable_buffer_output (o, argv[0], fixlen);
717 o = variable_buffer_output (o, " ", 1);
718 doneany = 1;
719 }
720
721 if (doneany)
722 /* Kill last space. */
723 --o;
724
725 return o;
726}
727
728static char *
729func_subst (char *o, char **argv, const char *funcname UNUSED)
730{
731 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
732 strlen (argv[1]), 0);
733
734 return o;
735}
736
737
738static char *
739func_firstword (char *o, char **argv, const char *funcname UNUSED)
740{
741 unsigned int i;
742 const char *words = argv[0]; /* Use a temp variable for find_next_token */
743 const char *p = find_next_token (&words, &i);
744
745 if (p != 0)
746 o = variable_buffer_output (o, p, i);
747
748 return o;
749}
750
751static char *
752func_lastword (char *o, char **argv, const char *funcname UNUSED)
753{
754 unsigned int i;
755 const char *words = argv[0]; /* Use a temp variable for find_next_token */
756 const char *p = NULL;
757 const char *t;
758
759 while ((t = find_next_token (&words, &i)))
760 p = t;
761
762 if (p != 0)
763 o = variable_buffer_output (o, p, i);
764
765 return o;
766}
767
768static char *
769func_words (char *o, char **argv, const char *funcname UNUSED)
770{
771 int i = 0;
772 const char *word_iterator = argv[0];
773 char buf[20];
774
775 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
776 ++i;
777
778 sprintf (buf, "%d", i);
779 o = variable_buffer_output (o, buf, strlen (buf));
780
781 return o;
782}
783
784/* Set begpp to point to the first non-whitespace character of the string,
785 * and endpp to point to the last non-whitespace character of the string.
786 * If the string is empty or contains nothing but whitespace, endpp will be
787 * begpp-1.
788 */
789char *
790strip_whitespace (const char **begpp, const char **endpp)
791{
792 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
793 (*begpp) ++;
794 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
795 (*endpp) --;
796 return (char *)*begpp;
797}
798
799static void
800check_numeric (const char *s, const char *msg)
801{
802 const char *end = s + strlen (s) - 1;
803 const char *beg = s;
804 strip_whitespace (&s, &end);
805
806 for (; s <= end; ++s)
807 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
808 break;
809
810 if (s <= end || end - beg < 0)
811 fatal (*expanding_var, "%s: '%s'", msg, beg);
812}
813
814
815
816static char *
817func_word (char *o, char **argv, const char *funcname UNUSED)
818{
819 const char *end_p;
820 const char *p;
821 int i;
822
823 /* Check the first argument. */
824 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
825 i = atoi (argv[0]);
826
827 if (i == 0)
828 fatal (*expanding_var,
829 _("first argument to `word' function must be greater than 0"));
830
831 end_p = argv[1];
832 while ((p = find_next_token (&end_p, 0)) != 0)
833 if (--i == 0)
834 break;
835
836 if (i == 0)
837 o = variable_buffer_output (o, p, end_p - p);
838
839 return o;
840}
841
842static char *
843func_wordlist (char *o, char **argv, const char *funcname UNUSED)
844{
845 int start, count;
846
847 /* Check the arguments. */
848 check_numeric (argv[0],
849 _("non-numeric first argument to `wordlist' function"));
850 check_numeric (argv[1],
851 _("non-numeric second argument to `wordlist' function"));
852
853 start = atoi (argv[0]);
854 if (start < 1)
855 fatal (*expanding_var,
856 "invalid first argument to `wordlist' function: `%d'", start);
857
858 count = atoi (argv[1]) - start + 1;
859
860 if (count > 0)
861 {
862 const char *p;
863 const char *end_p = argv[2];
864
865 /* Find the beginning of the "start"th word. */
866 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
867 ;
868
869 if (p)
870 {
871 /* Find the end of the "count"th word from start. */
872 while (--count && (find_next_token (&end_p, 0) != 0))
873 ;
874
875 /* Return the stuff in the middle. */
876 o = variable_buffer_output (o, p, end_p - p);
877 }
878 }
879
880 return o;
881}
882
883static char *
884func_findstring (char *o, char **argv, const char *funcname UNUSED)
885{
886 /* Find the first occurrence of the first string in the second. */
887 if (strstr (argv[1], argv[0]) != 0)
888 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
889
890 return o;
891}
892
893static char *
894func_foreach (char *o, char **argv, const char *funcname UNUSED)
895{
896 /* expand only the first two. */
897 char *varname = expand_argument (argv[0], NULL);
898 char *list = expand_argument (argv[1], NULL);
899 const char *body = argv[2];
900
901 int doneany = 0;
902 const char *list_iterator = list;
903 const char *p;
904 unsigned int len;
905 struct variable *var;
906
907 push_new_variable_scope ();
908 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
909
910 /* loop through LIST, put the value in VAR and expand BODY */
911 while ((p = find_next_token (&list_iterator, &len)) != 0)
912 {
913 char *result = 0;
914#ifdef CONFIG_WITH_VALUE_LENGTH
915 if (len >= (unsigned int)var->value_alloc_len)
916 {
917 free (var->value);
918 var->value_alloc_len = (len + 32) & ~31;
919 var->value = xmalloc (var->value_alloc_len);
920 }
921 memcpy (var->value, p, len);
922 var->value[len] = '\0';
923 var->value_length = len;
924#else
925 free (var->value);
926 var->value = savestring (p, len);
927#endif
928
929 result = allocated_variable_expand (body);
930
931 o = variable_buffer_output (o, result, strlen (result));
932 o = variable_buffer_output (o, " ", 1);
933 doneany = 1;
934 free (result);
935 }
936
937 if (doneany)
938 /* Kill the last space. */
939 --o;
940
941 pop_variable_scope ();
942 free (varname);
943 free (list);
944
945 return o;
946}
947
948struct a_word
949{
950 struct a_word *next;
951 struct a_word *chain;
952 char *str;
953 int length;
954 int matched;
955};
956
957static unsigned long
958a_word_hash_1 (const void *key)
959{
960 return_STRING_HASH_1 (((struct a_word const *) key)->str);
961}
962
963static unsigned long
964a_word_hash_2 (const void *key)
965{
966 return_STRING_HASH_2 (((struct a_word const *) key)->str);
967}
968
969static int
970a_word_hash_cmp (const void *x, const void *y)
971{
972 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
973 if (result)
974 return result;
975 return_STRING_COMPARE (((struct a_word const *) x)->str,
976 ((struct a_word const *) y)->str);
977}
978
979struct a_pattern
980{
981 struct a_pattern *next;
982 char *str;
983 char *percent;
984 int length;
985 int save_c;
986};
987
988static char *
989func_filter_filterout (char *o, char **argv, const char *funcname)
990{
991 struct a_word *wordhead;
992 struct a_word **wordtail;
993 struct a_word *wp;
994 struct a_pattern *pathead;
995 struct a_pattern **pattail;
996 struct a_pattern *pp;
997
998 struct hash_table a_word_table;
999 int is_filter = streq (funcname, "filter");
1000 const char *pat_iterator = argv[0];
1001 const char *word_iterator = argv[1];
1002 int literals = 0;
1003 int words = 0;
1004 int hashing = 0;
1005 char *p;
1006 unsigned int len;
1007
1008 /* Chop ARGV[0] up into patterns to match against the words. */
1009
1010 pattail = &pathead;
1011 while ((p = find_next_token (&pat_iterator, &len)) != 0)
1012 {
1013 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
1014
1015 *pattail = pat;
1016 pattail = &pat->next;
1017
1018 if (*pat_iterator != '\0')
1019 ++pat_iterator;
1020
1021 pat->str = p;
1022 pat->length = len;
1023 pat->save_c = p[len];
1024 p[len] = '\0';
1025 pat->percent = find_percent (p);
1026 if (pat->percent == 0)
1027 literals++;
1028 }
1029 *pattail = 0;
1030
1031 /* Chop ARGV[1] up into words to match against the patterns. */
1032
1033 wordtail = &wordhead;
1034 while ((p = find_next_token (&word_iterator, &len)) != 0)
1035 {
1036 struct a_word *word = alloca (sizeof (struct a_word));
1037
1038 *wordtail = word;
1039 wordtail = &word->next;
1040
1041 if (*word_iterator != '\0')
1042 ++word_iterator;
1043
1044 p[len] = '\0';
1045 word->str = p;
1046 word->length = len;
1047 word->matched = 0;
1048 word->chain = 0;
1049 words++;
1050 }
1051 *wordtail = 0;
1052
1053 /* Only use a hash table if arg list lengths justifies the cost. */
1054 hashing = (literals >= 2 && (literals * words) >= 10);
1055 if (hashing)
1056 {
1057 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
1058 a_word_hash_cmp);
1059 for (wp = wordhead; wp != 0; wp = wp->next)
1060 {
1061 struct a_word *owp = hash_insert (&a_word_table, wp);
1062 if (owp)
1063 wp->chain = owp;
1064 }
1065 }
1066
1067 if (words)
1068 {
1069 int doneany = 0;
1070
1071 /* Run each pattern through the words, killing words. */
1072 for (pp = pathead; pp != 0; pp = pp->next)
1073 {
1074 if (pp->percent)
1075 for (wp = wordhead; wp != 0; wp = wp->next)
1076 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1077 else if (hashing)
1078 {
1079 struct a_word a_word_key;
1080 a_word_key.str = pp->str;
1081 a_word_key.length = pp->length;
1082 wp = hash_find_item (&a_word_table, &a_word_key);
1083 while (wp)
1084 {
1085 wp->matched |= 1;
1086 wp = wp->chain;
1087 }
1088 }
1089 else
1090 for (wp = wordhead; wp != 0; wp = wp->next)
1091 wp->matched |= (wp->length == pp->length
1092 && strneq (pp->str, wp->str, wp->length));
1093 }
1094
1095 /* Output the words that matched (or didn't, for filter-out). */
1096 for (wp = wordhead; wp != 0; wp = wp->next)
1097 if (is_filter ? wp->matched : !wp->matched)
1098 {
1099 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1100 o = variable_buffer_output (o, " ", 1);
1101 doneany = 1;
1102 }
1103
1104 if (doneany)
1105 /* Kill the last space. */
1106 --o;
1107 }
1108
1109 for (pp = pathead; pp != 0; pp = pp->next)
1110 pp->str[pp->length] = pp->save_c;
1111
1112 if (hashing)
1113 hash_free (&a_word_table, 0);
1114
1115 return o;
1116}
1117
1118
1119static char *
1120func_strip (char *o, char **argv, const char *funcname UNUSED)
1121{
1122 const char *p = argv[0];
1123 int doneany = 0;
1124
1125 while (*p != '\0')
1126 {
1127 int i=0;
1128 const char *word_start;
1129
1130 while (isspace ((unsigned char)*p))
1131 ++p;
1132 word_start = p;
1133 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1134 {}
1135 if (!i)
1136 break;
1137 o = variable_buffer_output (o, word_start, i);
1138 o = variable_buffer_output (o, " ", 1);
1139 doneany = 1;
1140 }
1141
1142 if (doneany)
1143 /* Kill the last space. */
1144 --o;
1145
1146 return o;
1147}
1148
1149/*
1150 Print a warning or fatal message.
1151*/
1152static char *
1153func_error (char *o, char **argv, const char *funcname)
1154{
1155 char **argvp;
1156 char *msg, *p;
1157 int len;
1158
1159 /* The arguments will be broken on commas. Rather than create yet
1160 another special case where function arguments aren't broken up,
1161 just create a format string that puts them back together. */
1162 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1163 len += strlen (*argvp) + 2;
1164
1165 p = msg = alloca (len + 1);
1166
1167 for (argvp=argv; argvp[1] != 0; ++argvp)
1168 {
1169 strcpy (p, *argvp);
1170 p += strlen (*argvp);
1171 *(p++) = ',';
1172 *(p++) = ' ';
1173 }
1174 strcpy (p, *argvp);
1175
1176 switch (*funcname) {
1177 case 'e':
1178 fatal (reading_file, "%s", msg);
1179
1180 case 'w':
1181 error (reading_file, "%s", msg);
1182 break;
1183
1184 case 'i':
1185 printf ("%s\n", msg);
1186 fflush(stdout);
1187 break;
1188
1189 default:
1190 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1191 }
1192
1193 /* The warning function expands to the empty string. */
1194 return o;
1195}
1196
1197
1198/*
1199 chop argv[0] into words, and sort them.
1200 */
1201static char *
1202func_sort (char *o, char **argv, const char *funcname UNUSED)
1203{
1204 const char *t;
1205 char **words;
1206 int wordi;
1207 char *p;
1208 unsigned int len;
1209 int i;
1210
1211 /* Find the maximum number of words we'll have. */
1212 t = argv[0];
1213 wordi = 1;
1214 while (*t != '\0')
1215 {
1216 char c = *(t++);
1217
1218 if (! isspace ((unsigned char)c))
1219 continue;
1220
1221 ++wordi;
1222
1223 while (isspace ((unsigned char)*t))
1224 ++t;
1225 }
1226
1227 words = xmalloc (wordi * sizeof (char *));
1228
1229 /* Now assign pointers to each string in the array. */
1230 t = argv[0];
1231 wordi = 0;
1232 while ((p = find_next_token (&t, &len)) != 0)
1233 {
1234 ++t;
1235 p[len] = '\0';
1236 words[wordi++] = p;
1237 }
1238
1239 if (wordi)
1240 {
1241 /* Now sort the list of words. */
1242 qsort (words, wordi, sizeof (char *), alpha_compare);
1243
1244 /* Now write the sorted list, uniquified. */
1245#ifdef CONFIG_WITH_RSORT
1246 if (strcmp (funcname, "rsort"))
1247 {
1248 /* sort */
1249#endif
1250 for (i = 0; i < wordi; ++i)
1251 {
1252 len = strlen (words[i]);
1253 if (i == wordi - 1 || strlen (words[i + 1]) != len
1254 || strcmp (words[i], words[i + 1]))
1255 {
1256 o = variable_buffer_output (o, words[i], len);
1257 o = variable_buffer_output (o, " ", 1);
1258 }
1259 }
1260#ifdef CONFIG_WITH_RSORT
1261 }
1262 else
1263 {
1264 /* rsort - reverse the result */
1265 i = wordi;
1266 while (i-- > 0)
1267 {
1268 len = strlen (words[i]);
1269 if (i == 0 || strlen (words[i - 1]) != len
1270 || strcmp (words[i], words[i - 1]))
1271 {
1272 o = variable_buffer_output (o, words[i], len);
1273 o = variable_buffer_output (o, " ", 1);
1274 }
1275 }
1276 }
1277#endif
1278
1279 /* Kill the last space. */
1280 --o;
1281 }
1282
1283 free (words);
1284
1285 return o;
1286}
1287
1288/*
1289 $(if condition,true-part[,false-part])
1290
1291 CONDITION is false iff it evaluates to an empty string. White
1292 space before and after condition are stripped before evaluation.
1293
1294 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1295 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1296 you can use $(if ...) to create side-effects (with $(shell ...), for
1297 example).
1298*/
1299
1300static char *
1301func_if (char *o, char **argv, const char *funcname UNUSED)
1302{
1303 const char *begp = argv[0];
1304 const char *endp = begp + strlen (argv[0]) - 1;
1305 int result = 0;
1306
1307 /* Find the result of the condition: if we have a value, and it's not
1308 empty, the condition is true. If we don't have a value, or it's the
1309 empty string, then it's false. */
1310
1311 strip_whitespace (&begp, &endp);
1312
1313 if (begp <= endp)
1314 {
1315 char *expansion = expand_argument (begp, endp+1);
1316
1317 result = strlen (expansion);
1318 free (expansion);
1319 }
1320
1321 /* If the result is true (1) we want to eval the first argument, and if
1322 it's false (0) we want to eval the second. If the argument doesn't
1323 exist we do nothing, otherwise expand it and add to the buffer. */
1324
1325 argv += 1 + !result;
1326
1327 if (*argv)
1328 {
1329 char *expansion = expand_argument (*argv, NULL);
1330
1331 o = variable_buffer_output (o, expansion, strlen (expansion));
1332
1333 free (expansion);
1334 }
1335
1336 return o;
1337}
1338
1339/*
1340 $(or condition1[,condition2[,condition3[...]]])
1341
1342 A CONDITION is false iff it evaluates to an empty string. White
1343 space before and after CONDITION are stripped before evaluation.
1344
1345 CONDITION1 is evaluated. If it's true, then this is the result of
1346 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1347 the conditions are true, the expansion is the empty string.
1348
1349 Once a CONDITION is true no further conditions are evaluated
1350 (short-circuiting).
1351*/
1352
1353static char *
1354func_or (char *o, char **argv, const char *funcname UNUSED)
1355{
1356 for ( ; *argv ; ++argv)
1357 {
1358 const char *begp = *argv;
1359 const char *endp = begp + strlen (*argv) - 1;
1360 char *expansion;
1361 int result = 0;
1362
1363 /* Find the result of the condition: if it's false keep going. */
1364
1365 strip_whitespace (&begp, &endp);
1366
1367 if (begp > endp)
1368 continue;
1369
1370 expansion = expand_argument (begp, endp+1);
1371 result = strlen (expansion);
1372
1373 /* If the result is false keep going. */
1374 if (!result)
1375 {
1376 free (expansion);
1377 continue;
1378 }
1379
1380 /* It's true! Keep this result and return. */
1381 o = variable_buffer_output (o, expansion, result);
1382 free (expansion);
1383 break;
1384 }
1385
1386 return o;
1387}
1388
1389/*
1390 $(and condition1[,condition2[,condition3[...]]])
1391
1392 A CONDITION is false iff it evaluates to an empty string. White
1393 space before and after CONDITION are stripped before evaluation.
1394
1395 CONDITION1 is evaluated. If it's false, then this is the result of
1396 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1397 the conditions are true, the expansion is the result of the last condition.
1398
1399 Once a CONDITION is false no further conditions are evaluated
1400 (short-circuiting).
1401*/
1402
1403static char *
1404func_and (char *o, char **argv, const char *funcname UNUSED)
1405{
1406 char *expansion;
1407 int result;
1408
1409 while (1)
1410 {
1411 const char *begp = *argv;
1412 const char *endp = begp + strlen (*argv) - 1;
1413
1414 /* An empty condition is always false. */
1415 strip_whitespace (&begp, &endp);
1416 if (begp > endp)
1417 return o;
1418
1419 expansion = expand_argument (begp, endp+1);
1420 result = strlen (expansion);
1421
1422 /* If the result is false, stop here: we're done. */
1423 if (!result)
1424 break;
1425
1426 /* Otherwise the result is true. If this is the last one, keep this
1427 result and quit. Otherwise go on to the next one! */
1428
1429 if (*(++argv))
1430 free (expansion);
1431 else
1432 {
1433 o = variable_buffer_output (o, expansion, result);
1434 break;
1435 }
1436 }
1437
1438 free (expansion);
1439
1440 return o;
1441}
1442
1443static char *
1444func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1445{
1446#ifdef _AMIGA
1447 o = wildcard_expansion (argv[0], o);
1448#else
1449 char *p = string_glob (argv[0]);
1450 o = variable_buffer_output (o, p, strlen (p));
1451#endif
1452 return o;
1453}
1454
1455/*
1456 $(eval <makefile string>)
1457
1458 Always resolves to the empty string.
1459
1460 Treat the arguments as a segment of makefile, and parse them.
1461*/
1462
1463static char *
1464func_eval (char *o, char **argv, const char *funcname UNUSED)
1465{
1466 char *buf;
1467 unsigned int len;
1468
1469 /* Eval the buffer. Pop the current variable buffer setting so that the
1470 eval'd code can use its own without conflicting. */
1471
1472 install_variable_buffer (&buf, &len);
1473
1474 eval_buffer (argv[0]);
1475
1476 restore_variable_buffer (buf, len);
1477
1478 return o;
1479}
1480
1481
1482static char *
1483func_value (char *o, char **argv, const char *funcname UNUSED)
1484{
1485 /* Look up the variable. */
1486 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1487
1488 /* Copy its value into the output buffer without expanding it. */
1489 if (v)
1490#ifdef CONFIG_WITH_VALUE_LENGTH
1491 o = variable_buffer_output (o, v->value,
1492 v->value_length >= 0 ? v->value_length : strlen(v->value));
1493#else
1494 o = variable_buffer_output (o, v->value, strlen(v->value));
1495#endif
1496
1497 return o;
1498}
1499
1500/*
1501 \r is replaced on UNIX as well. Is this desirable?
1502 */
1503static void
1504fold_newlines (char *buffer, unsigned int *length)
1505{
1506 char *dst = buffer;
1507 char *src = buffer;
1508 char *last_nonnl = buffer -1;
1509 src[*length] = 0;
1510 for (; *src != '\0'; ++src)
1511 {
1512 if (src[0] == '\r' && src[1] == '\n')
1513 continue;
1514 if (*src == '\n')
1515 {
1516 *dst++ = ' ';
1517 }
1518 else
1519 {
1520 last_nonnl = dst;
1521 *dst++ = *src;
1522 }
1523 }
1524 *(++last_nonnl) = '\0';
1525 *length = last_nonnl - buffer;
1526}
1527
1528
1529
1530int shell_function_pid = 0, shell_function_completed;
1531
1532
1533#ifdef WINDOWS32
1534/*untested*/
1535
1536#include <windows.h>
1537#include <io.h>
1538#include "sub_proc.h"
1539
1540
1541void
1542windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1543{
1544 SECURITY_ATTRIBUTES saAttr;
1545 HANDLE hIn;
1546 HANDLE hErr;
1547 HANDLE hChildOutRd;
1548 HANDLE hChildOutWr;
1549 HANDLE hProcess;
1550
1551
1552 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1553 saAttr.bInheritHandle = TRUE;
1554 saAttr.lpSecurityDescriptor = NULL;
1555
1556 if (DuplicateHandle (GetCurrentProcess(),
1557 GetStdHandle(STD_INPUT_HANDLE),
1558 GetCurrentProcess(),
1559 &hIn,
1560 0,
1561 TRUE,
1562 DUPLICATE_SAME_ACCESS) == FALSE) {
1563 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1564 GetLastError());
1565
1566 }
1567 if (DuplicateHandle(GetCurrentProcess(),
1568 GetStdHandle(STD_ERROR_HANDLE),
1569 GetCurrentProcess(),
1570 &hErr,
1571 0,
1572 TRUE,
1573 DUPLICATE_SAME_ACCESS) == FALSE) {
1574 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1575 GetLastError());
1576 }
1577
1578 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1579 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1580
1581 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1582
1583 if (!hProcess)
1584 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1585
1586 /* make sure that CreateProcess() has Path it needs */
1587 sync_Path_environment();
1588
1589 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1590 /* register process for wait */
1591 process_register(hProcess);
1592
1593 /* set the pid for returning to caller */
1594 *pid_p = (int) hProcess;
1595
1596 /* set up to read data from child */
1597 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1598
1599 /* this will be closed almost right away */
1600 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1601 } else {
1602 /* reap/cleanup the failed process */
1603 process_cleanup(hProcess);
1604
1605 /* close handles which were duplicated, they weren't used */
1606 CloseHandle(hIn);
1607 CloseHandle(hErr);
1608
1609 /* close pipe handles, they won't be used */
1610 CloseHandle(hChildOutRd);
1611 CloseHandle(hChildOutWr);
1612
1613 /* set status for return */
1614 pipedes[0] = pipedes[1] = -1;
1615 *pid_p = -1;
1616 }
1617}
1618#endif
1619
1620
1621#ifdef __MSDOS__
1622FILE *
1623msdos_openpipe (int* pipedes, int *pidp, char *text)
1624{
1625 FILE *fpipe=0;
1626 /* MSDOS can't fork, but it has `popen'. */
1627 struct variable *sh = lookup_variable ("SHELL", 5);
1628 int e;
1629 extern int dos_command_running, dos_status;
1630
1631 /* Make sure not to bother processing an empty line. */
1632 while (isblank ((unsigned char)*text))
1633 ++text;
1634 if (*text == '\0')
1635 return 0;
1636
1637 if (sh)
1638 {
1639 char buf[PATH_MAX + 7];
1640 /* This makes sure $SHELL value is used by $(shell), even
1641 though the target environment is not passed to it. */
1642 sprintf (buf, "SHELL=%s", sh->value);
1643 putenv (buf);
1644 }
1645
1646 e = errno;
1647 errno = 0;
1648 dos_command_running = 1;
1649 dos_status = 0;
1650 /* If dos_status becomes non-zero, it means the child process
1651 was interrupted by a signal, like SIGINT or SIGQUIT. See
1652 fatal_error_signal in commands.c. */
1653 fpipe = popen (text, "rt");
1654 dos_command_running = 0;
1655 if (!fpipe || dos_status)
1656 {
1657 pipedes[0] = -1;
1658 *pidp = -1;
1659 if (dos_status)
1660 errno = EINTR;
1661 else if (errno == 0)
1662 errno = ENOMEM;
1663 shell_function_completed = -1;
1664 }
1665 else
1666 {
1667 pipedes[0] = fileno (fpipe);
1668 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1669 errno = e;
1670 shell_function_completed = 1;
1671 }
1672 return fpipe;
1673}
1674#endif
1675
1676/*
1677 Do shell spawning, with the naughty bits for different OSes.
1678 */
1679
1680#ifdef VMS
1681
1682/* VMS can't do $(shell ...) */
1683#define func_shell 0
1684
1685#else
1686#ifndef _AMIGA
1687static char *
1688func_shell (char *o, char **argv, const char *funcname UNUSED)
1689{
1690 char *batch_filename = NULL;
1691
1692#ifdef __MSDOS__
1693 FILE *fpipe;
1694#endif
1695 char **command_argv;
1696 const char *error_prefix;
1697 char **envp;
1698 int pipedes[2];
1699 int pid;
1700
1701#ifndef __MSDOS__
1702 /* Construct the argument list. */
1703 command_argv = construct_command_argv (argv[0], NULL, NULL, &batch_filename);
1704 if (command_argv == 0)
1705 return o;
1706#endif
1707
1708 /* Using a target environment for `shell' loses in cases like:
1709 export var = $(shell echo foobie)
1710 because target_environment hits a loop trying to expand $(var)
1711 to put it in the environment. This is even more confusing when
1712 var was not explicitly exported, but just appeared in the
1713 calling environment.
1714
1715 See Savannah bug #10593.
1716
1717 envp = target_environment (NILF);
1718 */
1719
1720 envp = environ;
1721
1722 /* For error messages. */
1723 if (reading_file && reading_file->filenm)
1724 {
1725 char *p = alloca (strlen (reading_file->filenm)+11+4);
1726 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1727 error_prefix = p;
1728 }
1729 else
1730 error_prefix = "";
1731
1732#if defined(__MSDOS__)
1733 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1734 if (pipedes[0] < 0)
1735 {
1736 perror_with_name (error_prefix, "pipe");
1737 return o;
1738 }
1739#elif defined(WINDOWS32)
1740 windows32_openpipe (pipedes, &pid, command_argv, envp);
1741 if (pipedes[0] < 0)
1742 {
1743 /* open of the pipe failed, mark as failed execution */
1744 shell_function_completed = -1;
1745
1746 return o;
1747 }
1748 else
1749#else
1750 if (pipe (pipedes) < 0)
1751 {
1752 perror_with_name (error_prefix, "pipe");
1753 return o;
1754 }
1755
1756# ifdef __EMX__
1757 /* close some handles that are unnecessary for the child process */
1758 CLOSE_ON_EXEC(pipedes[1]);
1759 CLOSE_ON_EXEC(pipedes[0]);
1760 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1761 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1762 if (pid < 0)
1763 perror_with_name (error_prefix, "spawn");
1764# else /* ! __EMX__ */
1765 pid = vfork ();
1766 if (pid < 0)
1767 perror_with_name (error_prefix, "fork");
1768 else if (pid == 0)
1769 child_execute_job (0, pipedes[1], command_argv, envp);
1770 else
1771# endif
1772#endif
1773 {
1774 /* We are the parent. */
1775 char *buffer;
1776 unsigned int maxlen, i;
1777 int cc;
1778
1779 /* Record the PID for reap_children. */
1780 shell_function_pid = pid;
1781#ifndef __MSDOS__
1782 shell_function_completed = 0;
1783
1784 /* Free the storage only the child needed. */
1785 free (command_argv[0]);
1786 free (command_argv);
1787
1788 /* Close the write side of the pipe. */
1789# ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
1790 if (pipedes[1] != -1)
1791# endif
1792 close (pipedes[1]);
1793#endif
1794
1795 /* Set up and read from the pipe. */
1796
1797 maxlen = 200;
1798 buffer = xmalloc (maxlen + 1);
1799
1800 /* Read from the pipe until it gets EOF. */
1801 for (i = 0; ; i += cc)
1802 {
1803 if (i == maxlen)
1804 {
1805 maxlen += 512;
1806 buffer = xrealloc (buffer, maxlen + 1);
1807 }
1808
1809 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1810 if (cc <= 0)
1811 break;
1812 }
1813 buffer[i] = '\0';
1814
1815 /* Close the read side of the pipe. */
1816#ifdef __MSDOS__
1817 if (fpipe)
1818 (void) pclose (fpipe);
1819#else
1820# ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
1821 if (pipedes[0] != -1)
1822# endif
1823 (void) close (pipedes[0]);
1824#endif
1825
1826 /* Loop until child_handler or reap_children() sets
1827 shell_function_completed to the status of our child shell. */
1828 while (shell_function_completed == 0)
1829 reap_children (1, 0);
1830
1831 if (batch_filename) {
1832 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1833 batch_filename));
1834 remove (batch_filename);
1835 free (batch_filename);
1836 }
1837 shell_function_pid = 0;
1838
1839 /* The child_handler function will set shell_function_completed
1840 to 1 when the child dies normally, or to -1 if it
1841 dies with status 127, which is most likely an exec fail. */
1842
1843 if (shell_function_completed == -1)
1844 {
1845 /* This likely means that the execvp failed, so we should just
1846 write the error message in the pipe from the child. */
1847 fputs (buffer, stderr);
1848 fflush (stderr);
1849 }
1850 else
1851 {
1852 /* The child finished normally. Replace all newlines in its output
1853 with spaces, and put that in the variable output buffer. */
1854 fold_newlines (buffer, &i);
1855 o = variable_buffer_output (o, buffer, i);
1856 }
1857
1858 free (buffer);
1859 }
1860
1861 return o;
1862}
1863
1864#else /* _AMIGA */
1865
1866/* Do the Amiga version of func_shell. */
1867
1868static char *
1869func_shell (char *o, char **argv, const char *funcname)
1870{
1871 /* Amiga can't fork nor spawn, but I can start a program with
1872 redirection of my choice. However, this means that we
1873 don't have an opportunity to reopen stdout to trap it. Thus,
1874 we save our own stdout onto a new descriptor and dup a temp
1875 file's descriptor onto our stdout temporarily. After we
1876 spawn the shell program, we dup our own stdout back to the
1877 stdout descriptor. The buffer reading is the same as above,
1878 except that we're now reading from a file. */
1879
1880#include <dos/dos.h>
1881#include <proto/dos.h>
1882
1883 BPTR child_stdout;
1884 char tmp_output[FILENAME_MAX];
1885 unsigned int maxlen = 200, i;
1886 int cc;
1887 char * buffer, * ptr;
1888 char ** aptr;
1889 int len = 0;
1890 char* batch_filename = NULL;
1891
1892 /* Construct the argument list. */
1893 command_argv = construct_command_argv (argv[0], (char **) NULL,
1894 (struct file *) 0, &batch_filename);
1895 if (command_argv == 0)
1896 return o;
1897
1898 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1899 Ideally we would use main.c:open_tmpfile(), but this uses a special
1900 Open(), not fopen(), and I'm not familiar enough with the code to mess
1901 with it. */
1902 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1903 mktemp (tmp_output);
1904 child_stdout = Open (tmp_output, MODE_NEWFILE);
1905
1906 for (aptr=command_argv; *aptr; aptr++)
1907 len += strlen (*aptr) + 1;
1908
1909 buffer = xmalloc (len + 1);
1910 ptr = buffer;
1911
1912 for (aptr=command_argv; *aptr; aptr++)
1913 {
1914 strcpy (ptr, *aptr);
1915 ptr += strlen (ptr) + 1;
1916 *ptr ++ = ' ';
1917 *ptr = 0;
1918 }
1919
1920 ptr[-1] = '\n';
1921
1922 Execute (buffer, NULL, child_stdout);
1923 free (buffer);
1924
1925 Close (child_stdout);
1926
1927 child_stdout = Open (tmp_output, MODE_OLDFILE);
1928
1929 buffer = xmalloc (maxlen);
1930 i = 0;
1931 do
1932 {
1933 if (i == maxlen)
1934 {
1935 maxlen += 512;
1936 buffer = xrealloc (buffer, maxlen + 1);
1937 }
1938
1939 cc = Read (child_stdout, &buffer[i], maxlen - i);
1940 if (cc > 0)
1941 i += cc;
1942 } while (cc > 0);
1943
1944 Close (child_stdout);
1945
1946 fold_newlines (buffer, &i);
1947 o = variable_buffer_output (o, buffer, i);
1948 free (buffer);
1949 return o;
1950}
1951#endif /* _AMIGA */
1952#endif /* !VMS */
1953
1954#ifdef EXPERIMENTAL
1955
1956/*
1957 equality. Return is string-boolean, ie, the empty string is false.
1958 */
1959static char *
1960func_eq (char *o, char **argv, const char *funcname)
1961{
1962 int result = ! strcmp (argv[0], argv[1]);
1963 o = variable_buffer_output (o, result ? "1" : "", result);
1964 return o;
1965}
1966
1967
1968/*
1969 string-boolean not operator.
1970 */
1971static char *
1972func_not (char *o, char **argv, const char *funcname)
1973{
1974 const char *s = argv[0];
1975 int result = 0;
1976 while (isspace ((unsigned char)*s))
1977 s++;
1978 result = ! (*s);
1979 o = variable_buffer_output (o, result ? "1" : "", result);
1980 return o;
1981}
1982#endif
1983
1984
1985
1986/* Return the absolute name of file NAME which does not contain any `.',
1987 `..' components nor any repeated path separators ('/'). */
1988#ifdef KMK
1989char *
1990#else
1991static char *
1992#endif
1993abspath (const char *name, char *apath)
1994{
1995 char *dest;
1996 const char *start, *end, *apath_limit;
1997
1998 if (name[0] == '\0' || apath == NULL)
1999 return NULL;
2000
2001#ifdef WINDOWS32 /* bird */
2002 dest = w32ify((char *)name, 1);
2003 if (!dest)
2004 return NULL;
2005 {
2006 size_t len = strlen(dest);
2007 memcpy(apath, dest, len);
2008 dest = apath + len;
2009 }
2010
2011 (void)end; (void)start; (void)apath_limit;
2012
2013#elif defined __OS2__ /* bird */
2014 if (_abspath(apath, name, GET_PATH_MAX))
2015 return NULL;
2016 dest = strchr(apath, '\0');
2017
2018 (void)end; (void)start; (void)apath_limit; (void)dest;
2019
2020#else /* !WINDOWS32 && !__OS2__ */
2021 apath_limit = apath + GET_PATH_MAX;
2022
2023#ifdef HAVE_DOS_PATHS /* bird added this */
2024 if (isalpha(name[0]) && name[1] == ':')
2025 {
2026 /* drive spec */
2027 apath[0] = toupper(name[0]);
2028 apath[1] = ':';
2029 apath[2] = '/';
2030 name += 2;
2031 }
2032 else
2033#endif /* HAVE_DOS_PATHS */
2034 if (name[0] != '/')
2035 {
2036 /* It is unlikely we would make it until here but just to make sure. */
2037 if (!starting_directory)
2038 return NULL;
2039
2040 strcpy (apath, starting_directory);
2041
2042 dest = strchr (apath, '\0');
2043 }
2044 else
2045 {
2046 apath[0] = '/';
2047 dest = apath + 1;
2048 }
2049
2050 for (start = end = name; *start != '\0'; start = end)
2051 {
2052 unsigned long len;
2053
2054 /* Skip sequence of multiple path-separators. */
2055 while (*start == '/')
2056 ++start;
2057
2058 /* Find end of path component. */
2059 for (end = start; *end != '\0' && *end != '/'; ++end)
2060 ;
2061
2062 len = end - start;
2063
2064 if (len == 0)
2065 break;
2066 else if (len == 1 && start[0] == '.')
2067 /* nothing */;
2068 else if (len == 2 && start[0] == '.' && start[1] == '.')
2069 {
2070 /* Back up to previous component, ignore if at root already. */
2071 if (dest > apath + 1)
2072 while ((--dest)[-1] != '/');
2073 }
2074 else
2075 {
2076 if (dest[-1] != '/')
2077 *dest++ = '/';
2078
2079 if (dest + len >= apath_limit)
2080 return NULL;
2081
2082 dest = memcpy (dest, start, len);
2083 dest += len;
2084 *dest = '\0';
2085 }
2086 }
2087#endif /* !WINDOWS32 && !__OS2__ */
2088
2089 /* Unless it is root strip trailing separator. */
2090#ifdef HAVE_DOS_PATHS /* bird (is this correct? what about UNC?) */
2091 if (dest > apath + 1 + (apath[0] != '/') && dest[-1] == '/')
2092#else
2093 if (dest > apath + 1 && dest[-1] == '/')
2094#endif
2095 --dest;
2096
2097 *dest = '\0';
2098
2099 return apath;
2100}
2101
2102
2103static char *
2104func_realpath (char *o, char **argv, const char *funcname UNUSED)
2105{
2106 /* Expand the argument. */
2107 const char *p = argv[0];
2108 const char *path = 0;
2109 int doneany = 0;
2110 unsigned int len = 0;
2111 PATH_VAR (in);
2112 PATH_VAR (out);
2113
2114 while ((path = find_next_token (&p, &len)) != 0)
2115 {
2116 if (len < GET_PATH_MAX)
2117 {
2118 strncpy (in, path, len);
2119 in[len] = '\0';
2120
2121 if (
2122#ifdef HAVE_REALPATH
2123 realpath (in, out)
2124#else
2125 abspath (in, out)
2126#endif
2127 )
2128 {
2129 o = variable_buffer_output (o, out, strlen (out));
2130 o = variable_buffer_output (o, " ", 1);
2131 doneany = 1;
2132 }
2133 }
2134 }
2135
2136 /* Kill last space. */
2137 if (doneany)
2138 --o;
2139
2140 return o;
2141}
2142
2143static char *
2144func_abspath (char *o, char **argv, const char *funcname UNUSED)
2145{
2146 /* Expand the argument. */
2147 const char *p = argv[0];
2148 const char *path = 0;
2149 int doneany = 0;
2150 unsigned int len = 0;
2151 PATH_VAR (in);
2152 PATH_VAR (out);
2153
2154 while ((path = find_next_token (&p, &len)) != 0)
2155 {
2156 if (len < GET_PATH_MAX)
2157 {
2158 strncpy (in, path, len);
2159 in[len] = '\0';
2160
2161 if (abspath (in, out))
2162 {
2163 o = variable_buffer_output (o, out, strlen (out));
2164 o = variable_buffer_output (o, " ", 1);
2165 doneany = 1;
2166 }
2167 }
2168 }
2169
2170 /* Kill last space. */
2171 if (doneany)
2172 --o;
2173
2174 return o;
2175}
2176
2177#ifdef CONFIG_WITH_ABSPATHEX
2178/* same as abspath except that the current path is given as the 2nd argument. */
2179static char *
2180func_abspathex (char *o, char **argv, const char *funcname UNUSED)
2181{
2182 /* Expand the argument. */
2183 const char *p = argv[0];
2184 char *cwd = argv[1];
2185 unsigned int cwd_len = ~0U;
2186 char *path = 0;
2187 int doneany = 0;
2188 unsigned int len = 0;
2189 PATH_VAR (in);
2190 PATH_VAR (out);
2191
2192 while ((path = find_next_token (&p, &len)) != 0)
2193 {
2194 if (len < GET_PATH_MAX)
2195 {
2196#ifdef HAVE_DOS_PATHS
2197 if (path[0] != '/' && path[0] != '\\' && (len < 2 || path[1] != ':') && cwd)
2198#else
2199 if (path[0] != '/' && cwd)
2200#endif
2201 {
2202 /* relative path, prefix with cwd. */
2203 if (cwd_len == ~0U)
2204 cwd_len = strlen (cwd);
2205 if (cwd_len + len + 1 >= GET_PATH_MAX)
2206 continue;
2207 memcpy (in, cwd, cwd_len);
2208 in[cwd_len] = '/';
2209 memcpy (in + cwd_len + 1, path, len);
2210 in[cwd_len + len + 1] = '\0';
2211 }
2212 else
2213 {
2214 /* absolute path pass it as-is. */
2215 memcpy (in, path, len);
2216 in[len] = '\0';
2217 }
2218
2219 if (abspath (in, out))
2220 {
2221 o = variable_buffer_output (o, out, strlen (out));
2222 o = variable_buffer_output (o, " ", 1);
2223 doneany = 1;
2224 }
2225 }
2226 }
2227
2228 /* Kill last space. */
2229 if (doneany)
2230 --o;
2231
2232 return o;
2233}
2234#endif
2235
2236#ifdef CONFIG_WITH_XARGS
2237/* Create one or more command lines avoiding the max argument
2238 lenght restriction of the host OS.
2239
2240 The last argument is the list of arguments that the normal
2241 xargs command would be fed from stdin.
2242
2243 The first argument is initial command and it's arguments.
2244
2245 If there are three or more arguments, the 2nd argument is
2246 the command and arguments to be used on subsequent
2247 command lines. Defaults to the initial command.
2248
2249 If there are four or more arguments, the 3rd argument is
2250 the command to be used at the final command line. Defaults
2251 to the sub sequent or initial command .
2252
2253 A future version of this function may define more arguments
2254 and therefor anyone specifying six or more arguments will
2255 cause fatal errors.
2256
2257 Typical usage is:
2258 $(xargs ar cas mylib.a,$(objects))
2259 or
2260 $(xargs ar cas mylib.a,ar as mylib.a,$(objects))
2261
2262 It will then create one or more "ar mylib.a ..." command
2263 lines with proper \n\t separation so it can be used when
2264 writing rules. */
2265static char *
2266func_xargs (char *o, char **argv, const char *funcname)
2267{
2268 int argc;
2269 const char *initial_cmd;
2270 size_t initial_cmd_len;
2271 const char *subsequent_cmd;
2272 size_t subsequent_cmd_len;
2273 const char *final_cmd;
2274 size_t final_cmd_len;
2275 const char *args;
2276 size_t max_args;
2277 int i;
2278
2279#ifdef ARG_MAX
2280 /* ARG_MAX is a bit unreliable (environment), so drop 25% of the max. */
2281# define XARGS_MAX (ARG_MAX - (ARG_MAX / 4))
2282#else /* FIXME: update configure with a command line length test. */
2283# define XARGS_MAX 10240
2284#endif
2285
2286 argc = 0;
2287 while (argv[argc])
2288 argc++;
2289 if (argc > 4)
2290 fatal (NILF, _("Too many arguments for $(xargs)!\n"));
2291
2292 /* first: the initial / default command.*/
2293 initial_cmd = argv[0];
2294 while (isspace ((unsigned char)*initial_cmd))
2295 initial_cmd++;
2296 max_args = initial_cmd_len = strlen (initial_cmd);
2297
2298 /* second: the command for the subsequent command lines. defaults to the initial cmd. */
2299 subsequent_cmd = argc > 2 && argv[1][0] != '\0' ? argv[1] : "";
2300 while (isspace ((unsigned char)*subsequent_cmd))
2301 subsequent_cmd++;
2302 if (*subsequent_cmd)
2303 {
2304 subsequent_cmd_len = strlen (subsequent_cmd);
2305 if (subsequent_cmd_len > max_args)
2306 max_args = subsequent_cmd_len;
2307 }
2308 else
2309 {
2310 subsequent_cmd = initial_cmd;
2311 subsequent_cmd_len = initial_cmd_len;
2312 }
2313
2314 /* third: the final command. defaults to the subseq cmd. */
2315 final_cmd = argc > 3 && argv[2][0] != '\0' ? argv[2] : "";
2316 while (isspace ((unsigned char)*final_cmd))
2317 final_cmd++;
2318 if (*final_cmd)
2319 {
2320 final_cmd_len = strlen (final_cmd);
2321 if (final_cmd_len > max_args)
2322 max_args = final_cmd_len;
2323 }
2324 else
2325 {
2326 final_cmd = subsequent_cmd;
2327 final_cmd_len = subsequent_cmd_len;
2328 }
2329
2330 /* last: the arguments to split up into sensible portions. */
2331 args = argv[argc - 1];
2332
2333 /* calc the max argument length. */
2334 if (XARGS_MAX <= max_args + 2)
2335 fatal (NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
2336 (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
2337 max_args = XARGS_MAX - max_args - 1;
2338
2339 /* generate the commands. */
2340 i = 0;
2341 for (i = 0; ; i++)
2342 {
2343 unsigned int len;
2344 const char *iterator = args;
2345 const char *end = args;
2346 const char *cur;
2347 const char *tmp;
2348
2349 /* scan the arguments till we reach the end or the max length. */
2350 while ((cur = find_next_token(&iterator, &len))
2351 && (size_t)((cur + len) - args) < max_args)
2352 end = cur + len;
2353 if (cur && end == args)
2354 fatal (NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
2355
2356 /* emit the command. */
2357 if (i == 0)
2358 {
2359 o = variable_buffer_output (o, (char *)initial_cmd, initial_cmd_len);
2360 o = variable_buffer_output (o, " ", 1);
2361 }
2362 else if (cur)
2363 {
2364 o = variable_buffer_output (o, "\n\t", 2);
2365 o = variable_buffer_output (o, (char *)subsequent_cmd, subsequent_cmd_len);
2366 o = variable_buffer_output (o, " ", 1);
2367 }
2368 else
2369 {
2370 o = variable_buffer_output (o, "\n\t", 2);
2371 o = variable_buffer_output (o, (char *)final_cmd, final_cmd_len);
2372 o = variable_buffer_output (o, " ", 1);
2373 }
2374
2375 tmp = end;
2376 while (tmp > args && isspace ((unsigned char)tmp[-1])) /* drop trailing spaces. */
2377 tmp--;
2378 o = variable_buffer_output (o, (char *)args, tmp - args);
2379
2380
2381 /* next */
2382 if (!cur)
2383 break;
2384 args = end;
2385 while (isspace ((unsigned char)*args))
2386 args++;
2387 }
2388
2389 return o;
2390}
2391#endif
2392
2393#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2394static char *
2395func_toupper_tolower (char *o, char **argv, const char *funcname)
2396{
2397 /* Expand the argument. */
2398 const char *p = argv[0];
2399 while (*p)
2400 {
2401 /* convert to temporary buffer */
2402 char tmp[256];
2403 unsigned int i;
2404 if (!strcmp(funcname, "toupper"))
2405 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2406 tmp[i] = toupper(*p);
2407 else
2408 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2409 tmp[i] = tolower(*p);
2410 o = variable_buffer_output (o, tmp, i);
2411 }
2412
2413 return o;
2414}
2415#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
2416
2417#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2418
2419/* Strip leading spaces and other things off a command. */
2420static const char *
2421comp_cmds_strip_leading (const char *s, const char *e)
2422{
2423 while (s < e)
2424 {
2425 const char ch = *s;
2426 if (!isblank (ch)
2427 && ch != '@'
2428 && ch != '+'
2429 && ch != '-')
2430 break;
2431 s++;
2432 }
2433 return s;
2434}
2435
2436/* Worker for func_comp_vars() which is called if the comparision failed.
2437 It will do the slow command by command comparision of the commands
2438 when there invoked as comp-cmds. */
2439static char *
2440comp_vars_ne (char *o, const char *s1, const char *e1, const char *s2, const char *e2,
2441 char *ne_retval, const char *funcname)
2442{
2443 /* give up at once if not comp-cmds. */
2444 if (strcmp (funcname, "comp-cmds") != 0)
2445 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
2446 else
2447 {
2448 const char * const s1_start = s1;
2449 int new_cmd = 1;
2450 int diff;
2451 for (;;)
2452 {
2453 /* if it's a new command, strip leading stuff. */
2454 if (new_cmd)
2455 {
2456 s1 = comp_cmds_strip_leading (s1, e1);
2457 s2 = comp_cmds_strip_leading (s2, e2);
2458 new_cmd = 0;
2459 }
2460 if (s1 >= e1 || s2 >= e2)
2461 break;
2462
2463 /*
2464 * Inner compare loop which compares one line.
2465 * FIXME: parse quoting!
2466 */
2467 for (;;)
2468 {
2469 const char ch1 = *s1;
2470 const char ch2 = *s2;
2471 diff = ch1 - ch2;
2472 if (diff)
2473 break;
2474 if (ch1 == '\n')
2475 break;
2476 assert (ch1 != '\r');
2477
2478 /* next */
2479 s1++;
2480 s2++;
2481 if (s1 >= e1 || s2 >= e2)
2482 break;
2483 }
2484
2485 /*
2486 * If we exited because of a difference try to end-of-command
2487 * comparision, e.g. ignore trailing spaces.
2488 */
2489 if (diff)
2490 {
2491 /* strip */
2492 while (s1 < e1 && isblank (*s1))
2493 s1++;
2494 while (s2 < e2 && isblank (*s2))
2495 s2++;
2496 if (s1 >= e1 || s2 >= e2)
2497 break;
2498
2499 /* compare again and check that it's a newline. */
2500 if (*s2 != '\n' || *s1 != '\n')
2501 break;
2502 }
2503 /* Break out if we exited because of EOS. */
2504 else if (s1 >= e1 || s2 >= e2)
2505 break;
2506
2507 /*
2508 * Detect the end of command lines.
2509 */
2510 if (*s1 == '\n')
2511 new_cmd = s1 == s1_start || s1[-1] != '\\';
2512 s1++;
2513 s2++;
2514 }
2515
2516 /*
2517 * Ignore trailing empty lines.
2518 */
2519 if (s1 < e1 || s2 < e2)
2520 {
2521 while (s1 < e1 && (isblank (*s1) || *s1 == '\n'))
2522 if (*s1++ == '\n')
2523 s1 = comp_cmds_strip_leading (s1, e1);
2524 while (s2 < e2 && (isblank (*s2) || *s2 == '\n'))
2525 if (*s2++ == '\n')
2526 s2 = comp_cmds_strip_leading (s2, e2);
2527 }
2528
2529 /* emit the result. */
2530 if (s1 == e1 && s2 == e2)
2531 o = variable_buffer_output (o, "", 1);
2532 else
2533 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
2534 }
2535 return o;
2536}
2537
2538/*
2539 $(comp-vars var1,var2,not-equal-return)
2540 or
2541 $(comp-cmds cmd-var1,cmd-var2,not-equal-return)
2542
2543 Compares the two variables (that's given by name to avoid unnecessary
2544 expanding) and return the string in the third argument if not equal.
2545 If equal, nothing is returned.
2546
2547 comp-vars will to an exact comparision only stripping leading and
2548 trailing spaces.
2549
2550 comp-cmds will compare command by command, ignoring not only leading
2551 and trailing spaces on each line but also leading one leading '@' and '-'.
2552*/
2553static char *
2554func_comp_vars (char *o, char **argv, const char *funcname)
2555{
2556 const char *s1, *e1, *x1, *s2, *e2, *x2;
2557 char *a1 = NULL, *a2 = NULL;
2558 size_t l, l1, l2;
2559 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
2560 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
2561
2562 /* the simple cases */
2563 if (var1 == var2)
2564 return variable_buffer_output (o, "", 1); /* eq */
2565 if (!var1 || !var2)
2566 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2567 if (var1->value == var2->value)
2568 return variable_buffer_output (o, "", 1); /* eq */
2569 if (!var1->recursive && !var2->recursive)
2570 {
2571 if ( var1->value_length == var2->value_length
2572 && !memcmp (var1->value, var2->value, var1->value_length))
2573 return variable_buffer_output (o, "", 1); /* eq */
2574
2575 /* ignore trailing and leading blanks */
2576 s1 = var1->value;
2577 while (isblank ((unsigned char) *s1))
2578 s1++;
2579 e1 = s1 + var1->value_length;
2580 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2581 e1--;
2582
2583 s2 = var2->value;
2584 while (isblank ((unsigned char) *s2))
2585 s2++;
2586 e2 = s2 + var2->value_length;
2587 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2588 e2--;
2589
2590 if (e1 - s1 != e2 - s2)
2591 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2592l_simple_compare:
2593 if (!memcmp (s1, s2, e1 - s1))
2594 return variable_buffer_output (o, "", 1); /* eq */
2595 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2596 }
2597
2598 /* ignore trailing and leading blanks */
2599 s1 = var1->value;
2600 e1 = s1 + var1->value_length;
2601 while (isblank ((unsigned char) *s1))
2602 s1++;
2603 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2604 e1--;
2605
2606 s2 = var2->value;
2607 e2 = s2 + var2->value_length;
2608 while (isblank((unsigned char)*s2))
2609 s2++;
2610 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2611 e2--;
2612
2613 /* both empty after stripping? */
2614 if (s1 == e1 && s2 == e2)
2615 return variable_buffer_output (o, "", 1); /* eq */
2616
2617 /* optimist. */
2618 if ( e1 - s1 == e2 - s2
2619 && !memcmp(s1, s2, e1 - s1))
2620 return variable_buffer_output (o, "", 1); /* eq */
2621
2622 /* compare up to the first '$' or the end. */
2623 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
2624 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
2625 if (!x1 && !x2)
2626 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2627
2628 l1 = x1 ? x1 - s1 : e1 - s1;
2629 l2 = x2 ? x2 - s2 : e2 - s2;
2630 l = l1 <= l2 ? l1 : l2;
2631 if (l && memcmp (s1, s2, l))
2632 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2633
2634 /* one or both buffers now require expanding. */
2635 if (!x1)
2636 s1 += l;
2637 else
2638 {
2639 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
2640 if (!l)
2641 while (isblank ((unsigned char) *s1))
2642 s1++;
2643 e1 = strchr (s1, '\0');
2644 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2645 e1--;
2646 }
2647
2648 if (!x2)
2649 s2 += l;
2650 else
2651 {
2652 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
2653 if (!l)
2654 while (isblank ((unsigned char) *s2))
2655 s2++;
2656 e2 = strchr (s2, '\0');
2657 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2658 e2--;
2659 }
2660
2661 /* the final compare */
2662 if ( e1 - s1 != e2 - s2
2663 || memcmp (s1, s2, e1 - s1))
2664 o = comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
2665 else
2666 o = variable_buffer_output (o, "", 1); /* eq */
2667 if (a1)
2668 free (a1);
2669 if (a2)
2670 free (a2);
2671 return o;
2672}
2673#endif
2674
2675
2676#ifdef CONFIG_WITH_STACK
2677
2678/* Push an item (string without spaces). */
2679static char *
2680func_stack_push (char *o, char **argv, const char *funcname)
2681{
2682 do_variable_definition(NILF, argv[0], argv[1], o_file, f_append, 0 /* !target_var */);
2683 return o;
2684}
2685
2686/* Pops an item off the stack / get the top stack element.
2687 (This is what's tricky to do in pure GNU make syntax.) */
2688static char *
2689func_stack_pop_top (char *o, char **argv, const char *funcname)
2690{
2691 struct variable *stack_var;
2692 const char *stack = argv[0];
2693 const int return_item = argv[0][sizeof("stack-pop") - 1] == '\0';
2694
2695 stack_var = lookup_variable (stack, strlen (stack) );
2696 if (stack_var)
2697 {
2698 unsigned int len;
2699 const char *iterator = stack_var->value;
2700 char *lastitem = NULL;
2701 char *cur;
2702
2703 while ((cur = find_next_token (&iterator, &len)))
2704 lastitem = cur;
2705
2706 if (lastitem != NULL)
2707 {
2708 if (strcmp (funcname, "stack-popv") != 0)
2709 o = variable_buffer_output (o, lastitem, len);
2710 if (strcmp (funcname, "stack-top") != 0)
2711 {
2712 *lastitem = '\0';
2713 while (lastitem > stack_var->value && isspace (lastitem[-1]))
2714 *--lastitem = '\0';
2715#ifdef CONFIG_WITH_VALUE_LENGTH
2716 stack_var->value_length = lastitem - stack_var->value;
2717#endif
2718 }
2719 }
2720 }
2721 return o;
2722}
2723#endif /* CONFIG_WITH_STACK */
2724
2725#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS)
2726/* outputs the number (as a string) into the variable buffer. */
2727static char *
2728math_int_to_variable_buffer (char *o, math_int num)
2729{
2730 static const char xdigits[17] = "0123456789abcdef";
2731 int negative;
2732 char strbuf[24]; /* 16 hex + 2 prefix + sign + term => 20
2733 or 20 dec + sign + term => 22 */
2734 char *str = &strbuf[sizeof (strbuf) - 1];
2735
2736 negative = num < 0;
2737 if (negative)
2738 num = -num;
2739
2740 *str = '\0';
2741
2742 do
2743 {
2744#ifdef HEX_MATH_NUMBERS
2745 *--str = xdigits[num & 0xf];
2746 num >>= 4;
2747#else
2748 *--str = xdigits[num % 10];
2749 num /= 10;
2750#endif
2751 }
2752 while (num);
2753
2754#ifdef HEX_MATH_NUMBERS
2755 *--str = 'x';
2756 *--str = '0';
2757#endif
2758
2759 if (negative)
2760 *--str = '-';
2761
2762 return variable_buffer_output (o, str, &strbuf[sizeof (strbuf) - 1] - str);
2763}
2764#endif /* CONFIG_WITH_MATH || CONFIG_WITH_NANOTS */
2765
2766#ifdef CONFIG_WITH_MATH
2767
2768/* Converts a string to an integer, causes an error if the format is invalid. */
2769static math_int
2770math_int_from_string (const char *str)
2771{
2772 const char *start;
2773 unsigned base = 0;
2774 int negative = 0;
2775 math_int num = 0;
2776
2777 /* strip spaces */
2778 while (isspace (*str))
2779 str++;
2780 if (!*str)
2781 {
2782 error (NILF, _("bad number: empty\n"));
2783 return 0;
2784 }
2785 start = str;
2786
2787 /* check for +/- */
2788 while (*str == '+' || *str == '-' || isspace (*str))
2789 if (*str++ == '-')
2790 negative = !negative;
2791
2792 /* check for prefix - we do not accept octal numbers, sorry. */
2793 if (*str == '0' && (str[1] == 'x' || str[1] == 'X'))
2794 {
2795 base = 16;
2796 str += 2;
2797 }
2798 else
2799 {
2800 /* look for a hex digit, if not found treat it as decimal */
2801 const char *p2 = str;
2802 for ( ; *p2; p2++)
2803 if (isxdigit (*p2) && !isdigit (*p2) && isascii (*p2) )
2804 {
2805 base = 16;
2806 break;
2807 }
2808 if (base == 0)
2809 base = 10;
2810 }
2811
2812 /* must have at least one digit! */
2813 if ( !isascii (*str)
2814 || !(base == 16 ? isxdigit (*str) : isdigit (*str)) )
2815 {
2816 error (NILF, _("bad number: '%s'\n"), start);
2817 return 0;
2818 }
2819
2820 /* convert it! */
2821 while (*str && !isspace (*str))
2822 {
2823 int ch = *str++;
2824 if (ch >= '0' && ch <= '9')
2825 ch -= '0';
2826 else if (base == 16 && ch >= 'a' && ch <= 'f')
2827 ch -= 'a' - 10;
2828 else if (base == 16 && ch >= 'A' && ch <= 'F')
2829 ch -= 'A' - 10;
2830 else
2831 {
2832 error (NILF, _("bad number: '%s' (base=%d, pos=%d)\n"), start, base, str - start);
2833 return 0;
2834 }
2835 num *= base;
2836 num += ch;
2837 }
2838
2839 /* check trailing spaces. */
2840 while (isspace (*str))
2841 str++;
2842 if (*str)
2843 {
2844 error (NILF, _("bad number: '%s'\n"), start);
2845 return 0;
2846 }
2847
2848 return negative ? -num : num;
2849}
2850
2851/* Add two or more integer numbers. */
2852static char *
2853func_int_add (char *o, char **argv, const char *funcname)
2854{
2855 math_int num;
2856 int i;
2857
2858 num = math_int_from_string (argv[0]);
2859 for (i = 1; argv[i]; i++)
2860 num += math_int_from_string (argv[i]);
2861
2862 return math_int_to_variable_buffer (o, num);
2863}
2864
2865/* Subtract two or more integer numbers. */
2866static char *
2867func_int_sub (char *o, char **argv, const char *funcname)
2868{
2869 math_int num;
2870 int i;
2871
2872 num = math_int_from_string (argv[0]);
2873 for (i = 1; argv[i]; i++)
2874 num -= math_int_from_string (argv[i]);
2875
2876 return math_int_to_variable_buffer (o, num);
2877}
2878
2879/* Multiply two or more integer numbers. */
2880static char *
2881func_int_mul (char *o, char **argv, const char *funcname)
2882{
2883 math_int num;
2884 int i;
2885
2886 num = math_int_from_string (argv[0]);
2887 for (i = 1; argv[i]; i++)
2888 num *= math_int_from_string (argv[i]);
2889
2890 return math_int_to_variable_buffer (o, num);
2891}
2892
2893/* Divide an integer number by one or more divisors. */
2894static char *
2895func_int_div (char *o, char **argv, const char *funcname)
2896{
2897 math_int num;
2898 math_int divisor;
2899 int i;
2900
2901 num = math_int_from_string (argv[0]);
2902 for (i = 1; argv[i]; i++)
2903 {
2904 divisor = math_int_from_string (argv[i]);
2905 if (!divisor)
2906 {
2907 error (NILF, _("divide by zero ('%s')\n"), argv[i]);
2908 return math_int_to_variable_buffer (o, 0);
2909 }
2910 num /= divisor;
2911 }
2912
2913 return math_int_to_variable_buffer (o, num);
2914}
2915
2916
2917/* Divide and return the remainder. */
2918static char *
2919func_int_mod (char *o, char **argv, const char *funcname)
2920{
2921 math_int num;
2922 math_int divisor;
2923
2924 num = math_int_from_string (argv[0]);
2925 divisor = math_int_from_string (argv[1]);
2926 if (!divisor)
2927 {
2928 error (NILF, _("divide by zero ('%s')\n"), argv[1]);
2929 return math_int_to_variable_buffer (o, 0);
2930 }
2931 num %= divisor;
2932
2933 return math_int_to_variable_buffer (o, num);
2934}
2935
2936/* 2-complement. */
2937static char *
2938func_int_not (char *o, char **argv, const char *funcname)
2939{
2940 math_int num;
2941
2942 num = math_int_from_string (argv[0]);
2943 num = ~num;
2944
2945 return math_int_to_variable_buffer (o, num);
2946}
2947
2948/* Bitwise AND (two or more numbers). */
2949static char *
2950func_int_and (char *o, char **argv, const char *funcname)
2951{
2952 math_int num;
2953 int i;
2954
2955 num = math_int_from_string (argv[0]);
2956 for (i = 1; argv[i]; i++)
2957 num &= math_int_from_string (argv[i]);
2958
2959 return math_int_to_variable_buffer (o, num);
2960}
2961
2962/* Bitwise OR (two or more numbers). */
2963static char *
2964func_int_or (char *o, char **argv, const char *funcname)
2965{
2966 math_int num;
2967 int i;
2968
2969 num = math_int_from_string (argv[0]);
2970 for (i = 1; argv[i]; i++)
2971 num |= math_int_from_string (argv[i]);
2972
2973 return math_int_to_variable_buffer (o, num);
2974}
2975
2976/* Bitwise XOR (two or more numbers). */
2977static char *
2978func_int_xor (char *o, char **argv, const char *funcname)
2979{
2980 math_int num;
2981 int i;
2982
2983 num = math_int_from_string (argv[0]);
2984 for (i = 1; argv[i]; i++)
2985 num ^= math_int_from_string (argv[i]);
2986
2987 return math_int_to_variable_buffer (o, num);
2988}
2989
2990/* Compare two integer numbers. Returns make boolean (true="1"; false=""). */
2991static char *
2992func_int_cmp (char *o, char **argv, const char *funcname)
2993{
2994 math_int num1;
2995 math_int num2;
2996 int rc;
2997
2998 num1 = math_int_from_string (argv[0]);
2999 num2 = math_int_from_string (argv[1]);
3000
3001 funcname += sizeof ("int-") - 1;
3002 if (!strcmp (funcname, "eq"))
3003 rc = num1 == num2;
3004 else if (!strcmp (funcname, "ne"))
3005 rc = num1 != num2;
3006 else if (!strcmp (funcname, "gt"))
3007 rc = num1 > num2;
3008 else if (!strcmp (funcname, "ge"))
3009 rc = num1 >= num2;
3010 else if (!strcmp (funcname, "lt"))
3011 rc = num1 < num2;
3012 else /*if (!strcmp (funcname, "le"))*/
3013 rc = num1 <= num2;
3014
3015 return variable_buffer_output (o, rc ? "1" : "", rc);
3016}
3017
3018#endif /* CONFIG_WITH_MATH */
3019
3020#ifdef CONFIG_WITH_NANOTS
3021/* Returns the current timestamp as nano seconds. The time
3022 source is a high res monotone one if the platform provides
3023 this (and we know about it).
3024
3025 Tip. Use this with int-sub to profile makefile reading
3026 and similar. */
3027static char *
3028func_nanots (char *o, char **argv, const char *funcname)
3029{
3030 math_int ts;
3031
3032#if defined (WINDOWS32)
3033 static int s_state = -1;
3034 static LARGE_INTEGER s_freq;
3035
3036 if (s_state == -1)
3037 s_state = QueryPerformanceFrequency (&s_freq);
3038 if (s_state)
3039 {
3040 LARGE_INTEGER pc;
3041 if (!QueryPerformanceCounter (&pc))
3042 {
3043 s_state = 0;
3044 return func_nanots (o, argv, funcname);
3045 }
3046 ts = (math_int)((long double)pc.QuadPart / (long double)s_freq.QuadPart * 1000000000);
3047 }
3048 else
3049 {
3050 /* fall back to low resolution system time. */
3051 LARGE_INTEGER bigint;
3052 FILETIME ft = {0,0};
3053 GetSystemTimeAsFileTime (&ft);
3054 bigint.u.LowPart = ft.dwLowDateTime;
3055 bigint.u.HighPart = ft.dwLowDateTime;
3056 ts = bigint.QuadPart * 100;
3057 }
3058
3059/* FIXME: Linux and others has the realtime clock_* api, detect and use it. */
3060
3061#elif HAVE_GETTIMEOFDAY
3062 struct timeval tv;
3063 if (!gettimeofday (&tv, NULL))
3064 ts = (math_int)tv.tv_sec * 1000000000
3065 + tv.tv_usec * 1000;
3066 else
3067 {
3068 error (NILF, _("$(nanots): gettimeofday failed"));
3069 ts = 0;
3070 }
3071
3072#else
3073# error "PORTME"
3074#endif
3075
3076 return math_int_to_variable_buffer (o, ts);
3077}
3078#endif
3079
3080
3081/* Lookup table for builtin functions.
3082
3083 This doesn't have to be sorted; we use a straight lookup. We might gain
3084 some efficiency by moving most often used functions to the start of the
3085 table.
3086
3087 If MAXIMUM_ARGS is 0, that means there is no maximum and all
3088 comma-separated values are treated as arguments.
3089
3090 EXPAND_ARGS means that all arguments should be expanded before invocation.
3091 Functions that do namespace tricks (foreach) don't automatically expand. */
3092
3093static char *func_call (char *o, char **argv, const char *funcname);
3094
3095
3096static struct function_table_entry function_table_init[] =
3097{
3098 /* Name/size */ /* MIN MAX EXP? Function */
3099 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
3100 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
3101 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
3102 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
3103 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
3104 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
3105 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
3106 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
3107 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
3108 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
3109 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
3110 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
3111 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
3112 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
3113 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
3114 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
3115 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
3116#ifdef CONFIG_WITH_RSORT
3117 { STRING_SIZE_TUPLE("rsort"), 0, 1, 1, func_sort},
3118#endif
3119 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
3120 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
3121 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
3122 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
3123 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
3124 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
3125 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
3126 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
3127 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
3128 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
3129 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
3130 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
3131 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
3132 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
3133 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
3134 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
3135 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
3136 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
3137#ifdef EXPERIMENTAL
3138 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
3139 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
3140#endif
3141#ifdef CONFIG_WITH_TOUPPER_TOLOWER
3142 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower},
3143 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower},
3144#endif
3145#ifdef CONFIG_WITH_ABSPATHEX
3146 { STRING_SIZE_TUPLE("abspathex"), 0, 2, 1, func_abspathex},
3147#endif
3148#ifdef CONFIG_WITH_XARGS
3149 { STRING_SIZE_TUPLE("xargs"), 2, 0, 1, func_xargs},
3150#endif
3151#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
3152 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars},
3153 { STRING_SIZE_TUPLE("comp-cmds"), 3, 3, 1, func_comp_vars},
3154#endif
3155#ifdef CONFIG_WITH_STACK
3156 { STRING_SIZE_TUPLE("stack-push"), 2, 2, 1, func_stack_push},
3157 { STRING_SIZE_TUPLE("stack-pop"), 1, 1, 1, func_stack_pop_top},
3158 { STRING_SIZE_TUPLE("stack-popv"), 1, 1, 1, func_stack_pop_top},
3159 { STRING_SIZE_TUPLE("stack-top"), 1, 1, 1, func_stack_pop_top},
3160#endif
3161#ifdef CONFIG_WITH_MATH
3162 { STRING_SIZE_TUPLE("int-add"), 2, 0, 1, func_int_add},
3163 { STRING_SIZE_TUPLE("int-sub"), 2, 0, 1, func_int_sub},
3164 { STRING_SIZE_TUPLE("int-mul"), 2, 0, 1, func_int_mul},
3165 { STRING_SIZE_TUPLE("int-div"), 2, 0, 1, func_int_div},
3166 { STRING_SIZE_TUPLE("int-mod"), 2, 2, 1, func_int_mod},
3167 { STRING_SIZE_TUPLE("int-not"), 1, 1, 1, func_int_not},
3168 { STRING_SIZE_TUPLE("int-and"), 2, 0, 1, func_int_and},
3169 { STRING_SIZE_TUPLE("int-or"), 2, 0, 1, func_int_or},
3170 { STRING_SIZE_TUPLE("int-xor"), 2, 0, 1, func_int_xor},
3171 { STRING_SIZE_TUPLE("int-eq"), 2, 2, 1, func_int_cmp},
3172 { STRING_SIZE_TUPLE("int-ne"), 2, 2, 1, func_int_cmp},
3173 { STRING_SIZE_TUPLE("int-gt"), 2, 2, 1, func_int_cmp},
3174 { STRING_SIZE_TUPLE("int-ge"), 2, 2, 1, func_int_cmp},
3175 { STRING_SIZE_TUPLE("int-lt"), 2, 2, 1, func_int_cmp},
3176 { STRING_SIZE_TUPLE("int-le"), 2, 2, 1, func_int_cmp},
3177#endif
3178#ifdef CONFIG_WITH_NANOTS
3179 { STRING_SIZE_TUPLE("nanots"), 0, 0, 0, func_nanots},
3180#endif
3181#ifdef KMK_HELPERS
3182 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool},
3183 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base},
3184 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix},
3185 { STRING_SIZE_TUPLE("kb-src-prop"), 4, 4, 0, func_kbuild_source_prop},
3186 { STRING_SIZE_TUPLE("kb-src-one"), 0, 1, 0, func_kbuild_source_one},
3187#endif
3188};
3189
3190#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
3191
3192
3193
3194/* These must come after the definition of function_table. */
3195
3196static char *
3197expand_builtin_function (char *o, int argc, char **argv,
3198 const struct function_table_entry *entry_p)
3199{
3200 if (argc < (int)entry_p->minimum_args)
3201 fatal (*expanding_var,
3202 _("insufficient number of arguments (%d) to function `%s'"),
3203 argc, entry_p->name);
3204
3205 /* I suppose technically some function could do something with no
3206 arguments, but so far none do, so just test it for all functions here
3207 rather than in each one. We can change it later if necessary. */
3208
3209 if (!argc)
3210 return o;
3211
3212 if (!entry_p->func_ptr)
3213 fatal (*expanding_var,
3214 _("unimplemented on this platform: function `%s'"), entry_p->name);
3215
3216 return entry_p->func_ptr (o, argv, entry_p->name);
3217}
3218
3219/* Check for a function invocation in *STRINGP. *STRINGP points at the
3220 opening ( or { and is not null-terminated. If a function invocation
3221 is found, expand it into the buffer at *OP, updating *OP, incrementing
3222 *STRINGP past the reference and returning nonzero. If not, return zero. */
3223
3224static int
3225handle_function2 (const struct function_table_entry *entry_p, char **op, const char **stringp) /* bird split it up. */
3226{
3227 char openparen = (*stringp)[0];
3228 char closeparen = openparen == '(' ? ')' : '}';
3229 const char *beg;
3230 const char *end;
3231 int count = 0;
3232 char *abeg = NULL;
3233 char **argv, **argvp;
3234 int nargs;
3235
3236 beg = *stringp + 1;
3237
3238 /* We found a builtin function. Find the beginning of its arguments (skip
3239 whitespace after the name). */
3240
3241 beg = next_token (beg + entry_p->len);
3242
3243 /* Find the end of the function invocation, counting nested use of
3244 whichever kind of parens we use. Since we're looking, count commas
3245 to get a rough estimate of how many arguments we might have. The
3246 count might be high, but it'll never be low. */
3247
3248 for (nargs=1, end=beg; *end != '\0'; ++end)
3249 if (*end == ',')
3250 ++nargs;
3251 else if (*end == openparen)
3252 ++count;
3253 else if (*end == closeparen && --count < 0)
3254 break;
3255
3256 if (count >= 0)
3257 fatal (*expanding_var,
3258 _("unterminated call to function `%s': missing `%c'"),
3259 entry_p->name, closeparen);
3260
3261 *stringp = end;
3262
3263 /* Get some memory to store the arg pointers. */
3264 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
3265
3266 /* Chop the string into arguments, then a nul. As soon as we hit
3267 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
3268 last argument.
3269
3270 If we're expanding, store pointers to the expansion of each one. If
3271 not, make a duplicate of the string and point into that, nul-terminating
3272 each argument. */
3273
3274 if (entry_p->expand_args)
3275 {
3276 const char *p;
3277 for (p=beg, nargs=0; p <= end; ++argvp)
3278 {
3279 const char *next;
3280
3281 ++nargs;
3282
3283 if (nargs == entry_p->maximum_args
3284 || (! (next = find_next_argument (openparen, closeparen, p, end))))
3285 next = end;
3286
3287 *argvp = expand_argument (p, next);
3288 p = next + 1;
3289 }
3290 }
3291 else
3292 {
3293 int len = end - beg;
3294 char *p, *aend;
3295
3296 abeg = xmalloc (len+1);
3297 memcpy (abeg, beg, len);
3298 abeg[len] = '\0';
3299 aend = abeg + len;
3300
3301 for (p=abeg, nargs=0; p <= aend; ++argvp)
3302 {
3303 char *next;
3304
3305 ++nargs;
3306
3307 if (nargs == entry_p->maximum_args
3308 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
3309 next = aend;
3310
3311 *argvp = p;
3312 *next = '\0';
3313 p = next + 1;
3314 }
3315 }
3316 *argvp = NULL;
3317
3318 /* Finally! Run the function... */
3319 *op = expand_builtin_function (*op, nargs, argv, entry_p);
3320
3321 /* Free memory. */
3322 if (entry_p->expand_args)
3323 for (argvp=argv; *argvp != 0; ++argvp)
3324 free (*argvp);
3325 if (abeg)
3326 free (abeg);
3327
3328 return 1;
3329}
3330
3331int
3332handle_function (char **op, const char **stringp) /* bird split it up */
3333{
3334 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
3335 if (!entry_p)
3336 return 0;
3337 return handle_function2 (entry_p, op, stringp);
3338}
3339
3340
3341
3342/* User-defined functions. Expand the first argument as either a builtin
3343 function or a make variable, in the context of the rest of the arguments
3344 assigned to $1, $2, ... $N. $0 is the name of the function. */
3345
3346static char *
3347func_call (char *o, char **argv, const char *funcname UNUSED)
3348{
3349 static int max_args = 0;
3350 char *fname;
3351 char *cp;
3352 char *body;
3353 int flen;
3354 int i;
3355 int saved_args;
3356 const struct function_table_entry *entry_p;
3357 struct variable *v;
3358
3359 /* There is no way to define a variable with a space in the name, so strip
3360 leading and trailing whitespace as a favor to the user. */
3361 fname = argv[0];
3362 while (*fname != '\0' && isspace ((unsigned char)*fname))
3363 ++fname;
3364
3365 cp = fname + strlen (fname) - 1;
3366 while (cp > fname && isspace ((unsigned char)*cp))
3367 --cp;
3368 cp[1] = '\0';
3369
3370 /* Calling nothing is a no-op */
3371 if (*fname == '\0')
3372 return o;
3373
3374 /* Are we invoking a builtin function? */
3375
3376 entry_p = lookup_function (fname);
3377 if (entry_p)
3378 {
3379 /* How many arguments do we have? */
3380 for (i=0; argv[i+1]; ++i)
3381 ;
3382 return expand_builtin_function (o, i, argv+1, entry_p);
3383 }
3384
3385 /* Not a builtin, so the first argument is the name of a variable to be
3386 expanded and interpreted as a function. Find it. */
3387 flen = strlen (fname);
3388
3389 v = lookup_variable (fname, flen);
3390
3391 if (v == 0)
3392 warn_undefined (fname, flen);
3393
3394 if (v == 0 || *v->value == '\0')
3395 return o;
3396
3397 body = alloca (flen + 4);
3398 body[0] = '$';
3399 body[1] = '(';
3400 memcpy (body + 2, fname, flen);
3401 body[flen+2] = ')';
3402 body[flen+3] = '\0';
3403
3404 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
3405
3406 push_new_variable_scope ();
3407
3408 for (i=0; *argv; ++i, ++argv)
3409 {
3410 char num[11];
3411
3412 sprintf (num, "%d", i);
3413 define_variable (num, strlen (num), *argv, o_automatic, 0);
3414 }
3415
3416 /* If the number of arguments we have is < max_args, it means we're inside
3417 a recursive invocation of $(call ...). Fill in the remaining arguments
3418 in the new scope with the empty value, to hide them from this
3419 invocation. */
3420
3421 for (; i < max_args; ++i)
3422 {
3423 char num[11];
3424
3425 sprintf (num, "%d", i);
3426 define_variable (num, strlen (num), "", o_automatic, 0);
3427 }
3428
3429 /* Expand the body in the context of the arguments, adding the result to
3430 the variable buffer. */
3431
3432 v->exp_count = EXP_COUNT_MAX;
3433
3434 saved_args = max_args;
3435 max_args = i;
3436 o = variable_expand_string (o, body, flen+3);
3437 max_args = saved_args;
3438
3439 v->exp_count = 0;
3440
3441 pop_variable_scope ();
3442
3443 return o + strlen (o);
3444}
3445
3446void
3447hash_init_function_table (void)
3448{
3449 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
3450 function_table_entry_hash_1, function_table_entry_hash_2,
3451 function_table_entry_hash_cmp);
3452 hash_load (&function_table, function_table_init,
3453 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
3454#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
3455 {
3456 unsigned i;
3457 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
3458 assert (function_table_init[i].len <= MAX_FUNCTION_LENGTH);
3459 }
3460#endif
3461}
Note: See TracBrowser for help on using the repository browser.

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