source: trunk/src/kmk/function.c@ 3157

Last change on this file since 3157 was 3156, checked in by bird, 7 years ago

kmk/win: Reworking child process handling. This effort will hopefully handle processor groups better and allow executing internal function off the main thread.

  • Property svn:eol-style set to native
File size: 171.5 KB
Line 
1/* Builtin function expansion for GNU Make.
2Copyright (C) 1988-2016 Free Software Foundation, Inc.
3This file is part of GNU Make.
4
5GNU Make is free software; you can redistribute it and/or modify it under the
6terms of the GNU General Public License as published by the Free Software
7Foundation; either version 3 of the License, or (at your option) any later
8version.
9
10GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
11WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13
14You should have received a copy of the GNU General Public License along with
15this program. If not, see <http://www.gnu.org/licenses/>. */
16
17#include "makeint.h"
18#include "filedef.h"
19#include "variable.h"
20#include "dep.h"
21#include "job.h"
22#include "commands.h"
23#include "debug.h"
24
25#ifdef _AMIGA
26#include "amiga.h"
27#endif
28
29#ifdef WINDOWS32 /* bird */
30# include "pathstuff.h"
31# ifdef CONFIG_NEW_WIN_CHILDREN
32# include "w32/winchildren.h"
33# endif
34#endif
35
36#ifdef KMK_HELPERS
37# include "kbuild.h"
38#endif
39#ifdef CONFIG_WITH_PRINTF
40# include "kmkbuiltin.h"
41#endif
42#ifdef CONFIG_WITH_XARGS /* bird */
43# ifdef HAVE_LIMITS_H
44# include <limits.h>
45# endif
46#endif
47#ifdef CONFIG_WITH_COMPILER
48# include "kmk_cc_exec.h"
49#endif
50#include <assert.h> /* bird */
51
52#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE) /* bird */
53# include <ctype.h>
54typedef big_int math_int;
55static char *math_int_to_variable_buffer (char *, math_int);
56static math_int math_int_from_string (const char *str);
57#endif
58
59#ifdef CONFIG_WITH_NANOTS /* bird */
60# ifdef WINDOWS32
61# include <Windows.h>
62# endif
63#endif
64
65#ifdef __OS2__
66# define CONFIG_WITH_OS2_LIBPATH 1
67#endif
68#ifdef CONFIG_WITH_OS2_LIBPATH
69# define INCL_BASE
70# define INCL_ERRROS
71# include <os2.h>
72
73# define QHINF_EXEINFO 1 /* NE exeinfo. */
74# define QHINF_READRSRCTBL 2 /* Reads from the resource table. */
75# define QHINF_READFILE 3 /* Reads from the executable file. */
76# define QHINF_LIBPATHLENGTH 4 /* Gets the libpath length. */
77# define QHINF_LIBPATH 5 /* Gets the entire libpath. */
78# define QHINF_FIXENTRY 6 /* NE only */
79# define QHINF_STE 7 /* NE only */
80# define QHINF_MAPSEL 8 /* NE only */
81 extern APIRET APIENTRY DosQueryHeaderInfo(HMODULE hmod, ULONG ulIndex, PVOID pvBuffer, ULONG cbBuffer, ULONG ulSubFunction);
82#endif /* CONFIG_WITH_OS2_LIBPATH */
83
84#ifdef KMK
85/** Checks if the @a_cch characters (bytes) in @a a_psz equals @a a_szConst. */
86# define STR_N_EQUALS(a_psz, a_cch, a_szConst) \
87 ( (a_cch) == sizeof (a_szConst) - 1 && !strncmp ((a_psz), (a_szConst), sizeof (a_szConst) - 1) )
88
89# ifdef _MSC_VER
90# include "kmkbuiltin/mscfakes.h"
91# endif
92#endif
93
94
95struct function_table_entry
96 {
97 union {
98 char *(*func_ptr) (char *output, char **argv, const char *fname);
99 gmk_func_ptr alloc_func_ptr;
100 } fptr;
101 const char *name;
102 unsigned char len;
103 unsigned char minimum_args;
104 unsigned char maximum_args;
105 unsigned char expand_args:1;
106 unsigned char alloc_fn:1;
107 };
108
109static unsigned long
110function_table_entry_hash_1 (const void *keyv)
111{
112 const struct function_table_entry *key = keyv;
113 return_STRING_N_HASH_1 (key->name, key->len);
114}
115
116static unsigned long
117function_table_entry_hash_2 (const void *keyv)
118{
119 const struct function_table_entry *key = keyv;
120 return_STRING_N_HASH_2 (key->name, key->len);
121}
122
123static int
124function_table_entry_hash_cmp (const void *xv, const void *yv)
125{
126 const struct function_table_entry *x = xv;
127 const struct function_table_entry *y = yv;
128 int result = x->len - y->len;
129 if (result)
130 return result;
131 return_STRING_N_COMPARE (x->name, y->name, x->len);
132}
133
134static struct hash_table function_table;
135
136#ifdef CONFIG_WITH_MAKE_STATS
137long make_stats_allocations = 0;
138long make_stats_reallocations = 0;
139unsigned long make_stats_allocated = 0;
140unsigned long make_stats_ht_lookups = 0;
141unsigned long make_stats_ht_collisions = 0;
142#endif
143
144
145
146/* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
147 each occurrence of SUBST with REPLACE. TEXT is null-terminated. SLEN is
148 the length of SUBST and RLEN is the length of REPLACE. If BY_WORD is
149 nonzero, substitutions are done only on matches which are complete
150 whitespace-delimited words. */
151
152char *
153subst_expand (char *o, const char *text, const char *subst, const char *replace,
154 unsigned int slen, unsigned int rlen, int by_word)
155{
156 const char *t = text;
157 const char *p;
158
159 if (slen == 0 && !by_word)
160 {
161 /* The first occurrence of "" in any string is its end. */
162 o = variable_buffer_output (o, t, strlen (t));
163 if (rlen > 0)
164 o = variable_buffer_output (o, replace, rlen);
165 return o;
166 }
167
168 do
169 {
170 if (by_word && slen == 0)
171 /* When matching by words, the empty string should match
172 the end of each word, rather than the end of the whole text. */
173 p = end_of_token (next_token (t));
174 else
175 {
176 p = strstr (t, subst);
177 if (p == 0)
178 {
179 /* No more matches. Output everything left on the end. */
180 o = variable_buffer_output (o, t, strlen (t));
181 return o;
182 }
183 }
184
185 /* Output everything before this occurrence of the string to replace. */
186 if (p > t)
187 o = variable_buffer_output (o, t, p - t);
188
189 /* If we're substituting only by fully matched words,
190 or only at the ends of words, check that this case qualifies. */
191 if (by_word
192 && ((p > text && !ISSPACE (p[-1]))
193 || ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
194 /* Struck out. Output the rest of the string that is
195 no longer to be replaced. */
196 o = variable_buffer_output (o, subst, slen);
197 else if (rlen > 0)
198 /* Output the replacement string. */
199 o = variable_buffer_output (o, replace, rlen);
200
201 /* Advance T past the string to be replaced. */
202 t = p + slen;
203 } while (*t != '\0');
204
205 return o;
206}
207
208
209
210/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
211 and replacing strings matching PATTERN with REPLACE.
212 If PATTERN_PERCENT is not nil, PATTERN has already been
213 run through find_percent, and PATTERN_PERCENT is the result.
214 If REPLACE_PERCENT is not nil, REPLACE has already been
215 run through find_percent, and REPLACE_PERCENT is the result.
216 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
217 character _AFTER_ the %, not to the % itself.
218*/
219
220char *
221patsubst_expand_pat (char *o, const char *text,
222 const char *pattern, const char *replace,
223 const char *pattern_percent, const char *replace_percent)
224{
225 unsigned int pattern_prepercent_len, pattern_postpercent_len;
226 unsigned int replace_prepercent_len, replace_postpercent_len;
227 const char *t;
228 unsigned int len;
229 int doneany = 0;
230
231 /* Record the length of REPLACE before and after the % so we don't have to
232 compute these lengths more than once. */
233 if (replace_percent)
234 {
235 replace_prepercent_len = replace_percent - replace - 1;
236 replace_postpercent_len = strlen (replace_percent);
237 }
238 else
239 {
240 replace_prepercent_len = strlen (replace);
241 replace_postpercent_len = 0;
242 }
243
244 if (!pattern_percent)
245 /* With no % in the pattern, this is just a simple substitution. */
246 return subst_expand (o, text, pattern, replace,
247 strlen (pattern), strlen (replace), 1);
248
249 /* Record the length of PATTERN before and after the %
250 so we don't have to compute it more than once. */
251 pattern_prepercent_len = pattern_percent - pattern - 1;
252 pattern_postpercent_len = strlen (pattern_percent);
253
254 while ((t = find_next_token (&text, &len)) != 0)
255 {
256 int fail = 0;
257
258 /* Is it big enough to match? */
259 if (len < pattern_prepercent_len + pattern_postpercent_len)
260 fail = 1;
261
262 /* Does the prefix match? */
263 if (!fail && pattern_prepercent_len > 0
264 && (*t != *pattern
265 || t[pattern_prepercent_len - 1] != pattern_percent[-2]
266 || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
267 fail = 1;
268
269 /* Does the suffix match? */
270 if (!fail && pattern_postpercent_len > 0
271 && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
272 || t[len - pattern_postpercent_len] != *pattern_percent
273 || !strneq (&t[len - pattern_postpercent_len],
274 pattern_percent, pattern_postpercent_len - 1)))
275 fail = 1;
276
277 if (fail)
278 /* It didn't match. Output the string. */
279 o = variable_buffer_output (o, t, len);
280 else
281 {
282 /* It matched. Output the replacement. */
283
284 /* Output the part of the replacement before the %. */
285 o = variable_buffer_output (o, replace, replace_prepercent_len);
286
287 if (replace_percent != 0)
288 {
289 /* Output the part of the matched string that
290 matched the % in the pattern. */
291 o = variable_buffer_output (o, t + pattern_prepercent_len,
292 len - (pattern_prepercent_len
293 + pattern_postpercent_len));
294 /* Output the part of the replacement after the %. */
295 o = variable_buffer_output (o, replace_percent,
296 replace_postpercent_len);
297 }
298 }
299
300 /* Output a space, but not if the replacement is "". */
301 if (fail || replace_prepercent_len > 0
302 || (replace_percent != 0 && len + replace_postpercent_len > 0))
303 {
304 o = variable_buffer_output (o, " ", 1);
305 doneany = 1;
306 }
307 }
308#ifndef CONFIG_WITH_VALUE_LENGTH
309 if (doneany)
310 /* Kill the last space. */
311 --o;
312#else
313 /* Kill the last space and make sure there is a terminator there
314 so that strcache_add_len doesn't have to do a lot of exacty work
315 when expand_deps sends the output its way. */
316 if (doneany)
317 *--o = '\0';
318 else
319 o = variable_buffer_output (o, "\0", 1) - 1;
320#endif
321
322 return o;
323}
324
325/* Store into VARIABLE_BUFFER at O the result of scanning TEXT
326 and replacing strings matching PATTERN with REPLACE.
327 If PATTERN_PERCENT is not nil, PATTERN has already been
328 run through find_percent, and PATTERN_PERCENT is the result.
329 If REPLACE_PERCENT is not nil, REPLACE has already been
330 run through find_percent, and REPLACE_PERCENT is the result.
331 Note that we expect PATTERN_PERCENT and REPLACE_PERCENT to point to the
332 character _AFTER_ the %, not to the % itself.
333*/
334
335char *
336patsubst_expand (char *o, const char *text, char *pattern, char *replace)
337{
338 const char *pattern_percent = find_percent (pattern);
339 const char *replace_percent = find_percent (replace);
340
341 /* If there's a percent in the pattern or replacement skip it. */
342 if (replace_percent)
343 ++replace_percent;
344 if (pattern_percent)
345 ++pattern_percent;
346
347 return patsubst_expand_pat (o, text, pattern, replace,
348 pattern_percent, replace_percent);
349}
350
351
352#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
353
354/* Char map containing the valid function name characters. */
355char func_char_map[256];
356
357/* Do the hash table lookup. */
358
359MY_INLINE const struct function_table_entry *
360lookup_function_in_hash_tab (const char *s, unsigned char len)
361{
362 struct function_table_entry function_table_entry_key;
363 function_table_entry_key.name = s;
364 function_table_entry_key.len = len;
365
366 return hash_find_item (&function_table, &function_table_entry_key);
367}
368
369/* Look up a function by name. */
370
371MY_INLINE const struct function_table_entry *
372lookup_function (const char *s, unsigned int len)
373{
374 unsigned char ch;
375# if 0 /* insane loop unroll */
376
377 if (len > MAX_FUNCTION_LENGTH)
378 len = MAX_FUNCTION_LENGTH + 1;
379
380# define X(idx) \
381 if (!func_char_map[ch = s[idx]]) \
382 { \
383 if (ISBLANK (ch)) \
384 return lookup_function_in_hash_tab (s, idx); \
385 return 0; \
386 }
387# define Z(idx) \
388 return lookup_function_in_hash_tab (s, idx);
389
390 switch (len)
391 {
392 default:
393 assert (0);
394 case 0: return 0;
395 case 1: return 0;
396 case 2: X(0); X(1); Z(2);
397 case 3: X(0); X(1); X(2); Z(3);
398 case 4: X(0); X(1); X(2); X(3); Z(4);
399 case 5: X(0); X(1); X(2); X(3); X(4); Z(5);
400 case 6: X(0); X(1); X(2); X(3); X(4); X(5); Z(6);
401 case 7: X(0); X(1); X(2); X(3); X(4); X(5); X(6); Z(7);
402 case 8: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); Z(8);
403 case 9: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); Z(9);
404 case 10: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); Z(10);
405 case 11: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); Z(11);
406 case 12: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); Z(12);
407 case 13: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); X(12);
408 if ((ch = s[12]) == '\0' || ISBLANK (ch))
409 return lookup_function_in_hash_tab (s, 12);
410 return 0;
411 }
412# undef Z
413# undef X
414
415# else /* normal loop */
416 const char *e = s;
417 if (len > MAX_FUNCTION_LENGTH)
418 len = MAX_FUNCTION_LENGTH;
419 while (func_char_map[ch = *e])
420 {
421 if (!len--)
422 return 0;
423 e++;
424 }
425 if (ch == '\0' || ISBLANK (ch))
426 return lookup_function_in_hash_tab (s, e - s);
427 return 0;
428# endif /* normal loop */
429}
430
431#else /* original code */
432/* Look up a function by name. */
433
434static const struct function_table_entry *
435lookup_function (const char *s)
436{
437 struct function_table_entry function_table_entry_key;
438 const char *e = s;
439 while (STOP_SET (*e, MAP_USERFUNC))
440 e++;
441
442 if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
443 return NULL;
444
445 function_table_entry_key.name = s;
446 function_table_entry_key.len = e - s;
447
448 return hash_find_item (&function_table, &function_table_entry_key);
449}
450#endif /* original code */
451
452
453
454/* Return 1 if PATTERN matches STR, 0 if not. */
455
456int
457pattern_matches (const char *pattern, const char *percent, const char *str)
458{
459 unsigned int sfxlen, strlength;
460
461 if (percent == 0)
462 {
463 unsigned int len = strlen (pattern) + 1;
464 char *new_chars = alloca (len);
465 memcpy (new_chars, pattern, len);
466 percent = find_percent (new_chars);
467 if (percent == 0)
468 return streq (new_chars, str);
469 pattern = new_chars;
470 }
471
472 sfxlen = strlen (percent + 1);
473 strlength = strlen (str);
474
475 if (strlength < (percent - pattern) + sfxlen
476 || !strneq (pattern, str, percent - pattern))
477 return 0;
478
479 return !strcmp (percent + 1, str + (strlength - sfxlen));
480}
481
482
483
484/* Find the next comma or ENDPAREN (counting nested STARTPAREN and
485 ENDPARENtheses), starting at PTR before END. Return a pointer to
486 next character.
487
488 If no next argument is found, return NULL.
489*/
490
491static char *
492find_next_argument (char startparen, char endparen,
493 const char *ptr, const char *end)
494{
495 int count = 0;
496
497 for (; ptr < end; ++ptr)
498 if (*ptr == startparen)
499 ++count;
500
501 else if (*ptr == endparen)
502 {
503 --count;
504 if (count < 0)
505 return NULL;
506 }
507
508 else if (*ptr == ',' && !count)
509 return (char *)ptr;
510
511 /* We didn't find anything. */
512 return NULL;
513}
514
515
516
517/* Glob-expand LINE. The returned pointer is
518 only good until the next call to string_glob. */
519
520static char *
521string_glob (char *line)
522{
523 static char *result = 0;
524 static unsigned int length;
525 struct nameseq *chain;
526 unsigned int idx;
527
528 chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
529 /* We do not want parse_file_seq to strip './'s.
530 That would break examples like:
531 $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)). */
532 PARSEFS_NOSTRIP|PARSEFS_NOCACHE|PARSEFS_EXISTS);
533
534 if (result == 0)
535 {
536 length = 100;
537 result = xmalloc (100);
538 }
539
540 idx = 0;
541 while (chain != 0)
542 {
543 struct nameseq *next = chain->next;
544 unsigned int len = strlen (chain->name);
545
546 if (idx + len + 1 > length)
547 {
548 length += (len + 1) * 2;
549 result = xrealloc (result, length);
550 }
551 memcpy (&result[idx], chain->name, len);
552 idx += len;
553 result[idx++] = ' ';
554
555 /* Because we used PARSEFS_NOCACHE above, we have to free() NAME. */
556 free ((char *)chain->name);
557#ifndef CONFIG_WITH_ALLOC_CACHES
558 free (chain);
559#else
560 alloccache_free (&nameseq_cache, chain);
561#endif
562 chain = next;
563 }
564
565 /* Kill the last space and terminate the string. */
566 if (idx == 0)
567 result[0] = '\0';
568 else
569 result[idx - 1] = '\0';
570
571 return result;
572}
573
574
575/*
576 Builtin functions
577 */
578
579static char *
580func_patsubst (char *o, char **argv, const char *funcname UNUSED)
581{
582 o = patsubst_expand (o, argv[2], argv[0], argv[1]);
583 return o;
584}
585
586
587static char *
588func_join (char *o, char **argv, const char *funcname UNUSED)
589{
590 int doneany = 0;
591
592 /* Write each word of the first argument directly followed
593 by the corresponding word of the second argument.
594 If the two arguments have a different number of words,
595 the excess words are just output separated by blanks. */
596 const char *tp;
597 const char *pp;
598 const char *list1_iterator = argv[0];
599 const char *list2_iterator = argv[1];
600 do
601 {
602 unsigned int len1, len2;
603
604 tp = find_next_token (&list1_iterator, &len1);
605 if (tp != 0)
606 o = variable_buffer_output (o, tp, len1);
607
608 pp = find_next_token (&list2_iterator, &len2);
609 if (pp != 0)
610 o = variable_buffer_output (o, pp, len2);
611
612 if (tp != 0 || pp != 0)
613 {
614 o = variable_buffer_output (o, " ", 1);
615 doneany = 1;
616 }
617 }
618 while (tp != 0 || pp != 0);
619 if (doneany)
620 /* Kill the last blank. */
621 --o;
622
623 return o;
624}
625
626
627static char *
628func_origin (char *o, char **argv, const char *funcname UNUSED)
629{
630 /* Expand the argument. */
631 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
632 if (v == 0)
633 o = variable_buffer_output (o, "undefined", 9);
634 else
635 switch (v->origin)
636 {
637 default:
638 case o_invalid:
639 abort ();
640 break;
641 case o_default:
642 o = variable_buffer_output (o, "default", 7);
643 break;
644 case o_env:
645 o = variable_buffer_output (o, "environment", 11);
646 break;
647 case o_file:
648 o = variable_buffer_output (o, "file", 4);
649 break;
650 case o_env_override:
651 o = variable_buffer_output (o, "environment override", 20);
652 break;
653 case o_command:
654 o = variable_buffer_output (o, "command line", 12);
655 break;
656 case o_override:
657 o = variable_buffer_output (o, "override", 8);
658 break;
659 case o_automatic:
660 o = variable_buffer_output (o, "automatic", 9);
661 break;
662#ifdef CONFIG_WITH_LOCAL_VARIABLES
663 case o_local:
664 o = variable_buffer_output (o, "local", 5);
665 break;
666#endif
667 }
668
669 return o;
670}
671
672static char *
673func_flavor (char *o, char **argv, const char *funcname UNUSED)
674{
675 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
676
677 if (v == 0)
678 o = variable_buffer_output (o, "undefined", 9);
679 else
680 if (v->recursive)
681 o = variable_buffer_output (o, "recursive", 9);
682 else
683 o = variable_buffer_output (o, "simple", 6);
684
685 return o;
686}
687
688#ifdef CONFIG_WITH_WHERE_FUNCTION
689static char *
690func_where (char *o, char **argv, const char *funcname UNUSED)
691{
692 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
693 char buf[64];
694
695 if (v == 0)
696 o = variable_buffer_output (o, "undefined", 9);
697 else
698 if (v->fileinfo.filenm)
699 {
700 o = variable_buffer_output (o, v->fileinfo.filenm, strlen(v->fileinfo.filenm));
701 sprintf (buf, ":%lu", v->fileinfo.lineno);
702 o = variable_buffer_output (o, buf, strlen(buf));
703 }
704 else
705 o = variable_buffer_output (o, "no-location", 11);
706
707 return o;
708}
709#endif /* CONFIG_WITH_WHERE_FUNCTION */
710
711static char *
712func_notdir_suffix (char *o, char **argv, const char *funcname)
713{
714 /* Expand the argument. */
715 const char *list_iterator = argv[0];
716 const char *p2;
717 int doneany =0;
718 unsigned int len=0;
719
720 int is_suffix = funcname[0] == 's';
721 int is_notdir = !is_suffix;
722 int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
723#ifdef VMS
724 /* For VMS list_iterator points to a comma separated list. To use the common
725 [find_]next_token, create a local copy and replace the commas with
726 spaces. Obviously, there is a problem if there is a ',' in the VMS filename
727 (can only happen on ODS5), the same problem as with spaces in filenames,
728 which seems to be present in make on all platforms. */
729 char *vms_list_iterator = alloca(strlen(list_iterator) + 1);
730 int i;
731 for (i = 0; list_iterator[i]; i++)
732 if (list_iterator[i] == ',')
733 vms_list_iterator[i] = ' ';
734 else
735 vms_list_iterator[i] = list_iterator[i];
736 vms_list_iterator[i] = list_iterator[i];
737 while ((p2 = find_next_token((const char**) &vms_list_iterator, &len)) != 0)
738#else
739 while ((p2 = find_next_token (&list_iterator, &len)) != 0)
740#endif
741 {
742 const char *p = p2 + len - 1;
743
744 while (p >= p2 && ! STOP_SET (*p, stop))
745 --p;
746
747 if (p >= p2)
748 {
749 if (is_notdir)
750 ++p;
751 else if (*p != '.')
752 continue;
753 o = variable_buffer_output (o, p, len - (p - p2));
754 }
755#ifdef HAVE_DOS_PATHS
756 /* Handle the case of "d:foo/bar". */
757 else if (is_notdir && p2[0] && p2[1] == ':')
758 {
759 p = p2 + 2;
760 o = variable_buffer_output (o, p, len - (p - p2));
761 }
762#endif
763 else if (is_notdir)
764 o = variable_buffer_output (o, p2, len);
765
766 if (is_notdir || p >= p2)
767 {
768#ifdef VMS
769 if (vms_comma_separator)
770 o = variable_buffer_output (o, ",", 1);
771 else
772#endif
773 o = variable_buffer_output (o, " ", 1);
774
775 doneany = 1;
776 }
777 }
778
779 if (doneany)
780 /* Kill last space. */
781 --o;
782
783 return o;
784}
785
786
787static char *
788func_basename_dir (char *o, char **argv, const char *funcname)
789{
790 /* Expand the argument. */
791 const char *p3 = argv[0];
792 const char *p2;
793 int doneany = 0;
794 unsigned int len = 0;
795
796 int is_basename = funcname[0] == 'b';
797 int is_dir = !is_basename;
798 int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
799#ifdef VMS
800 /* As in func_notdir_suffix ... */
801 char *vms_p3 = alloca (strlen(p3) + 1);
802 int i;
803 for (i = 0; p3[i]; i++)
804 if (p3[i] == ',')
805 vms_p3[i] = ' ';
806 else
807 vms_p3[i] = p3[i];
808 vms_p3[i] = p3[i];
809 while ((p2 = find_next_token((const char**) &vms_p3, &len)) != 0)
810#else
811 while ((p2 = find_next_token (&p3, &len)) != 0)
812#endif
813 {
814 const char *p = p2 + len - 1;
815 while (p >= p2 && ! STOP_SET (*p, stop))
816 --p;
817
818 if (p >= p2 && (is_dir))
819 o = variable_buffer_output (o, p2, ++p - p2);
820 else if (p >= p2 && (*p == '.'))
821 o = variable_buffer_output (o, p2, p - p2);
822#ifdef HAVE_DOS_PATHS
823 /* Handle the "d:foobar" case */
824 else if (p2[0] && p2[1] == ':' && is_dir)
825 o = variable_buffer_output (o, p2, 2);
826#endif
827 else if (is_dir)
828#ifdef VMS
829 {
830 extern int vms_report_unix_paths;
831 if (vms_report_unix_paths)
832 o = variable_buffer_output (o, "./", 2);
833 else
834 o = variable_buffer_output (o, "[]", 2);
835 }
836#else
837#ifndef _AMIGA
838 o = variable_buffer_output (o, "./", 2);
839#else
840 ; /* Just a nop... */
841#endif /* AMIGA */
842#endif /* !VMS */
843 else
844 /* The entire name is the basename. */
845 o = variable_buffer_output (o, p2, len);
846
847#ifdef VMS
848 if (vms_comma_separator)
849 o = variable_buffer_output (o, ",", 1);
850 else
851#endif
852 o = variable_buffer_output (o, " ", 1);
853 doneany = 1;
854 }
855
856 if (doneany)
857 /* Kill last space. */
858 --o;
859
860 return o;
861}
862
863#if 1 /* rewrite to new MAP stuff? */
864# ifdef VMS
865# define IS_PATHSEP(c) ((c) == ']')
866# else
867# ifdef HAVE_DOS_PATHS
868# define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
869# else
870# define IS_PATHSEP(c) ((c) == '/')
871# endif
872# endif
873#endif
874
875#ifdef CONFIG_WITH_ROOT_FUNC
876
877/*
878 $(root path)
879
880 This is mainly for dealing with drive letters and UNC paths on Windows
881 and OS/2.
882 */
883static char *
884func_root (char *o, char **argv, const char *funcname UNUSED)
885{
886 const char *paths = argv[0] ? argv[0] : "";
887 int doneany = 0;
888 const char *p;
889 unsigned int len;
890
891 while ((p = find_next_token (&paths, &len)) != 0)
892 {
893 const char *p2 = p;
894
895# ifdef HAVE_DOS_PATHS
896 if ( len >= 2
897 && p2[1] == ':'
898 && ( (p2[0] >= 'A' && p2[0] <= 'Z')
899 || (p2[0] >= 'a' && p2[0] <= 'z')))
900 {
901 p2 += 2;
902 len -= 2;
903 }
904 else if (len >= 4 && IS_PATHSEP(p2[0]) && IS_PATHSEP(p2[1])
905 && !IS_PATHSEP(p2[2]))
906 {
907 /* Min recognized UNC: "//./" - find the next slash
908 Typical root: "//srv/shr/" */
909 /* XXX: Check if //./ needs special handling. */
910
911 p2 += 3;
912 len -= 3;
913 while (len > 0 && !IS_PATHSEP(*p2))
914 p2++, len--;
915
916 if (len && IS_PATHSEP(p2[0]) && (len == 1 || !IS_PATHSEP(p2[1])))
917 {
918 p2++;
919 len--;
920
921 if (len) /* optional share */
922 while (len > 0 && !IS_PATHSEP(*p2))
923 p2++, len--;
924 }
925 else
926 p2 = NULL;
927 }
928 else if (IS_PATHSEP(*p2))
929 {
930 p2++;
931 len--;
932 }
933 else
934 p2 = NULL;
935
936# elif defined (VMS) || defined (AMGIA)
937 /* XXX: VMS and AMGIA */
938 O (fatal, NILF, _("$(root ) is not implemented on this platform"));
939# else
940 if (IS_PATHSEP(*p2))
941 {
942 p2++;
943 len--;
944 }
945 else
946 p2 = NULL;
947# endif
948 if (p2 != NULL)
949 {
950 /* Include all subsequent path separators. */
951
952 while (len > 0 && IS_PATHSEP(*p2))
953 p2++, len--;
954 o = variable_buffer_output (o, p, p2 - p);
955 o = variable_buffer_output (o, " ", 1);
956 doneany = 1;
957 }
958 }
959
960 if (doneany)
961 /* Kill last space. */
962 --o;
963
964 return o;
965}
966
967/*
968 $(notroot path)
969
970 This is mainly for dealing with drive letters and UNC paths on Windows
971 and OS/2.
972 */
973static char *
974func_notroot (char *o, char **argv, const char *funcname UNUSED)
975{
976 const char *paths = argv[0] ? argv[0] : "";
977 int doneany = 0;
978 const char *p;
979 unsigned int len;
980
981 while ((p = find_next_token (&paths, &len)) != 0)
982 {
983 const char *p2 = p;
984
985# ifdef HAVE_DOS_PATHS
986 if ( len >= 2
987 && p2[1] == ':'
988 && ( (p2[0] >= 'A' && p2[0] <= 'Z')
989 || (p2[0] >= 'a' && p2[0] <= 'z')))
990 {
991 p2 += 2;
992 len -= 2;
993 }
994 else if (len >= 4 && IS_PATHSEP(p2[0]) && IS_PATHSEP(p2[1])
995 && !IS_PATHSEP(p2[2]))
996 {
997 /* Min recognized UNC: "//./" - find the next slash
998 Typical root: "//srv/shr/" */
999 /* XXX: Check if //./ needs special handling. */
1000 unsigned int saved_len = len;
1001
1002 p2 += 3;
1003 len -= 3;
1004 while (len > 0 && !IS_PATHSEP(*p2))
1005 p2++, len--;
1006
1007 if (len && IS_PATHSEP(p2[0]) && (len == 1 || !IS_PATHSEP(p2[1])))
1008 {
1009 p2++;
1010 len--;
1011
1012 if (len) /* optional share */
1013 while (len > 0 && !IS_PATHSEP(*p2))
1014 p2++, len--;
1015 }
1016 else
1017 {
1018 p2 = p;
1019 len = saved_len;
1020 }
1021 }
1022
1023# elif defined (VMS) || defined (AMGIA)
1024 /* XXX: VMS and AMGIA */
1025 O (fatal, NILF, _("$(root ) is not implemented on this platform"));
1026# endif
1027
1028 /* Exclude all subsequent / leading path separators. */
1029
1030 while (len > 0 && IS_PATHSEP(*p2))
1031 p2++, len--;
1032 if (len > 0)
1033 o = variable_buffer_output (o, p2, len);
1034 else
1035 o = variable_buffer_output (o, ".", 1);
1036 o = variable_buffer_output (o, " ", 1);
1037 doneany = 1;
1038 }
1039
1040 if (doneany)
1041 /* Kill last space. */
1042 --o;
1043
1044 return o;
1045}
1046
1047#endif /* CONFIG_WITH_ROOT_FUNC */
1048
1049static char *
1050func_addsuffix_addprefix (char *o, char **argv, const char *funcname)
1051{
1052 int fixlen = strlen (argv[0]);
1053 const char *list_iterator = argv[1];
1054 int is_addprefix = funcname[3] == 'p';
1055 int is_addsuffix = !is_addprefix;
1056
1057 int doneany = 0;
1058 const char *p;
1059 unsigned int len;
1060
1061 while ((p = find_next_token (&list_iterator, &len)) != 0)
1062 {
1063 if (is_addprefix)
1064 o = variable_buffer_output (o, argv[0], fixlen);
1065 o = variable_buffer_output (o, p, len);
1066 if (is_addsuffix)
1067 o = variable_buffer_output (o, argv[0], fixlen);
1068 o = variable_buffer_output (o, " ", 1);
1069 doneany = 1;
1070 }
1071
1072 if (doneany)
1073 /* Kill last space. */
1074 --o;
1075
1076 return o;
1077}
1078
1079static char *
1080func_subst (char *o, char **argv, const char *funcname UNUSED)
1081{
1082 o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
1083 strlen (argv[1]), 0);
1084
1085 return o;
1086}
1087
1088#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
1089
1090/* Used by func_firstdefined and func_lastdefined to parse the optional last
1091 argument. Returns 0 if the variable name is to be returned and 1 if it's
1092 the variable value value. */
1093static int
1094parse_value_name_argument (const char *arg1, const char *funcname)
1095{
1096 const char *end;
1097 int rc;
1098
1099 if (arg1 == NULL)
1100 return 0;
1101
1102 end = strchr (arg1, '\0');
1103 strip_whitespace (&arg1, &end);
1104
1105 if (!strncmp (arg1, "name", end - arg1))
1106 rc = 0;
1107 else if (!strncmp (arg1, "value", end - arg1))
1108 rc = 1;
1109 else
1110# if 1 /* FIXME: later */
1111 OSS (fatal, *expanding_var,
1112 _("second argument to `%s' function must be `name' or `value', not `%s'"),
1113 funcname, arg1);
1114# else
1115 {
1116 /* check the expanded form */
1117 char *exp = expand_argument (arg1, strchr (arg1, '\0'));
1118 arg1 = exp;
1119 end = strchr (arg1, '\0');
1120 strip_whitespace (&arg1, &end);
1121
1122 if (!strncmp (arg1, "name", end - arg1))
1123 rc = 0;
1124 else if (!strncmp (arg1, "value", end - arg1))
1125 rc = 1;
1126 else
1127 OSS (fatal, *expanding_var,
1128 _("second argument to `%s' function must be `name' or `value', not `%s'"),
1129 funcname, exp);
1130 free (exp);
1131 }
1132# endif
1133
1134 return rc;
1135}
1136
1137/* Given a list of variable names (ARGV[0]), returned the first variable which
1138 is defined (i.e. value is not empty). ARGV[1] indicates whether to return
1139 the variable name or its value. */
1140static char *
1141func_firstdefined (char *o, char **argv, const char *funcname)
1142{
1143 unsigned int i;
1144 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1145 const char *p;
1146 int ret_value = parse_value_name_argument (argv[1], funcname);
1147
1148 /* FIXME: Optimize by not expanding the arguments, but instead expand them
1149 one by one here. This will require a find_next_token variant which
1150 takes `$(' and `)' into account. */
1151 while ((p = find_next_token (&words, &i)) != NULL)
1152 {
1153 struct variable *v = lookup_variable (p, i);
1154 if (v && v->value_length)
1155 {
1156 if (ret_value)
1157 variable_expand_string_2 (o, v->value, v->value_length, &o);
1158 else
1159 o = variable_buffer_output (o, p, i);
1160 break;
1161 }
1162 }
1163
1164 return o;
1165}
1166
1167/* Given a list of variable names (ARGV[0]), returned the last variable which
1168 is defined (i.e. value is not empty). ARGV[1] indicates whether to return
1169 the variable name or its value. */
1170static char *
1171func_lastdefined (char *o, char **argv, const char *funcname)
1172{
1173 struct variable *last_v = NULL;
1174 unsigned int i;
1175 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1176 const char *p;
1177 int ret_value = parse_value_name_argument (argv[1], funcname);
1178
1179 /* FIXME: Optimize this. Walk from the end on unexpanded arguments. */
1180 while ((p = find_next_token (&words, &i)) != NULL)
1181 {
1182 struct variable *v = lookup_variable (p, i);
1183 if (v && v->value_length)
1184 {
1185 last_v = v;
1186 break;
1187 }
1188 }
1189
1190 if (last_v != NULL)
1191 {
1192 if (ret_value)
1193 variable_expand_string_2 (o, last_v->value, last_v->value_length, &o);
1194 else
1195 o = variable_buffer_output (o, last_v->name, last_v->length);
1196 }
1197 return o;
1198}
1199
1200#endif /* CONFIG_WITH_DEFINED_FUNCTIONS */
1201
1202static char *
1203func_firstword (char *o, char **argv, const char *funcname UNUSED)
1204{
1205 unsigned int i;
1206 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1207 const char *p = find_next_token (&words, &i);
1208
1209 if (p != 0)
1210 o = variable_buffer_output (o, p, i);
1211
1212 return o;
1213}
1214
1215static char *
1216func_lastword (char *o, char **argv, const char *funcname UNUSED)
1217{
1218 unsigned int i;
1219 const char *words = argv[0]; /* Use a temp variable for find_next_token */
1220 const char *p = NULL;
1221 const char *t;
1222
1223 while ((t = find_next_token (&words, &i)))
1224 p = t;
1225
1226 if (p != 0)
1227 o = variable_buffer_output (o, p, i);
1228
1229 return o;
1230}
1231
1232static char *
1233func_words (char *o, char **argv, const char *funcname UNUSED)
1234{
1235 int i = 0;
1236 const char *word_iterator = argv[0];
1237 char buf[20];
1238
1239 while (find_next_token (&word_iterator, NULL) != 0)
1240 ++i;
1241
1242 sprintf (buf, "%d", i);
1243 o = variable_buffer_output (o, buf, strlen (buf));
1244
1245 return o;
1246}
1247
1248/* Set begpp to point to the first non-whitespace character of the string,
1249 * and endpp to point to the last non-whitespace character of the string.
1250 * If the string is empty or contains nothing but whitespace, endpp will be
1251 * begpp-1.
1252 */
1253char *
1254strip_whitespace (const char **begpp, const char **endpp)
1255{
1256 while (*begpp <= *endpp && ISSPACE (**begpp))
1257 (*begpp) ++;
1258 while (*endpp >= *begpp && ISSPACE (**endpp))
1259 (*endpp) --;
1260 return (char *)*begpp;
1261}
1262
1263static void
1264check_numeric (const char *s, const char *msg)
1265{
1266 const char *end = s + strlen (s) - 1;
1267 const char *beg = s;
1268 strip_whitespace (&s, &end);
1269
1270 for (; s <= end; ++s)
1271 if (!ISDIGIT (*s)) /* ISDIGIT only evals its arg once: see makeint.h. */
1272 break;
1273
1274 if (s <= end || end - beg < 0)
1275 OSS (fatal, *expanding_var, "%s: '%s'", msg, beg);
1276}
1277
1278
1279
1280static char *
1281func_word (char *o, char **argv, const char *funcname UNUSED)
1282{
1283 const char *end_p;
1284 const char *p;
1285 int i;
1286
1287 /* Check the first argument. */
1288 check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
1289 i = atoi (argv[0]);
1290
1291 if (i == 0)
1292 O (fatal, *expanding_var,
1293 _("first argument to 'word' function must be greater than 0"));
1294
1295 end_p = argv[1];
1296 while ((p = find_next_token (&end_p, 0)) != 0)
1297 if (--i == 0)
1298 break;
1299
1300 if (i == 0)
1301 o = variable_buffer_output (o, p, end_p - p);
1302
1303 return o;
1304}
1305
1306static char *
1307func_wordlist (char *o, char **argv, const char *funcname UNUSED)
1308{
1309 int start, count;
1310
1311 /* Check the arguments. */
1312 check_numeric (argv[0],
1313 _("non-numeric first argument to 'wordlist' function"));
1314 check_numeric (argv[1],
1315 _("non-numeric second argument to 'wordlist' function"));
1316
1317 start = atoi (argv[0]);
1318 if (start < 1)
1319 ON (fatal, *expanding_var,
1320 "invalid first argument to 'wordlist' function: '%d'", start);
1321
1322 count = atoi (argv[1]) - start + 1;
1323
1324 if (count > 0)
1325 {
1326 const char *p;
1327 const char *end_p = argv[2];
1328
1329 /* Find the beginning of the "start"th word. */
1330 while (((p = find_next_token (&end_p, 0)) != 0) && --start)
1331 ;
1332
1333 if (p)
1334 {
1335 /* Find the end of the "count"th word from start. */
1336 while (--count && (find_next_token (&end_p, 0) != 0))
1337 ;
1338
1339 /* Return the stuff in the middle. */
1340 o = variable_buffer_output (o, p, end_p - p);
1341 }
1342 }
1343
1344 return o;
1345}
1346
1347static char *
1348func_findstring (char *o, char **argv, const char *funcname UNUSED)
1349{
1350 /* Find the first occurrence of the first string in the second. */
1351 if (strstr (argv[1], argv[0]) != 0)
1352 o = variable_buffer_output (o, argv[0], strlen (argv[0]));
1353
1354 return o;
1355}
1356
1357static char *
1358func_foreach (char *o, char **argv, const char *funcname UNUSED)
1359{
1360 /* expand only the first two. */
1361 char *varname = expand_argument (argv[0], NULL);
1362 char *list = expand_argument (argv[1], NULL);
1363 const char *body = argv[2];
1364#ifdef CONFIG_WITH_VALUE_LENGTH
1365 long body_len = strlen (body);
1366#endif
1367
1368 int doneany = 0;
1369 const char *list_iterator = list;
1370 const char *p;
1371 unsigned int len;
1372 struct variable *var;
1373
1374 /* Clean up the variable name by removing whitespace. */
1375 char *vp = next_token (varname);
1376 end_of_token (vp)[0] = '\0';
1377
1378 push_new_variable_scope ();
1379 var = define_variable (vp, strlen (vp), "", o_automatic, 0);
1380
1381 /* loop through LIST, put the value in VAR and expand BODY */
1382 while ((p = find_next_token (&list_iterator, &len)) != 0)
1383 {
1384#ifndef CONFIG_WITH_VALUE_LENGTH
1385 char *result = 0;
1386
1387 free (var->value);
1388 var->value = xstrndup (p, len);
1389
1390 result = allocated_variable_expand (body);
1391
1392 o = variable_buffer_output (o, result, strlen (result));
1393 o = variable_buffer_output (o, " ", 1);
1394 doneany = 1;
1395 free (result);
1396#else /* CONFIG_WITH_VALUE_LENGTH */
1397 if (len >= var->value_alloc_len)
1398 {
1399# ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
1400 if (var->rdonly_val)
1401 var->rdonly_val = 0;
1402 else
1403# endif
1404 free (var->value);
1405 var->value_alloc_len = VAR_ALIGN_VALUE_ALLOC (len + 1);
1406 var->value = xmalloc (var->value_alloc_len);
1407 }
1408 memcpy (var->value, p, len);
1409 var->value[len] = '\0';
1410 var->value_length = len;
1411 VARIABLE_CHANGED (var);
1412
1413 variable_expand_string_2 (o, body, body_len, &o);
1414 o = variable_buffer_output (o, " ", 1);
1415 doneany = 1;
1416#endif /* CONFIG_WITH_VALUE_LENGTH */
1417 }
1418
1419 if (doneany)
1420 /* Kill the last space. */
1421 --o;
1422
1423 pop_variable_scope ();
1424 free (varname);
1425 free (list);
1426
1427 return o;
1428}
1429
1430#ifdef CONFIG_WITH_LOOP_FUNCTIONS
1431
1432
1433/* Helper for func_for that evaluates the INIT and NEXT parts. */
1434static void
1435helper_eval (char *text, size_t text_len)
1436{
1437 unsigned int buf_len;
1438 char *buf;
1439
1440 install_variable_buffer (&buf, &buf_len);
1441 eval_buffer (text, NULL, text + text_len);
1442 restore_variable_buffer (buf, buf_len);
1443}
1444
1445/*
1446 $(for init,condition,next,body)
1447 */
1448static char *
1449func_for (char *o, char **argv, const char *funcname UNUSED)
1450{
1451 char *init = argv[0];
1452 const char *cond = argv[1];
1453 const char *next = argv[2];
1454 size_t next_len = strlen (next);
1455 char *next_buf = xmalloc (next_len + 1);
1456 const char *body = argv[3];
1457 size_t body_len = strlen (body);
1458 unsigned int doneany = 0;
1459
1460 push_new_variable_scope ();
1461
1462 /* Evaluate INIT. */
1463
1464 helper_eval (init, strlen (init));
1465
1466 /* Loop till COND is false. */
1467
1468 while (expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
1469 {
1470 /* Expand BODY. */
1471
1472 if (!doneany)
1473 doneany = 1;
1474 else
1475 o = variable_buffer_output (o, " ", 1);
1476 variable_expand_string_2 (o, body, body_len, &o);
1477
1478 /* Evaluate NEXT. */
1479
1480 memcpy (next_buf, next, next_len + 1);
1481 helper_eval (next_buf, next_len);
1482 }
1483
1484 pop_variable_scope ();
1485 free (next_buf);
1486
1487 return o;
1488}
1489
1490/*
1491 $(while condition,body)
1492 */
1493static char *
1494func_while (char *o, char **argv, const char *funcname UNUSED)
1495{
1496 const char *cond = argv[0];
1497 const char *body = argv[1];
1498 size_t body_len = strlen (body);
1499 unsigned int doneany = 0;
1500
1501 push_new_variable_scope ();
1502
1503 while (expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
1504 {
1505 if (!doneany)
1506 doneany = 1;
1507 else
1508 o = variable_buffer_output (o, " ", 1);
1509 variable_expand_string_2 (o, body, body_len, &o);
1510 }
1511
1512 pop_variable_scope ();
1513
1514 return o;
1515}
1516
1517
1518#endif /* CONFIG_WITH_LOOP_FUNCTIONS */
1519
1520struct a_word
1521{
1522 struct a_word *next;
1523 struct a_word *chain;
1524 char *str;
1525 int length;
1526 int matched;
1527};
1528
1529static unsigned long
1530a_word_hash_1 (const void *key)
1531{
1532 return_STRING_HASH_1 (((struct a_word const *) key)->str);
1533}
1534
1535static unsigned long
1536a_word_hash_2 (const void *key)
1537{
1538 return_STRING_HASH_2 (((struct a_word const *) key)->str);
1539}
1540
1541static int
1542a_word_hash_cmp (const void *x, const void *y)
1543{
1544 int result = ((struct a_word const *) x)->length - ((struct a_word const *) y)->length;
1545 if (result)
1546 return result;
1547 return_STRING_COMPARE (((struct a_word const *) x)->str,
1548 ((struct a_word const *) y)->str);
1549}
1550
1551struct a_pattern
1552{
1553 struct a_pattern *next;
1554 char *str;
1555 char *percent;
1556 int length;
1557};
1558
1559static char *
1560func_filter_filterout (char *o, char **argv, const char *funcname)
1561{
1562 struct a_word *wordhead;
1563 struct a_word **wordtail;
1564 struct a_word *wp;
1565 struct a_pattern *pathead;
1566 struct a_pattern **pattail;
1567 struct a_pattern *pp;
1568
1569 struct hash_table a_word_table;
1570 int is_filter = funcname[CSTRLEN ("filter")] == '\0';
1571 const char *pat_iterator = argv[0];
1572 const char *word_iterator = argv[1];
1573 int literals = 0;
1574 int words = 0;
1575 int hashing = 0;
1576 char *p;
1577 unsigned int len;
1578
1579 /* Chop ARGV[0] up into patterns to match against the words.
1580 We don't need to preserve it because our caller frees all the
1581 argument memory anyway. */
1582
1583 pattail = &pathead;
1584 while ((p = find_next_token (&pat_iterator, &len)) != 0)
1585 {
1586 struct a_pattern *pat = alloca (sizeof (struct a_pattern));
1587
1588 *pattail = pat;
1589 pattail = &pat->next;
1590
1591 if (*pat_iterator != '\0')
1592 ++pat_iterator;
1593
1594 pat->str = p;
1595 p[len] = '\0';
1596 pat->percent = find_percent (p);
1597 if (pat->percent == 0)
1598 literals++;
1599
1600 /* find_percent() might shorten the string so LEN is wrong. */
1601 pat->length = strlen (pat->str);
1602 }
1603 *pattail = 0;
1604
1605 /* Chop ARGV[1] up into words to match against the patterns. */
1606
1607 wordtail = &wordhead;
1608 while ((p = find_next_token (&word_iterator, &len)) != 0)
1609 {
1610 struct a_word *word = alloca (sizeof (struct a_word));
1611
1612 *wordtail = word;
1613 wordtail = &word->next;
1614
1615 if (*word_iterator != '\0')
1616 ++word_iterator;
1617
1618 p[len] = '\0';
1619 word->str = p;
1620 word->length = len;
1621 word->matched = 0;
1622 word->chain = 0;
1623 words++;
1624 }
1625 *wordtail = 0;
1626
1627 /* Only use a hash table if arg list lengths justifies the cost. */
1628 hashing = (literals >= 2 && (literals * words) >= 10);
1629 if (hashing)
1630 {
1631 hash_init (&a_word_table, words, a_word_hash_1, a_word_hash_2,
1632 a_word_hash_cmp);
1633 for (wp = wordhead; wp != 0; wp = wp->next)
1634 {
1635 struct a_word *owp = hash_insert (&a_word_table, wp);
1636 if (owp)
1637 wp->chain = owp;
1638 }
1639 }
1640
1641 if (words)
1642 {
1643 int doneany = 0;
1644
1645 /* Run each pattern through the words, killing words. */
1646 for (pp = pathead; pp != 0; pp = pp->next)
1647 {
1648 if (pp->percent)
1649 for (wp = wordhead; wp != 0; wp = wp->next)
1650 wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
1651 else if (hashing)
1652 {
1653 struct a_word a_word_key;
1654 a_word_key.str = pp->str;
1655 a_word_key.length = pp->length;
1656 wp = hash_find_item (&a_word_table, &a_word_key);
1657 while (wp)
1658 {
1659 wp->matched |= 1;
1660 wp = wp->chain;
1661 }
1662 }
1663 else
1664 for (wp = wordhead; wp != 0; wp = wp->next)
1665 wp->matched |= (wp->length == pp->length
1666 && strneq (pp->str, wp->str, wp->length));
1667 }
1668
1669 /* Output the words that matched (or didn't, for filter-out). */
1670 for (wp = wordhead; wp != 0; wp = wp->next)
1671 if (is_filter ? wp->matched : !wp->matched)
1672 {
1673 o = variable_buffer_output (o, wp->str, strlen (wp->str));
1674 o = variable_buffer_output (o, " ", 1);
1675 doneany = 1;
1676 }
1677
1678 if (doneany)
1679 /* Kill the last space. */
1680 --o;
1681 }
1682
1683 if (hashing)
1684 hash_free (&a_word_table, 0);
1685
1686 return o;
1687}
1688
1689
1690static char *
1691func_strip (char *o, char **argv, const char *funcname UNUSED)
1692{
1693 const char *p = argv[0];
1694 int doneany = 0;
1695
1696 while (*p != '\0')
1697 {
1698 int i=0;
1699 const char *word_start;
1700
1701 NEXT_TOKEN (p);
1702 word_start = p;
1703 for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
1704 {}
1705 if (!i)
1706 break;
1707 o = variable_buffer_output (o, word_start, i);
1708 o = variable_buffer_output (o, " ", 1);
1709 doneany = 1;
1710 }
1711
1712 if (doneany)
1713 /* Kill the last space. */
1714 --o;
1715
1716 return o;
1717}
1718
1719/*
1720 Print a warning or fatal message.
1721*/
1722static char *
1723func_error (char *o, char **argv, const char *funcname)
1724{
1725 char **argvp;
1726 char *msg, *p;
1727 int len;
1728
1729 /* The arguments will be broken on commas. Rather than create yet
1730 another special case where function arguments aren't broken up,
1731 just create a format string that puts them back together. */
1732 for (len=0, argvp=argv; *argvp != 0; ++argvp)
1733 len += strlen (*argvp) + 2;
1734
1735 p = msg = alloca (len + 1);
1736
1737 for (argvp=argv; argvp[1] != 0; ++argvp)
1738 {
1739 strcpy (p, *argvp);
1740 p += strlen (*argvp);
1741 *(p++) = ',';
1742 *(p++) = ' ';
1743 }
1744 strcpy (p, *argvp);
1745
1746 switch (*funcname)
1747 {
1748 case 'e':
1749 OS (fatal, reading_file, "%s", msg);
1750
1751 case 'w':
1752 OS (error, reading_file, "%s", msg);
1753 break;
1754
1755 case 'i':
1756 outputs (0, msg);
1757 outputs (0, "\n");
1758 break;
1759
1760 default:
1761 OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
1762 }
1763
1764 /* The warning function expands to the empty string. */
1765 return o;
1766}
1767
1768
1769/*
1770 chop argv[0] into words, and sort them.
1771 */
1772static char *
1773func_sort (char *o, char **argv, const char *funcname UNUSED)
1774{
1775 const char *t;
1776 char **words;
1777 int wordi;
1778 char *p;
1779 unsigned int len;
1780
1781 /* Find the maximum number of words we'll have. */
1782 t = argv[0];
1783 wordi = 0;
1784 while ((p = find_next_token (&t, NULL)) != 0)
1785 {
1786 ++t;
1787 ++wordi;
1788 }
1789
1790 words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
1791
1792 /* Now assign pointers to each string in the array. */
1793 t = argv[0];
1794 wordi = 0;
1795 while ((p = find_next_token (&t, &len)) != 0)
1796 {
1797 if (*t != '\0') /* bird: Fixes access beyond end of string and overflowing words array. */
1798 ++t;
1799 p[len] = '\0';
1800 words[wordi++] = p;
1801 }
1802
1803 if (wordi)
1804 {
1805 int i;
1806
1807 /* Now sort the list of words. */
1808 qsort (words, wordi, sizeof (char *), alpha_compare);
1809
1810 /* Now write the sorted list, uniquified. */
1811#ifdef CONFIG_WITH_RSORT
1812 if (strcmp (funcname, "rsort"))
1813 {
1814 /* sort */
1815#endif
1816 for (i = 0; i < wordi; ++i)
1817 {
1818 len = strlen (words[i]);
1819 if (i == wordi - 1 || strlen (words[i + 1]) != len
1820 || strcmp (words[i], words[i + 1]))
1821 {
1822 o = variable_buffer_output (o, words[i], len);
1823 o = variable_buffer_output (o, " ", 1);
1824 }
1825 }
1826#ifdef CONFIG_WITH_RSORT
1827 }
1828 else
1829 {
1830 /* rsort - reverse the result */
1831 i = wordi;
1832 while (i-- > 0)
1833 {
1834 len = strlen (words[i]);
1835 if (i == 0 || strlen (words[i - 1]) != len
1836 || strcmp (words[i], words[i - 1]))
1837 {
1838 o = variable_buffer_output (o, words[i], len);
1839 o = variable_buffer_output (o, " ", 1);
1840 }
1841 }
1842 }
1843#endif
1844
1845 /* Kill the last space. */
1846 --o;
1847 }
1848
1849 free (words);
1850
1851 return o;
1852}
1853
1854/*
1855 $(if condition,true-part[,false-part])
1856
1857 CONDITION is false iff it evaluates to an empty string. White
1858 space before and after condition are stripped before evaluation.
1859
1860 If CONDITION is true, then TRUE-PART is evaluated, otherwise FALSE-PART is
1861 evaluated (if it exists). Because only one of the two PARTs is evaluated,
1862 you can use $(if ...) to create side-effects (with $(shell ...), for
1863 example).
1864*/
1865
1866static char *
1867func_if (char *o, char **argv, const char *funcname UNUSED)
1868{
1869 const char *begp = argv[0];
1870 const char *endp = begp + strlen (argv[0]) - 1;
1871 int result = 0;
1872
1873 /* Find the result of the condition: if we have a value, and it's not
1874 empty, the condition is true. If we don't have a value, or it's the
1875 empty string, then it's false. */
1876
1877 strip_whitespace (&begp, &endp);
1878
1879 if (begp <= endp)
1880 {
1881 char *expansion = expand_argument (begp, endp+1);
1882
1883 result = strlen (expansion);
1884 free (expansion);
1885 }
1886
1887 /* If the result is true (1) we want to eval the first argument, and if
1888 it's false (0) we want to eval the second. If the argument doesn't
1889 exist we do nothing, otherwise expand it and add to the buffer. */
1890
1891 argv += 1 + !result;
1892
1893 if (*argv)
1894 {
1895 char *expansion = expand_argument (*argv, NULL);
1896
1897 o = variable_buffer_output (o, expansion, strlen (expansion));
1898
1899 free (expansion);
1900 }
1901
1902 return o;
1903}
1904
1905/*
1906 $(or condition1[,condition2[,condition3[...]]])
1907
1908 A CONDITION is false iff it evaluates to an empty string. White
1909 space before and after CONDITION are stripped before evaluation.
1910
1911 CONDITION1 is evaluated. If it's true, then this is the result of
1912 expansion. If it's false, CONDITION2 is evaluated, and so on. If none of
1913 the conditions are true, the expansion is the empty string.
1914
1915 Once a CONDITION is true no further conditions are evaluated
1916 (short-circuiting).
1917*/
1918
1919static char *
1920func_or (char *o, char **argv, const char *funcname UNUSED)
1921{
1922 for ( ; *argv ; ++argv)
1923 {
1924 const char *begp = *argv;
1925 const char *endp = begp + strlen (*argv) - 1;
1926 char *expansion;
1927 int result = 0;
1928
1929 /* Find the result of the condition: if it's false keep going. */
1930
1931 strip_whitespace (&begp, &endp);
1932
1933 if (begp > endp)
1934 continue;
1935
1936 expansion = expand_argument (begp, endp+1);
1937 result = strlen (expansion);
1938
1939 /* If the result is false keep going. */
1940 if (!result)
1941 {
1942 free (expansion);
1943 continue;
1944 }
1945
1946 /* It's true! Keep this result and return. */
1947 o = variable_buffer_output (o, expansion, result);
1948 free (expansion);
1949 break;
1950 }
1951
1952 return o;
1953}
1954
1955/*
1956 $(and condition1[,condition2[,condition3[...]]])
1957
1958 A CONDITION is false iff it evaluates to an empty string. White
1959 space before and after CONDITION are stripped before evaluation.
1960
1961 CONDITION1 is evaluated. If it's false, then this is the result of
1962 expansion. If it's true, CONDITION2 is evaluated, and so on. If all of
1963 the conditions are true, the expansion is the result of the last condition.
1964
1965 Once a CONDITION is false no further conditions are evaluated
1966 (short-circuiting).
1967*/
1968
1969static char *
1970func_and (char *o, char **argv, const char *funcname UNUSED)
1971{
1972 char *expansion;
1973
1974 while (1)
1975 {
1976 const char *begp = *argv;
1977 const char *endp = begp + strlen (*argv) - 1;
1978 int result;
1979
1980 /* An empty condition is always false. */
1981 strip_whitespace (&begp, &endp);
1982 if (begp > endp)
1983 return o;
1984
1985 expansion = expand_argument (begp, endp+1);
1986 result = strlen (expansion);
1987
1988 /* If the result is false, stop here: we're done. */
1989 if (!result)
1990 break;
1991
1992 /* Otherwise the result is true. If this is the last one, keep this
1993 result and quit. Otherwise go on to the next one! */
1994
1995 if (*(++argv))
1996 free (expansion);
1997 else
1998 {
1999 o = variable_buffer_output (o, expansion, result);
2000 break;
2001 }
2002 }
2003
2004 free (expansion);
2005
2006 return o;
2007}
2008
2009static char *
2010func_wildcard (char *o, char **argv, const char *funcname UNUSED)
2011{
2012#ifdef _AMIGA
2013 o = wildcard_expansion (argv[0], o);
2014#else
2015 char *p = string_glob (argv[0]);
2016 o = variable_buffer_output (o, p, strlen (p));
2017#endif
2018 return o;
2019}
2020
2021/*
2022 $(eval <makefile string>)
2023
2024 Always resolves to the empty string.
2025
2026 Treat the arguments as a segment of makefile, and parse them.
2027*/
2028
2029static char *
2030func_eval (char *o, char **argv, const char *funcname UNUSED)
2031{
2032 char *buf;
2033 unsigned int len;
2034
2035 /* Eval the buffer. Pop the current variable buffer setting so that the
2036 eval'd code can use its own without conflicting. */
2037
2038 install_variable_buffer (&buf, &len);
2039
2040#ifndef CONFIG_WITH_VALUE_LENGTH
2041 eval_buffer (argv[0], NULL);
2042#else
2043 eval_buffer (argv[0], NULL, strchr (argv[0], '\0'));
2044#endif
2045
2046 restore_variable_buffer (buf, len);
2047
2048 return o;
2049}
2050
2051
2052#ifdef CONFIG_WITH_EVALPLUS
2053/* Same as func_eval except that we push and pop the local variable
2054 context before evaluating the buffer. */
2055static char *
2056func_evalctx (char *o, char **argv, const char *funcname UNUSED)
2057{
2058 char *buf;
2059 unsigned int len;
2060
2061 /* Eval the buffer. Pop the current variable buffer setting so that the
2062 eval'd code can use its own without conflicting. */
2063
2064 install_variable_buffer (&buf, &len);
2065
2066 push_new_variable_scope ();
2067
2068 eval_buffer (argv[0], NULL, strchr (argv[0], '\0'));
2069
2070 pop_variable_scope ();
2071
2072 restore_variable_buffer (buf, len);
2073
2074 return o;
2075}
2076
2077/* A mix of func_eval and func_value, saves memory for the expansion.
2078 This implements both evalval and evalvalctx, the latter has its own
2079 variable context just like evalctx. */
2080static char *
2081func_evalval (char *o, char **argv, const char *funcname)
2082{
2083 /* Look up the variable. */
2084 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
2085 if (v)
2086 {
2087 char *buf;
2088 unsigned int len;
2089 int var_ctx;
2090 size_t off;
2091 const floc *reading_file_saved = reading_file;
2092# ifdef CONFIG_WITH_MAKE_STATS
2093 unsigned long long uStartTick = CURRENT_CLOCK_TICK();
2094# ifndef CONFIG_WITH_COMPILER
2095 MAKE_STATS_2(v->evalval_count++);
2096# endif
2097# endif
2098
2099 var_ctx = !strcmp (funcname, "evalvalctx");
2100 if (var_ctx)
2101 push_new_variable_scope ();
2102 if (v->fileinfo.filenm)
2103 reading_file = &v->fileinfo;
2104
2105# ifdef CONFIG_WITH_COMPILER
2106 /* If this variable has been evaluated more than a few times, it make
2107 sense to compile it to speed up the processing. */
2108
2109 v->evalval_count++;
2110 if ( v->evalprog
2111 || (v->evalval_count == 3 && kmk_cc_compile_variable_for_eval (v)))
2112 {
2113 install_variable_buffer (&buf, &len); /* Really necessary? */
2114 kmk_exec_eval_variable (v);
2115 restore_variable_buffer (buf, len);
2116 }
2117 else
2118# endif
2119 {
2120 /* Make a copy of the value to the variable buffer first since
2121 eval_buffer will make changes to its input. */
2122
2123 off = o - variable_buffer;
2124 variable_buffer_output (o, v->value, v->value_length + 1);
2125 o = variable_buffer + off;
2126 assert (!o[v->value_length]);
2127
2128 install_variable_buffer (&buf, &len); /* Really necessary? */
2129 eval_buffer (o, NULL, o + v->value_length);
2130 restore_variable_buffer (buf, len);
2131 }
2132
2133 reading_file = reading_file_saved;
2134 if (var_ctx)
2135 pop_variable_scope ();
2136
2137 MAKE_STATS_2(v->cTicksEvalVal += CURRENT_CLOCK_TICK() - uStartTick);
2138 }
2139
2140 return o;
2141}
2142
2143/* Optimizes the content of one or more variables to save time in
2144 the eval functions. This function will collapse line continuations
2145 and remove comments. */
2146static char *
2147func_eval_optimize_variable (char *o, char **argv, const char *funcname)
2148{
2149 unsigned int i;
2150
2151 for (i = 0; argv[i]; i++)
2152 {
2153 struct variable *v = lookup_variable (argv[i], strlen (argv[i]));
2154# ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
2155 if (v && v->origin != o_automatic && !v->rdonly_val)
2156# else
2157 if (v && v->origin != o_automatic)
2158# endif
2159 {
2160 char *eos, *src;
2161
2162 eos = collapse_continuations (v->value, v->value_length);
2163 v->value_length = eos - v->value;
2164
2165 /* remove comments */
2166
2167 src = memchr (v->value, '#', v->value_length);
2168 if (src)
2169 {
2170 unsigned char ch = '\0';
2171 char *dst = src;
2172 do
2173 {
2174 /* drop blanks preceeding the comment */
2175 while (dst > v->value)
2176 {
2177 ch = (unsigned char)dst[-1];
2178 if (!ISBLANK (ch))
2179 break;
2180 dst--;
2181 }
2182
2183 /* advance SRC to eol / eos. */
2184 src = memchr (src, '\n', eos - src);
2185 if (!src)
2186 break;
2187
2188 /* drop a preceeding newline if possible (full line comment) */
2189 if (dst > v->value && dst[-1] == '\n')
2190 dst--;
2191
2192 /* copy till next comment or eol. */
2193 while (src < eos)
2194 {
2195 ch = *src++;
2196 if (ch == '#')
2197 break;
2198 *dst++ = ch;
2199 }
2200 }
2201 while (ch == '#' && src < eos);
2202
2203 *dst = '\0';
2204 v->value_length = dst - v->value;
2205 }
2206
2207 VARIABLE_CHANGED (v);
2208
2209# ifdef CONFIG_WITH_COMPILER
2210 /* Compile the variable for evalval, evalctx and expansion. */
2211
2212 if ( v->recursive
2213 && !IS_VARIABLE_RECURSIVE_WITHOUT_DOLLAR (v))
2214 kmk_cc_compile_variable_for_expand (v);
2215 kmk_cc_compile_variable_for_eval (v);
2216# endif
2217 }
2218 else if (v)
2219 OSS (error, NILF, _("$(%s ): variable `%s' is of the wrong type\n"), funcname, v->name);
2220 }
2221
2222 return o;
2223}
2224
2225#endif /* CONFIG_WITH_EVALPLUS */
2226
2227static char *
2228func_value (char *o, char **argv, const char *funcname UNUSED)
2229{
2230 /* Look up the variable. */
2231 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
2232
2233 /* Copy its value into the output buffer without expanding it. */
2234 if (v)
2235#ifdef CONFIG_WITH_VALUE_LENGTH
2236 {
2237 assert (v->value_length == strlen (v->value));
2238 o = variable_buffer_output (o, v->value, v->value_length);
2239 }
2240#else
2241 o = variable_buffer_output (o, v->value, strlen (v->value));
2242#endif
2243
2244 return o;
2245}
2246
2247/*
2248 \r is replaced on UNIX as well. Is this desirable?
2249 */
2250static void
2251fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
2252{
2253 char *dst = buffer;
2254 char *src = buffer;
2255 char *last_nonnl = buffer - 1;
2256 src[*length] = 0;
2257 for (; *src != '\0'; ++src)
2258 {
2259 if (src[0] == '\r' && src[1] == '\n')
2260 continue;
2261 if (*src == '\n')
2262 {
2263 *dst++ = ' ';
2264 }
2265 else
2266 {
2267 last_nonnl = dst;
2268 *dst++ = *src;
2269 }
2270 }
2271
2272 if (!trim_newlines && (last_nonnl < (dst - 2)))
2273 last_nonnl = dst - 2;
2274
2275 *(++last_nonnl) = '\0';
2276 *length = last_nonnl - buffer;
2277}
2278
2279pid_t shell_function_pid = 0;
2280static int shell_function_completed;
2281
2282void
2283shell_completed (int exit_code, int exit_sig)
2284{
2285 char buf[256];
2286
2287 shell_function_pid = 0;
2288 if (exit_sig == 0 && exit_code == 127)
2289 shell_function_completed = -1;
2290 else
2291 shell_function_completed = 1;
2292
2293 sprintf (buf, "%d", exit_code);
2294 define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
2295}
2296
2297#ifdef WINDOWS32
2298/*untested*/
2299
2300# ifndef CONFIG_NEW_WIN_CHILDREN
2301#include <windows.h>
2302#include <io.h>
2303#include "sub_proc.h"
2304
2305int
2306windows32_openpipe (int *pipedes, int errfd, pid_t *pid_p, char **command_argv, char **envp)
2307{
2308 SECURITY_ATTRIBUTES saAttr;
2309 HANDLE hIn = INVALID_HANDLE_VALUE;
2310 HANDLE hErr = INVALID_HANDLE_VALUE;
2311 HANDLE hChildOutRd;
2312 HANDLE hChildOutWr;
2313 HANDLE hProcess, tmpIn, tmpErr;
2314 DWORD e;
2315
2316 /* Set status for return. */
2317 pipedes[0] = pipedes[1] = -1;
2318 *pid_p = (pid_t)-1;
2319
2320 saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
2321 saAttr.bInheritHandle = TRUE;
2322 saAttr.lpSecurityDescriptor = NULL;
2323
2324 /* Standard handles returned by GetStdHandle can be NULL or
2325 INVALID_HANDLE_VALUE if the parent process closed them. If that
2326 happens, we open the null device and pass its handle to
2327 process_begin below as the corresponding handle to inherit. */
2328 tmpIn = GetStdHandle (STD_INPUT_HANDLE);
2329 if (DuplicateHandle (GetCurrentProcess (), tmpIn,
2330 GetCurrentProcess (), &hIn,
2331 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
2332 {
2333 e = GetLastError ();
2334 if (e == ERROR_INVALID_HANDLE)
2335 {
2336 tmpIn = CreateFile ("NUL", GENERIC_READ,
2337 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2338 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2339 if (tmpIn != INVALID_HANDLE_VALUE
2340 && DuplicateHandle (GetCurrentProcess (), tmpIn,
2341 GetCurrentProcess (), &hIn,
2342 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
2343 CloseHandle (tmpIn);
2344 }
2345 if (hIn == INVALID_HANDLE_VALUE)
2346 {
2347 ON (error, NILF,
2348 _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
2349 return -1;
2350 }
2351 }
2352 tmpErr = (HANDLE)_get_osfhandle (errfd);
2353 if (DuplicateHandle (GetCurrentProcess (), tmpErr,
2354 GetCurrentProcess (), &hErr,
2355 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
2356 {
2357 e = GetLastError ();
2358 if (e == ERROR_INVALID_HANDLE)
2359 {
2360 tmpErr = CreateFile ("NUL", GENERIC_WRITE,
2361 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2362 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2363 if (tmpErr != INVALID_HANDLE_VALUE
2364 && DuplicateHandle (GetCurrentProcess (), tmpErr,
2365 GetCurrentProcess (), &hErr,
2366 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
2367 CloseHandle (tmpErr);
2368 }
2369 if (hErr == INVALID_HANDLE_VALUE)
2370 {
2371 ON (error, NILF,
2372 _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
2373 return -1;
2374 }
2375 }
2376
2377 if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
2378 {
2379 ON (error, NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
2380 return -1;
2381 }
2382
2383 hProcess = process_init_fd (hIn, hChildOutWr, hErr);
2384
2385 if (!hProcess)
2386 {
2387 O (error, NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
2388 return -1;
2389 }
2390
2391 /* make sure that CreateProcess() has Path it needs */
2392 sync_Path_environment ();
2393 /* 'sync_Path_environment' may realloc 'environ', so take note of
2394 the new value. */
2395 envp = environ;
2396
2397 if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
2398 {
2399 /* register process for wait */
2400 process_register (hProcess);
2401
2402 /* set the pid for returning to caller */
2403 *pid_p = (pid_t) hProcess;
2404
2405 /* set up to read data from child */
2406 pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
2407
2408 /* this will be closed almost right away */
2409 pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
2410 return 0;
2411 }
2412 else
2413 {
2414 /* reap/cleanup the failed process */
2415 process_cleanup (hProcess);
2416
2417 /* close handles which were duplicated, they weren't used */
2418 if (hIn != INVALID_HANDLE_VALUE)
2419 CloseHandle (hIn);
2420 if (hErr != INVALID_HANDLE_VALUE)
2421 CloseHandle (hErr);
2422
2423 /* close pipe handles, they won't be used */
2424 CloseHandle (hChildOutRd);
2425 CloseHandle (hChildOutWr);
2426
2427 return -1;
2428 }
2429}
2430# endif /* !CONFIG_NEW_WIN_CHILDREN */
2431#endif
2432
2433
2434#ifdef __MSDOS__
2435FILE *
2436msdos_openpipe (int* pipedes, int *pidp, char *text)
2437{
2438 FILE *fpipe=0;
2439 /* MSDOS can't fork, but it has 'popen'. */
2440 struct variable *sh = lookup_variable ("SHELL", 5);
2441 int e;
2442 extern int dos_command_running, dos_status;
2443
2444 /* Make sure not to bother processing an empty line. */
2445 NEXT_TOKEN (text);
2446 if (*text == '\0')
2447 return 0;
2448
2449 if (sh)
2450 {
2451 char buf[PATH_MAX + 7];
2452 /* This makes sure $SHELL value is used by $(shell), even
2453 though the target environment is not passed to it. */
2454 sprintf (buf, "SHELL=%s", sh->value);
2455 putenv (buf);
2456 }
2457
2458 e = errno;
2459 errno = 0;
2460 dos_command_running = 1;
2461 dos_status = 0;
2462 /* If dos_status becomes non-zero, it means the child process
2463 was interrupted by a signal, like SIGINT or SIGQUIT. See
2464 fatal_error_signal in commands.c. */
2465 fpipe = popen (text, "rt");
2466 dos_command_running = 0;
2467 if (!fpipe || dos_status)
2468 {
2469 pipedes[0] = -1;
2470 *pidp = -1;
2471 if (dos_status)
2472 errno = EINTR;
2473 else if (errno == 0)
2474 errno = ENOMEM;
2475 if (fpipe)
2476 pclose (fpipe);
2477 shell_completed (127, 0);
2478 }
2479 else
2480 {
2481 pipedes[0] = fileno (fpipe);
2482 *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
2483 errno = e;
2484 }
2485 return fpipe;
2486}
2487#endif
2488
2489/*
2490 Do shell spawning, with the naughty bits for different OSes.
2491 */
2492
2493#ifdef VMS
2494
2495/* VMS can't do $(shell ...) */
2496
2497char *
2498func_shell_base (char *o, char **argv, int trim_newlines)
2499{
2500 fprintf (stderr, "This platform does not support shell\n");
2501 die (MAKE_TROUBLE);
2502 return NULL;
2503}
2504
2505#define func_shell 0
2506
2507#else
2508#ifndef _AMIGA
2509char *
2510func_shell_base (char *o, char **argv, int trim_newlines)
2511{
2512 char *batch_filename = NULL;
2513 int errfd;
2514#ifdef __MSDOS__
2515 FILE *fpipe;
2516#endif
2517 char **command_argv;
2518 const char * volatile error_prefix; /* bird: this volatile ~~and the 'o' one~~, is for shutting up gcc warnings */
2519 char **envp;
2520 int pipedes[2];
2521 pid_t pid;
2522
2523#ifndef __MSDOS__
2524#ifdef WINDOWS32
2525 /* Reset just_print_flag. This is needed on Windows when batch files
2526 are used to run the commands, because we normally refrain from
2527 creating batch files under -n. */
2528 int j_p_f = just_print_flag;
2529 just_print_flag = 0;
2530#endif
2531
2532 /* Construct the argument list. */
2533 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2534 &batch_filename);
2535 if (command_argv == 0)
2536 {
2537#ifdef WINDOWS32
2538 just_print_flag = j_p_f;
2539#endif
2540 return o;
2541 }
2542#endif /* !__MSDOS__ */
2543
2544 /* Using a target environment for 'shell' loses in cases like:
2545 export var = $(shell echo foobie)
2546 bad := $(var)
2547 because target_environment hits a loop trying to expand $(var) to put it
2548 in the environment. This is even more confusing when 'var' was not
2549 explicitly exported, but just appeared in the calling environment.
2550
2551 See Savannah bug #10593.
2552
2553 envp = target_environment (NULL);
2554 */
2555
2556 envp = environ;
2557
2558 /* For error messages. */
2559 if (reading_file && reading_file->filenm)
2560 {
2561 char *p = alloca (strlen (reading_file->filenm)+11+4);
2562 sprintf (p, "%s:%lu: ", reading_file->filenm,
2563 reading_file->lineno + reading_file->offset);
2564 error_prefix = p;
2565 }
2566 else
2567 error_prefix = "";
2568
2569 /* Set up the output in case the shell writes something. */
2570 output_start ();
2571
2572 errfd = (output_context && output_context->err >= 0
2573 ? output_context->err : FD_STDERR);
2574
2575#if defined(__MSDOS__)
2576 fpipe = msdos_openpipe (pipedes, &pid, argv[0]);
2577 if (pipedes[0] < 0)
2578 {
2579 perror_with_name (error_prefix, "pipe");
2580 return o;
2581 }
2582
2583#elif defined(WINDOWS32)
2584# ifdef CONFIG_NEW_WIN_CHILDREN
2585 pipedes[1] = -1;
2586 MkWinChildCreateWithStdOutPipe (command_argv, envp, errfd, &pid, &pipedes[0]);
2587# else
2588 windows32_openpipe (pipedes, errfd, &pid, command_argv, envp);
2589# endif
2590 /* Restore the value of just_print_flag. */
2591 just_print_flag = j_p_f;
2592
2593 if (pipedes[0] < 0)
2594 {
2595 /* Open of the pipe failed, mark as failed execution. */
2596 shell_completed (127, 0);
2597 perror_with_name (error_prefix, "pipe");
2598 return o;
2599 }
2600
2601#else
2602 if (pipe (pipedes) < 0)
2603 {
2604 perror_with_name (error_prefix, "pipe");
2605 return o;
2606 }
2607
2608 /* Close handles that are unnecessary for the child process. */
2609 CLOSE_ON_EXEC(pipedes[1]);
2610 CLOSE_ON_EXEC(pipedes[0]);
2611
2612 {
2613 struct output out;
2614 out.syncout = 1;
2615 out.out = pipedes[1];
2616 out.err = errfd;
2617
2618 pid = child_execute_job (&out, 1, command_argv, envp);
2619 }
2620
2621 if (pid < 0)
2622 {
2623 perror_with_name (error_prefix, "fork");
2624 return o;
2625 }
2626#endif
2627
2628 {
2629 char *buffer;
2630 unsigned int maxlen, i;
2631 int cc;
2632
2633 /* Record the PID for reap_children. */
2634 shell_function_pid = pid;
2635#ifndef __MSDOS__
2636 shell_function_completed = 0;
2637
2638 /* Free the storage only the child needed. */
2639 free (command_argv[0]);
2640 free (command_argv);
2641
2642 /* Close the write side of the pipe. We test for -1, since
2643 pipedes[1] is -1 on MS-Windows, and some versions of MS
2644 libraries barf when 'close' is called with -1. */
2645 if (pipedes[1] >= 0)
2646 close (pipedes[1]);
2647#endif
2648
2649 /* Set up and read from the pipe. */
2650
2651 maxlen = 200;
2652 buffer = xmalloc (maxlen + 1);
2653
2654 /* Read from the pipe until it gets EOF. */
2655 for (i = 0; ; i += cc)
2656 {
2657 if (i == maxlen)
2658 {
2659 maxlen += 512;
2660 buffer = xrealloc (buffer, maxlen + 1);
2661 }
2662
2663 EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
2664 if (cc <= 0)
2665 break;
2666 }
2667 buffer[i] = '\0';
2668
2669 /* Close the read side of the pipe. */
2670#ifdef __MSDOS__
2671 if (fpipe)
2672 {
2673 int st = pclose (fpipe);
2674 shell_completed (st, 0);
2675 }
2676#else
2677# ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
2678 if (pipedes[0] != -1)
2679# endif
2680 (void) close (pipedes[0]);
2681#endif
2682
2683 /* Loop until child_handler or reap_children() sets
2684 shell_function_completed to the status of our child shell. */
2685 while (shell_function_completed == 0)
2686 reap_children (1, 0);
2687
2688 if (batch_filename)
2689 {
2690 DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
2691 batch_filename));
2692 remove (batch_filename);
2693 free (batch_filename);
2694 }
2695 shell_function_pid = 0;
2696
2697 /* shell_completed() will set shell_function_completed to 1 when the
2698 child dies normally, or to -1 if it dies with status 127, which is
2699 most likely an exec fail. */
2700
2701 if (shell_function_completed == -1)
2702 {
2703 /* This likely means that the execvp failed, so we should just
2704 write the error message in the pipe from the child. */
2705 fputs (buffer, stderr);
2706 fflush (stderr);
2707 }
2708 else
2709 {
2710 /* The child finished normally. Replace all newlines in its output
2711 with spaces, and put that in the variable output buffer. */
2712 fold_newlines (buffer, &i, trim_newlines);
2713 o = variable_buffer_output (o, buffer, i);
2714 }
2715
2716 free (buffer);
2717 }
2718
2719 return o;
2720}
2721
2722#else /* _AMIGA */
2723
2724/* Do the Amiga version of func_shell. */
2725
2726char *
2727func_shell_base (char *o, char **argv, int trim_newlines)
2728{
2729 /* Amiga can't fork nor spawn, but I can start a program with
2730 redirection of my choice. However, this means that we
2731 don't have an opportunity to reopen stdout to trap it. Thus,
2732 we save our own stdout onto a new descriptor and dup a temp
2733 file's descriptor onto our stdout temporarily. After we
2734 spawn the shell program, we dup our own stdout back to the
2735 stdout descriptor. The buffer reading is the same as above,
2736 except that we're now reading from a file. */
2737
2738#include <dos/dos.h>
2739#include <proto/dos.h>
2740
2741 BPTR child_stdout;
2742 char tmp_output[FILENAME_MAX];
2743 unsigned int maxlen = 200, i;
2744 int cc;
2745 char * buffer, * ptr;
2746 char ** aptr;
2747 int len = 0;
2748 char* batch_filename = NULL;
2749
2750 /* Construct the argument list. */
2751 command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
2752 &batch_filename);
2753 if (command_argv == 0)
2754 return o;
2755
2756 /* Note the mktemp() is a security hole, but this only runs on Amiga.
2757 Ideally we would use output_tmpfile(), but this uses a special
2758 Open(), not fopen(), and I'm not familiar enough with the code to mess
2759 with it. */
2760 strcpy (tmp_output, "t:MakeshXXXXXXXX");
2761 mktemp (tmp_output);
2762 child_stdout = Open (tmp_output, MODE_NEWFILE);
2763
2764 for (aptr=command_argv; *aptr; aptr++)
2765 len += strlen (*aptr) + 1;
2766
2767 buffer = xmalloc (len + 1);
2768 ptr = buffer;
2769
2770 for (aptr=command_argv; *aptr; aptr++)
2771 {
2772 strcpy (ptr, *aptr);
2773 ptr += strlen (ptr) + 1;
2774 *ptr ++ = ' ';
2775 *ptr = 0;
2776 }
2777
2778 ptr[-1] = '\n';
2779
2780 Execute (buffer, NULL, child_stdout);
2781 free (buffer);
2782
2783 Close (child_stdout);
2784
2785 child_stdout = Open (tmp_output, MODE_OLDFILE);
2786
2787 buffer = xmalloc (maxlen);
2788 i = 0;
2789 do
2790 {
2791 if (i == maxlen)
2792 {
2793 maxlen += 512;
2794 buffer = xrealloc (buffer, maxlen + 1);
2795 }
2796
2797 cc = Read (child_stdout, &buffer[i], maxlen - i);
2798 if (cc > 0)
2799 i += cc;
2800 } while (cc > 0);
2801
2802 Close (child_stdout);
2803
2804 fold_newlines (buffer, &i, trim_newlines);
2805 o = variable_buffer_output (o, buffer, i);
2806 free (buffer);
2807 return o;
2808}
2809#endif /* _AMIGA */
2810
2811static char *
2812func_shell (char *o, char **argv, const char *funcname UNUSED)
2813{
2814 return func_shell_base (o, argv, 1);
2815}
2816#endif /* !VMS */
2817
2818#ifdef EXPERIMENTAL
2819
2820/*
2821 equality. Return is string-boolean, i.e., the empty string is false.
2822 */
2823static char *
2824func_eq (char *o, char **argv, const char *funcname UNUSED)
2825{
2826 int result = ! strcmp (argv[0], argv[1]);
2827 o = variable_buffer_output (o, result ? "1" : "", result);
2828 return o;
2829}
2830
2831
2832/*
2833 string-boolean not operator.
2834 */
2835static char *
2836func_not (char *o, char **argv, const char *funcname UNUSED)
2837{
2838 const char *s = argv[0];
2839 int result = 0;
2840 NEXT_TOKEN (s);
2841 result = ! (*s);
2842 o = variable_buffer_output (o, result ? "1" : "", result);
2843 return o;
2844}
2845#endif
2846
2847
2848
2849#ifdef HAVE_DOS_PATHS
2850# ifdef __CYGWIN__
2851# define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || STOP_SET (n[0], MAP_DIRSEP))
2852# else
2853# define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
2854# endif
2855# define ROOT_LEN 3
2856#else
2857#define IS_ABSOLUTE(n) (n[0] == '/')
2858#define ROOT_LEN 1
2859#endif
2860
2861/* Return the absolute name of file NAME which does not contain any '.',
2862 '..' components nor any repeated path separators ('/'). */
2863#ifdef KMK
2864char *
2865#else
2866static char *
2867#endif
2868abspath (const char *name, char *apath)
2869{
2870 char *dest;
2871 const char *start, *end, *apath_limit;
2872 unsigned long root_len = ROOT_LEN;
2873
2874 if (name[0] == '\0' || apath == NULL)
2875 return NULL;
2876
2877#ifdef WINDOWS32 /* bird */
2878 dest = w32ify((char *)name, 1);
2879 if (!dest)
2880 return NULL;
2881 {
2882 size_t len = strlen(dest);
2883 memcpy(apath, dest, len);
2884 dest = apath + len;
2885 }
2886
2887 (void)end; (void)start; (void)apath_limit;
2888
2889#elif defined __OS2__ /* bird */
2890 if (_abspath(apath, name, GET_PATH_MAX))
2891 return NULL;
2892 dest = strchr(apath, '\0');
2893
2894 (void)end; (void)start; (void)apath_limit; (void)dest;
2895
2896#else /* !WINDOWS32 && !__OS2__ */
2897 apath_limit = apath + GET_PATH_MAX;
2898
2899 if (!IS_ABSOLUTE(name))
2900 {
2901 /* It is unlikely we would make it until here but just to make sure. */
2902 if (!starting_directory)
2903 return NULL;
2904
2905 strcpy (apath, starting_directory);
2906
2907#ifdef HAVE_DOS_PATHS
2908 if (STOP_SET (name[0], MAP_DIRSEP))
2909 {
2910 if (STOP_SET (name[1], MAP_DIRSEP))
2911 {
2912 /* A UNC. Don't prepend a drive letter. */
2913 apath[0] = name[0];
2914 apath[1] = name[1];
2915 root_len = 2;
2916 }
2917 /* We have /foo, an absolute file name except for the drive
2918 letter. Assume the missing drive letter is the current
2919 drive, which we can get if we remove from starting_directory
2920 everything past the root directory. */
2921 apath[root_len] = '\0';
2922 }
2923#endif
2924
2925 dest = strchr (apath, '\0');
2926 }
2927 else
2928 {
2929#if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
2930 if (STOP_SET (name[0], MAP_DIRSEP))
2931 root_len = 1;
2932#endif
2933 strncpy (apath, name, root_len);
2934 apath[root_len] = '\0';
2935 dest = apath + root_len;
2936 /* Get past the root, since we already copied it. */
2937 name += root_len;
2938#ifdef HAVE_DOS_PATHS
2939 if (! STOP_SET (apath[root_len - 1], MAP_DIRSEP))
2940 {
2941 /* Convert d:foo into d:./foo and increase root_len. */
2942 apath[2] = '.';
2943 apath[3] = '/';
2944 dest++;
2945 root_len++;
2946 /* strncpy above copied one character too many. */
2947 name--;
2948 }
2949 else
2950 apath[root_len - 1] = '/'; /* make sure it's a forward slash */
2951#endif
2952 }
2953
2954 for (start = end = name; *start != '\0'; start = end)
2955 {
2956 unsigned long len;
2957
2958 /* Skip sequence of multiple path-separators. */
2959 while (STOP_SET (*start, MAP_DIRSEP))
2960 ++start;
2961
2962 /* Find end of path component. */
2963 for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
2964 ;
2965
2966 len = end - start;
2967
2968 if (len == 0)
2969 break;
2970 else if (len == 1 && start[0] == '.')
2971 /* nothing */;
2972 else if (len == 2 && start[0] == '.' && start[1] == '.')
2973 {
2974 /* Back up to previous component, ignore if at root already. */
2975 if (dest > apath + root_len)
2976 for (--dest; ! STOP_SET (dest[-1], MAP_DIRSEP); --dest)
2977 ;
2978 }
2979 else
2980 {
2981 if (! STOP_SET (dest[-1], MAP_DIRSEP))
2982 *dest++ = '/';
2983
2984 if (dest + len >= apath_limit)
2985 return NULL;
2986
2987 dest = memcpy (dest, start, len);
2988 dest += len;
2989 *dest = '\0';
2990 }
2991 }
2992#endif /* !WINDOWS32 && !__OS2__ */
2993
2994 /* Unless it is root strip trailing separator. */
2995 if (dest > apath + root_len && STOP_SET (dest[-1], MAP_DIRSEP))
2996 --dest;
2997
2998 *dest = '\0';
2999
3000 return apath;
3001}
3002
3003
3004static char *
3005func_realpath (char *o, char **argv, const char *funcname UNUSED)
3006{
3007 /* Expand the argument. */
3008 const char *p = argv[0];
3009 const char *path = 0;
3010 int doneany = 0;
3011 unsigned int len = 0;
3012
3013 while ((path = find_next_token (&p, &len)) != 0)
3014 {
3015 if (len < GET_PATH_MAX)
3016 {
3017 char *rp;
3018 struct stat st;
3019 PATH_VAR (in);
3020 PATH_VAR (out);
3021
3022 strncpy (in, path, len);
3023 in[len] = '\0';
3024
3025#ifdef HAVE_REALPATH
3026 ENULLLOOP (rp, realpath (in, out));
3027#else
3028 rp = abspath (in, out);
3029#endif
3030
3031 if (rp)
3032 {
3033 int r;
3034 EINTRLOOP (r, stat (out, &st));
3035 if (r == 0)
3036 {
3037 o = variable_buffer_output (o, out, strlen (out));
3038 o = variable_buffer_output (o, " ", 1);
3039 doneany = 1;
3040 }
3041 }
3042 }
3043 }
3044
3045 /* Kill last space. */
3046 if (doneany)
3047 --o;
3048
3049 return o;
3050}
3051
3052static char *
3053func_file (char *o, char **argv, const char *funcname UNUSED)
3054{
3055 char *fn = argv[0];
3056
3057 if (fn[0] == '>')
3058 {
3059 FILE *fp;
3060 const char *mode = "w";
3061
3062 /* We are writing a file. */
3063 ++fn;
3064 if (fn[0] == '>')
3065 {
3066 mode = "a";
3067 ++fn;
3068 }
3069 NEXT_TOKEN (fn);
3070
3071 if (fn[0] == '\0')
3072 O (fatal, *expanding_var, _("file: missing filename"));
3073
3074 ENULLLOOP (fp, fopen (fn, mode));
3075 if (fp == NULL)
3076 OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
3077
3078 if (argv[1])
3079 {
3080 int l = strlen (argv[1]);
3081 int nl = l == 0 || argv[1][l-1] != '\n';
3082
3083 if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
3084 OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
3085 }
3086 if (fclose (fp))
3087 OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
3088 }
3089 else if (fn[0] == '<')
3090 {
3091 char *preo = o;
3092 FILE *fp;
3093
3094 ++fn;
3095 NEXT_TOKEN (fn);
3096 if (fn[0] == '\0')
3097 O (fatal, *expanding_var, _("file: missing filename"));
3098
3099 if (argv[1])
3100 O (fatal, *expanding_var, _("file: too many arguments"));
3101
3102 ENULLLOOP (fp, fopen (fn, "r"));
3103 if (fp == NULL)
3104 {
3105 if (errno == ENOENT)
3106 return o;
3107 OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
3108 }
3109
3110 while (1)
3111 {
3112 char buf[1024];
3113 size_t l = fread (buf, 1, sizeof (buf), fp);
3114 if (l > 0)
3115 o = variable_buffer_output (o, buf, l);
3116
3117 if (ferror (fp))
3118 if (errno != EINTR)
3119 OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
3120 if (feof (fp))
3121 break;
3122 }
3123 if (fclose (fp))
3124 OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
3125
3126 /* Remove trailing newline. */
3127 if (o > preo && o[-1] == '\n')
3128 if (--o > preo && o[-1] == '\r')
3129 --o;
3130 }
3131 else
3132 OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
3133
3134 return o;
3135}
3136
3137static char *
3138func_abspath (char *o, char **argv, const char *funcname UNUSED)
3139{
3140 /* Expand the argument. */
3141 const char *p = argv[0];
3142 const char *path = 0;
3143 int doneany = 0;
3144 unsigned int len = 0;
3145
3146 while ((path = find_next_token (&p, &len)) != 0)
3147 {
3148 if (len < GET_PATH_MAX)
3149 {
3150 PATH_VAR (in);
3151 PATH_VAR (out);
3152
3153 strncpy (in, path, len);
3154 in[len] = '\0';
3155
3156 if (abspath (in, out))
3157 {
3158 o = variable_buffer_output (o, out, strlen (out));
3159 o = variable_buffer_output (o, " ", 1);
3160 doneany = 1;
3161 }
3162 }
3163 }
3164
3165 /* Kill last space. */
3166 if (doneany)
3167 --o;
3168
3169 return o;
3170}
3171
3172#ifdef CONFIG_WITH_ABSPATHEX
3173/* Same as abspath except that the current path may be given as the
3174 2nd argument. */
3175static char *
3176func_abspathex (char *o, char **argv, const char *funcname UNUSED)
3177{
3178 char *cwd = argv[1];
3179
3180 /* cwd needs leading spaces chopped and may be optional,
3181 in which case we're exactly like $(abspath ). */
3182 if (cwd)
3183 while (ISBLANK (*cwd))
3184 cwd++;
3185 if (!cwd || !*cwd)
3186 o = func_abspath (o, argv, funcname);
3187 else
3188 {
3189 /* Expand the argument. */
3190 const char *p = argv[0];
3191 unsigned int cwd_len = ~0U;
3192 char *path = 0;
3193 int doneany = 0;
3194 unsigned int len = 0;
3195 PATH_VAR (in);
3196 PATH_VAR (out);
3197
3198 while ((path = find_next_token (&p, &len)) != 0)
3199 {
3200 if (len < GET_PATH_MAX)
3201 {
3202#ifdef HAVE_DOS_PATHS
3203 if (path[0] != '/' && path[0] != '\\' && (len < 2 || path[1] != ':') && cwd)
3204#else
3205 if (path[0] != '/' && cwd)
3206#endif
3207 {
3208 /* relative path, prefix with cwd. */
3209 if (cwd_len == ~0U)
3210 cwd_len = strlen (cwd);
3211 if (cwd_len + len + 1 >= GET_PATH_MAX)
3212 continue;
3213 memcpy (in, cwd, cwd_len);
3214 in[cwd_len] = '/';
3215 memcpy (in + cwd_len + 1, path, len);
3216 in[cwd_len + len + 1] = '\0';
3217 }
3218 else
3219 {
3220 /* absolute path pass it as-is. */
3221 memcpy (in, path, len);
3222 in[len] = '\0';
3223 }
3224
3225 if (abspath (in, out))
3226 {
3227 o = variable_buffer_output (o, out, strlen (out));
3228 o = variable_buffer_output (o, " ", 1);
3229 doneany = 1;
3230 }
3231 }
3232 }
3233
3234 /* Kill last space. */
3235 if (doneany)
3236 --o;
3237 }
3238
3239 return o;
3240}
3241#endif
3242
3243#ifdef CONFIG_WITH_XARGS
3244/* Create one or more command lines avoiding the max argument
3245 length restriction of the host OS.
3246
3247 The last argument is the list of arguments that the normal
3248 xargs command would be fed from stdin.
3249
3250 The first argument is initial command and it's arguments.
3251
3252 If there are three or more arguments, the 2nd argument is
3253 the command and arguments to be used on subsequent
3254 command lines. Defaults to the initial command.
3255
3256 If there are four or more arguments, the 3rd argument is
3257 the command to be used at the final command line. Defaults
3258 to the sub sequent or initial command .
3259
3260 A future version of this function may define more arguments
3261 and therefor anyone specifying six or more arguments will
3262 cause fatal errors.
3263
3264 Typical usage is:
3265 $(xargs ar cas mylib.a,$(objects))
3266 or
3267 $(xargs ar cas mylib.a,ar as mylib.a,$(objects))
3268
3269 It will then create one or more "ar mylib.a ..." command
3270 lines with proper \n\t separation so it can be used when
3271 writing rules. */
3272static char *
3273func_xargs (char *o, char **argv, const char *funcname UNUSED)
3274{
3275 int argc;
3276 const char *initial_cmd;
3277 size_t initial_cmd_len;
3278 const char *subsequent_cmd;
3279 size_t subsequent_cmd_len;
3280 const char *final_cmd;
3281 size_t final_cmd_len;
3282 const char *args;
3283 size_t max_args;
3284 int i;
3285
3286#ifdef ARG_MAX
3287 /* ARG_MAX is a bit unreliable (environment), so drop 25% of the max. */
3288# define XARGS_MAX (ARG_MAX - (ARG_MAX / 4))
3289#else /* FIXME: update configure with a command line length test. */
3290# define XARGS_MAX 10240
3291#endif
3292
3293 argc = 0;
3294 while (argv[argc])
3295 argc++;
3296 if (argc > 4)
3297 O (fatal, NILF, _("Too many arguments for $(xargs)!\n"));
3298
3299 /* first: the initial / default command.*/
3300 initial_cmd = argv[0];
3301 while (ISSPACE (*initial_cmd))
3302 initial_cmd++;
3303 max_args = initial_cmd_len = strlen (initial_cmd);
3304
3305 /* second: the command for the subsequent command lines. defaults to the initial cmd. */
3306 subsequent_cmd = argc > 2 && argv[1][0] != '\0' ? argv[1] : "\0";
3307 while (ISSPACE (*subsequent_cmd))
3308 subsequent_cmd++; /* gcc 7.3.0 complains "offset ‘1’ outside bounds of constant string" if constant is "" rather than "\0". */
3309 if (*subsequent_cmd)
3310 {
3311 subsequent_cmd_len = strlen (subsequent_cmd);
3312 if (subsequent_cmd_len > max_args)
3313 max_args = subsequent_cmd_len;
3314 }
3315 else
3316 {
3317 subsequent_cmd = initial_cmd;
3318 subsequent_cmd_len = initial_cmd_len;
3319 }
3320
3321 /* third: the final command. defaults to the subseq cmd. */
3322 final_cmd = argc > 3 && argv[2][0] != '\0' ? argv[2] : "\0";
3323 while (ISSPACE (*final_cmd))
3324 final_cmd++; /* gcc 7.3.0: same complaint as for subsequent_cmd++ */
3325 if (*final_cmd)
3326 {
3327 final_cmd_len = strlen (final_cmd);
3328 if (final_cmd_len > max_args)
3329 max_args = final_cmd_len;
3330 }
3331 else
3332 {
3333 final_cmd = subsequent_cmd;
3334 final_cmd_len = subsequent_cmd_len;
3335 }
3336
3337 /* last: the arguments to split up into sensible portions. */
3338 args = argv[argc - 1];
3339
3340 /* calc the max argument length. */
3341 if (XARGS_MAX <= max_args + 2)
3342 ONN (fatal, NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
3343 (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
3344 max_args = XARGS_MAX - max_args - 1;
3345
3346 /* generate the commands. */
3347 i = 0;
3348 for (i = 0; ; i++)
3349 {
3350 unsigned int len;
3351 const char *iterator = args;
3352 const char *end = args;
3353 const char *cur;
3354 const char *tmp;
3355
3356 /* scan the arguments till we reach the end or the max length. */
3357 while ((cur = find_next_token(&iterator, &len))
3358 && (size_t)((cur + len) - args) < max_args)
3359 end = cur + len;
3360 if (cur && end == args)
3361 O (fatal, NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
3362
3363 /* emit the command. */
3364 if (i == 0)
3365 {
3366 o = variable_buffer_output (o, (char *)initial_cmd, initial_cmd_len);
3367 o = variable_buffer_output (o, " ", 1);
3368 }
3369 else if (cur)
3370 {
3371 o = variable_buffer_output (o, "\n\t", 2);
3372 o = variable_buffer_output (o, (char *)subsequent_cmd, subsequent_cmd_len);
3373 o = variable_buffer_output (o, " ", 1);
3374 }
3375 else
3376 {
3377 o = variable_buffer_output (o, "\n\t", 2);
3378 o = variable_buffer_output (o, (char *)final_cmd, final_cmd_len);
3379 o = variable_buffer_output (o, " ", 1);
3380 }
3381
3382 tmp = end;
3383 while (tmp > args && ISSPACE (tmp[-1])) /* drop trailing spaces. */
3384 tmp--;
3385 o = variable_buffer_output (o, (char *)args, tmp - args);
3386
3387
3388 /* next */
3389 if (!cur)
3390 break;
3391 args = end;
3392 while (ISSPACE (*args))
3393 args++;
3394 }
3395
3396 return o;
3397}
3398#endif
3399
3400
3401#ifdef CONFIG_WITH_STRING_FUNCTIONS
3402/*
3403 $(length string)
3404
3405 XXX: This doesn't take multibyte locales into account.
3406 */
3407static char *
3408func_length (char *o, char **argv, const char *funcname UNUSED)
3409{
3410 size_t len = strlen (argv[0]);
3411 return math_int_to_variable_buffer (o, len);
3412}
3413
3414/*
3415 $(length-var var)
3416
3417 XXX: This doesn't take multibyte locales into account.
3418 */
3419static char *
3420func_length_var (char *o, char **argv, const char *funcname UNUSED)
3421{
3422 struct variable *var = lookup_variable (argv[0], strlen (argv[0]));
3423 return math_int_to_variable_buffer (o, var ? var->value_length : 0);
3424}
3425
3426
3427/* func_insert and func_substr helper. */
3428static char *
3429helper_pad (char *o, size_t to_add, const char *pad, size_t pad_len)
3430{
3431 while (to_add > 0)
3432 {
3433 size_t size = to_add > pad_len ? pad_len : to_add;
3434 o = variable_buffer_output (o, pad, size);
3435 to_add -= size;
3436 }
3437 return o;
3438}
3439
3440/*
3441 $(insert in, str[, n[, length[, pad]]])
3442
3443 XXX: This doesn't take multibyte locales into account.
3444 */
3445static char *
3446func_insert (char *o, char **argv, const char *funcname UNUSED)
3447{
3448 const char *in = argv[0];
3449 math_int in_len = (math_int)strlen (in);
3450 const char *str = argv[1];
3451 math_int str_len = (math_int)strlen (str);
3452 math_int n = 0;
3453 math_int length = str_len;
3454 const char *pad = " ";
3455 size_t pad_len = 16;
3456 size_t i;
3457
3458 if (argv[2] != NULL)
3459 {
3460 n = math_int_from_string (argv[2]);
3461 if (n > 0)
3462 n--; /* one-origin */
3463 else if (n == 0)
3464 n = str_len; /* append */
3465 else
3466 { /* n < 0: from the end */
3467 n = str_len + n;
3468 if (n < 0)
3469 n = 0;
3470 }
3471 if (n > 16*1024*1024) /* 16MB */
3472 OS (fatal, NILF, _("$(insert ): n=%s is out of bounds\n"), argv[2]);
3473
3474 if (argv[3] != NULL)
3475 {
3476 length = math_int_from_string (argv[3]);
3477 if (length < 0 || length > 16*1024*1024 /* 16MB */)
3478 OS (fatal, NILF, _("$(insert ): length=%s is out of bounds\n"), argv[3]);
3479
3480 if (argv[4] != NULL)
3481 {
3482 const char *tmp = argv[4];
3483 for (i = 0; tmp[i] == ' '; i++)
3484 /* nothing */;
3485 if (tmp[i] != '\0')
3486 {
3487 pad = argv[4];
3488 pad_len = strlen (pad);
3489 }
3490 /* else: it was all default spaces. */
3491 }
3492 }
3493 }
3494
3495 /* the head of the original string */
3496 if (n > 0)
3497 {
3498 if (n <= str_len)
3499 o = variable_buffer_output (o, str, n);
3500 else
3501 {
3502 o = variable_buffer_output (o, str, str_len);
3503 o = helper_pad (o, n - str_len, pad, pad_len);
3504 }
3505 }
3506
3507 /* insert the string */
3508 if (length <= in_len)
3509 o = variable_buffer_output (o, in, length);
3510 else
3511 {
3512 o = variable_buffer_output (o, in, in_len);
3513 o = helper_pad (o, length - in_len, pad, pad_len);
3514 }
3515
3516 /* the tail of the original string */
3517 if (n < str_len)
3518 o = variable_buffer_output (o, str + n, str_len - n);
3519
3520 return o;
3521}
3522
3523
3524/*
3525 $(pos needle, haystack[, start])
3526 $(lastpos needle, haystack[, start])
3527
3528 XXX: This doesn't take multibyte locales into account.
3529 */
3530static char *
3531func_pos (char *o, char **argv, const char *funcname UNUSED)
3532{
3533 const char *needle = *argv[0] ? argv[0] : " ";
3534 size_t needle_len = strlen (needle);
3535 const char *haystack = argv[1];
3536 size_t haystack_len = strlen (haystack);
3537 math_int start = 0;
3538 const char *hit;
3539
3540 if (argv[2] != NULL)
3541 {
3542 start = math_int_from_string (argv[2]);
3543 if (start > 0)
3544 start--; /* one-origin */
3545 else if (start < 0)
3546 start = haystack_len + start; /* from the end */
3547 if (start < 0 || start + needle_len > haystack_len)
3548 return math_int_to_variable_buffer (o, 0);
3549 }
3550 else if (funcname[0] == 'l')
3551 start = haystack_len - 1;
3552
3553 /* do the searching */
3554 if (funcname[0] != 'l')
3555 { /* pos */
3556 if (needle_len == 1)
3557 hit = strchr (haystack + start, *needle);
3558 else
3559 hit = strstr (haystack + start, needle);
3560 }
3561 else
3562 { /* last pos */
3563 int ch = *needle;
3564 size_t off = start + 1;
3565
3566 hit = NULL;
3567 while (off-- > 0)
3568 {
3569 if ( haystack[off] == ch
3570 && ( needle_len == 1
3571 || strncmp (&haystack[off], needle, needle_len) == 0))
3572 {
3573 hit = haystack + off;
3574 break;
3575 }
3576 }
3577 }
3578
3579 return math_int_to_variable_buffer (o, hit ? hit - haystack + 1 : 0);
3580}
3581
3582
3583/*
3584 $(substr str, start[, length[, pad]])
3585
3586 XXX: This doesn't take multibyte locales into account.
3587 */
3588static char *
3589func_substr (char *o, char **argv, const char *funcname UNUSED)
3590{
3591 const char *str = argv[0];
3592 math_int str_len = (math_int)strlen (str);
3593 math_int start = math_int_from_string (argv[1]);
3594 math_int length = 0;
3595 const char *pad = NULL;
3596 size_t pad_len = 0;
3597
3598 if (argv[2] != NULL)
3599 {
3600 if (argv[3] != NULL)
3601 {
3602 pad = argv[3];
3603 for (pad_len = 0; pad[pad_len] == ' '; pad_len++)
3604 /* nothing */;
3605 if (pad[pad_len] != '\0')
3606 pad_len = strlen (pad);
3607 else
3608 {
3609 pad = " ";
3610 pad_len = 16;
3611 }
3612 }
3613 length = math_int_from_string (argv[2]);
3614 if (pad != NULL && length > 16*1024*1024 /* 16MB */)
3615 OS (fatal, NILF, _("$(substr ): length=%s is out of bounds\n"), argv[2]);
3616 if (pad != NULL && length < 0)
3617 OS (fatal, NILF, _("$(substr ): negative length (%s) and padding doesn't mix.\n"), argv[2]);
3618 if (length == 0)
3619 return o;
3620 }
3621
3622 /* Note that negative start is and length are used for referencing from the
3623 end of the string. */
3624 if (pad == NULL)
3625 {
3626 if (start > 0)
3627 start--; /* one-origin */
3628 else
3629 {
3630 start = str_len + start;
3631 if (start <= 0)
3632 {
3633 if (length < 0)
3634 return o;
3635 start += length;
3636 if (start <= 0)
3637 return o;
3638 length = start;
3639 start = 0;
3640 }
3641 }
3642
3643 if (start >= str_len)
3644 return o;
3645 if (length == 0)
3646 length = str_len - start;
3647 else if (length < 0)
3648 {
3649 if (str_len <= -length)
3650 return o;
3651 length += str_len;
3652 if (length <= start)
3653 return o;
3654 length -= start;
3655 }
3656 else if (start + length > str_len)
3657 length = str_len - start;
3658
3659 o = variable_buffer_output (o, str + start, length);
3660 }
3661 else
3662 {
3663 if (start > 0)
3664 {
3665 start--; /* one-origin */
3666 if (start >= str_len)
3667 return length ? helper_pad (o, length, pad, pad_len) : o;
3668 if (length == 0)
3669 length = str_len - start;
3670 }
3671 else
3672 {
3673 start = str_len + start;
3674 if (start <= 0)
3675 {
3676 if (start + length <= 0)
3677 return length ? helper_pad (o, length, pad, pad_len) : o;
3678 o = helper_pad (o, -start, pad, pad_len);
3679 return variable_buffer_output (o, str, length + start);
3680 }
3681 if (length == 0)
3682 length = str_len - start;
3683 }
3684 if (start + length <= str_len)
3685 o = variable_buffer_output (o, str + start, length);
3686 else
3687 {
3688 o = variable_buffer_output (o, str + start, str_len - start);
3689 o = helper_pad (o, start + length - str_len, pad, pad_len);
3690 }
3691 }
3692
3693 return o;
3694}
3695
3696
3697/*
3698 $(translate string, from-set[, to-set[, pad-char]])
3699
3700 XXX: This doesn't take multibyte locales into account.
3701 */
3702static char *
3703func_translate (char *o, char **argv, const char *funcname UNUSED)
3704{
3705 const unsigned char *str = (const unsigned char *)argv[0];
3706 const unsigned char *from_set = (const unsigned char *)argv[1];
3707 const char *to_set = argv[2] != NULL ? argv[2] : "";
3708 char trans_tab[1 << CHAR_BIT];
3709 int i;
3710 char ch;
3711
3712 /* init the array. */
3713 for (i = 0; i < (1 << CHAR_BIT); i++)
3714 trans_tab[i] = i;
3715
3716 while ( (i = *from_set) != '\0'
3717 && (ch = *to_set) != '\0')
3718 {
3719 trans_tab[i] = ch;
3720 from_set++;
3721 to_set++;
3722 }
3723
3724 if (i != '\0')
3725 {
3726 ch = '\0'; /* no padding == remove char */
3727 if (argv[2] != NULL && argv[3] != NULL)
3728 {
3729 ch = argv[3][0];
3730 if (ch && argv[3][1])
3731 OS (fatal, NILF, _("$(translate ): pad=`%s' expected a single char\n"), argv[3]);
3732 if (ch == '\0') /* no char == space */
3733 ch = ' ';
3734 }
3735 while ((i = *from_set++) != '\0')
3736 trans_tab[i] = ch;
3737 }
3738
3739 /* do the translation */
3740 while ((i = *str++) != '\0')
3741 {
3742 ch = trans_tab[i];
3743 if (ch)
3744 o = variable_buffer_output (o, &ch, 1);
3745 }
3746
3747 return o;
3748}
3749#endif /* CONFIG_WITH_STRING_FUNCTIONS */
3750
3751
3752#ifdef CONFIG_WITH_LAZY_DEPS_VARS
3753
3754/* This is also in file.c (bad). */
3755# if VMS
3756# define FILE_LIST_SEPARATOR ','
3757# else
3758# define FILE_LIST_SEPARATOR ' '
3759# endif
3760
3761/* Implements $^ and $+.
3762
3763 The first comes with FUNCNAME 'deps', the second as 'deps-all'.
3764
3765 If no second argument is given, or if it's empty, or if it's zero,
3766 all dependencies will be returned. If the second argument is non-zero
3767 the dependency at that position will be returned. If the argument is
3768 negative a fatal error is thrown. */
3769static char *
3770func_deps (char *o, char **argv, const char *funcname)
3771{
3772 unsigned int idx = 0;
3773 struct file *file;
3774
3775 /* Handle the argument if present. */
3776
3777 if (argv[1])
3778 {
3779 char *p = argv[1];
3780 while (ISSPACE (*p))
3781 p++;
3782 if (*p != '\0')
3783 {
3784 char *n;
3785 long l = strtol (p, &n, 0);
3786 while (ISSPACE (*n))
3787 n++;
3788 idx = l;
3789 if (*n != '\0' || l < 0 || (long)idx != l)
3790 OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
3791 }
3792 }
3793
3794 /* Find the file and select the list corresponding to FUNCNAME. */
3795
3796 file = lookup_file (argv[0]);
3797 if (file)
3798 {
3799 struct dep *deps;
3800 struct dep *d;
3801 if (funcname[4] == '\0')
3802 {
3803 deps = file->deps_no_dupes;
3804 if (!deps && file->deps)
3805 deps = file->deps = create_uniqute_deps_chain (file->deps);
3806 }
3807 else
3808 deps = file->deps;
3809
3810 if ( file->double_colon
3811 && ( file->double_colon != file
3812 || file->last != file))
3813 OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3814 funcname, file->name);
3815
3816 if (idx == 0 /* all */)
3817 {
3818 unsigned int total_len = 0;
3819
3820 /* calc the result length. */
3821
3822 for (d = deps; d; d = d->next)
3823 if (!d->ignore_mtime)
3824 {
3825 const char *c = dep_name (d);
3826
3827#ifndef NO_ARCHIVES
3828 if (ar_name (c))
3829 {
3830 c = strchr (c, '(') + 1;
3831 total_len += strlen (c);
3832 }
3833 else
3834#elif defined (CONFIG_WITH_STRCACHE2)
3835 total_len += strcache2_get_len (&file_strcache, c) + 1;
3836#else
3837 total_len += strlen (c) + 1;
3838#endif
3839 }
3840
3841 if (total_len)
3842 {
3843 /* prepare the variable buffer dude wrt to the output size and
3844 pass along the strings. */
3845
3846 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
3847
3848 for (d = deps; d; d = d->next)
3849 if (!d->ignore_mtime)
3850 {
3851 unsigned int len;
3852 const char *c = dep_name (d);
3853
3854#ifndef NO_ARCHIVES
3855 if (ar_name (c))
3856 {
3857 c = strchr (c, '(') + 1;
3858 len = strlen (c);
3859 }
3860 else
3861#elif defined (CONFIG_WITH_STRCACHE2)
3862 len = strcache2_get_len (&file_strcache, c) + 1;
3863#else
3864 len = strlen (c) + 1;
3865#endif
3866 o = variable_buffer_output (o, c, len);
3867 o[-1] = FILE_LIST_SEPARATOR;
3868 }
3869
3870 --o; /* nuke the last list separator */
3871 *o = '\0';
3872 }
3873 }
3874 else
3875 {
3876 /* Dependency given by index. */
3877
3878 for (d = deps; d; d = d->next)
3879 if (!d->ignore_mtime)
3880 {
3881 if (--idx == 0) /* 1 based indexing */
3882 {
3883 unsigned int len;
3884 const char *c = dep_name (d);
3885
3886#ifndef NO_ARCHIVES
3887 if (ar_name (c))
3888 {
3889 c = strchr (c, '(') + 1;
3890 len = strlen (c) - 1;
3891 }
3892 else
3893#elif defined (CONFIG_WITH_STRCACHE2)
3894 len = strcache2_get_len (&file_strcache, c);
3895#else
3896 len = strlen (c);
3897#endif
3898 o = variable_buffer_output (o, c, len);
3899 break;
3900 }
3901 }
3902 }
3903 }
3904
3905 return o;
3906}
3907
3908/* Implements $?.
3909
3910 If no second argument is given, or if it's empty, or if it's zero,
3911 all dependencies will be returned. If the second argument is non-zero
3912 the dependency at that position will be returned. If the argument is
3913 negative a fatal error is thrown. */
3914static char *
3915func_deps_newer (char *o, char **argv, const char *funcname)
3916{
3917 unsigned int idx = 0;
3918 struct file *file;
3919
3920 /* Handle the argument if present. */
3921
3922 if (argv[1])
3923 {
3924 char *p = argv[1];
3925 while (ISSPACE (*p))
3926 p++;
3927 if (*p != '\0')
3928 {
3929 char *n;
3930 long l = strtol (p, &n, 0);
3931 while (ISSPACE (*n))
3932 n++;
3933 idx = l;
3934 if (*n != '\0' || l < 0 || (long)idx != l)
3935 OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
3936 }
3937 }
3938
3939 /* Find the file. */
3940
3941 file = lookup_file (argv[0]);
3942 if (file)
3943 {
3944 struct dep *deps = file->deps;
3945 struct dep *d;
3946
3947 if ( file->double_colon
3948 && ( file->double_colon != file
3949 || file->last != file))
3950 OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
3951 funcname, file->name);
3952
3953 if (idx == 0 /* all */)
3954 {
3955 unsigned int total_len = 0;
3956
3957 /* calc the result length. */
3958
3959 for (d = deps; d; d = d->next)
3960 if (!d->ignore_mtime && d->changed)
3961 {
3962 const char *c = dep_name (d);
3963
3964#ifndef NO_ARCHIVES
3965 if (ar_name (c))
3966 {
3967 c = strchr (c, '(') + 1;
3968 total_len += strlen (c);
3969 }
3970 else
3971#elif defined (CONFIG_WITH_STRCACHE2)
3972 total_len += strcache2_get_len (&file_strcache, c) + 1;
3973#else
3974 total_len += strlen (c) + 1;
3975#endif
3976 }
3977
3978 if (total_len)
3979 {
3980 /* prepare the variable buffer dude wrt to the output size and
3981 pass along the strings. */
3982
3983 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
3984
3985 for (d = deps; d; d = d->next)
3986 if (!d->ignore_mtime && d->changed)
3987 {
3988 unsigned int len;
3989 const char *c = dep_name (d);
3990
3991#ifndef NO_ARCHIVES
3992 if (ar_name (c))
3993 {
3994 c = strchr (c, '(') + 1;
3995 len = strlen (c);
3996 }
3997 else
3998#elif defined (CONFIG_WITH_STRCACHE2)
3999 len = strcache2_get_len (&file_strcache, c) + 1;
4000#else
4001 len = strlen (c) + 1;
4002#endif
4003 o = variable_buffer_output (o, c, len);
4004 o[-1] = FILE_LIST_SEPARATOR;
4005 }
4006
4007 --o; /* nuke the last list separator */
4008 *o = '\0';
4009 }
4010 }
4011 else
4012 {
4013 /* Dependency given by index. */
4014
4015 for (d = deps; d; d = d->next)
4016 if (!d->ignore_mtime && d->changed)
4017 {
4018 if (--idx == 0) /* 1 based indexing */
4019 {
4020 unsigned int len;
4021 const char *c = dep_name (d);
4022
4023#ifndef NO_ARCHIVES
4024 if (ar_name (c))
4025 {
4026 c = strchr (c, '(') + 1;
4027 len = strlen (c) - 1;
4028 }
4029 else
4030#elif defined (CONFIG_WITH_STRCACHE2)
4031 len = strcache2_get_len (&file_strcache, c);
4032#else
4033 len = strlen (c);
4034#endif
4035 o = variable_buffer_output (o, c, len);
4036 break;
4037 }
4038 }
4039 }
4040 }
4041
4042 return o;
4043}
4044
4045/* Implements $|, the order only dependency list.
4046
4047 If no second argument is given, or if it's empty, or if it's zero,
4048 all dependencies will be returned. If the second argument is non-zero
4049 the dependency at that position will be returned. If the argument is
4050 negative a fatal error is thrown. */
4051static char *
4052func_deps_order_only (char *o, char **argv, const char *funcname)
4053{
4054 unsigned int idx = 0;
4055 struct file *file;
4056
4057 /* Handle the argument if present. */
4058
4059 if (argv[1])
4060 {
4061 char *p = argv[1];
4062 while (ISSPACE (*p))
4063 p++;
4064 if (*p != '\0')
4065 {
4066 char *n;
4067 long l = strtol (p, &n, 0);
4068 while (ISSPACE (*n))
4069 n++;
4070 idx = l;
4071 if (*n != '\0' || l < 0 || (long)idx != l)
4072 OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
4073 }
4074 }
4075
4076 /* Find the file. */
4077
4078 file = lookup_file (argv[0]);
4079 if (file)
4080 {
4081 struct dep *deps = file->deps;
4082 struct dep *d;
4083
4084 if ( file->double_colon
4085 && ( file->double_colon != file
4086 || file->last != file))
4087 OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
4088 funcname, file->name);
4089
4090 if (idx == 0 /* all */)
4091 {
4092 unsigned int total_len = 0;
4093
4094 /* calc the result length. */
4095
4096 for (d = deps; d; d = d->next)
4097 if (d->ignore_mtime)
4098 {
4099 const char *c = dep_name (d);
4100
4101#ifndef NO_ARCHIVES
4102 if (ar_name (c))
4103 {
4104 c = strchr (c, '(') + 1;
4105 total_len += strlen (c);
4106 }
4107 else
4108#elif defined (CONFIG_WITH_STRCACHE2)
4109 total_len += strcache2_get_len (&file_strcache, c) + 1;
4110#else
4111 total_len += strlen (c) + 1;
4112#endif
4113 }
4114
4115 if (total_len)
4116 {
4117 /* prepare the variable buffer dude wrt to the output size and
4118 pass along the strings. */
4119
4120 o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
4121
4122 for (d = deps; d; d = d->next)
4123 if (d->ignore_mtime)
4124 {
4125 unsigned int len;
4126 const char *c = dep_name (d);
4127
4128#ifndef NO_ARCHIVES
4129 if (ar_name (c))
4130 {
4131 c = strchr (c, '(') + 1;
4132 len = strlen (c);
4133 }
4134 else
4135#elif defined (CONFIG_WITH_STRCACHE2)
4136 len = strcache2_get_len (&file_strcache, c) + 1;
4137#else
4138 len = strlen (c) + 1;
4139#endif
4140 o = variable_buffer_output (o, c, len);
4141 o[-1] = FILE_LIST_SEPARATOR;
4142 }
4143
4144 --o; /* nuke the last list separator */
4145 *o = '\0';
4146 }
4147 }
4148 else
4149 {
4150 /* Dependency given by index. */
4151
4152 for (d = deps; d; d = d->next)
4153 if (d->ignore_mtime)
4154 {
4155 if (--idx == 0) /* 1 based indexing */
4156 {
4157 unsigned int len;
4158 const char *c = dep_name (d);
4159
4160#ifndef NO_ARCHIVES
4161 if (ar_name (c))
4162 {
4163 c = strchr (c, '(') + 1;
4164 len = strlen (c) - 1;
4165 }
4166 else
4167#elif defined (CONFIG_WITH_STRCACHE2)
4168 len = strcache2_get_len (&file_strcache, c);
4169#else
4170 len = strlen (c);
4171#endif
4172 o = variable_buffer_output (o, c, len);
4173 break;
4174 }
4175 }
4176 }
4177 }
4178
4179 return o;
4180}
4181#endif /* CONFIG_WITH_LAZY_DEPS_VARS */
4182
4183
4184
4185#ifdef CONFIG_WITH_DEFINED
4186/* Similar to ifdef. */
4187static char *
4188func_defined (char *o, char **argv, const char *funcname UNUSED)
4189{
4190 struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
4191 int result = v != NULL && *v->value != '\0';
4192 o = variable_buffer_output (o, result ? "1" : "", result);
4193 return o;
4194}
4195#endif /* CONFIG_WITH_DEFINED*/
4196
4197#ifdef CONFIG_WITH_TOUPPER_TOLOWER
4198static char *
4199func_toupper_tolower (char *o, char **argv, const char *funcname)
4200{
4201 /* Expand the argument. */
4202 const char *p = argv[0];
4203 while (*p)
4204 {
4205 /* convert to temporary buffer */
4206 char tmp[256];
4207 unsigned int i;
4208 if (!strcmp(funcname, "toupper"))
4209 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
4210 tmp[i] = toupper(*p);
4211 else
4212 for (i = 0; i < sizeof(tmp) && *p; i++, p++)
4213 tmp[i] = tolower(*p);
4214 o = variable_buffer_output (o, tmp, i);
4215 }
4216
4217 return o;
4218}
4219#endif /* CONFIG_WITH_TOUPPER_TOLOWER */
4220
4221#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
4222
4223/* Strip leading spaces and other things off a command. */
4224static const char *
4225comp_cmds_strip_leading (const char *s, const char *e)
4226{
4227 while (s < e)
4228 {
4229 const char ch = *s;
4230 if (!ISBLANK (ch)
4231 && ch != '@'
4232#ifdef CONFIG_WITH_COMMANDS_FUNC
4233 && ch != '%'
4234#endif
4235 && ch != '+'
4236 && ch != '-')
4237 break;
4238 s++;
4239 }
4240 return s;
4241}
4242
4243/* Worker for func_comp_vars() which is called if the comparision failed.
4244 It will do the slow command by command comparision of the commands
4245 when there invoked as comp-cmds. */
4246static char *
4247comp_vars_ne (char *o, const char *s1, const char *e1, const char *s2, const char *e2,
4248 char *ne_retval, const char *funcname)
4249{
4250 /* give up at once if not comp-cmds or comp-cmds-ex. */
4251 if (strcmp (funcname, "comp-cmds") != 0
4252 && strcmp (funcname, "comp-cmds-ex") != 0)
4253 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
4254 else
4255 {
4256 const char * const s1_start = s1;
4257 int new_cmd = 1;
4258 int diff;
4259 for (;;)
4260 {
4261 /* if it's a new command, strip leading stuff. */
4262 if (new_cmd)
4263 {
4264 s1 = comp_cmds_strip_leading (s1, e1);
4265 s2 = comp_cmds_strip_leading (s2, e2);
4266 new_cmd = 0;
4267 }
4268 if (s1 >= e1 || s2 >= e2)
4269 break;
4270
4271 /*
4272 * Inner compare loop which compares one line.
4273 * FIXME: parse quoting!
4274 */
4275 for (;;)
4276 {
4277 const char ch1 = *s1;
4278 const char ch2 = *s2;
4279 diff = ch1 - ch2;
4280 if (diff)
4281 break;
4282 if (ch1 == '\n')
4283 break;
4284 assert (ch1 != '\r');
4285
4286 /* next */
4287 s1++;
4288 s2++;
4289 if (s1 >= e1 || s2 >= e2)
4290 break;
4291 }
4292
4293 /*
4294 * If we exited because of a difference try to end-of-command
4295 * comparision, e.g. ignore trailing spaces.
4296 */
4297 if (diff)
4298 {
4299 /* strip */
4300 while (s1 < e1 && ISBLANK (*s1))
4301 s1++;
4302 while (s2 < e2 && ISBLANK (*s2))
4303 s2++;
4304 if (s1 >= e1 || s2 >= e2)
4305 break;
4306
4307 /* compare again and check that it's a newline. */
4308 if (*s2 != '\n' || *s1 != '\n')
4309 break;
4310 }
4311 /* Break out if we exited because of EOS. */
4312 else if (s1 >= e1 || s2 >= e2)
4313 break;
4314
4315 /*
4316 * Detect the end of command lines.
4317 */
4318 if (*s1 == '\n')
4319 new_cmd = s1 == s1_start || s1[-1] != '\\';
4320 s1++;
4321 s2++;
4322 }
4323
4324 /*
4325 * Ignore trailing empty lines.
4326 */
4327 if (s1 < e1 || s2 < e2)
4328 {
4329 while (s1 < e1 && (ISBLANK (*s1) || *s1 == '\n'))
4330 if (*s1++ == '\n')
4331 s1 = comp_cmds_strip_leading (s1, e1);
4332 while (s2 < e2 && (ISBLANK (*s2) || *s2 == '\n'))
4333 if (*s2++ == '\n')
4334 s2 = comp_cmds_strip_leading (s2, e2);
4335 }
4336
4337 /* emit the result. */
4338 if (s1 == e1 && s2 == e2)
4339 o = variable_buffer_output (o, "", 1) - 1; /** @todo check why this was necessary back the... */
4340 else
4341 o = variable_buffer_output (o, ne_retval, strlen (ne_retval));
4342 }
4343 return o;
4344}
4345
4346/*
4347 $(comp-vars var1,var2,not-equal-return)
4348 or
4349 $(comp-cmds cmd-var1,cmd-var2,not-equal-return)
4350
4351 Compares the two variables (that's given by name to avoid unnecessary
4352 expanding) and return the string in the third argument if not equal.
4353 If equal, nothing is returned.
4354
4355 comp-vars will to an exact comparision only stripping leading and
4356 trailing spaces.
4357
4358 comp-cmds will compare command by command, ignoring not only leading
4359 and trailing spaces on each line but also leading one leading '@',
4360 '-', '+' and '%'
4361*/
4362static char *
4363func_comp_vars (char *o, char **argv, const char *funcname)
4364{
4365 const char *s1, *e1, *x1, *s2, *e2, *x2;
4366 char *a1 = NULL, *a2 = NULL;
4367 size_t l, l1, l2;
4368 struct variable *var1 = lookup_variable (argv[0], strlen (argv[0]));
4369 struct variable *var2 = lookup_variable (argv[1], strlen (argv[1]));
4370
4371 /* the simple cases */
4372 if (var1 == var2)
4373 return variable_buffer_output (o, "", 0); /* eq */
4374 if (!var1 || !var2)
4375 return variable_buffer_output (o, argv[2], strlen(argv[2]));
4376 if (var1->value == var2->value)
4377 return variable_buffer_output (o, "", 0); /* eq */
4378 if ( (!var1->recursive || IS_VARIABLE_RECURSIVE_WITHOUT_DOLLAR (var1))
4379 && (!var2->recursive || IS_VARIABLE_RECURSIVE_WITHOUT_DOLLAR (var2)) )
4380 {
4381 if ( var1->value_length == var2->value_length
4382 && !memcmp (var1->value, var2->value, var1->value_length))
4383 return variable_buffer_output (o, "", 0); /* eq */
4384
4385 /* ignore trailing and leading blanks */
4386 s1 = var1->value;
4387 e1 = s1 + var1->value_length;
4388 while (ISBLANK (*s1))
4389 s1++;
4390 while (e1 > s1 && ISBLANK (e1[-1]))
4391 e1--;
4392
4393 s2 = var2->value;
4394 e2 = s2 + var2->value_length;
4395 while (ISBLANK (*s2))
4396 s2++;
4397 while (e2 > s2 && ISBLANK (e2[-1]))
4398 e2--;
4399
4400 if (e1 - s1 != e2 - s2)
4401 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4402 if (!memcmp (s1, s2, e1 - s1))
4403 return variable_buffer_output (o, "", 0); /* eq */
4404 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4405 }
4406
4407 /* ignore trailing and leading blanks */
4408 s1 = var1->value;
4409 e1 = s1 + var1->value_length;
4410 while (ISBLANK (*s1))
4411 s1++;
4412 while (e1 > s1 && ISBLANK (e1[-1]))
4413 e1--;
4414
4415 s2 = var2->value;
4416 e2 = s2 + var2->value_length;
4417 while (ISBLANK (*s2))
4418 s2++;
4419 while (e2 > s2 && ISBLANK (e2[-1]))
4420 e2--;
4421
4422 /* both empty after stripping? */
4423 if (s1 == e1 && s2 == e2)
4424 return variable_buffer_output (o, "", 0); /* eq */
4425
4426 /* optimist. */
4427 if ( e1 - s1 == e2 - s2
4428 && !memcmp(s1, s2, e1 - s1))
4429 return variable_buffer_output (o, "", 0); /* eq */
4430
4431 /* compare up to the first '$' or the end. */
4432 x1 = var1->recursive ? memchr (s1, '$', e1 - s1) : NULL;
4433 x2 = var2->recursive ? memchr (s2, '$', e2 - s2) : NULL;
4434 if (!x1 && !x2)
4435 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4436
4437 l1 = x1 ? x1 - s1 : e1 - s1;
4438 l2 = x2 ? x2 - s2 : e2 - s2;
4439 l = l1 <= l2 ? l1 : l2;
4440 if (l && memcmp (s1, s2, l))
4441 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4442
4443 /* one or both buffers now require expanding. */
4444 if (!x1)
4445 s1 += l;
4446 else
4447 {
4448 s1 = a1 = allocated_variable_expand ((char *)s1 + l);
4449 if (!l)
4450 while (ISBLANK (*s1))
4451 s1++;
4452 e1 = strchr (s1, '\0');
4453 while (e1 > s1 && ISBLANK (e1[-1]))
4454 e1--;
4455 }
4456
4457 if (!x2)
4458 s2 += l;
4459 else
4460 {
4461 s2 = a2 = allocated_variable_expand ((char *)s2 + l);
4462 if (!l)
4463 while (ISBLANK (*s2))
4464 s2++;
4465 e2 = strchr (s2, '\0');
4466 while (e2 > s2 && ISBLANK (e2[-1]))
4467 e2--;
4468 }
4469
4470 /* the final compare */
4471 if ( e1 - s1 != e2 - s2
4472 || memcmp (s1, s2, e1 - s1))
4473 o = comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4474 else
4475 o = variable_buffer_output (o, "", 1) - 1; /* eq */ /** @todo check why this was necessary back the... */
4476 if (a1)
4477 free (a1);
4478 if (a2)
4479 free (a2);
4480 return o;
4481}
4482
4483/*
4484 $(comp-cmds-ex cmds1,cmds2,not-equal-return)
4485
4486 Compares the two strings and return the string in the third argument
4487 if not equal. If equal, nothing is returned.
4488
4489 The comparision will be performed command by command, ignoring not
4490 only leading and trailing spaces on each line but also leading one
4491 leading '@', '-', '+' and '%'.
4492*/
4493static char *
4494func_comp_cmds_ex (char *o, char **argv, const char *funcname)
4495{
4496 const char *s1, *e1, *s2, *e2;
4497 size_t l1, l2;
4498
4499 /* the simple cases */
4500 s1 = argv[0];
4501 s2 = argv[1];
4502 if (s1 == s2)
4503 return variable_buffer_output (o, "", 0); /* eq */
4504 l1 = strlen (argv[0]);
4505 l2 = strlen (argv[1]);
4506
4507 if ( l1 == l2
4508 && !memcmp (s1, s2, l1))
4509 return variable_buffer_output (o, "", 0); /* eq */
4510
4511 /* ignore trailing and leading blanks */
4512 e1 = s1 + l1;
4513 s1 = comp_cmds_strip_leading (s1, e1);
4514
4515 e2 = s2 + l2;
4516 s2 = comp_cmds_strip_leading (s2, e2);
4517
4518 if (e1 - s1 != e2 - s2)
4519 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4520 if (!memcmp (s1, s2, e1 - s1))
4521 return variable_buffer_output (o, "", 0); /* eq */
4522 return comp_vars_ne (o, s1, e1, s2, e2, argv[2], funcname);
4523}
4524#endif
4525
4526#ifdef CONFIG_WITH_DATE
4527# if defined (_MSC_VER) /* FIXME: !defined (HAVE_STRPTIME) */
4528char *strptime(const char *s, const char *format, struct tm *tm)
4529{
4530 return (char *)"strptime is not implemented";
4531}
4532# endif
4533/* Check if the string is all blanks or not. */
4534static int
4535all_blanks (const char *s)
4536{
4537 if (!s)
4538 return 1;
4539 while (ISSPACE (*s))
4540 s++;
4541 return *s == '\0';
4542}
4543
4544/* The first argument is the strftime format string, a iso
4545 timestamp is the default if nothing is given.
4546
4547 The second argument is a time value if given. The format
4548 is either the format from the first argument or given as
4549 an additional third argument. */
4550static char *
4551func_date (char *o, char **argv, const char *funcname)
4552{
4553 char *p;
4554 char *buf;
4555 size_t buf_size;
4556 struct tm t;
4557 const char *format;
4558
4559 /* determin the format - use a single word as the default. */
4560 format = !strcmp (funcname, "date-utc")
4561 ? "%Y-%m-%dT%H:%M:%SZ"
4562 : "%Y-%m-%dT%H:%M:%S";
4563 if (!all_blanks (argv[0]))
4564 format = argv[0];
4565
4566 /* get the time. */
4567 memset (&t, 0, sizeof(t));
4568 if (argv[0] && !all_blanks (argv[1]))
4569 {
4570 const char *input_format = !all_blanks (argv[2]) ? argv[2] : format;
4571 p = strptime (argv[1], input_format, &t);
4572 if (!p || *p != '\0')
4573 {
4574 OSSSS (error, NILF, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname,
4575 argv[1], input_format, p ? p : "<null>");
4576 return variable_buffer_output (o, "", 0);
4577 }
4578 }
4579 else
4580 {
4581 time_t tval;
4582 time (&tval);
4583 if (!strcmp (funcname, "date-utc"))
4584 t = *gmtime (&tval);
4585 else
4586 t = *localtime (&tval);
4587 }
4588
4589 /* format it. note that zero isn't necessarily an error, so we'll
4590 have to keep shut about failures. */
4591 buf_size = 64;
4592 buf = xmalloc (buf_size);
4593 while (strftime (buf, buf_size, format, &t) == 0)
4594 {
4595 if (buf_size >= 4096)
4596 {
4597 *buf = '\0';
4598 break;
4599 }
4600 buf = xrealloc (buf, buf_size <<= 1);
4601 }
4602 o = variable_buffer_output (o, buf, strlen (buf));
4603 free (buf);
4604 return o;
4605}
4606#endif
4607
4608#ifdef CONFIG_WITH_FILE_SIZE
4609/* Prints the size of the specified file. Only one file is
4610 permitted, notthing is stripped. -1 is returned if stat
4611 fails. */
4612static char *
4613func_file_size (char *o, char **argv, const char *funcname UNUSED)
4614{
4615 struct stat st;
4616 if (stat (argv[0], &st))
4617 return variable_buffer_output (o, "-1", 2);
4618 return math_int_to_variable_buffer (o, st.st_size);
4619}
4620#endif
4621
4622#ifdef CONFIG_WITH_WHICH
4623/* Checks if the specified file exists an is executable.
4624 On systems employing executable extensions, the name may
4625 be modified to include the extension. */
4626static int func_which_test_x (char *file)
4627{
4628 struct stat st;
4629# if defined(WINDOWS32) || defined(__OS2__)
4630 char *ext;
4631 char *slash;
4632
4633 /* fix slashes first. */
4634 slash = file;
4635 while ((slash = strchr (slash, '\\')) != NULL)
4636 *slash++ = '/';
4637
4638 /* straight */
4639 if (stat (file, &st) == 0
4640 && S_ISREG (st.st_mode))
4641 return 1;
4642
4643 /* don't try add an extension if there already is one */
4644 ext = strchr (file, '\0');
4645 if (ext - file >= 4
4646 && ( !stricmp (ext - 4, ".exe")
4647 || !stricmp (ext - 4, ".cmd")
4648 || !stricmp (ext - 4, ".bat")
4649 || !stricmp (ext - 4, ".com")))
4650 return 0;
4651
4652 /* try the extensions. */
4653 strcpy (ext, ".exe");
4654 if (stat (file, &st) == 0
4655 && S_ISREG (st.st_mode))
4656 return 1;
4657
4658 strcpy (ext, ".cmd");
4659 if (stat (file, &st) == 0
4660 && S_ISREG (st.st_mode))
4661 return 1;
4662
4663 strcpy (ext, ".bat");
4664 if (stat (file, &st) == 0
4665 && S_ISREG (st.st_mode))
4666 return 1;
4667
4668 strcpy (ext, ".com");
4669 if (stat (file, &st) == 0
4670 && S_ISREG (st.st_mode))
4671 return 1;
4672
4673 return 0;
4674
4675# else
4676
4677 return access (file, X_OK) == 0
4678 && stat (file, &st) == 0
4679 && S_ISREG (st.st_mode);
4680# endif
4681}
4682
4683/* Searches for the specified programs in the PATH and print
4684 their full location if found. Prints nothing if not found. */
4685static char *
4686func_which (char *o, char **argv, const char *funcname UNUSED)
4687{
4688 const char *path;
4689 struct variable *path_var;
4690 unsigned i;
4691 int first = 1;
4692 PATH_VAR (buf);
4693
4694 path_var = lookup_variable ("PATH", 4);
4695 if (path_var)
4696 path = path_var->value;
4697 else
4698 path = ".";
4699
4700 /* iterate input */
4701 for (i = 0; argv[i]; i++)
4702 {
4703 unsigned int len;
4704 const char *iterator = argv[i];
4705 char *cur;
4706
4707 while ((cur = find_next_token (&iterator, &len)))
4708 {
4709 /* if there is a separator, don't walk the path. */
4710 if (memchr (cur, '/', len)
4711#ifdef HAVE_DOS_PATHS
4712 || memchr (cur, '\\', len)
4713 || memchr (cur, ':', len)
4714#endif
4715 )
4716 {
4717 if (len + 1 + 4 < GET_PATH_MAX) /* +4 for .exe */
4718 {
4719 memcpy (buf, cur, len);
4720 buf[len] = '\0';
4721 if (func_which_test_x (buf))
4722 o = variable_buffer_output (o, buf, strlen (buf));
4723 }
4724 }
4725 else
4726 {
4727 const char *comp = path;
4728 for (;;)
4729 {
4730 const char *src = comp;
4731 const char *end = strchr (comp, PATH_SEPARATOR_CHAR);
4732 size_t src_len = end ? (size_t)(end - comp) : strlen (comp);
4733 if (!src_len)
4734 {
4735 src_len = 1;
4736 src = ".";
4737 }
4738 if (len + src_len + 2 + 4 < GET_PATH_MAX) /* +4 for .exe */
4739 {
4740 memcpy (buf, src, src_len);
4741 buf [src_len] = '/';
4742 memcpy (&buf[src_len + 1], cur, len);
4743 buf[src_len + 1 + len] = '\0';
4744
4745 if (func_which_test_x (buf))
4746 {
4747 if (!first)
4748 o = variable_buffer_output (o, " ", 1);
4749 o = variable_buffer_output (o, buf, strlen (buf));
4750 first = 0;
4751 break;
4752 }
4753 }
4754
4755 /* next */
4756 if (!end)
4757 break;
4758 comp = end + 1;
4759 }
4760 }
4761 }
4762 }
4763
4764 return variable_buffer_output (o, "", 0);
4765}
4766#endif /* CONFIG_WITH_WHICH */
4767
4768#ifdef CONFIG_WITH_IF_CONDITIONALS
4769
4770/* Evaluates the expression given in the argument using the
4771 same evaluator as for the new 'if' statements, except now
4772 we don't force the result into a boolean like for 'if' and
4773 '$(if-expr ,,)'. */
4774static char *
4775func_expr (char *o, char **argv, const char *funcname UNUSED)
4776{
4777 o = expr_eval_to_string (o, argv[0]);
4778 return o;
4779}
4780
4781/* Same as '$(if ,,)' except the first argument is evaluated
4782 using the same evaluator as for the new 'if' statements. */
4783static char *
4784func_if_expr (char *o, char **argv, const char *funcname UNUSED)
4785{
4786 int rc;
4787 char *to_expand;
4788
4789 /* Evaluate the condition in argv[0] and expand the 2nd or
4790 3rd (optional) argument according to the result. */
4791 rc = expr_eval_if_conditionals (argv[0], NULL);
4792 to_expand = rc == 0 ? argv[1] : argv[2];
4793 if (to_expand && *to_expand)
4794 variable_expand_string_2 (o, to_expand, -1, &o);
4795
4796 return o;
4797}
4798
4799/*
4800 $(select when1-cond, when1-body[,whenN-cond, whenN-body]).
4801 */
4802static char *
4803func_select (char *o, char **argv, const char *funcname UNUSED)
4804{
4805 int i;
4806
4807 /* Test WHEN-CONDs until one matches. The check for 'otherwise[:]'
4808 and 'default[:]' make this a bit more fun... */
4809
4810 for (i = 0; argv[i] != NULL; i += 2)
4811 {
4812 const char *cond = argv[i];
4813 int is_otherwise = 0;
4814
4815 if (argv[i + 1] == NULL)
4816 O (fatal, NILF, _("$(select ): not an even argument count\n"));
4817
4818 while (ISSPACE (*cond))
4819 cond++;
4820 if ( (*cond == 'o' && strncmp (cond, "otherwise", 9) == 0)
4821 || (*cond == 'd' && strncmp (cond, "default", 7) == 0))
4822 {
4823 const char *end = cond + (*cond == 'o' ? 9 : 7);
4824 while (ISSPACE (*end))
4825 end++;
4826 if (*end == ':')
4827 do end++;
4828 while (ISSPACE (*end));
4829 is_otherwise = *end == '\0';
4830 }
4831
4832 if ( is_otherwise
4833 || expr_eval_if_conditionals (cond, NULL) == 0 /* true */)
4834 {
4835 variable_expand_string_2 (o, argv[i + 1], -1, &o);
4836 break;
4837 }
4838 }
4839
4840 return o;
4841}
4842
4843#endif /* CONFIG_WITH_IF_CONDITIONALS */
4844
4845#ifdef CONFIG_WITH_SET_CONDITIONALS
4846static char *
4847func_set_intersects (char *o, char **argv, const char *funcname UNUSED)
4848{
4849 const char *s1_cur;
4850 unsigned int s1_len;
4851 const char *s1_iterator = argv[0];
4852
4853 while ((s1_cur = find_next_token (&s1_iterator, &s1_len)) != 0)
4854 {
4855 const char *s2_cur;
4856 unsigned int s2_len;
4857 const char *s2_iterator = argv[1];
4858 while ((s2_cur = find_next_token (&s2_iterator, &s2_len)) != 0)
4859 if (s2_len == s1_len
4860 && strneq (s2_cur, s1_cur, s1_len) )
4861 return variable_buffer_output (o, "1", 1); /* found intersection */
4862 }
4863
4864 return o; /* no intersection */
4865}
4866#endif /* CONFIG_WITH_SET_CONDITIONALS */
4867
4868#ifdef CONFIG_WITH_STACK
4869
4870/* Push an item (string without spaces). */
4871static char *
4872func_stack_push (char *o, char **argv, const char *funcname UNUSED)
4873{
4874 do_variable_definition(NILF, argv[0], argv[1], o_file, f_append, 0 /* !target_var */);
4875 return o;
4876}
4877
4878/* Pops an item off the stack / get the top stack element.
4879 (This is what's tricky to do in pure GNU make syntax.) */
4880static char *
4881func_stack_pop_top (char *o, char **argv, const char *funcname)
4882{
4883 struct variable *stack_var;
4884 const char *stack = argv[0];
4885
4886 stack_var = lookup_variable (stack, strlen (stack) );
4887 if (stack_var)
4888 {
4889 unsigned int len;
4890 const char *iterator = stack_var->value;
4891 char *lastitem = NULL;
4892 char *cur;
4893
4894 while ((cur = find_next_token (&iterator, &len)))
4895 lastitem = cur;
4896
4897 if (lastitem != NULL)
4898 {
4899 if (strcmp (funcname, "stack-popv") != 0)
4900 o = variable_buffer_output (o, lastitem, len);
4901 if (strcmp (funcname, "stack-top") != 0)
4902 {
4903 *lastitem = '\0';
4904 while (lastitem > stack_var->value && ISSPACE (lastitem[-1]))
4905 *--lastitem = '\0';
4906#ifdef CONFIG_WITH_VALUE_LENGTH
4907 stack_var->value_length = lastitem - stack_var->value;
4908#endif
4909 VARIABLE_CHANGED (stack_var);
4910 }
4911 }
4912 }
4913 return o;
4914}
4915#endif /* CONFIG_WITH_STACK */
4916
4917#if defined (CONFIG_WITH_MATH) || defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_FILE_SIZE)
4918/* outputs the number (as a string) into the variable buffer. */
4919static char *
4920math_int_to_variable_buffer (char *o, math_int num)
4921{
4922 static const char xdigits[17] = "0123456789abcdef";
4923 int negative;
4924 char strbuf[24]; /* 16 hex + 2 prefix + sign + term => 20
4925 or 20 dec + sign + term => 22 */
4926 char *str = &strbuf[sizeof (strbuf) - 1];
4927
4928 negative = num < 0;
4929 if (negative)
4930 num = -num;
4931
4932 *str = '\0';
4933
4934 do
4935 {
4936#ifdef HEX_MATH_NUMBERS
4937 *--str = xdigits[num & 0xf];
4938 num >>= 4;
4939#else
4940 *--str = xdigits[num % 10];
4941 num /= 10;
4942#endif
4943 }
4944 while (num);
4945
4946#ifdef HEX_MATH_NUMBERS
4947 *--str = 'x';
4948 *--str = '0';
4949#endif
4950
4951 if (negative)
4952 *--str = '-';
4953
4954 return variable_buffer_output (o, str, &strbuf[sizeof (strbuf) - 1] - str);
4955}
4956#endif /* CONFIG_WITH_MATH || CONFIG_WITH_NANOTS */
4957
4958#ifdef CONFIG_WITH_MATH
4959
4960/* Converts a string to an integer, causes an error if the format is invalid. */
4961static math_int
4962math_int_from_string (const char *str)
4963{
4964 const char *start;
4965 unsigned base = 0;
4966 int negative = 0;
4967 math_int num = 0;
4968
4969 /* strip spaces */
4970 while (ISSPACE (*str))
4971 str++;
4972 if (!*str)
4973 {
4974 O (error, NILF, _("bad number: empty\n"));
4975 return 0;
4976 }
4977 start = str;
4978
4979 /* check for +/- */
4980 while (*str == '+' || *str == '-' || ISSPACE (*str))
4981 if (*str++ == '-')
4982 negative = !negative;
4983
4984 /* check for prefix - we do not accept octal numbers, sorry. */
4985 if (*str == '0' && (str[1] == 'x' || str[1] == 'X'))
4986 {
4987 base = 16;
4988 str += 2;
4989 }
4990 else
4991 {
4992 /* look for a hex digit, if not found treat it as decimal */
4993 const char *p2 = str;
4994 for ( ; *p2; p2++)
4995 if (isxdigit (*p2) && !isdigit (*p2) && isascii (*p2) )
4996 {
4997 base = 16;
4998 break;
4999 }
5000 if (base == 0)
5001 base = 10;
5002 }
5003
5004 /* must have at least one digit! */
5005 if ( !isascii (*str)
5006 || !(base == 16 ? isxdigit (*str) : isdigit (*str)) )
5007 {
5008 OS (error, NILF, _("bad number: '%s'\n"), start);
5009 return 0;
5010 }
5011
5012 /* convert it! */
5013 while (*str && !ISSPACE (*str))
5014 {
5015 int ch = *str++;
5016 if (ch >= '0' && ch <= '9')
5017 ch -= '0';
5018 else if (base == 16 && ch >= 'a' && ch <= 'f')
5019 ch -= 'a' - 10;
5020 else if (base == 16 && ch >= 'A' && ch <= 'F')
5021 ch -= 'A' - 10;
5022 else
5023 {
5024 OSNN (error, NILF, _("bad number: '%s' (base=%u, pos=%lu)\n"), start, base, (unsigned long)(str - start));
5025 return 0;
5026 }
5027 num *= base;
5028 num += ch;
5029 }
5030
5031 /* check trailing spaces. */
5032 while (ISSPACE (*str))
5033 str++;
5034 if (*str)
5035 {
5036 OS (error, NILF, _("bad number: '%s'\n"), start);
5037 return 0;
5038 }
5039
5040 return negative ? -num : num;
5041}
5042
5043/* Add two or more integer numbers. */
5044static char *
5045func_int_add (char *o, char **argv, const char *funcname UNUSED)
5046{
5047 math_int num;
5048 int i;
5049
5050 num = math_int_from_string (argv[0]);
5051 for (i = 1; argv[i]; i++)
5052 num += math_int_from_string (argv[i]);
5053
5054 return math_int_to_variable_buffer (o, num);
5055}
5056
5057/* Subtract two or more integer numbers. */
5058static char *
5059func_int_sub (char *o, char **argv, const char *funcname UNUSED)
5060{
5061 math_int num;
5062 int i;
5063
5064 num = math_int_from_string (argv[0]);
5065 for (i = 1; argv[i]; i++)
5066 num -= math_int_from_string (argv[i]);
5067
5068 return math_int_to_variable_buffer (o, num);
5069}
5070
5071/* Multiply two or more integer numbers. */
5072static char *
5073func_int_mul (char *o, char **argv, const char *funcname UNUSED)
5074{
5075 math_int num;
5076 int i;
5077
5078 num = math_int_from_string (argv[0]);
5079 for (i = 1; argv[i]; i++)
5080 num *= math_int_from_string (argv[i]);
5081
5082 return math_int_to_variable_buffer (o, num);
5083}
5084
5085/* Divide an integer number by one or more divisors. */
5086static char *
5087func_int_div (char *o, char **argv, const char *funcname UNUSED)
5088{
5089 math_int num;
5090 math_int divisor;
5091 int i;
5092
5093 num = math_int_from_string (argv[0]);
5094 for (i = 1; argv[i]; i++)
5095 {
5096 divisor = math_int_from_string (argv[i]);
5097 if (!divisor)
5098 {
5099 OS (error, NILF, _("divide by zero ('%s')\n"), argv[i]);
5100 return math_int_to_variable_buffer (o, 0);
5101 }
5102 num /= divisor;
5103 }
5104
5105 return math_int_to_variable_buffer (o, num);
5106}
5107
5108
5109/* Divide and return the remainder. */
5110static char *
5111func_int_mod (char *o, char **argv, const char *funcname UNUSED)
5112{
5113 math_int num;
5114 math_int divisor;
5115
5116 num = math_int_from_string (argv[0]);
5117 divisor = math_int_from_string (argv[1]);
5118 if (!divisor)
5119 {
5120 OS (error, NILF, _("divide by zero ('%s')\n"), argv[1]);
5121 return math_int_to_variable_buffer (o, 0);
5122 }
5123 num %= divisor;
5124
5125 return math_int_to_variable_buffer (o, num);
5126}
5127
5128/* 2-complement. */
5129static char *
5130func_int_not (char *o, char **argv, const char *funcname UNUSED)
5131{
5132 math_int num;
5133
5134 num = math_int_from_string (argv[0]);
5135 num = ~num;
5136
5137 return math_int_to_variable_buffer (o, num);
5138}
5139
5140/* Bitwise AND (two or more numbers). */
5141static char *
5142func_int_and (char *o, char **argv, const char *funcname UNUSED)
5143{
5144 math_int num;
5145 int i;
5146
5147 num = math_int_from_string (argv[0]);
5148 for (i = 1; argv[i]; i++)
5149 num &= math_int_from_string (argv[i]);
5150
5151 return math_int_to_variable_buffer (o, num);
5152}
5153
5154/* Bitwise OR (two or more numbers). */
5155static char *
5156func_int_or (char *o, char **argv, const char *funcname UNUSED)
5157{
5158 math_int num;
5159 int i;
5160
5161 num = math_int_from_string (argv[0]);
5162 for (i = 1; argv[i]; i++)
5163 num |= math_int_from_string (argv[i]);
5164
5165 return math_int_to_variable_buffer (o, num);
5166}
5167
5168/* Bitwise XOR (two or more numbers). */
5169static char *
5170func_int_xor (char *o, char **argv, const char *funcname UNUSED)
5171{
5172 math_int num;
5173 int i;
5174
5175 num = math_int_from_string (argv[0]);
5176 for (i = 1; argv[i]; i++)
5177 num ^= math_int_from_string (argv[i]);
5178
5179 return math_int_to_variable_buffer (o, num);
5180}
5181
5182/* Compare two integer numbers. Returns make boolean (true="1"; false=""). */
5183static char *
5184func_int_cmp (char *o, char **argv, const char *funcname)
5185{
5186 math_int num1;
5187 math_int num2;
5188 int rc;
5189
5190 num1 = math_int_from_string (argv[0]);
5191 num2 = math_int_from_string (argv[1]);
5192
5193 funcname += sizeof ("int-") - 1;
5194 if (!strcmp (funcname, "eq"))
5195 rc = num1 == num2;
5196 else if (!strcmp (funcname, "ne"))
5197 rc = num1 != num2;
5198 else if (!strcmp (funcname, "gt"))
5199 rc = num1 > num2;
5200 else if (!strcmp (funcname, "ge"))
5201 rc = num1 >= num2;
5202 else if (!strcmp (funcname, "lt"))
5203 rc = num1 < num2;
5204 else /*if (!strcmp (funcname, "le"))*/
5205 rc = num1 <= num2;
5206
5207 return variable_buffer_output (o, rc ? "1" : "", rc);
5208}
5209
5210#endif /* CONFIG_WITH_MATH */
5211
5212#ifdef CONFIG_WITH_NANOTS
5213/* Returns the current timestamp as nano seconds. The time
5214 source is a high res monotone one if the platform provides
5215 this (and we know about it).
5216
5217 Tip. Use this with int-sub to profile makefile reading
5218 and similar. */
5219static char *
5220func_nanots (char *o, char **argv UNUSED, const char *funcname UNUSED)
5221{
5222 return math_int_to_variable_buffer (o, nano_timestamp ());
5223}
5224#endif
5225
5226#ifdef CONFIG_WITH_OS2_LIBPATH
5227/* Sets or gets the OS/2 libpath variables.
5228
5229 The first argument indicates which variable - BEGINLIBPATH,
5230 ENDLIBPATH, LIBPATHSTRICT or LIBPATH.
5231
5232 The second indicates whether this is a get (not present) or
5233 set (present) operation. When present it is the new value for
5234 the variable. */
5235static char *
5236func_os2_libpath (char *o, char **argv, const char *funcname UNUSED)
5237{
5238 char buf[4096];
5239 ULONG fVar;
5240 APIRET rc;
5241
5242 /* translate variable name (first arg) */
5243 if (!strcmp (argv[0], "BEGINLIBPATH"))
5244 fVar = BEGIN_LIBPATH;
5245 else if (!strcmp (argv[0], "ENDLIBPATH"))
5246 fVar = END_LIBPATH;
5247 else if (!strcmp (argv[0], "LIBPATHSTRICT"))
5248 fVar = LIBPATHSTRICT;
5249 else if (!strcmp (argv[0], "LIBPATH"))
5250 fVar = 0;
5251 else
5252 {
5253 OS (error, NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
5254 return variable_buffer_output (o, "", 0);
5255 }
5256
5257 if (!argv[1])
5258 {
5259 /* get the variable value. */
5260 if (fVar != 0)
5261 {
5262 buf[0] = buf[1] = buf[2] = buf[3] = '\0';
5263 rc = DosQueryExtLIBPATH (buf, fVar);
5264 }
5265 else
5266 rc = DosQueryHeaderInfo (NULLHANDLE, 0, buf, sizeof(buf), QHINF_LIBPATH);
5267 if (rc != NO_ERROR)
5268 {
5269 OSN (error, NILF, _("$(libpath): failed to query `%s', rc=%d"), argv[0], rc);
5270 return variable_buffer_output (o, "", 0);
5271 }
5272 o = variable_buffer_output (o, buf, strlen (buf));
5273 }
5274 else
5275 {
5276 /* set the variable value. */
5277 size_t len;
5278 size_t len_max = sizeof (buf) < 2048 ? sizeof (buf) : 2048;
5279 const char *val;
5280 const char *end;
5281
5282 if (fVar == 0)
5283 {
5284 O (error, NILF, _("$(libpath): LIBPATH is read-only"));
5285 return variable_buffer_output (o, "", 0);
5286 }
5287
5288 /* strip leading and trailing spaces and check for max length. */
5289 val = argv[1];
5290 while (ISSPACE (*val))
5291 val++;
5292 end = strchr (val, '\0');
5293 while (end > val && ISSPACE (end[-1]))
5294 end--;
5295
5296 len = end - val;
5297 if (len >= len_max)
5298 {
5299 OSNN (error, NILF, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
5300 argv[0], len, len_max);
5301 return variable_buffer_output (o, "", 0);
5302 }
5303
5304 /* make a stripped copy in low memory and try set it. */
5305 memcpy (buf, val, len);
5306 buf[len] = '\0';
5307 rc = DosSetExtLIBPATH (buf, fVar);
5308 if (rc != NO_ERROR)
5309 {
5310 OSSN (error, (NILF, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv[0], buf, rc);
5311 return variable_buffer_output (o, "", 0);
5312 }
5313
5314 o = variable_buffer_output (o, "", 0);
5315 }
5316 return o;
5317}
5318#endif /* CONFIG_WITH_OS2_LIBPATH */
5319
5320#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5321/* Retrieve make statistics. */
5322static char *
5323func_make_stats (char *o, char **argv, const char *funcname UNUSED)
5324{
5325 char buf[512];
5326 int len;
5327
5328 if (!argv[0] || (!argv[0][0] && !argv[1]))
5329 {
5330# ifdef CONFIG_WITH_MAKE_STATS
5331 len = sprintf (buf, "alloc-cur: %5ld/%3ld %3luMB hash: %5lu %2lu%%",
5332 make_stats_allocations,
5333 make_stats_reallocations,
5334 make_stats_allocated / (1024*1024),
5335 make_stats_ht_lookups,
5336 (make_stats_ht_collisions * 100) / make_stats_ht_lookups);
5337 o = variable_buffer_output (o, buf, len);
5338#endif
5339 }
5340 else
5341 {
5342 /* selective */
5343 int i;
5344 for (i = 0; argv[i]; i++)
5345 {
5346 unsigned long val;
5347 if (i != 0)
5348 o = variable_buffer_output (o, " ", 1);
5349 if (0)
5350 continue;
5351# ifdef CONFIG_WITH_MAKE_STATS
5352 else if (!strcmp(argv[i], "allocations"))
5353 val = make_stats_allocations;
5354 else if (!strcmp(argv[i], "reallocations"))
5355 val = make_stats_reallocations;
5356 else if (!strcmp(argv[i], "allocated"))
5357 val = make_stats_allocated;
5358 else if (!strcmp(argv[i], "ht_lookups"))
5359 val = make_stats_ht_lookups;
5360 else if (!strcmp(argv[i], "ht_collisions"))
5361 val = make_stats_ht_collisions;
5362 else if (!strcmp(argv[i], "ht_collisions_pct"))
5363 val = (make_stats_ht_collisions * 100) / make_stats_ht_lookups;
5364#endif
5365 else
5366 {
5367 o = variable_buffer_output (o, argv[i], strlen (argv[i]));
5368 continue;
5369 }
5370
5371 len = sprintf (buf, "%ld", val);
5372 o = variable_buffer_output (o, buf, len);
5373 }
5374 }
5375
5376 return o;
5377}
5378#endif /* CONFIG_WITH_MAKE_STATS */
5379
5380#ifdef CONFIG_WITH_COMMANDS_FUNC
5381/* Gets all the commands for a target, separated by newlines.
5382
5383 This is useful when creating and checking target dependencies since
5384 it reduces the amount of work and the memory consuption. A new prefix
5385 character '%' has been introduced for skipping certain lines, like
5386 for instance the one calling this function and pushing to a dep file.
5387 Blank lines are also skipped.
5388
5389 The commands function takes exactly one argument, which is the name of
5390 the target which commands should be returned.
5391
5392 The commands-sc is identical to commands except that it uses a ';' to
5393 separate the commands.
5394
5395 The commands-usr is similar to commands except that it takes a 2nd
5396 argument that is used to separate the commands. */
5397char *
5398func_commands (char *o, char **argv, const char *funcname)
5399{
5400 struct file *file;
5401 static int recursive = 0;
5402
5403 if (recursive)
5404 {
5405 OS (error, reading_file, _("$(%s ) was invoked recursivly"), funcname);
5406 return variable_buffer_output (o, "recursive", sizeof ("recursive") - 1);
5407 }
5408 if (*argv[0] == '\0')
5409 {
5410 OS (error, reading_file, _("$(%s ) was invoked with an empty target name"), funcname);
5411 return o;
5412 }
5413 recursive = 1;
5414
5415 file = lookup_file (argv[0]);
5416 if (file && file->cmds)
5417 {
5418 unsigned int i;
5419 int cmd_sep_len;
5420 struct commands *cmds = file->cmds;
5421 const char *cmd_sep;
5422
5423 if (!strcmp (funcname, "commands"))
5424 {
5425 cmd_sep = "\n";
5426 cmd_sep_len = 1;
5427 }
5428 else if (!strcmp (funcname, "commands-sc"))
5429 {
5430 cmd_sep = ";";
5431 cmd_sep_len = 1;
5432 }
5433 else /*if (!strcmp (funcname, "commands-usr"))*/
5434 {
5435 cmd_sep = argv[1];
5436 cmd_sep_len = strlen (cmd_sep);
5437 }
5438
5439 initialize_file_variables (file, 1 /* don't search for pattern vars */);
5440 set_file_variables (file, 1 /* early call */);
5441 chop_commands (cmds);
5442
5443 for (i = 0; i < cmds->ncommand_lines; i++)
5444 {
5445 char *p;
5446 char *in, *out, *ref;
5447
5448 /* Skip it if it has a '%' prefix or is blank. */
5449 if (cmds->lines_flags[i] & COMMAND_GETTER_SKIP_IT)
5450 continue;
5451 p = cmds->command_lines[i];
5452 while (ISBLANK (*p))
5453 p++;
5454 if (*p == '\0')
5455 continue;
5456
5457 /* --- copied from new_job() in job.c --- */
5458
5459 /* Collapse backslash-newline combinations that are inside variable
5460 or function references. These are left alone by the parser so
5461 that they will appear in the echoing of commands (where they look
5462 nice); and collapsed by construct_command_argv when it tokenizes.
5463 But letting them survive inside function invocations loses because
5464 we don't want the functions to see them as part of the text. */
5465
5466 /* IN points to where in the line we are scanning.
5467 OUT points to where in the line we are writing.
5468 When we collapse a backslash-newline combination,
5469 IN gets ahead of OUT. */
5470
5471 in = out = p;
5472 while ((ref = strchr (in, '$')) != 0)
5473 {
5474 ++ref; /* Move past the $. */
5475
5476 if (out != in)
5477 /* Copy the text between the end of the last chunk
5478 we processed (where IN points) and the new chunk
5479 we are about to process (where REF points). */
5480 memmove (out, in, ref - in);
5481
5482 /* Move both pointers past the boring stuff. */
5483 out += ref - in;
5484 in = ref;
5485
5486 if (*ref == '(' || *ref == '{')
5487 {
5488 char openparen = *ref;
5489 char closeparen = openparen == '(' ? ')' : '}';
5490 int count;
5491 char *p2;
5492
5493 *out++ = *in++; /* Copy OPENPAREN. */
5494 /* IN now points past the opening paren or brace.
5495 Count parens or braces until it is matched. */
5496 count = 0;
5497 while (*in != '\0')
5498 {
5499 if (*in == closeparen && --count < 0)
5500 break;
5501 else if (*in == '\\' && in[1] == '\n')
5502 {
5503 /* We have found a backslash-newline inside a
5504 variable or function reference. Eat it and
5505 any following whitespace. */
5506
5507 int quoted = 0;
5508 for (p2 = in - 1; p2 > ref && *p2 == '\\'; --p2)
5509 quoted = !quoted;
5510
5511 if (quoted)
5512 /* There were two or more backslashes, so this is
5513 not really a continuation line. We don't collapse
5514 the quoting backslashes here as is done in
5515 collapse_continuations, because the line will
5516 be collapsed again after expansion. */
5517 *out++ = *in++;
5518 else
5519 {
5520 /* Skip the backslash, newline and
5521 any following whitespace. */
5522 in = next_token (in + 2);
5523
5524 /* Discard any preceding whitespace that has
5525 already been written to the output. */
5526 while (out > ref
5527 && ISBLANK (out[-1]))
5528 --out;
5529
5530 /* Replace it all with a single space. */
5531 *out++ = ' ';
5532 }
5533 }
5534 else
5535 {
5536 if (*in == openparen)
5537 ++count;
5538
5539 *out++ = *in++;
5540 }
5541 }
5542 }
5543 /* Some of these can be amended ($< perhaps), but we're likely to be called while the
5544 dep expansion happens, so it would have to be on a hackish basis. sad... */
5545 else if (*ref == '<' || *ref == '*' || *ref == '%' || *ref == '^' || *ref == '+')
5546 OSN (error, reading_file, _("$(%s ) does not work reliably with $%c in all cases"), funcname, *ref);
5547 }
5548
5549 /* There are no more references in this line to worry about.
5550 Copy the remaining uninteresting text to the output. */
5551 if (out != in)
5552 strcpy (out, in);
5553
5554 /* --- copied from new_job() in job.c --- */
5555
5556 /* Finally, expand the line. */
5557 if (i)
5558 o = variable_buffer_output (o, cmd_sep, cmd_sep_len);
5559 o = variable_expand_for_file_2 (o, cmds->command_lines[i], ~0U, file, NULL);
5560
5561 /* Skip it if it has a '%' prefix or is blank. */
5562 p = o;
5563 while (ISBLANK (*o)
5564 || *o == '@'
5565 || *o == '-'
5566 || *o == '+')
5567 o++;
5568 if (*o != '\0' && *o != '%')
5569 o = strchr (o, '\0');
5570 else if (i)
5571 o = p - cmd_sep_len;
5572 else
5573 o = p;
5574 } /* for each command line */
5575 }
5576 /* else FIXME: bitch about it? */
5577
5578 recursive = 0;
5579 return o;
5580}
5581#endif /* CONFIG_WITH_COMMANDS_FUNC */
5582#ifdef KMK
5583
5584/* Useful when debugging kmk and/or makefiles. */
5585char *
5586func_breakpoint (char *o, char **argv UNUSED, const char *funcname UNUSED)
5587{
5588#ifdef _MSC_VER
5589 __debugbreak();
5590#elif defined(__i386__) || defined(__x86__) || defined(__X86__) || defined(_M_IX86) || defined(__i386) \
5591 || defined(__amd64__) || defined(__x86_64__) || defined(__AMD64__) || defined(_M_X64) || defined(__amd64)
5592# ifdef __sun__
5593 __asm__ __volatile__ ("int $3\n\t");
5594# else
5595 __asm__ __volatile__ ("int3\n\t");
5596# endif
5597#else
5598 char *p = (char *)0;
5599 *p = '\0';
5600#endif
5601 return o;
5602}
5603
5604/* umask | umask -S. */
5605char *
5606func_get_umask (char *o, char **argv UNUSED, const char *funcname UNUSED)
5607{
5608 char sz[80];
5609 int off;
5610 mode_t u;
5611 int symbolic = 0;
5612 const char *psz = argv[0];
5613
5614 if (psz)
5615 {
5616 const char *pszEnd = strchr (psz, '\0');
5617 strip_whitespace (&psz, &pszEnd);
5618
5619 if (pszEnd != psz)
5620 {
5621 if ( STR_N_EQUALS (psz, pszEnd - pszEnd, "S")
5622 || STR_N_EQUALS (psz, pszEnd - pszEnd, "-S")
5623 || STR_N_EQUALS (psz, pszEnd - pszEnd, "symbolic") )
5624 symbolic = 1;
5625 else
5626 OSS (error, reading_file, _("$(%s ) invalid argument `%s'"),
5627 funcname, argv[0]);
5628 }
5629 }
5630
5631 u = umask (002);
5632 umask (u);
5633
5634 if (symbolic)
5635 {
5636 off = 0;
5637 sz[off++] = 'u';
5638 sz[off++] = '=';
5639 if ((u & S_IRUSR) == 0)
5640 sz[off++] = 'r';
5641 if ((u & S_IWUSR) == 0)
5642 sz[off++] = 'w';
5643 if ((u & S_IXUSR) == 0)
5644 sz[off++] = 'x';
5645 sz[off++] = ',';
5646 sz[off++] = 'g';
5647 sz[off++] = '=';
5648 if ((u & S_IRGRP) == 0)
5649 sz[off++] = 'r';
5650 if ((u & S_IWGRP) == 0)
5651 sz[off++] = 'w';
5652 if ((u & S_IXGRP) == 0)
5653 sz[off++] = 'x';
5654 sz[off++] = ',';
5655 sz[off++] = 'o';
5656 sz[off++] = '=';
5657 if ((u & S_IROTH) == 0)
5658 sz[off++] = 'r';
5659 if ((u & S_IWOTH) == 0)
5660 sz[off++] = 'w';
5661 if ((u & S_IXOTH) == 0)
5662 sz[off++] = 'x';
5663 }
5664 else
5665 off = sprintf (sz, "%.4o", u);
5666
5667 return variable_buffer_output (o, sz, off);
5668}
5669
5670
5671/* umask 0002 | umask u=rwx,g=rwx,o=rx. */
5672char *
5673func_set_umask (char *o, char **argv UNUSED, const char *funcname UNUSED)
5674{
5675 mode_t u;
5676 const char *psz;
5677
5678 /* Figure what kind of input this is. */
5679 psz = argv[0];
5680 while (ISBLANK (*psz))
5681 psz++;
5682
5683 if (isdigit ((unsigned char)*psz))
5684 {
5685 u = 0;
5686 while (*psz)
5687 {
5688 u <<= 3;
5689 if (*psz < '0' || *psz >= '8')
5690 {
5691 OSS (error, reading_file, _("$(%s ) illegal number `%s'"), funcname, argv[0]);
5692 break;
5693 }
5694 u += *psz - '0';
5695 psz++;
5696 }
5697
5698 if (argv[1] != NULL)
5699 OS (error, reading_file, _("$(%s ) too many arguments for octal mode"), funcname);
5700 }
5701 else
5702 {
5703 u = umask(0);
5704 umask(u);
5705 OS (error, reading_file, _("$(%s ) symbol mode is not implemented"), funcname);
5706 }
5707
5708 umask(u);
5709
5710 return o;
5711}
5712
5713
5714/* Controls the cache in dir-bird-nt.c. */
5715
5716char *
5717func_dircache_ctl (char *o, char **argv UNUSED, const char *funcname UNUSED)
5718{
5719# ifdef KBUILD_OS_WINDOWS
5720 const char *cmd = argv[0];
5721 while (ISBLANK (*cmd))
5722 cmd++;
5723 if (strcmp (cmd, "invalidate") == 0)
5724 {
5725 if (argv[1] != NULL)
5726 O (error, reading_file, "$(dircache-ctl invalidate) takes no parameters");
5727 dir_cache_invalid_all ();
5728 }
5729 else if (strcmp (cmd, "invalidate-missing") == 0)
5730 {
5731 if (argv[1] != NULL)
5732 O (error, reading_file, "$(dircache-ctl invalidate-missing) takes no parameters");
5733 dir_cache_invalid_missing ();
5734 }
5735 else if (strcmp (cmd, "volatile") == 0)
5736 {
5737 size_t i;
5738 for (i = 1; argv[i] != NULL; i++)
5739 {
5740 const char *dir = argv[i];
5741 while (ISBLANK (*dir))
5742 dir++;
5743 if (*dir)
5744 dir_cache_volatile_dir (dir);
5745 }
5746 }
5747 else if (strcmp (cmd, "deleted") == 0)
5748 {
5749 size_t i;
5750 for (i = 1; argv[i] != NULL; i++)
5751 {
5752 const char *dir = argv[i];
5753 while (ISBLANK (*dir))
5754 dir++;
5755 if (*dir)
5756 dir_cache_deleted_directory (dir);
5757 }
5758 }
5759 else
5760 OS (error, reading_file, "Unknown $(dircache-ctl ) command: '%s'", cmd);
5761# endif
5762 return o;
5763}
5764
5765#endif /* KMK */
5766
5767
5768/* Lookup table for builtin functions.
5769
5770 This doesn't have to be sorted; we use a straight lookup. We might gain
5771 some efficiency by moving most often used functions to the start of the
5772 table.
5773
5774 If MAXIMUM_ARGS is 0, that means there is no maximum and all
5775 comma-separated values are treated as arguments.
5776
5777 EXPAND_ARGS means that all arguments should be expanded before invocation.
5778 Functions that do namespace tricks (foreach) don't automatically expand. */
5779
5780static char *func_call (char *o, char **argv, const char *funcname);
5781
5782#define FT_ENTRY(_name, _min, _max, _exp, _func) \
5783 { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0 }
5784
5785static struct function_table_entry function_table_init[] =
5786{
5787 /* Name MIN MAX EXP? Function */
5788 FT_ENTRY ("abspath", 0, 1, 1, func_abspath),
5789 FT_ENTRY ("addprefix", 2, 2, 1, func_addsuffix_addprefix),
5790 FT_ENTRY ("addsuffix", 2, 2, 1, func_addsuffix_addprefix),
5791 FT_ENTRY ("basename", 0, 1, 1, func_basename_dir),
5792 FT_ENTRY ("dir", 0, 1, 1, func_basename_dir),
5793 FT_ENTRY ("notdir", 0, 1, 1, func_notdir_suffix),
5794#ifdef CONFIG_WITH_ROOT_FUNC
5795 FT_ENTRY ("root", 0, 1, 1, func_root),
5796 FT_ENTRY ("notroot", 0, 1, 1, func_notroot),
5797#endif
5798 FT_ENTRY ("subst", 3, 3, 1, func_subst),
5799 FT_ENTRY ("suffix", 0, 1, 1, func_notdir_suffix),
5800 FT_ENTRY ("filter", 2, 2, 1, func_filter_filterout),
5801 FT_ENTRY ("filter-out", 2, 2, 1, func_filter_filterout),
5802 FT_ENTRY ("findstring", 2, 2, 1, func_findstring),
5803#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
5804 FT_ENTRY ("firstdefined", 0, 2, 1, func_firstdefined),
5805#endif
5806 FT_ENTRY ("firstword", 0, 1, 1, func_firstword),
5807 FT_ENTRY ("flavor", 0, 1, 1, func_flavor),
5808 FT_ENTRY ("join", 2, 2, 1, func_join),
5809#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
5810 FT_ENTRY ("lastdefined", 0, 2, 1, func_lastdefined),
5811#endif
5812 FT_ENTRY ("lastword", 0, 1, 1, func_lastword),
5813 FT_ENTRY ("patsubst", 3, 3, 1, func_patsubst),
5814 FT_ENTRY ("realpath", 0, 1, 1, func_realpath),
5815#ifdef CONFIG_WITH_RSORT
5816 FT_ENTRY ("rsort", 0, 1, 1, func_sort),
5817#endif
5818 FT_ENTRY ("shell", 0, 1, 1, func_shell),
5819 FT_ENTRY ("sort", 0, 1, 1, func_sort),
5820 FT_ENTRY ("strip", 0, 1, 1, func_strip),
5821#ifdef CONFIG_WITH_WHERE_FUNCTION
5822 FT_ENTRY ("where", 0, 1, 1, func_where),
5823#endif
5824 FT_ENTRY ("wildcard", 0, 1, 1, func_wildcard),
5825 FT_ENTRY ("word", 2, 2, 1, func_word),
5826 FT_ENTRY ("wordlist", 3, 3, 1, func_wordlist),
5827 FT_ENTRY ("words", 0, 1, 1, func_words),
5828 FT_ENTRY ("origin", 0, 1, 1, func_origin),
5829 FT_ENTRY ("foreach", 3, 3, 0, func_foreach),
5830#ifdef CONFIG_WITH_LOOP_FUNCTIONS
5831 FT_ENTRY ("for", 4, 4, 0, func_for),
5832 FT_ENTRY ("while", 2, 2, 0, func_while),
5833#endif
5834 FT_ENTRY ("call", 1, 0, 1, func_call),
5835 FT_ENTRY ("info", 0, 1, 1, func_error),
5836 FT_ENTRY ("error", 0, 1, 1, func_error),
5837 FT_ENTRY ("warning", 0, 1, 1, func_error),
5838 FT_ENTRY ("if", 2, 3, 0, func_if),
5839 FT_ENTRY ("or", 1, 0, 0, func_or),
5840 FT_ENTRY ("and", 1, 0, 0, func_and),
5841 FT_ENTRY ("value", 0, 1, 1, func_value),
5842#ifdef EXPERIMENTAL
5843 FT_ENTRY ("eq", 2, 2, 1, func_eq),
5844 FT_ENTRY ("not", 0, 1, 1, func_not),
5845#endif
5846 FT_ENTRY ("eval", 0, 1, 1, func_eval),
5847#ifdef CONFIG_WITH_EVALPLUS
5848 FT_ENTRY ("evalctx", 0, 1, 1, func_evalctx),
5849 FT_ENTRY ("evalval", 1, 1, 1, func_evalval),
5850 FT_ENTRY ("evalvalctx", 1, 1, 1, func_evalval),
5851 FT_ENTRY ("evalcall", 1, 0, 1, func_call),
5852 FT_ENTRY ("evalcall2", 1, 0, 1, func_call),
5853 FT_ENTRY ("eval-opt-var", 1, 0, 1, func_eval_optimize_variable),
5854#endif
5855 FT_ENTRY ("file", 1, 2, 1, func_file),
5856#ifdef CONFIG_WITH_STRING_FUNCTIONS
5857 FT_ENTRY ("length", 1, 1, 1, func_length),
5858 FT_ENTRY ("length-var", 1, 1, 1, func_length_var),
5859 FT_ENTRY ("insert", 2, 5, 1, func_insert),
5860 FT_ENTRY ("pos", 2, 3, 1, func_pos),
5861 FT_ENTRY ("lastpos", 2, 3, 1, func_pos),
5862 FT_ENTRY ("substr", 2, 4, 1, func_substr),
5863 FT_ENTRY ("translate", 2, 4, 1, func_translate),
5864#endif
5865#ifdef CONFIG_WITH_PRINTF
5866 FT_ENTRY ("printf", 1, 0, 1, kmk_builtin_func_printf),
5867#endif
5868#ifdef CONFIG_WITH_LAZY_DEPS_VARS
5869 FT_ENTRY ("deps", 1, 2, 1, func_deps),
5870 FT_ENTRY ("deps-all", 1, 2, 1, func_deps),
5871 FT_ENTRY ("deps-newer", 1, 2, 1, func_deps_newer),
5872 FT_ENTRY ("deps-oo", 1, 2, 1, func_deps_order_only),
5873#endif
5874#ifdef CONFIG_WITH_DEFINED
5875 FT_ENTRY ("defined", 1, 1, 1, func_defined),
5876#endif
5877#ifdef CONFIG_WITH_TOUPPER_TOLOWER
5878 FT_ENTRY ("toupper", 0, 1, 1, func_toupper_tolower),
5879 FT_ENTRY ("tolower", 0, 1, 1, func_toupper_tolower),
5880#endif
5881#ifdef CONFIG_WITH_ABSPATHEX
5882 FT_ENTRY ("abspathex", 0, 2, 1, func_abspathex),
5883#endif
5884#ifdef CONFIG_WITH_XARGS
5885 FT_ENTRY ("xargs", 2, 0, 1, func_xargs),
5886#endif
5887#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
5888 FT_ENTRY ("comp-vars", 3, 3, 1, func_comp_vars),
5889 FT_ENTRY ("comp-cmds", 3, 3, 1, func_comp_vars),
5890 FT_ENTRY ("comp-cmds-ex", 3, 3, 1, func_comp_cmds_ex),
5891#endif
5892#ifdef CONFIG_WITH_DATE
5893 FT_ENTRY ("date", 0, 1, 1, func_date),
5894 FT_ENTRY ("date-utc", 0, 3, 1, func_date),
5895#endif
5896#ifdef CONFIG_WITH_FILE_SIZE
5897 FT_ENTRY ("file-size", 1, 1, 1, func_file_size),
5898#endif
5899#ifdef CONFIG_WITH_WHICH
5900 FT_ENTRY ("which", 0, 0, 1, func_which),
5901#endif
5902#ifdef CONFIG_WITH_IF_CONDITIONALS
5903 FT_ENTRY ("expr", 1, 1, 0, func_expr),
5904 FT_ENTRY ("if-expr", 2, 3, 0, func_if_expr),
5905 FT_ENTRY ("select", 2, 0, 0, func_select),
5906#endif
5907#ifdef CONFIG_WITH_SET_CONDITIONALS
5908 FT_ENTRY ("intersects", 2, 2, 1, func_set_intersects),
5909#endif
5910#ifdef CONFIG_WITH_STACK
5911 FT_ENTRY ("stack-push", 2, 2, 1, func_stack_push),
5912 FT_ENTRY ("stack-pop", 1, 1, 1, func_stack_pop_top),
5913 FT_ENTRY ("stack-popv", 1, 1, 1, func_stack_pop_top),
5914 FT_ENTRY ("stack-top", 1, 1, 1, func_stack_pop_top),
5915#endif
5916#ifdef CONFIG_WITH_MATH
5917 FT_ENTRY ("int-add", 2, 0, 1, func_int_add),
5918 FT_ENTRY ("int-sub", 2, 0, 1, func_int_sub),
5919 FT_ENTRY ("int-mul", 2, 0, 1, func_int_mul),
5920 FT_ENTRY ("int-div", 2, 0, 1, func_int_div),
5921 FT_ENTRY ("int-mod", 2, 2, 1, func_int_mod),
5922 FT_ENTRY ("int-not", 1, 1, 1, func_int_not),
5923 FT_ENTRY ("int-and", 2, 0, 1, func_int_and),
5924 FT_ENTRY ("int-or", 2, 0, 1, func_int_or),
5925 FT_ENTRY ("int-xor", 2, 0, 1, func_int_xor),
5926 FT_ENTRY ("int-eq", 2, 2, 1, func_int_cmp),
5927 FT_ENTRY ("int-ne", 2, 2, 1, func_int_cmp),
5928 FT_ENTRY ("int-gt", 2, 2, 1, func_int_cmp),
5929 FT_ENTRY ("int-ge", 2, 2, 1, func_int_cmp),
5930 FT_ENTRY ("int-lt", 2, 2, 1, func_int_cmp),
5931 FT_ENTRY ("int-le", 2, 2, 1, func_int_cmp),
5932#endif
5933#ifdef CONFIG_WITH_NANOTS
5934 FT_ENTRY ("nanots", 0, 0, 0, func_nanots),
5935#endif
5936#ifdef CONFIG_WITH_OS2_LIBPATH
5937 FT_ENTRY ("libpath", 1, 2, 1, func_os2_libpath),
5938#endif
5939#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
5940 FT_ENTRY ("make-stats", 0, 0, 0, func_make_stats),
5941#endif
5942#ifdef CONFIG_WITH_COMMANDS_FUNC
5943 FT_ENTRY ("commands", 1, 1, 1, func_commands),
5944 FT_ENTRY ("commands-sc", 1, 1, 1, func_commands),
5945 FT_ENTRY ("commands-usr", 2, 2, 1, func_commands),
5946#endif
5947#ifdef KMK_HELPERS
5948 FT_ENTRY ("kb-src-tool", 1, 1, 0, func_kbuild_source_tool),
5949 FT_ENTRY ("kb-obj-base", 1, 1, 0, func_kbuild_object_base),
5950 FT_ENTRY ("kb-obj-suff", 1, 1, 0, func_kbuild_object_suffix),
5951 FT_ENTRY ("kb-src-prop", 3, 4, 0, func_kbuild_source_prop),
5952 FT_ENTRY ("kb-src-one", 0, 1, 0, func_kbuild_source_one),
5953 FT_ENTRY ("kb-exp-tmpl", 6, 6, 1, func_kbuild_expand_template),
5954#endif
5955#ifdef KMK
5956 FT_ENTRY ("dircache-ctl", 1, 0, 1, func_dircache_ctl),
5957 FT_ENTRY ("breakpoint", 0, 0, 0, func_breakpoint),
5958 FT_ENTRY ("set-umask", 1, 3, 1, func_set_umask),
5959 FT_ENTRY ("get-umask", 0, 0, 0, func_get_umask),
5960#endif
5961};
5962
5963#define FUNCTION_TABLE_ENTRIES (sizeof (function_table_init) / sizeof (struct function_table_entry))
5964
5965
5966
5967/* These must come after the definition of function_table. */
5968
5969static char *
5970expand_builtin_function (char *o, int argc, char **argv,
5971 const struct function_table_entry *entry_p)
5972{
5973 char *p;
5974
5975 if (argc < (int)entry_p->minimum_args)
5976 fatal (*expanding_var, strlen (entry_p->name),
5977 _("insufficient number of arguments (%d) to function '%s'"),
5978 argc, entry_p->name);
5979
5980 /* I suppose technically some function could do something with no arguments,
5981 but so far no internal ones do, so just test it for all functions here
5982 rather than in each one. We can change it later if necessary. */
5983
5984 if (!argc && !entry_p->alloc_fn)
5985 return o;
5986
5987 if (!entry_p->fptr.func_ptr)
5988 OS (fatal, *expanding_var,
5989 _("unimplemented on this platform: function '%s'"), entry_p->name);
5990
5991 if (!entry_p->alloc_fn)
5992 return entry_p->fptr.func_ptr (o, argv, entry_p->name);
5993
5994 /* This function allocates memory and returns it to us.
5995 Write it to the variable buffer, then free it. */
5996
5997 p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
5998 if (p)
5999 {
6000 o = variable_buffer_output (o, p, strlen (p));
6001 free (p);
6002 }
6003
6004 return o;
6005}
6006
6007/* Check for a function invocation in *STRINGP. *STRINGP points at the
6008 opening ( or { and is not null-terminated. If a function invocation
6009 is found, expand it into the buffer at *OP, updating *OP, incrementing
6010 *STRINGP past the reference and returning nonzero. If not, return zero. */
6011
6012static int
6013handle_function2 (const struct function_table_entry *entry_p, char **op, const char **stringp) /* bird split it up. */
6014{
6015 char openparen = (*stringp)[0];
6016 char closeparen = openparen == '(' ? ')' : '}';
6017 const char *beg;
6018 const char *end;
6019 int count = 0;
6020 char *abeg = NULL;
6021 char **argv, **argvp;
6022 int nargs;
6023
6024 beg = *stringp + 1;
6025
6026 /* We found a builtin function. Find the beginning of its arguments (skip
6027 whitespace after the name). */
6028
6029 beg += entry_p->len;
6030 NEXT_TOKEN (beg);
6031
6032 /* Find the end of the function invocation, counting nested use of
6033 whichever kind of parens we use. Since we're looking, count commas
6034 to get a rough estimate of how many arguments we might have. The
6035 count might be high, but it'll never be low. */
6036
6037 for (nargs=1, end=beg; *end != '\0'; ++end)
6038 if (*end == ',')
6039 ++nargs;
6040 else if (*end == openparen)
6041 ++count;
6042 else if (*end == closeparen && --count < 0)
6043 break;
6044
6045 if (count >= 0)
6046 fatal (*expanding_var, strlen (entry_p->name),
6047 _("unterminated call to function '%s': missing '%c'"),
6048 entry_p->name, closeparen);
6049
6050 *stringp = end;
6051
6052 /* Get some memory to store the arg pointers. */
6053 argvp = argv = alloca (sizeof (char *) * (nargs + 2));
6054
6055 /* Chop the string into arguments, then a nul. As soon as we hit
6056 MAXIMUM_ARGS (if it's >0) assume the rest of the string is part of the
6057 last argument.
6058
6059 If we're expanding, store pointers to the expansion of each one. If
6060 not, make a duplicate of the string and point into that, nul-terminating
6061 each argument. */
6062
6063 if (entry_p->expand_args)
6064 {
6065 const char *p;
6066 for (p=beg, nargs=0; p <= end; ++argvp)
6067 {
6068 const char *next;
6069
6070 ++nargs;
6071
6072 if (nargs == entry_p->maximum_args
6073 || (! (next = find_next_argument (openparen, closeparen, p, end))))
6074 next = end;
6075
6076 *argvp = expand_argument (p, next);
6077 p = next + 1;
6078 }
6079 }
6080 else
6081 {
6082 int len = end - beg;
6083 char *p, *aend;
6084
6085 abeg = xmalloc (len+1);
6086 memcpy (abeg, beg, len);
6087 abeg[len] = '\0';
6088 aend = abeg + len;
6089
6090 for (p=abeg, nargs=0; p <= aend; ++argvp)
6091 {
6092 char *next;
6093
6094 ++nargs;
6095
6096 if (nargs == entry_p->maximum_args
6097 || (! (next = find_next_argument (openparen, closeparen, p, aend))))
6098 next = aend;
6099
6100 *argvp = p;
6101 *next = '\0';
6102 p = next + 1;
6103 }
6104 }
6105 *argvp = NULL;
6106
6107 /* Finally! Run the function... */
6108 *op = expand_builtin_function (*op, nargs, argv, entry_p);
6109
6110 /* Free memory. */
6111 if (entry_p->expand_args)
6112 for (argvp=argv; *argvp != 0; ++argvp)
6113 free (*argvp);
6114 else
6115 free (abeg);
6116
6117 return 1;
6118}
6119
6120
6121int /* bird split it up and hacked it. */
6122#ifndef CONFIG_WITH_VALUE_LENGTH
6123handle_function (char **op, const char **stringp)
6124{
6125 const struct function_table_entry *entry_p = lookup_function (*stringp + 1);
6126 if (!entry_p)
6127 return 0;
6128 return handle_function2 (entry_p, op, stringp);
6129}
6130#else /* CONFIG_WITH_VALUE_LENGTH */
6131handle_function (char **op, const char **stringp, const char *nameend, const char *eol UNUSED)
6132{
6133 const char *fname = *stringp + 1;
6134 const struct function_table_entry *entry_p =
6135 lookup_function_in_hash_tab (fname, nameend - fname);
6136 if (!entry_p)
6137 return 0;
6138 return handle_function2 (entry_p, op, stringp);
6139}
6140#endif /* CONFIG_WITH_VALUE_LENGTH */
6141
6142#ifdef CONFIG_WITH_COMPILER
6143/* Used by the "compiler" to get all info about potential functions. */
6144make_function_ptr_t
6145lookup_function_for_compiler (const char *name, unsigned int len,
6146 unsigned char *minargsp, unsigned char *maxargsp,
6147 char *expargsp, const char **funcnamep)
6148{
6149 const struct function_table_entry *entry_p = lookup_function (name, len);
6150 if (!entry_p)
6151 return 0;
6152 *minargsp = entry_p->minimum_args;
6153 *maxargsp = entry_p->maximum_args;
6154 *expargsp = entry_p->expand_args;
6155 *funcnamep = entry_p->name;
6156 return entry_p->func_ptr;
6157}
6158#endif /* CONFIG_WITH_COMPILER */
6159
6160
6161
6162/* User-defined functions. Expand the first argument as either a builtin
6163 function or a make variable, in the context of the rest of the arguments
6164 assigned to $1, $2, ... $N. $0 is the name of the function. */
6165
6166static char *
6167func_call (char *o, char **argv, const char *funcname UNUSED)
6168{
6169 static int max_args = 0;
6170 char *fname;
6171 char *body;
6172 int flen;
6173 int i;
6174 int saved_args;
6175 const struct function_table_entry *entry_p;
6176 struct variable *v;
6177#ifdef CONFIG_WITH_EVALPLUS
6178 char *buf;
6179 unsigned int len;
6180#endif
6181#ifdef CONFIG_WITH_VALUE_LENGTH
6182 char *fname_end;
6183#endif
6184#if defined (CONFIG_WITH_EVALPLUS) || defined (CONFIG_WITH_VALUE_LENGTH)
6185 char num[11];
6186#endif
6187
6188 /* Clean up the name of the variable to be invoked. */
6189 fname = next_token (argv[0]);
6190#ifndef CONFIG_WITH_VALUE_LENGTH
6191 end_of_token (fname)[0] = '\0';
6192#else
6193 fname_end = end_of_token (fname);
6194 *fname_end = '\0';
6195#endif
6196
6197 /* Calling nothing is a no-op */
6198#ifndef CONFIG_WITH_VALUE_LENGTH
6199 if (*fname == '\0')
6200#else
6201 if (fname == fname_end)
6202#endif
6203 return o;
6204
6205 /* Are we invoking a builtin function? */
6206
6207#ifndef CONFIG_WITH_VALUE_LENGTH
6208 entry_p = lookup_function (fname);
6209#else
6210 entry_p = lookup_function (fname, fname_end - fname);
6211#endif
6212 if (entry_p)
6213 {
6214 /* How many arguments do we have? */
6215 for (i=0; argv[i+1]; ++i)
6216 ;
6217 return expand_builtin_function (o, i, argv+1, entry_p);
6218 }
6219
6220 /* Not a builtin, so the first argument is the name of a variable to be
6221 expanded and interpreted as a function. Find it. */
6222 flen = strlen (fname);
6223
6224 v = lookup_variable (fname, flen);
6225
6226 if (v == 0)
6227 warn_undefined (fname, flen);
6228
6229 if (v == 0 || *v->value == '\0')
6230 return o;
6231
6232 body = alloca (flen + 4);
6233 body[0] = '$';
6234 body[1] = '(';
6235 memcpy (body + 2, fname, flen);
6236 body[flen+2] = ')';
6237 body[flen+3] = '\0';
6238
6239 /* Set up arguments $(1) .. $(N). $(0) is the function name. */
6240
6241 push_new_variable_scope ();
6242
6243 for (i=0; *argv; ++i, ++argv)
6244#ifdef CONFIG_WITH_VALUE_LENGTH
6245 define_variable (num, sprintf (num, "%d", i), *argv, o_automatic, 0);
6246#else
6247 {
6248 char num[11];
6249
6250 sprintf (num, "%d", i);
6251 define_variable (num, strlen (num), *argv, o_automatic, 0);
6252 }
6253#endif
6254
6255#ifdef CONFIG_WITH_EVALPLUS
6256 /* $(.ARGC) is the argument count. */
6257
6258 len = sprintf (num, "%d", i - 1);
6259 define_variable_vl (".ARGC", sizeof (".ARGC") - 1, num, len,
6260 1 /* dup val */, o_automatic, 0);
6261#endif
6262
6263 /* If the number of arguments we have is < max_args, it means we're inside
6264 a recursive invocation of $(call ...). Fill in the remaining arguments
6265 in the new scope with the empty value, to hide them from this
6266 invocation. */
6267
6268 for (; i < max_args; ++i)
6269#ifdef CONFIG_WITH_VALUE_LENGTH
6270 define_variable (num, sprintf (num, "%d", i), "", o_automatic, 0);
6271#else
6272 {
6273 char num[11];
6274
6275 sprintf (num, "%d", i);
6276 define_variable (num, strlen (num), "", o_automatic, 0);
6277 }
6278#endif
6279
6280 saved_args = max_args;
6281 max_args = i;
6282
6283#ifdef CONFIG_WITH_EVALPLUS
6284 if (!strcmp (funcname, "call"))
6285 {
6286#endif
6287 /* Expand the body in the context of the arguments, adding the result to
6288 the variable buffer. */
6289
6290 v->exp_count = EXP_COUNT_MAX;
6291#ifndef CONFIG_WITH_VALUE_LENGTH
6292 o = variable_expand_string (o, body, flen+3);
6293 v->exp_count = 0;
6294
6295 o += strlen (o);
6296#else /* CONFIG_WITH_VALUE_LENGTH */
6297 variable_expand_string_2 (o, body, flen+3, &o);
6298 v->exp_count = 0;
6299#endif /* CONFIG_WITH_VALUE_LENGTH */
6300#ifdef CONFIG_WITH_EVALPLUS
6301 }
6302 else
6303 {
6304 const floc *reading_file_saved = reading_file;
6305 char *eos;
6306
6307 if (!strcmp (funcname, "evalcall"))
6308 {
6309 /* Evaluate the variable value without expanding it. We
6310 need a copy since eval_buffer is destructive. */
6311
6312 size_t off = o - variable_buffer;
6313 eos = variable_buffer_output (o, v->value, v->value_length + 1) - 1;
6314 o = variable_buffer + off;
6315 if (v->fileinfo.filenm)
6316 reading_file = &v->fileinfo;
6317 }
6318 else
6319 {
6320 /* Expand the body first and then evaluate the output. */
6321
6322 v->exp_count = EXP_COUNT_MAX;
6323 o = variable_expand_string_2 (o, body, flen+3, &eos);
6324 v->exp_count = 0;
6325 }
6326
6327 install_variable_buffer (&buf, &len);
6328 eval_buffer (o, NULL, eos);
6329 restore_variable_buffer (buf, len);
6330 reading_file = reading_file_saved;
6331
6332 /* Deal with the .RETURN value if present. */
6333
6334 v = lookup_variable_in_set (".RETURN", sizeof (".RETURN") - 1,
6335 current_variable_set_list->set);
6336 if (v && v->value_length)
6337 {
6338 if (v->recursive && !IS_VARIABLE_RECURSIVE_WITHOUT_DOLLAR (v))
6339 {
6340 v->exp_count = EXP_COUNT_MAX;
6341 variable_expand_string_2 (o, v->value, v->value_length, &o);
6342 v->exp_count = 0;
6343 }
6344 else
6345 o = variable_buffer_output (o, v->value, v->value_length);
6346 }
6347 }
6348#endif /* CONFIG_WITH_EVALPLUS */
6349
6350 max_args = saved_args;
6351
6352 pop_variable_scope ();
6353
6354 return o;
6355}
6356
6357void
6358define_new_function (const floc *flocp, const char *name,
6359 unsigned int min, unsigned int max, unsigned int flags,
6360 gmk_func_ptr func)
6361{
6362 const char *e = name;
6363 struct function_table_entry *ent;
6364 size_t len;
6365
6366 while (STOP_SET (*e, MAP_USERFUNC))
6367 e++;
6368 len = e - name;
6369
6370 if (len == 0)
6371 O (fatal, flocp, _("Empty function name"));
6372 if (*name == '.' || *e != '\0')
6373 OS (fatal, flocp, _("Invalid function name: %s"), name);
6374 if (len > 255)
6375 OS (fatal, flocp, _("Function name too long: %s"), name);
6376 if (min > 255)
6377 ONS (fatal, flocp,
6378 _("Invalid minimum argument count (%u) for function %s"), min, name);
6379 if (max > 255 || (max && max < min))
6380 ONS (fatal, flocp,
6381 _("Invalid maximum argument count (%u) for function %s"), max, name);
6382
6383 ent = xmalloc (sizeof (struct function_table_entry));
6384 ent->name = name;
6385 ent->len = len;
6386 ent->minimum_args = min;
6387 ent->maximum_args = max;
6388 ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
6389 ent->alloc_fn = 1;
6390 ent->fptr.alloc_func_ptr = func;
6391
6392 hash_insert (&function_table, ent);
6393}
6394
6395void
6396hash_init_function_table (void)
6397{
6398 hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
6399 function_table_entry_hash_1, function_table_entry_hash_2,
6400 function_table_entry_hash_cmp);
6401 hash_load (&function_table, function_table_init,
6402 FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
6403#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
6404 {
6405 unsigned int i;
6406 for (i = 0; i < FUNCTION_TABLE_ENTRIES; i++)
6407 {
6408 const char *fn = function_table_init[i].name;
6409 while (*fn)
6410 {
6411 func_char_map[(int)*fn] = 1;
6412 fn++;
6413 }
6414 assert (function_table_init[i].len <= MAX_FUNCTION_LENGTH);
6415 assert (function_table_init[i].len >= MIN_FUNCTION_LENGTH);
6416 }
6417 }
6418#endif
6419}
Note: See TracBrowser for help on using the repository browser.