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