VirtualBox

source: kBuild/vendor/gnumake/current/function.c@ 2397

Last change on this file since 2397 was 1989, checked in by bird, 16 years ago

Load gnumake-2008-10-28-CVS 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, 2007 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 3 of the License, or (at your option) any later
10version.
11
12GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License along with
17this program. If not, see <http://www.gnu.org/licenses/>. */
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, 0,
1612 &batch_filename);
1613 if (command_argv == 0)
1614 return o;
1615#endif
1616
1617 /* Using a target environment for `shell' loses in cases like:
1618 export var = $(shell echo foobie)
1619 because target_environment hits a loop trying to expand $(var)
1620 to put it in the environment. This is even more confusing when
1621 var was not explicitly exported, but just appeared in the
1622 calling environment.
1623
1624 See Savannah bug #10593.
1625
1626 envp = target_environment (NILF);
1627 */
1628
1629 envp = environ;
1630
1631 /* For error messages. */
1632 if (reading_file && reading_file->filenm)
1633 {
1634 char *p = alloca (strlen (reading_file->filenm)+11+4);
1635 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1636 error_prefix = p;
1637 }
1638 else
1639 error_prefix = "";
1640
1641#if defined(__MSDOS__)
1642 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1643 if (pipedes[0] < 0)
1644 {
1645 perror_with_name (error_prefix, "pipe");
1646 return o;
1647 }
1648#elif defined(WINDOWS32)
1649 windows32_openpipe (pipedes, &pid, command_argv, envp);
1650 if (pipedes[0] < 0)
1651 {
1652 /* open of the pipe failed, mark as failed execution */
1653 shell_function_completed = -1;
1654
1655 return o;
1656 }
1657 else
1658#else
1659 if (pipe (pipedes) < 0)
1660 {
1661 perror_with_name (error_prefix, "pipe");
1662 return o;
1663 }
1664
1665# ifdef __EMX__
1666 /* close some handles that are unnecessary for the child process */
1667 CLOSE_ON_EXEC(pipedes[1]);
1668 CLOSE_ON_EXEC(pipedes[0]);
1669 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1670 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1671 if (pid < 0)
1672 perror_with_name (error_prefix, "spawn");
1673# else /* ! __EMX__ */
1674 pid = vfork ();
1675 if (pid < 0)
1676 perror_with_name (error_prefix, "fork");
1677 else if (pid == 0)
1678 child_execute_job (0, pipedes[1], command_argv, envp);
1679 else
1680# endif
1681#endif
1682 {
1683 /* We are the parent. */
1684 char *buffer;
1685 unsigned int maxlen, i;
1686 int cc;
1687
1688 /* Record the PID for reap_children. */
1689 shell_function_pid = pid;
1690#ifndef __MSDOS__
1691 shell_function_completed = 0;
1692
1693 /* Free the storage only the child needed. */
1694 free (command_argv[0]);
1695 free (command_argv);
1696
1697 /* Close the write side of the pipe. */
1698 close (pipedes[1]);
1699#endif
1700
1701 /* Set up and read from the pipe. */
1702
1703 maxlen = 200;
1704 buffer = xmalloc (maxlen + 1);
1705
1706 /* Read from the pipe until it gets EOF. */
1707 for (i = 0; ; i += cc)
1708 {
1709 if (i == maxlen)
1710 {
1711 maxlen += 512;
1712 buffer = xrealloc (buffer, maxlen + 1);
1713 }
1714
1715 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
1716 if (cc <= 0)
1717 break;
1718 }
1719 buffer[i] = '\0';
1720
1721 /* Close the read side of the pipe. */
1722#ifdef __MSDOS__
1723 if (fpipe)
1724 (void) pclose (fpipe);
1725#else
1726 (void) close (pipedes[0]);
1727#endif
1728
1729 /* Loop until child_handler or reap_children() sets
1730 shell_function_completed to the status of our child shell. */
1731 while (shell_function_completed == 0)
1732 reap_children (1, 0);
1733
1734 if (batch_filename) {
1735 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
1736 batch_filename));
1737 remove (batch_filename);
1738 free (batch_filename);
1739 }
1740 shell_function_pid = 0;
1741
1742 /* The child_handler function will set shell_function_completed
1743 to 1 when the child dies normally, or to -1 if it
1744 dies with status 127, which is most likely an exec fail. */
1745
1746 if (shell_function_completed == -1)
1747 {
1748 /* This likely means that the execvp failed, so we should just
1749 write the error message in the pipe from the child. */
1750 fputs (buffer, stderr);
1751 fflush (stderr);
1752 }
1753 else
1754 {
1755 /* The child finished normally. Replace all newlines in its output
1756 with spaces, and put that in the variable output buffer. */
1757 fold_newlines (buffer, &i);
1758 o = variable_buffer_output (o, buffer, i);
1759 }
1760
1761 free (buffer);
1762 }
1763
1764 return o;
1765}
1766
1767#else /* _AMIGA */
1768
1769/* Do the Amiga version of func_shell. */
1770
1771static char *
1772func_shell (char *o, char **argv, const char *funcname)
1773{
1774 /* Amiga can't fork nor spawn, but I can start a program with
1775 redirection of my choice. However, this means that we
1776 don't have an opportunity to reopen stdout to trap it. Thus,
1777 we save our own stdout onto a new descriptor and dup a temp
1778 file's descriptor onto our stdout temporarily. After we
1779 spawn the shell program, we dup our own stdout back to the
1780 stdout descriptor. The buffer reading is the same as above,
1781 except that we're now reading from a file. */
1782
1783#include <dos/dos.h>
1784#include <proto/dos.h>
1785
1786 BPTR child_stdout;
1787 char tmp_output[FILENAME_MAX];
1788 unsigned int maxlen = 200, i;
1789 int cc;
1790 char * buffer, * ptr;
1791 char ** aptr;
1792 int len = 0;
1793 char* batch_filename = NULL;
1794
1795 /* Construct the argument list. */
1796 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1797 &batch_filename);
1798 if (command_argv == 0)
1799 return o;
1800
1801 /* Note the mktemp() is a security hole, but this only runs on Amiga.
1802 Ideally we would use main.c:open_tmpfile(), but this uses a special
1803 Open(), not fopen(), and I'm not familiar enough with the code to mess
1804 with it. */
1805 strcpy (tmp_output, "t:MakeshXXXXXXXX");
1806 mktemp (tmp_output);
1807 child_stdout = Open (tmp_output, MODE_NEWFILE);
1808
1809 for (aptr=command_argv; *aptr; aptr++)
1810 len += strlen (*aptr) + 1;
1811
1812 buffer = xmalloc (len + 1);
1813 ptr = buffer;
1814
1815 for (aptr=command_argv; *aptr; aptr++)
1816 {
1817 strcpy (ptr, *aptr);
1818 ptr += strlen (ptr) + 1;
1819 *ptr ++ = ' ';
1820 *ptr = 0;
1821 }
1822
1823 ptr[-1] = '\n';
1824
1825 Execute (buffer, NULL, child_stdout);
1826 free (buffer);
1827
1828 Close (child_stdout);
1829
1830 child_stdout = Open (tmp_output, MODE_OLDFILE);
1831
1832 buffer = xmalloc (maxlen);
1833 i = 0;
1834 do
1835 {
1836 if (i == maxlen)
1837 {
1838 maxlen += 512;
1839 buffer = xrealloc (buffer, maxlen + 1);
1840 }
1841
1842 cc = Read (child_stdout, &buffer[i], maxlen - i);
1843 if (cc > 0)
1844 i += cc;
1845 } while (cc > 0);
1846
1847 Close (child_stdout);
1848
1849 fold_newlines (buffer, &i);
1850 o = variable_buffer_output (o, buffer, i);
1851 free (buffer);
1852 return o;
1853}
1854#endif /* _AMIGA */
1855#endif /* !VMS */
1856
1857#ifdef EXPERIMENTAL
1858
1859/*
1860 equality. Return is string-boolean, ie, the empty string is false.
1861 */
1862static char *
1863func_eq (char *o, char **argv, char *funcname)
1864{
1865 int result = ! strcmp (argv[0], argv[1]);
1866 o = variable_buffer_output (o, result ? "1" : "", result);
1867 return o;
1868}
1869
1870
1871/*
1872 string-boolean not operator.
1873 */
1874static char *
1875func_not (char *o, char **argv, char *funcname)
1876{
1877 const char *s = argv[0];
1878 int result = 0;
1879 while (isspace ((unsigned char)*s))
1880 s++;
1881 result = ! (*s);
1882 o = variable_buffer_output (o, result ? "1" : "", result);
1883 return o;
1884}
1885#endif
1886
1887
1888
1889/* Return the absolute name of file NAME which does not contain any `.',
1890 `..' components nor any repeated path separators ('/'). */
1891
1892static char *
1893abspath (const char *name, char *apath)
1894{
1895 char *dest;
1896 const char *start, *end, *apath_limit;
1897
1898 if (name[0] == '\0' || apath == NULL)
1899 return NULL;
1900
1901 apath_limit = apath + GET_PATH_MAX;
1902
1903 if (name[0] != '/')
1904 {
1905 /* It is unlikely we would make it until here but just to make sure. */
1906 if (!starting_directory)
1907 return NULL;
1908
1909 strcpy (apath, starting_directory);
1910
1911 dest = strchr (apath, '\0');
1912 }
1913 else
1914 {
1915 apath[0] = '/';
1916 dest = apath + 1;
1917 }
1918
1919 for (start = end = name; *start != '\0'; start = end)
1920 {
1921 unsigned long len;
1922
1923 /* Skip sequence of multiple path-separators. */
1924 while (*start == '/')
1925 ++start;
1926
1927 /* Find end of path component. */
1928 for (end = start; *end != '\0' && *end != '/'; ++end)
1929 ;
1930
1931 len = end - start;
1932
1933 if (len == 0)
1934 break;
1935 else if (len == 1 && start[0] == '.')
1936 /* nothing */;
1937 else if (len == 2 && start[0] == '.' && start[1] == '.')
1938 {
1939 /* Back up to previous component, ignore if at root already. */
1940 if (dest > apath + 1)
1941 while ((--dest)[-1] != '/');
1942 }
1943 else
1944 {
1945 if (dest[-1] != '/')
1946 *dest++ = '/';
1947
1948 if (dest + len >= apath_limit)
1949 return NULL;
1950
1951 dest = memcpy (dest, start, len);
1952 dest += len;
1953 *dest = '\0';
1954 }
1955 }
1956
1957 /* Unless it is root strip trailing separator. */
1958 if (dest > apath + 1 && dest[-1] == '/')
1959 --dest;
1960
1961 *dest = '\0';
1962
1963 return apath;
1964}
1965
1966
1967static char *
1968func_realpath (char *o, char **argv, const char *funcname UNUSED)
1969{
1970 /* Expand the argument. */
1971 const char *p = argv[0];
1972 const char *path = 0;
1973 int doneany = 0;
1974 unsigned int len = 0;
1975 PATH_VAR (in);
1976 PATH_VAR (out);
1977
1978 while ((path = find_next_token (&p, &len)) != 0)
1979 {
1980 if (len < GET_PATH_MAX)
1981 {
1982 strncpy (in, path, len);
1983 in[len] = '\0';
1984
1985 if (
1986#ifdef HAVE_REALPATH
1987 realpath (in, out)
1988#else
1989 abspath (in, out)
1990#endif
1991 )
1992 {
1993 o = variable_buffer_output (o, out, strlen (out));
1994 o = variable_buffer_output (o, " ", 1);
1995 doneany = 1;
1996 }
1997 }
1998 }
1999
2000 /* Kill last space. */
2001 if (doneany)
2002 --o;
2003
2004 return o;
2005}
2006
2007static char *
2008func_abspath (char *o, char **argv, const char *funcname UNUSED)
2009{
2010 /* Expand the argument. */
2011 const char *p = argv[0];
2012 const char *path = 0;
2013 int doneany = 0;
2014 unsigned int len = 0;
2015 PATH_VAR (in);
2016 PATH_VAR (out);
2017
2018 while ((path = find_next_token (&p, &len)) != 0)
2019 {
2020 if (len < GET_PATH_MAX)
2021 {
2022 strncpy (in, path, len);
2023 in[len] = '\0';
2024
2025 if (abspath (in, out))
2026 {
2027 o = variable_buffer_output (o, out, strlen (out));
2028 o = variable_buffer_output (o, " ", 1);
2029 doneany = 1;
2030 }
2031 }
2032 }
2033
2034 /* Kill last space. */
2035 if (doneany)
2036 --o;
2037
2038 return o;
2039}
2040
2041/* Lookup table for builtin functions.
2042
2043 This doesn't have to be sorted; we use a straight lookup. We might gain
2044 some efficiency by moving most often used functions to the start of the
2045 table.
2046
2047 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2048 comma-separated values are treated as arguments.
2049
2050 EXPAND_ARGS means that all arguments should be expanded before invocation.
2051 Functions that do namespace tricks (foreach) don't automatically expand. */
2052
2053static char *func_call (char *o, char **argv, const char *funcname);
2054
2055
2056static struct function_table_entry function_table_init[] =
2057{
2058 /* Name/size */ /* MIN MAX EXP? Function */
2059 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2060 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2061 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2062 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2063 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2064 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2065 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2066 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2067 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2068 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2069 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2070 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2071 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2072 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2073 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2074 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2075 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2076 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2077 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2078 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2079 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2080 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2081 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2082 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2083 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2084 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2085 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2086 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2087 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2088 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2089 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2090 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2091 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2092 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2093 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2094#ifdef EXPERIMENTAL
2095 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2096 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2097#endif
2098};
2099
2100#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2101
2102
2103
2104/* These must come after the definition of function_table. */
2105
2106static char *
2107expand_builtin_function (char *o, int argc, char **argv,
2108 const struct function_table_entry *entry_p)
2109{
2110 if (argc < (int)entry_p->minimum_args)
2111 fatal (*expanding_var,
2112 _("insufficient number of arguments (%d) to function `%s'"),
2113 argc, entry_p->name);
2114
2115 /* I suppose technically some function could do something with no
2116 arguments, but so far none do, so just test it for all functions here
2117 rather than in each one. We can change it later if necessary. */
2118
2119 if (!argc)
2120 return o;
2121
2122 if (!entry_p->func_ptr)
2123 fatal (*expanding_var,
2124 _("unimplemented on this platform: function `%s'"), entry_p->name);
2125
2126 return entry_p->func_ptr (o, argv, entry_p->name);
2127}
2128
2129/* Check for a function invocation in *STRINGP. *STRINGP points at the
2130 opening ( or { and is not null-terminated. If a function invocation
2131 is found, expand it into the buffer at *OP, updating *OP, incrementing
2132 *STRINGP past the reference and returning nonzero. If not, return zero. */
2133
2134int
2135handle_function (char **op, const char **stringp)
2136{
2137 const struct function_table_entry *entry_p;
2138 char openparen = (*stringp)[0];
2139 char closeparen = openparen == '(' ? ')' : '}';
2140 const char *beg;
2141 const char *end;
2142 int count = 0;
2143 char *abeg = NULL;
2144 char **argv, **argvp;
2145 int nargs;
2146
2147 beg = *stringp + 1;
2148
2149 entry_p = lookup_function (beg);
2150
2151 if (!entry_p)
2152 return 0;
2153
2154 /* We found a builtin function. Find the beginning of its arguments (skip
2155 whitespace after the name). */
2156
2157 beg = next_token (beg + entry_p->len);
2158
2159 /* Find the end of the function invocation, counting nested use of
2160 whichever kind of parens we use. Since we're looking, count commas
2161 to get a rough estimate of how many arguments we might have. The
2162 count might be high, but it'll never be low. */
2163
2164 for (nargs=1, end=beg; *end != '\0'; ++end)
2165 if (*end == ',')
2166 ++nargs;
2167 else if (*end == openparen)
2168 ++count;
2169 else if (*end == closeparen && --count < 0)
2170 break;
2171
2172 if (count >= 0)
2173 fatal (*expanding_var,
2174 _("unterminated call to function `%s': missing `%c'"),
2175 entry_p->name, closeparen);
2176
2177 *stringp = end;
2178
2179 /* Get some memory to store the arg pointers. */
2180 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2181
2182 /* Chop the string into arguments, then a nul. As soon as we hit
2183 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2184 last argument.
2185
2186 If we're expanding, store pointers to the expansion of each one. If
2187 not, make a duplicate of the string and point into that, nul-terminating
2188 each argument. */
2189
2190 if (entry_p->expand_args)
2191 {
2192 const char *p;
2193 for (p=beg, nargs=0; p <= end; ++argvp)
2194 {
2195 const char *next;
2196
2197 ++nargs;
2198
2199 if (nargs == entry_p->maximum_args
2200 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2201 next = end;
2202
2203 *argvp = expand_argument (p, next);
2204 p = next + 1;
2205 }
2206 }
2207 else
2208 {
2209 int len = end - beg;
2210 char *p, *aend;
2211
2212 abeg = xmalloc (len+1);
2213 memcpy (abeg, beg, len);
2214 abeg[len] = '\0';
2215 aend = abeg + len;
2216
2217 for (p=abeg, nargs=0; p <= aend; ++argvp)
2218 {
2219 char *next;
2220
2221 ++nargs;
2222
2223 if (nargs == entry_p->maximum_args
2224 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2225 next = aend;
2226
2227 *argvp = p;
2228 *next = '\0';
2229 p = next + 1;
2230 }
2231 }
2232 *argvp = NULL;
2233
2234 /* Finally! Run the function... */
2235 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2236
2237 /* Free memory. */
2238 if (entry_p->expand_args)
2239 for (argvp=argv; *argvp != 0; ++argvp)
2240 free (*argvp);
2241 if (abeg)
2242 free (abeg);
2243
2244 return 1;
2245}
2246
2247
2248
2249/* User-defined functions. Expand the first argument as either a builtin
2250 function or a make variable, in the context of the rest of the arguments
2251 assigned to $1, $2, ... $N. $0 is the name of the function. */
2252
2253static char *
2254func_call (char *o, char **argv, const char *funcname UNUSED)
2255{
2256 static int max_args = 0;
2257 char *fname;
2258 char *cp;
2259 char *body;
2260 int flen;
2261 int i;
2262 int saved_args;
2263 const struct function_table_entry *entry_p;
2264 struct variable *v;
2265
2266 /* There is no way to define a variable with a space in the name, so strip
2267 leading and trailing whitespace as a favor to the user. */
2268 fname = argv[0];
2269 while (*fname != '\0' && isspace ((unsigned char)*fname))
2270 ++fname;
2271
2272 cp = fname + strlen (fname) - 1;
2273 while (cp > fname && isspace ((unsigned char)*cp))
2274 --cp;
2275 cp[1] = '\0';
2276
2277 /* Calling nothing is a no-op */
2278 if (*fname == '\0')
2279 return o;
2280
2281 /* Are we invoking a builtin function? */
2282
2283 entry_p = lookup_function (fname);
2284 if (entry_p)
2285 {
2286 /* How many arguments do we have? */
2287 for (i=0; argv[i+1]; ++i)
2288 ;
2289 return expand_builtin_function (o, i, argv+1, entry_p);
2290 }
2291
2292 /* Not a builtin, so the first argument is the name of a variable to be
2293 expanded and interpreted as a function. Find it. */
2294 flen = strlen (fname);
2295
2296 v = lookup_variable (fname, flen);
2297
2298 if (v == 0)
2299 warn_undefined (fname, flen);
2300
2301 if (v == 0 || *v->value == '\0')
2302 return o;
2303
2304 body = alloca (flen + 4);
2305 body[0] = '$';
2306 body[1] = '(';
2307 memcpy (body + 2, fname, flen);
2308 body[flen+2] = ')';
2309 body[flen+3] = '\0';
2310
2311 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2312
2313 push_new_variable_scope ();
2314
2315 for (i=0; *argv; ++i, ++argv)
2316 {
2317 char num[11];
2318
2319 sprintf (num, "%d", i);
2320 define_variable (num, strlen (num), *argv, o_automatic, 0);
2321 }
2322
2323 /* If the number of arguments we have is < max_args, it means we're inside
2324 a recursive invocation of $(call ...). Fill in the remaining arguments
2325 in the new scope with the empty value, to hide them from this
2326 invocation. */
2327
2328 for (; i < max_args; ++i)
2329 {
2330 char num[11];
2331
2332 sprintf (num, "%d", i);
2333 define_variable (num, strlen (num), "", o_automatic, 0);
2334 }
2335
2336 /* Expand the body in the context of the arguments, adding the result to
2337 the variable buffer. */
2338
2339 v->exp_count = EXP_COUNT_MAX;
2340
2341 saved_args = max_args;
2342 max_args = i;
2343 o = variable_expand_string (o, body, flen+3);
2344 max_args = saved_args;
2345
2346 v->exp_count = 0;
2347
2348 pop_variable_scope ();
2349
2350 return o + strlen (o);
2351}
2352
2353void
2354hash_init_function_table (void)
2355{
2356 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2357 function_table_entry_hash_1, function_table_entry_hash_2,
2358 function_table_entry_hash_cmp);
2359 hash_load (&function_table, function_table_init,
2360 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
2361}
Note: See TracBrowser for help on using the repository browser.

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