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