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