1 /* $NetBSD: cond.c,v 1.79 2020/07/09 22:34:08 sjg Exp $ */ 2 3 /* 4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Adam de Boor. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * Copyright (c) 1988, 1989 by Adam de Boor 37 * Copyright (c) 1989 by Berkeley Softworks 38 * All rights reserved. 39 * 40 * This code is derived from software contributed to Berkeley by 41 * Adam de Boor. 42 * 43 * Redistribution and use in source and binary forms, with or without 44 * modification, are permitted provided that the following conditions 45 * are met: 46 * 1. Redistributions of source code must retain the above copyright 47 * notice, this list of conditions and the following disclaimer. 48 * 2. Redistributions in binary form must reproduce the above copyright 49 * notice, this list of conditions and the following disclaimer in the 50 * documentation and/or other materials provided with the distribution. 51 * 3. All advertising materials mentioning features or use of this software 52 * must display the following acknowledgement: 53 * This product includes software developed by the University of 54 * California, Berkeley and its contributors. 55 * 4. Neither the name of the University nor the names of its contributors 56 * may be used to endorse or promote products derived from this software 57 * without specific prior written permission. 58 * 59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 69 * SUCH DAMAGE. 70 */ 71 72 #ifndef MAKE_NATIVE 73 static char rcsid[] = "$NetBSD: cond.c,v 1.79 2020/07/09 22:34:08 sjg Exp $"; 74 #else 75 #include <sys/cdefs.h> 76 #ifndef lint 77 #if 0 78 static char sccsid[] = "@(#)cond.c 8.2 (Berkeley) 1/2/94"; 79 #else 80 __RCSID("$NetBSD: cond.c,v 1.79 2020/07/09 22:34:08 sjg Exp $"); 81 #endif 82 #endif /* not lint */ 83 #endif 84 85 /*- 86 * cond.c -- 87 * Functions to handle conditionals in a makefile. 88 * 89 * Interface: 90 * Cond_Eval Evaluate the conditional in the passed line. 91 * 92 */ 93 94 #include <assert.h> 95 #include <ctype.h> 96 #include <errno.h> /* For strtoul() error checking */ 97 98 #include "make.h" 99 #include "hash.h" 100 #include "dir.h" 101 #include "buf.h" 102 103 /* 104 * The parsing of conditional expressions is based on this grammar: 105 * E -> F || E 106 * E -> F 107 * F -> T && F 108 * F -> T 109 * T -> defined(variable) 110 * T -> make(target) 111 * T -> exists(file) 112 * T -> empty(varspec) 113 * T -> target(name) 114 * T -> commands(name) 115 * T -> symbol 116 * T -> $(varspec) op value 117 * T -> $(varspec) == "string" 118 * T -> $(varspec) != "string" 119 * T -> "string" 120 * T -> ( E ) 121 * T -> ! T 122 * op -> == | != | > | < | >= | <= 123 * 124 * 'symbol' is some other symbol to which the default function (condDefProc) 125 * is applied. 126 * 127 * Tokens are scanned from the 'condExpr' string. The scanner (CondToken) 128 * will return TOK_AND for '&' and '&&', TOK_OR for '|' and '||', 129 * TOK_NOT for '!', TOK_LPAREN for '(', TOK_RPAREN for ')' and will evaluate 130 * the other terminal symbols, using either the default function or the 131 * function given in the terminal, and return the result as either TOK_TRUE 132 * or TOK_FALSE. 133 * 134 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons. 135 * 136 * All Non-Terminal functions (CondE, CondF and CondT) return TOK_ERROR on 137 * error. 138 */ 139 typedef enum { 140 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT, 141 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR 142 } Token; 143 144 /*- 145 * Structures to handle elegantly the different forms of #if's. The 146 * last two fields are stored in condInvert and condDefProc, respectively. 147 */ 148 static void CondPushBack(Token); 149 static int CondGetArg(Boolean, char **, char **, const char *); 150 static Boolean CondDoDefined(int, const char *); 151 static int CondStrMatch(const void *, const void *); 152 static Boolean CondDoMake(int, const char *); 153 static Boolean CondDoExists(int, const char *); 154 static Boolean CondDoTarget(int, const char *); 155 static Boolean CondDoCommands(int, const char *); 156 static Boolean CondCvtArg(char *, double *); 157 static Token CondToken(Boolean); 158 static Token CondT(Boolean); 159 static Token CondF(Boolean); 160 static Token CondE(Boolean); 161 static int do_Cond_EvalExpression(Boolean *); 162 163 static const struct If { 164 const char *form; /* Form of if */ 165 int formlen; /* Length of form */ 166 Boolean doNot; /* TRUE if default function should be negated */ 167 Boolean (*defProc)(int, const char *); /* Default function to apply */ 168 } ifs[] = { 169 { "def", 3, FALSE, CondDoDefined }, 170 { "ndef", 4, TRUE, CondDoDefined }, 171 { "make", 4, FALSE, CondDoMake }, 172 { "nmake", 5, TRUE, CondDoMake }, 173 { "", 0, FALSE, CondDoDefined }, 174 { NULL, 0, FALSE, NULL } 175 }; 176 177 static const struct If *if_info; /* Info for current statement */ 178 static char *condExpr; /* The expression to parse */ 179 static Token condPushBack=TOK_NONE; /* Single push-back token used in 180 * parsing */ 181 182 static unsigned int cond_depth = 0; /* current .if nesting level */ 183 static unsigned int cond_min_depth = 0; /* depth at makefile open */ 184 185 /* 186 * Indicate when we should be strict about lhs of comparisons. 187 * TRUE when Cond_EvalExpression is called from Cond_Eval (.if etc) 188 * FALSE when Cond_EvalExpression is called from var.c:ApplyModifiers 189 * since lhs is already expanded and we cannot tell if 190 * it was a variable reference or not. 191 */ 192 static Boolean lhsStrict; 193 194 static int 195 istoken(const char *str, const char *tok, size_t len) 196 { 197 return strncmp(str, tok, len) == 0 && !isalpha((unsigned char)str[len]); 198 } 199 200 /*- 201 *----------------------------------------------------------------------- 202 * CondPushBack -- 203 * Push back the most recent token read. We only need one level of 204 * this, so the thing is just stored in 'condPushback'. 205 * 206 * Input: 207 * t Token to push back into the "stream" 208 * 209 * Results: 210 * None. 211 * 212 * Side Effects: 213 * condPushback is overwritten. 214 * 215 *----------------------------------------------------------------------- 216 */ 217 static void 218 CondPushBack(Token t) 219 { 220 condPushBack = t; 221 } 222 223 /*- 224 *----------------------------------------------------------------------- 225 * CondGetArg -- 226 * Find the argument of a built-in function. 227 * 228 * Results: 229 * The length of the argument and the address of the argument. 230 * 231 * Side Effects: 232 * The pointer is set to point to the closing parenthesis of the 233 * function call. 234 * 235 *----------------------------------------------------------------------- 236 */ 237 static int 238 CondGetArg(Boolean doEval, char **linePtr, char **argPtr, const char *func) 239 { 240 char *cp; 241 int argLen; 242 Buffer buf; 243 int paren_depth; 244 char ch; 245 246 cp = *linePtr; 247 if (func != NULL) 248 /* Skip opening '(' - verfied by caller */ 249 cp++; 250 251 if (*cp == '\0') { 252 /* 253 * No arguments whatsoever. Because 'make' and 'defined' aren't really 254 * "reserved words", we don't print a message. I think this is better 255 * than hitting the user with a warning message every time s/he uses 256 * the word 'make' or 'defined' at the beginning of a symbol... 257 */ 258 *argPtr = NULL; 259 return 0; 260 } 261 262 while (*cp == ' ' || *cp == '\t') { 263 cp++; 264 } 265 266 /* 267 * Create a buffer for the argument and start it out at 16 characters 268 * long. Why 16? Why not? 269 */ 270 Buf_Init(&buf, 16); 271 272 paren_depth = 0; 273 for (;;) { 274 ch = *cp; 275 if (ch == 0 || ch == ' ' || ch == '\t') 276 break; 277 if ((ch == '&' || ch == '|') && paren_depth == 0) 278 break; 279 if (*cp == '$') { 280 /* 281 * Parse the variable spec and install it as part of the argument 282 * if it's valid. We tell Var_Parse to complain on an undefined 283 * variable, so we don't do it too. Nor do we return an error, 284 * though perhaps we should... 285 */ 286 char *cp2; 287 int len; 288 void *freeIt; 289 290 cp2 = Var_Parse(cp, VAR_CMD, VARF_UNDEFERR| 291 (doEval ? VARF_WANTRES : 0), 292 &len, &freeIt); 293 Buf_AddBytes(&buf, strlen(cp2), cp2); 294 free(freeIt); 295 cp += len; 296 continue; 297 } 298 if (ch == '(') 299 paren_depth++; 300 else 301 if (ch == ')' && --paren_depth < 0) 302 break; 303 Buf_AddByte(&buf, *cp); 304 cp++; 305 } 306 307 *argPtr = Buf_GetAll(&buf, &argLen); 308 Buf_Destroy(&buf, FALSE); 309 310 while (*cp == ' ' || *cp == '\t') { 311 cp++; 312 } 313 314 if (func != NULL && *cp++ != ')') { 315 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()", 316 func); 317 return 0; 318 } 319 320 *linePtr = cp; 321 return argLen; 322 } 323 324 /*- 325 *----------------------------------------------------------------------- 326 * CondDoDefined -- 327 * Handle the 'defined' function for conditionals. 328 * 329 * Results: 330 * TRUE if the given variable is defined. 331 * 332 * Side Effects: 333 * None. 334 * 335 *----------------------------------------------------------------------- 336 */ 337 static Boolean 338 CondDoDefined(int argLen MAKE_ATTR_UNUSED, const char *arg) 339 { 340 char *p1; 341 Boolean result; 342 343 if (Var_Value(arg, VAR_CMD, &p1) != NULL) { 344 result = TRUE; 345 } else { 346 result = FALSE; 347 } 348 349 free(p1); 350 return result; 351 } 352 353 /*- 354 *----------------------------------------------------------------------- 355 * CondStrMatch -- 356 * Front-end for Str_Match so it returns 0 on match and non-zero 357 * on mismatch. Callback function for CondDoMake via Lst_Find 358 * 359 * Results: 360 * 0 if string matches pattern 361 * 362 * Side Effects: 363 * None 364 * 365 *----------------------------------------------------------------------- 366 */ 367 static int 368 CondStrMatch(const void *string, const void *pattern) 369 { 370 return !Str_Match(string, pattern); 371 } 372 373 /*- 374 *----------------------------------------------------------------------- 375 * CondDoMake -- 376 * Handle the 'make' function for conditionals. 377 * 378 * Results: 379 * TRUE if the given target is being made. 380 * 381 * Side Effects: 382 * None. 383 * 384 *----------------------------------------------------------------------- 385 */ 386 static Boolean 387 CondDoMake(int argLen MAKE_ATTR_UNUSED, const char *arg) 388 { 389 return Lst_Find(create, arg, CondStrMatch) != NULL; 390 } 391 392 /*- 393 *----------------------------------------------------------------------- 394 * CondDoExists -- 395 * See if the given file exists. 396 * 397 * Results: 398 * TRUE if the file exists and FALSE if it does not. 399 * 400 * Side Effects: 401 * None. 402 * 403 *----------------------------------------------------------------------- 404 */ 405 static Boolean 406 CondDoExists(int argLen MAKE_ATTR_UNUSED, const char *arg) 407 { 408 Boolean result; 409 char *path; 410 411 path = Dir_FindFile(arg, dirSearchPath); 412 if (DEBUG(COND)) { 413 fprintf(debug_file, "exists(%s) result is \"%s\"\n", 414 arg, path ? path : ""); 415 } 416 if (path != NULL) { 417 result = TRUE; 418 free(path); 419 } else { 420 result = FALSE; 421 } 422 return result; 423 } 424 425 /*- 426 *----------------------------------------------------------------------- 427 * CondDoTarget -- 428 * See if the given node exists and is an actual target. 429 * 430 * Results: 431 * TRUE if the node exists as a target and FALSE if it does not. 432 * 433 * Side Effects: 434 * None. 435 * 436 *----------------------------------------------------------------------- 437 */ 438 static Boolean 439 CondDoTarget(int argLen MAKE_ATTR_UNUSED, const char *arg) 440 { 441 GNode *gn; 442 443 gn = Targ_FindNode(arg, TARG_NOCREATE); 444 return gn != NULL && !OP_NOP(gn->type); 445 } 446 447 /*- 448 *----------------------------------------------------------------------- 449 * CondDoCommands -- 450 * See if the given node exists and is an actual target with commands 451 * associated with it. 452 * 453 * Results: 454 * TRUE if the node exists as a target and has commands associated with 455 * it and FALSE if it does not. 456 * 457 * Side Effects: 458 * None. 459 * 460 *----------------------------------------------------------------------- 461 */ 462 static Boolean 463 CondDoCommands(int argLen MAKE_ATTR_UNUSED, const char *arg) 464 { 465 GNode *gn; 466 467 gn = Targ_FindNode(arg, TARG_NOCREATE); 468 return gn != NULL && !OP_NOP(gn->type) && !Lst_IsEmpty(gn->commands); 469 } 470 471 /*- 472 *----------------------------------------------------------------------- 473 * CondCvtArg -- 474 * Convert the given number into a double. 475 * We try a base 10 or 16 integer conversion first, if that fails 476 * then we try a floating point conversion instead. 477 * 478 * Results: 479 * Sets 'value' to double value of string. 480 * Returns 'true' if the convertion suceeded 481 * 482 *----------------------------------------------------------------------- 483 */ 484 static Boolean 485 CondCvtArg(char *str, double *value) 486 { 487 char *eptr, ech; 488 unsigned long l_val; 489 double d_val; 490 491 errno = 0; 492 if (!*str) { 493 *value = (double)0; 494 return TRUE; 495 } 496 l_val = strtoul(str, &eptr, str[1] == 'x' ? 16 : 10); 497 ech = *eptr; 498 if (ech == 0 && errno != ERANGE) { 499 d_val = str[0] == '-' ? -(double)-l_val : (double)l_val; 500 } else { 501 if (ech != 0 && ech != '.' && ech != 'e' && ech != 'E') 502 return FALSE; 503 d_val = strtod(str, &eptr); 504 if (*eptr) 505 return FALSE; 506 } 507 508 *value = d_val; 509 return TRUE; 510 } 511 512 /*- 513 *----------------------------------------------------------------------- 514 * CondGetString -- 515 * Get a string from a variable reference or an optionally quoted 516 * string. This is called for the lhs and rhs of string compares. 517 * 518 * Results: 519 * Sets freeIt if needed, 520 * Sets quoted if string was quoted, 521 * Returns NULL on error, 522 * else returns string - absent any quotes. 523 * 524 * Side Effects: 525 * Moves condExpr to end of this token. 526 * 527 * 528 *----------------------------------------------------------------------- 529 */ 530 /* coverity:[+alloc : arg-*2] */ 531 static char * 532 CondGetString(Boolean doEval, Boolean *quoted, void **freeIt, Boolean strictLHS) 533 { 534 Buffer buf; 535 char *cp; 536 char *str; 537 int len; 538 int qt; 539 char *start; 540 541 Buf_Init(&buf, 0); 542 str = NULL; 543 *freeIt = NULL; 544 *quoted = qt = *condExpr == '"' ? 1 : 0; 545 if (qt) 546 condExpr++; 547 for (start = condExpr; *condExpr && str == NULL; condExpr++) { 548 switch (*condExpr) { 549 case '\\': 550 if (condExpr[1] != '\0') { 551 condExpr++; 552 Buf_AddByte(&buf, *condExpr); 553 } 554 break; 555 case '"': 556 if (qt) { 557 condExpr++; /* we don't want the quotes */ 558 goto got_str; 559 } else 560 Buf_AddByte(&buf, *condExpr); /* likely? */ 561 break; 562 case ')': 563 case '!': 564 case '=': 565 case '>': 566 case '<': 567 case ' ': 568 case '\t': 569 if (!qt) 570 goto got_str; 571 else 572 Buf_AddByte(&buf, *condExpr); 573 break; 574 case '$': 575 /* if we are in quotes, then an undefined variable is ok */ 576 str = Var_Parse(condExpr, VAR_CMD, 577 ((!qt && doEval) ? VARF_UNDEFERR : 0) | 578 (doEval ? VARF_WANTRES : 0), &len, freeIt); 579 if (str == var_Error) { 580 if (*freeIt) { 581 free(*freeIt); 582 *freeIt = NULL; 583 } 584 /* 585 * Even if !doEval, we still report syntax errors, which 586 * is what getting var_Error back with !doEval means. 587 */ 588 str = NULL; 589 goto cleanup; 590 } 591 condExpr += len; 592 /* 593 * If the '$' was first char (no quotes), and we are 594 * followed by space, the operator or end of expression, 595 * we are done. 596 */ 597 if ((condExpr == start + len) && 598 (*condExpr == '\0' || 599 isspace((unsigned char) *condExpr) || 600 strchr("!=><)", *condExpr))) { 601 goto cleanup; 602 } 603 /* 604 * Nope, we better copy str to buf 605 */ 606 for (cp = str; *cp; cp++) { 607 Buf_AddByte(&buf, *cp); 608 } 609 if (*freeIt) { 610 free(*freeIt); 611 *freeIt = NULL; 612 } 613 str = NULL; /* not finished yet */ 614 condExpr--; /* don't skip over next char */ 615 break; 616 default: 617 if (strictLHS && !qt && *start != '$' && 618 !isdigit((unsigned char) *start)) { 619 /* lhs must be quoted, a variable reference or number */ 620 if (*freeIt) { 621 free(*freeIt); 622 *freeIt = NULL; 623 } 624 str = NULL; 625 goto cleanup; 626 } 627 Buf_AddByte(&buf, *condExpr); 628 break; 629 } 630 } 631 got_str: 632 str = Buf_GetAll(&buf, NULL); 633 *freeIt = str; 634 cleanup: 635 Buf_Destroy(&buf, FALSE); 636 return str; 637 } 638 639 /*- 640 *----------------------------------------------------------------------- 641 * CondToken -- 642 * Return the next token from the input. 643 * 644 * Results: 645 * A Token for the next lexical token in the stream. 646 * 647 * Side Effects: 648 * condPushback will be set back to TOK_NONE if it is used. 649 * 650 *----------------------------------------------------------------------- 651 */ 652 static Token 653 compare_expression(Boolean doEval) 654 { 655 Token t; 656 char *lhs; 657 char *rhs; 658 char *op; 659 void *lhsFree; 660 void *rhsFree; 661 Boolean lhsQuoted; 662 Boolean rhsQuoted; 663 double left, right; 664 665 t = TOK_ERROR; 666 rhs = NULL; 667 lhsFree = rhsFree = FALSE; 668 lhsQuoted = rhsQuoted = FALSE; 669 670 /* 671 * Parse the variable spec and skip over it, saving its 672 * value in lhs. 673 */ 674 lhs = CondGetString(doEval, &lhsQuoted, &lhsFree, lhsStrict); 675 if (!lhs) 676 goto done; 677 678 /* 679 * Skip whitespace to get to the operator 680 */ 681 while (isspace((unsigned char) *condExpr)) 682 condExpr++; 683 684 /* 685 * Make sure the operator is a valid one. If it isn't a 686 * known relational operator, pretend we got a 687 * != 0 comparison. 688 */ 689 op = condExpr; 690 switch (*condExpr) { 691 case '!': 692 case '=': 693 case '<': 694 case '>': 695 if (condExpr[1] == '=') { 696 condExpr += 2; 697 } else { 698 condExpr += 1; 699 } 700 break; 701 default: 702 if (!doEval) { 703 t = TOK_FALSE; 704 goto done; 705 } 706 /* For .ifxxx "..." check for non-empty string. */ 707 if (lhsQuoted) { 708 t = lhs[0] != 0; 709 goto done; 710 } 711 /* For .ifxxx <number> compare against zero */ 712 if (CondCvtArg(lhs, &left)) { 713 t = left != 0.0; 714 goto done; 715 } 716 /* For .if ${...} check for non-empty string (defProc is ifdef). */ 717 if (if_info->form[0] == 0) { 718 t = lhs[0] != 0; 719 goto done; 720 } 721 /* Otherwise action default test ... */ 722 t = if_info->defProc(strlen(lhs), lhs) != if_info->doNot; 723 goto done; 724 } 725 726 while (isspace((unsigned char)*condExpr)) 727 condExpr++; 728 729 if (*condExpr == '\0') { 730 Parse_Error(PARSE_WARNING, 731 "Missing right-hand-side of operator"); 732 goto done; 733 } 734 735 rhs = CondGetString(doEval, &rhsQuoted, &rhsFree, FALSE); 736 if (!rhs) 737 goto done; 738 739 if (!doEval) { 740 t = TOK_FALSE; 741 goto done; 742 } 743 744 if (rhsQuoted || lhsQuoted) { 745 do_string_compare: 746 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) { 747 Parse_Error(PARSE_WARNING, 748 "String comparison operator should be either == or !="); 749 goto done; 750 } 751 752 if (DEBUG(COND)) { 753 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", 754 lhs, rhs, op); 755 } 756 /* 757 * Null-terminate rhs and perform the comparison. 758 * t is set to the result. 759 */ 760 if (*op == '=') { 761 t = strcmp(lhs, rhs) == 0; 762 } else { 763 t = strcmp(lhs, rhs) != 0; 764 } 765 } else { 766 /* 767 * rhs is either a float or an integer. Convert both the 768 * lhs and the rhs to a double and compare the two. 769 */ 770 771 if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right)) 772 goto do_string_compare; 773 774 if (DEBUG(COND)) { 775 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left, 776 right, op); 777 } 778 switch(op[0]) { 779 case '!': 780 if (op[1] != '=') { 781 Parse_Error(PARSE_WARNING, 782 "Unknown operator"); 783 goto done; 784 } 785 t = (left != right); 786 break; 787 case '=': 788 if (op[1] != '=') { 789 Parse_Error(PARSE_WARNING, 790 "Unknown operator"); 791 goto done; 792 } 793 t = (left == right); 794 break; 795 case '<': 796 if (op[1] == '=') { 797 t = (left <= right); 798 } else { 799 t = (left < right); 800 } 801 break; 802 case '>': 803 if (op[1] == '=') { 804 t = (left >= right); 805 } else { 806 t = (left > right); 807 } 808 break; 809 } 810 } 811 812 done: 813 free(lhsFree); 814 free(rhsFree); 815 return t; 816 } 817 818 static int 819 get_mpt_arg(Boolean doEval, char **linePtr, char **argPtr, const char *func MAKE_ATTR_UNUSED) 820 { 821 /* 822 * Use Var_Parse to parse the spec in parens and return 823 * TOK_TRUE if the resulting string is empty. 824 */ 825 int length; 826 void *freeIt; 827 char *val; 828 char *cp = *linePtr; 829 830 /* We do all the work here and return the result as the length */ 831 *argPtr = NULL; 832 833 val = Var_Parse(cp - 1, VAR_CMD, doEval ? VARF_WANTRES : 0, &length, &freeIt); 834 /* 835 * Advance *linePtr to beyond the closing ). Note that 836 * we subtract one because 'length' is calculated from 'cp - 1'. 837 */ 838 *linePtr = cp - 1 + length; 839 840 if (val == var_Error) { 841 free(freeIt); 842 return -1; 843 } 844 845 /* A variable is empty when it just contains spaces... 4/15/92, christos */ 846 while (isspace(*(unsigned char *)val)) 847 val++; 848 849 /* 850 * For consistency with the other functions we can't generate the 851 * true/false here. 852 */ 853 length = *val ? 2 : 1; 854 free(freeIt); 855 return length; 856 } 857 858 static Boolean 859 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED) 860 { 861 return arglen == 1; 862 } 863 864 static Token 865 compare_function(Boolean doEval) 866 { 867 static const struct fn_def { 868 const char *fn_name; 869 int fn_name_len; 870 int (*fn_getarg)(Boolean, char **, char **, const char *); 871 Boolean (*fn_proc)(int, const char *); 872 } fn_defs[] = { 873 { "defined", 7, CondGetArg, CondDoDefined }, 874 { "make", 4, CondGetArg, CondDoMake }, 875 { "exists", 6, CondGetArg, CondDoExists }, 876 { "empty", 5, get_mpt_arg, CondDoEmpty }, 877 { "target", 6, CondGetArg, CondDoTarget }, 878 { "commands", 8, CondGetArg, CondDoCommands }, 879 { NULL, 0, NULL, NULL }, 880 }; 881 const struct fn_def *fn_def; 882 Token t; 883 char *arg = NULL; 884 int arglen; 885 char *cp = condExpr; 886 char *cp1; 887 888 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) { 889 if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len)) 890 continue; 891 cp += fn_def->fn_name_len; 892 /* There can only be whitespace before the '(' */ 893 while (isspace(*(unsigned char *)cp)) 894 cp++; 895 if (*cp != '(') 896 break; 897 898 arglen = fn_def->fn_getarg(doEval, &cp, &arg, fn_def->fn_name); 899 if (arglen <= 0) { 900 condExpr = cp; 901 return arglen < 0 ? TOK_ERROR : TOK_FALSE; 902 } 903 /* Evaluate the argument using the required function. */ 904 t = !doEval || fn_def->fn_proc(arglen, arg); 905 free(arg); 906 condExpr = cp; 907 return t; 908 } 909 910 /* Push anything numeric through the compare expression */ 911 cp = condExpr; 912 if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0])) 913 return compare_expression(doEval); 914 915 /* 916 * Most likely we have a naked token to apply the default function to. 917 * However ".if a == b" gets here when the "a" is unquoted and doesn't 918 * start with a '$'. This surprises people. 919 * If what follows the function argument is a '=' or '!' then the syntax 920 * would be invalid if we did "defined(a)" - so instead treat as an 921 * expression. 922 */ 923 arglen = CondGetArg(doEval, &cp, &arg, NULL); 924 for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++) 925 continue; 926 if (*cp1 == '=' || *cp1 == '!') 927 return compare_expression(doEval); 928 condExpr = cp; 929 930 /* 931 * Evaluate the argument using the default function. 932 * This path always treats .if as .ifdef. To get here the character 933 * after .if must have been taken literally, so the argument cannot 934 * be empty - even if it contained a variable expansion. 935 */ 936 t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot; 937 free(arg); 938 return t; 939 } 940 941 static Token 942 CondToken(Boolean doEval) 943 { 944 Token t; 945 946 t = condPushBack; 947 if (t != TOK_NONE) { 948 condPushBack = TOK_NONE; 949 return t; 950 } 951 952 while (*condExpr == ' ' || *condExpr == '\t') { 953 condExpr++; 954 } 955 956 switch (*condExpr) { 957 958 case '(': 959 condExpr++; 960 return TOK_LPAREN; 961 962 case ')': 963 condExpr++; 964 return TOK_RPAREN; 965 966 case '|': 967 if (condExpr[1] == '|') { 968 condExpr++; 969 } 970 condExpr++; 971 return TOK_OR; 972 973 case '&': 974 if (condExpr[1] == '&') { 975 condExpr++; 976 } 977 condExpr++; 978 return TOK_AND; 979 980 case '!': 981 condExpr++; 982 return TOK_NOT; 983 984 case '#': 985 case '\n': 986 case '\0': 987 return TOK_EOF; 988 989 case '"': 990 case '$': 991 return compare_expression(doEval); 992 993 default: 994 return compare_function(doEval); 995 } 996 } 997 998 /*- 999 *----------------------------------------------------------------------- 1000 * CondT -- 1001 * Parse a single term in the expression. This consists of a terminal 1002 * symbol or TOK_NOT and a terminal symbol (not including the binary 1003 * operators): 1004 * T -> defined(variable) | make(target) | exists(file) | symbol 1005 * T -> ! T | ( E ) 1006 * 1007 * Results: 1008 * TOK_TRUE, TOK_FALSE or TOK_ERROR. 1009 * 1010 * Side Effects: 1011 * Tokens are consumed. 1012 * 1013 *----------------------------------------------------------------------- 1014 */ 1015 static Token 1016 CondT(Boolean doEval) 1017 { 1018 Token t; 1019 1020 t = CondToken(doEval); 1021 1022 if (t == TOK_EOF) { 1023 /* 1024 * If we reached the end of the expression, the expression 1025 * is malformed... 1026 */ 1027 t = TOK_ERROR; 1028 } else if (t == TOK_LPAREN) { 1029 /* 1030 * T -> ( E ) 1031 */ 1032 t = CondE(doEval); 1033 if (t != TOK_ERROR) { 1034 if (CondToken(doEval) != TOK_RPAREN) { 1035 t = TOK_ERROR; 1036 } 1037 } 1038 } else if (t == TOK_NOT) { 1039 t = CondT(doEval); 1040 if (t == TOK_TRUE) { 1041 t = TOK_FALSE; 1042 } else if (t == TOK_FALSE) { 1043 t = TOK_TRUE; 1044 } 1045 } 1046 return t; 1047 } 1048 1049 /*- 1050 *----------------------------------------------------------------------- 1051 * CondF -- 1052 * Parse a conjunctive factor (nice name, wot?) 1053 * F -> T && F | T 1054 * 1055 * Results: 1056 * TOK_TRUE, TOK_FALSE or TOK_ERROR 1057 * 1058 * Side Effects: 1059 * Tokens are consumed. 1060 * 1061 *----------------------------------------------------------------------- 1062 */ 1063 static Token 1064 CondF(Boolean doEval) 1065 { 1066 Token l, o; 1067 1068 l = CondT(doEval); 1069 if (l != TOK_ERROR) { 1070 o = CondToken(doEval); 1071 1072 if (o == TOK_AND) { 1073 /* 1074 * F -> T && F 1075 * 1076 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to 1077 * parse the r.h.s. anyway (to throw it away). 1078 * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no. 1079 */ 1080 if (l == TOK_TRUE) { 1081 l = CondF(doEval); 1082 } else { 1083 (void)CondF(FALSE); 1084 } 1085 } else { 1086 /* 1087 * F -> T 1088 */ 1089 CondPushBack(o); 1090 } 1091 } 1092 return l; 1093 } 1094 1095 /*- 1096 *----------------------------------------------------------------------- 1097 * CondE -- 1098 * Main expression production. 1099 * E -> F || E | F 1100 * 1101 * Results: 1102 * TOK_TRUE, TOK_FALSE or TOK_ERROR. 1103 * 1104 * Side Effects: 1105 * Tokens are, of course, consumed. 1106 * 1107 *----------------------------------------------------------------------- 1108 */ 1109 static Token 1110 CondE(Boolean doEval) 1111 { 1112 Token l, o; 1113 1114 l = CondF(doEval); 1115 if (l != TOK_ERROR) { 1116 o = CondToken(doEval); 1117 1118 if (o == TOK_OR) { 1119 /* 1120 * E -> F || E 1121 * 1122 * A similar thing occurs for ||, except that here we make sure 1123 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s. 1124 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once 1125 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away. 1126 */ 1127 if (l == TOK_FALSE) { 1128 l = CondE(doEval); 1129 } else { 1130 (void)CondE(FALSE); 1131 } 1132 } else { 1133 /* 1134 * E -> F 1135 */ 1136 CondPushBack(o); 1137 } 1138 } 1139 return l; 1140 } 1141 1142 /*- 1143 *----------------------------------------------------------------------- 1144 * Cond_EvalExpression -- 1145 * Evaluate an expression in the passed line. The expression 1146 * consists of &&, ||, !, make(target), defined(variable) 1147 * and parenthetical groupings thereof. 1148 * 1149 * Results: 1150 * COND_PARSE if the condition was valid grammatically 1151 * COND_INVALID if not a valid conditional. 1152 * 1153 * (*value) is set to the boolean value of the condition 1154 * 1155 * Side Effects: 1156 * None. 1157 * 1158 *----------------------------------------------------------------------- 1159 */ 1160 int 1161 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint, Boolean strictLHS) 1162 { 1163 static const struct If *dflt_info; 1164 const struct If *sv_if_info = if_info; 1165 char *sv_condExpr = condExpr; 1166 Token sv_condPushBack = condPushBack; 1167 int rval; 1168 1169 lhsStrict = strictLHS; 1170 1171 while (*line == ' ' || *line == '\t') 1172 line++; 1173 1174 if (info == NULL && (info = dflt_info) == NULL) { 1175 /* Scan for the entry for .if - it can't be first */ 1176 for (info = ifs; ; info++) 1177 if (info->form[0] == 0) 1178 break; 1179 dflt_info = info; 1180 } 1181 assert(info != NULL); 1182 1183 if_info = info; 1184 condExpr = line; 1185 condPushBack = TOK_NONE; 1186 1187 rval = do_Cond_EvalExpression(value); 1188 1189 if (rval == COND_INVALID && eprint) 1190 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line); 1191 1192 if_info = sv_if_info; 1193 condExpr = sv_condExpr; 1194 condPushBack = sv_condPushBack; 1195 1196 return rval; 1197 } 1198 1199 static int 1200 do_Cond_EvalExpression(Boolean *value) 1201 { 1202 1203 switch (CondE(TRUE)) { 1204 case TOK_TRUE: 1205 if (CondToken(TRUE) == TOK_EOF) { 1206 *value = TRUE; 1207 return COND_PARSE; 1208 } 1209 break; 1210 case TOK_FALSE: 1211 if (CondToken(TRUE) == TOK_EOF) { 1212 *value = FALSE; 1213 return COND_PARSE; 1214 } 1215 break; 1216 default: 1217 case TOK_ERROR: 1218 break; 1219 } 1220 1221 return COND_INVALID; 1222 } 1223 1224 1225 /*- 1226 *----------------------------------------------------------------------- 1227 * Cond_Eval -- 1228 * Evaluate the conditional in the passed line. The line 1229 * looks like this: 1230 * .<cond-type> <expr> 1231 * where <cond-type> is any of if, ifmake, ifnmake, ifdef, 1232 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef 1233 * and <expr> consists of &&, ||, !, make(target), defined(variable) 1234 * and parenthetical groupings thereof. 1235 * 1236 * Input: 1237 * line Line to parse 1238 * 1239 * Results: 1240 * COND_PARSE if should parse lines after the conditional 1241 * COND_SKIP if should skip lines after the conditional 1242 * COND_INVALID if not a valid conditional. 1243 * 1244 * Side Effects: 1245 * None. 1246 * 1247 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order 1248 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF) 1249 * otherwise .else could be treated as '.elif 1'. 1250 * 1251 *----------------------------------------------------------------------- 1252 */ 1253 int 1254 Cond_Eval(char *line) 1255 { 1256 #define MAXIF 128 /* maximum depth of .if'ing */ 1257 #define MAXIF_BUMP 32 /* how much to grow by */ 1258 enum if_states { 1259 IF_ACTIVE, /* .if or .elif part active */ 1260 ELSE_ACTIVE, /* .else part active */ 1261 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */ 1262 SKIP_TO_ELSE, /* has been true, but not seen '.else' */ 1263 SKIP_TO_ENDIF /* nothing else to execute */ 1264 }; 1265 static enum if_states *cond_state = NULL; 1266 static unsigned int max_if_depth = MAXIF; 1267 1268 const struct If *ifp; 1269 Boolean isElif; 1270 Boolean value; 1271 int level; /* Level at which to report errors. */ 1272 enum if_states state; 1273 1274 level = PARSE_FATAL; 1275 if (!cond_state) { 1276 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state)); 1277 cond_state[0] = IF_ACTIVE; 1278 } 1279 /* skip leading character (the '.') and any whitespace */ 1280 for (line++; *line == ' ' || *line == '\t'; line++) 1281 continue; 1282 1283 /* Find what type of if we're dealing with. */ 1284 if (line[0] == 'e') { 1285 if (line[1] != 'l') { 1286 if (!istoken(line + 1, "ndif", 4)) 1287 return COND_INVALID; 1288 /* End of conditional section */ 1289 if (cond_depth == cond_min_depth) { 1290 Parse_Error(level, "if-less endif"); 1291 return COND_PARSE; 1292 } 1293 /* Return state for previous conditional */ 1294 cond_depth--; 1295 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP; 1296 } 1297 1298 /* Quite likely this is 'else' or 'elif' */ 1299 line += 2; 1300 if (istoken(line, "se", 2)) { 1301 /* It is else... */ 1302 if (cond_depth == cond_min_depth) { 1303 Parse_Error(level, "if-less else"); 1304 return COND_PARSE; 1305 } 1306 1307 state = cond_state[cond_depth]; 1308 switch (state) { 1309 case SEARCH_FOR_ELIF: 1310 state = ELSE_ACTIVE; 1311 break; 1312 case ELSE_ACTIVE: 1313 case SKIP_TO_ENDIF: 1314 Parse_Error(PARSE_WARNING, "extra else"); 1315 /* FALLTHROUGH */ 1316 default: 1317 case IF_ACTIVE: 1318 case SKIP_TO_ELSE: 1319 state = SKIP_TO_ENDIF; 1320 break; 1321 } 1322 cond_state[cond_depth] = state; 1323 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP; 1324 } 1325 /* Assume for now it is an elif */ 1326 isElif = TRUE; 1327 } else 1328 isElif = FALSE; 1329 1330 if (line[0] != 'i' || line[1] != 'f') 1331 /* Not an ifxxx or elifxxx line */ 1332 return COND_INVALID; 1333 1334 /* 1335 * Figure out what sort of conditional it is -- what its default 1336 * function is, etc. -- by looking in the table of valid "ifs" 1337 */ 1338 line += 2; 1339 for (ifp = ifs; ; ifp++) { 1340 if (ifp->form == NULL) 1341 return COND_INVALID; 1342 if (istoken(ifp->form, line, ifp->formlen)) { 1343 line += ifp->formlen; 1344 break; 1345 } 1346 } 1347 1348 /* Now we know what sort of 'if' it is... */ 1349 1350 if (isElif) { 1351 if (cond_depth == cond_min_depth) { 1352 Parse_Error(level, "if-less elif"); 1353 return COND_PARSE; 1354 } 1355 state = cond_state[cond_depth]; 1356 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) { 1357 Parse_Error(PARSE_WARNING, "extra elif"); 1358 cond_state[cond_depth] = SKIP_TO_ENDIF; 1359 return COND_SKIP; 1360 } 1361 if (state != SEARCH_FOR_ELIF) { 1362 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */ 1363 cond_state[cond_depth] = SKIP_TO_ELSE; 1364 return COND_SKIP; 1365 } 1366 } else { 1367 /* Normal .if */ 1368 if (cond_depth + 1 >= max_if_depth) { 1369 /* 1370 * This is rare, but not impossible. 1371 * In meta mode, dirdeps.mk (only runs at level 0) 1372 * can need more than the default. 1373 */ 1374 max_if_depth += MAXIF_BUMP; 1375 cond_state = bmake_realloc(cond_state, max_if_depth * 1376 sizeof(*cond_state)); 1377 } 1378 state = cond_state[cond_depth]; 1379 cond_depth++; 1380 if (state > ELSE_ACTIVE) { 1381 /* If we aren't parsing the data, treat as always false */ 1382 cond_state[cond_depth] = SKIP_TO_ELSE; 1383 return COND_SKIP; 1384 } 1385 } 1386 1387 /* And evaluate the conditional expresssion */ 1388 if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) { 1389 /* Syntax error in conditional, error message already output. */ 1390 /* Skip everything to matching .endif */ 1391 cond_state[cond_depth] = SKIP_TO_ELSE; 1392 return COND_SKIP; 1393 } 1394 1395 if (!value) { 1396 cond_state[cond_depth] = SEARCH_FOR_ELIF; 1397 return COND_SKIP; 1398 } 1399 cond_state[cond_depth] = IF_ACTIVE; 1400 return COND_PARSE; 1401 } 1402 1403 1404 1405 /*- 1406 *----------------------------------------------------------------------- 1407 * Cond_End -- 1408 * Make sure everything's clean at the end of a makefile. 1409 * 1410 * Results: 1411 * None. 1412 * 1413 * Side Effects: 1414 * Parse_Error will be called if open conditionals are around. 1415 * 1416 *----------------------------------------------------------------------- 1417 */ 1418 void 1419 Cond_restore_depth(unsigned int saved_depth) 1420 { 1421 int open_conds = cond_depth - cond_min_depth; 1422 1423 if (open_conds != 0 || saved_depth > cond_depth) { 1424 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds, 1425 open_conds == 1 ? "" : "s"); 1426 cond_depth = cond_min_depth; 1427 } 1428 1429 cond_min_depth = saved_depth; 1430 } 1431 1432 unsigned int 1433 Cond_save_depth(void) 1434 { 1435 int depth = cond_min_depth; 1436 1437 cond_min_depth = cond_depth; 1438 return depth; 1439 } 1440