VirtualBox

source: kBuild/trunk/src/gmake/function.c@ 503

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

Untested merge with GNU Make v3.81 (vendor/gnumake/2005-05-16 -> vendor/gnumake/current).

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

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