VirtualBox

source: kBuild/vendor/gnumake/2005-05-16/function.c

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

Current make snaphot, 2005-05-16.

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