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