cond.c revision 1.79 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 /*-
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 (!doEval) {
748 t = TOK_FALSE;
749 goto done;
750 }
751
752 if (rhsQuoted || lhsQuoted) {
753 do_string_compare:
754 if (((*op != '!') && (*op != '=')) || (op[1] != '=')) {
755 Parse_Error(PARSE_WARNING,
756 "String comparison operator should be either == or !=");
757 goto done;
758 }
759
760 if (DEBUG(COND)) {
761 fprintf(debug_file, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n",
762 lhs, rhs, op);
763 }
764 /*
765 * Null-terminate rhs and perform the comparison.
766 * t is set to the result.
767 */
768 if (*op == '=') {
769 t = strcmp(lhs, rhs) == 0;
770 } else {
771 t = strcmp(lhs, rhs) != 0;
772 }
773 } else {
774 /*
775 * rhs is either a float or an integer. Convert both the
776 * lhs and the rhs to a double and compare the two.
777 */
778
779 if (!CondCvtArg(lhs, &left) || !CondCvtArg(rhs, &right))
780 goto do_string_compare;
781
782 if (DEBUG(COND)) {
783 fprintf(debug_file, "left = %f, right = %f, op = %.2s\n", left,
784 right, op);
785 }
786 switch(op[0]) {
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 Parse_Error(PARSE_WARNING,
798 "Unknown operator");
799 goto done;
800 }
801 t = (left == right);
802 break;
803 case '<':
804 if (op[1] == '=') {
805 t = (left <= right);
806 } else {
807 t = (left < right);
808 }
809 break;
810 case '>':
811 if (op[1] == '=') {
812 t = (left >= right);
813 } else {
814 t = (left > right);
815 }
816 break;
817 }
818 }
819
820 done:
821 free(lhsFree);
822 free(rhsFree);
823 return t;
824 }
825
826 static int
827 get_mpt_arg(Boolean doEval, char **linePtr, char **argPtr, const char *func MAKE_ATTR_UNUSED)
828 {
829 /*
830 * Use Var_Parse to parse the spec in parens and return
831 * TOK_TRUE if the resulting string is empty.
832 */
833 int length;
834 void *freeIt;
835 char *val;
836 char *cp = *linePtr;
837
838 /* We do all the work here and return the result as the length */
839 *argPtr = NULL;
840
841 val = Var_Parse(cp - 1, VAR_CMD, doEval ? VARF_WANTRES : 0, &length, &freeIt);
842 /*
843 * Advance *linePtr to beyond the closing ). Note that
844 * we subtract one because 'length' is calculated from 'cp - 1'.
845 */
846 *linePtr = cp - 1 + length;
847
848 if (val == var_Error) {
849 free(freeIt);
850 return -1;
851 }
852
853 /* A variable is empty when it just contains spaces... 4/15/92, christos */
854 while (isspace(*(unsigned char *)val))
855 val++;
856
857 /*
858 * For consistency with the other functions we can't generate the
859 * true/false here.
860 */
861 length = *val ? 2 : 1;
862 free(freeIt);
863 return length;
864 }
865
866 static Boolean
867 CondDoEmpty(int arglen, const char *arg MAKE_ATTR_UNUSED)
868 {
869 return arglen == 1;
870 }
871
872 static Token
873 compare_function(Boolean doEval)
874 {
875 static const struct fn_def {
876 const char *fn_name;
877 int fn_name_len;
878 int (*fn_getarg)(Boolean, char **, char **, const char *);
879 Boolean (*fn_proc)(int, const char *);
880 } fn_defs[] = {
881 { "defined", 7, CondGetArg, CondDoDefined },
882 { "make", 4, CondGetArg, CondDoMake },
883 { "exists", 6, CondGetArg, CondDoExists },
884 { "empty", 5, get_mpt_arg, CondDoEmpty },
885 { "target", 6, CondGetArg, CondDoTarget },
886 { "commands", 8, CondGetArg, CondDoCommands },
887 { NULL, 0, NULL, NULL },
888 };
889 const struct fn_def *fn_def;
890 Token t;
891 char *arg = NULL;
892 int arglen;
893 char *cp = condExpr;
894 char *cp1;
895
896 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
897 if (!istoken(cp, fn_def->fn_name, fn_def->fn_name_len))
898 continue;
899 cp += fn_def->fn_name_len;
900 /* There can only be whitespace before the '(' */
901 while (isspace(*(unsigned char *)cp))
902 cp++;
903 if (*cp != '(')
904 break;
905
906 arglen = fn_def->fn_getarg(doEval, &cp, &arg, fn_def->fn_name);
907 if (arglen <= 0) {
908 condExpr = cp;
909 return arglen < 0 ? TOK_ERROR : TOK_FALSE;
910 }
911 /* Evaluate the argument using the required function. */
912 t = !doEval || fn_def->fn_proc(arglen, arg);
913 free(arg);
914 condExpr = cp;
915 return t;
916 }
917
918 /* Push anything numeric through the compare expression */
919 cp = condExpr;
920 if (isdigit((unsigned char)cp[0]) || strchr("+-", cp[0]))
921 return compare_expression(doEval);
922
923 /*
924 * Most likely we have a naked token to apply the default function to.
925 * However ".if a == b" gets here when the "a" is unquoted and doesn't
926 * start with a '$'. This surprises people.
927 * If what follows the function argument is a '=' or '!' then the syntax
928 * would be invalid if we did "defined(a)" - so instead treat as an
929 * expression.
930 */
931 arglen = CondGetArg(doEval, &cp, &arg, NULL);
932 for (cp1 = cp; isspace(*(unsigned char *)cp1); cp1++)
933 continue;
934 if (*cp1 == '=' || *cp1 == '!')
935 return compare_expression(doEval);
936 condExpr = cp;
937
938 /*
939 * Evaluate the argument using the default function.
940 * This path always treats .if as .ifdef. To get here the character
941 * after .if must have been taken literally, so the argument cannot
942 * be empty - even if it contained a variable expansion.
943 */
944 t = !doEval || if_info->defProc(arglen, arg) != if_info->doNot;
945 free(arg);
946 return t;
947 }
948
949 static Token
950 CondToken(Boolean doEval)
951 {
952 Token t;
953
954 t = condPushBack;
955 if (t != TOK_NONE) {
956 condPushBack = TOK_NONE;
957 return t;
958 }
959
960 while (*condExpr == ' ' || *condExpr == '\t') {
961 condExpr++;
962 }
963
964 switch (*condExpr) {
965
966 case '(':
967 condExpr++;
968 return TOK_LPAREN;
969
970 case ')':
971 condExpr++;
972 return TOK_RPAREN;
973
974 case '|':
975 if (condExpr[1] == '|') {
976 condExpr++;
977 }
978 condExpr++;
979 return TOK_OR;
980
981 case '&':
982 if (condExpr[1] == '&') {
983 condExpr++;
984 }
985 condExpr++;
986 return TOK_AND;
987
988 case '!':
989 condExpr++;
990 return TOK_NOT;
991
992 case '#':
993 case '\n':
994 case '\0':
995 return TOK_EOF;
996
997 case '"':
998 case '$':
999 return compare_expression(doEval);
1000
1001 default:
1002 return compare_function(doEval);
1003 }
1004 }
1005
1006 /*-
1007 *-----------------------------------------------------------------------
1008 * CondT --
1009 * Parse a single term in the expression. This consists of a terminal
1010 * symbol or TOK_NOT and a terminal symbol (not including the binary
1011 * operators):
1012 * T -> defined(variable) | make(target) | exists(file) | symbol
1013 * T -> ! T | ( E )
1014 *
1015 * Results:
1016 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1017 *
1018 * Side Effects:
1019 * Tokens are consumed.
1020 *
1021 *-----------------------------------------------------------------------
1022 */
1023 static Token
1024 CondT(Boolean doEval)
1025 {
1026 Token t;
1027
1028 t = CondToken(doEval);
1029
1030 if (t == TOK_EOF) {
1031 /*
1032 * If we reached the end of the expression, the expression
1033 * is malformed...
1034 */
1035 t = TOK_ERROR;
1036 } else if (t == TOK_LPAREN) {
1037 /*
1038 * T -> ( E )
1039 */
1040 t = CondE(doEval);
1041 if (t != TOK_ERROR) {
1042 if (CondToken(doEval) != TOK_RPAREN) {
1043 t = TOK_ERROR;
1044 }
1045 }
1046 } else if (t == TOK_NOT) {
1047 t = CondT(doEval);
1048 if (t == TOK_TRUE) {
1049 t = TOK_FALSE;
1050 } else if (t == TOK_FALSE) {
1051 t = TOK_TRUE;
1052 }
1053 }
1054 return t;
1055 }
1056
1057 /*-
1059 *-----------------------------------------------------------------------
1060 * CondF --
1061 * Parse a conjunctive factor (nice name, wot?)
1062 * F -> T && F | T
1063 *
1064 * Results:
1065 * TOK_TRUE, TOK_FALSE or TOK_ERROR
1066 *
1067 * Side Effects:
1068 * Tokens are consumed.
1069 *
1070 *-----------------------------------------------------------------------
1071 */
1072 static Token
1073 CondF(Boolean doEval)
1074 {
1075 Token l, o;
1076
1077 l = CondT(doEval);
1078 if (l != TOK_ERROR) {
1079 o = CondToken(doEval);
1080
1081 if (o == TOK_AND) {
1082 /*
1083 * F -> T && F
1084 *
1085 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we have to
1086 * parse the r.h.s. anyway (to throw it away).
1087 * If T is TOK_TRUE, the result is the r.h.s., be it an TOK_ERROR or no.
1088 */
1089 if (l == TOK_TRUE) {
1090 l = CondF(doEval);
1091 } else {
1092 (void)CondF(FALSE);
1093 }
1094 } else {
1095 /*
1096 * F -> T
1097 */
1098 CondPushBack(o);
1099 }
1100 }
1101 return l;
1102 }
1103
1104 /*-
1106 *-----------------------------------------------------------------------
1107 * CondE --
1108 * Main expression production.
1109 * E -> F || E | F
1110 *
1111 * Results:
1112 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
1113 *
1114 * Side Effects:
1115 * Tokens are, of course, consumed.
1116 *
1117 *-----------------------------------------------------------------------
1118 */
1119 static Token
1120 CondE(Boolean doEval)
1121 {
1122 Token l, o;
1123
1124 l = CondF(doEval);
1125 if (l != TOK_ERROR) {
1126 o = CondToken(doEval);
1127
1128 if (o == TOK_OR) {
1129 /*
1130 * E -> F || E
1131 *
1132 * A similar thing occurs for ||, except that here we make sure
1133 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
1134 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
1135 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
1136 */
1137 if (l == TOK_FALSE) {
1138 l = CondE(doEval);
1139 } else {
1140 (void)CondE(FALSE);
1141 }
1142 } else {
1143 /*
1144 * E -> F
1145 */
1146 CondPushBack(o);
1147 }
1148 }
1149 return l;
1150 }
1151
1152 /*-
1153 *-----------------------------------------------------------------------
1154 * Cond_EvalExpression --
1155 * Evaluate an expression in the passed line. The expression
1156 * consists of &&, ||, !, make(target), defined(variable)
1157 * and parenthetical groupings thereof.
1158 *
1159 * Results:
1160 * COND_PARSE if the condition was valid grammatically
1161 * COND_INVALID if not a valid conditional.
1162 *
1163 * (*value) is set to the boolean value of the condition
1164 *
1165 * Side Effects:
1166 * None.
1167 *
1168 *-----------------------------------------------------------------------
1169 */
1170 int
1171 Cond_EvalExpression(const struct If *info, char *line, Boolean *value, int eprint, Boolean strictLHS)
1172 {
1173 static const struct If *dflt_info;
1174 const struct If *sv_if_info = if_info;
1175 char *sv_condExpr = condExpr;
1176 Token sv_condPushBack = condPushBack;
1177 int rval;
1178
1179 lhsStrict = strictLHS;
1180
1181 while (*line == ' ' || *line == '\t')
1182 line++;
1183
1184 if (info == NULL && (info = dflt_info) == NULL) {
1185 /* Scan for the entry for .if - it can't be first */
1186 for (info = ifs; ; info++)
1187 if (info->form[0] == 0)
1188 break;
1189 dflt_info = info;
1190 }
1191 assert(info != NULL);
1192
1193 if_info = info;
1194 condExpr = line;
1195 condPushBack = TOK_NONE;
1196
1197 rval = do_Cond_EvalExpression(value);
1198
1199 if (rval == COND_INVALID && eprint)
1200 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", line);
1201
1202 if_info = sv_if_info;
1203 condExpr = sv_condExpr;
1204 condPushBack = sv_condPushBack;
1205
1206 return rval;
1207 }
1208
1209 static int
1210 do_Cond_EvalExpression(Boolean *value)
1211 {
1212
1213 switch (CondE(TRUE)) {
1214 case TOK_TRUE:
1215 if (CondToken(TRUE) == TOK_EOF) {
1216 *value = TRUE;
1217 return COND_PARSE;
1218 }
1219 break;
1220 case TOK_FALSE:
1221 if (CondToken(TRUE) == TOK_EOF) {
1222 *value = FALSE;
1223 return COND_PARSE;
1224 }
1225 break;
1226 default:
1227 case TOK_ERROR:
1228 break;
1229 }
1230
1231 return COND_INVALID;
1232 }
1233
1234
1235 /*-
1237 *-----------------------------------------------------------------------
1238 * Cond_Eval --
1239 * Evaluate the conditional in the passed line. The line
1240 * looks like this:
1241 * .<cond-type> <expr>
1242 * where <cond-type> is any of if, ifmake, ifnmake, ifdef,
1243 * ifndef, elif, elifmake, elifnmake, elifdef, elifndef
1244 * and <expr> consists of &&, ||, !, make(target), defined(variable)
1245 * and parenthetical groupings thereof.
1246 *
1247 * Input:
1248 * line Line to parse
1249 *
1250 * Results:
1251 * COND_PARSE if should parse lines after the conditional
1252 * COND_SKIP if should skip lines after the conditional
1253 * COND_INVALID if not a valid conditional.
1254 *
1255 * Side Effects:
1256 * None.
1257 *
1258 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1259 * to detect splurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF)
1260 * otherwise .else could be treated as '.elif 1'.
1261 *
1262 *-----------------------------------------------------------------------
1263 */
1264 int
1265 Cond_Eval(char *line)
1266 {
1267 #define MAXIF 128 /* maximum depth of .if'ing */
1268 #define MAXIF_BUMP 32 /* how much to grow by */
1269 enum if_states {
1270 IF_ACTIVE, /* .if or .elif part active */
1271 ELSE_ACTIVE, /* .else part active */
1272 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1273 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1274 SKIP_TO_ENDIF /* nothing else to execute */
1275 };
1276 static enum if_states *cond_state = NULL;
1277 static unsigned int max_if_depth = MAXIF;
1278
1279 const struct If *ifp;
1280 Boolean isElif;
1281 Boolean value;
1282 int level; /* Level at which to report errors. */
1283 enum if_states state;
1284
1285 level = PARSE_FATAL;
1286 if (!cond_state) {
1287 cond_state = bmake_malloc(max_if_depth * sizeof(*cond_state));
1288 cond_state[0] = IF_ACTIVE;
1289 }
1290 /* skip leading character (the '.') and any whitespace */
1291 for (line++; *line == ' ' || *line == '\t'; line++)
1292 continue;
1293
1294 /* Find what type of if we're dealing with. */
1295 if (line[0] == 'e') {
1296 if (line[1] != 'l') {
1297 if (!istoken(line + 1, "ndif", 4))
1298 return COND_INVALID;
1299 /* End of conditional section */
1300 if (cond_depth == cond_min_depth) {
1301 Parse_Error(level, "if-less endif");
1302 return COND_PARSE;
1303 }
1304 /* Return state for previous conditional */
1305 cond_depth--;
1306 return cond_state[cond_depth] <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1307 }
1308
1309 /* Quite likely this is 'else' or 'elif' */
1310 line += 2;
1311 if (istoken(line, "se", 2)) {
1312 /* It is else... */
1313 if (cond_depth == cond_min_depth) {
1314 Parse_Error(level, "if-less else");
1315 return COND_PARSE;
1316 }
1317
1318 state = cond_state[cond_depth];
1319 switch (state) {
1320 case SEARCH_FOR_ELIF:
1321 state = ELSE_ACTIVE;
1322 break;
1323 case ELSE_ACTIVE:
1324 case SKIP_TO_ENDIF:
1325 Parse_Error(PARSE_WARNING, "extra else");
1326 /* FALLTHROUGH */
1327 default:
1328 case IF_ACTIVE:
1329 case SKIP_TO_ELSE:
1330 state = SKIP_TO_ENDIF;
1331 break;
1332 }
1333 cond_state[cond_depth] = state;
1334 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1335 }
1336 /* Assume for now it is an elif */
1337 isElif = TRUE;
1338 } else
1339 isElif = FALSE;
1340
1341 if (line[0] != 'i' || line[1] != 'f')
1342 /* Not an ifxxx or elifxxx line */
1343 return COND_INVALID;
1344
1345 /*
1346 * Figure out what sort of conditional it is -- what its default
1347 * function is, etc. -- by looking in the table of valid "ifs"
1348 */
1349 line += 2;
1350 for (ifp = ifs; ; ifp++) {
1351 if (ifp->form == NULL)
1352 return COND_INVALID;
1353 if (istoken(ifp->form, line, ifp->formlen)) {
1354 line += ifp->formlen;
1355 break;
1356 }
1357 }
1358
1359 /* Now we know what sort of 'if' it is... */
1360
1361 if (isElif) {
1362 if (cond_depth == cond_min_depth) {
1363 Parse_Error(level, "if-less elif");
1364 return COND_PARSE;
1365 }
1366 state = cond_state[cond_depth];
1367 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1368 Parse_Error(PARSE_WARNING, "extra elif");
1369 cond_state[cond_depth] = SKIP_TO_ENDIF;
1370 return COND_SKIP;
1371 }
1372 if (state != SEARCH_FOR_ELIF) {
1373 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1374 cond_state[cond_depth] = SKIP_TO_ELSE;
1375 return COND_SKIP;
1376 }
1377 } else {
1378 /* Normal .if */
1379 if (cond_depth + 1 >= max_if_depth) {
1380 /*
1381 * This is rare, but not impossible.
1382 * In meta mode, dirdeps.mk (only runs at level 0)
1383 * can need more than the default.
1384 */
1385 max_if_depth += MAXIF_BUMP;
1386 cond_state = bmake_realloc(cond_state, max_if_depth *
1387 sizeof(*cond_state));
1388 }
1389 state = cond_state[cond_depth];
1390 cond_depth++;
1391 if (state > ELSE_ACTIVE) {
1392 /* If we aren't parsing the data, treat as always false */
1393 cond_state[cond_depth] = SKIP_TO_ELSE;
1394 return COND_SKIP;
1395 }
1396 }
1397
1398 /* And evaluate the conditional expresssion */
1399 if (Cond_EvalExpression(ifp, line, &value, 1, TRUE) == COND_INVALID) {
1400 /* Syntax error in conditional, error message already output. */
1401 /* Skip everything to matching .endif */
1402 cond_state[cond_depth] = SKIP_TO_ELSE;
1403 return COND_SKIP;
1404 }
1405
1406 if (!value) {
1407 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1408 return COND_SKIP;
1409 }
1410 cond_state[cond_depth] = IF_ACTIVE;
1411 return COND_PARSE;
1412 }
1413
1414
1415
1416 /*-
1418 *-----------------------------------------------------------------------
1419 * Cond_End --
1420 * Make sure everything's clean at the end of a makefile.
1421 *
1422 * Results:
1423 * None.
1424 *
1425 * Side Effects:
1426 * Parse_Error will be called if open conditionals are around.
1427 *
1428 *-----------------------------------------------------------------------
1429 */
1430 void
1431 Cond_restore_depth(unsigned int saved_depth)
1432 {
1433 int open_conds = cond_depth - cond_min_depth;
1434
1435 if (open_conds != 0 || saved_depth > cond_depth) {
1436 Parse_Error(PARSE_FATAL, "%d open conditional%s", open_conds,
1437 open_conds == 1 ? "" : "s");
1438 cond_depth = cond_min_depth;
1439 }
1440
1441 cond_min_depth = saved_depth;
1442 }
1443
1444 unsigned int
1445 Cond_save_depth(void)
1446 {
1447 int depth = cond_min_depth;
1448
1449 cond_min_depth = cond_depth;
1450 return depth;
1451 }
1452