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

Last change on this file since 530 was 530, checked in by bird, 19 years ago

Added kBuild specific functions for speeding up source processing.

  • Property svn:eol-style set to native
File size: 63.6 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
39# include "kbuild.h"
40#endif
41
42
43struct function_table_entry
44 {
45 const char *name;
46 unsigned char len;
47 unsigned char minimum_args;
48 unsigned char maximum_args;
49 char expand_args;
50 char *(*func_ptr) PARAMS ((char *output, char **argv, const char *fname));
51 };
52
53static unsigned long
54function_table_entry_hash_1 (const void *keyv)
55{
56 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
57 return_STRING_N_HASH_1 (key->name, key->len);
58}
59
60static unsigned long
61function_table_entry_hash_2 (const void *keyv)
62{
63 struct function_table_entry const *key = (struct function_table_entry const *) keyv;
64 return_STRING_N_HASH_2 (key->name, key->len);
65}
66
67static int
68function_table_entry_hash_cmp (const void *xv, const void *yv)
69{
70 struct function_table_entry const *x = (struct function_table_entry const *) xv;
71 struct function_table_entry const *y = (struct function_table_entry const *) yv;
72 int result = x->len - y->len;
73 if (result)
74 return result;
75 return_STRING_N_COMPARE (x->name, y->name, x->len);
76}
77
78static struct hash_table function_table;
79
80
81
82/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
83 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
84 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
85 nonzero, substitutions are done only on matches which are complete
86 whitespace-delimited words. */
87
88char *
89subst_expand (char *o, char *text, char *subst, char *replace,
90 unsigned int slen, unsigned int rlen, int by_word)
91{
92 char *t = text;
93 char *p;
94
95 if (slen == 0 && !by_word)
96 {
97 /* The first occurrence of "" in any string is its end. */
98 o = variable_buffer_output (o, t, strlen (t));
99 if (rlen > 0)
100 o = variable_buffer_output (o, replace, rlen);
101 return o;
102 }
103
104 do
105 {
106 if (by_word && slen == 0)
107 /* When matching by words, the empty string should match
108 the end of each word, rather than the end of the whole text. */
109 p = end_of_token (next_token (t));
110 else
111 {
112 p = strstr (t, subst);
113 if (p == 0)
114 {
115 /* No more matches. Output everything left on the end. */
116 o = variable_buffer_output (o, t, strlen (t));
117 return o;
118 }
119 }
120
121 /* Output everything before this occurrence of the string to replace. */
122 if (p > t)
123 o = variable_buffer_output (o, t, p - t);
124
125 /* If we're substituting only by fully matched words,
126 or only at the ends of words, check that this case qualifies. */
127 if (by_word
128 && ((p > text && !isblank ((unsigned char)p[-1]))
129 || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
130 /* Struck out. Output the rest of the string that is
131 no longer to be replaced. */
132 o = variable_buffer_output (o, subst, slen);
133 else if (rlen > 0)
134 /* Output the replacement string. */
135 o = variable_buffer_output (o, replace, rlen);
136
137 /* Advance T past the string to be replaced. */
138 {
139 char *nt = p + slen;
140 t = nt;
141 }
142 } while (*t != '\0');
143
144 return o;
145}
146
147
148
149/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
150 and replacing strings matching PATTERN with REPLACE.
151 If PATTERN_PERCENT is not nil, PATTERN has already been
152 run through find_percent, and PATTERN_PERCENT is the result.
153 If REPLACE_PERCENT is not nil, REPLACE has already been
154 run through find_percent, and REPLACE_PERCENT is the result.
155 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
156 character _AFTER_ the %, not to the % itself.
157*/
158
159char *
160patsubst_expand (char *o, char *text, char *pattern, char *replace,
161 char *pattern_percent, char *replace_percent)
162{
163 unsigned int pattern_prepercent_len, pattern_postpercent_len;
164 unsigned int replace_prepercent_len, replace_postpercent_len;
165 char *t;
166 unsigned int len;
167 int doneany = 0;
168
169 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
170 will be collapsed before we call subst_expand if PATTERN has no %. */
171 if (!replace_percent)
172 {
173 replace_percent = find_percent (replace);
174 if (replace_percent)
175 ++replace_percent;
176 }
177
178 /* Record the length of REPLACE before and after the % so we don't have to
179 compute these lengths more than once. */
180 if (replace_percent)
181 {
182 replace_prepercent_len = replace_percent - replace - 1;
183 replace_postpercent_len = strlen (replace_percent);
184 }
185 else
186 {
187 replace_prepercent_len = strlen (replace);
188 replace_postpercent_len = 0;
189 }
190
191 if (!pattern_percent)
192 {
193 pattern_percent = find_percent (pattern);
194 if (pattern_percent)
195 ++pattern_percent;
196 }
197 if (!pattern_percent)
198 /* With no % in the pattern, this is just a simple substitution. */
199 return subst_expand (o, text, pattern, replace,
200 strlen (pattern), strlen (replace), 1);
201
202 /* Record the length of PATTERN before and after the %
203 so we don't have to compute it more than once. */
204 pattern_prepercent_len = pattern_percent - pattern - 1;
205 pattern_postpercent_len = strlen (pattern_percent);
206
207 while ((t = find_next_token (&text, &len)) != 0)
208 {
209 int fail = 0;
210
211 /* Is it big enough to match? */
212 if (len < pattern_prepercent_len + pattern_postpercent_len)
213 fail = 1;
214
215 /* Does the prefix match? */
216 if (!fail && pattern_prepercent_len > 0
217 && (*t != *pattern
218 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
219 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
220 fail = 1;
221
222 /* Does the suffix match? */
223 if (!fail && pattern_postpercent_len > 0
224 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
225 || t[len - pattern_postpercent_len] != *pattern_percent
226 || !strneq (&t[len - pattern_postpercent_len],
227 pattern_percent, pattern_postpercent_len - 1)))
228 fail = 1;
229
230 if (fail)
231 /* It didn't match. Output the string. */
232 o = variable_buffer_output (o, t, len);
233 else
234 {
235 /* It matched. Output the replacement. */
236
237 /* Output the part of the replacement before the %. */
238 o = variable_buffer_output (o, replace, replace_prepercent_len);
239
240 if (replace_percent != 0)
241 {
242 /* Output the part of the matched string that
243 matched the % in the pattern. */
244 o = variable_buffer_output (o, t + pattern_prepercent_len,
245 len - (pattern_prepercent_len
246 + pattern_postpercent_len));
247 /* Output the part of the replacement after the %. */
248 o = variable_buffer_output (o, replace_percent,
249 replace_postpercent_len);
250 }
251 }
252
253 /* Output a space, but not if the replacement is "". */
254 if (fail || replace_prepercent_len > 0
255 || (replace_percent != 0 && len + replace_postpercent_len > 0))
256 {
257 o = variable_buffer_output (o, " ", 1);
258 doneany = 1;
259 }
260 }
261 if (doneany)
262 /* Kill the last space. */
263 --o;
264
265 return o;
266}
267
268
269#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
270/* The maximum length of a function, once reached there is
271 it can't be function and we can skip the hash lookup drop out. */
272
273#ifdef KMK
274# define MAX_FUNCTION_LENGTH 12
275#else
276# define MAX_FUNCTION_LENGTH 10
277#endif
278
279/* Look up a function by name. */
280__inline
281#endif /* CONFIG_WITH_OPTIMIZATION_HACKS */
282static const struct function_table_entry *
283lookup_function (const char *s)
284{
285 const char *e = s;
286#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
287 int left = MAX_FUNCTION_LENGTH;
288 int ch;
289 while (((ch = *e) >= 'a' && ch <='z') || ch == '-')
290 {
291 if (!left--)
292 return 0;
293 e++;
294 }
295#else
296 while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
297 e++;
298#endif
299 if (*e == '\0' || isblank ((unsigned char) *e))
300 {
301 struct function_table_entry function_table_entry_key;
302 function_table_entry_key.name = s;
303 function_table_entry_key.len = e - s;
304
305 return hash_find_item (&function_table, &function_table_entry_key);
306 }
307 return 0;
308}
309
310
311
312/* Return 1 if PATTERN matches STR, 0 if not. */
313
314int
315pattern_matches (char *pattern, char *percent, char *str)
316{
317 unsigned int sfxlen, strlength;
318
319 if (percent == 0)
320 {
321 unsigned int len = strlen (pattern) + 1;
322 char *new_chars = (char *) alloca (len);
323 bcopy (pattern, new_chars, len);
324 pattern = new_chars;
325 percent = find_percent (pattern);
326 if (percent == 0)
327 return streq (pattern, str);
328 }
329
330 sfxlen = strlen (percent + 1);
331 strlength = strlen (str);
332
333 if (strlength < (percent - pattern) + sfxlen
334 || !strneq (pattern, str, percent - pattern))
335 return 0;
336
337 return !strcmp (percent + 1, str + (strlength - sfxlen));
338}
339
340
341
342/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
343 ENDPARENtheses), starting at PTR before END. Return a pointer to
344 next character.
345
346 If no next argument is found, return NULL.
347*/
348
349static char *
350find_next_argument (char startparen, char endparen,
351 const char *ptr, const char *end)
352{
353 int count = 0;
354
355 for (; ptr < end; ++ptr)
356 if (*ptr == startparen)
357 ++count;
358
359 else if (*ptr == endparen)
360 {
361 --count;
362 if (count < 0)
363 return NULL;
364 }
365
366 else if (*ptr == ',' && !count)
367 return (char *)ptr;
368
369 /* We didn't find anything. */
370 return NULL;
371}
372
373
374
375/* Glob-expand LINE. The returned pointer is
376 only good until the next call to string_glob. */
377
378static char *
379string_glob (char *line)
380{
381 static char *result = 0;
382 static unsigned int length;
383 register struct nameseq *chain;
384 register unsigned int idx;
385
386 chain = multi_glob (parse_file_seq
387 (&line, '\0', sizeof (struct nameseq),
388 /* We do not want parse_file_seq to strip `./'s.
389 That would break examples like:
390 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
391 0),
392 sizeof (struct nameseq));
393
394 if (result == 0)
395 {
396 length = 100;
397 result = (char *) xmalloc (100);
398 }
399
400 idx = 0;
401 while (chain != 0)
402 {
403 register char *name = chain->name;
404 unsigned int len = strlen (name);
405
406 struct nameseq *next = chain->next;
407 free ((char *) chain);
408 chain = next;
409
410 /* multi_glob will pass names without globbing metacharacters
411 through as is, but we want only files that actually exist. */
412 if (file_exists_p (name))
413 {
414 if (idx + len + 1 > length)
415 {
416 length += (len + 1) * 2;
417 result = (char *) xrealloc (result, length);
418 }
419 bcopy (name, &result[idx], len);
420 idx += len;
421 result[idx++] = ' ';
422 }
423
424 free (name);
425 }
426
427 /* Kill the last space and terminate the string. */
428 if (idx == 0)
429 result[0] = '\0';
430 else
431 result[idx - 1] = '\0';
432
433 return result;
434}
435
436
437/*
438 Builtin functions
439 */
440
441static char *
442func_patsubst (char *o, char **argv, const char *funcname UNUSED)
443{
444 o = patsubst_expand (o, argv[2], argv[0], argv[1], (char *) 0, (char *) 0);
445 return o;
446}
447
448
449static char *
450func_join (char *o, char **argv, const char *funcname UNUSED)
451{
452 int doneany = 0;
453
454 /* Write each word of the first argument directly followed
455 by the corresponding word of the second argument.
456 If the two arguments have a different number of words,
457 the excess words are just output separated by blanks. */
458 register char *tp;
459 register char *pp;
460 char *list1_iterator = argv[0];
461 char *list2_iterator = argv[1];
462 do
463 {
464 unsigned int len1, len2;
465
466 tp = find_next_token (&list1_iterator, &len1);
467 if (tp != 0)
468 o = variable_buffer_output (o, tp, len1);
469
470 pp = find_next_token (&list2_iterator, &len2);
471 if (pp != 0)
472 o = variable_buffer_output (o, pp, len2);
473
474 if (tp != 0 || pp != 0)
475 {
476 o = variable_buffer_output (o, " ", 1);
477 doneany = 1;
478 }
479 }
480 while (tp != 0 || pp != 0);
481 if (doneany)
482 /* Kill the last blank. */
483 --o;
484
485 return o;
486}
487
488
489static char *
490func_origin (char *o, char **argv, const char *funcname UNUSED)
491{
492 /* Expand the argument. */
493 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
494 if (v == 0)
495 o = variable_buffer_output (o, "undefined", 9);
496 else
497 switch (v->origin)
498 {
499 default:
500 case o_invalid:
501 abort ();
502 break;
503 case o_default:
504 o = variable_buffer_output (o, "default", 7);
505 break;
506 case o_env:
507 o = variable_buffer_output (o, "environment", 11);
508 break;
509 case o_file:
510 o = variable_buffer_output (o, "file", 4);
511 break;
512 case o_env_override:
513 o = variable_buffer_output (o, "environment override", 20);
514 break;
515 case o_command:
516 o = variable_buffer_output (o, "command line", 12);
517 break;
518 case o_override:
519 o = variable_buffer_output (o, "override", 8);
520 break;
521 case o_automatic:
522 o = variable_buffer_output (o, "automatic", 9);
523 break;
524 }
525
526 return o;
527}
528
529static char *
530func_flavor (char *o, char **argv, const char *funcname UNUSED)
531{
532 register struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
533
534 if (v == 0)
535 o = variable_buffer_output (o, "undefined", 9);
536 else
537 if (v->recursive)
538 o = variable_buffer_output (o, "recursive", 9);
539 else
540 o = variable_buffer_output (o, "simple", 6);
541
542 return o;
543}
544
545#ifdef VMS
546# define IS_PATHSEP(c) ((c) == ']')
547#else
548# ifdef HAVE_DOS_PATHS
549# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
550# else
551# define IS_PATHSEP(c) ((c) == '/')
552# endif
553#endif
554
555
556static char *
557func_notdir_suffix (char *o, char **argv, const char *funcname)
558{
559 /* Expand the argument. */
560 char *list_iterator = argv[0];
561 char *p2 =0;
562 int doneany =0;
563 unsigned int len=0;
564
565 int is_suffix = streq (funcname, "suffix");
566 int is_notdir = !is_suffix;
567 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
568 {
569 char *p = p2 + len;
570
571
572 while (p >= p2 && (!is_suffix || *p != '.'))
573 {
574 if (IS_PATHSEP (*p))
575 break;
576 --p;
577 }
578
579 if (p >= p2)
580 {
581 if (is_notdir)
582 ++p;
583 else if (*p != '.')
584 continue;
585 o = variable_buffer_output (o, p, len - (p - p2));
586 }
587#ifdef HAVE_DOS_PATHS
588 /* Handle the case of "d:foo/bar". */
589 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
590 {
591 p = p2 + 2;
592 o = variable_buffer_output (o, p, len - (p - p2));
593 }
594#endif
595 else if (is_notdir)
596 o = variable_buffer_output (o, p2, len);
597
598 if (is_notdir || p >= p2)
599 {
600 o = variable_buffer_output (o, " ", 1);
601 doneany = 1;
602 }
603 }
604 if (doneany)
605 /* Kill last space. */
606 --o;
607
608
609 return o;
610
611}
612
613
614static char *
615func_basename_dir (char *o, char **argv, const char *funcname)
616{
617 /* Expand the argument. */
618 char *p3 = argv[0];
619 char *p2=0;
620 int doneany=0;
621 unsigned int len=0;
622 char *p=0;
623 int is_basename= streq (funcname, "basename");
624 int is_dir= !is_basename;
625
626 while ((p2 = find_next_token (&p3, &len)) != 0)
627 {
628 p = p2 + len;
629 while (p >= p2 && (!is_basename || *p != '.'))
630 {
631 if (IS_PATHSEP (*p))
632 break;
633 --p;
634 }
635
636 if (p >= p2 && (is_dir))
637 o = variable_buffer_output (o, p2, ++p - p2);
638 else if (p >= p2 && (*p == '.'))
639 o = variable_buffer_output (o, p2, p - p2);
640#ifdef HAVE_DOS_PATHS
641 /* Handle the "d:foobar" case */
642 else if (p2[0] && p2[1] == ':' && is_dir)
643 o = variable_buffer_output (o, p2, 2);
644#endif
645 else if (is_dir)
646#ifdef VMS
647 o = variable_buffer_output (o, "[]", 2);
648#else
649#ifndef _AMIGA
650 o = variable_buffer_output (o, "./", 2);
651#else
652 ; /* Just a nop... */
653#endif /* AMIGA */
654#endif /* !VMS */
655 else
656 /* The entire name is the basename. */
657 o = variable_buffer_output (o, p2, len);
658
659 o = variable_buffer_output (o, " ", 1);
660 doneany = 1;
661 }
662 if (doneany)
663 /* Kill last space. */
664 --o;
665
666
667 return o;
668}
669
670static char *
671func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
672{
673 int fixlen = strlen (argv[0]);
674 char *list_iterator = argv[1];
675 int is_addprefix = streq (funcname, "addprefix");
676 int is_addsuffix = !is_addprefix;
677
678 int doneany = 0;
679 char *p;
680 unsigned int len;
681
682 while ((p = find_next_token (&list_iterator, &len)) != 0)
683 {
684 if (is_addprefix)
685 o = variable_buffer_output (o, argv[0], fixlen);
686 o = variable_buffer_output (o, p, len);
687 if (is_addsuffix)
688 o = variable_buffer_output (o, argv[0], fixlen);
689 o = variable_buffer_output (o, " ", 1);
690 doneany = 1;
691 }
692
693 if (doneany)
694 /* Kill last space. */
695 --o;
696
697 return o;
698}
699
700static char *
701func_subst (char *o, char **argv, const char *funcname UNUSED)
702{
703 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
704 strlen (argv[1]), 0);
705
706 return o;
707}
708
709
710static char *
711func_firstword (char *o, char **argv, const char *funcname UNUSED)
712{
713 unsigned int i;
714 char *words = argv[0]; /* Use a temp variable for find_next_token */
715 char *p = find_next_token (&words, &i);
716
717 if (p != 0)
718 o = variable_buffer_output (o, p, i);
719
720 return o;
721}
722
723static char *
724func_lastword (char *o, char **argv, const char *funcname UNUSED)
725{
726 unsigned int i;
727 char *words = argv[0]; /* Use a temp variable for find_next_token */
728 char *p = 0;
729 char *t;
730
731 while ((t = find_next_token (&words, &i)))
732 p = t;
733
734 if (p != 0)
735 o = variable_buffer_output (o, p, i);
736
737 return o;
738}
739
740static char *
741func_words (char *o, char **argv, const char *funcname UNUSED)
742{
743 int i = 0;
744 char *word_iterator = argv[0];
745 char buf[20];
746
747 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
748 ++i;
749
750 sprintf (buf, "%d", i);
751 o = variable_buffer_output (o, buf, strlen (buf));
752
753
754 return o;
755}
756
757/* Set begpp to point to the first non-whitespace character of the string,
758 * and endpp to point to the last non-whitespace character of the string.
759 * If the string is empty or contains nothing but whitespace, endpp will be
760 * begpp-1.
761 */
762char *
763strip_whitespace (const char **begpp, const char **endpp)
764{
765 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
766 (*begpp) ++;
767 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
768 (*endpp) --;
769 return (char *)*begpp;
770}
771
772static void
773check_numeric (const char *s, const char *message)
774{
775 const char *end = s + strlen (s) - 1;
776 const char *beg = s;
777 strip_whitespace (&s, &end);
778
779 for (; s <= end; ++s)
780 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
781 break;
782
783 if (s <= end || end - beg < 0)
784 fatal (*expanding_var, "%s: '%s'", message, beg);
785}
786
787
788
789static char *
790func_word (char *o, char **argv, const char *funcname UNUSED)
791{
792 char *end_p=0;
793 int i=0;
794 char *p=0;
795
796 /* Check the first argument. */
797 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
798 i = atoi (argv[0]);
799
800 if (i == 0)
801 fatal (*expanding_var,
802 _("first argument to `word' function must be greater than 0"));
803
804
805 end_p = argv[1];
806 while ((p = find_next_token (&end_p, 0)) != 0)
807 if (--i == 0)
808 break;
809
810 if (i == 0)
811 o = variable_buffer_output (o, p, end_p - p);
812
813 return o;
814}
815
816static char *
817func_wordlist (char *o, char **argv, const char *funcname UNUSED)
818{
819 int start, count;
820
821 /* Check the arguments. */
822 check_numeric (argv[0],
823 _("non-numeric first argument to `wordlist' function"));
824 check_numeric (argv[1],
825 _("non-numeric second argument to `wordlist' function"));
826
827 start = atoi (argv[0]);
828 if (start < 1)
829 fatal (*expanding_var,
830 "invalid first argument to `wordlist' function: `%d'", start);
831
832 count = atoi (argv[1]) - start + 1;
833
834 if (count > 0)
835 {
836 char *p;
837 char *end_p = argv[2];
838
839 /* Find the beginning of the "start"th word. */
840 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
841 ;
842
843 if (p)
844 {
845 /* Find the end of the "count"th word from start. */
846 while (--count && (find_next_token (&end_p, 0) != 0))
847 ;
848
849 /* Return the stuff in the middle. */
850 o = variable_buffer_output (o, p, end_p - p);
851 }
852 }
853
854 return o;
855}
856
857static char*
858func_findstring (char *o, char **argv, const char *funcname UNUSED)
859{
860 /* Find the first occurrence of the first string in the second. */
861 if (strstr (argv[1], argv[0]) != 0)
862 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
863
864 return o;
865}
866
867static char *
868func_foreach (char *o, char **argv, const char *funcname UNUSED)
869{
870 /* expand only the first two. */
871 char *varname = expand_argument (argv[0], NULL);
872 char *list = expand_argument (argv[1], NULL);
873 char *body = argv[2];
874
875 int doneany = 0;
876 char *list_iterator = list;
877 char *p;
878 unsigned int len;
879 register struct variable *var;
880
881 push_new_variable_scope ();
882 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
883
884 /* loop through LIST, put the value in VAR and expand BODY */
885 while ((p = find_next_token (&list_iterator, &len)) != 0)
886 {
887 char *result = 0;
888
889 {
890 char save = p[len];
891
892 p[len] = '\0';
893 free (var->value);
894 var->value = (char *) xstrdup ((char*) p);
895 p[len] = save;
896 }
897
898 result = allocated_variable_expand (body);
899
900 o = variable_buffer_output (o, result, strlen (result));
901 o = variable_buffer_output (o, " ", 1);
902 doneany = 1;
903 free (result);
904 }
905
906 if (doneany)
907 /* Kill the last space. */
908 --o;
909
910 pop_variable_scope ();
911 free (varname);
912 free (list);
913
914 return o;
915}
916
917struct a_word
918{
919 struct a_word *next;
920 struct a_word *chain;
921 char *str;
922 int length;
923 int matched;
924};
925
926static unsigned long
927a_word_hash_1 (const void *key)
928{
929 return_STRING_HASH_1 (((struct a_word const *) key)->str);
930}
931
932static unsigned long
933a_word_hash_2 (const void *key)
934{
935 return_STRING_HASH_2 (((struct a_word const *) key)->str);
936}
937
938static int
939a_word_hash_cmp (const void *x, const void *y)
940{
941 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
942 if (result)
943 return result;
944 return_STRING_COMPARE (((struct a_word const *) x)->str,
945 ((struct a_word const *) y)->str);
946}
947
948struct a_pattern
949{
950 struct a_pattern *next;
951 char *str;
952 char *percent;
953 int length;
954 int save_c;
955};
956
957static char *
958func_filter_filterout (char *o, char **argv, const char *funcname)
959{
960 struct a_word *wordhead;
961 struct a_word **wordtail;
962 struct a_word *wp;
963 struct a_pattern *pathead;
964 struct a_pattern **pattail;
965 struct a_pattern *pp;
966
967 struct hash_table a_word_table;
968 int is_filter = streq (funcname, "filter");
969 char *pat_iterator = argv[0];
970 char *word_iterator = argv[1];
971 int literals = 0;
972 int words = 0;
973 int hashing = 0;
974 char *p;
975 unsigned int len;
976
977 /* Chop ARGV[0] up into patterns to match against the words. */
978
979 pattail = &pathead;
980 while ((p = find_next_token (&pat_iterator, &len)) != 0)
981 {
982 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
983
984 *pattail = pat;
985 pattail = &pat->next;
986
987 if (*pat_iterator != '\0')
988 ++pat_iterator;
989
990 pat->str = p;
991 pat->length = len;
992 pat->save_c = p[len];
993 p[len] = '\0';
994 pat->percent = find_percent (p);
995 if (pat->percent == 0)
996 literals++;
997 }
998 *pattail = 0;
999
1000 /* Chop ARGV[1] up into words to match against the patterns. */
1001
1002 wordtail = &wordhead;
1003 while ((p = find_next_token (&word_iterator, &len)) != 0)
1004 {
1005 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
1006
1007 *wordtail = word;
1008 wordtail = &word->next;
1009
1010 if (*word_iterator != '\0')
1011 ++word_iterator;
1012
1013 p[len] = '\0';
1014 word->str = p;
1015 word->length = len;
1016 word->matched = 0;
1017 word->chain = 0;
1018 words++;
1019 }
1020 *wordtail = 0;
1021
1022 /* Only use a hash table if arg list lengths justifies the cost. */
1023 hashing = (literals >= 2 && (literals * words) >= 10);
1024 if (hashing)
1025 {
1026 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
1027 for (wp = wordhead; wp != 0; wp = wp->next)
1028 {
1029 struct a_word *owp = hash_insert (&a_word_table, wp);
1030 if (owp)
1031 wp->chain = owp;
1032 }
1033 }
1034
1035 if (words)
1036 {
1037 int doneany = 0;
1038
1039 /* Run each pattern through the words, killing words. */
1040 for (pp = pathead; pp != 0; pp = pp->next)
1041 {
1042 if (pp->percent)
1043 for (wp = wordhead; wp != 0; wp = wp->next)
1044 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1045 else if (hashing)
1046 {
1047 struct a_word a_word_key;
1048 a_word_key.str = pp->str;
1049 a_word_key.length = pp->length;
1050 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1051 while (wp)
1052 {
1053 wp->matched |= 1;
1054 wp = wp->chain;
1055 }
1056 }
1057 else
1058 for (wp = wordhead; wp != 0; wp = wp->next)
1059 wp->matched |= (wp->length == pp->length
1060 && strneq (pp->str, wp->str, wp->length));
1061 }
1062
1063 /* Output the words that matched (or didn't, for filter-out). */
1064 for (wp = wordhead; wp != 0; wp = wp->next)
1065 if (is_filter ? wp->matched : !wp->matched)
1066 {
1067 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1068 o = variable_buffer_output (o, " ", 1);
1069 doneany = 1;
1070 }
1071
1072 if (doneany)
1073 /* Kill the last space. */
1074 --o;
1075 }
1076
1077 for (pp = pathead; pp != 0; pp = pp->next)
1078 pp->str[pp->length] = pp->save_c;
1079
1080 if (hashing)
1081 hash_free (&a_word_table, 0);
1082
1083 return o;
1084}
1085
1086
1087static char *
1088func_strip (char *o, char **argv, const char *funcname UNUSED)
1089{
1090 char *p = argv[0];
1091 int doneany =0;
1092
1093 while (*p != '\0')
1094 {
1095 int i=0;
1096 char *word_start=0;
1097
1098 while (isspace ((unsigned char)*p))
1099 ++p;
1100 word_start = p;
1101 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1102 {}
1103 if (!i)
1104 break;
1105 o = variable_buffer_output (o, word_start, i);
1106 o = variable_buffer_output (o, " ", 1);
1107 doneany = 1;
1108 }
1109
1110 if (doneany)
1111 /* Kill the last space. */
1112 --o;
1113 return o;
1114}
1115
1116/*
1117 Print a warning or fatal message.
1118*/
1119static char *
1120func_error (char *o, char **argv, const char *funcname)
1121{
1122 char **argvp;
1123 char *msg, *p;
1124 int len;
1125
1126 /* The arguments will be broken on commas. Rather than create yet
1127 another special case where function arguments aren't broken up,
1128 just create a format string that puts them back together. */
1129 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1130 len += strlen (*argvp) + 2;
1131
1132 p = msg = (char *) alloca (len + 1);
1133
1134 for (argvp=argv; argvp[1] != 0; ++argvp)
1135 {
1136 strcpy (p, *argvp);
1137 p += strlen (*argvp);
1138 *(p++) = ',';
1139 *(p++) = ' ';
1140 }
1141 strcpy (p, *argvp);
1142
1143 switch (*funcname) {
1144 case 'e':
1145 fatal (reading_file, "%s", msg);
1146
1147 case 'w':
1148 error (reading_file, "%s", msg);
1149 break;
1150
1151 case 'i':
1152 printf ("%s\n", msg);
1153 fflush(stdout);
1154 break;
1155
1156 default:
1157 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1158 }
1159
1160 /* The warning function expands to the empty string. */
1161 return o;
1162}
1163
1164
1165/*
1166 chop argv[0] into words, and sort them.
1167 */
1168static char *
1169func_sort (char *o, char **argv, const char *funcname UNUSED)
1170{
1171 char **words = 0;
1172 int nwords = 0;
1173 register int wordi = 0;
1174
1175 /* Chop ARGV[0] into words and put them in WORDS. */
1176 char *t = argv[0];
1177 char *p;
1178 unsigned int len;
1179 int i;
1180
1181 while ((p = find_next_token (&t, &len)) != 0)
1182 {
1183 if (wordi >= nwords - 1)
1184 {
1185 nwords = (2 * nwords) + 5;
1186 words = (char **) xrealloc ((char *) words,
1187 nwords * sizeof (char *));
1188 }
1189 words[wordi++] = savestring (p, len);
1190 }
1191
1192 if (!wordi)
1193 return o;
1194
1195 /* Now sort the list of words. */
1196 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1197
1198 /* Now write the sorted list. */
1199 for (i = 0; i < wordi; ++i)
1200 {
1201 len = strlen (words[i]);
1202 if (i == wordi - 1 || strlen (words[i + 1]) != len
1203 || strcmp (words[i], words[i + 1]))
1204 {
1205 o = variable_buffer_output (o, words[i], len);
1206 o = variable_buffer_output (o, " ", 1);
1207 }
1208 free (words[i]);
1209 }
1210 /* Kill the last space. */
1211 --o;
1212
1213 free (words);
1214
1215 return o;
1216}
1217
1218/*
1219 $(if condition,true-part[,false-part])
1220
1221 CONDITION is false iff it evaluates to an empty string. White
1222 space before and after condition are stripped before evaluation.
1223
1224 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1225 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1226 you can use $(if ...) to create side-effects (with $(shell ...), for
1227 example).
1228*/
1229
1230static char *
1231func_if (char *o, char **argv, const char *funcname UNUSED)
1232{
1233 const char *begp = argv[0];
1234 const char *endp = begp + strlen (argv[0]) - 1;
1235 int result = 0;
1236
1237 /* Find the result of the condition: if we have a value, and it's not
1238 empty, the condition is true. If we don't have a value, or it's the
1239 empty string, then it's false. */
1240
1241 strip_whitespace (&begp, &endp);
1242
1243 if (begp <= endp)
1244 {
1245 char *expansion = expand_argument (begp, endp+1);
1246
1247 result = strlen (expansion);
1248 free (expansion);
1249 }
1250
1251 /* If the result is true (1) we want to eval the first argument, and if
1252 it's false (0) we want to eval the second. If the argument doesn't
1253 exist we do nothing, otherwise expand it and add to the buffer. */
1254
1255 argv += 1 + !result;
1256
1257 if (argv[0])
1258 {
1259 char *expansion;
1260
1261 expansion = expand_argument (argv[0], NULL);
1262
1263 o = variable_buffer_output (o, expansion, strlen (expansion));
1264
1265 free (expansion);
1266 }
1267
1268 return o;
1269}
1270
1271/*
1272 $(or condition1[,condition2[,condition3[...]]])
1273
1274 A CONDITION is false iff it evaluates to an empty string. White
1275 space before and after CONDITION are stripped before evaluation.
1276
1277 CONDITION1 is evaluated. If it's true, then this is the result of
1278 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1279 the conditions are true, the expansion is the empty string.
1280
1281 Once a CONDITION is true no further conditions are evaluated
1282 (short-circuiting).
1283*/
1284
1285static char *
1286func_or (char *o, char **argv, const char *funcname UNUSED)
1287{
1288 for ( ; *argv ; ++argv)
1289 {
1290 const char *begp = *argv;
1291 const char *endp = begp + strlen (*argv) - 1;
1292 char *expansion;
1293 int result = 0;
1294
1295 /* Find the result of the condition: if it's false keep going. */
1296
1297 strip_whitespace (&begp, &endp);
1298
1299 if (begp > endp)
1300 continue;
1301
1302 expansion = expand_argument (begp, endp+1);
1303 result = strlen (expansion);
1304
1305 /* If the result is false keep going. */
1306 if (!result)
1307 {
1308 free (expansion);
1309 continue;
1310 }
1311
1312 /* It's true! Keep this result and return. */
1313 o = variable_buffer_output (o, expansion, result);
1314 free (expansion);
1315 break;
1316 }
1317
1318 return o;
1319}
1320
1321/*
1322 $(and condition1[,condition2[,condition3[...]]])
1323
1324 A CONDITION is false iff it evaluates to an empty string. White
1325 space before and after CONDITION are stripped before evaluation.
1326
1327 CONDITION1 is evaluated. If it's false, then this is the result of
1328 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1329 the conditions are true, the expansion is the result of the last condition.
1330
1331 Once a CONDITION is false no further conditions are evaluated
1332 (short-circuiting).
1333*/
1334
1335static char *
1336func_and (char *o, char **argv, const char *funcname UNUSED)
1337{
1338 char *expansion;
1339 int result;
1340
1341 while (1)
1342 {
1343 const char *begp = *argv;
1344 const char *endp = begp + strlen (*argv) - 1;
1345
1346 /* An empty condition is always false. */
1347 strip_whitespace (&begp, &endp);
1348 if (begp > endp)
1349 return o;
1350
1351 expansion = expand_argument (begp, endp+1);
1352 result = strlen (expansion);
1353
1354 /* If the result is false, stop here: we're done. */
1355 if (!result)
1356 break;
1357
1358 /* Otherwise the result is true. If this is the last one, keep this
1359 result and quit. Otherwise go on to the next one! */
1360
1361 if (*(++argv))
1362 free (expansion);
1363 else
1364 {
1365 o = variable_buffer_output (o, expansion, result);
1366 break;
1367 }
1368 }
1369
1370 free (expansion);
1371
1372 return o;
1373}
1374
1375static char *
1376func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1377{
1378
1379#ifdef _AMIGA
1380 o = wildcard_expansion (argv[0], o);
1381#else
1382 char *p = string_glob (argv[0]);
1383 o = variable_buffer_output (o, p, strlen (p));
1384#endif
1385 return o;
1386}
1387
1388/*
1389 $(eval <makefile string>)
1390
1391 Always resolves to the empty string.
1392
1393 Treat the arguments as a segment of makefile, and parse them.
1394*/
1395
1396static char *
1397func_eval (char *o, char **argv, const char *funcname UNUSED)
1398{
1399 char *buf;
1400 unsigned int len;
1401
1402 /* Eval the buffer. Pop the current variable buffer setting so that the
1403 eval'd code can use its own without conflicting. */
1404
1405 install_variable_buffer (&buf, &len);
1406
1407 eval_buffer (argv[0]);
1408
1409 restore_variable_buffer (buf, len);
1410
1411 return o;
1412}
1413
1414
1415static char *
1416func_value (char *o, char **argv, const char *funcname UNUSED)
1417{
1418 /* Look up the variable. */
1419 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1420
1421 /* Copy its value into the output buffer without expanding it. */
1422 if (v)
1423#ifdef CONFIG_WITH_VALUE_LENGTH
1424 o = variable_buffer_output (o, v->value,
1425 v->value_length >= 0 ? v->value_length : strlen(v->value));
1426#else
1427 o = variable_buffer_output (o, v->value, strlen(v->value));
1428#endif
1429
1430 return o;
1431}
1432
1433/*
1434 \r is replaced on UNIX as well. Is this desirable?
1435 */
1436static void
1437fold_newlines (char *buffer, unsigned int *length)
1438{
1439 char *dst = buffer;
1440 char *src = buffer;
1441 char *last_nonnl = buffer -1;
1442 src[*length] = 0;
1443 for (; *src != '\0'; ++src)
1444 {
1445 if (src[0] == '\r' && src[1] == '\n')
1446 continue;
1447 if (*src == '\n')
1448 {
1449 *dst++ = ' ';
1450 }
1451 else
1452 {
1453 last_nonnl = dst;
1454 *dst++ = *src;
1455 }
1456 }
1457 *(++last_nonnl) = '\0';
1458 *length = last_nonnl - buffer;
1459}
1460
1461
1462
1463int shell_function_pid = 0, shell_function_completed;
1464
1465
1466#ifdef WINDOWS32
1467/*untested*/
1468
1469#include <windows.h>
1470#include <io.h>
1471#include "sub_proc.h"
1472
1473
1474void
1475windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1476{
1477 SECURITY_ATTRIBUTES saAttr;
1478 HANDLE hIn;
1479 HANDLE hErr;
1480 HANDLE hChildOutRd;
1481 HANDLE hChildOutWr;
1482 HANDLE hProcess;
1483
1484
1485 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1486 saAttr.bInheritHandle = TRUE;
1487 saAttr.lpSecurityDescriptor = NULL;
1488
1489 if (DuplicateHandle (GetCurrentProcess(),
1490 GetStdHandle(STD_INPUT_HANDLE),
1491 GetCurrentProcess(),
1492 &hIn,
1493 0,
1494 TRUE,
1495 DUPLICATE_SAME_ACCESS) == FALSE) {
1496 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1497 GetLastError());
1498
1499 }
1500 if (DuplicateHandle(GetCurrentProcess(),
1501 GetStdHandle(STD_ERROR_HANDLE),
1502 GetCurrentProcess(),
1503 &hErr,
1504 0,
1505 TRUE,
1506 DUPLICATE_SAME_ACCESS) == FALSE) {
1507 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1508 GetLastError());
1509 }
1510
1511 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1512 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1513
1514 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1515
1516 if (!hProcess)
1517 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1518
1519 /* make sure that CreateProcess() has Path it needs */
1520 sync_Path_environment();
1521
1522 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1523 /* register process for wait */
1524 process_register(hProcess);
1525
1526 /* set the pid for returning to caller */
1527 *pid_p = (int) hProcess;
1528
1529 /* set up to read data from child */
1530 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1531
1532 /* this will be closed almost right away */
1533 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1534 } else {
1535 /* reap/cleanup the failed process */
1536 process_cleanup(hProcess);
1537
1538 /* close handles which were duplicated, they weren't used */
1539 CloseHandle(hIn);
1540 CloseHandle(hErr);
1541
1542 /* close pipe handles, they won't be used */
1543 CloseHandle(hChildOutRd);
1544 CloseHandle(hChildOutWr);
1545
1546 /* set status for return */
1547 pipedes[0] = pipedes[1] = -1;
1548 *pid_p = -1;
1549 }
1550}
1551#endif
1552
1553
1554#ifdef __MSDOS__
1555FILE *
1556msdos_openpipe (int* pipedes, int *pidp, char *text)
1557{
1558 FILE *fpipe=0;
1559 /* MSDOS can't fork, but it has `popen'. */
1560 struct variable *sh = lookup_variable ("SHELL", 5);
1561 int e;
1562 extern int dos_command_running, dos_status;
1563
1564 /* Make sure not to bother processing an empty line. */
1565 while (isblank ((unsigned char)*text))
1566 ++text;
1567 if (*text == '\0')
1568 return 0;
1569
1570 if (sh)
1571 {
1572 char buf[PATH_MAX + 7];
1573 /* This makes sure $SHELL value is used by $(shell), even
1574 though the target environment is not passed to it. */
1575 sprintf (buf, "SHELL=%s", sh->value);
1576 putenv (buf);
1577 }
1578
1579 e = errno;
1580 errno = 0;
1581 dos_command_running = 1;
1582 dos_status = 0;
1583 /* If dos_status becomes non-zero, it means the child process
1584 was interrupted by a signal, like SIGINT or SIGQUIT. See
1585 fatal_error_signal in commands.c. */
1586 fpipe = popen (text, "rt");
1587 dos_command_running = 0;
1588 if (!fpipe || dos_status)
1589 {
1590 pipedes[0] = -1;
1591 *pidp = -1;
1592 if (dos_status)
1593 errno = EINTR;
1594 else if (errno == 0)
1595 errno = ENOMEM;
1596 shell_function_completed = -1;
1597 }
1598 else
1599 {
1600 pipedes[0] = fileno (fpipe);
1601 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1602 errno = e;
1603 shell_function_completed = 1;
1604 }
1605 return fpipe;
1606}
1607#endif
1608
1609/*
1610 Do shell spawning, with the naughty bits for different OSes.
1611 */
1612
1613#ifdef VMS
1614
1615/* VMS can't do $(shell ...) */
1616#define func_shell 0
1617
1618#else
1619#ifndef _AMIGA
1620static char *
1621func_shell (char *o, char **argv, const char *funcname UNUSED)
1622{
1623 char* batch_filename = NULL;
1624
1625#ifdef __MSDOS__
1626 FILE *fpipe;
1627#endif
1628 char **command_argv;
1629 char *error_prefix;
1630 char **envp;
1631 int pipedes[2];
1632 int pid;
1633
1634#ifndef __MSDOS__
1635 /* Construct the argument list. */
1636 command_argv = construct_command_argv (argv[0],
1637 (char **) NULL, (struct file *) 0,
1638 &batch_filename);
1639 if (command_argv == 0)
1640 return o;
1641#endif
1642
1643 /* Using a target environment for `shell' loses in cases like:
1644 export var = $(shell echo foobie)
1645 because target_environment hits a loop trying to expand $(var)
1646 to put it in the environment. This is even more confusing when
1647 var was not explicitly exported, but just appeared in the
1648 calling environment.
1649
1650 envp = target_environment (NILF);
1651 */
1652
1653 envp = environ;
1654
1655 /* For error messages. */
1656 if (reading_file && reading_file->filenm)
1657 {
1658 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1659 sprintf (error_prefix,
1660 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1661 }
1662 else
1663 error_prefix = "";
1664
1665#ifdef WINDOWS32
1666
1667 windows32_openpipe (pipedes, &pid, command_argv, envp);
1668
1669 if (pipedes[0] < 0) {
1670 /* open of the pipe failed, mark as failed execution */
1671 shell_function_completed = -1;
1672
1673 return o;
1674 } else
1675
1676#elif defined(__MSDOS__)
1677
1678 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1679 if (pipedes[0] < 0)
1680 {
1681 perror_with_name (error_prefix, "pipe");
1682 return o;
1683 }
1684
1685#else
1686
1687 if (pipe (pipedes) < 0)
1688 {
1689 perror_with_name (error_prefix, "pipe");
1690 return o;
1691 }
1692
1693# ifdef __EMX__
1694
1695 /* close some handles that are unnecessary for the child process */
1696 CLOSE_ON_EXEC(pipedes[1]);
1697 CLOSE_ON_EXEC(pipedes[0]);
1698 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1699 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1700 if (pid < 0)
1701 perror_with_name (error_prefix, "spawn");
1702
1703# else /* ! __EMX__ */
1704
1705 pid = vfork ();
1706 if (pid < 0)
1707 perror_with_name (error_prefix, "fork");
1708 else if (pid == 0)
1709 child_execute_job (0, pipedes[1], command_argv, envp);
1710 else
1711
1712# endif
1713
1714#endif
1715 {
1716 /* We are the parent. */
1717 char *buffer;
1718 unsigned int maxlen, i;
1719 int cc;
1720
1721 /* Record the PID for reap_children. */
1722 shell_function_pid = pid;
1723#ifndef __MSDOS__
1724 shell_function_completed = 0;
1725
1726 /* Free the storage only the child needed. */
1727 free (command_argv[0]);
1728 free ((char *) command_argv);
1729
1730 /* Close the write side of the pipe. */
1731 (void) close (pipedes[1]);
1732#endif
1733
1734 /* Set up and read from the pipe. */
1735
1736 maxlen = 200;
1737 buffer = (char *) xmalloc (maxlen + 1);
1738
1739 /* Read from the pipe until it gets EOF. */
1740 for (i = 0; ; i += cc)
1741 {
1742 if (i == maxlen)
1743 {
1744 maxlen += 512;
1745 buffer = (char *) xrealloc (buffer, maxlen + 1);
1746 }
1747
1748 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1749 if (cc <= 0)
1750 break;
1751 }
1752 buffer[i] = '\0';
1753
1754 /* Close the read side of the pipe. */
1755#ifdef __MSDOS__
1756 if (fpipe)
1757 (void) pclose (fpipe);
1758#else
1759 (void) close (pipedes[0]);
1760#endif
1761
1762 /* Loop until child_handler or reap_children() sets
1763 shell_function_completed to the status of our child shell. */
1764 while (shell_function_completed == 0)
1765 reap_children (1, 0);
1766
1767 if (batch_filename) {
1768 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1769 batch_filename));
1770 remove (batch_filename);
1771 free (batch_filename);
1772 }
1773 shell_function_pid = 0;
1774
1775 /* The child_handler function will set shell_function_completed
1776 to 1 when the child dies normally, or to -1 if it
1777 dies with status 127, which is most likely an exec fail. */
1778
1779 if (shell_function_completed == -1)
1780 {
1781 /* This likely means that the execvp failed, so we should just
1782 write the error message in the pipe from the child. */
1783 fputs (buffer, stderr);
1784 fflush (stderr);
1785 }
1786 else
1787 {
1788 /* The child finished normally. Replace all newlines in its output
1789 with spaces, and put that in the variable output buffer. */
1790 fold_newlines (buffer, &i);
1791 o = variable_buffer_output (o, buffer, i);
1792 }
1793
1794 free (buffer);
1795 }
1796
1797 return o;
1798}
1799
1800#else /* _AMIGA */
1801
1802/* Do the Amiga version of func_shell. */
1803
1804static char *
1805func_shell (char *o, char **argv, const char *funcname)
1806{
1807 /* Amiga can't fork nor spawn, but I can start a program with
1808 redirection of my choice. However, this means that we
1809 don't have an opportunity to reopen stdout to trap it. Thus,
1810 we save our own stdout onto a new descriptor and dup a temp
1811 file's descriptor onto our stdout temporarily. After we
1812 spawn the shell program, we dup our own stdout back to the
1813 stdout descriptor. The buffer reading is the same as above,
1814 except that we're now reading from a file. */
1815
1816#include <dos/dos.h>
1817#include <proto/dos.h>
1818
1819 BPTR child_stdout;
1820 char tmp_output[FILENAME_MAX];
1821 unsigned int maxlen = 200, i;
1822 int cc;
1823 char * buffer, * ptr;
1824 char ** aptr;
1825 int len = 0;
1826 char* batch_filename = NULL;
1827
1828 /* Construct the argument list. */
1829 command_argv = construct_command_argv (argv[0], (char **) NULL,
1830 (struct file *) 0, &batch_filename);
1831 if (command_argv == 0)
1832 return o;
1833
1834 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1835 Ideally we would use main.c:open_tmpfile(), but this uses a special
1836 Open(), not fopen(), and I'm not familiar enough with the code to mess
1837 with it. */
1838 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1839 mktemp (tmp_output);
1840 child_stdout = Open (tmp_output, MODE_NEWFILE);
1841
1842 for (aptr=command_argv; *aptr; aptr++)
1843 len += strlen (*aptr) + 1;
1844
1845 buffer = xmalloc (len + 1);
1846 ptr = buffer;
1847
1848 for (aptr=command_argv; *aptr; aptr++)
1849 {
1850 strcpy (ptr, *aptr);
1851 ptr += strlen (ptr) + 1;
1852 *ptr ++ = ' ';
1853 *ptr = 0;
1854 }
1855
1856 ptr[-1] = '\n';
1857
1858 Execute (buffer, NULL, child_stdout);
1859 free (buffer);
1860
1861 Close (child_stdout);
1862
1863 child_stdout = Open (tmp_output, MODE_OLDFILE);
1864
1865 buffer = xmalloc (maxlen);
1866 i = 0;
1867 do
1868 {
1869 if (i == maxlen)
1870 {
1871 maxlen += 512;
1872 buffer = (char *) xrealloc (buffer, maxlen + 1);
1873 }
1874
1875 cc = Read (child_stdout, &buffer[i], maxlen - i);
1876 if (cc > 0)
1877 i += cc;
1878 } while (cc > 0);
1879
1880 Close (child_stdout);
1881
1882 fold_newlines (buffer, &i);
1883 o = variable_buffer_output (o, buffer, i);
1884 free (buffer);
1885 return o;
1886}
1887#endif /* _AMIGA */
1888#endif /* !VMS */
1889
1890#ifdef EXPERIMENTAL
1891
1892/*
1893 equality. Return is string-boolean, ie, the empty string is false.
1894 */
1895static char *
1896func_eq (char *o, char **argv, char *funcname)
1897{
1898 int result = ! strcmp (argv[0], argv[1]);
1899 o = variable_buffer_output (o, result ? "1" : "", result);
1900 return o;
1901}
1902
1903
1904/*
1905 string-boolean not operator.
1906 */
1907static char *
1908func_not (char *o, char **argv, char *funcname)
1909{
1910 char *s = argv[0];
1911 int result = 0;
1912 while (isspace ((unsigned char)*s))
1913 s++;
1914 result = ! (*s);
1915 o = variable_buffer_output (o, result ? "1" : "", result);
1916 return o;
1917}
1918#endif
1919
1920
1921
1922/* Return the absolute name of file NAME which does not contain any `.',
1923 `..' components nor any repeated path separators ('/'). */
1924
1925static char *
1926abspath (const char *name, char *apath)
1927{
1928 char *dest;
1929 const char *start, *end, *apath_limit;
1930
1931 if (name[0] == '\0' || apath == NULL)
1932 return NULL;
1933
1934#ifdef WINDOWS32 /* bird */
1935 dest = w32ify((char *)name, 1);
1936 if (!dest)
1937 return NULL;
1938 {
1939 size_t len = strlen(dest);
1940 memcpy(apath, dest, len);
1941 dest = apath + len;
1942 }
1943
1944 (void)end; (void)start; (void)apath_limit;
1945
1946#elif defined __OS2__ /* bird */
1947 if (_abspath(apath, name, GET_PATH_MAX))
1948 return NULL;
1949 dest = strchr(apath, '\0');
1950
1951 (void)end; (void)start; (void)apath_limit; (void)dest;
1952
1953#else /* !WINDOWS32 && !__OS2__ */
1954 apath_limit = apath + GET_PATH_MAX;
1955
1956#ifdef HAVE_DOS_PATHS /* bird added this */
1957 if (isalpha(name[0]) && name[1] == ':')
1958 {
1959 /* drive spec */
1960 apath[0] = toupper(name[0]);
1961 apath[1] = ':';
1962 apath[2] = '/';
1963 name += 2;
1964 }
1965 else
1966#endif /* HAVE_DOS_PATHS */
1967 if (name[0] != '/')
1968 {
1969 /* It is unlikely we would make it until here but just to make sure. */
1970 if (!starting_directory)
1971 return NULL;
1972
1973 strcpy (apath, starting_directory);
1974
1975 dest = strchr (apath, '\0');
1976 }
1977 else
1978 {
1979 apath[0] = '/';
1980 dest = apath + 1;
1981 }
1982
1983 for (start = end = name; *start != '\0'; start = end)
1984 {
1985 unsigned long len;
1986
1987 /* Skip sequence of multiple path-separators. */
1988 while (*start == '/')
1989 ++start;
1990
1991 /* Find end of path component. */
1992 for (end = start; *end != '\0' && *end != '/'; ++end)
1993 ;
1994
1995 len = end - start;
1996
1997 if (len == 0)
1998 break;
1999 else if (len == 1 && start[0] == '.')
2000 /* nothing */;
2001 else if (len == 2 && start[0] == '.' && start[1] == '.')
2002 {
2003 /* Back up to previous component, ignore if at root already. */
2004 if (dest > apath + 1)
2005 while ((--dest)[-1] != '/');
2006 }
2007 else
2008 {
2009 if (dest[-1] != '/')
2010 *dest++ = '/';
2011
2012 if (dest + len >= apath_limit)
2013 return NULL;
2014
2015 dest = memcpy (dest, start, len);
2016 dest += len;
2017 *dest = '\0';
2018 }
2019 }
2020#endif /* !WINDOWS32 && !__OS2__ */
2021
2022 /* Unless it is root strip trailing separator. */
2023#ifdef HAVE_DOS_PATHS /* bird (is this correct? what about UNC?) */
2024 if (dest > apath + 1 + (apath[0] != '/') && dest[-1] == '/')
2025#else
2026 if (dest > apath + 1 && dest[-1] == '/')
2027#endif
2028 --dest;
2029
2030 *dest = '\0';
2031
2032 return apath;
2033}
2034
2035
2036static char *
2037func_realpath (char *o, char **argv, const char *funcname UNUSED)
2038{
2039 /* Expand the argument. */
2040 char *p = argv[0];
2041 char *path = 0;
2042 int doneany = 0;
2043 unsigned int len = 0;
2044 PATH_VAR (in);
2045 PATH_VAR (out);
2046
2047 while ((path = find_next_token (&p, &len)) != 0)
2048 {
2049 if (len < GET_PATH_MAX)
2050 {
2051 strncpy (in, path, len);
2052 in[len] = '\0';
2053
2054 if
2055 (
2056#ifdef HAVE_REALPATH
2057 realpath (in, out)
2058#else
2059 abspath (in, out)
2060#endif
2061 )
2062 {
2063 o = variable_buffer_output (o, out, strlen (out));
2064 o = variable_buffer_output (o, " ", 1);
2065 doneany = 1;
2066 }
2067 }
2068 }
2069
2070 /* Kill last space. */
2071 if (doneany)
2072 --o;
2073
2074 return o;
2075}
2076
2077static char *
2078func_abspath (char *o, char **argv, const char *funcname UNUSED)
2079{
2080 /* Expand the argument. */
2081 char *p = argv[0];
2082 char *path = 0;
2083 int doneany = 0;
2084 unsigned int len = 0;
2085 PATH_VAR (in);
2086 PATH_VAR (out);
2087
2088 while ((path = find_next_token (&p, &len)) != 0)
2089 {
2090 if (len < GET_PATH_MAX)
2091 {
2092 strncpy (in, path, len);
2093 in[len] = '\0';
2094
2095 if (abspath (in, out))
2096 {
2097 o = variable_buffer_output (o, out, strlen (out));
2098 o = variable_buffer_output (o, " ", 1);
2099 doneany = 1;
2100 }
2101 }
2102 }
2103
2104 /* Kill last space. */
2105 if (doneany)
2106 --o;
2107
2108 return o;
2109}
2110
2111#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2112static char *
2113func_toupper_tolower (char *o, char **argv, const char *funcname)
2114{
2115 /* Expand the argument. */
2116 const char *p = argv[0];
2117 while (*p)
2118 {
2119 /* convert to temporary buffer */
2120 char tmp[256];
2121 unsigned int i;
2122 if (!strcmp(funcname, "toupper"))
2123 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2124 tmp[i] = toupper(*p);
2125 else
2126 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2127 tmp[i] = tolower(*p);
2128 o = variable_buffer_output (o, tmp, i);
2129 }
2130
2131 return o;
2132}
2133#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
2134
2135#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2136/* Returns empty string if equal, returns the third arg if not equal. */
2137static char *
2138func_comp_vars (char *o, char **argv, const char *funcname)
2139{
2140 const char *s1, *e1, *x1, *s2, *e2, *x2;
2141 char *a1 = NULL, *a2 = NULL;
2142 size_t l, l1, l2;
2143 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
2144 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
2145
2146 /* the simple cases */
2147 if (var1 == var2)
2148 return variable_buffer_output (o, "", 1); /* eq */
2149 if (!var1 || !var2)
2150 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2151 if (var1->value == var2->value)
2152 return variable_buffer_output (o, "", 1); /* eq */
2153 if (!var1->recursive && !var2->recursive)
2154 {
2155 if ( var1->value_length == var2->value_length
2156 && !memcmp (var1->value, var2->value, var1->value_length))
2157 return variable_buffer_output (o, "", 1); /* eq */
2158
2159 /* ignore trailing and leading blanks */
2160 s1 = var1->value;
2161 while (isblank ((unsigned char) *s1))
2162 s1++;
2163 e1 = s1 + var1->value_length;
2164 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2165 e1--;
2166
2167 s2 = var2->value;
2168 while (isblank ((unsigned char) *s2))
2169 s2++;
2170 e2 = s2 + var2->value_length;
2171 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2172 e2--;
2173
2174 if (e1 - s1 != e2 - s2)
2175 return variable_buffer_output (o, "", 1); /* eq */
2176l_simple_compare:
2177 if (!memcmp (s1, s2, e1 - s1))
2178 return variable_buffer_output (o, "", 1); /* eq */
2179 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2180 }
2181
2182 /* ignore trailing and leading blanks */
2183 s1 = var1->value;
2184 e1 = s1 + var1->value_length;
2185 while (isblank ((unsigned char) *s1))
2186 s1++;
2187 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2188 e1--;
2189
2190 s2 = var2->value;
2191 e2 = s2 + var2->value_length;
2192 while (isblank((unsigned char)*s2))
2193 s2++;
2194 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2195 e2--;
2196
2197 /* both empty after stripping? */
2198 if (s1 == e1 && s2 == e2)
2199 return variable_buffer_output (o, "", 1); /* eq */
2200
2201 /* optimist. */
2202 if ( e1 - s1 == e2 - s2
2203 && !memcmp(s1, s2, e1 - s1))
2204 return variable_buffer_output (o, "", 1); /* eq */
2205
2206 /* compare up to the first '$' or the end. */
2207 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
2208 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
2209 if (!x1 && !x2)
2210 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2211
2212 l1 = x1 ? x1 - s1 : e1 - s1;
2213 l2 = x2 ? x2 - s2 : e2 - s2;
2214 l = l1 <= l2 ? l1 : l2;
2215 if (l && memcmp (s1, s2, l))
2216 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2217
2218 /* one or both buffers now require expanding. */
2219 if (!x1)
2220 s1 += l;
2221 else
2222 {
2223 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
2224 if (!l)
2225 while (isblank ((unsigned char) *s1))
2226 s1++;
2227 e1 = strchr (s1, '\0'); /*hmm*/
2228 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2229 e1--;
2230 }
2231
2232 if (!x2)
2233 s2 += l;
2234 else
2235 {
2236 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
2237 if (!l)
2238 while (isblank ((unsigned char) *s2))
2239 s2++;
2240 e2 = strchr (s2, '\0'); /*hmm*/
2241 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2242 e2--;
2243 }
2244
2245 /* the final compare */
2246 l = ( e1 - s1 != e2 - s2
2247 || memcmp (s1, s2, e1 - s1));
2248 if (a1)
2249 free (a1);
2250 if (a2)
2251 free (a2);
2252 if (l)
2253 return variable_buffer_output (o, "", 1);
2254 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2255}
2256#endif
2257
2258/* Lookup table for builtin functions.
2259
2260 This doesn't have to be sorted; we use a straight lookup. We might gain
2261 some efficiency by moving most often used functions to the start of the
2262 table.
2263
2264 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2265 comma-separated values are treated as arguments.
2266
2267 EXPAND_ARGS means that all arguments should be expanded before invocation.
2268 Functions that do namespace tricks (foreach) don't automatically expand. */
2269
2270static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
2271
2272
2273static struct function_table_entry function_table_init[] =
2274{
2275 /* Name/size */ /* MIN MAX EXP? Function */
2276 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2277 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2278 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2279 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2280 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2281 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2282 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2283 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2284 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2285 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2286 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2287 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2288 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2289 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2290 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2291 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2292 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2293 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2294 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2295 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2296 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2297 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2298 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2299 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2300 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2301 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2302 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2303 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2304 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2305 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2306 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2307 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2308 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2309 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2310 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2311#ifdef EXPERIMENTAL
2312 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2313 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2314#endif
2315#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2316 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower},
2317 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower},
2318#endif
2319#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2320 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars},
2321#endif
2322#ifdef KMK
2323 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool},
2324 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base},
2325 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix},
2326 { STRING_SIZE_TUPLE("kb-src-prop"), 3, 3, 0, func_kbuild_source_prop},
2327 { STRING_SIZE_TUPLE("kb-src-one"), 1, 1, 0, func_kbuild_source_one},
2328#endif
2329};
2330
2331#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2332
2333
2334
2335/* These must come after the definition of function_table. */
2336
2337static char *
2338expand_builtin_function (char *o, int argc, char **argv,
2339 const struct function_table_entry *entry_p)
2340{
2341 if (argc < (int)entry_p->minimum_args)
2342 fatal (*expanding_var,
2343 _("insufficient number of arguments (%d) to function `%s'"),
2344 argc, entry_p->name);
2345
2346 /* I suppose technically some function could do something with no
2347 arguments, but so far none do, so just test it for all functions here
2348 rather than in each one. We can change it later if necessary. */
2349
2350 if (!argc)
2351 return o;
2352
2353 if (!entry_p->func_ptr)
2354 fatal (*expanding_var,
2355 _("unimplemented on this platform: function `%s'"), entry_p->name);
2356
2357 return entry_p->func_ptr (o, argv, entry_p->name);
2358}
2359
2360/* Check for a function invocation in *STRINGP. *STRINGP points at the
2361 opening ( or { and is not null-terminated. If a function invocation
2362 is found, expand it into the buffer at *OP, updating *OP, incrementing
2363 *STRINGP past the reference and returning nonzero. If not, return zero. */
2364
2365static int
2366handle_function2 (const struct function_table_entry *entry_p, char **op, char **stringp) /* bird split it up. */
2367{
2368 char openparen = (*stringp)[0];
2369 char closeparen = openparen == '(' ? ')' : '}';
2370 char *beg;
2371 char *end;
2372 int count = 0;
2373 register char *p;
2374 char **argv, **argvp;
2375 int nargs;
2376
2377 beg = *stringp + 1;
2378
2379 /* We found a builtin function. Find the beginning of its arguments (skip
2380 whitespace after the name). */
2381
2382 beg = next_token (beg + entry_p->len);
2383
2384 /* Find the end of the function invocation, counting nested use of
2385 whichever kind of parens we use. Since we're looking, count commas
2386 to get a rough estimate of how many arguments we might have. The
2387 count might be high, but it'll never be low. */
2388
2389 for (nargs=1, end=beg; *end != '\0'; ++end)
2390 if (*end == ',')
2391 ++nargs;
2392 else if (*end == openparen)
2393 ++count;
2394 else if (*end == closeparen && --count < 0)
2395 break;
2396
2397 if (count >= 0)
2398 fatal (*expanding_var,
2399 _("unterminated call to function `%s': missing `%c'"),
2400 entry_p->name, closeparen);
2401
2402 *stringp = end;
2403
2404 /* Get some memory to store the arg pointers. */
2405 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
2406
2407 /* Chop the string into arguments, then a nul. As soon as we hit
2408 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2409 last argument.
2410
2411 If we're expanding, store pointers to the expansion of each one. If
2412 not, make a duplicate of the string and point into that, nul-terminating
2413 each argument. */
2414
2415 if (!entry_p->expand_args)
2416 {
2417 int len = end - beg;
2418
2419 p = xmalloc (len+1);
2420 memcpy (p, beg, len);
2421 p[len] = '\0';
2422 beg = p;
2423 end = beg + len;
2424 }
2425
2426 for (p=beg, nargs=0; p <= end; ++argvp)
2427 {
2428 char *next;
2429
2430 ++nargs;
2431
2432 if (nargs == entry_p->maximum_args
2433 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2434 next = end;
2435
2436 if (entry_p->expand_args)
2437 *argvp = expand_argument (p, next);
2438 else
2439 {
2440 *argvp = p;
2441 *next = '\0';
2442 }
2443
2444 p = next + 1;
2445 }
2446 *argvp = NULL;
2447
2448 /* Finally! Run the function... */
2449 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2450
2451 /* Free memory. */
2452 if (entry_p->expand_args)
2453 for (argvp=argv; *argvp != 0; ++argvp)
2454 free (*argvp);
2455 else
2456 free (beg);
2457
2458 return 1;
2459}
2460
2461int
2462handle_function (char **op, char **stringp) /* bird split it up */
2463{
2464 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
2465 if (!entry_p)
2466 return 0;
2467 return handle_function2 (entry_p, op, stringp);
2468}
2469
2470
2471
2472/* User-defined functions. Expand the first argument as either a builtin
2473 function or a make variable, in the context of the rest of the arguments
2474 assigned to $1, $2, ... $N. $0 is the name of the function. */
2475
2476static char *
2477func_call (char *o, char **argv, const char *funcname UNUSED)
2478{
2479 static int max_args = 0;
2480 char *fname;
2481 char *cp;
2482 char *body;
2483 int flen;
2484 int i;
2485 int saved_args;
2486 const struct function_table_entry *entry_p;
2487 struct variable *v;
2488
2489 /* There is no way to define a variable with a space in the name, so strip
2490 leading and trailing whitespace as a favor to the user. */
2491 fname = argv[0];
2492 while (*fname != '\0' && isspace ((unsigned char)*fname))
2493 ++fname;
2494
2495 cp = fname + strlen (fname) - 1;
2496 while (cp > fname && isspace ((unsigned char)*cp))
2497 --cp;
2498 cp[1] = '\0';
2499
2500 /* Calling nothing is a no-op */
2501 if (*fname == '\0')
2502 return o;
2503
2504 /* Are we invoking a builtin function? */
2505
2506 entry_p = lookup_function (fname);
2507
2508 if (entry_p)
2509 {
2510 /* How many arguments do we have? */
2511 for (i=0; argv[i+1]; ++i)
2512 ;
2513
2514 return expand_builtin_function (o, i, argv+1, entry_p);
2515 }
2516
2517 /* Not a builtin, so the first argument is the name of a variable to be
2518 expanded and interpreted as a function. Find it. */
2519 flen = strlen (fname);
2520
2521 v = lookup_variable (fname, flen);
2522
2523 if (v == 0)
2524 warn_undefined (fname, flen);
2525
2526 if (v == 0 || *v->value == '\0')
2527 return o;
2528
2529 body = (char *) alloca (flen + 4);
2530 body[0] = '$';
2531 body[1] = '(';
2532 memcpy (body + 2, fname, flen);
2533 body[flen+2] = ')';
2534 body[flen+3] = '\0';
2535
2536 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2537
2538 push_new_variable_scope ();
2539
2540 for (i=0; *argv; ++i, ++argv)
2541 {
2542 char num[11];
2543
2544 sprintf (num, "%d", i);
2545 define_variable (num, strlen (num), *argv, o_automatic, 0);
2546 }
2547
2548 /* If the number of arguments we have is < max_args, it means we're inside
2549 a recursive invocation of $(call ...). Fill in the remaining arguments
2550 in the new scope with the empty value, to hide them from this
2551 invocation. */
2552
2553 for (; i < max_args; ++i)
2554 {
2555 char num[11];
2556
2557 sprintf (num, "%d", i);
2558 define_variable (num, strlen (num), "", o_automatic, 0);
2559 }
2560
2561 /* Expand the body in the context of the arguments, adding the result to
2562 the variable buffer. */
2563
2564 v->exp_count = EXP_COUNT_MAX;
2565
2566 saved_args = max_args;
2567 max_args = i;
2568 o = variable_expand_string (o, body, flen+3);
2569 max_args = saved_args;
2570
2571 v->exp_count = 0;
2572
2573 pop_variable_scope ();
2574
2575 return o + strlen (o);
2576}
2577
2578void
2579hash_init_function_table (void)
2580{
2581 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2582 function_table_entry_hash_1, function_table_entry_hash_2,
2583 function_table_entry_hash_cmp);
2584 hash_load (&function_table, function_table_init,
2585 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
2586#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
2587 {
2588 unsigned i;
2589 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
2590 assert(function_table_init[i].len <= MAX_FUNCTION_LENGTH);
2591 }
2592#endif
2593}
Note: See TracBrowser for help on using the repository browser.