VirtualBox

source: kBuild/vendor/gnumake/2007-05-23/function.c

Last change on this file was 900, checked in by bird, 17 years ago

Load /home/bird/src/Gnu/make/2007-05-23 into vendor/gnumake/current.

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

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