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

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

New function: $(xargs)

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