VirtualBox

source: kBuild/vendor/gnumake/3.82-cvs/function.c

Last change on this file was 2580, checked in by bird, 12 years ago

Importing the make-3-82 CVS tag with --auto-props but no keywords.

  • Property svn:eol-style set to native
File size: 58.9 KB
Line 
1/* Builtin function expansion for GNU Make.
2Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
31998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
42010 Free Software Foundation, 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 = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
365 /* We do not want parse_file_seq to strip `./'s.
366 That would break examples like:
367 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
368 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
369
370 if (result == 0)
371 {
372 length = 100;
373 result = xmalloc (100);
374 }
375
376 idx = 0;
377 while (chain != 0)
378 {
379 struct nameseq *next = chain->next;
380 unsigned int len = strlen (chain->name);
381
382 if (idx + len + 1 > length)
383 {
384 length += (len + 1) * 2;
385 result = xrealloc (result, length);
386 }
387 memcpy (&result[idx], chain->name, len);
388 idx += len;
389 result[idx++] = ' ';
390
391 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
392 free ((char *)chain->name);
393 free (chain);
394 chain = next;
395 }
396
397 /* Kill the last space and terminate the string. */
398 if (idx == 0)
399 result[0] = '\0';
400 else
401 result[idx - 1] = '\0';
402
403 return result;
404}
405
406
407/*
408 Builtin functions
409 */
410
411static char *
412func_patsubst (char *o, char **argv, const char *funcname UNUSED)
413{
414 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
415 return o;
416}
417
418
419static char *
420func_join (char *o, char **argv, const char *funcname UNUSED)
421{
422 int doneany = 0;
423
424 /* Write each word of the first argument directly followed
425 by the corresponding word of the second argument.
426 If the two arguments have a different number of words,
427 the excess words are just output separated by blanks. */
428 const char *tp;
429 const char *pp;
430 const char *list1_iterator = argv[0];
431 const char *list2_iterator = argv[1];
432 do
433 {
434 unsigned int len1, len2;
435
436 tp = find_next_token (&list1_iterator, &len1);
437 if (tp != 0)
438 o = variable_buffer_output (o, tp, len1);
439
440 pp = find_next_token (&list2_iterator, &len2);
441 if (pp != 0)
442 o = variable_buffer_output (o, pp, len2);
443
444 if (tp != 0 || pp != 0)
445 {
446 o = variable_buffer_output (o, " ", 1);
447 doneany = 1;
448 }
449 }
450 while (tp != 0 || pp != 0);
451 if (doneany)
452 /* Kill the last blank. */
453 --o;
454
455 return o;
456}
457
458
459static char *
460func_origin (char *o, char **argv, const char *funcname UNUSED)
461{
462 /* Expand the argument. */
463 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
464 if (v == 0)
465 o = variable_buffer_output (o, "undefined", 9);
466 else
467 switch (v->origin)
468 {
469 default:
470 case o_invalid:
471 abort ();
472 break;
473 case o_default:
474 o = variable_buffer_output (o, "default", 7);
475 break;
476 case o_env:
477 o = variable_buffer_output (o, "environment", 11);
478 break;
479 case o_file:
480 o = variable_buffer_output (o, "file", 4);
481 break;
482 case o_env_override:
483 o = variable_buffer_output (o, "environment override", 20);
484 break;
485 case o_command:
486 o = variable_buffer_output (o, "command line", 12);
487 break;
488 case o_override:
489 o = variable_buffer_output (o, "override", 8);
490 break;
491 case o_automatic:
492 o = variable_buffer_output (o, "automatic", 9);
493 break;
494 }
495
496 return o;
497}
498
499static char *
500func_flavor (char *o, char **argv, const char *funcname UNUSED)
501{
502 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
503
504 if (v == 0)
505 o = variable_buffer_output (o, "undefined", 9);
506 else
507 if (v->recursive)
508 o = variable_buffer_output (o, "recursive", 9);
509 else
510 o = variable_buffer_output (o, "simple", 6);
511
512 return o;
513}
514
515#ifdef VMS
516# define IS_PATHSEP(c) ((c) == ']')
517#else
518# ifdef HAVE_DOS_PATHS
519# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
520# else
521# define IS_PATHSEP(c) ((c) == '/')
522# endif
523#endif
524
525
526static char *
527func_notdir_suffix (char *o, char **argv, const char *funcname)
528{
529 /* Expand the argument. */
530 const char *list_iterator = argv[0];
531 const char *p2;
532 int doneany =0;
533 unsigned int len=0;
534
535 int is_suffix = streq (funcname, "suffix");
536 int is_notdir = !is_suffix;
537 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
538 {
539 const char *p = p2 + len;
540
541
542 while (p >= p2 && (!is_suffix || *p != '.'))
543 {
544 if (IS_PATHSEP (*p))
545 break;
546 --p;
547 }
548
549 if (p >= p2)
550 {
551 if (is_notdir)
552 ++p;
553 else if (*p != '.')
554 continue;
555 o = variable_buffer_output (o, p, len - (p - p2));
556 }
557#ifdef HAVE_DOS_PATHS
558 /* Handle the case of "d:foo/bar". */
559 else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
560 {
561 p = p2 + 2;
562 o = variable_buffer_output (o, p, len - (p - p2));
563 }
564#endif
565 else if (is_notdir)
566 o = variable_buffer_output (o, p2, len);
567
568 if (is_notdir || p >= p2)
569 {
570 o = variable_buffer_output (o, " ", 1);
571 doneany = 1;
572 }
573 }
574
575 if (doneany)
576 /* Kill last space. */
577 --o;
578
579 return o;
580}
581
582
583static char *
584func_basename_dir (char *o, char **argv, const char *funcname)
585{
586 /* Expand the argument. */
587 const char *p3 = argv[0];
588 const char *p2;
589 int doneany=0;
590 unsigned int len=0;
591
592 int is_basename= streq (funcname, "basename");
593 int is_dir= !is_basename;
594
595 while ((p2 = find_next_token (&p3, &len)) != 0)
596 {
597 const char *p = p2 + len;
598 while (p >= p2 && (!is_basename || *p != '.'))
599 {
600 if (IS_PATHSEP (*p))
601 break;
602 --p;
603 }
604
605 if (p >= p2 && (is_dir))
606 o = variable_buffer_output (o, p2, ++p - p2);
607 else if (p >= p2 && (*p == '.'))
608 o = variable_buffer_output (o, p2, p - p2);
609#ifdef HAVE_DOS_PATHS
610 /* Handle the "d:foobar" case */
611 else if (p2[0] && p2[1] == ':' && is_dir)
612 o = variable_buffer_output (o, p2, 2);
613#endif
614 else if (is_dir)
615#ifdef VMS
616 o = variable_buffer_output (o, "[]", 2);
617#else
618#ifndef _AMIGA
619 o = variable_buffer_output (o, "./", 2);
620#else
621 ; /* Just a nop... */
622#endif /* AMIGA */
623#endif /* !VMS */
624 else
625 /* The entire name is the basename. */
626 o = variable_buffer_output (o, p2, len);
627
628 o = variable_buffer_output (o, " ", 1);
629 doneany = 1;
630 }
631
632 if (doneany)
633 /* Kill last space. */
634 --o;
635
636 return o;
637}
638
639static char *
640func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
641{
642 int fixlen = strlen (argv[0]);
643 const char *list_iterator = argv[1];
644 int is_addprefix = streq (funcname, "addprefix");
645 int is_addsuffix = !is_addprefix;
646
647 int doneany = 0;
648 const char *p;
649 unsigned int len;
650
651 while ((p = find_next_token (&list_iterator, &len)) != 0)
652 {
653 if (is_addprefix)
654 o = variable_buffer_output (o, argv[0], fixlen);
655 o = variable_buffer_output (o, p, len);
656 if (is_addsuffix)
657 o = variable_buffer_output (o, argv[0], fixlen);
658 o = variable_buffer_output (o, " ", 1);
659 doneany = 1;
660 }
661
662 if (doneany)
663 /* Kill last space. */
664 --o;
665
666 return o;
667}
668
669static char *
670func_subst (char *o, char **argv, const char *funcname UNUSED)
671{
672 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
673 strlen (argv[1]), 0);
674
675 return o;
676}
677
678
679static char *
680func_firstword (char *o, char **argv, const char *funcname UNUSED)
681{
682 unsigned int i;
683 const char *words = argv[0]; /* Use a temp variable for find_next_token */
684 const char *p = find_next_token (&words, &i);
685
686 if (p != 0)
687 o = variable_buffer_output (o, p, i);
688
689 return o;
690}
691
692static char *
693func_lastword (char *o, char **argv, const char *funcname UNUSED)
694{
695 unsigned int i;
696 const char *words = argv[0]; /* Use a temp variable for find_next_token */
697 const char *p = NULL;
698 const char *t;
699
700 while ((t = find_next_token (&words, &i)))
701 p = t;
702
703 if (p != 0)
704 o = variable_buffer_output (o, p, i);
705
706 return o;
707}
708
709static char *
710func_words (char *o, char **argv, const char *funcname UNUSED)
711{
712 int i = 0;
713 const char *word_iterator = argv[0];
714 char buf[20];
715
716 while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
717 ++i;
718
719 sprintf (buf, "%d", i);
720 o = variable_buffer_output (o, buf, strlen (buf));
721
722 return o;
723}
724
725/* Set begpp to point to the first non-whitespace character of the string,
726 * and endpp to point to the last non-whitespace character of the string.
727 * If the string is empty or contains nothing but whitespace, endpp will be
728 * begpp-1.
729 */
730char *
731strip_whitespace (const char **begpp, const char **endpp)
732{
733 while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
734 (*begpp) ++;
735 while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
736 (*endpp) --;
737 return (char *)*begpp;
738}
739
740static void
741check_numeric (const char *s, const char *msg)
742{
743 const char *end = s + strlen (s) - 1;
744 const char *beg = s;
745 strip_whitespace (&s, &end);
746
747 for (; s <= end; ++s)
748 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see make.h. */
749 break;
750
751 if (s <= end || end - beg < 0)
752 fatal (*expanding_var, "%s: '%s'", msg, beg);
753}
754
755
756
757static char *
758func_word (char *o, char **argv, const char *funcname UNUSED)
759{
760 const char *end_p;
761 const char *p;
762 int i;
763
764 /* Check the first argument. */
765 check_numeric (argv[0], _("non-numeric first argument to `word' function"));
766 i = atoi (argv[0]);
767
768 if (i == 0)
769 fatal (*expanding_var,
770 _("first argument to `word' function must be greater than 0"));
771
772 end_p = argv[1];
773 while ((p = find_next_token (&end_p, 0)) != 0)
774 if (--i == 0)
775 break;
776
777 if (i == 0)
778 o = variable_buffer_output (o, p, end_p - p);
779
780 return o;
781}
782
783static char *
784func_wordlist (char *o, char **argv, const char *funcname UNUSED)
785{
786 int start, count;
787
788 /* Check the arguments. */
789 check_numeric (argv[0],
790 _("non-numeric first argument to `wordlist' function"));
791 check_numeric (argv[1],
792 _("non-numeric second argument to `wordlist' function"));
793
794 start = atoi (argv[0]);
795 if (start < 1)
796 fatal (*expanding_var,
797 "invalid first argument to `wordlist' function: `%d'", start);
798
799 count = atoi (argv[1]) - start + 1;
800
801 if (count > 0)
802 {
803 const char *p;
804 const char *end_p = argv[2];
805
806 /* Find the beginning of the "start"th word. */
807 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
808 ;
809
810 if (p)
811 {
812 /* Find the end of the "count"th word from start. */
813 while (--count && (find_next_token (&end_p, 0) != 0))
814 ;
815
816 /* Return the stuff in the middle. */
817 o = variable_buffer_output (o, p, end_p - p);
818 }
819 }
820
821 return o;
822}
823
824static char *
825func_findstring (char *o, char **argv, const char *funcname UNUSED)
826{
827 /* Find the first occurrence of the first string in the second. */
828 if (strstr (argv[1], argv[0]) != 0)
829 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
830
831 return o;
832}
833
834static char *
835func_foreach (char *o, char **argv, const char *funcname UNUSED)
836{
837 /* expand only the first two. */
838 char *varname = expand_argument (argv[0], NULL);
839 char *list = expand_argument (argv[1], NULL);
840 const char *body = argv[2];
841
842 int doneany = 0;
843 const char *list_iterator = list;
844 const char *p;
845 unsigned int len;
846 struct variable *var;
847
848 push_new_variable_scope ();
849 var = define_variable (varname, strlen (varname), "", o_automatic, 0);
850
851 /* loop through LIST, put the value in VAR and expand BODY */
852 while ((p = find_next_token (&list_iterator, &len)) != 0)
853 {
854 char *result = 0;
855
856 free (var->value);
857 var->value = xstrndup (p, len);
858
859 result = allocated_variable_expand (body);
860
861 o = variable_buffer_output (o, result, strlen (result));
862 o = variable_buffer_output (o, " ", 1);
863 doneany = 1;
864 free (result);
865 }
866
867 if (doneany)
868 /* Kill the last space. */
869 --o;
870
871 pop_variable_scope ();
872 free (varname);
873 free (list);
874
875 return o;
876}
877
878struct a_word
879{
880 struct a_word *next;
881 struct a_word *chain;
882 char *str;
883 int length;
884 int matched;
885};
886
887static unsigned long
888a_word_hash_1 (const void *key)
889{
890 return_STRING_HASH_1 (((struct a_word const *) key)->str);
891}
892
893static unsigned long
894a_word_hash_2 (const void *key)
895{
896 return_STRING_HASH_2 (((struct a_word const *) key)->str);
897}
898
899static int
900a_word_hash_cmp (const void *x, const void *y)
901{
902 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
903 if (result)
904 return result;
905 return_STRING_COMPARE (((struct a_word const *) x)->str,
906 ((struct a_word const *) y)->str);
907}
908
909struct a_pattern
910{
911 struct a_pattern *next;
912 char *str;
913 char *percent;
914 int length;
915 int save_c;
916};
917
918static char *
919func_filter_filterout (char *o, char **argv, const char *funcname)
920{
921 struct a_word *wordhead;
922 struct a_word **wordtail;
923 struct a_word *wp;
924 struct a_pattern *pathead;
925 struct a_pattern **pattail;
926 struct a_pattern *pp;
927
928 struct hash_table a_word_table;
929 int is_filter = streq (funcname, "filter");
930 const char *pat_iterator = argv[0];
931 const char *word_iterator = argv[1];
932 int literals = 0;
933 int words = 0;
934 int hashing = 0;
935 char *p;
936 unsigned int len;
937
938 /* Chop ARGV[0] up into patterns to match against the words. */
939
940 pattail = &pathead;
941 while ((p = find_next_token (&pat_iterator, &len)) != 0)
942 {
943 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
944
945 *pattail = pat;
946 pattail = &pat->next;
947
948 if (*pat_iterator != '\0')
949 ++pat_iterator;
950
951 pat->str = p;
952 pat->length = len;
953 pat->save_c = p[len];
954 p[len] = '\0';
955 pat->percent = find_percent (p);
956 if (pat->percent == 0)
957 literals++;
958 }
959 *pattail = 0;
960
961 /* Chop ARGV[1] up into words to match against the patterns. */
962
963 wordtail = &wordhead;
964 while ((p = find_next_token (&word_iterator, &len)) != 0)
965 {
966 struct a_word *word = alloca (sizeof (struct a_word));
967
968 *wordtail = word;
969 wordtail = &word->next;
970
971 if (*word_iterator != '\0')
972 ++word_iterator;
973
974 p[len] = '\0';
975 word->str = p;
976 word->length = len;
977 word->matched = 0;
978 word->chain = 0;
979 words++;
980 }
981 *wordtail = 0;
982
983 /* Only use a hash table if arg list lengths justifies the cost. */
984 hashing = (literals >= 2 && (literals * words) >= 10);
985 if (hashing)
986 {
987 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
988 a_word_hash_cmp);
989 for (wp = wordhead; wp != 0; wp = wp->next)
990 {
991 struct a_word *owp = hash_insert (&a_word_table, wp);
992 if (owp)
993 wp->chain = owp;
994 }
995 }
996
997 if (words)
998 {
999 int doneany = 0;
1000
1001 /* Run each pattern through the words, killing words. */
1002 for (pp = pathead; pp != 0; pp = pp->next)
1003 {
1004 if (pp->percent)
1005 for (wp = wordhead; wp != 0; wp = wp->next)
1006 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1007 else if (hashing)
1008 {
1009 struct a_word a_word_key;
1010 a_word_key.str = pp->str;
1011 a_word_key.length = pp->length;
1012 wp = hash_find_item (&a_word_table, &a_word_key);
1013 while (wp)
1014 {
1015 wp->matched |= 1;
1016 wp = wp->chain;
1017 }
1018 }
1019 else
1020 for (wp = wordhead; wp != 0; wp = wp->next)
1021 wp->matched |= (wp->length == pp->length
1022 && strneq (pp->str, wp->str, wp->length));
1023 }
1024
1025 /* Output the words that matched (or didn't, for filter-out). */
1026 for (wp = wordhead; wp != 0; wp = wp->next)
1027 if (is_filter ? wp->matched : !wp->matched)
1028 {
1029 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1030 o = variable_buffer_output (o, " ", 1);
1031 doneany = 1;
1032 }
1033
1034 if (doneany)
1035 /* Kill the last space. */
1036 --o;
1037 }
1038
1039 for (pp = pathead; pp != 0; pp = pp->next)
1040 pp->str[pp->length] = pp->save_c;
1041
1042 if (hashing)
1043 hash_free (&a_word_table, 0);
1044
1045 return o;
1046}
1047
1048
1049static char *
1050func_strip (char *o, char **argv, const char *funcname UNUSED)
1051{
1052 const char *p = argv[0];
1053 int doneany = 0;
1054
1055 while (*p != '\0')
1056 {
1057 int i=0;
1058 const char *word_start;
1059
1060 while (isspace ((unsigned char)*p))
1061 ++p;
1062 word_start = p;
1063 for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
1064 {}
1065 if (!i)
1066 break;
1067 o = variable_buffer_output (o, word_start, i);
1068 o = variable_buffer_output (o, " ", 1);
1069 doneany = 1;
1070 }
1071
1072 if (doneany)
1073 /* Kill the last space. */
1074 --o;
1075
1076 return o;
1077}
1078
1079/*
1080 Print a warning or fatal message.
1081*/
1082static char *
1083func_error (char *o, char **argv, const char *funcname)
1084{
1085 char **argvp;
1086 char *msg, *p;
1087 int len;
1088
1089 /* The arguments will be broken on commas. Rather than create yet
1090 another special case where function arguments aren't broken up,
1091 just create a format string that puts them back together. */
1092 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1093 len += strlen (*argvp) + 2;
1094
1095 p = msg = alloca (len + 1);
1096
1097 for (argvp=argv; argvp[1] != 0; ++argvp)
1098 {
1099 strcpy (p, *argvp);
1100 p += strlen (*argvp);
1101 *(p++) = ',';
1102 *(p++) = ' ';
1103 }
1104 strcpy (p, *argvp);
1105
1106 switch (*funcname) {
1107 case 'e':
1108 fatal (reading_file, "%s", msg);
1109
1110 case 'w':
1111 error (reading_file, "%s", msg);
1112 break;
1113
1114 case 'i':
1115 printf ("%s\n", msg);
1116 fflush(stdout);
1117 break;
1118
1119 default:
1120 fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
1121 }
1122
1123 /* The warning function expands to the empty string. */
1124 return o;
1125}
1126
1127
1128/*
1129 chop argv[0] into words, and sort them.
1130 */
1131static char *
1132func_sort (char *o, char **argv, const char *funcname UNUSED)
1133{
1134 const char *t;
1135 char **words;
1136 int wordi;
1137 char *p;
1138 unsigned int len;
1139 int i;
1140
1141 /* Find the maximum number of words we'll have. */
1142 t = argv[0];
1143 wordi = 1;
1144 while (*t != '\0')
1145 {
1146 char c = *(t++);
1147
1148 if (! isspace ((unsigned char)c))
1149 continue;
1150
1151 ++wordi;
1152
1153 while (isspace ((unsigned char)*t))
1154 ++t;
1155 }
1156
1157 words = xmalloc (wordi * sizeof (char *));
1158
1159 /* Now assign pointers to each string in the array. */
1160 t = argv[0];
1161 wordi = 0;
1162 while ((p = find_next_token (&t, &len)) != 0)
1163 {
1164 ++t;
1165 p[len] = '\0';
1166 words[wordi++] = p;
1167 }
1168
1169 if (wordi)
1170 {
1171 /* Now sort the list of words. */
1172 qsort (words, wordi, sizeof (char *), alpha_compare);
1173
1174 /* Now write the sorted list, uniquified. */
1175 for (i = 0; i < wordi; ++i)
1176 {
1177 len = strlen (words[i]);
1178 if (i == wordi - 1 || strlen (words[i + 1]) != len
1179 || strcmp (words[i], words[i + 1]))
1180 {
1181 o = variable_buffer_output (o, words[i], len);
1182 o = variable_buffer_output (o, " ", 1);
1183 }
1184 }
1185
1186 /* Kill the last space. */
1187 --o;
1188 }
1189
1190 free (words);
1191
1192 return o;
1193}
1194
1195/*
1196 $(if condition,true-part[,false-part])
1197
1198 CONDITION is false iff it evaluates to an empty string. White
1199 space before and after condition are stripped before evaluation.
1200
1201 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1202 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1203 you can use $(if ...) to create side-effects (with $(shell ...), for
1204 example).
1205*/
1206
1207static char *
1208func_if (char *o, char **argv, const char *funcname UNUSED)
1209{
1210 const char *begp = argv[0];
1211 const char *endp = begp + strlen (argv[0]) - 1;
1212 int result = 0;
1213
1214 /* Find the result of the condition: if we have a value, and it's not
1215 empty, the condition is true. If we don't have a value, or it's the
1216 empty string, then it's false. */
1217
1218 strip_whitespace (&begp, &endp);
1219
1220 if (begp <= endp)
1221 {
1222 char *expansion = expand_argument (begp, endp+1);
1223
1224 result = strlen (expansion);
1225 free (expansion);
1226 }
1227
1228 /* If the result is true (1) we want to eval the first argument, and if
1229 it's false (0) we want to eval the second. If the argument doesn't
1230 exist we do nothing, otherwise expand it and add to the buffer. */
1231
1232 argv += 1 + !result;
1233
1234 if (*argv)
1235 {
1236 char *expansion = expand_argument (*argv, NULL);
1237
1238 o = variable_buffer_output (o, expansion, strlen (expansion));
1239
1240 free (expansion);
1241 }
1242
1243 return o;
1244}
1245
1246/*
1247 $(or condition1[,condition2[,condition3[...]]])
1248
1249 A CONDITION is false iff it evaluates to an empty string. White
1250 space before and after CONDITION are stripped before evaluation.
1251
1252 CONDITION1 is evaluated. If it's true, then this is the result of
1253 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1254 the conditions are true, the expansion is the empty string.
1255
1256 Once a CONDITION is true no further conditions are evaluated
1257 (short-circuiting).
1258*/
1259
1260static char *
1261func_or (char *o, char **argv, const char *funcname UNUSED)
1262{
1263 for ( ; *argv ; ++argv)
1264 {
1265 const char *begp = *argv;
1266 const char *endp = begp + strlen (*argv) - 1;
1267 char *expansion;
1268 int result = 0;
1269
1270 /* Find the result of the condition: if it's false keep going. */
1271
1272 strip_whitespace (&begp, &endp);
1273
1274 if (begp > endp)
1275 continue;
1276
1277 expansion = expand_argument (begp, endp+1);
1278 result = strlen (expansion);
1279
1280 /* If the result is false keep going. */
1281 if (!result)
1282 {
1283 free (expansion);
1284 continue;
1285 }
1286
1287 /* It's true! Keep this result and return. */
1288 o = variable_buffer_output (o, expansion, result);
1289 free (expansion);
1290 break;
1291 }
1292
1293 return o;
1294}
1295
1296/*
1297 $(and condition1[,condition2[,condition3[...]]])
1298
1299 A CONDITION is false iff it evaluates to an empty string. White
1300 space before and after CONDITION are stripped before evaluation.
1301
1302 CONDITION1 is evaluated. If it's false, then this is the result of
1303 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1304 the conditions are true, the expansion is the result of the last condition.
1305
1306 Once a CONDITION is false no further conditions are evaluated
1307 (short-circuiting).
1308*/
1309
1310static char *
1311func_and (char *o, char **argv, const char *funcname UNUSED)
1312{
1313 char *expansion;
1314 int result;
1315
1316 while (1)
1317 {
1318 const char *begp = *argv;
1319 const char *endp = begp + strlen (*argv) - 1;
1320
1321 /* An empty condition is always false. */
1322 strip_whitespace (&begp, &endp);
1323 if (begp > endp)
1324 return o;
1325
1326 expansion = expand_argument (begp, endp+1);
1327 result = strlen (expansion);
1328
1329 /* If the result is false, stop here: we're done. */
1330 if (!result)
1331 break;
1332
1333 /* Otherwise the result is true. If this is the last one, keep this
1334 result and quit. Otherwise go on to the next one! */
1335
1336 if (*(++argv))
1337 free (expansion);
1338 else
1339 {
1340 o = variable_buffer_output (o, expansion, result);
1341 break;
1342 }
1343 }
1344
1345 free (expansion);
1346
1347 return o;
1348}
1349
1350static char *
1351func_wildcard (char *o, char **argv, const char *funcname UNUSED)
1352{
1353#ifdef _AMIGA
1354 o = wildcard_expansion (argv[0], o);
1355#else
1356 char *p = string_glob (argv[0]);
1357 o = variable_buffer_output (o, p, strlen (p));
1358#endif
1359 return o;
1360}
1361
1362/*
1363 $(eval <makefile string>)
1364
1365 Always resolves to the empty string.
1366
1367 Treat the arguments as a segment of makefile, and parse them.
1368*/
1369
1370static char *
1371func_eval (char *o, char **argv, const char *funcname UNUSED)
1372{
1373 char *buf;
1374 unsigned int len;
1375
1376 /* Eval the buffer. Pop the current variable buffer setting so that the
1377 eval'd code can use its own without conflicting. */
1378
1379 install_variable_buffer (&buf, &len);
1380
1381 eval_buffer (argv[0]);
1382
1383 restore_variable_buffer (buf, len);
1384
1385 return o;
1386}
1387
1388
1389static char *
1390func_value (char *o, char **argv, const char *funcname UNUSED)
1391{
1392 /* Look up the variable. */
1393 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
1394
1395 /* Copy its value into the output buffer without expanding it. */
1396 if (v)
1397 o = variable_buffer_output (o, v->value, strlen(v->value));
1398
1399 return o;
1400}
1401
1402/*
1403 \r is replaced on UNIX as well. Is this desirable?
1404 */
1405static void
1406fold_newlines (char *buffer, unsigned int *length)
1407{
1408 char *dst = buffer;
1409 char *src = buffer;
1410 char *last_nonnl = buffer -1;
1411 src[*length] = 0;
1412 for (; *src != '\0'; ++src)
1413 {
1414 if (src[0] == '\r' && src[1] == '\n')
1415 continue;
1416 if (*src == '\n')
1417 {
1418 *dst++ = ' ';
1419 }
1420 else
1421 {
1422 last_nonnl = dst;
1423 *dst++ = *src;
1424 }
1425 }
1426 *(++last_nonnl) = '\0';
1427 *length = last_nonnl - buffer;
1428}
1429
1430
1431
1432int shell_function_pid = 0, shell_function_completed;
1433
1434
1435#ifdef WINDOWS32
1436/*untested*/
1437
1438#include <windows.h>
1439#include <io.h>
1440#include "sub_proc.h"
1441
1442
1443void
1444windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
1445{
1446 SECURITY_ATTRIBUTES saAttr;
1447 HANDLE hIn;
1448 HANDLE hErr;
1449 HANDLE hChildOutRd;
1450 HANDLE hChildOutWr;
1451 HANDLE hProcess;
1452
1453
1454 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
1455 saAttr.bInheritHandle = TRUE;
1456 saAttr.lpSecurityDescriptor = NULL;
1457
1458 if (DuplicateHandle (GetCurrentProcess(),
1459 GetStdHandle(STD_INPUT_HANDLE),
1460 GetCurrentProcess(),
1461 &hIn,
1462 0,
1463 TRUE,
1464 DUPLICATE_SAME_ACCESS) == FALSE) {
1465 fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
1466 GetLastError());
1467
1468 }
1469 if (DuplicateHandle(GetCurrentProcess(),
1470 GetStdHandle(STD_ERROR_HANDLE),
1471 GetCurrentProcess(),
1472 &hErr,
1473 0,
1474 TRUE,
1475 DUPLICATE_SAME_ACCESS) == FALSE) {
1476 fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
1477 GetLastError());
1478 }
1479
1480 if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
1481 fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
1482
1483 hProcess = process_init_fd(hIn, hChildOutWr, hErr);
1484
1485 if (!hProcess)
1486 fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
1487
1488 /* make sure that CreateProcess() has Path it needs */
1489 sync_Path_environment();
1490 /* `sync_Path_environment' may realloc `environ', so take note of
1491 the new value. */
1492 envp = environ;
1493
1494 if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
1495 /* register process for wait */
1496 process_register(hProcess);
1497
1498 /* set the pid for returning to caller */
1499 *pid_p = (pid_t) hProcess;
1500
1501 /* set up to read data from child */
1502 pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
1503
1504 /* this will be closed almost right away */
1505 pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
1506 } else {
1507 /* reap/cleanup the failed process */
1508 process_cleanup(hProcess);
1509
1510 /* close handles which were duplicated, they weren't used */
1511 CloseHandle(hIn);
1512 CloseHandle(hErr);
1513
1514 /* close pipe handles, they won't be used */
1515 CloseHandle(hChildOutRd);
1516 CloseHandle(hChildOutWr);
1517
1518 /* set status for return */
1519 pipedes[0] = pipedes[1] = -1;
1520 *pid_p = (pid_t)-1;
1521 }
1522}
1523#endif
1524
1525
1526#ifdef __MSDOS__
1527FILE *
1528msdos_openpipe (int* pipedes, int *pidp, char *text)
1529{
1530 FILE *fpipe=0;
1531 /* MSDOS can't fork, but it has `popen'. */
1532 struct variable *sh = lookup_variable ("SHELL", 5);
1533 int e;
1534 extern int dos_command_running, dos_status;
1535
1536 /* Make sure not to bother processing an empty line. */
1537 while (isblank ((unsigned char)*text))
1538 ++text;
1539 if (*text == '\0')
1540 return 0;
1541
1542 if (sh)
1543 {
1544 char buf[PATH_MAX + 7];
1545 /* This makes sure $SHELL value is used by $(shell), even
1546 though the target environment is not passed to it. */
1547 sprintf (buf, "SHELL=%s", sh->value);
1548 putenv (buf);
1549 }
1550
1551 e = errno;
1552 errno = 0;
1553 dos_command_running = 1;
1554 dos_status = 0;
1555 /* If dos_status becomes non-zero, it means the child process
1556 was interrupted by a signal, like SIGINT or SIGQUIT. See
1557 fatal_error_signal in commands.c. */
1558 fpipe = popen (text, "rt");
1559 dos_command_running = 0;
1560 if (!fpipe || dos_status)
1561 {
1562 pipedes[0] = -1;
1563 *pidp = -1;
1564 if (dos_status)
1565 errno = EINTR;
1566 else if (errno == 0)
1567 errno = ENOMEM;
1568 shell_function_completed = -1;
1569 }
1570 else
1571 {
1572 pipedes[0] = fileno (fpipe);
1573 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1574 errno = e;
1575 shell_function_completed = 1;
1576 }
1577 return fpipe;
1578}
1579#endif
1580
1581/*
1582 Do shell spawning, with the naughty bits for different OSes.
1583 */
1584
1585#ifdef VMS
1586
1587/* VMS can't do $(shell ...) */
1588#define func_shell 0
1589
1590#else
1591#ifndef _AMIGA
1592static char *
1593func_shell (char *o, char **argv, const char *funcname UNUSED)
1594{
1595 char *batch_filename = NULL;
1596
1597#ifdef __MSDOS__
1598 FILE *fpipe;
1599#endif
1600 char **command_argv;
1601 const char *error_prefix;
1602 char **envp;
1603 int pipedes[2];
1604 pid_t pid;
1605
1606#ifndef __MSDOS__
1607 /* Construct the argument list. */
1608 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
1609 &batch_filename);
1610 if (command_argv == 0)
1611 return o;
1612#endif
1613
1614 /* Using a target environment for `shell' loses in cases like:
1615 export var = $(shell echo foobie)
1616 because target_environment hits a loop trying to expand $(var)
1617 to put it in the environment. This is even more confusing when
1618 var was not explicitly exported, but just appeared in the
1619 calling environment.
1620
1621 See Savannah bug #10593.
1622
1623 envp = target_environment (NILF);
1624 */
1625
1626 envp = environ;
1627
1628 /* For error messages. */
1629 if (reading_file && reading_file->filenm)
1630 {
1631 char *p = alloca (strlen (reading_file->filenm)+11+4);
1632 sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
1633 error_prefix = p;
1634 }
1635 else
1636 error_prefix = "";
1637
1638#if defined(__MSDOS__)
1639 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
1640 if (pipedes[0] < 0)
1641 {
1642 perror_with_name (error_prefix, "pipe");
1643 return o;
1644 }
1645#elif defined(WINDOWS32)
1646 windows32_openpipe (pipedes, &pid, command_argv, envp);
1647 if (pipedes[0] < 0)
1648 {
1649 /* open of the pipe failed, mark as failed execution */
1650 shell_function_completed = -1;
1651
1652 return o;
1653 }
1654 else
1655#else
1656 if (pipe (pipedes) < 0)
1657 {
1658 perror_with_name (error_prefix, "pipe");
1659 return o;
1660 }
1661
1662# ifdef __EMX__
1663 /* close some handles that are unnecessary for the child process */
1664 CLOSE_ON_EXEC(pipedes[1]);
1665 CLOSE_ON_EXEC(pipedes[0]);
1666 /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
1667 pid = child_execute_job (0, pipedes[1], command_argv, envp);
1668 if (pid < 0)
1669 perror_with_name (error_prefix, "spawn");
1670# else /* ! __EMX__ */
1671 pid = vfork ();
1672 if (pid < 0)
1673 perror_with_name (error_prefix, "fork");
1674 else if (pid == 0)
1675 child_execute_job (0, pipedes[1], command_argv, envp);
1676 else
1677# endif
1678#endif
1679 {
1680 /* We are the parent. */
1681 char *buffer;
1682 unsigned int maxlen, i;
1683 int cc;
1684
1685 /* Record the PID for reap_children. */
1686 shell_function_pid = pid;
1687#ifndef __MSDOS__
1688 shell_function_completed = 0;
1689
1690 /* Free the storage only the child needed. */
1691 free (command_argv[0]);
1692 free (command_argv);
1693
1694 /* Close the write side of the pipe. We test for -1, since
1695 pipedes[1] is -1 on MS-Windows, and some versions of MS
1696 libraries barf when `close' is called with -1. */
1697 if (pipedes[1] >= 0)
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#ifdef HAVE_DOS_PATHS
1890#define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
1891#define ROOT_LEN 3
1892#else
1893#define IS_ABSOLUTE(n) (n[0] == '/')
1894#define ROOT_LEN 1
1895#endif
1896
1897/* Return the absolute name of file NAME which does not contain any `.',
1898 `..' components nor any repeated path separators ('/'). */
1899
1900static char *
1901abspath (const char *name, char *apath)
1902{
1903 char *dest;
1904 const char *start, *end, *apath_limit;
1905 unsigned long root_len = ROOT_LEN;
1906
1907 if (name[0] == '\0' || apath == NULL)
1908 return NULL;
1909
1910 apath_limit = apath + GET_PATH_MAX;
1911
1912 if (!IS_ABSOLUTE(name))
1913 {
1914 /* It is unlikely we would make it until here but just to make sure. */
1915 if (!starting_directory)
1916 return NULL;
1917
1918 strcpy (apath, starting_directory);
1919
1920#ifdef HAVE_DOS_PATHS
1921 if (IS_PATHSEP(name[0]))
1922 {
1923 if (IS_PATHSEP(name[1]))
1924 {
1925 /* A UNC. Don't prepend a drive letter. */
1926 apath[0] = name[0];
1927 apath[1] = name[1];
1928 root_len = 2;
1929 }
1930 /* We have /foo, an absolute file name except for the drive
1931 letter. Assume the missing drive letter is the current
1932 drive, which we can get if we remove from starting_directory
1933 everything past the root directory. */
1934 apath[root_len] = '\0';
1935 }
1936#endif
1937
1938 dest = strchr (apath, '\0');
1939 }
1940 else
1941 {
1942 strncpy (apath, name, root_len);
1943 apath[root_len] = '\0';
1944 dest = apath + root_len;
1945 /* Get past the root, since we already copied it. */
1946 name += root_len;
1947#ifdef HAVE_DOS_PATHS
1948 if (!IS_PATHSEP(apath[2]))
1949 {
1950 /* Convert d:foo into d:./foo and increase root_len. */
1951 apath[2] = '.';
1952 apath[3] = '/';
1953 dest++;
1954 root_len++;
1955 /* strncpy above copied one character too many. */
1956 name--;
1957 }
1958 else
1959 apath[2] = '/'; /* make sure it's a forward slash */
1960#endif
1961 }
1962
1963 for (start = end = name; *start != '\0'; start = end)
1964 {
1965 unsigned long len;
1966
1967 /* Skip sequence of multiple path-separators. */
1968 while (IS_PATHSEP(*start))
1969 ++start;
1970
1971 /* Find end of path component. */
1972 for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
1973 ;
1974
1975 len = end - start;
1976
1977 if (len == 0)
1978 break;
1979 else if (len == 1 && start[0] == '.')
1980 /* nothing */;
1981 else if (len == 2 && start[0] == '.' && start[1] == '.')
1982 {
1983 /* Back up to previous component, ignore if at root already. */
1984 if (dest > apath + root_len)
1985 for (--dest; !IS_PATHSEP(dest[-1]); --dest);
1986 }
1987 else
1988 {
1989 if (!IS_PATHSEP(dest[-1]))
1990 *dest++ = '/';
1991
1992 if (dest + len >= apath_limit)
1993 return NULL;
1994
1995 dest = memcpy (dest, start, len);
1996 dest += len;
1997 *dest = '\0';
1998 }
1999 }
2000
2001 /* Unless it is root strip trailing separator. */
2002 if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
2003 --dest;
2004
2005 *dest = '\0';
2006
2007 return apath;
2008}
2009
2010
2011static char *
2012func_realpath (char *o, char **argv, const char *funcname UNUSED)
2013{
2014 /* Expand the argument. */
2015 const char *p = argv[0];
2016 const char *path = 0;
2017 int doneany = 0;
2018 unsigned int len = 0;
2019#ifndef HAVE_REALPATH
2020 struct stat st;
2021#endif
2022 PATH_VAR (in);
2023 PATH_VAR (out);
2024
2025 while ((path = find_next_token (&p, &len)) != 0)
2026 {
2027 if (len < GET_PATH_MAX)
2028 {
2029 strncpy (in, path, len);
2030 in[len] = '\0';
2031
2032 if (
2033#ifdef HAVE_REALPATH
2034 realpath (in, out)
2035#else
2036 abspath (in, out) && stat (out, &st) == 0
2037#endif
2038 )
2039 {
2040 o = variable_buffer_output (o, out, strlen (out));
2041 o = variable_buffer_output (o, " ", 1);
2042 doneany = 1;
2043 }
2044 }
2045 }
2046
2047 /* Kill last space. */
2048 if (doneany)
2049 --o;
2050
2051 return o;
2052}
2053
2054static char *
2055func_abspath (char *o, char **argv, const char *funcname UNUSED)
2056{
2057 /* Expand the argument. */
2058 const char *p = argv[0];
2059 const char *path = 0;
2060 int doneany = 0;
2061 unsigned int len = 0;
2062 PATH_VAR (in);
2063 PATH_VAR (out);
2064
2065 while ((path = find_next_token (&p, &len)) != 0)
2066 {
2067 if (len < GET_PATH_MAX)
2068 {
2069 strncpy (in, path, len);
2070 in[len] = '\0';
2071
2072 if (abspath (in, out))
2073 {
2074 o = variable_buffer_output (o, out, strlen (out));
2075 o = variable_buffer_output (o, " ", 1);
2076 doneany = 1;
2077 }
2078 }
2079 }
2080
2081 /* Kill last space. */
2082 if (doneany)
2083 --o;
2084
2085 return o;
2086}
2087
2088/* Lookup table for builtin functions.
2089
2090 This doesn't have to be sorted; we use a straight lookup. We might gain
2091 some efficiency by moving most often used functions to the start of the
2092 table.
2093
2094 If MAXIMUM_ARGS is 0, that means there is no maximum and all
2095 comma-separated values are treated as arguments.
2096
2097 EXPAND_ARGS means that all arguments should be expanded before invocation.
2098 Functions that do namespace tricks (foreach) don't automatically expand. */
2099
2100static char *func_call (char *o, char **argv, const char *funcname);
2101
2102
2103static struct function_table_entry function_table_init[] =
2104{
2105 /* Name/size */ /* MIN MAX EXP? Function */
2106 { STRING_SIZE_TUPLE("abspath"), 0, 1, 1, func_abspath},
2107 { STRING_SIZE_TUPLE("addprefix"), 2, 2, 1, func_addsuffix_addprefix},
2108 { STRING_SIZE_TUPLE("addsuffix"), 2, 2, 1, func_addsuffix_addprefix},
2109 { STRING_SIZE_TUPLE("basename"), 0, 1, 1, func_basename_dir},
2110 { STRING_SIZE_TUPLE("dir"), 0, 1, 1, func_basename_dir},
2111 { STRING_SIZE_TUPLE("notdir"), 0, 1, 1, func_notdir_suffix},
2112 { STRING_SIZE_TUPLE("subst"), 3, 3, 1, func_subst},
2113 { STRING_SIZE_TUPLE("suffix"), 0, 1, 1, func_notdir_suffix},
2114 { STRING_SIZE_TUPLE("filter"), 2, 2, 1, func_filter_filterout},
2115 { STRING_SIZE_TUPLE("filter-out"), 2, 2, 1, func_filter_filterout},
2116 { STRING_SIZE_TUPLE("findstring"), 2, 2, 1, func_findstring},
2117 { STRING_SIZE_TUPLE("firstword"), 0, 1, 1, func_firstword},
2118 { STRING_SIZE_TUPLE("flavor"), 0, 1, 1, func_flavor},
2119 { STRING_SIZE_TUPLE("join"), 2, 2, 1, func_join},
2120 { STRING_SIZE_TUPLE("lastword"), 0, 1, 1, func_lastword},
2121 { STRING_SIZE_TUPLE("patsubst"), 3, 3, 1, func_patsubst},
2122 { STRING_SIZE_TUPLE("realpath"), 0, 1, 1, func_realpath},
2123 { STRING_SIZE_TUPLE("shell"), 0, 1, 1, func_shell},
2124 { STRING_SIZE_TUPLE("sort"), 0, 1, 1, func_sort},
2125 { STRING_SIZE_TUPLE("strip"), 0, 1, 1, func_strip},
2126 { STRING_SIZE_TUPLE("wildcard"), 0, 1, 1, func_wildcard},
2127 { STRING_SIZE_TUPLE("word"), 2, 2, 1, func_word},
2128 { STRING_SIZE_TUPLE("wordlist"), 3, 3, 1, func_wordlist},
2129 { STRING_SIZE_TUPLE("words"), 0, 1, 1, func_words},
2130 { STRING_SIZE_TUPLE("origin"), 0, 1, 1, func_origin},
2131 { STRING_SIZE_TUPLE("foreach"), 3, 3, 0, func_foreach},
2132 { STRING_SIZE_TUPLE("call"), 1, 0, 1, func_call},
2133 { STRING_SIZE_TUPLE("info"), 0, 1, 1, func_error},
2134 { STRING_SIZE_TUPLE("error"), 0, 1, 1, func_error},
2135 { STRING_SIZE_TUPLE("warning"), 0, 1, 1, func_error},
2136 { STRING_SIZE_TUPLE("if"), 2, 3, 0, func_if},
2137 { STRING_SIZE_TUPLE("or"), 1, 0, 0, func_or},
2138 { STRING_SIZE_TUPLE("and"), 1, 0, 0, func_and},
2139 { STRING_SIZE_TUPLE("value"), 0, 1, 1, func_value},
2140 { STRING_SIZE_TUPLE("eval"), 0, 1, 1, func_eval},
2141#ifdef EXPERIMENTAL
2142 { STRING_SIZE_TUPLE("eq"), 2, 2, 1, func_eq},
2143 { STRING_SIZE_TUPLE("not"), 0, 1, 1, func_not},
2144#endif
2145};
2146
2147#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
2148
2149
2150
2151/* These must come after the definition of function_table. */
2152
2153static char *
2154expand_builtin_function (char *o, int argc, char **argv,
2155 const struct function_table_entry *entry_p)
2156{
2157 if (argc < (int)entry_p->minimum_args)
2158 fatal (*expanding_var,
2159 _("insufficient number of arguments (%d) to function `%s'"),
2160 argc, entry_p->name);
2161
2162 /* I suppose technically some function could do something with no
2163 arguments, but so far none do, so just test it for all functions here
2164 rather than in each one. We can change it later if necessary. */
2165
2166 if (!argc)
2167 return o;
2168
2169 if (!entry_p->func_ptr)
2170 fatal (*expanding_var,
2171 _("unimplemented on this platform: function `%s'"), entry_p->name);
2172
2173 return entry_p->func_ptr (o, argv, entry_p->name);
2174}
2175
2176/* Check for a function invocation in *STRINGP. *STRINGP points at the
2177 opening ( or { and is not null-terminated. If a function invocation
2178 is found, expand it into the buffer at *OP, updating *OP, incrementing
2179 *STRINGP past the reference and returning nonzero. If not, return zero. */
2180
2181int
2182handle_function (char **op, const char **stringp)
2183{
2184 const struct function_table_entry *entry_p;
2185 char openparen = (*stringp)[0];
2186 char closeparen = openparen == '(' ? ')' : '}';
2187 const char *beg;
2188 const char *end;
2189 int count = 0;
2190 char *abeg = NULL;
2191 char **argv, **argvp;
2192 int nargs;
2193
2194 beg = *stringp + 1;
2195
2196 entry_p = lookup_function (beg);
2197
2198 if (!entry_p)
2199 return 0;
2200
2201 /* We found a builtin function. Find the beginning of its arguments (skip
2202 whitespace after the name). */
2203
2204 beg = next_token (beg + entry_p->len);
2205
2206 /* Find the end of the function invocation, counting nested use of
2207 whichever kind of parens we use. Since we're looking, count commas
2208 to get a rough estimate of how many arguments we might have. The
2209 count might be high, but it'll never be low. */
2210
2211 for (nargs=1, end=beg; *end != '\0'; ++end)
2212 if (*end == ',')
2213 ++nargs;
2214 else if (*end == openparen)
2215 ++count;
2216 else if (*end == closeparen && --count < 0)
2217 break;
2218
2219 if (count >= 0)
2220 fatal (*expanding_var,
2221 _("unterminated call to function `%s': missing `%c'"),
2222 entry_p->name, closeparen);
2223
2224 *stringp = end;
2225
2226 /* Get some memory to store the arg pointers. */
2227 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
2228
2229 /* Chop the string into arguments, then a nul. As soon as we hit
2230 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
2231 last argument.
2232
2233 If we're expanding, store pointers to the expansion of each one. If
2234 not, make a duplicate of the string and point into that, nul-terminating
2235 each argument. */
2236
2237 if (entry_p->expand_args)
2238 {
2239 const char *p;
2240 for (p=beg, nargs=0; p <= end; ++argvp)
2241 {
2242 const char *next;
2243
2244 ++nargs;
2245
2246 if (nargs == entry_p->maximum_args
2247 || (! (next = find_next_argument (openparen, closeparen, p, end))))
2248 next = end;
2249
2250 *argvp = expand_argument (p, next);
2251 p = next + 1;
2252 }
2253 }
2254 else
2255 {
2256 int len = end - beg;
2257 char *p, *aend;
2258
2259 abeg = xmalloc (len+1);
2260 memcpy (abeg, beg, len);
2261 abeg[len] = '\0';
2262 aend = abeg + len;
2263
2264 for (p=abeg, nargs=0; p <= aend; ++argvp)
2265 {
2266 char *next;
2267
2268 ++nargs;
2269
2270 if (nargs == entry_p->maximum_args
2271 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
2272 next = aend;
2273
2274 *argvp = p;
2275 *next = '\0';
2276 p = next + 1;
2277 }
2278 }
2279 *argvp = NULL;
2280
2281 /* Finally! Run the function... */
2282 *op = expand_builtin_function (*op, nargs, argv, entry_p);
2283
2284 /* Free memory. */
2285 if (entry_p->expand_args)
2286 for (argvp=argv; *argvp != 0; ++argvp)
2287 free (*argvp);
2288 if (abeg)
2289 free (abeg);
2290
2291 return 1;
2292}
2293
2294
2295
2296/* User-defined functions. Expand the first argument as either a builtin
2297 function or a make variable, in the context of the rest of the arguments
2298 assigned to $1, $2, ... $N. $0 is the name of the function. */
2299
2300static char *
2301func_call (char *o, char **argv, const char *funcname UNUSED)
2302{
2303 static int max_args = 0;
2304 char *fname;
2305 char *cp;
2306 char *body;
2307 int flen;
2308 int i;
2309 int saved_args;
2310 const struct function_table_entry *entry_p;
2311 struct variable *v;
2312
2313 /* There is no way to define a variable with a space in the name, so strip
2314 leading and trailing whitespace as a favor to the user. */
2315 fname = argv[0];
2316 while (*fname != '\0' && isspace ((unsigned char)*fname))
2317 ++fname;
2318
2319 cp = fname + strlen (fname) - 1;
2320 while (cp > fname && isspace ((unsigned char)*cp))
2321 --cp;
2322 cp[1] = '\0';
2323
2324 /* Calling nothing is a no-op */
2325 if (*fname == '\0')
2326 return o;
2327
2328 /* Are we invoking a builtin function? */
2329
2330 entry_p = lookup_function (fname);
2331 if (entry_p)
2332 {
2333 /* How many arguments do we have? */
2334 for (i=0; argv[i+1]; ++i)
2335 ;
2336 return expand_builtin_function (o, i, argv+1, entry_p);
2337 }
2338
2339 /* Not a builtin, so the first argument is the name of a variable to be
2340 expanded and interpreted as a function. Find it. */
2341 flen = strlen (fname);
2342
2343 v = lookup_variable (fname, flen);
2344
2345 if (v == 0)
2346 warn_undefined (fname, flen);
2347
2348 if (v == 0 || *v->value == '\0')
2349 return o;
2350
2351 body = alloca (flen + 4);
2352 body[0] = '$';
2353 body[1] = '(';
2354 memcpy (body + 2, fname, flen);
2355 body[flen+2] = ')';
2356 body[flen+3] = '\0';
2357
2358 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
2359
2360 push_new_variable_scope ();
2361
2362 for (i=0; *argv; ++i, ++argv)
2363 {
2364 char num[11];
2365
2366 sprintf (num, "%d", i);
2367 define_variable (num, strlen (num), *argv, o_automatic, 0);
2368 }
2369
2370 /* If the number of arguments we have is < max_args, it means we're inside
2371 a recursive invocation of $(call ...). Fill in the remaining arguments
2372 in the new scope with the empty value, to hide them from this
2373 invocation. */
2374
2375 for (; i < max_args; ++i)
2376 {
2377 char num[11];
2378
2379 sprintf (num, "%d", i);
2380 define_variable (num, strlen (num), "", o_automatic, 0);
2381 }
2382
2383 /* Expand the body in the context of the arguments, adding the result to
2384 the variable buffer. */
2385
2386 v->exp_count = EXP_COUNT_MAX;
2387
2388 saved_args = max_args;
2389 max_args = i;
2390 o = variable_expand_string (o, body, flen+3);
2391 max_args = saved_args;
2392
2393 v->exp_count = 0;
2394
2395 pop_variable_scope ();
2396
2397 return o + strlen (o);
2398}
2399
2400void
2401hash_init_function_table (void)
2402{
2403 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
2404 function_table_entry_hash_1, function_table_entry_hash_2,
2405 function_table_entry_hash_cmp);
2406 hash_load (&function_table, function_table_init,
2407 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
2408}
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