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