cond.c revision 1.191 1 /* $NetBSD: cond.c,v 1.191 2020/11/08 22:41:40 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 /*
36 * Copyright (c) 1988, 1989 by Adam de Boor
37 * Copyright (c) 1989 by Berkeley Softworks
38 * All rights reserved.
39 *
40 * This code is derived from software contributed to Berkeley by
41 * Adam de Boor.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. All advertising materials mentioning features or use of this software
52 * must display the following acknowledgement:
53 * This product includes software developed by the University of
54 * California, Berkeley and its contributors.
55 * 4. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 */
71
72 /* Handling of conditionals in a makefile.
73 *
74 * Interface:
75 * Cond_EvalLine Evaluate the conditional.
76 *
77 * Cond_EvalCondition
78 * Evaluate the conditional, which is either the argument
79 * of one of the .if directives or the condition in a
80 * ':?then:else' variable modifier.
81 *
82 * Cond_save_depth
83 * Cond_restore_depth
84 * Save and restore the nesting of the conditions, at
85 * the start and end of including another makefile, to
86 * ensure that in each makefile the conditional
87 * directives are well-balanced.
88 */
89
90 #include <errno.h>
91
92 #include "make.h"
93 #include "dir.h"
94
95 /* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
96 MAKE_RCSID("$NetBSD: cond.c,v 1.191 2020/11/08 22:41:40 rillig Exp $");
97
98 /*
99 * The parsing of conditional expressions is based on this grammar:
100 * E -> F || E
101 * E -> F
102 * F -> T && F
103 * F -> T
104 * T -> defined(variable)
105 * T -> make(target)
106 * T -> exists(file)
107 * T -> empty(varspec)
108 * T -> target(name)
109 * T -> commands(name)
110 * T -> symbol
111 * T -> $(varspec) op value
112 * T -> $(varspec) == "string"
113 * T -> $(varspec) != "string"
114 * T -> "string"
115 * T -> ( E )
116 * T -> ! T
117 * op -> == | != | > | < | >= | <=
118 *
119 * 'symbol' is some other symbol to which the default function is applied.
120 *
121 * The tokens are scanned by CondToken, which returns:
122 * TOK_AND for '&' or '&&'
123 * TOK_OR for '|' or '||'
124 * TOK_NOT for '!'
125 * TOK_LPAREN for '('
126 * TOK_RPAREN for ')'
127 * Other terminal symbols are evaluated using either the default function or
128 * the function given in the terminal, they return either TOK_TRUE or
129 * TOK_FALSE.
130 *
131 * TOK_FALSE is 0 and TOK_TRUE 1 so we can directly assign C comparisons.
132 *
133 * All non-terminal functions (CondParser_Expr, CondParser_Factor and
134 * CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
135 */
136 typedef enum Token {
137 TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
138 TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
139 } Token;
140
141 typedef struct CondParser {
142 const struct If *if_info; /* Info for current statement */
143 const char *p; /* The remaining condition to parse */
144 Token curr; /* Single push-back token used in parsing */
145
146 /* Whether an error message has already been printed for this condition.
147 * The first available error message is usually the most specific one,
148 * therefore it makes sense to suppress the standard "Malformed
149 * conditional" message. */
150 Boolean printedError;
151 } CondParser;
152
153 static Token CondParser_Expr(CondParser *par, Boolean);
154
155 static unsigned int cond_depth = 0; /* current .if nesting level */
156 static unsigned int cond_min_depth = 0; /* depth at makefile open */
157
158 /*
159 * Indicate when we should be strict about lhs of comparisons.
160 * In strict mode, the lhs must be a variable expression or a string literal
161 * in quotes. In non-strict mode it may also be an unquoted string literal.
162 *
163 * TRUE when CondEvalExpression is called from Cond_EvalLine (.if etc)
164 * FALSE when CondEvalExpression is called from ApplyModifier_IfElse
165 * since lhs is already expanded, and at that point we cannot tell if
166 * it was a variable reference or not.
167 */
168 static Boolean lhsStrict;
169
170 static int
171 is_token(const char *str, const char *tok, size_t len)
172 {
173 return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
174 }
175
176 static Token
177 ToToken(Boolean cond)
178 {
179 return cond ? TOK_TRUE : TOK_FALSE;
180 }
181
182 /* Push back the most recent token read. We only need one level of this. */
183 static void
184 CondParser_PushBack(CondParser *par, Token t)
185 {
186 assert(par->curr == TOK_NONE);
187 assert(t != TOK_NONE);
188
189 par->curr = t;
190 }
191
192 static void
193 CondParser_SkipWhitespace(CondParser *par)
194 {
195 cpp_skip_whitespace(&par->p);
196 }
197
198 /* Parse the argument of a built-in function.
199 *
200 * Arguments:
201 * *pp initially points at the '(',
202 * upon successful return it points right after the ')'.
203 *
204 * *out_arg receives the argument as string.
205 *
206 * func says whether the argument belongs to an actual function, or
207 * whether the parsed argument is passed to the default function.
208 *
209 * Return the length of the argument, or 0 on error. */
210 static size_t
211 ParseFuncArg(const char **pp, Boolean doEval, const char *func,
212 char **out_arg) {
213 const char *p = *pp;
214 Buffer argBuf;
215 int paren_depth;
216 size_t argLen;
217
218 if (func != NULL)
219 p++; /* Skip opening '(' - verified by caller */
220
221 if (*p == '\0') {
222 /*
223 * No arguments whatsoever. Because 'make' and 'defined' aren't really
224 * "reserved words", we don't print a message. I think this is better
225 * than hitting the user with a warning message every time s/he uses
226 * the word 'make' or 'defined' at the beginning of a symbol...
227 */
228 *out_arg = NULL;
229 return 0;
230 }
231
232 cpp_skip_hspace(&p);
233
234 Buf_InitSize(&argBuf, 16);
235
236 paren_depth = 0;
237 for (;;) {
238 char ch = *p;
239 if (ch == '\0' || ch == ' ' || ch == '\t')
240 break;
241 if ((ch == '&' || ch == '|') && paren_depth == 0)
242 break;
243 if (*p == '$') {
244 /*
245 * Parse the variable spec and install it as part of the argument
246 * if it's valid. We tell Var_Parse to complain on an undefined
247 * variable, so we don't need to do it. Nor do we return an error,
248 * though perhaps we should...
249 */
250 void *nestedVal_freeIt;
251 VarEvalFlags eflags = doEval ? VARE_WANTRES | VARE_UNDEFERR
252 : VARE_NONE;
253 const char *nestedVal;
254 (void)Var_Parse(&p, VAR_CMDLINE, eflags, &nestedVal,
255 &nestedVal_freeIt);
256 /* TODO: handle errors */
257 Buf_AddStr(&argBuf, nestedVal);
258 free(nestedVal_freeIt);
259 continue;
260 }
261 if (ch == '(')
262 paren_depth++;
263 else if (ch == ')' && --paren_depth < 0)
264 break;
265 Buf_AddByte(&argBuf, *p);
266 p++;
267 }
268
269 *out_arg = Buf_GetAll(&argBuf, &argLen);
270 Buf_Destroy(&argBuf, FALSE);
271
272 cpp_skip_hspace(&p);
273
274 if (func != NULL && *p++ != ')') {
275 Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
276 func);
277 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
278 return 0;
279 }
280
281 *pp = p;
282 return argLen;
283 }
284
285 /* Test whether the given variable is defined. */
286 static Boolean
287 FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
288 {
289 void *freeIt;
290 Boolean result = Var_Value(arg, VAR_CMDLINE, &freeIt) != NULL;
291 bmake_free(freeIt);
292 return result;
293 }
294
295 /* See if the given target is being made. */
296 static Boolean
297 FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
298 {
299 StringListNode *ln;
300
301 for (ln = opts.create->first; ln != NULL; ln = ln->next)
302 if (Str_Match(ln->datum, arg))
303 return TRUE;
304 return FALSE;
305 }
306
307 /* See if the given file exists. */
308 static Boolean
309 FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
310 {
311 Boolean result;
312 char *path;
313
314 path = Dir_FindFile(arg, dirSearchPath);
315 DEBUG2(COND, "exists(%s) result is \"%s\"\n",
316 arg, path != NULL ? path : "");
317 result = path != NULL;
318 free(path);
319 return result;
320 }
321
322 /* See if the given node exists and is an actual target. */
323 static Boolean
324 FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
325 {
326 GNode *gn = Targ_FindNode(arg);
327 return gn != NULL && GNode_IsTarget(gn);
328 }
329
330 /* See if the given node exists and is an actual target with commands
331 * associated with it. */
332 static Boolean
333 FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
334 {
335 GNode *gn = Targ_FindNode(arg);
336 return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(gn->commands);
337 }
338
339 /*
340 * Convert the given number into a double.
341 * We try a base 10 or 16 integer conversion first, if that fails
342 * then we try a floating point conversion instead.
343 *
344 * Results:
345 * Returns TRUE if the conversion succeeded.
346 * Sets 'out_value' to the converted number.
347 */
348 static Boolean
349 TryParseNumber(const char *str, double *out_value)
350 {
351 char *end;
352 unsigned long ul_val;
353 double dbl_val;
354
355 errno = 0;
356 if (str[0] == '\0') { /* XXX: why is an empty string a number? */
357 *out_value = 0.0;
358 return TRUE;
359 }
360
361 ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
362 if (*end == '\0' && errno != ERANGE) {
363 *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
364 return TRUE;
365 }
366
367 if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
368 return FALSE; /* skip the expensive strtod call */
369 dbl_val = strtod(str, &end);
370 if (*end != '\0')
371 return FALSE;
372
373 *out_value = dbl_val;
374 return TRUE;
375 }
376
377 static Boolean
378 is_separator(char ch)
379 {
380 return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
381 }
382
383 /*-
384 * Parse a string from a variable reference or an optionally quoted
385 * string. This is called for the lhs and rhs of string comparisons.
386 *
387 * Results:
388 * Returns the string, absent any quotes, or NULL on error.
389 * Sets out_quoted if the string was quoted.
390 * Sets out_freeIt.
391 */
392 /* coverity:[+alloc : arg-*4] */
393 static const char *
394 CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
395 Boolean *out_quoted, void **out_freeIt)
396 {
397 Buffer buf;
398 const char *str;
399 Boolean atStart;
400 const char *nested_p;
401 Boolean quoted;
402 const char *start;
403 VarEvalFlags eflags;
404 VarParseResult parseResult;
405
406 Buf_Init(&buf);
407 str = NULL;
408 *out_freeIt = NULL;
409 *out_quoted = quoted = par->p[0] == '"';
410 start = par->p;
411 if (quoted)
412 par->p++;
413 while (par->p[0] != '\0' && str == NULL) {
414 switch (par->p[0]) {
415 case '\\':
416 par->p++;
417 if (par->p[0] != '\0') {
418 Buf_AddByte(&buf, par->p[0]);
419 par->p++;
420 }
421 continue;
422 case '"':
423 if (quoted) {
424 par->p++; /* skip the closing quote */
425 goto got_str;
426 }
427 Buf_AddByte(&buf, par->p[0]); /* likely? */
428 par->p++;
429 continue;
430 case ')': /* see is_separator */
431 case '!':
432 case '=':
433 case '>':
434 case '<':
435 case ' ':
436 case '\t':
437 if (!quoted)
438 goto got_str;
439 Buf_AddByte(&buf, par->p[0]);
440 par->p++;
441 continue;
442 case '$':
443 /* if we are in quotes, an undefined variable is ok */
444 eflags = doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR :
445 doEval ? VARE_WANTRES :
446 VARE_NONE;
447
448 nested_p = par->p;
449 atStart = nested_p == start;
450 parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags, &str,
451 out_freeIt);
452 /* TODO: handle errors */
453 if (str == var_Error) {
454 if (parseResult & VPR_ANY_MSG)
455 par->printedError = TRUE;
456 if (*out_freeIt != NULL) {
457 free(*out_freeIt);
458 *out_freeIt = NULL;
459 }
460 /*
461 * Even if !doEval, we still report syntax errors, which
462 * is what getting var_Error back with !doEval means.
463 */
464 str = NULL;
465 goto cleanup;
466 }
467 par->p = nested_p;
468
469 /*
470 * If the '$' started the string literal (which means no quotes),
471 * and the variable expression is followed by a space, looks like
472 * a comparison operator or is the end of the expression, we are
473 * done.
474 */
475 if (atStart && is_separator(par->p[0]))
476 goto cleanup;
477
478 Buf_AddStr(&buf, str);
479 if (*out_freeIt) {
480 free(*out_freeIt);
481 *out_freeIt = NULL;
482 }
483 str = NULL; /* not finished yet */
484 continue;
485 default:
486 if (strictLHS && !quoted && *start != '$' && !ch_isdigit(*start)) {
487 /* lhs must be quoted, a variable reference or number */
488 if (*out_freeIt) {
489 free(*out_freeIt);
490 *out_freeIt = NULL;
491 }
492 str = NULL;
493 goto cleanup;
494 }
495 Buf_AddByte(&buf, par->p[0]);
496 par->p++;
497 continue;
498 }
499 }
500 got_str:
501 *out_freeIt = Buf_GetAll(&buf, NULL);
502 str = *out_freeIt;
503 cleanup:
504 Buf_Destroy(&buf, FALSE);
505 return str;
506 }
507
508 struct If {
509 const char *form; /* Form of if */
510 size_t formlen; /* Length of form */
511 Boolean doNot; /* TRUE if default function should be negated */
512 Boolean (*defProc)(size_t, const char *); /* Default function to apply */
513 };
514
515 /* The different forms of .if directives. */
516 static const struct If ifs[] = {
517 { "def", 3, FALSE, FuncDefined },
518 { "ndef", 4, TRUE, FuncDefined },
519 { "make", 4, FALSE, FuncMake },
520 { "nmake", 5, TRUE, FuncMake },
521 { "", 0, FALSE, FuncDefined },
522 { NULL, 0, FALSE, NULL }
523 };
524
525 static Boolean
526 If_Eval(const struct If *if_info, const char *arg, size_t arglen)
527 {
528 Boolean res = if_info->defProc(arglen, arg);
529 return if_info->doNot ? !res : res;
530 }
531
532 /* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
533 * ".if 0". */
534 static Boolean
535 EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
536 {
537 double left;
538
539 /* For .ifxxx "...", check for non-empty string. */
540 if (quoted)
541 return value[0] != '\0';
542
543 /* For .ifxxx <number>, compare against zero */
544 if (TryParseNumber(value, &left))
545 return left != 0.0;
546
547 /* For .if ${...}, check for non-empty string (defProc is ifdef). */
548 if (par->if_info->form[0] == '\0')
549 return value[0] != '\0';
550
551 /* Otherwise action default test ... */
552 return If_Eval(par->if_info, value, strlen(value));
553 }
554
555 /* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
556 static Token
557 EvalCompareNum(double lhs, const char *op, double rhs)
558 {
559 DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
560
561 switch (op[0]) {
562 case '!':
563 if (op[1] != '=') {
564 Parse_Error(PARSE_WARNING, "Unknown operator");
565 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
566 return TOK_ERROR;
567 }
568 return ToToken(lhs != rhs);
569 case '=':
570 if (op[1] != '=') {
571 Parse_Error(PARSE_WARNING, "Unknown operator");
572 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
573 return TOK_ERROR;
574 }
575 return ToToken(lhs == rhs);
576 case '<':
577 return ToToken(op[1] == '=' ? lhs <= rhs : lhs < rhs);
578 case '>':
579 return ToToken(op[1] == '=' ? lhs >= rhs : lhs > rhs);
580 }
581 return TOK_ERROR;
582 }
583
584 static Token
585 EvalCompareStr(const char *lhs, const char *op, const char *rhs)
586 {
587 if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
588 Parse_Error(PARSE_WARNING,
589 "String comparison operator must be either == or !=");
590 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
591 return TOK_ERROR;
592 }
593
594 DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
595 return ToToken((*op == '=') == (strcmp(lhs, rhs) == 0));
596 }
597
598 /* Evaluate a comparison, such as "${VAR} == 12345". */
599 static Token
600 EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
601 const char *rhs, Boolean rhsQuoted)
602 {
603 double left, right;
604
605 if (!rhsQuoted && !lhsQuoted)
606 if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
607 return EvalCompareNum(left, op, right);
608
609 return EvalCompareStr(lhs, op, rhs);
610 }
611
612 /* Parse a comparison condition such as:
613 *
614 * 0
615 * ${VAR:Mpattern}
616 * ${VAR} == value
617 * ${VAR:U0} < 12345
618 */
619 static Token
620 CondParser_Comparison(CondParser *par, Boolean doEval)
621 {
622 Token t = TOK_ERROR;
623 const char *lhs, *op, *rhs;
624 void *lhs_freeIt, *rhs_freeIt;
625 Boolean lhsQuoted, rhsQuoted;
626
627 /*
628 * Parse the variable spec and skip over it, saving its
629 * value in lhs.
630 */
631 lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhs_freeIt);
632 if (lhs == NULL)
633 goto done_lhs;
634
635 CondParser_SkipWhitespace(par);
636
637 op = par->p;
638 switch (par->p[0]) {
639 case '!':
640 case '=':
641 case '<':
642 case '>':
643 if (par->p[1] == '=')
644 par->p += 2;
645 else
646 par->p++;
647 break;
648 default:
649 /* Unknown operator, compare against an empty string or 0. */
650 t = ToToken(doEval && EvalNotEmpty(par, lhs, lhsQuoted));
651 goto done_lhs;
652 }
653
654 CondParser_SkipWhitespace(par);
655
656 if (par->p[0] == '\0') {
657 Parse_Error(PARSE_WARNING, "Missing right-hand-side of operator");
658 /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
659 goto done_lhs;
660 }
661
662 rhs = CondParser_String(par, doEval, FALSE, &rhsQuoted, &rhs_freeIt);
663 if (rhs == NULL)
664 goto done_rhs;
665
666 if (!doEval) {
667 t = TOK_FALSE;
668 goto done_rhs;
669 }
670
671 t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
672
673 done_rhs:
674 free(rhs_freeIt);
675 done_lhs:
676 free(lhs_freeIt);
677 return t;
678 }
679
680 static size_t
681 ParseEmptyArg(const char **pp, Boolean doEval,
682 const char *func MAKE_ATTR_UNUSED, char **out_arg)
683 {
684 void *val_freeIt;
685 const char *val;
686 size_t magic_res;
687
688 /* We do all the work here and return the result as the length */
689 *out_arg = NULL;
690
691 (*pp)--; /* Make (*pp)[1] point to the '('. */
692 (void)Var_Parse(pp, VAR_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
693 &val, &val_freeIt);
694 /* TODO: handle errors */
695 /* If successful, *pp points beyond the closing ')' now. */
696
697 if (val == var_Error) {
698 free(val_freeIt);
699 return (size_t)-1;
700 }
701
702 /* A variable is empty when it just contains spaces... 4/15/92, christos */
703 cpp_skip_whitespace(&val);
704
705 /*
706 * For consistency with the other functions we can't generate the
707 * true/false here.
708 */
709 magic_res = *val != '\0' ? 2 : 1;
710 free(val_freeIt);
711 return magic_res;
712 }
713
714 static Boolean
715 FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
716 {
717 /* Magic values ahead, see ParseEmptyArg. */
718 return arglen == 1;
719 }
720
721 static Token
722 CondParser_Func(CondParser *par, Boolean doEval)
723 {
724 static const struct fn_def {
725 const char *fn_name;
726 size_t fn_name_len;
727 size_t (*fn_parse)(const char **, Boolean, const char *, char **);
728 Boolean (*fn_eval)(size_t, const char *);
729 } fn_defs[] = {
730 { "defined", 7, ParseFuncArg, FuncDefined },
731 { "make", 4, ParseFuncArg, FuncMake },
732 { "exists", 6, ParseFuncArg, FuncExists },
733 { "empty", 5, ParseEmptyArg, FuncEmpty },
734 { "target", 6, ParseFuncArg, FuncTarget },
735 { "commands", 8, ParseFuncArg, FuncCommands },
736 { NULL, 0, NULL, NULL },
737 };
738 const struct fn_def *fn_def;
739 Token t;
740 char *arg = NULL;
741 size_t arglen;
742 const char *cp = par->p;
743 const char *cp1;
744
745 for (fn_def = fn_defs; fn_def->fn_name != NULL; fn_def++) {
746 if (!is_token(cp, fn_def->fn_name, fn_def->fn_name_len))
747 continue;
748 cp += fn_def->fn_name_len;
749 /* There can only be whitespace before the '(' */
750 cpp_skip_whitespace(&cp);
751 if (*cp != '(')
752 break;
753
754 arglen = fn_def->fn_parse(&cp, doEval, fn_def->fn_name, &arg);
755 if (arglen == 0 || arglen == (size_t)-1) {
756 par->p = cp;
757 return arglen == 0 ? TOK_FALSE : TOK_ERROR;
758 }
759 /* Evaluate the argument using the required function. */
760 t = !doEval || fn_def->fn_eval(arglen, arg);
761 free(arg);
762 par->p = cp;
763 return t;
764 }
765
766 /* Push anything numeric through the compare expression */
767 cp = par->p;
768 if (ch_isdigit(cp[0]) || strchr("+-", cp[0]) != NULL)
769 return CondParser_Comparison(par, doEval);
770
771 /*
772 * Most likely we have a naked token to apply the default function to.
773 * However ".if a == b" gets here when the "a" is unquoted and doesn't
774 * start with a '$'. This surprises people.
775 * If what follows the function argument is a '=' or '!' then the syntax
776 * would be invalid if we did "defined(a)" - so instead treat as an
777 * expression.
778 */
779 arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
780 cp1 = cp;
781 cpp_skip_whitespace(&cp1);
782 if (*cp1 == '=' || *cp1 == '!')
783 return CondParser_Comparison(par, doEval);
784 par->p = cp;
785
786 /*
787 * Evaluate the argument using the default function.
788 * This path always treats .if as .ifdef. To get here, the character
789 * after .if must have been taken literally, so the argument cannot
790 * be empty - even if it contained a variable expansion.
791 */
792 t = !doEval || If_Eval(par->if_info, arg, arglen);
793 free(arg);
794 return t;
795 }
796
797 /* Return the next token or comparison result from the parser. */
798 static Token
799 CondParser_Token(CondParser *par, Boolean doEval)
800 {
801 Token t;
802
803 t = par->curr;
804 if (t != TOK_NONE) {
805 par->curr = TOK_NONE;
806 return t;
807 }
808
809 cpp_skip_hspace(&par->p);
810
811 switch (par->p[0]) {
812
813 case '(':
814 par->p++;
815 return TOK_LPAREN;
816
817 case ')':
818 par->p++;
819 return TOK_RPAREN;
820
821 case '|':
822 par->p++;
823 if (par->p[0] == '|') {
824 par->p++;
825 }
826 return TOK_OR;
827
828 case '&':
829 par->p++;
830 if (par->p[0] == '&') {
831 par->p++;
832 }
833 return TOK_AND;
834
835 case '!':
836 par->p++;
837 return TOK_NOT;
838
839 case '#':
840 case '\n':
841 case '\0':
842 return TOK_EOF;
843
844 case '"':
845 case '$':
846 return CondParser_Comparison(par, doEval);
847
848 default:
849 return CondParser_Func(par, doEval);
850 }
851 }
852
853 /* Parse a single term in the expression. This consists of a terminal symbol
854 * or TOK_NOT and a term (not including the binary operators):
855 *
856 * T -> defined(variable) | make(target) | exists(file) | symbol
857 * T -> ! T | ( E )
858 *
859 * Results:
860 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
861 */
862 static Token
863 CondParser_Term(CondParser *par, Boolean doEval)
864 {
865 Token t;
866
867 t = CondParser_Token(par, doEval);
868
869 if (t == TOK_EOF) {
870 /*
871 * If we reached the end of the expression, the expression
872 * is malformed...
873 */
874 t = TOK_ERROR;
875 } else if (t == TOK_LPAREN) {
876 /*
877 * T -> ( E )
878 */
879 t = CondParser_Expr(par, doEval);
880 if (t != TOK_ERROR) {
881 if (CondParser_Token(par, doEval) != TOK_RPAREN) {
882 t = TOK_ERROR;
883 }
884 }
885 } else if (t == TOK_NOT) {
886 t = CondParser_Term(par, doEval);
887 if (t == TOK_TRUE) {
888 t = TOK_FALSE;
889 } else if (t == TOK_FALSE) {
890 t = TOK_TRUE;
891 }
892 }
893 return t;
894 }
895
896 /* Parse a conjunctive factor (nice name, wot?)
897 *
898 * F -> T && F | T
899 *
900 * Results:
901 * TOK_TRUE, TOK_FALSE or TOK_ERROR
902 */
903 static Token
904 CondParser_Factor(CondParser *par, Boolean doEval)
905 {
906 Token l, o;
907
908 l = CondParser_Term(par, doEval);
909 if (l != TOK_ERROR) {
910 o = CondParser_Token(par, doEval);
911
912 if (o == TOK_AND) {
913 /*
914 * F -> T && F
915 *
916 * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we
917 * have to parse the r.h.s. anyway (to throw it away).
918 * If T is TOK_TRUE, the result is the r.h.s., be it a TOK_ERROR
919 * or not.
920 */
921 if (l == TOK_TRUE) {
922 l = CondParser_Factor(par, doEval);
923 } else {
924 (void)CondParser_Factor(par, FALSE);
925 }
926 } else {
927 /*
928 * F -> T
929 */
930 CondParser_PushBack(par, o);
931 }
932 }
933 return l;
934 }
935
936 /* Main expression production.
937 *
938 * E -> F || E | F
939 *
940 * Results:
941 * TOK_TRUE, TOK_FALSE or TOK_ERROR.
942 */
943 static Token
944 CondParser_Expr(CondParser *par, Boolean doEval)
945 {
946 Token l, o;
947
948 l = CondParser_Factor(par, doEval);
949 if (l != TOK_ERROR) {
950 o = CondParser_Token(par, doEval);
951
952 if (o == TOK_OR) {
953 /*
954 * E -> F || E
955 *
956 * A similar thing occurs for ||, except that here we make sure
957 * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
958 * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
959 * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
960 */
961 if (l == TOK_FALSE) {
962 l = CondParser_Expr(par, doEval);
963 } else {
964 (void)CondParser_Expr(par, FALSE);
965 }
966 } else {
967 /*
968 * E -> F
969 */
970 CondParser_PushBack(par, o);
971 }
972 }
973 return l;
974 }
975
976 static CondEvalResult
977 CondParser_Eval(CondParser *par, Boolean *value)
978 {
979 Token res;
980
981 DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
982
983 res = CondParser_Expr(par, TRUE);
984 if (res != TOK_FALSE && res != TOK_TRUE)
985 return COND_INVALID;
986
987 if (CondParser_Token(par, TRUE /* XXX: Why TRUE? */) != TOK_EOF)
988 return COND_INVALID;
989
990 *value = res == TOK_TRUE;
991 return COND_PARSE;
992 }
993
994 /* Evaluate the condition, including any side effects from the variable
995 * expressions in the condition. The condition consists of &&, ||, !,
996 * function(arg), comparisons and parenthetical groupings thereof.
997 *
998 * Results:
999 * COND_PARSE if the condition was valid grammatically
1000 * COND_INVALID if not a valid conditional.
1001 *
1002 * (*value) is set to the boolean value of the condition
1003 */
1004 static CondEvalResult
1005 CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
1006 Boolean eprint, Boolean strictLHS)
1007 {
1008 static const struct If *dflt_info;
1009 CondParser par;
1010 CondEvalResult rval;
1011
1012 lhsStrict = strictLHS;
1013
1014 cpp_skip_hspace(&cond);
1015
1016 if (info == NULL && (info = dflt_info) == NULL) {
1017 /* Scan for the entry for .if - it can't be first */
1018 for (info = ifs;; info++)
1019 if (info->form[0] == '\0')
1020 break;
1021 dflt_info = info;
1022 }
1023 assert(info != NULL);
1024
1025 par.if_info = info;
1026 par.p = cond;
1027 par.curr = TOK_NONE;
1028 par.printedError = FALSE;
1029
1030 rval = CondParser_Eval(&par, value);
1031
1032 if (rval == COND_INVALID && eprint && !par.printedError)
1033 Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
1034
1035 return rval;
1036 }
1037
1038 CondEvalResult
1039 Cond_EvalCondition(const char *cond, Boolean *out_value)
1040 {
1041 return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
1042 }
1043
1044 /* Evaluate the conditional in the passed line. The line looks like this:
1045 * .<cond-type> <expr>
1046 * In this line, <cond-type> is any of if, ifmake, ifnmake, ifdef, ifndef,
1047 * elif, elifmake, elifnmake, elifdef, elifndef.
1048 * In this line, <expr> consists of &&, ||, !, function(arg), comparisons
1049 * and parenthetical groupings thereof.
1050 *
1051 * Note that the states IF_ACTIVE and ELSE_ACTIVE are only different in order
1052 * to detect spurious .else lines (as are SKIP_TO_ELSE and SKIP_TO_ENDIF),
1053 * otherwise .else could be treated as '.elif 1'.
1054 *
1055 * Results:
1056 * COND_PARSE to continue parsing the lines after the conditional
1057 * (when .if or .else returns TRUE)
1058 * COND_SKIP to skip the lines after the conditional
1059 * (when .if or .elif returns FALSE, or when a previous
1060 * branch has already been taken)
1061 * COND_INVALID if the conditional was not valid, either because of
1062 * a syntax error or because some variable was undefined
1063 * or because the condition could not be evaluated
1064 */
1065 CondEvalResult
1066 Cond_EvalLine(const char *line)
1067 {
1068 enum { MAXIF = 128 }; /* maximum depth of .if'ing */
1069 enum { MAXIF_BUMP = 32 }; /* how much to grow by */
1070 enum if_states {
1071 IF_ACTIVE, /* .if or .elif part active */
1072 ELSE_ACTIVE, /* .else part active */
1073 SEARCH_FOR_ELIF, /* searching for .elif/else to execute */
1074 SKIP_TO_ELSE, /* has been true, but not seen '.else' */
1075 SKIP_TO_ENDIF /* nothing else to execute */
1076 };
1077 static enum if_states *cond_state = NULL;
1078 static unsigned int max_if_depth = MAXIF;
1079
1080 const struct If *ifp;
1081 Boolean isElif;
1082 Boolean value;
1083 enum if_states state;
1084
1085 if (cond_state == NULL) {
1086 cond_state = bmake_malloc(max_if_depth * sizeof *cond_state);
1087 cond_state[0] = IF_ACTIVE;
1088 }
1089 line++; /* skip the leading '.' */
1090 cpp_skip_hspace(&line);
1091
1092 /* Find what type of if we're dealing with. */
1093 if (line[0] == 'e') {
1094 if (line[1] != 'l') {
1095 if (!is_token(line + 1, "ndif", 4))
1096 return COND_INVALID;
1097 /* End of conditional section */
1098 if (cond_depth == cond_min_depth) {
1099 Parse_Error(PARSE_FATAL, "if-less endif");
1100 return COND_PARSE;
1101 }
1102 /* Return state for previous conditional */
1103 cond_depth--;
1104 return cond_state[cond_depth] <= ELSE_ACTIVE
1105 ? COND_PARSE : COND_SKIP;
1106 }
1107
1108 /* Quite likely this is 'else' or 'elif' */
1109 line += 2;
1110 if (is_token(line, "se", 2)) {
1111 /* It is else... */
1112 if (cond_depth == cond_min_depth) {
1113 Parse_Error(PARSE_FATAL, "if-less else");
1114 return COND_PARSE;
1115 }
1116
1117 state = cond_state[cond_depth];
1118 switch (state) {
1119 case SEARCH_FOR_ELIF:
1120 state = ELSE_ACTIVE;
1121 break;
1122 case ELSE_ACTIVE:
1123 case SKIP_TO_ENDIF:
1124 Parse_Error(PARSE_WARNING, "extra else");
1125 /* FALLTHROUGH */
1126 default:
1127 case IF_ACTIVE:
1128 case SKIP_TO_ELSE:
1129 state = SKIP_TO_ENDIF;
1130 break;
1131 }
1132 cond_state[cond_depth] = state;
1133 return state <= ELSE_ACTIVE ? COND_PARSE : COND_SKIP;
1134 }
1135 /* Assume for now it is an elif */
1136 isElif = TRUE;
1137 } else
1138 isElif = FALSE;
1139
1140 if (line[0] != 'i' || line[1] != 'f')
1141 return COND_INVALID; /* Not an ifxxx or elifxxx line */
1142
1143 /*
1144 * Figure out what sort of conditional it is -- what its default
1145 * function is, etc. -- by looking in the table of valid "ifs"
1146 */
1147 line += 2;
1148 for (ifp = ifs;; ifp++) {
1149 if (ifp->form == NULL)
1150 return COND_INVALID;
1151 if (is_token(ifp->form, line, ifp->formlen)) {
1152 line += ifp->formlen;
1153 break;
1154 }
1155 }
1156
1157 /* Now we know what sort of 'if' it is... */
1158
1159 if (isElif) {
1160 if (cond_depth == cond_min_depth) {
1161 Parse_Error(PARSE_FATAL, "if-less elif");
1162 return COND_PARSE;
1163 }
1164 state = cond_state[cond_depth];
1165 if (state == SKIP_TO_ENDIF || state == ELSE_ACTIVE) {
1166 Parse_Error(PARSE_WARNING, "extra elif");
1167 cond_state[cond_depth] = SKIP_TO_ENDIF;
1168 return COND_SKIP;
1169 }
1170 if (state != SEARCH_FOR_ELIF) {
1171 /* Either just finished the 'true' block, or already SKIP_TO_ELSE */
1172 cond_state[cond_depth] = SKIP_TO_ELSE;
1173 return COND_SKIP;
1174 }
1175 } else {
1176 /* Normal .if */
1177 if (cond_depth + 1 >= max_if_depth) {
1178 /*
1179 * This is rare, but not impossible.
1180 * In meta mode, dirdeps.mk (only runs at level 0)
1181 * can need more than the default.
1182 */
1183 max_if_depth += MAXIF_BUMP;
1184 cond_state = bmake_realloc(cond_state,
1185 max_if_depth * sizeof *cond_state);
1186 }
1187 state = cond_state[cond_depth];
1188 cond_depth++;
1189 if (state > ELSE_ACTIVE) {
1190 /* If we aren't parsing the data, treat as always false */
1191 cond_state[cond_depth] = SKIP_TO_ELSE;
1192 return COND_SKIP;
1193 }
1194 }
1195
1196 /* And evaluate the conditional expression */
1197 if (CondEvalExpression(ifp, line, &value, TRUE, TRUE) == COND_INVALID) {
1198 /* Syntax error in conditional, error message already output. */
1199 /* Skip everything to matching .endif */
1200 cond_state[cond_depth] = SKIP_TO_ELSE;
1201 return COND_SKIP;
1202 }
1203
1204 if (!value) {
1205 cond_state[cond_depth] = SEARCH_FOR_ELIF;
1206 return COND_SKIP;
1207 }
1208 cond_state[cond_depth] = IF_ACTIVE;
1209 return COND_PARSE;
1210 }
1211
1212 void
1213 Cond_restore_depth(unsigned int saved_depth)
1214 {
1215 unsigned int open_conds = cond_depth - cond_min_depth;
1216
1217 if (open_conds != 0 || saved_depth > cond_depth) {
1218 Parse_Error(PARSE_FATAL, "%u open conditional%s", open_conds,
1219 open_conds == 1 ? "" : "s");
1220 cond_depth = cond_min_depth;
1221 }
1222
1223 cond_min_depth = saved_depth;
1224 }
1225
1226 unsigned int
1227 Cond_save_depth(void)
1228 {
1229 unsigned int depth = cond_min_depth;
1230
1231 cond_min_depth = cond_depth;
1232 return depth;
1233 }
1234