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