VirtualBox

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

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

Must strip trailing slashes in abspath. added tolower and toupper.

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