1 /* Builtin function expansion for GNU Make.
2 Copyright (C) 1988,89,91,92,93,94,95,96,97 Free Software Foundation, Inc.
3 This file is part of GNU Make.
5 GNU Make is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 GNU Make is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNU Make; see the file COPYING. If not, write to
17 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
33 struct function_table_entry
39 char *(*func_ptr
) PARAMS((char *output
, char **argv
, const char*funcname
));
43 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
44 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
45 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
46 nonzero, substitutions are done only on matches which are complete
47 whitespace-delimited words. If SUFFIX_ONLY is nonzero, substitutions are
48 done only at the ends of whitespace-delimited words. */
51 subst_expand (o
, text
, subst
, replace
, slen
, rlen
, by_word
, suffix_only
)
54 char *subst
, *replace
;
55 unsigned int slen
, rlen
;
56 int by_word
, suffix_only
;
58 register char *t
= text
;
61 if (slen
== 0 && !by_word
&& !suffix_only
)
63 /* The first occurrence of "" in any string is its end. */
64 o
= variable_buffer_output (o
, t
, strlen (t
));
66 o
= variable_buffer_output (o
, replace
, rlen
);
72 if ((by_word
| suffix_only
) && slen
== 0)
73 /* When matching by words, the empty string should match
74 the end of each word, rather than the end of the whole text. */
75 p
= end_of_token (next_token (t
));
78 p
= sindex (t
, 0, subst
, slen
);
81 /* No more matches. Output everything left on the end. */
82 o
= variable_buffer_output (o
, t
, strlen (t
));
87 /* Output everything before this occurrence of the string to replace. */
89 o
= variable_buffer_output (o
, t
, p
- t
);
91 /* If we're substituting only by fully matched words,
92 or only at the ends of words, check that this case qualifies. */
94 && ((p
> t
&& !isblank (p
[-1]))
95 || (p
[slen
] != '\0' && !isblank (p
[slen
]))))
97 && (p
[slen
] != '\0' && !isblank (p
[slen
]))))
98 /* Struck out. Output the rest of the string that is
99 no longer to be replaced. */
100 o
= variable_buffer_output (o
, subst
, slen
);
102 /* Output the replacement string. */
103 o
= variable_buffer_output (o
, replace
, rlen
);
105 /* Advance T past the string to be replaced. */
107 } while (*t
!= '\0');
113 /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
114 and replacing strings matching PATTERN with REPLACE.
115 If PATTERN_PERCENT is not nil, PATTERN has already been
116 run through find_percent, and PATTERN_PERCENT is the result.
117 If REPLACE_PERCENT is not nil, REPLACE has already been
118 run through find_percent, and REPLACE_PERCENT is the result. */
121 patsubst_expand (o
, text
, pattern
, replace
, pattern_percent
, replace_percent
)
124 register char *pattern
, *replace
;
125 register char *pattern_percent
, *replace_percent
;
127 unsigned int pattern_prepercent_len
, pattern_postpercent_len
;
128 unsigned int replace_prepercent_len
, replace_postpercent_len
= 0;
133 /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
134 will be collapsed before we call subst_expand if PATTERN has no %. */
135 if (replace_percent
== 0)
136 replace_percent
= find_percent (replace
);
137 if (replace_percent
!= 0)
139 /* Record the length of REPLACE before and after the % so
140 we don't have to compute these lengths more than once. */
141 replace_prepercent_len
= replace_percent
- replace
;
142 replace_postpercent_len
= strlen (replace_percent
+ 1);
145 /* We store the length of the replacement
146 so we only need to compute it once. */
147 replace_prepercent_len
= strlen (replace
);
149 if (pattern_percent
== 0)
150 pattern_percent
= find_percent (pattern
);
151 if (pattern_percent
== 0)
152 /* With no % in the pattern, this is just a simple substitution. */
153 return subst_expand (o
, text
, pattern
, replace
,
154 strlen (pattern
), strlen (replace
), 1, 0);
156 /* Record the length of PATTERN before and after the %
157 so we don't have to compute it more than once. */
158 pattern_prepercent_len
= pattern_percent
- pattern
;
159 pattern_postpercent_len
= strlen (pattern_percent
+ 1);
161 while ((t
= find_next_token (&text
, &len
)) != 0)
165 /* Is it big enough to match? */
166 if (len
< pattern_prepercent_len
+ pattern_postpercent_len
)
169 /* Does the prefix match? */
170 if (!fail
&& pattern_prepercent_len
> 0
172 || t
[pattern_prepercent_len
- 1] != pattern_percent
[-1]
173 || !strneq (t
+ 1, pattern
+ 1, pattern_prepercent_len
- 1)))
176 /* Does the suffix match? */
177 if (!fail
&& pattern_postpercent_len
> 0
178 && (t
[len
- 1] != pattern_percent
[pattern_postpercent_len
]
179 || t
[len
- pattern_postpercent_len
] != pattern_percent
[1]
180 || !strneq (&t
[len
- pattern_postpercent_len
],
181 &pattern_percent
[1], pattern_postpercent_len
- 1)))
185 /* It didn't match. Output the string. */
186 o
= variable_buffer_output (o
, t
, len
);
189 /* It matched. Output the replacement. */
191 /* Output the part of the replacement before the %. */
192 o
= variable_buffer_output (o
, replace
, replace_prepercent_len
);
194 if (replace_percent
!= 0)
196 /* Output the part of the matched string that
197 matched the % in the pattern. */
198 o
= variable_buffer_output (o
, t
+ pattern_prepercent_len
,
199 len
- (pattern_prepercent_len
200 + pattern_postpercent_len
));
201 /* Output the part of the replacement after the %. */
202 o
= variable_buffer_output (o
, replace_percent
+ 1,
203 replace_postpercent_len
);
207 /* Output a space, but not if the replacement is "". */
208 if (fail
|| replace_prepercent_len
> 0
209 || (replace_percent
!= 0 && len
+ replace_postpercent_len
> 0))
211 o
= variable_buffer_output (o
, " ", 1);
216 /* Kill the last space. */
223 /* Look up a function by name.
224 The table is currently small enough that it's not really worthwhile to use
225 a fancier lookup algorithm. If it gets larger, maybe...
228 static const struct function_table_entry
*
229 lookup_function (table
, s
)
230 const struct function_table_entry
*table
;
235 for (; table
->name
!= NULL
; ++table
)
236 if (table
->len
<= len
237 && (isblank (s
[table
->len
]) || s
[table
->len
] == '\0')
238 && strneq (s
, table
->name
, table
->len
))
245 /* Return 1 if PATTERN matches STR, 0 if not. */
248 pattern_matches (pattern
, percent
, str
)
249 register char *pattern
, *percent
, *str
;
251 unsigned int sfxlen
, strlength
;
255 unsigned int len
= strlen (pattern
) + 1;
256 char *new_chars
= (char *) alloca (len
);
257 bcopy (pattern
, new_chars
, len
);
259 percent
= find_percent (pattern
);
261 return streq (pattern
, str
);
264 sfxlen
= strlen (percent
+ 1);
265 strlength
= strlen (str
);
267 if (strlength
< (percent
- pattern
) + sfxlen
268 || !strneq (pattern
, str
, percent
- pattern
))
271 return !strcmp (percent
+ 1, str
+ (strlength
- sfxlen
));
275 /* Find the next comma or ENDPAREN (counting nested STARTPAREN and
276 ENDPARENtheses), starting at PTR before END. Return a pointer to
279 If no next argument is found, return NULL.
283 find_next_argument (startparen
, endparen
, ptr
, end
)
291 for (; ptr
< end
; ++ptr
)
292 if (*ptr
== startparen
)
295 else if (*ptr
== endparen
)
302 else if (*ptr
== ',' && !count
)
305 /* We didn't find anything. */
310 /* Glob-expand LINE. The returned pointer is
311 only good until the next call to string_glob. */
317 static char *result
= 0;
318 static unsigned int length
;
319 register struct nameseq
*chain
;
320 register unsigned int idx
;
322 chain
= multi_glob (parse_file_seq
323 (&line
, '\0', sizeof (struct nameseq
),
324 /* We do not want parse_file_seq to strip `./'s.
325 That would break examples like:
326 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
328 sizeof (struct nameseq
));
333 result
= (char *) xmalloc (100);
339 register char *name
= chain
->name
;
340 unsigned int len
= strlen (name
);
342 struct nameseq
*next
= chain
->next
;
343 free ((char *) chain
);
346 /* multi_glob will pass names without globbing metacharacters
347 through as is, but we want only files that actually exist. */
348 if (file_exists_p (name
))
350 if (idx
+ len
+ 1 > length
)
352 length
+= (len
+ 1) * 2;
353 result
= (char *) xrealloc (result
, length
);
355 bcopy (name
, &result
[idx
], len
);
363 /* Kill the last space and terminate the string. */
367 result
[idx
- 1] = '\0';
377 func_patsubst (o
, argv
, funcname
)
380 const char *funcname
;
382 o
= patsubst_expand (o
, argv
[2], argv
[0], argv
[1], (char *) 0, (char *) 0);
388 func_join(o
, argv
, funcname
)
391 const char *funcname
;
395 /* Write each word of the first argument directly followed
396 by the corresponding word of the second argument.
397 If the two arguments have a different number of words,
398 the excess words are just output separated by blanks. */
401 char *list1_iterator
= argv
[0];
402 char *list2_iterator
= argv
[1];
405 unsigned int len1
, len2
;
407 tp
= find_next_token (&list1_iterator
, &len1
);
409 o
= variable_buffer_output (o
, tp
, len1
);
411 pp
= find_next_token (&list2_iterator
, &len2
);
413 o
= variable_buffer_output (o
, pp
, len2
);
415 if (tp
!= 0 || pp
!= 0)
417 o
= variable_buffer_output (o
, " ", 1);
421 while (tp
!= 0 || pp
!= 0);
423 /* Kill the last blank. */
431 func_origin(o
, argv
, funcname
)
434 const char *funcname
;
436 /* Expand the argument. */
437 register struct variable
*v
= lookup_variable (argv
[0], strlen (argv
[0]));
439 o
= variable_buffer_output (o
, "undefined", 9);
448 o
= variable_buffer_output (o
, "default", 7);
451 o
= variable_buffer_output (o
, "environment", 11);
454 o
= variable_buffer_output (o
, "file", 4);
457 o
= variable_buffer_output (o
, "environment override", 20);
460 o
= variable_buffer_output (o
, "command line", 12);
463 o
= variable_buffer_output (o
, "override", 8);
466 o
= variable_buffer_output (o
, "automatic", 9);
474 #define IS_PATHSEP(c) ((c) == ']')
476 #if defined(__MSDOS__) || defined(WINDOWS32)
477 #define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
479 #define IS_PATHSEP(c) ((c) == '/')
485 func_notdir_suffix(o
, argv
, funcname
)
488 const char *funcname
;
490 /* Expand the argument. */
491 char *list_iterator
= argv
[0];
496 int is_suffix
= streq(funcname
, "suffix");
497 int is_notdir
= !is_suffix
;
498 while ((p2
= find_next_token (&list_iterator
, &len
)) != 0)
503 while (p
>= p2
&& (!is_suffix
|| *p
!= '.'))
516 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
518 #if defined(WINDOWS32) || defined(__MSDOS__)
519 /* Handle the case of "d:foo/bar". */
520 else if (streq(funcname
, "notdir") && p2
[0] && p2
[1] == ':')
523 o
= variable_buffer_output (o
, p
, len
- (p
- p2
));
527 o
= variable_buffer_output (o
, p2
, len
);
529 if (is_notdir
|| p
>= p2
)
531 o
= variable_buffer_output (o
, " ", 1);
536 /* Kill last space. */
546 func_basename_dir(o
, argv
, funcname
)
549 const char *funcname
;
551 /* Expand the argument. */
557 int is_basename
= streq(funcname
, "basename");
558 int is_dir
= !is_basename
;
560 while ((p2
= find_next_token (&p3
, &len
)) != 0)
563 while (p
>= p2
&& (!is_basename
|| *p
!= '.'))
570 if (p
>= p2
&& (is_dir
))
571 o
= variable_buffer_output (o
, p2
, ++p
- p2
);
572 else if (p
>= p2
&& (*p
== '.'))
573 o
= variable_buffer_output (o
, p2
, p
- p2
);
574 #if defined(WINDOWS32) || defined(__MSDOS__)
575 /* Handle the "d:foobar" case */
576 else if (p2
[0] && p2
[1] == ':' && is_dir
)
577 o
= variable_buffer_output (o
, p2
, 2);
581 o
= variable_buffer_output (o
, "[]", 2);
584 o
= variable_buffer_output (o
, "./", 2);
586 ; /* Just a nop... */
590 /* The entire name is the basename. */
591 o
= variable_buffer_output (o
, p2
, len
);
593 o
= variable_buffer_output (o
, " ", 1);
597 /* Kill last space. */
605 func_addsuffix_addprefix(o
, argv
, funcname
)
608 const char *funcname
;
610 int fixlen
= strlen (argv
[0]);
611 char *list_iterator
= argv
[1];
612 int is_addprefix
= streq (funcname
, "addprefix");
613 int is_addsuffix
= !is_addprefix
;
619 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
622 o
= variable_buffer_output (o
, argv
[0], fixlen
);
623 o
= variable_buffer_output (o
, p
, len
);
625 o
= variable_buffer_output (o
, argv
[0], fixlen
);
626 o
= variable_buffer_output (o
, " ", 1);
631 /* Kill last space. */
638 func_subst(o
, argv
, funcname
)
641 const char *funcname
;
643 o
= subst_expand (o
, argv
[2], argv
[0], argv
[1], strlen (argv
[0]),
644 strlen (argv
[1]), 0, 0);
651 func_firstword(o
, argv
, funcname
)
654 const char *funcname
;
657 char *words
= argv
[0]; /* Use a temp variable for find_next_token */
658 char *p
= find_next_token (&words
, &i
);
661 o
= variable_buffer_output (o
, p
, i
);
668 func_words(o
, argv
, funcname
)
671 const char *funcname
;
674 char *word_iterator
= argv
[0];
677 while (find_next_token (&word_iterator
, (unsigned int *) 0) != 0)
680 sprintf (buf
, "%d", i
);
681 o
= variable_buffer_output (o
, buf
, strlen (buf
));
688 strip_whitespace (begpp
, endpp
)
692 while (isspace ((unsigned char)**begpp
) && *begpp
<= *endpp
)
694 while (isspace ((unsigned char)**endpp
) && *endpp
>= *begpp
)
703 char *end
= p
+ strlen (p
) - 1;
705 strip_whitespace (&p
, &end
);
708 if (!ISDIGIT (*(p
++))) /* ISDIGIT only evals its arg once: see make.h. */
711 return (end
- beg
>= 0);
715 check_numeric (s
, message
)
720 fatal (reading_file
, message
);
726 func_word(o
, argv
, funcname
)
729 const char *funcname
;
735 /* Check the first argument. */
736 check_numeric (argv
[0], _("non-numeric first argument to `word' function"));
740 fatal (reading_file
, _("the `word' function takes a positive index argument"));
744 while ((p
= find_next_token (&end_p
, 0)) != 0)
749 o
= variable_buffer_output (o
, p
, end_p
- p
);
755 func_wordlist (o
, argv
, funcname
)
758 const char *funcname
;
763 /* Check the first argument. */
764 check_numeric (argv
[0],
765 _("non-numeric first argument to `wordlist' function"));
767 check_numeric (argv
[1],
768 _("non-numeric second argument to `wordlist' function"));
775 char *end_p
= argv
[2];
777 int start
= (i
< j
) ? i
: j
;
785 while (((p
= find_next_token (&end_p
, 0)) != 0) && --start
)
789 while (--count
&& (find_next_token (&end_p
, 0) != 0))
791 o
= variable_buffer_output (o
, p
, end_p
- p
);
798 func_findstring(o
, argv
, funcname
)
801 const char *funcname
;
803 /* Find the first occurrence of the first string in the second. */
804 int i
= strlen (argv
[0]);
805 if (sindex (argv
[1], 0, argv
[0], i
) != 0)
806 o
= variable_buffer_output (o
, argv
[0], i
);
812 func_foreach (o
, argv
, funcname
)
815 const char *funcname
;
817 /* expand only the first two. */
818 char *varname
= expand_argument (argv
[0], argv
[1] - 1);
819 char *list
= expand_argument (argv
[1], argv
[2] -1);
820 char *body
= savestring (argv
[2], argv
[3] - argv
[2] - 1);
823 char *list_iterator
= list
;
826 register struct variable
*var
;
828 push_new_variable_scope ();
829 var
= define_variable (varname
, strlen (varname
), "", o_automatic
, 0);
831 /* loop through LIST, put the value in VAR and expand BODY */
832 while ((p
= find_next_token (&list_iterator
, &len
)) != 0)
841 var
->value
= (char *) xstrdup ((char*) p
);
845 result
= allocated_variable_expand (body
);
847 o
= variable_buffer_output (o
, result
, strlen (result
));
848 o
= variable_buffer_output (o
, " ", 1);
854 /* Kill the last space. */
857 pop_variable_scope ();
873 func_filter_filterout (o
, argv
, funcname
)
876 const char *funcname
;
878 struct a_word
*wordhead
= 0;
879 struct a_word
*wordtail
= 0;
881 int is_filter
= streq (funcname
, "filter");
882 char *patterns
= argv
[0];
883 char *word_iterator
= argv
[1];
888 /* Chop ARGV[1] up into words and then run each pattern through. */
889 while ((p
= find_next_token (&word_iterator
, &len
)) != 0)
891 struct a_word
*w
= (struct a_word
*)alloca(sizeof(struct a_word
));
898 if (*word_iterator
!= '\0')
907 char *pat_iterator
= patterns
;
913 /* Run each pattern through the words, killing words. */
914 while ((p
= find_next_token (&pat_iterator
, &len
)) != 0)
920 percent
= find_percent (p
);
921 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
922 wp
->matched
|= (percent
== 0 ? streq (p
, wp
->str
)
923 : pattern_matches (p
, percent
, wp
->str
));
928 /* Output the words that matched (or didn't, for filter-out). */
929 for (wp
= wordhead
; wp
!= 0; wp
= wp
->next
)
930 if (is_filter
? wp
->matched
: !wp
->matched
)
932 o
= variable_buffer_output (o
, wp
->str
, strlen (wp
->str
));
933 o
= variable_buffer_output (o
, " ", 1);
938 /* Kill the last space. */
947 func_strip(o
, argv
, funcname
)
950 const char *funcname
;
960 while (isspace ((unsigned char)*p
))
963 for (i
=0; *p
!= '\0' && !isspace ((unsigned char)*p
); ++p
, ++i
)
967 o
= variable_buffer_output (o
, word_start
, i
);
968 o
= variable_buffer_output (o
, " ", 1);
973 /* Kill the last space. */
979 Print a warning or fatal message.
982 func_error (o
, argv
, funcname
)
985 const char *funcname
;
991 /* The arguments will be broken on commas. Rather than create yet
992 another special case where function arguments aren't broken up,
993 just create a format string that puts them back together. */
994 for (len
=0, argvp
=argv
; *argvp
!= 0; ++argvp
)
995 len
+= strlen(*argvp
) + 2;
997 p
= msg
= alloca (len
+ 1);
999 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1002 p
+= strlen(*argvp
);
1008 if (*funcname
== 'e')
1009 fatal (reading_file
, "%s", msg
);
1011 /* The warning function expands to the empty string. */
1012 error (reading_file
, "%s", msg
);
1019 chop argv[0] into words, and sort them.
1022 func_sort (o
, argv
, funcname
)
1025 const char *funcname
;
1029 register int wordi
= 0;
1031 /* Chop ARGV[0] into words and put them in WORDS. */
1037 while ((p
= find_next_token (&t
, &len
)) != 0)
1039 if (wordi
>= nwords
- 1)
1041 nwords
= (2 * nwords
) + 5;
1042 words
= (char **) xrealloc ((char *) words
,
1043 nwords
* sizeof (char *));
1045 words
[wordi
++] = savestring (p
, len
);
1051 /* Now sort the list of words. */
1052 qsort ((char *) words
, wordi
, sizeof (char *), alpha_compare
);
1054 /* Now write the sorted list. */
1055 for (i
= 0; i
< wordi
; ++i
)
1057 len
= strlen (words
[i
]);
1058 if (i
== wordi
- 1 || strlen (words
[i
+ 1]) != len
1059 || strcmp (words
[i
], words
[i
+ 1]))
1061 o
= variable_buffer_output (o
, words
[i
], len
);
1062 o
= variable_buffer_output (o
, " ", 1);
1066 /* Kill the last space. */
1075 $(if condition,true-part[,false-part])
1077 CONDITION is false iff it evaluates to an empty string. White
1078 space before and after condition are stripped before evaluation.
1080 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1081 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1082 you can use $(if ...) to create side-effects (with $(shell ...), for
1087 func_if (o
, argv
, funcname
)
1090 const char *funcname
;
1092 char *begp
= argv
[0];
1093 char *endp
= argv
[1]-1;
1096 /* Find the result of the condition: if we have a value, and it's not
1097 empty, the condition is true. If we don't have a value, or it's the
1098 empty string, then it's false. */
1100 strip_whitespace (&begp
, &endp
);
1104 char *expansion
= expand_argument (begp
, endp
);
1106 result
= strlen (expansion
);
1110 /* If the result is true (1) we want to eval the first argument, and if
1111 it's false (0) we want to eval the second. If the argument doesn't
1112 exist we do nothing, otherwise expand it and add to the buffer. */
1114 argv
+= 1 + !result
;
1116 if (argv
[0] != NULL
&& argv
[1] != NULL
)
1119 char **argend
= argv
+1;
1121 /* If we're doing the else-clause, make sure we concatenate any
1122 potential extra arguments into the last argument. */
1127 expansion
= expand_argument (*argv
, *argend
-1);
1129 o
= variable_buffer_output (o
, expansion
, strlen (expansion
));
1137 func_wildcard(o
, argv
, funcname
)
1140 const char *funcname
;
1144 o
= wildcard_expansion (argv
[0], o
);
1146 char *p
= string_glob (argv
[0]);
1147 o
= variable_buffer_output (o
, p
, strlen (p
));
1153 \r is replaced on UNIX as well. Is this desirable?
1156 fold_newlines (buffer
, length
)
1162 char *last_nonnl
= buffer
-1;
1164 for (; *src
!= '\0'; ++src
)
1166 if (src
[0] == '\r' && src
[1] == '\n')
1178 *(++last_nonnl
) = '\0';
1179 *length
= last_nonnl
- buffer
;
1184 int shell_function_pid
= 0, shell_function_completed
;
1190 #include <windows.h>
1192 #include "sub_proc.h"
1196 windows32_openpipe (int *pipedes
, int *pid_p
, char **command_argv
, char **envp
)
1198 SECURITY_ATTRIBUTES saAttr
;
1206 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
1207 saAttr
.bInheritHandle
= TRUE
;
1208 saAttr
.lpSecurityDescriptor
= NULL
;
1210 if (DuplicateHandle(GetCurrentProcess(),
1211 GetStdHandle(STD_INPUT_HANDLE
),
1212 GetCurrentProcess(),
1216 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1217 fatal (NILF
, _("create_child_process: DuplicateHandle(In) failed (e=%d)\n"),
1221 if (DuplicateHandle(GetCurrentProcess(),
1222 GetStdHandle(STD_ERROR_HANDLE
),
1223 GetCurrentProcess(),
1227 DUPLICATE_SAME_ACCESS
) == FALSE
) {
1228 fatal (NILF
, _("create_child_process: DuplicateHandle(Err) failed (e=%d)\n"),
1232 if (!CreatePipe(&hChildOutRd
, &hChildOutWr
, &saAttr
, 0))
1233 fatal (NILF
, _("CreatePipe() failed (e=%d)\n"), GetLastError());
1237 hProcess
= process_init_fd(hIn
, hChildOutWr
, hErr
);
1240 fatal (NILF
, _("windows32_openpipe (): process_init_fd() failed\n"));
1243 process_register(hProcess
);
1245 /* make sure that CreateProcess() has Path it needs */
1246 sync_Path_environment();
1248 if (!process_begin(hProcess
, command_argv
, envp
, command_argv
[0], NULL
))
1249 *pid_p
= (int) hProcess
;
1251 fatal (NILF
, _("windows32_openpipe (): unable to launch process (e=%d)\n"),
1252 process_last_err(hProcess
));
1254 /* set up to read data from child */
1255 pipedes
[0] = _open_osfhandle((long) hChildOutRd
, O_RDONLY
);
1257 /* this will be closed almost right away */
1258 pipedes
[1] = _open_osfhandle((long) hChildOutWr
, O_APPEND
);
1265 msdos_openpipe (int* pipedes
, int *pidp
, char *text
)
1268 /* MSDOS can't fork, but it has `popen'. */
1269 struct variable
*sh
= lookup_variable ("SHELL", 5);
1271 extern int dos_command_running
, dos_status
;
1273 /* Make sure not to bother processing an empty line. */
1274 while (isblank (*text
))
1281 char buf
[PATH_MAX
+ 7];
1282 /* This makes sure $SHELL value is used by $(shell), even
1283 though the target environment is not passed to it. */
1284 sprintf (buf
, "SHELL=%s", sh
->value
);
1290 dos_command_running
= 1;
1292 /* If dos_status becomes non-zero, it means the child process
1293 was interrupted by a signal, like SIGINT or SIGQUIT. See
1294 fatal_error_signal in commands.c. */
1295 fpipe
= popen (text
, "rt");
1296 dos_command_running
= 0;
1297 if (!fpipe
|| dos_status
)
1303 else if (errno
== 0)
1305 shell_function_completed
= -1;
1309 pipedes
[0] = fileno (fpipe
);
1310 *pidp
= 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
1312 shell_function_completed
= 1;
1319 Do shell spawning, with the naughty bits for different OSes.
1324 /* VMS can't do $(shell ...) */
1325 #define func_shell 0
1330 func_shell (o
, argv
, funcname
)
1333 const char *funcname
;
1335 char* batch_filename
= NULL
;
1341 char **command_argv
;
1348 /* Construct the argument list. */
1349 command_argv
= construct_command_argv (argv
[0],
1350 (char **) NULL
, (struct file
*) 0,
1352 if (command_argv
== 0)
1356 /* Using a target environment for `shell' loses in cases like:
1357 export var = $(shell echo foobie)
1358 because target_environment hits a loop trying to expand $(var)
1359 to put it in the environment. This is even more confusing when
1360 var was not explicitly exported, but just appeared in the
1361 calling environment. */
1365 /* For error messages. */
1366 if (reading_file
!= 0)
1368 error_prefix
= (char *) alloca (strlen(reading_file
->filenm
)+11+4);
1369 sprintf (error_prefix
,
1370 "%s:%lu: ", reading_file
->filenm
, reading_file
->lineno
);
1376 windows32_openpipe (pipedes
, &pid
, command_argv
, envp
);
1377 #else /* WINDOWS32 */
1380 fpipe
= msdos_openpipe (pipedes
, &pid
, argv
[0]);
1383 perror_with_name (error_prefix
, "pipe");
1387 if (pipe (pipedes
) < 0)
1389 perror_with_name (error_prefix
, "pipe");
1395 perror_with_name (error_prefix
, "fork");
1397 child_execute_job (0, pipedes
[1], command_argv
, envp
);
1399 # endif /* ! __MSDOS__ */
1401 #endif /* WINDOWS32 */
1403 /* We are the parent. */
1406 unsigned int maxlen
;
1409 /* Record the PID for reap_children. */
1410 shell_function_pid
= pid
;
1412 shell_function_completed
= 0;
1414 /* Free the storage only the child needed. */
1415 free (command_argv
[0]);
1416 free ((char *) command_argv
);
1418 /* Close the write side of the pipe. */
1419 (void) close (pipedes
[1]);
1422 /* Set up and read from the pipe. */
1425 buffer
= (char *) xmalloc (maxlen
+ 1);
1427 /* Read from the pipe until it gets EOF. */
1434 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1438 cc
= read (pipedes
[0], &buffer
[i
], maxlen
- i
);
1442 while (cc
> 0 || EINTR_SET
);
1444 /* Close the read side of the pipe. */
1447 (void) pclose (fpipe
);
1449 (void) close (pipedes
[0]);
1452 /* Loop until child_handler sets shell_function_completed
1453 to the status of our child shell. */
1454 while (shell_function_completed
== 0)
1455 reap_children (1, 0);
1457 if (batch_filename
) {
1458 DB (DB_EXTRA
, (_("Cleaning up temporary batch file %s\n"),
1460 remove(batch_filename
);
1461 free(batch_filename
);
1463 shell_function_pid
= 0;
1465 /* The child_handler function will set shell_function_completed
1466 to 1 when the child dies normally, or to -1 if it
1467 dies with status 127, which is most likely an exec fail. */
1469 if (shell_function_completed
== -1)
1471 /* This most likely means that the execvp failed,
1472 so we should just write out the error message
1473 that came in over the pipe from the child. */
1474 fputs (buffer
, stderr
);
1479 /* The child finished normally. Replace all
1480 newlines in its output with spaces, and put
1481 that in the variable output buffer. */
1482 fold_newlines (buffer
, &i
);
1483 o
= variable_buffer_output (o
, buffer
, i
);
1494 /* Do the Amiga version of func_shell. */
1497 func_shell (char *o
, char **argv
, const char *funcname
)
1499 /* Amiga can't fork nor spawn, but I can start a program with
1500 redirection of my choice. However, this means that we
1501 don't have an opportunity to reopen stdout to trap it. Thus,
1502 we save our own stdout onto a new descriptor and dup a temp
1503 file's descriptor onto our stdout temporarily. After we
1504 spawn the shell program, we dup our own stdout back to the
1505 stdout descriptor. The buffer reading is the same as above,
1506 except that we're now reading from a file. */
1508 #include <dos/dos.h>
1509 #include <proto/dos.h>
1512 char tmp_output
[FILENAME_MAX
];
1513 unsigned int maxlen
= 200;
1515 char * buffer
, * ptr
;
1518 char* batch_filename
= NULL
;
1520 /* Construct the argument list. */
1521 command_argv
= construct_command_argv (argv
[0], (char **) NULL
,
1522 (struct file
*) 0, &batch_filename
);
1523 if (command_argv
== 0)
1527 strcpy (tmp_output
, "t:MakeshXXXXXXXX");
1528 mktemp (tmp_output
);
1529 child_stdout
= Open (tmp_output
, MODE_NEWFILE
);
1531 for (aptr
=command_argv
; *aptr
; aptr
++)
1532 len
+= strlen (*aptr
) + 1;
1534 buffer
= xmalloc (len
+ 1);
1537 for (aptr
=command_argv
; *aptr
; aptr
++)
1539 strcpy (ptr
, *aptr
);
1540 ptr
+= strlen (ptr
) + 1;
1547 Execute (buffer
, NULL
, child_stdout
);
1550 Close (child_stdout
);
1552 child_stdout
= Open (tmp_output
, MODE_OLDFILE
);
1554 buffer
= xmalloc (maxlen
);
1561 buffer
= (char *) xrealloc (buffer
, maxlen
+ 1);
1564 cc
= Read (child_stdout
, &buffer
[i
], maxlen
- i
);
1569 Close (child_stdout
);
1571 fold_newlines (buffer
, &i
);
1572 o
= variable_buffer_output (o
, buffer
, i
);
1582 equality. Return is string-boolean, ie, the empty string is false.
1585 func_eq (char* o
, char **argv
, char *funcname
)
1587 int result
= ! strcmp (argv
[0], argv
[1]);
1588 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1594 string-boolean not operator.
1597 func_not (char* o
, char **argv
, char *funcname
)
1601 while (isspace ((unsigned char)*s
))
1604 o
= variable_buffer_output (o
, result
? "1" : "", result
);
1610 #define STRING_SIZE_TUPLE(_s) (_s), (sizeof(_s)-1)
1612 /* Lookup table for builtin functions.
1614 This doesn't have to be sorted; we use a straight lookup. We might gain
1615 some efficiency by moving most often used functions to the start of the
1618 If REQUIRED_ARGS is positive, the function takes exactly that many
1619 arguments. All subsequent text is included with the last argument. So,
1620 since $(sort a,b,c) takes only one argument, it will be the full string
1621 "a,b,c". If the value is negative, it's the minimum number of arguments.
1622 A function can have more, but if it has less an error is generated.
1624 EXPAND_ARGS means that all arguments should be expanded before invocation.
1625 Functions that do namespace tricks (foreach) don't automatically expand. */
1627 static char *func_call
PARAMS((char *o
, char **argv
, const char *funcname
));
1630 static struct function_table_entry function_table
[] =
1632 /* Name/size */ /* ARG EXP? Function */
1633 { STRING_SIZE_TUPLE("addprefix"), 2, 1, func_addsuffix_addprefix
},
1634 { STRING_SIZE_TUPLE("addsuffix"), 2, 1, func_addsuffix_addprefix
},
1635 { STRING_SIZE_TUPLE("basename"), 1, 1, func_basename_dir
},
1636 { STRING_SIZE_TUPLE("dir"), 1, 1, func_basename_dir
},
1637 { STRING_SIZE_TUPLE("notdir"), 1, 1, func_notdir_suffix
},
1638 { STRING_SIZE_TUPLE("subst"), 3, 1, func_subst
},
1639 { STRING_SIZE_TUPLE("suffix"), 1, 1, func_notdir_suffix
},
1640 { STRING_SIZE_TUPLE("filter"), 2, 1, func_filter_filterout
},
1641 { STRING_SIZE_TUPLE("filter-out"), 2, 1, func_filter_filterout
},
1642 { STRING_SIZE_TUPLE("findstring"), 2, 1, func_findstring
},
1643 { STRING_SIZE_TUPLE("firstword"), 1, 1, func_firstword
},
1644 { STRING_SIZE_TUPLE("join"), 2, 1, func_join
},
1645 { STRING_SIZE_TUPLE("patsubst"), 3, 1, func_patsubst
},
1646 { STRING_SIZE_TUPLE("shell"), 1, 1, func_shell
},
1647 { STRING_SIZE_TUPLE("sort"), 1, 1, func_sort
},
1648 { STRING_SIZE_TUPLE("strip"), 1, 1, func_strip
},
1649 { STRING_SIZE_TUPLE("wildcard"), 1, 1, func_wildcard
},
1650 { STRING_SIZE_TUPLE("word"), 2, 1, func_word
},
1651 { STRING_SIZE_TUPLE("wordlist"), 3, 1, func_wordlist
},
1652 { STRING_SIZE_TUPLE("words"), 1, 1, func_words
},
1653 { STRING_SIZE_TUPLE("origin"), 1, 1, func_origin
},
1654 { STRING_SIZE_TUPLE("foreach"), 3, 0, func_foreach
},
1655 { STRING_SIZE_TUPLE("call"), -1, 1, func_call
},
1656 { STRING_SIZE_TUPLE("error"), 1, 1, func_error
},
1657 { STRING_SIZE_TUPLE("warning"), 1, 1, func_error
},
1658 { STRING_SIZE_TUPLE("if"), -2, 0, func_if
},
1660 { STRING_SIZE_TUPLE("eq"), 2, 1, func_eq
},
1661 { STRING_SIZE_TUPLE("not"), 1, 1, func_not
},
1667 /* These must come after the definition of function_table[]. */
1670 expand_builtin_function (o
, argc
, argv
, entry_p
)
1674 struct function_table_entry
*entry_p
;
1676 int min
= (entry_p
->required_args
> 0
1677 ? entry_p
->required_args
1678 : -entry_p
->required_args
);
1681 fatal (reading_file
,
1682 _("Insufficient number of arguments (%d) to function `%s'"),
1683 argc
, entry_p
->name
);
1685 if (!entry_p
->func_ptr
)
1686 fatal (reading_file
, _("Unimplemented on this platform: function `%s'"),
1689 return entry_p
->func_ptr (o
, argv
, entry_p
->name
);
1692 /* Check for a function invocation in *STRINGP. *STRINGP points at the
1693 opening ( or { and is not null-terminated. If a function invocation
1694 is found, expand it into the buffer at *OP, updating *OP, incrementing
1695 *STRINGP past the reference and returning nonzero. If not, return zero. */
1698 handle_function (op
, stringp
)
1702 const struct function_table_entry
*entry_p
;
1703 char openparen
= (*stringp
)[0];
1704 char closeparen
= openparen
== '(' ? ')' : '}';
1705 char *beg
= *stringp
+ 1;
1710 char **argv
, **argvp
;
1713 entry_p
= lookup_function (function_table
, beg
);
1718 /* We have found a call to a builtin function. Find the end of the
1719 arguments, and do the function. */
1721 endref
= beg
+ entry_p
->len
;
1723 /* Space after function name isn't part of the args. */
1724 p
= next_token (endref
);
1727 /* Find the end of the function invocation, counting nested use of
1728 whichever kind of parens we use. Since we're looking, count commas
1729 to get a rough estimate of how many arguments we might have. The
1730 count might be high, but it'll never be low. */
1732 for (nargs
=1; *p
!= '\0'; ++p
)
1735 else if (*p
== openparen
)
1737 else if (*p
== closeparen
&& --count
< 0)
1741 fatal (reading_file
,
1742 _("unterminated call to function `%s': missing `%c'"),
1743 entry_p
->name
, closeparen
);
1745 /* Get some memory to store the arg pointers. */
1746 argvp
= argv
= (char **) alloca (sizeof(char *) * (nargs
+ 2));
1748 /* Chop the string into arguments, then store the end pointer and a nul.
1749 If REQUIRED_ARGS is positive, as soon as we hit that many assume the
1750 rest of the string is part of the last argument. */
1753 while (entry_p
->required_args
< 0 || nargs
< entry_p
->required_args
)
1755 char *next
= find_next_argument (openparen
, closeparen
, *argvp
, p
);
1760 *(++argvp
) = next
+1;
1767 /* If we should expand, do it. */
1768 if (entry_p
->expand_args
)
1770 for (argvp
=argv
; argvp
[1] != 0; ++argvp
)
1771 *argvp
= expand_argument (*argvp
, argvp
[1]-1);
1773 /* end pointer doesn't make sense for expanded stuff. */
1777 /* Finally! Run the function... */
1778 *op
= expand_builtin_function (*op
, nargs
, argv
, entry_p
);
1780 /* If we allocated memory for the expanded args, free it again. */
1781 if (entry_p
->expand_args
)
1782 for (argvp
=argv
; *argvp
!= 0; ++argvp
)
1791 /* User-defined functions. Expand the first argument as either a builtin
1792 function or a make variable, in the context of the rest of the arguments
1793 assigned to $1, $2, ... $N. $0 is the name of the function. */
1796 func_call (o
, argv
, funcname
)
1799 const char *funcname
;
1805 const struct function_table_entry
*entry_p
;
1807 /* Calling nothing is a no-op. */
1808 if (*argv
[0] == '\0')
1811 /* There is no way to define a variable with a space in the name, so strip
1812 trailing whitespace as a favor to the user. */
1814 flen
= strlen (argv
[0]);
1815 fname
= argv
[0] + flen
- 1;
1816 while (isspace ((unsigned char)*fname
))
1820 flen
= fname
- argv
[0] + 1;
1823 /* Are we invoking a builtin function? */
1825 entry_p
= lookup_function (function_table
, fname
);
1829 for (i
=0; argv
[i
+1]; ++i
)
1832 return expand_builtin_function (o
, i
, argv
+ 1, entry_p
);
1835 /* No, so the first argument is the name of a variable to be expanded and
1836 interpreted as a function. Create the variable reference. */
1837 body
= alloca (flen
+ 4);
1840 strcpy (body
+ 2, fname
);
1844 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
1846 push_new_variable_scope ();
1848 for (i
=0; *argv
; ++i
, ++argv
)
1852 sprintf (num
, "%d", i
);
1853 define_variable (num
, strlen (num
), *argv
, o_automatic
, 0);
1856 /* Expand the body in the context of the arguments, adding the result to
1857 the variable buffer. */
1859 o
= variable_expand_string (o
, body
, flen
+3);
1861 pop_variable_scope ();
1863 return o
+ strlen(o
);