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