VirtualBox

source: kBuild/trunk/src/gmake/function.c@ 531

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

skip some unnecessary copies and allocations.

  • Property svn:eol-style set to native
File size: 63.9 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#ifdef CONFIG_WITH_VALUE_LENGTH
889 if (len > (unsigned int)var->value_length)
890 {
891 free (var->value);
892 var->value = xmalloc (len + 1);
893 }
894 memcpy (var->value, p, len);
895 var->value[len] = '\0';
896 var->value_length = len;
897#else
898 {
899 char save = p[len];
900
901 p[len] = '\0';
902 free (var->value);
903 var->value = (char *) xstrdup ((char*) p);
904 p[len] = save;
905 }
906#endif
907
908 result = allocated_variable_expand (body);
909
910 o = variable_buffer_output (o, result, strlen (result));
911 o = variable_buffer_output (o, " ", 1);
912 doneany = 1;
913 free (result);
914 }
915
916 if (doneany)
917 /* Kill the last space. */
918 --o;
919
920 pop_variable_scope ();
921 free (varname);
922 free (list);
923
924 return o;
925}
926
927struct a_word
928{
929 struct a_word *next;
930 struct a_word *chain;
931 char *str;
932 int length;
933 int matched;
934};
935
936static unsigned long
937a_word_hash_1 (const void *key)
938{
939 return_STRING_HASH_1 (((struct a_word const *) key)->str);
940}
941
942static unsigned long
943a_word_hash_2 (const void *key)
944{
945 return_STRING_HASH_2 (((struct a_word const *) key)->str);
946}
947
948static int
949a_word_hash_cmp (const void *x, const void *y)
950{
951 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
952 if (result)
953 return result;
954 return_STRING_COMPARE (((struct a_word const *) x)->str,
955 ((struct a_word const *) y)->str);
956}
957
958struct a_pattern
959{
960 struct a_pattern *next;
961 char *str;
962 char *percent;
963 int length;
964 int save_c;
965};
966
967static char *
968func_filter_filterout (char *o, char **argv, const char *funcname)
969{
970 struct a_word *wordhead;
971 struct a_word **wordtail;
972 struct a_word *wp;
973 struct a_pattern *pathead;
974 struct a_pattern **pattail;
975 struct a_pattern *pp;
976
977 struct hash_table a_word_table;
978 int is_filter = streq (funcname, "filter");
979 char *pat_iterator = argv[0];
980 char *word_iterator = argv[1];
981 int literals = 0;
982 int words = 0;
983 int hashing = 0;
984 char *p;
985 unsigned int len;
986
987 /* Chop ARGV[0] up into patterns to match against the words. */
988
989 pattail = &pathead;
990 while ((p = find_next_token (&pat_iterator, &len)) != 0)
991 {
992 struct a_pattern *pat = (struct a_pattern *) alloca (sizeof (struct a_pattern));
993
994 *pattail = pat;
995 pattail = &pat->next;
996
997 if (*pat_iterator != '\0')
998 ++pat_iterator;
999
1000 pat->str = p;
1001 pat->length = len;
1002 pat->save_c = p[len];
1003 p[len] = '\0';
1004 pat->percent = find_percent (p);
1005 if (pat->percent == 0)
1006 literals++;
1007 }
1008 *pattail = 0;
1009
1010 /* Chop ARGV[1] up into words to match against the patterns. */
1011
1012 wordtail = &wordhead;
1013 while ((p = find_next_token (&word_iterator, &len)) != 0)
1014 {
1015 struct a_word *word = (struct a_word *) alloca (sizeof (struct a_word));
1016
1017 *wordtail = word;
1018 wordtail = &word->next;
1019
1020 if (*word_iterator != '\0')
1021 ++word_iterator;
1022
1023 p[len] = '\0';
1024 word->str = p;
1025 word->length = len;
1026 word->matched = 0;
1027 word->chain = 0;
1028 words++;
1029 }
1030 *wordtail = 0;
1031
1032 /* Only use a hash table if arg list lengths justifies the cost. */
1033 hashing = (literals >= 2 && (literals * words) >= 10);
1034 if (hashing)
1035 {
1036 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2, a_word_hash_cmp);
1037 for (wp = wordhead; wp != 0; wp = wp->next)
1038 {
1039 struct a_word *owp = hash_insert (&a_word_table, wp);
1040 if (owp)
1041 wp->chain = owp;
1042 }
1043 }
1044
1045 if (words)
1046 {
1047 int doneany = 0;
1048
1049 /* Run each pattern through the words, killing words. */
1050 for (pp = pathead; pp != 0; pp = pp->next)
1051 {
1052 if (pp->percent)
1053 for (wp = wordhead; wp != 0; wp = wp->next)
1054 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1055 else if (hashing)
1056 {
1057 struct a_word a_word_key;
1058 a_word_key.str = pp->str;
1059 a_word_key.length = pp->length;
1060 wp = (struct a_word *) hash_find_item (&a_word_table, &a_word_key);
1061 while (wp)
1062 {
1063 wp->matched |= 1;
1064 wp = wp->chain;
1065 }
1066 }
1067 else
1068 for (wp = wordhead; wp != 0; wp = wp->next)
1069 wp->matched |= (wp->length == pp->length
1070 && strneq (pp->str, wp->str, wp->length));
1071 }
1072
1073 /* Output the words that matched (or didn't, for filter-out). */
1074 for (wp = wordhead; wp != 0; wp = wp->next)
1075 if (is_filter ? wp->matched : !wp->matched)
1076 {
1077 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1078 o = variable_buffer_output (o, " ", 1);
1079 doneany = 1;
1080 }
1081
1082 if (doneany)
1083 /* Kill the last space. */
1084 --o;
1085 }
1086
1087 for (pp = pathead; pp != 0; pp = pp->next)
1088 pp->str[pp->length] = pp->save_c;
1089
1090 if (hashing)
1091 hash_free (&a_word_table, 0);
1092
1093 return o;
1094}
1095
1096
1097static char *
1098func_strip (char *o, char **argv, const char *funcname UNUSED)
1099{
1100 char *p = argv[0];
1101 int doneany =0;
1102
1103 while (*p != '\0')
1104 {
1105 int i=0;
1106 char *word_start=0;
1107
1108 while (isspace ((unsigned char)*p))
1109 ++p;
1110 word_start = p;
1111 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1112 {}
1113 if (!i)
1114 break;
1115 o = variable_buffer_output (o, word_start, i);
1116 o = variable_buffer_output (o, " ", 1);
1117 doneany = 1;
1118 }
1119
1120 if (doneany)
1121 /* Kill the last space. */
1122 --o;
1123 return o;
1124}
1125
1126/*
1127 Print a warning or fatal message.
1128*/
1129static char *
1130func_error (char *o, char **argv, const char *funcname)
1131{
1132 char **argvp;
1133 char *msg, *p;
1134 int len;
1135
1136 /* The arguments will be broken on commas. Rather than create yet
1137 another special case where function arguments aren't broken up,
1138 just create a format string that puts them back together. */
1139 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1140 len += strlen (*argvp) + 2;
1141
1142 p = msg = (char *) alloca (len + 1);
1143
1144 for (argvp=argv; argvp[1] != 0; ++argvp)
1145 {
1146 strcpy (p, *argvp);
1147 p += strlen (*argvp);
1148 *(p++) = ',';
1149 *(p++) = ' ';
1150 }
1151 strcpy (p, *argvp);
1152
1153 switch (*funcname) {
1154 case 'e':
1155 fatal (reading_file, "%s", msg);
1156
1157 case 'w':
1158 error (reading_file, "%s", msg);
1159 break;
1160
1161 case 'i':
1162 printf ("%s\n", msg);
1163 fflush(stdout);
1164 break;
1165
1166 default:
1167 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1168 }
1169
1170 /* The warning function expands to the empty string. */
1171 return o;
1172}
1173
1174
1175/*
1176 chop argv[0] into words, and sort them.
1177 */
1178static char *
1179func_sort (char *o, char **argv, const char *funcname UNUSED)
1180{
1181 char **words = 0;
1182 int nwords = 0;
1183 register int wordi = 0;
1184
1185 /* Chop ARGV[0] into words and put them in WORDS. */
1186 char *t = argv[0];
1187 char *p;
1188 unsigned int len;
1189 int i;
1190
1191 while ((p = find_next_token (&t, &len)) != 0)
1192 {
1193 if (wordi >= nwords - 1)
1194 {
1195 nwords = (2 * nwords) + 5;
1196 words = (char **) xrealloc ((char *) words,
1197 nwords * sizeof (char *));
1198 }
1199 words[wordi++] = savestring (p, len);
1200 }
1201
1202 if (!wordi)
1203 return o;
1204
1205 /* Now sort the list of words. */
1206 qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
1207
1208 /* Now write the sorted list. */
1209 for (i = 0; i < wordi; ++i)
1210 {
1211 len = strlen (words[i]);
1212 if (i == wordi - 1 || strlen (words[i + 1]) != len
1213 || strcmp (words[i], words[i + 1]))
1214 {
1215 o = variable_buffer_output (o, words[i], len);
1216 o = variable_buffer_output (o, " ", 1);
1217 }
1218 free (words[i]);
1219 }
1220 /* Kill the last space. */
1221 --o;
1222
1223 free (words);
1224
1225 return o;
1226}
1227
1228/*
1229 $(if condition,true-part[,false-part])
1230
1231 CONDITION is false iff it evaluates to an empty string. White
1232 space before and after condition are stripped before evaluation.
1233
1234 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1235 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1236 you can use $(if ...) to create side-effects (with $(shell ...), for
1237 example).
1238*/
1239
1240static char *
1241func_if (char *o, char **argv, const char *funcname UNUSED)
1242{
1243 const char *begp = argv[0];
1244 const char *endp = begp + strlen (argv[0]) - 1;
1245 int result = 0;
1246
1247 /* Find the result of the condition: if we have a value, and it's not
1248 empty, the condition is true. If we don't have a value, or it's the
1249 empty string, then it's false. */
1250
1251 strip_whitespace (&begp, &endp);
1252
1253 if (begp <= endp)
1254 {
1255 char *expansion = expand_argument (begp, endp+1);
1256
1257 result = strlen (expansion);
1258 free (expansion);
1259 }
1260
1261 /* If the result is true (1) we want to eval the first argument, and if
1262 it's false (0) we want to eval the second. If the argument doesn't
1263 exist we do nothing, otherwise expand it and add to the buffer. */
1264
1265 argv += 1 + !result;
1266
1267 if (argv[0])
1268 {
1269 char *expansion;
1270
1271 expansion = expand_argument (argv[0], NULL);
1272
1273 o = variable_buffer_output (o, expansion, strlen (expansion));
1274
1275 free (expansion);
1276 }
1277
1278 return o;
1279}
1280
1281/*
1282 $(or condition1[,condition2[,condition3[...]]])
1283
1284 A CONDITION is false iff it evaluates to an empty string. White
1285 space before and after CONDITION are stripped before evaluation.
1286
1287 CONDITION1 is evaluated. If it's true, then this is the result of
1288 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1289 the conditions are true, the expansion is the empty string.
1290
1291 Once a CONDITION is true no further conditions are evaluated
1292 (short-circuiting).
1293*/
1294
1295static char *
1296func_or (char *o, char **argv, const char *funcname UNUSED)
1297{
1298 for ( ; *argv ; ++argv)
1299 {
1300 const char *begp = *argv;
1301 const char *endp = begp + strlen (*argv) - 1;
1302 char *expansion;
1303 int result = 0;
1304
1305 /* Find the result of the condition: if it's false keep going. */
1306
1307 strip_whitespace (&begp, &endp);
1308
1309 if (begp > endp)
1310 continue;
1311
1312 expansion = expand_argument (begp, endp+1);
1313 result = strlen (expansion);
1314
1315 /* If the result is false keep going. */
1316 if (!result)
1317 {
1318 free (expansion);
1319 continue;
1320 }
1321
1322 /* It's true! Keep this result and return. */
1323 o = variable_buffer_output (o, expansion, result);
1324 free (expansion);
1325 break;
1326 }
1327
1328 return o;
1329}
1330
1331/*
1332 $(and condition1[,condition2[,condition3[...]]])
1333
1334 A CONDITION is false iff it evaluates to an empty string. White
1335 space before and after CONDITION are stripped before evaluation.
1336
1337 CONDITION1 is evaluated. If it's false, then this is the result of
1338 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1339 the conditions are true, the expansion is the result of the last condition.
1340
1341 Once a CONDITION is false no further conditions are evaluated
1342 (short-circuiting).
1343*/
1344
1345static char *
1346func_and (char *o, char **argv, const char *funcname UNUSED)
1347{
1348 char *expansion;
1349 int result;
1350
1351 while (1)
1352 {
1353 const char *begp = *argv;
1354 const char *endp = begp + strlen (*argv) - 1;
1355
1356 /* An empty condition is always false. */
1357 strip_whitespace (&begp, &endp);
1358 if (begp > endp)
1359 return o;
1360
1361 expansion = expand_argument (begp, endp+1);
1362 result = strlen (expansion);
1363
1364 /* If the result is false, stop here: we're done. */
1365 if (!result)
1366 break;
1367
1368 /* Otherwise the result is true. If this is the last one, keep this
1369 result and quit. Otherwise go on to the next one! */
1370
1371 if (*(++argv))
1372 free (expansion);
1373 else
1374 {
1375 o = variable_buffer_output (o, expansion, result);
1376 break;
1377 }
1378 }
1379
1380 free (expansion);
1381
1382 return o;
1383}
1384
1385static char *
1386func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1387{
1388
1389#ifdef _AMIGA
1390 o = wildcard_expansion (argv[0], o);
1391#else
1392 char *p = string_glob (argv[0]);
1393 o = variable_buffer_output (o, p, strlen (p));
1394#endif
1395 return o;
1396}
1397
1398/*
1399 $(eval <makefile string>)
1400
1401 Always resolves to the empty string.
1402
1403 Treat the arguments as a segment of makefile, and parse them.
1404*/
1405
1406static char *
1407func_eval (char *o, char **argv, const char *funcname UNUSED)
1408{
1409 char *buf;
1410 unsigned int len;
1411
1412 /* Eval the buffer. Pop the current variable buffer setting so that the
1413 eval'd code can use its own without conflicting. */
1414
1415 install_variable_buffer (&buf, &len);
1416
1417 eval_buffer (argv[0]);
1418
1419 restore_variable_buffer (buf, len);
1420
1421 return o;
1422}
1423
1424
1425static char *
1426func_value (char *o, char **argv, const char *funcname UNUSED)
1427{
1428 /* Look up the variable. */
1429 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1430
1431 /* Copy its value into the output buffer without expanding it. */
1432 if (v)
1433#ifdef CONFIG_WITH_VALUE_LENGTH
1434 o = variable_buffer_output (o, v->value,
1435 v->value_length >= 0 ? v->value_length : strlen(v->value));
1436#else
1437 o = variable_buffer_output (o, v->value, strlen(v->value));
1438#endif
1439
1440 return o;
1441}
1442
1443/*
1444 \r is replaced on UNIX as well. Is this desirable?
1445 */
1446static void
1447fold_newlines (char *buffer, unsigned int *length)
1448{
1449 char *dst = buffer;
1450 char *src = buffer;
1451 char *last_nonnl = buffer -1;
1452 src[*length] = 0;
1453 for (; *src != '\0'; ++src)
1454 {
1455 if (src[0] == '\r' && src[1] == '\n')
1456 continue;
1457 if (*src == '\n')
1458 {
1459 *dst++ = ' ';
1460 }
1461 else
1462 {
1463 last_nonnl = dst;
1464 *dst++ = *src;
1465 }
1466 }
1467 *(++last_nonnl) = '\0';
1468 *length = last_nonnl - buffer;
1469}
1470
1471
1472
1473int shell_function_pid = 0, shell_function_completed;
1474
1475
1476#ifdef WINDOWS32
1477/*untested*/
1478
1479#include <windows.h>
1480#include <io.h>
1481#include "sub_proc.h"
1482
1483
1484void
1485windows32_openpipe (int *pipedes, int *pid_p, char **command_argv, char **envp)
1486{
1487 SECURITY_ATTRIBUTES saAttr;
1488 HANDLE hIn;
1489 HANDLE hErr;
1490 HANDLE hChildOutRd;
1491 HANDLE hChildOutWr;
1492 HANDLE hProcess;
1493
1494
1495 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1496 saAttr.bInheritHandle = TRUE;
1497 saAttr.lpSecurityDescriptor = NULL;
1498
1499 if (DuplicateHandle (GetCurrentProcess(),
1500 GetStdHandle(STD_INPUT_HANDLE),
1501 GetCurrentProcess(),
1502 &hIn,
1503 0,
1504 TRUE,
1505 DUPLICATE_SAME_ACCESS) == FALSE) {
1506 fatal (NILF, _("create_child_process: DuplicateHandle(In) failed (e=%ld)\n"),
1507 GetLastError());
1508
1509 }
1510 if (DuplicateHandle(GetCurrentProcess(),
1511 GetStdHandle(STD_ERROR_HANDLE),
1512 GetCurrentProcess(),
1513 &hErr,
1514 0,
1515 TRUE,
1516 DUPLICATE_SAME_ACCESS) == FALSE) {
1517 fatal (NILF, _("create_child_process: DuplicateHandle(Err) failed (e=%ld)\n"),
1518 GetLastError());
1519 }
1520
1521 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1522 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1523
1524 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1525
1526 if (!hProcess)
1527 fatal (NILF, _("windows32_openpipe (): process_init_fd() failed\n"));
1528
1529 /* make sure that CreateProcess() has Path it needs */
1530 sync_Path_environment();
1531
1532 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1533 /* register process for wait */
1534 process_register(hProcess);
1535
1536 /* set the pid for returning to caller */
1537 *pid_p = (int) hProcess;
1538
1539 /* set up to read data from child */
1540 pipedes[0] = _open_osfhandle((long) hChildOutRd, O_RDONLY);
1541
1542 /* this will be closed almost right away */
1543 pipedes[1] = _open_osfhandle((long) hChildOutWr, O_APPEND);
1544 } else {
1545 /* reap/cleanup the failed process */
1546 process_cleanup(hProcess);
1547
1548 /* close handles which were duplicated, they weren't used */
1549 CloseHandle(hIn);
1550 CloseHandle(hErr);
1551
1552 /* close pipe handles, they won't be used */
1553 CloseHandle(hChildOutRd);
1554 CloseHandle(hChildOutWr);
1555
1556 /* set status for return */
1557 pipedes[0] = pipedes[1] = -1;
1558 *pid_p = -1;
1559 }
1560}
1561#endif
1562
1563
1564#ifdef __MSDOS__
1565FILE *
1566msdos_openpipe (int* pipedes, int *pidp, char *text)
1567{
1568 FILE *fpipe=0;
1569 /* MSDOS can't fork, but it has `popen'. */
1570 struct variable *sh = lookup_variable ("SHELL", 5);
1571 int e;
1572 extern int dos_command_running, dos_status;
1573
1574 /* Make sure not to bother processing an empty line. */
1575 while (isblank ((unsigned char)*text))
1576 ++text;
1577 if (*text == '\0')
1578 return 0;
1579
1580 if (sh)
1581 {
1582 char buf[PATH_MAX + 7];
1583 /* This makes sure $SHELL value is used by $(shell), even
1584 though the target environment is not passed to it. */
1585 sprintf (buf, "SHELL=%s", sh->value);
1586 putenv (buf);
1587 }
1588
1589 e = errno;
1590 errno = 0;
1591 dos_command_running = 1;
1592 dos_status = 0;
1593 /* If dos_status becomes non-zero, it means the child process
1594 was interrupted by a signal, like SIGINT or SIGQUIT. See
1595 fatal_error_signal in commands.c. */
1596 fpipe = popen (text, "rt");
1597 dos_command_running = 0;
1598 if (!fpipe || dos_status)
1599 {
1600 pipedes[0] = -1;
1601 *pidp = -1;
1602 if (dos_status)
1603 errno = EINTR;
1604 else if (errno == 0)
1605 errno = ENOMEM;
1606 shell_function_completed = -1;
1607 }
1608 else
1609 {
1610 pipedes[0] = fileno (fpipe);
1611 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1612 errno = e;
1613 shell_function_completed = 1;
1614 }
1615 return fpipe;
1616}
1617#endif
1618
1619/*
1620 Do shell spawning, with the naughty bits for different OSes.
1621 */
1622
1623#ifdef VMS
1624
1625/* VMS can't do $(shell ...) */
1626#define func_shell 0
1627
1628#else
1629#ifndef _AMIGA
1630static char *
1631func_shell (char *o, char **argv, const char *funcname UNUSED)
1632{
1633 char* batch_filename = NULL;
1634
1635#ifdef __MSDOS__
1636 FILE *fpipe;
1637#endif
1638 char **command_argv;
1639 char *error_prefix;
1640 char **envp;
1641 int pipedes[2];
1642 int pid;
1643
1644#ifndef __MSDOS__
1645 /* Construct the argument list. */
1646 command_argv = construct_command_argv (argv[0],
1647 (char **) NULL, (struct file *) 0,
1648 &batch_filename);
1649 if (command_argv == 0)
1650 return o;
1651#endif
1652
1653 /* Using a target environment for `shell' loses in cases like:
1654 export var = $(shell echo foobie)
1655 because target_environment hits a loop trying to expand $(var)
1656 to put it in the environment. This is even more confusing when
1657 var was not explicitly exported, but just appeared in the
1658 calling environment.
1659
1660 envp = target_environment (NILF);
1661 */
1662
1663 envp = environ;
1664
1665 /* For error messages. */
1666 if (reading_file && reading_file->filenm)
1667 {
1668 error_prefix = (char *) alloca (strlen (reading_file->filenm)+11+4);
1669 sprintf (error_prefix,
1670 "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1671 }
1672 else
1673 error_prefix = "";
1674
1675#ifdef WINDOWS32
1676
1677 windows32_openpipe (pipedes, &pid, command_argv, envp);
1678
1679 if (pipedes[0] < 0) {
1680 /* open of the pipe failed, mark as failed execution */
1681 shell_function_completed = -1;
1682
1683 return o;
1684 } else
1685
1686#elif defined(__MSDOS__)
1687
1688 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1689 if (pipedes[0] < 0)
1690 {
1691 perror_with_name (error_prefix, "pipe");
1692 return o;
1693 }
1694
1695#else
1696
1697 if (pipe (pipedes) < 0)
1698 {
1699 perror_with_name (error_prefix, "pipe");
1700 return o;
1701 }
1702
1703# ifdef __EMX__
1704
1705 /* close some handles that are unnecessary for the child process */
1706 CLOSE_ON_EXEC(pipedes[1]);
1707 CLOSE_ON_EXEC(pipedes[0]);
1708 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1709 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1710 if (pid < 0)
1711 perror_with_name (error_prefix, "spawn");
1712
1713# else /* ! __EMX__ */
1714
1715 pid = vfork ();
1716 if (pid < 0)
1717 perror_with_name (error_prefix, "fork");
1718 else if (pid == 0)
1719 child_execute_job (0, pipedes[1], command_argv, envp);
1720 else
1721
1722# endif
1723
1724#endif
1725 {
1726 /* We are the parent. */
1727 char *buffer;
1728 unsigned int maxlen, i;
1729 int cc;
1730
1731 /* Record the PID for reap_children. */
1732 shell_function_pid = pid;
1733#ifndef __MSDOS__
1734 shell_function_completed = 0;
1735
1736 /* Free the storage only the child needed. */
1737 free (command_argv[0]);
1738 free ((char *) command_argv);
1739
1740 /* Close the write side of the pipe. */
1741 (void) close (pipedes[1]);
1742#endif
1743
1744 /* Set up and read from the pipe. */
1745
1746 maxlen = 200;
1747 buffer = (char *) xmalloc (maxlen + 1);
1748
1749 /* Read from the pipe until it gets EOF. */
1750 for (i = 0; ; i += cc)
1751 {
1752 if (i == maxlen)
1753 {
1754 maxlen += 512;
1755 buffer = (char *) xrealloc (buffer, maxlen + 1);
1756 }
1757
1758 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1759 if (cc <= 0)
1760 break;
1761 }
1762 buffer[i] = '\0';
1763
1764 /* Close the read side of the pipe. */
1765#ifdef __MSDOS__
1766 if (fpipe)
1767 (void) pclose (fpipe);
1768#else
1769 (void) close (pipedes[0]);
1770#endif
1771
1772 /* Loop until child_handler or reap_children() sets
1773 shell_function_completed to the status of our child shell. */
1774 while (shell_function_completed == 0)
1775 reap_children (1, 0);
1776
1777 if (batch_filename) {
1778 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1779 batch_filename));
1780 remove (batch_filename);
1781 free (batch_filename);
1782 }
1783 shell_function_pid = 0;
1784
1785 /* The child_handler function will set shell_function_completed
1786 to 1 when the child dies normally, or to -1 if it
1787 dies with status 127, which is most likely an exec fail. */
1788
1789 if (shell_function_completed == -1)
1790 {
1791 /* This likely means that the execvp failed, so we should just
1792 write the error message in the pipe from the child. */
1793 fputs (buffer, stderr);
1794 fflush (stderr);
1795 }
1796 else
1797 {
1798 /* The child finished normally. Replace all newlines in its output
1799 with spaces, and put that in the variable output buffer. */
1800 fold_newlines (buffer, &i);
1801 o = variable_buffer_output (o, buffer, i);
1802 }
1803
1804 free (buffer);
1805 }
1806
1807 return o;
1808}
1809
1810#else /* _AMIGA */
1811
1812/* Do the Amiga version of func_shell. */
1813
1814static char *
1815func_shell (char *o, char **argv, const char *funcname)
1816{
1817 /* Amiga can't fork nor spawn, but I can start a program with
1818 redirection of my choice. However, this means that we
1819 don't have an opportunity to reopen stdout to trap it. Thus,
1820 we save our own stdout onto a new descriptor and dup a temp
1821 file's descriptor onto our stdout temporarily. After we
1822 spawn the shell program, we dup our own stdout back to the
1823 stdout descriptor. The buffer reading is the same as above,
1824 except that we're now reading from a file. */
1825
1826#include <dos/dos.h>
1827#include <proto/dos.h>
1828
1829 BPTR child_stdout;
1830 char tmp_output[FILENAME_MAX];
1831 unsigned int maxlen = 200, i;
1832 int cc;
1833 char * buffer, * ptr;
1834 char ** aptr;
1835 int len = 0;
1836 char* batch_filename = NULL;
1837
1838 /* Construct the argument list. */
1839 command_argv = construct_command_argv (argv[0], (char **) NULL,
1840 (struct file *) 0, &batch_filename);
1841 if (command_argv == 0)
1842 return o;
1843
1844 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1845 Ideally we would use main.c:open_tmpfile(), but this uses a special
1846 Open(), not fopen(), and I'm not familiar enough with the code to mess
1847 with it. */
1848 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1849 mktemp (tmp_output);
1850 child_stdout = Open (tmp_output, MODE_NEWFILE);
1851
1852 for (aptr=command_argv; *aptr; aptr++)
1853 len += strlen (*aptr) + 1;
1854
1855 buffer = xmalloc (len + 1);
1856 ptr = buffer;
1857
1858 for (aptr=command_argv; *aptr; aptr++)
1859 {
1860 strcpy (ptr, *aptr);
1861 ptr += strlen (ptr) + 1;
1862 *ptr ++ = ' ';
1863 *ptr = 0;
1864 }
1865
1866 ptr[-1] = '\n';
1867
1868 Execute (buffer, NULL, child_stdout);
1869 free (buffer);
1870
1871 Close (child_stdout);
1872
1873 child_stdout = Open (tmp_output, MODE_OLDFILE);
1874
1875 buffer = xmalloc (maxlen);
1876 i = 0;
1877 do
1878 {
1879 if (i == maxlen)
1880 {
1881 maxlen += 512;
1882 buffer = (char *) xrealloc (buffer, maxlen + 1);
1883 }
1884
1885 cc = Read (child_stdout, &buffer[i], maxlen - i);
1886 if (cc > 0)
1887 i += cc;
1888 } while (cc > 0);
1889
1890 Close (child_stdout);
1891
1892 fold_newlines (buffer, &i);
1893 o = variable_buffer_output (o, buffer, i);
1894 free (buffer);
1895 return o;
1896}
1897#endif /* _AMIGA */
1898#endif /* !VMS */
1899
1900#ifdef EXPERIMENTAL
1901
1902/*
1903 equality. Return is string-boolean, ie, the empty string is false.
1904 */
1905static char *
1906func_eq (char *o, char **argv, char *funcname)
1907{
1908 int result = ! strcmp (argv[0], argv[1]);
1909 o = variable_buffer_output (o, result ? "1" : "", result);
1910 return o;
1911}
1912
1913
1914/*
1915 string-boolean not operator.
1916 */
1917static char *
1918func_not (char *o, char **argv, char *funcname)
1919{
1920 char *s = argv[0];
1921 int result = 0;
1922 while (isspace ((unsigned char)*s))
1923 s++;
1924 result = ! (*s);
1925 o = variable_buffer_output (o, result ? "1" : "", result);
1926 return o;
1927}
1928#endif
1929
1930
1931
1932/* Return the absolute name of file NAME which does not contain any `.',
1933 `..' components nor any repeated path separators ('/'). */
1934
1935static char *
1936abspath (const char *name, char *apath)
1937{
1938 char *dest;
1939 const char *start, *end, *apath_limit;
1940
1941 if (name[0] == '\0' || apath == NULL)
1942 return NULL;
1943
1944#ifdef WINDOWS32 /* bird */
1945 dest = w32ify((char *)name, 1);
1946 if (!dest)
1947 return NULL;
1948 {
1949 size_t len = strlen(dest);
1950 memcpy(apath, dest, len);
1951 dest = apath + len;
1952 }
1953
1954 (void)end; (void)start; (void)apath_limit;
1955
1956#elif defined __OS2__ /* bird */
1957 if (_abspath(apath, name, GET_PATH_MAX))
1958 return NULL;
1959 dest = strchr(apath, '\0');
1960
1961 (void)end; (void)start; (void)apath_limit; (void)dest;
1962
1963#else /* !WINDOWS32 && !__OS2__ */
1964 apath_limit = apath + GET_PATH_MAX;
1965
1966#ifdef HAVE_DOS_PATHS /* bird added this */
1967 if (isalpha(name[0]) && name[1] == ':')
1968 {
1969 /* drive spec */
1970 apath[0] = toupper(name[0]);
1971 apath[1] = ':';
1972 apath[2] = '/';
1973 name += 2;
1974 }
1975 else
1976#endif /* HAVE_DOS_PATHS */
1977 if (name[0] != '/')
1978 {
1979 /* It is unlikely we would make it until here but just to make sure. */
1980 if (!starting_directory)
1981 return NULL;
1982
1983 strcpy (apath, starting_directory);
1984
1985 dest = strchr (apath, '\0');
1986 }
1987 else
1988 {
1989 apath[0] = '/';
1990 dest = apath + 1;
1991 }
1992
1993 for (start = end = name; *start != '\0'; start = end)
1994 {
1995 unsigned long len;
1996
1997 /* Skip sequence of multiple path-separators. */
1998 while (*start == '/')
1999 ++start;
2000
2001 /* Find end of path component. */
2002 for (end = start; *end != '\0' && *end != '/'; ++end)
2003 ;
2004
2005 len = end - start;
2006
2007 if (len == 0)
2008 break;
2009 else if (len == 1 && start[0] == '.')
2010 /* nothing */;
2011 else if (len == 2 && start[0] == '.' && start[1] == '.')
2012 {
2013 /* Back up to previous component, ignore if at root already. */
2014 if (dest > apath + 1)
2015 while ((--dest)[-1] != '/');
2016 }
2017 else
2018 {
2019 if (dest[-1] != '/')
2020 *dest++ = '/';
2021
2022 if (dest + len >= apath_limit)
2023 return NULL;
2024
2025 dest = memcpy (dest, start, len);
2026 dest += len;
2027 *dest = '\0';
2028 }
2029 }
2030#endif /* !WINDOWS32 && !__OS2__ */
2031
2032 /* Unless it is root strip trailing separator. */
2033#ifdef HAVE_DOS_PATHS /* bird (is this correct? what about UNC?) */
2034 if (dest > apath + 1 + (apath[0] != '/') && dest[-1] == '/')
2035#else
2036 if (dest > apath + 1 && dest[-1] == '/')
2037#endif
2038 --dest;
2039
2040 *dest = '\0';
2041
2042 return apath;
2043}
2044
2045
2046static char *
2047func_realpath (char *o, char **argv, const char *funcname UNUSED)
2048{
2049 /* Expand the argument. */
2050 char *p = argv[0];
2051 char *path = 0;
2052 int doneany = 0;
2053 unsigned int len = 0;
2054 PATH_VAR (in);
2055 PATH_VAR (out);
2056
2057 while ((path = find_next_token (&p, &len)) != 0)
2058 {
2059 if (len < GET_PATH_MAX)
2060 {
2061 strncpy (in, path, len);
2062 in[len] = '\0';
2063
2064 if
2065 (
2066#ifdef HAVE_REALPATH
2067 realpath (in, out)
2068#else
2069 abspath (in, out)
2070#endif
2071 )
2072 {
2073 o = variable_buffer_output (o, out, strlen (out));
2074 o = variable_buffer_output (o, " ", 1);
2075 doneany = 1;
2076 }
2077 }
2078 }
2079
2080 /* Kill last space. */
2081 if (doneany)
2082 --o;
2083
2084 return o;
2085}
2086
2087static char *
2088func_abspath (char *o, char **argv, const char *funcname UNUSED)
2089{
2090 /* Expand the argument. */
2091 char *p = argv[0];
2092 char *path = 0;
2093 int doneany = 0;
2094 unsigned int len = 0;
2095 PATH_VAR (in);
2096 PATH_VAR (out);
2097
2098 while ((path = find_next_token (&p, &len)) != 0)
2099 {
2100 if (len < GET_PATH_MAX)
2101 {
2102 strncpy (in, path, len);
2103 in[len] = '\0';
2104
2105 if (abspath (in, out))
2106 {
2107 o = variable_buffer_output (o, out, strlen (out));
2108 o = variable_buffer_output (o, " ", 1);
2109 doneany = 1;
2110 }
2111 }
2112 }
2113
2114 /* Kill last space. */
2115 if (doneany)
2116 --o;
2117
2118 return o;
2119}
2120
2121#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2122static char *
2123func_toupper_tolower (char *o, char **argv, const char *funcname)
2124{
2125 /* Expand the argument. */
2126 const char *p = argv[0];
2127 while (*p)
2128 {
2129 /* convert to temporary buffer */
2130 char tmp[256];
2131 unsigned int i;
2132 if (!strcmp(funcname, "toupper"))
2133 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2134 tmp[i] = toupper(*p);
2135 else
2136 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
2137 tmp[i] = tolower(*p);
2138 o = variable_buffer_output (o, tmp, i);
2139 }
2140
2141 return o;
2142}
2143#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
2144
2145#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2146/* Returns empty string if equal, returns the third arg if not equal. */
2147static char *
2148func_comp_vars (char *o, char **argv, const char *funcname)
2149{
2150 const char *s1, *e1, *x1, *s2, *e2, *x2;
2151 char *a1 = NULL, *a2 = NULL;
2152 size_t l, l1, l2;
2153 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
2154 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
2155
2156 /* the simple cases */
2157 if (var1 == var2)
2158 return variable_buffer_output (o, "", 1); /* eq */
2159 if (!var1 || !var2)
2160 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2161 if (var1->value == var2->value)
2162 return variable_buffer_output (o, "", 1); /* eq */
2163 if (!var1->recursive && !var2->recursive)
2164 {
2165 if ( var1->value_length == var2->value_length
2166 && !memcmp (var1->value, var2->value, var1->value_length))
2167 return variable_buffer_output (o, "", 1); /* eq */
2168
2169 /* ignore trailing and leading blanks */
2170 s1 = var1->value;
2171 while (isblank ((unsigned char) *s1))
2172 s1++;
2173 e1 = s1 + var1->value_length;
2174 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2175 e1--;
2176
2177 s2 = var2->value;
2178 while (isblank ((unsigned char) *s2))
2179 s2++;
2180 e2 = s2 + var2->value_length;
2181 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2182 e2--;
2183
2184 if (e1 - s1 != e2 - s2)
2185 return variable_buffer_output (o, "", 1); /* eq */
2186l_simple_compare:
2187 if (!memcmp (s1, s2, e1 - s1))
2188 return variable_buffer_output (o, "", 1); /* eq */
2189 return variable_buffer_output (o, argv[2], strlen(argv[2]));
2190 }
2191
2192 /* ignore trailing and leading blanks */
2193 s1 = var1->value;
2194 e1 = s1 + var1->value_length;
2195 while (isblank ((unsigned char) *s1))
2196 s1++;
2197 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2198 e1--;
2199
2200 s2 = var2->value;
2201 e2 = s2 + var2->value_length;
2202 while (isblank((unsigned char)*s2))
2203 s2++;
2204 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2205 e2--;
2206
2207 /* both empty after stripping? */
2208 if (s1 == e1 && s2 == e2)
2209 return variable_buffer_output (o, "", 1); /* eq */
2210
2211 /* optimist. */
2212 if ( e1 - s1 == e2 - s2
2213 && !memcmp(s1, s2, e1 - s1))
2214 return variable_buffer_output (o, "", 1); /* eq */
2215
2216 /* compare up to the first '$' or the end. */
2217 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
2218 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
2219 if (!x1 && !x2)
2220 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2221
2222 l1 = x1 ? x1 - s1 : e1 - s1;
2223 l2 = x2 ? x2 - s2 : e2 - s2;
2224 l = l1 <= l2 ? l1 : l2;
2225 if (l && memcmp (s1, s2, l))
2226 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2227
2228 /* one or both buffers now require expanding. */
2229 if (!x1)
2230 s1 += l;
2231 else
2232 {
2233 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
2234 if (!l)
2235 while (isblank ((unsigned char) *s1))
2236 s1++;
2237 e1 = strchr (s1, '\0'); /*hmm*/
2238 while (e1 > s1 && isblank ((unsigned char) e1[-1]))
2239 e1--;
2240 }
2241
2242 if (!x2)
2243 s2 += l;
2244 else
2245 {
2246 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
2247 if (!l)
2248 while (isblank ((unsigned char) *s2))
2249 s2++;
2250 e2 = strchr (s2, '\0'); /*hmm*/
2251 while (e2 > s2 && isblank ((unsigned char) e2[-1]))
2252 e2--;
2253 }
2254
2255 /* the final compare */
2256 l = ( e1 - s1 != e2 - s2
2257 || memcmp (s1, s2, e1 - s1));
2258 if (a1)
2259 free (a1);
2260 if (a2)
2261 free (a2);
2262 if (l)
2263 return variable_buffer_output (o, "", 1);
2264 return variable_buffer_output (o, argv[2], strlen (argv[2]));
2265}
2266#endif
2267
2268/* Lookup table for builtin functions.
2269
2270 This doesn't have to be sorted; we use a straight lookup. We might gain
2271 some efficiency by moving most often used functions to the start of the
2272 table.
2273
2274 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2275 comma-separated values are treated as arguments.
2276
2277 EXPAND_ARGS means that all arguments should be expanded before invocation.
2278 Functions that do namespace tricks (foreach) don't automatically expand. */
2279
2280static char *func_call PARAMS ((char *o, char **argv, const char *funcname));
2281
2282
2283static struct function_table_entry function_table_init[] =
2284{
2285 /* Name/size */ /* MIN MAX EXP? Function */
2286 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2287 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2288 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2289 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2290 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2291 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2292 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2293 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2294 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2295 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2296 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2297 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2298 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2299 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2300 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2301 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2302 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2303 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2304 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2305 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2306 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2307 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2308 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2309 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2310 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2311 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2312 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2313 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2314 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2315 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2316 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2317 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2318 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2319 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2320 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2321#ifdef EXPERIMENTAL
2322 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2323 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2324#endif
2325#ifdef CONFIG_WITH_TOUPPER_TOLOWER
2326 { STRING_SIZE_TUPLE("toupper"), 0, 1, 1, func_toupper_tolower},
2327 { STRING_SIZE_TUPLE("tolower"), 0, 1, 1, func_toupper_tolower},
2328#endif
2329#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
2330 { STRING_SIZE_TUPLE("comp-vars"), 3, 3, 1, func_comp_vars},
2331#endif
2332#ifdef KMK
2333 { STRING_SIZE_TUPLE("kb-src-tool"), 1, 1, 0, func_kbuild_source_tool},
2334 { STRING_SIZE_TUPLE("kb-obj-base"), 1, 1, 0, func_kbuild_object_base},
2335 { STRING_SIZE_TUPLE("kb-obj-suff"), 1, 1, 0, func_kbuild_object_suffix},
2336 { STRING_SIZE_TUPLE("kb-src-prop"), 3, 3, 0, func_kbuild_source_prop},
2337 { STRING_SIZE_TUPLE("kb-src-one"), 1, 1, 0, func_kbuild_source_one},
2338#endif
2339};
2340
2341#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2342
2343
2344
2345/* These must come after the definition of function_table. */
2346
2347static char *
2348expand_builtin_function (char *o, int argc, char **argv,
2349 const struct function_table_entry *entry_p)
2350{
2351 if (argc < (int)entry_p->minimum_args)
2352 fatal (*expanding_var,
2353 _("insufficient number of arguments (%d) to function `%s'"),
2354 argc, entry_p->name);
2355
2356 /* I suppose technically some function could do something with no
2357 arguments, but so far none do, so just test it for all functions here
2358 rather than in each one. We can change it later if necessary. */
2359
2360 if (!argc)
2361 return o;
2362
2363 if (!entry_p->func_ptr)
2364 fatal (*expanding_var,
2365 _("unimplemented on this platform: function `%s'"), entry_p->name);
2366
2367 return entry_p->func_ptr (o, argv, entry_p->name);
2368}
2369
2370/* Check for a function invocation in *STRINGP. *STRINGP points at the
2371 opening ( or { and is not null-terminated. If a function invocation
2372 is found, expand it into the buffer at *OP, updating *OP, incrementing
2373 *STRINGP past the reference and returning nonzero. If not, return zero. */
2374
2375static int
2376handle_function2 (const struct function_table_entry *entry_p, char **op, char **stringp) /* bird split it up. */
2377{
2378 char openparen = (*stringp)[0];
2379 char closeparen = openparen == '(' ? ')' : '}';
2380 char *beg;
2381 char *end;
2382 int count = 0;
2383 register char *p;
2384 char **argv, **argvp;
2385 int nargs;
2386
2387 beg = *stringp + 1;
2388
2389 /* We found a builtin function. Find the beginning of its arguments (skip
2390 whitespace after the name). */
2391
2392 beg = next_token (beg + entry_p->len);
2393
2394 /* Find the end of the function invocation, counting nested use of
2395 whichever kind of parens we use. Since we're looking, count commas
2396 to get a rough estimate of how many arguments we might have. The
2397 count might be high, but it'll never be low. */
2398
2399 for (nargs=1, end=beg; *end != '\0'; ++end)
2400 if (*end == ',')
2401 ++nargs;
2402 else if (*end == openparen)
2403 ++count;
2404 else if (*end == closeparen && --count < 0)
2405 break;
2406
2407 if (count >= 0)
2408 fatal (*expanding_var,
2409 _("unterminated call to function `%s': missing `%c'"),
2410 entry_p->name, closeparen);
2411
2412 *stringp = end;
2413
2414 /* Get some memory to store the arg pointers. */
2415 argvp = argv = (char **) alloca (sizeof (char *) * (nargs + 2));
2416
2417 /* Chop the string into arguments, then a nul. As soon as we hit
2418 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2419 last argument.
2420
2421 If we're expanding, store pointers to the expansion of each one. If
2422 not, make a duplicate of the string and point into that, nul-terminating
2423 each argument. */
2424
2425 if (!entry_p->expand_args)
2426 {
2427 int len = end - beg;
2428
2429 p = xmalloc (len+1);
2430 memcpy (p, beg, len);
2431 p[len] = '\0';
2432 beg = p;
2433 end = beg + len;
2434 }
2435
2436 for (p=beg, nargs=0; p <= end; ++argvp)
2437 {
2438 char *next;
2439
2440 ++nargs;
2441
2442 if (nargs == entry_p->maximum_args
2443 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2444 next = end;
2445
2446 if (entry_p->expand_args)
2447 *argvp = expand_argument (p, next);
2448 else
2449 {
2450 *argvp = p;
2451 *next = '\0';
2452 }
2453
2454 p = next + 1;
2455 }
2456 *argvp = NULL;
2457
2458 /* Finally! Run the function... */
2459 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2460
2461 /* Free memory. */
2462 if (entry_p->expand_args)
2463 for (argvp=argv; *argvp != 0; ++argvp)
2464 free (*argvp);
2465 else
2466 free (beg);
2467
2468 return 1;
2469}
2470
2471int
2472handle_function (char **op, char **stringp) /* bird split it up */
2473{
2474 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
2475 if (!entry_p)
2476 return 0;
2477 return handle_function2 (entry_p, op, stringp);
2478}
2479
2480
2481
2482/* User-defined functions. Expand the first argument as either a builtin
2483 function or a make variable, in the context of the rest of the arguments
2484 assigned to $1, $2, ... $N. $0 is the name of the function. */
2485
2486static char *
2487func_call (char *o, char **argv, const char *funcname UNUSED)
2488{
2489 static int max_args = 0;
2490 char *fname;
2491 char *cp;
2492 char *body;
2493 int flen;
2494 int i;
2495 int saved_args;
2496 const struct function_table_entry *entry_p;
2497 struct variable *v;
2498
2499 /* There is no way to define a variable with a space in the name, so strip
2500 leading and trailing whitespace as a favor to the user. */
2501 fname = argv[0];
2502 while (*fname != '\0' && isspace ((unsigned char)*fname))
2503 ++fname;
2504
2505 cp = fname + strlen (fname) - 1;
2506 while (cp > fname && isspace ((unsigned char)*cp))
2507 --cp;
2508 cp[1] = '\0';
2509
2510 /* Calling nothing is a no-op */
2511 if (*fname == '\0')
2512 return o;
2513
2514 /* Are we invoking a builtin function? */
2515
2516 entry_p = lookup_function (fname);
2517
2518 if (entry_p)
2519 {
2520 /* How many arguments do we have? */
2521 for (i=0; argv[i+1]; ++i)
2522 ;
2523
2524 return expand_builtin_function (o, i, argv+1, entry_p);
2525 }
2526
2527 /* Not a builtin, so the first argument is the name of a variable to be
2528 expanded and interpreted as a function. Find it. */
2529 flen = strlen (fname);
2530
2531 v = lookup_variable (fname, flen);
2532
2533 if (v == 0)
2534 warn_undefined (fname, flen);
2535
2536 if (v == 0 || *v->value == '\0')
2537 return o;
2538
2539 body = (char *) alloca (flen + 4);
2540 body[0] = '$';
2541 body[1] = '(';
2542 memcpy (body + 2, fname, flen);
2543 body[flen+2] = ')';
2544 body[flen+3] = '\0';
2545
2546 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2547
2548 push_new_variable_scope ();
2549
2550 for (i=0; *argv; ++i, ++argv)
2551 {
2552 char num[11];
2553
2554 sprintf (num, "%d", i);
2555 define_variable (num, strlen (num), *argv, o_automatic, 0);
2556 }
2557
2558 /* If the number of arguments we have is < max_args, it means we're inside
2559 a recursive invocation of $(call ...). Fill in the remaining arguments
2560 in the new scope with the empty value, to hide them from this
2561 invocation. */
2562
2563 for (; i < max_args; ++i)
2564 {
2565 char num[11];
2566
2567 sprintf (num, "%d", i);
2568 define_variable (num, strlen (num), "", o_automatic, 0);
2569 }
2570
2571 /* Expand the body in the context of the arguments, adding the result to
2572 the variable buffer. */
2573
2574 v->exp_count = EXP_COUNT_MAX;
2575
2576 saved_args = max_args;
2577 max_args = i;
2578 o = variable_expand_string (o, body, flen+3);
2579 max_args = saved_args;
2580
2581 v->exp_count = 0;
2582
2583 pop_variable_scope ();
2584
2585 return o + strlen (o);
2586}
2587
2588void
2589hash_init_function_table (void)
2590{
2591 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2592 function_table_entry_hash_1, function_table_entry_hash_2,
2593 function_table_entry_hash_cmp);
2594 hash_load (&function_table, function_table_init,
2595 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
2596#ifdef CONFIG_WITH_OPTIMIZATION_HACKS
2597 {
2598 unsigned i;
2599 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
2600 assert(function_table_init[i].len <= MAX_FUNCTION_LENGTH);
2601 }
2602#endif
2603}
Note: See TracBrowser for help on using the repository browser.

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