source: trunk/src/gmake/function.c@ 898

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

Visual C++ 2005 fix.

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