VirtualBox

source: kBuild/trunk/src/gmakenew/function.c@ 907

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

Fixed rsort bug.

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